# safeinstall [Health: Active]

**Category:** 🔒 Security  
**Repository:** https://github.com/Mickdownunder/SafeInstall  
**GitHub Stars:** 3  
**Views:** 1  
**Installs:** 0  
**Upvotes:** 0  
**Directory Page:** https://allmcps.com/mcp/safeinstall

## Description
Local-first supply-chain security gate for npm/pnpm/bun: typosquat, release age, provenance checks

## Claude Desktop Quick Installation
Install path detected from listing signals. Uses `npx` (confidence: high):

```json
"mcpServers": {
  "safeinstall": {
    "command": "npx",
    "args": ["-y","create-next-app"]
  }
}
```

## Documentation & README

<p align="center">
  <strong>SafeInstall</strong>
  <br />
  <em>Supply-chain security for the AI-agent era.</em>
</p>

<p align="center">
  <a href="https://www.npmjs.com/package/safeinstall-cli"><img src="https://img.shields.io/npm/v/safeinstall-cli?style=flat-square&color=22c55e" alt="npm version" /></a>
  <a href="https://github.com/Mickdownunder/SafeInstall/blob/HEAD/LICENSE"><img src="https://img.shields.io/badge/license-MIT-22c55e?style=flat-square" alt="license" /></a>
  <a href="https://github.com/Mickdownunder/SafeInstall"><img src="https://img.shields.io/github/stars/Mickdownunder/SafeInstall?style=flat-square" alt="stars" /></a>
  <a href="https://github.com/Mickdownunder/SafeInstall"><img src="https://img.shields.io/badge/TypeScript-strict-blue?style=flat-square" alt="TypeScript" /></a>
  <a href="https://safeinstall.dev"><img src="https://img.shields.io/badge/docs-safeinstall.dev-22c55e?style=flat-square" alt="docs" /></a>
  <a href="https://github.com/Mickdownunder/SafeInstall/actions/workflows/safeinstall-trust.yml"><img src="https://img.shields.io/github/actions/workflow/status/Mickdownunder/SafeInstall/safeinstall-trust.yml?branch=main&style=flat-square&label=trust%20surface&color=22c55e" alt="trust surface" /></a>
</p>

<p align="center">
  The artifact-bound install gate for <strong>npm</strong> and <strong>pnpm</strong> — for the humans who type <code>install</code>, the AI agents that run it for them, and the config that programs those agents.<br />
  Policy runs first. Then your package manager. Not the other way around.<br /><br />
  Local-first · No cloud · No account · MIT · Free forever
</p>

---

## What it does

SafeInstall runs your **policy before your package manager** — locally, blocking by default. One tool, three layers of defense:

- 🧑‍💻 **For the humans who install** — prefix supported install commands: `safeinstall pnpm add axios`. Policy runs first; the resolved lockfile is then checked against the approved version and SHA-512 before the frozen install. Release age, install scripts, untrusted sources, typo-squats, and cryptographic provenance are [policy checks](#policy-defaults).
- 🤖 **For the AI agents that install for you** — an [MCP tool](#mcp-server--ai-agents) agents can call, plus a [shell guard](#shell-guard--enforcement-not-advice) that intercepts install commands in Claude Code, Codex, and Cursor *before they run*. Best-effort shell interception — one defense layer that fires even when the agent isn't cooperating, not a lossless guarantee.
- 🔒 **For the files that program the agents** — the [Agent Trust Surface](#agent-trust-surface--self-defending-policy): a committed hash baseline of your config, hooks, rules, and MCP files, reconciled locally and re-verified in CI, so tampering with the rules surfaces as drift instead of silently owning every future session — with a fully consistent rewrite caught by human review of the diff, not the automated check alone.

---

## Why SafeInstall

AI coding tools suggest packages in seconds. They don't check publish dates. They don't read install scripts. They don't verify the source. You type "yes" and move on.

SafeInstall is the gate between suggestion and execution.

```
$ safeinstall pnpm add compromised-pkg@9.9.9

Install blocked.
- compromised-pkg@9.9.9
  Blocked: release too new (published 3 hours ago; minimum is 72 hours).
  Blocked: install script present (has postinstall).
```

No dashboard. No account. No cloud. One command prefix — policy runs locally, blocks by default, then invokes the real tool.

---

## Catching a maintainer-compromise attack

A valid Sigstore signature is not enough. An attacker who compromises an npm maintainer account can publish a malicious version of a package you already trust, and the attestation on that malicious version will cryptographically verify — signed by a GitHub Actions workflow the attacker controls in a fork of the real repository.

SafeInstall catches this. Pin the expected source repository with `provenance.trustedPublishers` and any build that comes from anywhere else is blocked, even if the signature is valid:

```
$ safeinstall check
Using config: ./safeinstall.config.json
Check blocked.
- axios@1.99.0
  Blocked: publisher mismatch for axios (expected axios/axios, got evil-org/axios).
  Suggestion: Verify the package source. Update provenance.trustedPublishers only if the change is intentional.
```

This is the only check of its kind in an install-time policy gate. CVE scanners look for known vulnerabilities. Content analyzers look for suspicious code. SafeInstall enforces that the cryptographic chain of trust points at the repository you agreed to trust — and refuses anything else, no matter how legitimate it looks.

SafeInstall itself is published with a Sigstore attestation. You can eat your own dog food: enable provenance verification, pin `safeinstall-cli` to `Mickdownunder/SafeInstall`, and watch SafeInstall verify its own trust chain against the public Sigstore transparency log.

```
$ safeinstall check
Using config: ./safeinstall.config.json
Info: safeinstall-cli: provenance verified from Mickdownunder/SafeInstall via .github/workflows/release.yml.
Check passed: no direct dependency policy violations found.
```

---

## Install

```bash
npm install -g safeinstall-cli
```

> Node.js >=20 · macOS, Linux, Windows · Command: `safeinstall`

## Quickstart

```bash
safeinstall init                      # config + shell guard hooks + trust lock, in one command
safeinstall pnpm add axios            # policy runs, then pnpm
safeinstall npm install               # lockfile-aware project install
safeinstall check                     # audit direct deps against policy
```

---

## How it works

```
Resolve → Policy → Lockfile-only preparation → Verify artifact binding → Frozen install
                      Any failed policy or binding check → Exit 2 (blocked)
```

1. Resolves the requested version and captures the registry's tarball URL and SHA-512
2. Fetches registry metadata (publish time, declared scripts)
3. Evaluates policy rules
4. For explicit package additions, pins the evaluated version and runs a scripts-disabled, lockfile-only preparation
5. Checks every direct registry dependency in the affected lockfile scope against its evaluated version, SHA-512, and tarball URL where recorded; applies configured transitive checks
6. Runs `npm ci` or `pnpm install --frozen-lockfile` with scripts disabled and the configured registry enforced; rejects manifest/lockfile changes during evaluation or installation

No registry proxy. No tarball rewriting. No cloud dependency.

---

## Policy defaults

| Rule | Default | Block message |
|:---|:---|:---|
| **Release age** | 72 hours minimum | `Blocked: release too new` |
| **Lifecycle scripts** | preinstall, install, postinstall blocked | `Blocked: install script present` |
| **Source types** | registry, workspace, file, directory allowed. First-party workspace packages (`workspace:`, or a path matched by the workspace globs) are always allowed; any other local directory counts as `directory` and a local tarball as `file` | `Blocked: untrusted source` |
| **Trust downgrade** | Flags a dependency that was `registry` in the committed manifest and is now git/url/tarball or any local source (`file:`, `link:`, directory, `workspace:`). A dependency that was already local at the baseline is not flagged. `decisions authorize` compares against the base commit's manifest (never the config); `check` and installs compare against the manifest at git `HEAD`. `sourceBaselines` applies only when there is no `HEAD` manifest (no git, unborn `HEAD`, untracked manifest), and then missing history fails closed | `Blocked: trust level dropped` |
| **Typo-squat detection** | Off by default; opt in via `typoSquat.mode` | `Blocked: suspected typo-squat` |
| **Provenance verification** | Off by default; opt in via `provenance.mode` | `Blocked: attestation missing/invalid/publisher mismatch` |
| **Lockfile sources** | Every entry of an npm or pnpm lockfile, direct or transitive, must come from a source in `allowedSources` | `Blocked: transitive dependency resolves from an untrusted source` |
| **Transitive install scripts** | Off by default; opt in via `transitive.mode` | `Blocked: transitive install script` |
| **Provenance continuity** | Off by default; opt in via `continuity.mode` | `Blocked: provenance downgrade / identity discontinuity` |

All rules are configurable. Ambiguous or incomplete metadata **blocks instead of allowing**.

### Provenance continuity — catching what npm defaults can't

This is SafeInstall's most distinctive check, and the one no other consumer-side tool does. npm verifies provenance at *publish* time and binds a package to a source repository — but it does not enforce **continuity** between versions. A compromised maintainer account can publish a new version with *no* attestation (from a stolen token), or from a *different* repository, and npm raises no alarm. This is the signature of the 2026 attack wave (Mastra, the dormant-account republishes).

Continuity learns a per-package trust baseline from the provenance identity of recent versions, then blocks deviations:

- **`provenance-downgrade`** — recent versions were attested, this one isn't. The fingerprint of an account-compromise publish from a personal token. *(This is the Mastra case.)*
- **`identity-discontinuity`** — this version is attested from a different source repository than the established baseline.

Because the baseline is learned **per package**, there are no false positives on the large majority of packages that never adopted provenance — they simply have no baseline and the check stays silent. No global "require provenance" sledgehammer.

Continuity verifies the attestation of the target version and of each baseline version locally with the optional `sigstore` package before using its repository identity (about one second per package, and it needs the Sigstore trust root, so it needs network access to it the first time). An attestation that fails verification counts as no provenance. If `sigstore` is not installed or the trust root cannot be fetched, continuity is reported as unevaluated with a warning and does not block. Opt in with `continuity.mode` set to `"warn"` or `"block"`.

> **Honest limit:** continuity does not catch an attack that comes *through* a legitimately-compromised CI workflow with valid provenance from the real repository (e.g. the Shai-Hulud worm class). There is no identity discontinuity to detect there. SafeInstall raises the bar against the dominant 2026 attack pattern; it does not close every door.

### Transitive dependencies

Most supply-chain attacks reach you through a *transitive* dependency — a package you never chose, pulled in several levels deep. Two checks read the full lockfile tree, with **zero extra registry calls**.

**Lockfile sources, always on.** Every entry of an npm or pnpm lockfile must resolve from a source in `allowedSources`. An entry whose download address points at another host or a git repository blocks `check`, project installs and `decisions authorize` with `transitive-untrusted-source`, whatever `transitive.mode` says: a single edited lockfile line is enough to change what gets installed, so this is not opt-in and never degrades to a warning. The public npm registry and the configured `registryUrl` count as `registry`. Workspace links are not flagged. If a transitive dependency legitimately comes from git or a URL, add that source type to `allowedSources`.

**Transitive checks, opt-in via `transitive.mode`:**

- **`install-script`** — flags transitive packages that declare a lifecycle script (the `ua-parser-js` attack class: a deeply nested dependency running code at install time). npm records this in the lockfile; pnpm lockfiles do not, so this check is npm-only for now.
- **`untrusted-source`** — accepted for compatibility. The source check above runs regardless of this entry and of the mode.

Release-age, typo-squat, and provenance are deliberately **not** run transitively — they would either flood you with noise or require a registry round-trip per package. Transitive evaluation applies to `safeinstall check`, project installs, and the prepared lockfile for explicit npm/pnpm additions.

With `transitive.mode` off, a project without a readable npm or pnpm lockfile is not an error: there are no lockfile sources to check. An enabled transitive policy never treats unavailable lockfile evidence as a clean result. `block` mode blocks when an npm/pnpm lockfile is missing, unreadable, unsupported, or invalid; `warn` mode emits an explicit warning instead. Bun lockfiles are not currently supported for transitive evaluation, so Bun checks follow the same fail-closed or warning behavior according to the configured mode.

```json
{
  "transitive": {
    "mode": "warn",
    "checks": ["install-script", "untrusted-source"]
  }
}
```

### Typo-squat detection

Flags install requests whose package name is a close-but-not-exact match to a well-known popular package — the most common supply-chain attack pattern: `lodsh` for `lodash`, `axois` for `axios`, `raect` for `react`, and so on.

- **Algorithm:** Damerau-Levenshtein distance (transpositions count as a single edit)
- **Target list:** curated set of popular ecosystem packages, embedded at build time (no runtime network fetch)
- **Default mode:** `"off"` — opt in with `typoSquat: { "mode": "warn" }` or `"block"`
- **False-positive mitigation:** exact matches to the list are never flagged, short names (< 4 chars) are skipped, per-project `ignore` list is supported

### Provenance verification

**Cryptographically verifies** the npm provenance attestation for registry installs and optionally **pins the source repository** via per-package trusted publisher patterns.

- Fetches the attestation bundle from the npm registry's `/-/npm/v1/attestations/<pkg>@<version>` endpoint
- Verifies the Sigstore bundle via the official `sigstore` package (signatures, Rekor transparency log, Sigstore public trust root)
- Extracts source repository, commit ref, and workflow path from the SLSA v1 provenance statement
- Matches the source repository slug against per-package `trustedPublishers` patterns — catching not only tampered tarballs but also **maintainer-compromise attacks** where an attacker republishes a legitimate-looking package from a fork they control
- **Publisher mismatches always block**, even in `"warn"` mode, because a valid signature from the wrong repo is exactly what maintainer compromise looks like

Default mode is `"off"`. Opt in by setting `provenance.mode` to `"warn"` or `"require"`.

---

## Usage

```bash
# Ad-hoc installs
safeinstall pnpm add axios
safeinstall npm install react@19.2.0

# Project installs (lockfile-aware for npm/pnpm)
safeinstall pnpm install
safeinstall npm ci

# Monorepo — select a package; shared-lockfile installs review all importers
safeinstall pnpm -C packages/app install
safeinstall npm --prefix packages/app ci

# Utilities
safeinstall check                     # direct dependency audit
safeinstall check --json              # machine-readable
safeinstall init                      # one-command onboarding: config, guard hooks for
                                      # detected agents (.claude/, .codex/, .cursor/), trust lock
safeinstall init --force              # overwrite an existing config (hooks/lock stay idempotent)
safeinstall init --client codex       # force specific agents instead of detection
safeinstall init --no-guard --no-lock # config only (the old behavior)
safeinstall mcp                       # MCP server for AI coding agents
safeinstall guard install             # register agent shell hooks (Claude Code, Codex, Cursor)
safeinstall trust lock                # baseline the Agent Trust Surface
safeinstall trust lock --ci github    # ...and scaffold the CI re-verification workflow
safeinstall trust status              # reconcile the trust surface (exit 2 on drift; read-only)
safeinstall trust approve             # review drift and re-baseline (interactive)
safeinstall trust unlock              # remove the baseline (lock, ledger, head mirror)
safeinstall --help
safeinstall --version

# JSON output (CI/automation)
safeinstall --json pnpm add axios

# Explicit config file (skips upward discovery)
safeinstall --config ./ci/safeinstall.config.json check
```

## Project installs

For `pnpm install` and `npm install` / `npm ci`, dependency versions come from the lockfile — not loose ranges in `package.json`.

- `pnpm-lock.yaml` for pnpm
- `package-lock.json` or `npm-shrinkwrap.json` for npm
- Stale, missing, or mismatched lockfile entries **fail closed**
- If `packageManager` is set in `package.json`, using a different CLI is blocked
- Workspace-targeting flags (`--filter`, `--workspace`) are blocked — use `-C` or `--prefix`
- `bun add` / `bun install` fail closed until artifact-bound Bun installation is implemented; `check` and MCP policy queries remain available

### Artifact-bound installation contract

Installation requires one canonical SHA-512 digest in the checked registry manifest and the matching lockfile entry. SHA-1-only or missing-integrity entries block. A different command-line registry, script-enabling flags, global installs, and unknown installation options block. Registry selection in environment variables or scoped `.npmrc` settings cannot authorize a different artifact: the resulting lockfile must still match the checked binding.

Explicit additions resolve into a lockfile with the evaluated exact version before installation. Preparation can update `package.json` and the lockfile, and can populate the manager's cache, even if the later binding/policy check blocks. Those files are left for inspection, not automatically rolled back. npm's frozen phase uses `ci`, which replaces `node_modules`. Shared workspace lockfiles cause all recorded importers' direct dependencies to be reviewed under the selected policy, not just the selected package.

Lifecycle scripts are always disabled, including when legacy `packageManagerDefaults.*.ignoreScripts` is `false`. `allowedScripts` permits a policy exception, not script execution. pnpm's executable `.pnpmfile.cjs` hooks are disabled too. Explicit non-registry additions currently block; existing local/workspace dependencies are governed by `allowedSources` (workspace packages are always allowed; other local directories are `directory`, local tarballs `file`, whether inside or outside the repository) and are not claimed to have registry-artifact binding. The previous source of a dependency comes from a committed manifest, not from the working-tree manifest being checked: the base commit's manifest in `decisions authorize` (for the root project and every importer; a moved importer is matched to the base package with the same `name`), and the manifest at git `HEAD` in project-level `check` and installs. Only when no `HEAD` manifest exists (not a git repository, unborn `HEAD`, or an untracked manifest) do git, URL, and tarball dependencies need a reviewed `sourceBaselines` entry; category-wide `allowedSources` alone cannot prove that a registry dependency was not replaced.

---

## MCP server / AI agents

The CLI reaches humans who type `safeinstall`. The **MCP server reaches AI coding agents** — Claude Code, Codex, Cursor, Windsurf, Cline — so the policy engine can be consulted *before* an agent suggests or runs an install, without anyone typing anything.

`safeinstall mcp` starts a [Model Context Protocol](https://modelcontextprotocol.io) server over stdio that exposes one tool, `check_package`, backed by the exact same engine as the CLI (release age, install scripts, untrusted sources, typo-squat, Sigstore provenance, and provenance continuity).

> [!IMPORTANT]
> MCP tools are **advisory**. Installing the server makes `check_package` *available*; it does not force an agent to call it. "Install once, protected forever" = **one MCP config block + one rule snippet** ([`mcp/agent-rule.md`](https://github.com/Mickdownunder/SafeInstall/blob/HEAD/mcp/agent-rule.md)) telling the agent to call the tool before every install.

### Wire it into your agent

Install the supported CLI and MCP SDK into a dedicated local directory with
exact versions and a retained lockfile:

```bash
npm install --save-exact --ignore-scripts safeinstall-cli@0.16.0 @modelcontextprotocol/sdk@1.32.2
```

Before enabling the server, compare the `safeinstall-cli` SHA-512 integrity in
`package-lock.json` with the release's signed npm provenance, review the lockfile,
and retain it. Recreate the installation with `npm ci --ignore-scripts`; do not
let an MCP client fetch executable code on startup.

**Claude Code / Claude Desktop** — add to your MCP config (`claude_desktop_config.json` or `.mcp.json`):

```json
{
  "mcpServers": {
    "safeinstall": {
      "command": "node",
      "args": [
        "/absolute/path/to/safeinstall-mcp/node_modules/safeinstall-cli/dist/cli.js",
        "mcp"
      ]
    }
  }
}
```

**Cursor** — add the same block to `.cursor/mcp.json`.

Then paste the rule from [`mcp/agent-rule.md`](https://github.com/Mickdownunder/SafeInstall/blob/HEAD/mcp/agent-rule.md) into your `CLAUDE.md` / Cursor Rules. Full setup details: [`mcp/README.md`](https://github.com/Mickdownunder/SafeInstall/blob/HEAD/mcp/README.md).

### What the agent sees

`check_package` accepts `name` (required), `version` (optional, defaults to latest), and `manager` (optional, informational) and returns a JSON verdict:

```json
{
  "verdict": "block",
  "name": "raect",
  "version": null,
  "reasons": [
    { "code": "typo-squat-suspected", "message": "Blocked: Suspected typo-squat: \"raect\" is 2 edit(s) away from popular package \"react\".", "suggestion": "Verify you meant to install \"react\"." }
  ],
  "warnings": [],
  "infos": [],
  "sourceRepository": null,
  "ageHours": null
}
```

`verdict` is `"block"` when any policy reason blocks the install, otherwise `"allow"`.

When **no `safeinstall.config.json` is found**, the MCP server uses a **recommended secure preset** — the built-in defaults with `typoSquat` and `continuity` promoted to `"block"`, because the agent use case wants maximum signal. When a config file **is** found, it is respected exactly (same resolution as the CLI).

The MCP SDK ships as an **optional dependency**, lazily loaded only when `safeinstall mcp` runs — CLI-only users never install it. If it is missing, the command prints an install hint and exits non-zero.

---

## Shell guard — enforcement, not advice

The MCP tool is advisory: an agent *can* consult it. The guard is a stronger layer: it hooks into the agent's shell layer and screens commands *before they run*, firing even when the agent doesn't know SafeInstall exists. This is best-effort shell interception — one layer of defense in depth, not a complete boundary; its command parsing is not exhaustive (see [Guard limitations](#guard-limitations)).

```bash
safeinstall guard install                  # Claude Code, Codex, and Cursor
safeinstall guard install --client codex   # or just one client
```

This writes project-level hook configuration (merged non-destructively, idempotent on re-runs):

- **Claude Code** — a `PreToolUse` hook on the `Bash` tool in `.claude/settings.json`; raw installs are rewritten in-place through the SafeInstall CLI via `updatedInput` with no `permissionDecision`, so Claude's normal permission prompt still fires and shows the user the rewritten command to approve
- **Codex** — a [`PreToolUse` hook](https://learn.chatgpt.com/docs/hooks#pretooluse) on `Bash` in `.codex/hooks.json`; raw installs are rewritten in-place through the SafeInstall CLI via Codex `updatedInput`. Open `/hooks` in Codex after installation and trust the new project hook before expecting it to run.
- **Cursor** — a `beforeShellExecution` hook in `.cursor/hooks.json`, registered with `failClosed: true` so a crashed or timed-out guard blocks instead of silently allowing

After registration, the CLI reports the Trust Surface step that matches the project state. A project without a baseline is directed to `safeinstall trust lock`. If a baseline already exists and the guard changed it, review the complete drift with `safeinstall trust status` and run `safeinstall trust approve` only when every change is intentional. Re-running an already-registered guard does not require re-approval unless status reports drift.

### How the guard decides

The guard never evaluates policy itself — it detects package installs and routes them through the CLI, which owns the decision:

| Agent runs | Guard response |
|:---|:---|
| `git status`, `npm test`, ... | Allowed — not an install |
| `npm install axios` (also `npm i`, `pnpm add`, `bun a`, `npm ci`, `corepack pnpm add`, `pnpm --dir app add`, ...) | Claude/Codex: **rewritten in-place** to `safeinstall npm install axios` before execution (the permission prompt shows the routed command). Cursor: **denied** with the SafeInstall replacement |
| `cd app && npm i axios && npm test` | Rewrite prefixes only the install segment; Claude/Codex apply it directly, Cursor returns it to the agent |
| `safeinstall npm install axios` | Allowed — already routed through the policy engine |
| `npm install $(cat list.txt)`, `bash -c "npm install ..."` | **Denied** — cannot be analyzed safely (fail-closed) |
| `yarn add axios` | **Denied** — SafeInstall cannot policy-check yarn |
| `npx tsc` with `typescript` installed locally | Allowed — npx resolves the local binary, nothing is downloaded |
| `npx create-next-app`, `pnpm dlx ...`, `bunx ...`, `yarn dlx ...` | Claude/Cursor: **ask**. Codex: **deny** because Codex `PreToolUse` does not currently support an `ask` decision |

Routing through the CLI matters more than a simple allow/deny: a vetted-but-raw `npm install` would still execute lifecycle scripts. Through SafeInstall, the same install gets the full policy evaluation *and* runs with install scripts disabled.

Claude and Codex apply the rewrite in-place through `updatedInput`, so the user's normal permission prompt shows the SafeInstall-routed command to approve rather than the raw install. Cursor receives the exact rewritten command in the block message so a well-behaved agent self-corrects in one step. The guard needs no network access and answers in milliseconds.

### Guard limitations

- The `safeinstall` binary must be on the agent's `PATH` (`npm install -g safeinstall-cli`).
- Codex requires users to review and trust new or changed project hooks with `/hooks`; until then Codex skips the hook. Codex currently intercepts only supported simple shell calls, not every `unified_exec` path, so the hook is still a defense-in-depth guardrail rather than a complete boundary.
- `npx` and friends are not policy-checked: SafeInstall's engine evaluates installs, not one-off executions. Claude/Cursor request approval; Codex fails closed because its `PreToolUse` hook does not currently support `ask`. For a direct, standalone runner command, the local-binary fast path mirrors the runner's own resolution (nearest `node_modules/.bin`), so approved project tooling does not trigger the remote-runner gate. Compound, wrapped, or substitution-bearing runner commands require approval because shell state or directory options can change resolution before execution.
- A determined adversary can bypass shell-level analysis — installs can run out of band (a script file written first, `node -e`, and similar), and command-line parsing itself is not exhaustive. Do not rely on the shell layer alone: it raises the bar as one layer of defense in depth — combine it with the MCP tool and CI checks.

---

## Agent Trust Surface — self-defending policy

The guard stops raw installs. But a prompt-injected agent does not have to fight the guard — it can just **rewrite the rules**: weaken `safeinstall.config.json`, delete an agent hook, disable Codex hooks in `.codex/config.toml`, plant an invisible-Unicode instruction in `AGENTS.md`, or register a malicious MCP server. Those files program the *next* agent session; in the agent era they are the persistence mechanism, the new crontab.

`safeinstall trust lock` records a hash baseline of that surface. SafeInstall then reconciles the real state against it before guard decisions and before every install/check, and can re-verify it in CI.

```bash
safeinstall guard install       # register the hooks
safeinstall trust lock --ci github  # baseline the surface AND scaffold CI re-verification
safeinstall trust status        # reconcile — exit 2 on drift (use in CI); read-only
safeinstall trust approve       # review drift and re-baseline (interactive only)
safeinstall trust unlock        # remove the baseline (lock, ledger, head mirror)
```

`--ci github` writes `.github/workflows/safeinstall-trust.yml`, which re-verifies the committed baseline on every pull request by running `safeinstall trust status --require-lock` with the CLI pinned to an exact version *and* its sha512 content hash, recorded from the registry at scaffold time (trust on first use) — a registry that later serves different bytes for that version fails the check instead of silently swapping the verifier. The workflow uses `pull_request_target`, so GitHub loads its definition from the protected base branch; it checks out the proposed revision without credentials, treats it only as data, and never executes PR code. Commit `.safeinstall/` and that workflow together. An existing workflow file is never overwritten. A PR therefore cannot neutralize the verifier that judges it — but a fully consistent rewrite of policy plus baseline still needs human review of the diff (see the CODEOWNERS note below).

Two things you must do for the check to actually enforce, because a CLI cannot set them for you:

- Make the workflow a **required status check** in your branch protection — otherwise a red check does not block a merge.
- Require review of changes to `.safeinstall/` and `.github/workflows/` (e.g. via `CODEOWNERS`). The automatic check catches *inconsistent* tampering; a fully consistent rewrite of the whole baseline in one PR is only caught by a human reviewing the `.safeinstall/` diff.

### The three zones

| Zone | Files | On drift |
|:---|:---|:---|
| **Enforcement** | `safeinstall.config.json`, `.claude/settings.json`, `.codex/hooks.json`, `.codex/config.toml`, `.cursor/hooks.json`, `.github/workflows/safeinstall-trust.yml`, `.safeinstall/` | Every agent command is denied until a human approves |
| **Instruction** | `AGENTS.md`, `CLAUDE.md`, `.cursorrules` and `.cursor/rules/**` at any depth (nested ones such as `packages/app/AGENTS.md` included, never under `node_modules`); at the root also `.claude/CLAUDE.md`, `.claude/rules/**` and `.github/copilot-instructions.md` | Hidden Unicode is always blocked; content drift warns (blocks in `--mode strict`) |
| **Tool** | `.mcp.json`, `.cursor/mcp.json`, MCP blocks in `.claude/settings.json` | Installs and runners are denied until a human approves; unpinned MCP servers are flagged |

Nested instruction files are found with one `git ls-files` call (tracked plus untracked files that are not ignored), or a bounded directory walk outside a git repository. A nested file that `.gitignore` excludes is not discovered, so it is neither hashed nor checked for hidden Unicode. A lock written by an earlier version shows nested files that already exist as added instruction drift until `safeinstall trust approve`.

Instruction content drift only warns by default because Claude Code writes to `CLAUDE.md` itself (its memory feature) — blocking that would break a normal workflow. Hidden Unicode, on the other hand, has no legitimate purpose in these files and always blocks.

### How it defends itself

- **The verifier comes from the protected base branch; human review still owns intentional re-baselines.** Run `safeinstall trust lock --ci github` to scaffold a workflow that re-hashes the candidate trust surface against its committed lock on every pull request, on a machine the agent does not control, with the CLI pinned to an exact version and its sha512 content hash. `pull_request_target` keeps the verifier definition outside the PR's control, while the candidate checkout is inert data with no credentials. This blocks a PR from editing the workflow to waive its own failure. Honest boundary: a PR can still rewrite policy and baseline *consistently*, so require independent review of those diffs. (Wiring the Action directly also works — pin the Action commit, which also pins the CLI version and its recorded digest.)
- **Reconciliation on top of interception.** The guard is the fast layer; every `safeinstall` install/check also reconciles against the baseline. Deleting the hook to silence the guard, or editing a protected file, shows up as drift on the next SafeInstall run locally — and, regardless, fails CI re-verification.
- **Human-gated changes.** Both commands that relax enforcement require a human: `safeinstall trust approve` reads its confirmation from the controlling terminal (`/dev/tty`), never from stdin, and `trust unlock` likewise requires a controlling terminal — both refuse to run in CI or known agent-hook contexts, including when only a parent process carries the context marker (Linux and macOS), so an agent cannot silently re-baseline or remove the surface by dropping the marker from its own environment. This is a barrier, not proof of human presence. `trust status` is read-only (safe in CI, never mutates the repo).
- **Hash-chained ledger.** Baseline decisions are chained in `.safeinstall/ledger.jsonl`; the lock binds to a ledger entry (including its enforcement `mode`), so editing the committed lock to drop a file or downgrade strict→warn breaks the binding. A local head mirror under `~/.safeinstall/` catches naive/accidental history rewrites; a vanished mirror is self-healed from the verified head on the next clean run, so a fresh clone establishes it automatically without noise.

### Trust surface limitations — read honestly

- **The strongest layer is the committed lock reviewed on a PR, not the local mirror.** Locally this is **tamper-evident against mistakes and non-targeted tampering, not tamper-proof.** A scheme-aware agent in your own user account can bypass interception (e.g. an install driven from `node -e`), rewrite the in-repo lock and ledger into a consistent state, and delete the local head mirror — user space cannot stop that, because the agent can read and delete anything you can. CI re-verification runs on a separate machine from a base-branch-owned workflow, so the PR cannot disable its own verifier. A consistent policy-and-baseline rewrite can still pass automatically. **The residual guarantee against a capable adversary is independent human review of the trust-surface diff (workflow, lock, and config) on every dependency PR — enforced by a ruleset once a second trusted reviewer is available. Run the CI check and require that review; they cover different failure modes.**
- It watches shell commands and files, not intent: an install performed by a program the agent writes and runs is caught by reconciliation on the next SafeInstall/CI run, not prevented at the moment of the call.
- A missing local head mirror is ambiguous (a fresh clone has none too), so on a clean verify it is self-healed from the committed ledger head rather than warned or blocked — the mirror is a best-effort local convenience, never the guarantee.

---

## Configuration

Optional `safeinstall.config.json` — discovered by walking upward from the project directory, or passed explicitly with `--config <path>`. An explicit path that cannot be read is an error (exit 1), never a silent fallback to defaults. `--config` must come before the command (`safeinstall --config <path> check`); after the command it is an error. In a project with a trust lock, only the locked `safeinstall.config.json` at the trust root is accepted: any other config, whether passed explicitly or discovered in a subfolder or parent folder, blocks with `trust-unbound-config`.

```json
{
  "minimumCliVersion": "0.12.0",
  "minimumReleaseAgeHours": 72,
  "registryUrl": "https://registry.npmjs.org",
  "allowedScripts": {
    "esbuild": ["postinstall"]
  },
  "allowedSources": ["registry", "workspace", "file", "directory"],
  "sourceBaselines": {},
  "allowedPackages": [],
  "packageManagerDefaults": {
    "npm": { "ignoreScripts": true },
    "pnpm": { "ignoreScripts": true },
    "bun": { "ignoreScripts": true }
  },
  "typoSquat": {
    "mode": "warn",
    "minNameLength": 4,
    "ignore": []
  },
  "provenance": {
    "mode": "warn",
    "requireFor": [],
    "trustedPublishers": {
      "axios": "axios/axios"
    },
    "offlineBehavior": "fail-closed",
    "toolingUnavailable": "warn"
  },
  "transitive": {
    "mode": "warn",
    "checks": ["install-script", "untrusted-source"]
  },
  "continuity": {
    "mode": "warn",
    "baselineSize": 5
  }
}
```

| Field | Purpose |
|:---|:---|
| `minimumCliVersion` | Optional. Lowest safeinstall-cli version whose behavior this project's protections assume (exact semver). An older running CLI **warns** — in the guard, `install`/`check`, and `trust status` — but never hard-fails |
| `minimumReleaseAgeHours` | Minimum age in hours for registry versions |
| `registryUrl` | Credential-free npm-compatible registry URL for metadata and installation (mirrors, Artifactory, Verdaccio); userinfo, query parameters, and fragments are rejected |
| `allowedScripts` | Per-package lifecycle script exceptions |
| `allowedSources` | Permitted source types: `registry`, `git`, `url`, `tarball`, `workspace`, `file` (local tarball), `directory` (local directory that is not a workspace package). First-party workspace packages are always allowed |
| `sourceBaselines` | Reviewed package-to-source identities (`registry`, `git`, `url`, or `tarball`). Fallback only when there is no git `HEAD` manifest for the project; never consulted by `decisions authorize` and ignored whenever `HEAD` has the manifest |
| `allowedPackages` | Names that skip release-age, install-script, and typo-squat checks (with warning). Source, trust-downgrade, and provenance checks still apply. |
| `packageManagerDefaults` | Legacy configuration; lifecycle scripts remain disabled even when `ignoreScripts` is `false` |
| `typoSquat.mode` | `"off"` / `"warn"` / `"block"` — how to handle suspected typo-squats |
| `typoSquat.minNameLength` | Minimum package name length to check (shorter names are skipped) |
| `typoSquat.ignore` | Known legitimate lookalikes to skip, lowercased on load |
| `provenance.mode` | `"off"` / `"warn"` / `"require"` — whether to verify Sigstore attestations |
| `provenance.requireFor` | Package names (glob supported) for which provenance is required even in `"warn"` mode |
| `provenance.trustedPublishers` | Map of package name pattern → expected `owner/repo` slug; mismatches always block |
| `provenance.offlineBehavior` | `"fail-closed"` blocks on fetch failure, `"allow-cached"` falls back to a cryptographically verified cached attestation whose signed subject matches the exact package and version. Without such a cached attestation, a package whose provenance is required (`mode: "require"`, `requireFor`) or pinned (`trustedPublishers`) is still blocked; any other package gets a warning |
| `provenance.toolingUnavailable` | `"warn"` (default) proceeds with a loud warning when the `sigstore` verifier is not installed; `"fail-closed"` treats a missing verifier as suspicious and blocks every install until it is present (installing `sigstore` itself stays exempt, so it can never deadlock) |
| `transitive.mode` | `"off"` / `"warn"` / `"block"` — transitive install-script check, and whether a missing or unreadable lockfile warns or blocks. Lockfile sources are checked against `allowedSources` in every mode |
| `transitive.checks` | `"install-script"` enables the install-script check. `"untrusted-source"` is accepted but has no effect: that check always runs |
| `continuity.mode` | `"off"` / `"warn"` / `"block"` — detect provenance downgrades and source-repo changes against a learned per-package baseline |
| `continuity.baselineSize` | How many recent versions to sample when learning the baseline (default 5). When those carry no provenance but the registry lists it for earlier versions, the versions before them are verified and used instead, up to three times this size back |

A project `.npmrc` or `pnpm-workspace.yaml` is read by the package manager itself, not by SafeInstall.
Credentials and registry scopes belong there. Settings that move where the package manager reads or
writes (`modules-dir`, `virtual-store-dir`, `lockfile-dir`, a project-supplied `store-dir`), switch off
one of its checks (`verify-store-integrity=false`, `ignore-scripts=false`) or make
it load code (`pnpmfile`, `use-node-version`, `git`, `script-shell`) block the install, also when they
arrive as `npm_config_*` environment variables.

Keep private-registry authentication in an environment-backed `.npmrc` entry, such as an
`_authToken=${NPM_TOKEN}` setting, rather than embedding authority material in `registryUrl`.
SafeInstall's own metadata requests do not send credentials (Node's `fetch` refuses URLs that
carry them), and it does not read registry URLs from `.npmrc` or `npm_config_registry`, so those
never reach its output or decision records. A `registryUrl` with userinfo, query parameters, or a
fragment is a config error, and `decisions verify` reports a committed one as `registry-not-default`.
If a credential-bearing URL was previously used, treat the credential as exposed: audit
`.safeinstall/decisions/`, CI logs and artifacts, and Git history; revoke and rotate the
credential; then remove it from retained artifacts and repository history using your host's
secret-removal procedure.

### Pinning a minimum CLI version

Guard verdicts change across releases (fixed false positives, new checks), but the CLI is typically installed globally — so a project can assume `0.12.0` behavior while an agent's machine still runs `0.11.0`. Set `minimumCliVersion` to the lowest version whose behavior your policy assumes, and every older CLI announces the mismatch loudly:

```text
Warning: This project's safeinstall.config.json expects safeinstall-cli >= 0.12.0, but version 0.11.0 is running — protections this project relies on may be missing or behave differently. Update with `npm install -g safeinstall-cli@latest`.
```

The check is fully offline (a semver comparison against the running version) and deliberately a warning, never a hard failure: a hard failure would break every agent session after each release until the global CLI is updated. Two sharp edges to know:

- The field must be an **exact version** (`"0.12.0"`), not a range — it is a floor, not a constraint. Anything else fails config parsing closed.
- CLIs released **before this field existed** reject unknown config keys, so they refuse the whole config (fail-closed) instead of warning. Setting the field effectively requires collaborators to run a CLI that knows it.

Run `safeinstall init` to generate a starter config.

---

## Exit codes

| Code | Meaning |
|:---|:---|
| `0` | Allowed / check passed |
| `1` | Runtime or config error |
| `2` | Blocked by policy |

Use exit code 2 like any other failing step in a CI pipeline.

## JSON output

Pass `--json` anywhere in the command. Structured output goes to stdout.

```bash
safeinstall --json pnpm add axios
```

Fields: `command`, `commandString`, `packageManager`, `decision`, `summary`, `reasons`, `warnings`, `affectedPackages`, `exitCode`, `exitCodeMeaning`. Allowed installs include `execution.stdout` and `execution.stderr`.

---

## Examples

> Want to see every check in action? Run [`bash demo/run.sh`](https://github.com/Mickdownunder/SafeInstall/blob/HEAD/demo) — a reproducible script that blocks one scenario per policy check against real packages. See [demo/README.md](https://github.com/Mickdownunder/SafeInstall/blob/HEAD/demo/README.md) for the walkthrough.
>
> Want to see it against a **real attack**? Run [`pnpm replay mastra`](https://github.com/Mickdownunder/SafeInstall/blob/HEAD/demo/replay) — it feeds the recorded attack-time state of the June 2026 Mastra compromise into SafeInstall's real policy engine and shows which checks would have blocked it. See [demo/replay/README.md](https://github.com/Mickdownunder/SafeInstall/blob/HEAD/demo/replay/README.md).

<details>
<summary><strong>Fresh release blocked</strong></summary>

```
$ safeinstall pnpm add axios
Using config: built-in defaults
Install blocked.
- axios@1.14.0
  Blocked: release too new (axios@1.14.0 is 6 hours old; minimum is 72 hours).
  Suggestion: Retry later or lower minimumReleaseAgeHours if this package is intentionally urgent.
```

</details>

<details>
<summary><strong>Git source blocked</strong></summary>

```
$ safeinstall npm install github:axios/axios
Using config: built-in defaults
Install blocked.
- github:axios/axios
  Blocked: untrusted source (git).
  Suggestion: Use a registry release or allow this source intentionally.
```

</details>

<details>
<summary><strong>Package manager mismatch</strong></summary>

```
$ safeinstall npm install
Using config: built-in defaults
Install blocked.
- Project install blocked: package.json declares pnpm as packageManager, but this command uses npm.
```

</details>

<details>
<summary><strong>Stale lockfile</strong></summary>

```
$ safeinstall pnpm install
Using config: built-in defaults
Install blocked.
- Project install blocked: axios is declared in package.json but missing from pnpm-lock.yaml.
```

</details>

<details>
<summary><strong>Typo-squat caught</strong></summary>

```
$ safeinstall pnpm add raect
Using config: ./safeinstall.config.json
Install blocked.
- raect
  Blocked: Suspected typo-squat: "raect" is 1 edit(s) away from popular package "react".
  Suggestion: Verify you meant to install "react". If this package is intentional, add "raect" to typoSquat.ignore.
```

</details>

<details>
<summary><strong>Publisher mismatch (maintainer compromise defense)</strong></summary>

```
$ safeinstall pnpm add axios@1.99.0
Using config: ./safeinstall.config.json
Install blocked.
- axios@1.99.0
  Blocked: publisher mismatch for axios (expected axios/axios, got evil-org/axios).
  Suggestion: Verify the package source. Update provenance.trustedPublishers only if the change is intentional.
```

</details>

---

## GitHub Action

Run SafeInstall policy checks automatically on every pull request. Pin the
Action to a reviewed full commit SHA, and bind the CLI release to its
independently verified SHA-512 SRI. Replace both placeholders below from the
same reviewed Action release before enabling the workflow.

```yaml
# .github/workflows/safeinstall.yml
name: SafeInstall Policy Check
on: [pull_request]
jobs:
  policy:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0
      - uses: actions/setup-node@48b55a011bda9f5d6aeb4c2d9c7362e8dae4041e # v6.4.0
        with:
          node-version: 22
      - uses: Mickdownunder/SafeInstall@<full-40-character-commit-sha>
```

Pinning the Action to a commit also pins the CLI: the Action records an exact default CLI version together with the SHA-512 of its published tarball, downloads that tarball, and refuses to install bytes that do not match. To run a different CLI version, set both inputs:

```yaml
      - uses: Mickdownunder/SafeInstall@<full-40-character-commit-sha>
        with:
          version: 0.15.0
          integrity: sha512-<verified-release-integrity>
```

Take the digest from `npm view safeinstall-cli@<version> dist.integrity` and check it against the release provenance. `latest`, other dist-tags and ranges are rejected.

The action runs `safeinstall check` against your direct dependencies and sets the job status to pass or fail. Blocked dependencies appear in the GitHub Actions job summary with the exact block reason and suggestion.

### Install mode

To enforce policy during the actual install step (not just a check):

```yaml
      - uses: Mickdownunder/SafeInstall@<full-40-character-commit-sha>
        with:
          mode: install
          package-manager: pnpm
          args: "--frozen-lockfile"
```

### Inputs

| Input | Default | Description |
|:---|:---|:---|
| `mode` | `check` | `check` audits deps; `install` runs the package manager through SafeInstall |
| `package-manager` | `pnpm` | `npm` or `pnpm` for installation; `bun` fails closed |
| `args` | | Additional arguments forwarded to the package manager |
| `config-path` | | Explicit path to `safeinstall.config.json` (auto-discovered if omitted) |
| `version` | `0.16.0` | Exact SafeInstall CLI version to install; dist-tags and ranges are rejected |
| `integrity` | recorded for the default version | SHA-512 SRI of the selected CLI tarball; required when `version` is not the default |

### Outputs

| Output | Description |
|:---|:---|
| `decision` | `allow` or `block` |
| `summary` | Human-readable one-line summary |
| `exit-code` | `0` (allow), `2` (block), or `1` (error) |
| `json` | Full JSON result from SafeInstall |

---

## Limitations

- **Not a CVE scanner** — pair with `npm audit` or Snyk for vulnerability data
- **Transitive dependencies** are always checked for their lockfile source, and for install scripts when `transitive.mode` is enabled. Release-age, typo-squat, and provenance still apply to direct dependencies only. A transitive entry that names the right registry address with a different digest is not compared with the registry here; the frozen install then fails on the digest mismatch.
- **Transitive install-script detection** is npm-only — pnpm lockfiles do not record install-script presence. Transitive untrusted-source detection works for both.
- **Native builds (`binding.gyp`)** are caught via the install-script check: npm normalizes `binding.gyp` into a `node-gyp rebuild` install script at publish time, so it is present in the registry metadata SafeInstall already reads — no tarball download required. The residual edge is a package published through a non-standard client that omits this normalization while still shipping a `binding.gyp`; detecting that would require tarball content inspection, which is out of scope (see *What it does not do*).
- **`peerDependencies`** not evaluated unless also declared as direct dependencies
- **Trust downgrade detection** compares a direct dependency's declared source with the committed manifest (see *Trust downgrade* above). It covers swaps from `registry` to `git`, `url`, or `tarball` only; swaps to `file:`, `link:`, or `workspace:` sources, lockfile-only changes, and moves to a different registry are not detected by this check
- **Bun installation** fails closed; an artifact-binding adapter is not implemented
- **Trusted execution boundary** — this is not an OS sandbox. It relies on a trusted npm/pnpm binary enforcing frozen-lockfile integrity, the selected registry metadata, and the local filesystem not being controlled by a concurrent attacker. It does not prove package code benign, inspect every transitive artifact against registry policy, or isolate runtime execution
- **Typo-squat target list** is curated and refreshed manually between releases; brand new packages published in the last day may not yet appear
- **Provenance verification** supports GitHub Actions trusted publishers on the public Sigstore root only (GitLab CI, self-hosted Sigstore currently out of scope)
- **Git sources** are identified by URL for allowlist purposes, not by inferred package name — conflating registry `axios` with `github:any-fork/axios` would be dangerous
- Ambiguous metadata blocks instead of guessing — by design

## What it does not do

- Vulnerability scanning or CVE databases
- Registry proxying or tarball rewriting
- Malware detection or package content analysis
- Selective lifecycle script execution (always forces `--ignore-scripts`)

---

## Works with

SafeInstall works with any tool that runs package manager commands — including AI coding assistants:

**Cursor** · **Codex** · **GitHub Copilot** · **Cline** · **Claude Code** · **Windsurf** · **Aider** · **Devin** · **Continue**

Just prefix your install commands with `safeinstall`. Same workflow, one safety layer.

---

## Contributing

```bash
pnpm install
pnpm typecheck
pnpm test
pnpm build
```

Issues and PRs welcome. Author merges at own discretion — this is a solo-maintained project.

## License

MIT — see [LICENSE](https://github.com/Mickdownunder/SafeInstall/blob/HEAD/LICENSE).

## Disclaimer

SafeInstall is provided as-is under the MIT license. It is a policy tool that enforces configurable rules on package installs. It does not guarantee the safety of any package, does not detect all supply-chain attacks, and does not replace professional security review. Use at your own risk. The authors are not liable for any damages arising from the use of this software.

Last verified: 2026-10-01

---

<p align="center">
  <a href="https://safeinstall.dev">safeinstall.dev</a> · <a href="https://www.npmjs.com/package/safeinstall-cli">npm</a> · <a href="https://github.com/Mickdownunder/SafeInstall">GitHub</a>
</p>

