Skip to navigation

Claude Code Hallucinated Packages: A Supply Chain Risk You Can Block

In short: An agent can invent a package name and install a malicious lookalike. Check registry existence, provenance and install scripts before running package managers.

Published 19 min read
On this page

Direct answer

Verify every agent-proposed dependency before a package manager runs. Check the exact registry name, publisher, version, release history, provenance and install scripts. Then enforce that review with a fail-closed pre-install control instead of relying on the model to remember the rule.

Independent. Research describes coding agents declaring packages that do not exist, allowing an attacker to register the name and publish malicious code. This is a general agent risk, not proof that Claude Code installed a specific malicious package. Official. Claude Code supports PreToolUse hooks and permission decisions, including deny rules and fail-closed behavior on supported versions. The practical win is a blocked install before execution. The honest loss is friction: a strict gate can stop legitimate new dependencies and still cannot make registry metadata trustworthy by itself.

How the package-name risk works

A coding agent may suggest a plausible library while implementing a feature. If the name is wrong, a normal package-manager command can resolve to something unintended. In the dangerous case, the imagined name does not exist yet. An attacker can register it, publish a package and wait for an agent or developer to install it.

The risk is not limited to a completely invented name. A misspelled real package, an abandoned namespace or a lookalike maintained by an unexpected publisher can create a similar problem. Typosquatting is the practice of choosing a name that resembles a legitimate package. The goal is to exploit a quick approval or an automatic install.

Independent. The supplied research on hallucinated dependencies describes this attack path and discusses the yul tool, which blocks hallucinated dependencies at manifest write time. The research establishes a general coding-agent risk. It does not establish that Claude Code installed a particular malicious package, and it does not provide a Claude Code failure rate.

Community. Claude Code issue #39421 asks for a built-in npm supply-chain defense hook and describes risks from hallucinated names, vulnerable versions and install scripts. It closed as NOT_PLANNED without an official implementation. Treat the issue as a feature request and risk description, not a confirmed universal defect.

Stage What can happen Control point Evidence boundary
Proposal Agent writes a plausible dependency name Manifest review General agent behavior, not a Claude-specific incident
Resolution Package manager queries a registry Exact-name registry check Registry metadata can still be wrong or compromised
Acquisition Archive and integrity data are fetched Lockfile and provenance review A matching hash does not prove benign code
Execution Lifecycle or install script runs Pre-install hook and isolation Scripts can have broad host access
Runtime Imported package performs work Tests, sandbox and monitoring Static checks cannot prove runtime safety

The Claude Code repository-hook security review explains why the enforcement layer deserves its own trust review. A hook that blocks installs is code running on the host. Limit it to a small, reviewed implementation owned by the team rather than copied from an untrusted repository.

Supply-chain evidence map from agent prompt to hallucinated name, lookalike package and install script
Editorial attack-path map based on independent dependency-hallucination research. It does not claim that Claude Code installed a specific malicious package.

Typosquatting is only one version of the problem

A name that differs by one character is easy to spot when a person compares it with a trusted reference. It is harder to spot when the agent generates the name, edits the manifest and proceeds to install in one flow. The reviewer sees a completed diff, not the moment a plausible name became a real registry entry.

Scope confusion deserves the same attention. A scoped package belongs to a specific namespace. Changing the scope changes the package identity even when the visible name looks familiar. Treat the full registry identifier as the thing to verify. Do not approve a dependency from its short display name alone.

Publisher history matters too. A newly registered package can be legitimate, but a new publisher attached to a familiar name deserves review. Download counts and stars are weak signals. They can rise after a package becomes popular or after an attack begins. They do not replace provenance, release history and a known source for the dependency.

Name risk Example shape Why it survives a quick review Required check
Invented name Plausible library that is not registered Sounds consistent with the task Confirm registry existence and intended source
Typosquat One changed or omitted character Looks correct at a glance Compare exact normalized name
Scope swap Familiar name under another namespace Short name appears unchanged Verify the full scoped identifier
Publisher takeover Known name with unexpected maintainer Package history looks established Review current publisher and release provenance
Version confusion Legitimate package, unexpected release Name matches the intended library Pin and review the exact version

The Claude Code generated-test oracle bias is relevant after installation. A test generated from the implementation can inherit its assumptions, including the assumption that a dependency behaves as intended. Define the expected behavior independently, then test the package integration against that oracle.

A package can also be real, popular and still wrong for the task. Supply-chain review is not only a malicious-name check. It includes whether the version is compatible, whether the license fits the project and whether the dependency adds behavior the team did not request. Those questions belong in the same approval record.

Check the registry without running the package

Start with a read-only registry query. Confirm the exact name, available versions, publisher information, repository link and release metadata. Do this before install, add or an update command can execute lifecycle scripts. The query itself should not install or execute the candidate package.

Next, compare the result with a trusted source. Candidates include official project documentation, an existing lockfile, an internal approved-dependency list or a maintainer’s verified repository. A search result is a lead, not approval. If the agent is the only source for the name, mark the dependency unverified until a person or trusted reference confirms it.

Review the version deliberately. A broad range can resolve to a release that was not reviewed. A lockfile preserves the resolved graph, but it does not prove that every package is safe. When a dependency changes, inspect the lockfile diff and record why the new version was selected.

Registry check Question Pass signal Escalate when
Exact identity Is the full name and scope correct? Matches a trusted reference Only the agent confirms the name
Publisher Who controls this release? Expected maintainer or verified provenance Publisher changed without explanation
Version Is this the intended release? Explicit version with a reviewed diff Range resolves to an unfamiliar release
Repository Does metadata point to the expected project? Consistent official source Repository is missing or unrelated
Integrity Does downloaded content match recorded integrity data? Lockfile and registry data agree Hash or signature is missing or inconsistent
Scripts What runs during installation? Scripts are absent or reviewed New lifecycle behavior is unexplained

Provenance can strengthen the record, but it is not a guarantee. An attested build can show who performed a build under particular conditions. It does not prove that the source code is benign or that the publisher is trustworthy. Attach the attestation to the version review rather than treating it as a permanent approval for all future releases.

The Claude Code MCP output truncation guide matters when registry output is long. Preserve the decisive fields: exact name, version, publisher, repository and script metadata. A truncated result that keeps only the first matching package can hide the scope or publisher difference that mattered.

Pre-install workflow from exact-name check through publisher, version, provenance and script review
Editorial review workflow. Registry checks reduce uncertainty but do not certify a package as safe or establish a Claude Code-specific incident rate.

Install scripts deserve a separate decision

A package archive can contain code that runs during installation. This code may perform setup, download additional content or modify the local environment. The exact behavior depends on the package and package manager. Treat it as executable code, not inert metadata.

A common mitigation is to disable install scripts while evaluating a candidate. This can reduce one execution path, but it does not make the package safe for later use. Some packages need their scripts to function. Others may behave differently when scripts are skipped. Record the mode used and do not present a script-disabled test as proof that normal installation is harmless.

Isolation adds a second boundary. Run the first install in a disposable environment without production credentials, broad home-directory access or unnecessary network services. Observe filesystem, process and network effects. The goal is to learn what the package does before it becomes part of a trusted development or build environment.

Official. Claude Code’s security documentation describes the security model, and the permissions documentation explains rule evaluation and limits. Permission rules evaluate deny, then ask, then allow. Bash rules do not stop commands invoked through full paths or wrappers such as sh -c. A package-install policy therefore needs to account for alternate command forms rather than matching one literal string.

Install mode What it helps with What remains Required follow-up
Metadata only Confirms identity and release data No proof about runtime behavior Review source and scripts separately
Scripts disabled Reduces lifecycle execution during evaluation Later normal install may execute scripts Test normal mode in isolation
Disposable environment Limits host and credential exposure Package may still phone home or fail subtly Inspect effects and retain logs
Locked install Reproduces a reviewed graph Does not prove the graph is benign Review graph changes and integrity
Production install Uses the approved version Carries the approved risk into delivery Monitor and keep rollback ready

The Claude Code GitHub Actions secret boundaries show why CI credentials need a separate boundary. A dependency install that runs with a broad workflow token can turn a package problem into a repository or secret problem. Isolate untrusted installation from privileged jobs and default tokens.

Build a fail-closed pre-install hook

The useful control runs before the package manager, not after the manifest is already changed. A PreToolUse hook can inspect the proposed command and return a deny decision when the dependency has not passed review. The hook should fail closed when its checks cannot complete.

Official. Claude Code supports command, HTTP, MCP tool, prompt and agent hooks. Execution points include PreToolUse, PostToolUse, permission events and subagent events. For command, HTTP or MCP tool hooks, onFailure: block can make failures or timeouts block the action. It requires v2.1.295 or later for command and HTTP hooks, and v2.1.328 or later for MCP hooks. PreToolUse can also return permissionDecision: deny, and exit code 2 blocks relevant actions.

Those version requirements belong in the rollout checklist. A team that configures onFailure: block on an older client should not assume the setting provides the documented protection. Verify the installed version and test the failure path with a harmless fixture.

A practical hook pattern has six steps:

1. Read the proposed tool command and working directory.
2. Detect package-manager install or update operations, including wrappers.
3. Compare the proposed manifest and lockfile change with the approved list.
4. Query registry metadata without executing the candidate package.
5. Deny unknown names, unreviewed versions or failed checks.
6. Record the decision and the evidence reference.

This is a policy pattern, not a drop-in configuration. The exact parser, approved-list format and registry client depend on the project. Make the hook deterministic and small enough to review. Do not ask a model to decide whether a package is safe inside the same hook that grants installation permission.

Official. Without fail-closed behavior, most hook failures are non-blocking. This is convenient for optional automation and dangerous for a security gate. The hook’s error path is part of the control. A timeout, parser failure or registry outage should stop the install when the policy requires prior verification.

Hook case Expected decision Reason Test evidence
Approved exact version Allow Matches reviewed record Decision log and version match
New package name Deny No trusted reference yet Deny response before install
Changed publisher Deny Provenance needs review Metadata diff
Registry check fails Block Verification is unavailable Timeout or error path
Wrapped command Inspect or deny Literal matching can be bypassed Wrapper test case
Manifest-only edit Review Later install still needs a gate Diff and approval record

The Claude Code auto-mode classifier limitations are a useful reminder not to replace a deterministic gate with a vague safety judgment. Auto mode uses a classifier for potentially destructive actions, and the official page gives no numerical approval rate. Dependency approval needs an explicit policy and a recorded result.

Supply-chain control tradeoffs comparing registry checks, script disabling, isolation and deterministic hooks
Editorial tradeoff map based on independent risk research and official hook controls. Each control reduces a different failure path and leaves residual risk.

Test the gate without installing anything untrusted

A safe test uses synthetic command strings and a disposable fixture. Do not point the test at a real unverified package. Do not run a candidate’s install script just to see whether the hook notices it. The test should prove the decision path, not execute the risky action.

Start with an approved fixture that already exists in the test project. Run the proposed command through the hook in a mode that records the decision without performing the install. Confirm that the exact approved version is allowed and that a changed version is denied. Then add an unknown fixture name and confirm that the hook blocks before any package-manager process starts.

Test wrappers and full paths next. A rule that recognizes one command spelling can miss another. The official permissions documentation explicitly warns that Bash rules do not stop commands invoked through full paths or wrappers such as sh -c. The hook tests should include those forms, or the enforcement layer should reject command shapes it cannot parse.

Finally, break the checker on purpose. Point it at an unavailable registry fixture or make its parser fail. The expected result is a blocked install when fail-closed policy is active. A gate that allows installation because its own check crashed is not a gate.

Test Fixture Expected result What it proves
Approved version Existing local fixture Allow decision Exact match path works
Version change Same fixture, different version Deny decision Review is version-specific
Unknown name Reserved synthetic name Deny decision New dependencies stop
Wrapper Harmless wrapper around fixture command Inspect or deny Literal matching is not the only path
Registry outage Local failing endpoint Block decision Failure path is closed
Timeout Delayed local endpoint Block decision A stalled check cannot admit install

The Claude Code destructive git guardrails use the same design principle: make the safe operation the default and test the denial path. Dependency review is safer when the hook cannot silently skip its own checks.

Limit test output to a compact result. The Claude Code task budgets versus hard stops article explains that an advisory token budget is not an enforcement cap. A hook test should have its own timeout and explicit expected decision. Do not rely on the agent to stop after a reasonable number of attempts.

Pre-install hook checklist covering approved versions, unknown names, publisher changes, wrappers and fail-closed errors
Editorial control checklist derived from official hook and permission behavior. The tests verify decisions without executing an untrusted package.

Roll out the gate without hiding its cost

Start in report-only mode long enough to learn which package-manager commands the repository actually uses. Record proposed installs, versions and wrapper forms without blocking them. Review the log for false positives and missed command shapes. Then switch to deny mode with an owner and a documented exception process.

Report-only mode is not protection. It is a measurement phase. Do not leave a security gate in that mode after rollout and describe it as fail closed. The switch should be explicit, tested and visible in the workflow configuration.

Exceptions need an expiry and a reason. A temporary allowance for a package with incomplete metadata should identify the version, reviewer and review date. Broad exceptions for an entire package family make the gate easier to bypass and harder to audit.

Measure the operational cost as well as the blocked installs. The Claude Code cost per verified change framework can track reviewer time and rework. The context-portable migration guide helps preserve the approval record when a repository changes agents or CI systems.

Place hook configuration outside untrusted repository changes where possible. The Claude Code settings-file secret exposure guide explains why saved rules deserve review. The Claude Code harness security boundaries show why the hook, permissions and host isolation must be reviewed together. A dependency gate that an attacker can edit is not a trust boundary.

Fit the control into the repository workflow

A hook works best when the repository already has a dependency approval record. This record should name the package, exact version, trusted source, reviewer and date. When the agent proposes a change, it can attach the proposed diff and evidence. A person approves the new entry before the install gate allows it.

Large repositories need a clear owner for that record. The Claude Code monorepo search and token budget guide explains how scoped retrieval can reduce repeated discovery. For dependency policy, scope matters because one package may be approved for a build tool but not for production runtime. Record the allowed scope with the version.

Legacy projects need a slower path. The Claude Code legacy-code characterization workflow recommends capturing behavior before changing structure. An old dependency may be poorly documented but essential to a hidden business rule. Blocking an upgrade is sometimes correct until that behavior is characterized.

Workflow stage Owner Required artifact Gate
Proposal Agent or developer Name, version and reason No install yet
Evidence Developer Registry and provenance record Trusted source confirmed
Review Dependency owner Approval or rejection Exact scope recorded
Install Hook Decision log Fail closed on unknown or error
Verification Test owner Independent behavior checks Runtime assumptions tested
Update Reviewer Lockfile and release diff Reapproval when material facts change

The Claude Code proof-of-work packet is a good model for the final record. Group the manifest diff, lockfile diff, approval, hook decision and test output together. A passing build without that chain shows only that the package worked in one run.

The honest loss and the data gap

The win is a decision before execution. A deterministic pre-install gate can stop an invented name, an unreviewed version or a failed registry check. It also creates a record that another person can audit.

The loss is operational friction. Legitimate dependencies will sometimes arrive without complete metadata. Registry services will time out. A strict policy can slow a task or push work toward wrappers that bypass weak rules. Reviewers may also approve a package that later turns out to be compromised. No pre-install checklist eliminates that risk.

Unknown. The frozen evidence does not provide a Claude Code package-hallucination rate, a registry compromise rate for a specific project or a guarantee that a hook blocks every command form. Issue #39421 is a request, not an implemented defense. Future updates should revisit official hook documentation, permission behavior and any built-in supply-chain controls.

The Claude Code sandbox boundary for CVE-2026-55607 is a separate malicious-repository case. Its official CVE record required cloning a malicious repository and running Claude Code against it. Do not combine that incident with package hallucination or imply that one proves the other.

Supply-chain verdict separating blocked installs, approved versions and residual registry or runtime risk
Editorial verdict map based on independent risk research and official controls. A blocked install is a concrete win; registry and runtime risk remain.

Keep a dependency decision record

The approval record should survive the task. Save the exact package identifier, version, registry, publisher evidence, script review, reviewer and date. Link the lockfile diff and the test result. When the same dependency appears in another project, reuse the evidence but confirm that the scope and version still match.

Do not store credentials in the record. The API reference describes key controls such as caps, expiry and model allowlists, but dependency approval does not need a live key. If a registry requires private authentication, reference the secret by name and keep the value in the trusted secret store.

A quarterly or release-based review can catch stale approvals. Recheck dependencies with changed publishers, unexpected releases or new install scripts. The review should also remove exceptions that no longer have an owner. An expired exception is an open gate, not a harmless note.

Unexpected package activity may also create a billing question. Use the Claude Code billing-dispute evidence packet to reconcile transactions without assuming that a security incident makes a charge invalid. If a refund request follows, the Claude Code refund and support policy guide explains the applicable branch. A malicious extension is a different incident again; follow the Claude Code extension-trojan remediation steps rather than treating it as a dependency approval problem.

Practical alternative: test an OpenAI-format agent

If you want to compare dependency-heavy workflows in another agent, One AI API Key lists 46 live free model IDs for OpenAI-format agents such as OpenCode, Cline or Cursor. The quickstart shows the base URL and first request. The free lane shares 100 requests and 5,000,000 tokens per day per account, resets at 05:30 IST / 00:00 UTC, and permits one request in flight per key.

The documented Claude Code route uses the Anthropic-format endpoint, but all four Claude IDs were marked unavailable on 2026-11-27. Free IDs are OpenAI-format only, so they are not a Claude Code option. Use the prepaid pricing page for paid credit details and the cost calculator to estimate a trial. Model choice does not replace dependency review.

FAQ

Can Claude Code invent an npm package name?

Coding agents can generate non-existent dependency names, according to independent research. The supplied evidence does not prove that Claude Code installed a specific malicious package. Treat every new agent-proposed name as unverified until it matches a trusted source.

Does a registry search prove a package is safe?

No. It can confirm identity, versions and publisher metadata. It does not prove that the code is benign, that the publisher is trustworthy or that install scripts are harmless. Review provenance, scripts and exact versions, then test in isolation.

What is the strongest pre-install control?

A reviewed, deterministic PreToolUse gate that denies unknown dependencies and fails closed when checks fail. Official. onFailure: block has version requirements, and Bash permission rules have wrapper and full-path limits. Test the denial and failure paths.

Should I disable install scripts?

Disabling scripts can reduce execution during evaluation, but it does not make a package safe for normal use. Some packages need scripts to function, and a script-disabled test does not prove that a later normal install is harmless. Record the mode and isolate the first real install.

Is issue #39421 a confirmed Claude Code vulnerability?

No. It is a community feature request describing supply-chain concerns. The request closed as NOT_PLANNED without an official implementation. Use it as context, not as proof of a universal defect or an installed malicious package.

More Claude Code troubleshooting

Sources

More in Blog

Try it

One API key for GPT, Grok, DeepSeek, Kimi, GLM, MiniMax, Qwen, Step, Beam, Nemotron, ERNIE, Hunyuan, Gemma, Laguna, LFM, LongCat, Llama, Solar, Jais, Mistral, K2 and Roleplay.

One AI API Key speaks the OpenAI and Anthropic formats, so you change the base URL and the key, not your code. Credit packs start at $10, and every model has a published per-token rate.

New accounts$10 credit on sign-up
  • 100requests
    per day
  • 3Mtokens
    per day
  • 47free
    models
  • $0per
    token
  • No card
  • No end date
Claim $10 credit →