Skip to content

A full-featured CRM built with React, shadcn/ui, and Supabase.

Vet agent installs in a hook instead of denying them

Jerome06c017aa9c79
diff --git a/.claude/hooks/dependency-gate.mjs b/.claude/hooks/dependency-gate.mjs
new file mode 100755
index 00000000..897f1882
--- /dev/null
+++ b/.claude/hooks/dependency-gate.mjs
@@ -0,0 +1,190 @@
+#!/usr/bin/env node
+// PreToolUse(Bash) — any caller. Vets every package an `npm install <pkg>` or `npx <pkg>`
+// would fetch, then adds `--ignore-scripts --min-release-age=<days>` so npm itself refuses
+// a too-recent version anywhere in the tree, transitive ones included. The thresholds are
+// `dependencies.*` in harness.config.json; an invalid block falls back to the defaults, so
+// a typo can never loosen the gate.
+//
+// Fails CLOSED when the registry cannot be reached: the install needs it anyway, and
+// failing open would hand back exactly the unvetted install this replaces.
+//
+// A project's `permissions.deny` on `Bash(npm install *)` wins over this hook, so the gate
+// only takes effect once that deny is removed.
+
+import { existsSync, readFileSync } from "node:fs";
+import { join, resolve } from "node:path";
+import { dependencyPolicy, loadConfig } from "./lib/config.mjs";
+import { createHookContext } from "./lib/context.mjs";
+import { updatedToolInput } from "./lib/io.mjs";
+import { findInstalls, parseSpec } from "./lib/install-commands.mjs";
+import { fetchFacts, refusal } from "./lib/npm-registry.mjs";
+
+const NEXT_STEP =
+ "Do not stop on this: build the feature without the package (plain code, or a package " +
+ "the project already has), or use a well-established alternative. Only if neither is " +
+ "possible, tell the user that a developer has to approve this package " +
+ "(`dependencies.allow` in harness.config.json).";
+
+const describePolicy = (policy) =>
+ `Packages an agent adds are vetted automatically: on the npm registry, first published ` +
+ `${policy.minReleaseAgeDays}+ days ago, ${policy.minWeeklyDownloads}+ weekly downloads, ` +
+ `not deprecated, no install script, no ${policy.blockingSeverities.join(" or ")} ` +
+ `security advisory.`;
+
+const declaredDependencies = (dir) => {
+ try {
+ const pkg = JSON.parse(readFileSync(join(dir, "package.json"), "utf8"));
+ return new Set(
+ Object.keys({
+ ...pkg.dependencies,
+ ...pkg.devDependencies,
+ ...pkg.optionalDependencies,
+ ...pkg.peerDependencies,
+ }),
+ );
+ } catch {
+ return new Set();
+ }
+};
+
+const isApproved = (name, allow) =>
+ allow.some(
+ (entry) =>
+ entry === name ||
+ (entry.endsWith("/*") && name.startsWith(entry.slice(0, -1))),
+ );
+
+const skipReason = (parsed, declared, allow) => {
+ if (!parsed) return "";
+ if (declared.has(parsed.name)) return "declared";
+ return isApproved(parsed.name, allow) ? "approved" : "";
+};
+
+const isLocalBin = (dir, name) =>
+ existsSync(join(dir, "node_modules", ".bin", name));
+
+const quoted = (items) => items.map((s) => `\`${s}\``).join(", ");
+
+/**
+ * @param {{ cwd?: string, tool_input?: { command?: string } }} input
+ * @param {{minReleaseAgeDays: number, minWeeklyDownloads: number, blockingSeverities: string[], allow: string[]}} policy
+ * @returns {Promise<null | { block: string, log: string } | { rewrite: string, log: string }>}
+ */
+async function decide(input, policy) {
+ const command = String(input.tool_input?.command || "");
+ const found = findInstalls(command);
+ if (!found.length) return null;
+
+ const other = found.find((f) => f.kind === "other");
+ if (other)
+ return {
+ block:
+ `Dependency gate: \`${other.manager}\` installs are not vetted, only npm's are ` +
+ `(\`npm install <pkg>\`, \`npx <pkg>\`). In an npm project use those. ${NEXT_STEP}`,
+ log: `other-manager=${other.manager}`,
+ };
+
+ const owned = found.flatMap((f) => f.gateFlags);
+ if (owned.length)
+ return {
+ block:
+ `Dependency gate: ${quoted(owned)} would bypass the vetting, which sets the registry, ` +
+ `the release-age cutoff and --ignore-scripts itself. Drop the flag. A version younger ` +
+ `than ${policy.minReleaseAgeDays} days or an install script needs a developer's approval.`,
+ log: `gate-owned-flags=${owned.join(",")}`,
+ };
+
+ const installs = found
+ .map((f) => ({
+ ...f,
+ dir: resolve(input.cwd || process.cwd(), f.cwd || "."),
+ }))
+ .filter((f) => !(f.binOnly && isLocalBin(f.dir, f.specs[0])));
+ if (!installs.length) return null;
+
+ const specs = installs.flatMap((f) => {
+ const declared = declaredDependencies(f.dir);
+ return f.specs.map((spec) => {
+ const parsed = parseSpec(spec);
+ return { spec, parsed, skip: skipReason(parsed, declared, policy.allow) };
+ });
+ });
+ const unparsable = specs.find((s) => !s.parsed);
+ if (unparsable)
+ return {
+ block:
+ `Dependency gate: \`${unparsable.spec}\` is not a plain registry package (a git URL, ` +
+ `tarball, path, alias or variable), so it cannot be vetted. ${NEXT_STEP}`,
+ log: `unparsable=${unparsable.spec}`,
+ };
+
+ const toVet = specs.filter((s) => !s.skip);
+ let refused;
+ try {
+ const verdicts = await Promise.all(
+ toVet.map(async (s) => ({
+ spec: s.spec,
+ reason: refusal(
+ await fetchFacts(s.parsed.name, s.parsed.version),
+ policy,
+ ),
+ })),
+ );
+ refused = verdicts.filter((v) => v.reason);
+ } catch (e) {
+ return {
+ block:
+ `Dependency gate: could not reach the npm registry to vet ${quoted(toVet.map((s) => s.spec))} ` +
+ `(${e.message}), even after a retry. The install is refused rather than run unvetted. ` +
+ NEXT_STEP,
+ log: `registry-error ${e.message}`,
+ };
+ }
+ if (refused.length)
+ return {
+ block:
+ `Dependency gate refused ${refused.map((r) => `\`${r.spec}\` (${r.reason})`).join(", ")}. ` +
+ `${describePolicy(policy)} ${NEXT_STEP}`,
+ log: `refused=${refused.map((r) => `${r.spec}:${r.reason}`).join(";")}`,
+ };
+
+ const pinned = ` --ignore-scripts --min-release-age=${policy.minReleaseAgeDays}`;
+ const rewrite = installs
+ .map((f) => f.insertAt)
+ .sort((a, b) => b - a)
+ .reduce((cmd, at) => cmd.slice(0, at) + pinned + cmd.slice(at), command);
+ const names = (skip) =>
+ specs
+ .filter((s) => s.skip === skip)
+ .map((s) => s.spec)
+ .join(",");
+ return {
+ rewrite,
+ log: `vetted=[${names("")}] declared=[${names("declared")}] approved=[${names("approved")}]`,
+ };
+}
+
+const loadPolicy = (ctx) => {
+ try {
+ return dependencyPolicy(loadConfig());
+ } catch (e) {
+ ctx.log(`config unreadable, using the default policy: ${e.message}`);
+ return dependencyPolicy({});
+ }
+};
+
+let input = {};
+try {
+ input = JSON.parse(readFileSync(0, "utf8"));
+} catch {
+ process.exit(0);
+}
+if (!findInstalls(input.tool_input?.command).length) process.exit(0);
+const ctx = createHookContext(input, "dependency-gate");
+const decision = await decide(input, loadPolicy(ctx));
+if (decision?.block) ctx.block({ reason: decision.block, log: decision.log });
+if (decision?.rewrite) {
+ ctx.log(`REWRITE ${decision.log}`);
+ updatedToolInput({ ...input.tool_input, command: decision.rewrite });
+}
+process.exit(0);
diff --git a/.claude/hooks/lib/config.mjs b/.claude/hooks/lib/config.mjs
index 9fec0980..24141254 100644
--- a/.claude/hooks/lib/config.mjs
+++ b/.claude/hooks/lib/config.mjs
@@ -10,6 +10,8 @@ import { REPO } from "./paths.mjs";
export const CONFIG_FILENAME = "harness.config.json";
+const SEVERITIES = ["low", "moderate", "high", "critical"];
+
// Minimal safe baseline. The committed harness.config.json overrides these.
// Optional capabilities (deploy, app) are ABSENT here on purpose: a capability
// exists iff its block is present in the config.
@@ -20,6 +22,12 @@ const DEFAULTS = {
worktree: { provision: "npm-link" },
skills: { developerMenu: [] },
roles: {},
+ dependencies: {
+ minReleaseAgeDays: 21,
+ minWeeklyDownloads: 1000,
+ blockingSeverities: ["high", "critical"],
+ allow: [],
+ },
launcher: {
sessionDirEnv: "CHAT_SESSION_DIR",
turnSentinelDir: null,
@@ -80,6 +88,28 @@ function validate(cfg) {
}
}
+ const deps = cfg.dependencies;
+ if (!isObject(deps)) fail("`dependencies` must be an object");
+ for (const key of ["minReleaseAgeDays", "minWeeklyDownloads"]) {
+ if (!Number.isInteger(deps[key]) || deps[key] < 0) {
+ fail(`dependencies.${key} must be a non-negative integer`);
+ }
+ }
+ if (
+ !Array.isArray(deps.blockingSeverities) ||
+ deps.blockingSeverities.some((s) => !SEVERITIES.includes(s))
+ ) {
+ fail(
+ `dependencies.blockingSeverities must list severities among ${SEVERITIES.join(", ")}`,
+ );
+ }
+ if (
+ !Array.isArray(deps.allow) ||
+ deps.allow.some((name) => typeof name !== "string" || !name)
+ ) {
+ fail("dependencies.allow must be an array of package names");
+ }
+
if ("deploy" in cfg && cfg.deploy !== undefined) {
if (!isObject(cfg.deploy) || !Array.isArray(cfg.deploy.relevantGlobs)) {
fail("`deploy.relevantGlobs` must be an array when `deploy` is present");
@@ -137,6 +167,8 @@ export const debounceRoles = (cfg) =>
roleNames(cfg).filter((r) => cfg.roles[r]?.debounce);
// Managed-launcher extension points (empty object when no launcher overlay).
export const launcher = (cfg) => cfg.launcher ?? {};
+export const dependencyPolicy = (cfg) =>
+ cfg.dependencies ?? DEFAULTS.dependencies;
// The format-kind validation step (null when none), used by format-on-write.
export const formatStep = (cfg) =>
validationSteps(cfg).find((s) => s.kind === "format") ?? null;
diff --git a/.claude/hooks/lib/install-commands.mjs b/.claude/hooks/lib/install-commands.mjs
new file mode 100644
index 00000000..f1fc9c50
--- /dev/null
+++ b/.claude/hooks/lib/install-commands.mjs
@@ -0,0 +1,258 @@
+// Find the package installs and npx runs inside a Bash command, so dependency-gate can vet
+// what they would fetch. Reads the quote-masked text: a package name inside a commit
+// message or an echo is not an install.
+
+/**
+ * Blank out the CONTENT of quoted spans, keeping the quotes and the length.
+ *
+ * Every regex below reads shell punctuation, and none of it means anything inside quotes:
+ * `grep "a;b" f` split into two commands whose second one had no known verb, and
+ * `echo "a -> b"` read as a redirect into a file. Both were counted as work.
+ *
+ * @param {string} command
+ * @returns {string} the command with quoted content replaced by `x`
+ */
+function maskQuoted(command) {
+ let out = "";
+ let quote = "";
+ for (let i = 0; i < command.length; i++) {
+ const ch = command[i];
+ if (quote) {
+ if (ch === "\\" && quote === '"' && i + 1 < command.length) {
+ out += "xx";
+ i++;
+ continue;
+ }
+ if (ch === quote) {
+ quote = "";
+ out += ch;
+ continue;
+ }
+ out += "x";
+ continue;
+ }
+ if (ch === '"' || ch === "'") {
+ quote = ch;
+ out += ch;
+ continue;
+ }
+ if (ch === "\\" && i + 1 < command.length) {
+ out += ch + command[i + 1];
+ i++;
+ continue;
+ }
+ out += ch;
+ }
+ return out;
+}
+
+const NPM_INSTALL = new Set([
+ "install",
+ "i",
+ "add",
+ "in",
+ "ins",
+ "inst",
+ "insta",
+ "instal",
+ "isnt",
+ "isnta",
+ "isntal",
+ "isntall",
+ "it",
+ "install-test",
+]);
+const NPM_EXEC = new Set(["exec", "x"]);
+const NPM_VALUE_FLAGS = new Set([
+ "--prefix",
+ "-C",
+ "--workspace",
+ "-w",
+ "--omit",
+ "--include",
+ "--tag",
+ "--install-strategy",
+ "--cache",
+ "--userconfig",
+ "--registry",
+ "--before",
+ "--min-release-age",
+]);
+const EXEC_VALUE_FLAGS = new Set([...NPM_VALUE_FLAGS, "--call", "-c"]);
+const GATE_OWNED =
+ /^--(?:registry|before|min-release-age)(?:=|$)|^--(?:no-ignore-scripts|ignore-scripts=false)$/;
+
+const MANAGER = /(?:^|[\s;&|(){}`])(npm|npx|pnpm|pnpx|yarn|bun|bunx)(?=\s|$)/g;
+const SEGMENT_END = /[;&|\n)`]/;
+const CD = /(?:^|[\s;&|(){}`])cd\s+(\S+)/g;
+const REDIRECT = /^\d*[<>]/;
+const BARE_REDIRECT = /^\d*[<>]+&?$/;
+const NAME = /^(?:@[a-z0-9~][\w.~-]*\/)?[a-z0-9~][\w.~-]*$/i;
+
+const unquote = (text) => text.replace(/["']/g, "");
+
+const tokensOf = (command, masked, from, to) =>
+ [...masked.slice(from, to).matchAll(/\S+/g)].map((m) => {
+ const start = from + m.index;
+ const end = start + m[0].length;
+ return { text: unquote(command.slice(start, end)), end };
+ });
+
+const installArgs = (words) => {
+ const specs = [];
+ const flags = [];
+ for (let i = 0; i < words.length; i++) {
+ const w = words[i].text;
+ if (REDIRECT.test(w)) {
+ if (BARE_REDIRECT.test(w)) i++;
+ continue;
+ }
+ if (w.startsWith("-")) {
+ flags.push(w);
+ if (NPM_VALUE_FLAGS.has(w)) i++;
+ continue;
+ }
+ specs.push(w);
+ }
+ return { specs, gateFlags: flags.filter((f) => GATE_OWNED.test(f)) };
+};
+
+const execArgs = (words) => {
+ const packages = [];
+ const flags = [];
+ let bin;
+ for (let i = 0; i < words.length && bin === undefined; i++) {
+ const w = words[i].text;
+ if (w === "--") bin = words[i + 1]?.text ?? "";
+ else if (w.startsWith("--package=")) packages.push(w.slice(10));
+ else if (w === "-p" || w === "--package") packages.push(words[++i]?.text);
+ else if (w.startsWith("-")) {
+ flags.push(w);
+ if (EXEC_VALUE_FLAGS.has(w)) i++;
+ } else bin = w;
+ }
+ const specs = packages.length ? packages.filter(Boolean) : bin ? [bin] : [];
+ return {
+ specs,
+ binOnly: !packages.length,
+ gateFlags: flags.filter((f) => GATE_OWNED.test(f)),
+ };
+};
+
+const addsWithOtherManager = (manager, [sub, next] = []) => {
+ const withPackage = next !== undefined && !next.startsWith("-");
+ switch (manager) {
+ case "pnpx":
+ case "bunx":
+ return true;
+ case "pnpm":
+ return (
+ sub === "add" ||
+ sub === "dlx" ||
+ ((sub === "i" || sub === "install") && withPackage)
+ );
+ case "yarn":
+ return (
+ sub === "add" || sub === "dlx" || (sub === "global" && next === "add")
+ );
+ case "bun":
+ return (
+ ["add", "a", "x"].includes(sub) ||
+ ((sub === "i" || sub === "install") && withPackage)
+ );
+ default:
+ return false;
+ }
+};
+
+const classify = (manager, managerEnd, words) => {
+ if (manager === "npx") {
+ const exec = execArgs(words);
+ return exec.specs.length
+ ? { kind: "exec", manager, insertAt: managerEnd, ...exec }
+ : null;
+ }
+ if (manager !== "npm") {
+ return addsWithOtherManager(
+ manager,
+ words.map((w) => w.text),
+ )
+ ? { kind: "other", manager, specs: [], gateFlags: [], insertAt: -1 }
+ : null;
+ }
+ let i = 0;
+ while (i < words.length && words[i].text.startsWith("-")) {
+ i += NPM_VALUE_FLAGS.has(words[i].text) ? 2 : 1;
+ }
+ const sub = words[i];
+ if (!sub) return null;
+ if (NPM_INSTALL.has(sub.text)) {
+ const install = installArgs(words.slice(i + 1));
+ return install.specs.length
+ ? {
+ kind: "install",
+ manager,
+ insertAt: sub.end,
+ binOnly: false,
+ ...install,
+ }
+ : null;
+ }
+ if (NPM_EXEC.has(sub.text)) {
+ const exec = execArgs(words.slice(i + 1));
+ return exec.specs.length
+ ? { kind: "exec", manager, insertAt: sub.end, ...exec }
+ : null;
+ }
+ return null;
+};
+
+const lastCdBefore = (command, masked, index) => {
+ let dir;
+ for (const m of masked.slice(0, index).matchAll(CD)) {
+ const start = m.index + m[0].length - m[1].length;
+ dir = unquote(command.slice(start, start + m[1].length));
+ }
+ return dir;
+};
+
+/**
+ * Every install or npx run in `command`, in order.
+ *
+ * `kind` is `install` (npm install and its aliases, with at least one package), `exec`
+ * (npx / npm exec), or `other` (a pnpm / yarn / bun install or runner, which the gate
+ * does not vet). `insertAt` is the offset right after the subcommand, where flags go.
+ * `binOnly` means the spec is a command name npx may resolve to a local bin.
+ * @param {string} command
+ * @returns {Array<{kind: string, manager: string, specs: string[], gateFlags: string[], insertAt: number, binOnly?: boolean, cwd?: string}>}
+ */
+export function findInstalls(command) {
+ const original = String(command || "");
+ const masked = maskQuoted(original);
+ const found = [];
+ for (const m of masked.matchAll(MANAGER)) {
+ const start = m.index + m[0].length - m[1].length;
+ const endRel = masked.slice(start).search(SEGMENT_END);
+ const end = endRel === -1 ? masked.length : start + endRel;
+ const [managerToken, ...words] = tokensOf(original, masked, start, end);
+ const install = classify(m[1], managerToken.end, words);
+ if (install)
+ found.push({ ...install, cwd: lastCdBefore(original, masked, start) });
+ }
+ return found;
+}
+
+/**
+ * Split a registry spec into name and version part, or null when `spec` is not a plain
+ * registry package (git URL, GitHub shorthand, tarball, path, alias, shell variable).
+ * @param {string} spec
+ * @returns {{name: string, version: string} | null}
+ */
+export function parseSpec(spec) {
+ const at = spec.indexOf("@", 1);
+ const name = at === -1 ? spec : spec.slice(0, at);
+ const version = at === -1 ? "" : spec.slice(at + 1);
+ if (!NAME.test(name) || /[:/]/.test(version) || /\.tgz$/i.test(spec))
+ return null;
+ return { name, version };
+}
diff --git a/.claude/hooks/lib/io.mjs b/.claude/hooks/lib/io.mjs
index c50debca..87ba7119 100644
--- a/.claude/hooks/lib/io.mjs
+++ b/.claude/hooks/lib/io.mjs
@@ -3,3 +3,16 @@
export function decisionBlock(reason) {
process.stdout.write(JSON.stringify({ decision: "block", reason }) + "\n");
}
+
+// Replace a PreToolUse call's `tool_input` and let it proceed. Sent without
+// `permissionDecision`, so the call still goes through the project's permission rules.
+export function updatedToolInput(toolInput) {
+ process.stdout.write(
+ JSON.stringify({
+ hookSpecificOutput: {
+ hookEventName: "PreToolUse",
+ updatedInput: toolInput,
+ },
+ }) + "\n",
+ );
+}
diff --git a/.claude/hooks/lib/npm-registry.mjs b/.claude/hooks/lib/npm-registry.mjs
new file mode 100644
index 00000000..1f3520cc
--- /dev/null
+++ b/.claude/hooks/lib/npm-registry.mjs
@@ -0,0 +1,113 @@
+// What the npm registry says about a package, and whether that is enough for an agent to
+// add it without a human. `npm_config_registry` and HARNESS_NPM_DOWNLOADS_API point the
+// lookups elsewhere (a mirror, or the test stub).
+
+const DAY_MS = 24 * 60 * 60 * 1000;
+const TIMEOUT_MS = 10_000;
+const RETRY_DELAY_MS = 1000;
+const INSTALL_SCRIPTS = ["preinstall", "install", "postinstall"];
+const EXACT = /^v?\d+\.\d+\.\d+(?:[-+][\w.-]+)?$/;
+const TAG = /^[a-z][\w.-]*$/i;
+
+const trimSlash = (url) => url.replace(/\/+$/, "");
+const registry = () =>
+ trimSlash(process.env.npm_config_registry || "https://registry.npmjs.org");
+const downloadsApi = () =>
+ trimSlash(process.env.HARNESS_NPM_DOWNLOADS_API || "https://api.npmjs.org");
+
+const fetchOnce = async (url, init) => {
+ const res = await fetch(url, {
+ ...init,
+ signal: AbortSignal.timeout(TIMEOUT_MS),
+ });
+ if (res.status === 404) return null;
+ if (!res.ok) throw new Error(`${url} answered ${res.status}`);
+ return res.json();
+};
+
+const getJson = async (url, init = {}) => {
+ try {
+ return await fetchOnce(url, init);
+ } catch {
+ await new Promise((r) => setTimeout(r, RETRY_DELAY_MS));
+ return fetchOnce(url, init);
+ }
+};
+
+/**
+ * The version a spec would install, as far as it can be told without semver: the
+ * `latest` tag for a bare name, the version itself, or a tag. "" for a range.
+ * @param {object} packument
+ * @param {string} version the part after `@`, possibly empty
+ * @returns {string}
+ */
+export function targetVersion(packument, version) {
+ const tags = packument["dist-tags"] ?? {};
+ if (!version) return tags.latest ?? "";
+ if (EXACT.test(version)) return version.replace(/^v/, "");
+ if (TAG.test(version)) return tags[version] ?? version;
+ return "";
+}
+
+/**
+ * @param {string} name
+ * @param {string} version
+ * @returns {Promise<{packument: object | null, target?: string, weeklyDownloads?: number, advisories?: object[]}>}
+ */
+export async function fetchFacts(name, version) {
+ const [packument, downloads] = await Promise.all([
+ getJson(`${registry()}/${name.replace("/", "%2f")}`),
+ getJson(`${downloadsApi()}/downloads/point/last-week/${name}`),
+ ]);
+ if (!packument) return { packument };
+ const target = targetVersion(packument, version);
+ const bulk =
+ target && packument.versions?.[target]
+ ? await getJson(`${registry()}/-/npm/v1/security/advisories/bulk`, {
+ method: "POST",
+ headers: { "content-type": "application/json" },
+ body: JSON.stringify({ [name]: [target] }),
+ })
+ : null;
+ return {
+ packument,
+ target,
+ weeklyDownloads: downloads?.downloads ?? 0,
+ advisories: bulk?.[name] ?? [],
+ };
+}
+
+/**
+ * Why an agent may not add this package under `policy`, or null when it may.
+ * @param {Awaited<ReturnType<typeof fetchFacts>>} facts
+ * @param {{minReleaseAgeDays: number, minWeeklyDownloads: number, blockingSeverities: string[]}} policy
+ * @param {number} [now]
+ * @returns {string | null}
+ */
+export function refusal(
+ { packument, target, weeklyDownloads = 0, advisories = [] },
+ policy,
+ now = Date.now(),
+) {
+ if (!packument) return "does not exist on the npm registry";
+ const ageDays = (now - Date.parse(packument.time?.created ?? "")) / DAY_MS;
+ if (!(ageDays >= policy.minReleaseAgeDays))
+ return `was first published less than ${policy.minReleaseAgeDays} days ago`;
+ if (weeklyDownloads < policy.minWeeklyDownloads)
+ return `has ${weeklyDownloads} downloads a week (minimum ${policy.minWeeklyDownloads})`;
+ if (!target) return null;
+ const manifest = packument.versions?.[target];
+ if (!manifest) return `has no published version or tag \`${target}\``;
+ if (manifest.deprecated)
+ return `${target} is deprecated: ${manifest.deprecated}`;
+ const script =
+ INSTALL_SCRIPTS.find((k) => manifest.scripts?.[k]) ??
+ (manifest.gypfile ? "node-gyp" : "");
+ if (script) return `${target} runs an install script (\`${script}\`)`;
+ const advisory = advisories.find((a) =>
+ policy.blockingSeverities.includes(a.severity),
+ );
+ if (advisory)
+ return `${target} has a ${advisory.severity} security advisory: ${advisory.title}`;
+ return null;
+}
diff --git a/.claude/hooks/test/config.test.mjs b/.claude/hooks/test/config.test.mjs
index a7a07a46..4119c340 100644
--- a/.claude/hooks/test/config.test.mjs
+++ b/.claude/hooks/test/config.test.mjs
@@ -18,6 +18,7 @@ import {
roleModel,
worktreeProvision,
prePrSteps,
+ dependencyPolicy,
} from "../lib/config.mjs";
const REPO_ROOT = join(
@@ -155,3 +156,35 @@ describe("config loader", () => {
expect(pipelineRoles(cfg)).toContain("test-writer");
});
});
+
+describe("dependencies", () => {
+ const withDependencies = (dependencies) =>
+ makeRepo({ validation: { steps: [] }, roles: {}, dependencies });
+
+ test("defaults to the strict policy", () => {
+ expect(dependencyPolicy(loadConfig(makeRepo(undefined)))).toEqual({
+ minReleaseAgeDays: 21,
+ minWeeklyDownloads: 1000,
+ blockingSeverities: ["high", "critical"],
+ allow: [],
+ });
+ });
+
+ test("a project overrides one threshold and keeps the others", () => {
+ const policy = dependencyPolicy(
+ loadConfig(withDependencies({ minWeeklyDownloads: 200 })),
+ );
+ expect(policy.minWeeklyDownloads).toBe(200);
+ expect(policy.minReleaseAgeDays).toBe(21);
+ });
+
+ test.each([
+ [{ minReleaseAgeDays: -1 }, /dependencies\.minReleaseAgeDays/],
+ [{ minWeeklyDownloads: 1.5 }, /dependencies\.minWeeklyDownloads/],
+ [{ blockingSeverities: ["severe"] }, /dependencies\.blockingSeverities/],
+ [{ allow: [""] }, /dependencies\.allow/],
+ [{ allow: "zod" }, /dependencies\.allow/],
+ ])("rejects %j", (dependencies, error) => {
+ expect(() => loadConfig(withDependencies(dependencies))).toThrow(error);
+ });
+});
diff --git a/.claude/hooks/test/dependency-gate.test.mjs b/.claude/hooks/test/dependency-gate.test.mjs
new file mode 100644
index 00000000..0324bdb1
--- /dev/null
+++ b/.claude/hooks/test/dependency-gate.test.mjs
@@ -0,0 +1,326 @@
+// The gate run as a real hook against a stub npm registry. Spawned asynchronously:
+// spawnSync would block the event loop the stub answers on.
+
+import { spawn } from "node:child_process";
+import { createServer } from "node:http";
+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { dirname, join } from "node:path";
+import { fileURLToPath } from "node:url";
+import { afterAll, beforeAll, describe, expect, test } from "vitest";
+
+const HERE = dirname(fileURLToPath(import.meta.url));
+const HOOK = join(HERE, "..", "dependency-gate.mjs");
+const PINNED = "--ignore-scripts --min-release-age=21";
+const UNREACHABLE = "http://127.0.0.1:1";
+
+const daysAgo = (n) => new Date(Date.now() - n * 86_400_000).toISOString();
+
+const pkg = ({
+ created = 400,
+ downloads = 500_000,
+ manifest = {},
+ advisories = [],
+} = {}) => ({
+ packument: {
+ "dist-tags": { latest: "2.0.0" },
+ time: { created: daysAgo(created), "2.0.0": daysAgo(created) },
+ versions: { "2.0.0": { version: "2.0.0", ...manifest } },
+ },
+ downloads,
+ advisories,
+});
+
+const REGISTRY = {
+ "well-known": pkg(),
+ "@scope/kit": pkg(),
+ "brand-new": pkg({ created: 3 }),
+ obscure: pkg({ downloads: 12 }),
+ abandoned: pkg({ manifest: { deprecated: "use well-known instead" } }),
+ "native-addon": pkg({
+ manifest: { scripts: { install: "node-gyp rebuild" } },
+ }),
+ "gyp-addon": pkg({ manifest: { gypfile: true } }),
+ vulnerable: pkg({
+ advisories: [{ severity: "high", title: "Prototype pollution" }],
+ }),
+ "mildly-vulnerable": pkg({
+ advisories: [{ severity: "moderate", title: "ReDoS" }],
+ }),
+ flaky: pkg(),
+};
+
+let server;
+let registryUrl;
+let tmp;
+let flakyPackumentHits = 0;
+
+beforeAll(async () => {
+ tmp = mkdtempSync(join(tmpdir(), "dependency-gate-"));
+ server = createServer((req, res) => {
+ const send = (status, body) => {
+ res.writeHead(status, { "content-type": "application/json" });
+ res.end(JSON.stringify(body));
+ };
+ const path = decodeURIComponent(req.url);
+ if (
+ req.method === "POST" &&
+ path === "/-/npm/v1/security/advisories/bulk"
+ ) {
+ let body = "";
+ req.on("data", (d) => (body += d));
+ req.on("end", () => {
+ const [name] = Object.keys(JSON.parse(body));
+ send(200, { [name]: REGISTRY[name]?.advisories ?? [] });
+ });
+ return;
+ }
+ const downloads = path.match(/^\/downloads\/point\/last-week\/(.+)$/);
+ const name = downloads ? downloads[1] : path.slice(1);
+ const entry = REGISTRY[name];
+ if (!entry) return send(404, { error: "not found" });
+ if (name === "flaky" && !downloads && flakyPackumentHits++ === 0)
+ return send(503, { error: "try again" });
+ send(200, downloads ? { downloads: entry.downloads } : entry.packument);
+ });
+ await new Promise((r) => server.listen(0, "127.0.0.1", r));
+ registryUrl = `http://127.0.0.1:${server.address().port}`;
+});
+
+afterAll(() => {
+ server.close();
+ rmSync(tmp, { recursive: true, force: true });
+});
+
+const run = (
+ command,
+ { registry = registryUrl, cwd = tmp, appDir = tmp } = {},
+) =>
+ new Promise((resolve) => {
+ const env = {
+ ...process.env,
+ npm_config_registry: registry,
+ HARNESS_NPM_DOWNLOADS_API: registry,
+ APP_DIR: appDir,
+ };
+ delete env.CLAUDE_PROJECT_DIR;
+ delete env.CLAUDE_AGENT_NAME;
+ const child = spawn("node", [HOOK], { env });
+ let stdout = "";
+ let stderr = "";
+ child.stdout.on("data", (d) => (stdout += d));
+ child.stderr.on("data", (d) => (stderr += d));
+ child.on("close", (status) => {
+ const out = stdout.trim()
+ ? JSON.parse(stdout.trim().split("\n").pop())
+ : {};
+ resolve({
+ status,
+ stderr,
+ blocked: out.decision === "block" ? out.reason : null,
+ command: out.hookSpecificOutput?.updatedInput?.command ?? null,
+ });
+ });
+ child.stdin.end(
+ JSON.stringify({
+ tool_name: "Bash",
+ session_id: "dependency-gate-test",
+ cwd,
+ tool_input: { command },
+ }),
+ );
+ });
+
+const project = (name, { dependencies = {}, bins = [] } = {}) => {
+ const dir = join(tmp, name);
+ mkdirSync(join(dir, "node_modules", ".bin"), { recursive: true });
+ writeFileSync(join(dir, "package.json"), JSON.stringify({ dependencies }));
+ for (const bin of bins)
+ writeFileSync(join(dir, "node_modules", ".bin", bin), "");
+ return dir;
+};
+
+const configured = (name, dependencies) => {
+ const dir = join(tmp, name);
+ mkdirSync(dir, { recursive: true });
+ writeFileSync(
+ join(dir, "harness.config.json"),
+ JSON.stringify({ dependencies }),
+ );
+ return dir;
+};
+
+describe("dependency-gate", () => {
+ describe("lets a vetted package through, pinned", () => {
+ test("adds the pinned flags right after the install subcommand", async () => {
+ const r = await run("npm install well-known");
+ expect(r.blocked).toBeNull();
+ expect(r.command).toBe(`npm install ${PINNED} well-known`);
+ });
+
+ test("pins every install of a compound command and leaves the rest alone", async () => {
+ const r = await run(
+ "cd /tmp && npm i -D well-known @scope/kit 2>&1 | tail -3 && npm add well-known",
+ );
+ expect(r.command).toBe(
+ `cd /tmp && npm i ${PINNED} -D well-known @scope/kit 2>&1 | tail -3 && npm add ${PINNED} well-known`,
+ );
+ });
+
+ test("pins an npx run that fetches its package", async () => {
+ const r = await run("npx -y [email protected] --help");
+ expect(r.command).toBe(`npx ${PINNED} -y [email protected] --help`);
+ });
+
+ test("a moderate advisory does not refuse the package", async () => {
+ const r = await run("npm install mildly-vulnerable");
+ expect(r.command).toBe(`npm install ${PINNED} mildly-vulnerable`);
+ });
+
+ test("a range skips the version checks but is still pinned to --ignore-scripts", async () => {
+ const r = await run("npm install native-addon@^2");
+ expect(r.command).toBe(`npm install ${PINNED} native-addon@^2`);
+ });
+ });
+
+ describe("needs no registry for what the project already has", () => {
+ test("a package declared in package.json is pinned without being vetted", async () => {
+ const dir = project("declared", { dependencies: { obscure: "^1.0.0" } });
+ const r = await run(`cd ${dir} && npm install [email protected]`, {
+ registry: UNREACHABLE,
+ });
+ expect(r.command).toBe(
+ `cd ${dir} && npm install ${PINNED} [email protected]`,
+ );
+ });
+
+ test("an npx command that resolves to a local bin is left untouched", async () => {
+ const dir = project("local-bin", { bins: ["prettier"] });
+ const r = await run(`cd ${dir} && npx prettier --check .`, {
+ registry: UNREACHABLE,
+ });
+ expect(r).toMatchObject({ blocked: null, command: null });
+ });
+
+ test.each([
+ "git status",
+ "npm install",
+ "npm ci",
+ "npm run build",
+ 'echo "npm install x"',
+ ])("`%s` is left untouched", async (command) => {
+ const r = await run(command, { registry: UNREACHABLE });
+ expect(r).toMatchObject({ status: 0, blocked: null, command: null });
+ });
+ });
+
+ describe("refuses what fails the vetting", () => {
+ test.each([
+ ["hallucinated-name", "does not exist on the npm registry"],
+ ["brand-new", "first published less than 21 days ago"],
+ ["obscure", "12 downloads a week"],
+ ["abandoned", "deprecated: use well-known instead"],
+ ["native-addon", "runs an install script (`install`)"],
+ ["gyp-addon", "runs an install script (`node-gyp`)"],
+ ["vulnerable", "high security advisory: Prototype pollution"],
+ ["[email protected]", "no published version or tag `9.9.9`"],
+ ])("`npm install %s`", async (spec, why) => {
+ const r = await run(`npm install ${spec}`);
+ expect(r.blocked).toContain(why);
+ expect(r.blocked).toContain("build the feature without the package");
+ });
+
+ test("one refused package refuses the whole command", async () => {
+ const r = await run("npm install well-known brand-new");
+ expect(r.blocked).toContain("`brand-new`");
+ expect(r.blocked).not.toContain("`well-known`");
+ });
+
+ test("a transient registry error is retried once", async () => {
+ const r = await run("npm install flaky");
+ expect(r.command).toBe(`npm install ${PINNED} flaky`);
+ });
+
+ test("an unreachable registry refuses rather than lets the install run unvetted", async () => {
+ const r = await run("npm install well-known", { registry: UNREACHABLE });
+ expect(r.blocked).toContain("could not reach the npm registry");
+ });
+ });
+
+ describe("refuses what would bypass the vetting", () => {
+ test.each([
+ "pnpm add zod",
+ "yarn add zod",
+ "bun add zod",
+ "bunx cowsay",
+ "pnpm dlx create-vite",
+ ])("`%s`", async (command) => {
+ const r = await run(command, { registry: UNREACHABLE });
+ expect(r.blocked).toContain("installs are not vetted, only npm's are");
+ });
+
+ test.each([
+ "github:user/repo",
+ "./local-pkg",
+ "https://example.com/pkg.tgz",
+ "alias@npm:zod",
+ ])("the non-registry spec `%s`", async (spec) => {
+ const r = await run(`npm install ${spec}`, { registry: UNREACHABLE });
+ expect(r.blocked).toContain("is not a plain registry package");
+ });
+
+ test.each([
+ "--min-release-age=0",
+ "--registry https://evil.example",
+ "--no-ignore-scripts",
+ ])("the gate-owned flag `%s`", async (flag) => {
+ const r = await run(`npm install well-known ${flag}`, {
+ registry: UNREACHABLE,
+ });
+ expect(r.blocked).toContain("would bypass the vetting");
+ });
+ });
+
+ describe("a project tunes the policy in harness.config.json", () => {
+ test("a lower download floor lets a smaller package through", async () => {
+ const appDir = configured("low-floor", { minWeeklyDownloads: 10 });
+ const r = await run("npm install obscure", { appDir });
+ expect(r.command).toBe(`npm install ${PINNED} obscure`);
+ });
+
+ test("a shorter release age lets a newer package through and pins npm to it", async () => {
+ const appDir = configured("short-age", { minReleaseAgeDays: 2 });
+ const r = await run("npm install brand-new", { appDir });
+ expect(r.command).toBe(
+ "npm install --ignore-scripts --min-release-age=2 brand-new",
+ );
+ });
+
+ test("only the listed severities refuse a package", async () => {
+ const appDir = configured("critical-only", {
+ blockingSeverities: ["critical"],
+ });
+ const r = await run("npm install vulnerable", { appDir });
+ expect(r.command).toBe(`npm install ${PINNED} vulnerable`);
+ });
+
+ test("an approved name or scope skips the vetting, still pinned", async () => {
+ const appDir = configured("approved", {
+ allow: ["native-addon", "@acme/*"],
+ });
+ const r = await run("npm install native-addon @acme/private-kit", {
+ appDir,
+ registry: UNREACHABLE,
+ });
+ expect(r.command).toBe(
+ `npm install ${PINNED} native-addon @acme/private-kit`,
+ );
+ });
+
+ test("an invalid block falls back to the defaults, it never loosens them", async () => {
+ const appDir = configured("invalid", { minWeeklyDownloads: "lots" });
+ const r = await run("npm install obscure", { appDir });
+ expect(r.blocked).toContain("12 downloads a week (minimum 1000)");
+ });
+ });
+});
diff --git a/.claude/hooks/test/install-commands.test.mjs b/.claude/hooks/test/install-commands.test.mjs
new file mode 100644
index 00000000..8a020f88
--- /dev/null
+++ b/.claude/hooks/test/install-commands.test.mjs
@@ -0,0 +1,146 @@
+import { describe, expect, test } from "vitest";
+import { findInstalls, parseSpec } from "../lib/install-commands.mjs";
+
+const specsOf = (command) => findInstalls(command).map((f) => f.specs);
+
+describe("findInstalls", () => {
+ test.each([
+ "git status",
+ "npm install",
+ "npm ci",
+ "npm install --legacy-peer-deps",
+ "npm run build",
+ "npm uninstall lodash",
+ "echo 'npm install left-pad'",
+ 'git commit -m "npm install left-pad"',
+ "npx -c 'eslint .'",
+ "pnpm install --frozen-lockfile",
+ "yarn",
+ "bun install",
+ ])("finds nothing to vet in `%s`", (command) => {
+ expect(findInstalls(command)).toEqual([]);
+ });
+
+ test.each([
+ ["npm install date-fns", [["date-fns"]]],
+ ["npm i -D @types/node vitest", [["@types/node", "vitest"]]],
+ ["npm add zod", [["zod"]]],
+ ["npm isntall zod", [["zod"]]],
+ ["npm -g install serve", [["serve"]]],
+ ["npm install --prefix sub left-pad", [["left-pad"]]],
+ ['npm install "lodash@^4"', [["lodash@^4"]]],
+ ["npm install [email protected] 2>&1 | tail -5", [["[email protected]"]]],
+ ["npm install zod > /tmp/out.log", [["zod"]]],
+ ["npm install a && npm install b", [["a"], ["b"]]],
+ ])("reads the packages of `%s`", (command, expected) => {
+ expect(specsOf(command)).toEqual(expected);
+ });
+
+ test("puts the flags right after the install subcommand", () => {
+ const command = "FOO=1 npm i -D zod";
+ const [found] = findInstalls(command);
+ expect(command.slice(0, found.insertAt)).toBe("FOO=1 npm i");
+ });
+
+ test("remembers the directory a preceding cd moved into", () => {
+ const [found] = findInstalls("cd /tmp/wt/TASK-001 && npm install zod");
+ expect(found.cwd).toBe("/tmp/wt/TASK-001");
+ });
+
+ test.each([
+ ["npm install zod --registry https://evil.example", ["--registry"]],
+ [
+ "npm install zod --registry=https://evil.example",
+ ["--registry=https://evil.example"],
+ ],
+ ["npm install zod --min-release-age=0", ["--min-release-age=0"]],
+ ["npm install zod --before 2030-01-01", ["--before"]],
+ ["npm install zod --no-ignore-scripts", ["--no-ignore-scripts"]],
+ ["npm install zod --ignore-scripts=false", ["--ignore-scripts=false"]],
+ [
+ "npx --registry=https://evil.example zod",
+ ["--registry=https://evil.example"],
+ ],
+ ])("flags `%s` as overriding a gate-owned setting", (command, flags) => {
+ const [found] = findInstalls(command);
+ expect(found.gateFlags).toEqual(flags);
+ expect(found.specs).toEqual(["zod"]);
+ });
+
+ describe("npx and npm exec", () => {
+ test("a bare command name may be a local bin", () => {
+ const [found] = findInstalls("npx prettier --check .");
+ expect(found).toMatchObject({
+ kind: "exec",
+ specs: ["prettier"],
+ binOnly: true,
+ });
+ });
+
+ test("arguments after the command are not packages", () => {
+ expect(
+ specsOf("npx -y create-vite@latest my-app --template react"),
+ ).toEqual([["create-vite@latest"]]);
+ });
+
+ test("--package names what is fetched, and is never a local bin", () => {
+ const [found] = findInstalls("npx -p typescript --package=ts-node tsc");
+ expect(found).toMatchObject({
+ specs: ["typescript", "ts-node"],
+ binOnly: false,
+ });
+ });
+
+ test("npm exec reads the command after --", () => {
+ expect(specsOf("npm exec --yes -- cowsay hi")).toEqual([["cowsay"]]);
+ expect(specsOf("npm x cowsay")).toEqual([["cowsay"]]);
+ });
+ });
+
+ test.each([
+ "pnpm add zod",
+ "pnpm i zod",
+ "pnpm dlx create-vite",
+ "pnpx create-vite",
+ "yarn add zod",
+ "yarn global add serve",
+ "yarn dlx create-vite",
+ "bun add zod",
+ "bunx cowsay",
+ "bun x cowsay",
+ ])("marks `%s` as another manager's install", (command) => {
+ expect(findInstalls(command)).toMatchObject([{ kind: "other" }]);
+ });
+});
+
+describe("parseSpec", () => {
+ test.each([
+ ["zod", { name: "zod", version: "" }],
+ ["[email protected]", { name: "zod", version: "3.23.8" }],
+ ["react@next", { name: "react", version: "next" }],
+ ["react@^18", { name: "react", version: "^18" }],
+ ["@types/node", { name: "@types/node", version: "" }],
+ [
+ "@tanstack/react-query@5",
+ { name: "@tanstack/react-query", version: "5" },
+ ],
+ ["JSONStream", { name: "JSONStream", version: "" }],
+ ])("splits the registry spec `%s`", (spec, expected) => {
+ expect(parseSpec(spec)).toEqual(expected);
+ });
+
+ test.each([
+ "github:user/repo",
+ "user/repo",
+ "git+https://github.com/user/repo.git",
+ "https://example.com/pkg.tgz",
+ "./local-pkg",
+ "../sibling",
+ "file:../sibling",
+ "pkg.tgz",
+ "alias@npm:zod",
+ "$PKG",
+ ])("refuses `%s` as not a plain registry package", (spec) => {
+ expect(parseSpec(spec)).toBeNull();
+ });
+});
diff --git a/.claude/rules/dependency-safety.md b/.claude/rules/dependency-safety.md
index 51483eef..c79c6329 100644
--- a/.claude/rules/dependency-safety.md
+++ b/.claude/rules/dependency-safety.md
@@ -1,18 +1,28 @@
# Dependency safety
-Adding a new package is a supply-chain decision, so agents never do it silently.
+Adding a package is a supply-chain decision, so no agent adds one unvetted.
## Rule
-- New-package installs are denied by permissions (`settings.json` -> `permissions.deny`:
- `Bash(npm install *)`, `Bash(npm i *)`, `Bash(pnpm add *)`, `Bash(yarn add *)`). A
- deny is ~100% respected; a CLAUDE.md rule or a post-action warning is not.
-- Bare `npm install` / `pnpm install` / `yarn install` (no package argument, restoring
- the lockfile) stays allowed: the literal space in the deny glob requires an argument,
- so an argument-less install is not matched.
-- To add a package, the human validates THAT specific package first: minimum 21 days
- since publication, healthy download/maintainer count, no open advisory
- (`npm audit`, Snyk).
+- `dependency-gate` (PreToolUse Bash) vets every package an `npm install <pkg>` or
+ `npx <pkg>` would fetch: on the npm registry, first published 21+ days ago, 1000+ weekly
+ downloads, not deprecated, no install script, no high or critical advisory (defaults).
+- A vetted command runs with `--ignore-scripts --min-release-age=<days>` added, so npm
+ itself refuses any version younger than the release-age floor, transitive ones included.
+- A refusal is not a dead end: build the feature without the package, or use an established
+ alternative, before asking the user.
+- The thresholds are `dependencies.*` in `harness.config.json`. `dependencies.allow` lists
+ the names (or `@scope/*`) a developer approved; they skip the vetting.
+- Not vetted: a package already declared in `package.json` or approved, an npx command that
+ resolves to a local bin, and a bare `npm install` / `npm ci` restoring the lockfile.
+- Refused outright, because they would bypass the vetting: pnpm / yarn / bun installs and
+ runners, non-registry specs (git, tarball, path, alias), and `--registry`, `--before`,
+ `--min-release-age`, `--no-ignore-scripts`. A developer adds those.
+- An unreachable registry means refused, not unvetted.
+- A dependency written straight into `package.json`, then installed by a bare
+ `npm install`, is not vetted: it only shows up in the diff.
+- The project must not keep `Bash(npm install *)` in `permissions.deny`: a deny wins over
+ the hook and the gate never runs.
## Third-party skills and MCP servers
diff --git a/.claude/settings.json b/.claude/settings.json
index 7de73b81..e7659c42 100644
--- a/.claude/settings.json
+++ b/.claude/settings.json
@@ -21,10 +21,6 @@
"permissions": {
"allow": [],
"deny": [
- "Bash(npm install *)",
- "Bash(npm i *)",
- "Bash(pnpm add *)",
- "Bash(yarn add *)",
"mcp__github__merge_pull_request",
"mcp__github__create_or_update_file",
"mcp__github__push_files",
@@ -93,6 +89,11 @@
"type": "command",
"command": "$CLAUDE_PROJECT_DIR/.claude/hooks/block-docker-containers.mjs"
},
+ {
+ "type": "command",
+ "command": "$CLAUDE_PROJECT_DIR/.claude/hooks/dependency-gate.mjs",
+ "timeout": 60
+ },
{
"type": "command",
"command": "$CLAUDE_PROJECT_DIR/.claude/hooks/circuit-breaker.mjs"