diff --git a/CHANGELOG.md b/CHANGELOG.md index f90bfaff..b64211f7 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,11 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/). ## [Unreleased] +## [1.17.0] - 2026-06-23 + +### Added +- **Install-time supply-chain triage (`kit supply-chain`).** Four deterministic, local-first checks over `package.json` + `package-lock.json` (no network, no node_modules walk): **install-scripts** (deps that run pre/post/install — the malware-execution vector, from the lockfile's `hasInstallScript`), **lockfile-drift** (declared deps missing from the lockfile + packages resolved from a non-registry http/git source), **dep-confusion** (a dep under a declared `[supply_chain] internal_scopes` entry that the lockfile resolves from the PUBLIC registry), and **slopsquat** (a dep name ≤1 Damerau-Levenshtein edit — incl. transposition, e.g. `lodahs`→`lodash` — from a bundled high-traffic-package corpus). Pure check functions are fixture-tested; the typosquat corpus is local and curated. (#49) + ## [1.16.0] - 2026-06-23 ### Added diff --git a/package-lock.json b/package-lock.json index 96971a33..e06541b0 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "sandstream-kit", - "version": "1.16.0", + "version": "1.17.0", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "sandstream-kit", - "version": "1.16.0", + "version": "1.17.0", "license": "MIT", "workspaces": [ "packages/*" diff --git a/package.json b/package.json index 4af52bf7..66634e97 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "sandstream-kit", - "version": "1.16.0", + "version": "1.17.0", "description": "developer kit. zero LLM, local-first, multi-vault. one command from git clone to working dev environment.", "license": "MIT", "funding": "https://buymeacoffee.com/sandstream", diff --git a/src/cli.ts b/src/cli.ts index 87a5a71c..9a98435c 100644 --- a/src/cli.ts +++ b/src/cli.ts @@ -4167,6 +4167,32 @@ async function cmdIngest(): Promise { return true; } +async function cmdSupplyChain(): Promise { + const jsonMode = hasFlag(process.argv, "--json"); + const config = await loadConfig(resolveConfigPath()); + const scopes = config.supply_chain?.internal_scopes ?? []; + const { runSupplyChain } = await import("./supply-chain.js"); + const results = runSupplyChain(process.cwd(), scopes); + const fails = results.filter((r) => r.status === "fail").length; + + if (jsonMode) { + console.log(JSON.stringify({ ok: fails === 0, results }, null, 2)); + return fails === 0; + } + + console.log(`${c.bold}kit supply-chain${c.reset}`); + for (const r of results) { + const mark = + r.status === "fail" ? `${c.red}✗${c.reset}` : + r.status === "warn" ? `${c.yellow}!${c.reset}` : + r.status === "skip" ? `${c.dim}−${c.reset}` : `${c.green}✓${c.reset}`; + console.log(` ${mark} ${r.name} ${c.dim}${r.detail}${c.reset}`); + if (r.suggestion) console.log(` ${c.dim}${r.suggestion}${c.reset}`); + } + if (fails > 0) console.log(`${c.red}${fails} fail${c.reset}`); + return fails === 0; +} + async function cmdWhoami(): Promise { const jsonMode = hasFlag(process.argv, "--json"); @@ -4906,6 +4932,7 @@ async function main(): Promise { check: cmdCheck, health: cmdHealth, ingest: cmdIngest, + "supply-chain": cmdSupplyChain, init: cmdInit, upgrade: cmdUpgrade, install: cmdInstall, diff --git a/src/config.ts b/src/config.ts index 7323f22e..368d40be 100644 --- a/src/config.ts +++ b/src/config.ts @@ -296,6 +296,8 @@ export interface kitConfig { hooks?: HooksConfig; /** Per-project CLI context lock (account+project per tool). */ context?: ContextConfig; + /** Install-time supply-chain triage settings (`kit supply-chain`). */ + supply_chain?: { internal_scopes?: string[] }; web?: { search?: WebSearchConfig; }; @@ -538,6 +540,10 @@ const kitConfigSchema = z }) .passthrough() .optional(), + supply_chain: z + .object({ internal_scopes: z.array(z.string()).optional() }) + .passthrough() + .optional(), web: WebConfigSchema, setup: z .object({ diff --git a/src/data/top-npm.ts b/src/data/top-npm.ts new file mode 100644 index 00000000..29c26bf7 --- /dev/null +++ b/src/data/top-npm.ts @@ -0,0 +1,24 @@ +/** + * A curated set of high-traffic npm package names, used as the typosquat/slopsquat + * reference corpus: a dependency that is edit-distance ≤1 from one of these but not + * an exact match is a likely look-alike. Kept deliberately small and local (no + * network) — it covers the names attackers most often imitate, not all of npm. + */ +export const TOP_NPM: readonly string[] = [ + "react", "react-dom", "lodash", "express", "axios", "chalk", "commander", + "debug", "moment", "request", "async", "bluebird", "underscore", "yargs", + "uuid", "glob", "minimist", "semver", "rimraf", "mkdirp", "dotenv", "cors", + "body-parser", "webpack", "babel-core", "typescript", "eslint", "prettier", + "jest", "mocha", "chai", "vue", "angular", "next", "vite", "rollup", "ws", + "node-fetch", "cross-env", "nodemon", "ts-node", "tslib", "zod", "prisma", + "redux", "react-redux", "styled-components", "tailwindcss", "postcss", + "classnames", "immer", "rxjs", "graphql", "apollo-server", "mongoose", + "sequelize", "pg", "mysql2", "redis", "ioredis", "socket.io", "passport", + "jsonwebtoken", "bcrypt", "bcryptjs", "helmet", "morgan", "winston", "pino", + "nanoid", "date-fns", "dayjs", "ramda", "fastify", "koa", "ejs", "handlebars", + "sharp", "puppeteer", "playwright", "cheerio", "form-data", "qs", "ini", + "colors", "inquirer", "ora", "execa", "fs-extra", "globby", "chokidar", + "esbuild", "terser", "core-js", "regenerator-runtime", "left-pad", +]; + +export const TOP_NPM_SET: ReadonlySet = new Set(TOP_NPM); diff --git a/src/supply-chain.test.ts b/src/supply-chain.test.ts new file mode 100644 index 00000000..18834020 --- /dev/null +++ b/src/supply-chain.test.ts @@ -0,0 +1,83 @@ +import { describe, it } from "node:test"; +import assert from "node:assert/strict"; +import { + findInstallScripts, + findLockDrift, + findNonRegistryResolved, + findDepConfusion, + editDistance, + findSlopsquat, + parseLockPkgs, + type LockPkg, +} from "./supply-chain.js"; + +const lockPkgs: LockPkg[] = [ + { path: "node_modules/lodash", name: "lodash", version: "4.17.21", resolved: "https://registry.npmjs.org/lodash/-/lodash-4.17.21.tgz" }, + { path: "node_modules/esbuild", name: "esbuild", version: "0.20.0", resolved: "https://registry.npmjs.org/esbuild/-/esbuild-0.20.0.tgz", hasInstallScript: true }, + { path: "node_modules/sketchy", name: "sketchy", version: "1.0.0", resolved: "https://evil.example/sketchy.tgz" }, + { path: "node_modules/@acme/core", name: "@acme/core", version: "2.0.0", resolved: "https://registry.npmjs.org/@acme/core/-/core-2.0.0.tgz" }, +]; + +describe("findInstallScripts", () => { + it("flags only packages with hasInstallScript", () => { + assert.deepEqual(findInstallScripts(lockPkgs), ["esbuild@0.20.0"]); + }); +}); + +describe("findLockDrift", () => { + it("flags declared deps absent from the lockfile", () => { + const lockNames = new Set(lockPkgs.map((p) => p.name)); + assert.deepEqual(findLockDrift(["lodash", "ghost-dep"], lockNames), ["ghost-dep"]); + }); +}); + +describe("findNonRegistryResolved", () => { + it("flags http/git tarball sources, not registry ones", () => { + const bad = findNonRegistryResolved(lockPkgs); + assert.equal(bad.length, 1); + assert.equal(bad[0].name, "sketchy"); + }); +}); + +describe("findDepConfusion", () => { + const resolved = new Map(lockPkgs.map((p) => [p.name, p.resolved] as const)); + it("flags an internal-scoped dep resolved from the public registry", () => { + assert.deepEqual(findDepConfusion(["@acme/core"], resolved, ["@acme"]), ["@acme/core"]); + }); + it("is empty when no internal scopes are declared", () => { + assert.deepEqual(findDepConfusion(["@acme/core"], resolved, []), []); + }); + it("does not flag a scope substring match (@acme vs @acme-tools)", () => { + const r = new Map([["@acme-tools/x", "https://registry.npmjs.org/x"] as const]); + assert.deepEqual(findDepConfusion(["@acme-tools/x"], r, ["@acme"]), []); + }); +}); + +describe("editDistance (bounded Damerau)", () => { + it("treats a transposition as a single edit, plus subs/inserts/deletes, and caps", () => { + assert.equal(editDistance("lodash", "lodash"), 0); + assert.equal(editDistance("lodash", "lodahs"), 1); // adjacent transposition + assert.equal(editDistance("react", "preact"), 1); // insertion + assert.equal(editDistance("abc", "xyzzy", 2), 3); // exceeds cap + }); +}); + +describe("findSlopsquat", () => { + it("flags a 1-edit look-alike of a popular package", () => { + const hits = findSlopsquat(["lodahs", "expres"]); // lodash, express look-alikes + const names = hits.map((h) => h.name); + assert.ok(names.includes("lodahs")); + assert.ok(names.includes("expres")); + }); + it("does not flag exact popular packages or distant names", () => { + assert.deepEqual(findSlopsquat(["lodash", "my-unique-internal-pkg"]), []); + }); +}); + +describe("parseLockPkgs", () => { + it("skips the root entry and flattens packages", () => { + const pkgs = parseLockPkgs({ packages: { "": { name: "root" }, "node_modules/x": { version: "1.0.0", resolved: "r" } } }); + assert.equal(pkgs.length, 1); + assert.equal(pkgs[0].name, "x"); + }); +}); diff --git a/src/supply-chain.ts b/src/supply-chain.ts new file mode 100644 index 00000000..6a4078c8 --- /dev/null +++ b/src/supply-chain.ts @@ -0,0 +1,207 @@ +/** + * Install-time supply-chain triage — deterministic, local-first checks over a + * project's `package.json` + `package-lock.json` (no network, no node_modules walk): + * + * - install-scripts : deps that run pre/post/install scripts (the classic malware + * execution vector) — surfaced so they can be reviewed / run + * with `--ignore-scripts`. + * - lockfile-drift : a declared dependency missing from the lockfile, or a package + * resolved from a NON-registry source (http/git/github tarball). + * - dep-confusion : a dependency under one of your declared internal scopes that + * the lockfile resolves from the PUBLIC registry (a name your + * private package shares with a public one). + * - slopsquat : a dependency edit-distance ≤1 from a high-traffic package + * name but not an exact match (a likely look-alike). + * + * The check functions are pure (parsed data in → findings out) and fixture-tested; + * `runSupplyChain` is the thin file-reading wrapper. + */ +import { readFileSync } from "node:fs"; +import { resolve } from "node:path"; +import type { SecurityCheckResult } from "./check-security.js"; +import { TOP_NPM_SET } from "./data/top-npm.js"; + +export interface LockPkg { + /** lockfile key, e.g. "node_modules/lodash" */ + path: string; + name: string; + version?: string; + resolved?: string; + hasInstallScript?: boolean; +} + +const REGISTRY = /registry\.npmjs\.org\//; + +/** Packages whose install runs a script (npm lockfile v3 records this). */ +export function findInstallScripts(lockPkgs: LockPkg[]): string[] { + return lockPkgs + .filter((p) => p.hasInstallScript && p.name) + .map((p) => (p.version ? `${p.name}@${p.version}` : p.name)); +} + +/** Declared deps that have no entry in the lockfile (drift / un-pinned). */ +export function findLockDrift(declaredDeps: string[], lockNames: Set): string[] { + return declaredDeps.filter((d) => !lockNames.has(d)); +} + +/** Packages resolved from a non-registry source (http/git tarball) — supply-chain risk. */ +export function findNonRegistryResolved(lockPkgs: LockPkg[]): { name: string; resolved: string }[] { + return lockPkgs + .filter((p) => p.resolved && !REGISTRY.test(p.resolved) && /^(https?:|git\+|github:)/.test(p.resolved)) + .map((p) => ({ name: p.name, resolved: p.resolved! })); +} + +/** Internal-scoped deps the lockfile resolves from the public registry (confusion risk). */ +export function findDepConfusion( + declaredDeps: string[], + resolvedByName: Map, + internalScopes: string[], +): string[] { + if (internalScopes.length === 0) return []; + return declaredDeps.filter( + (d) => internalScopes.some((s) => d === s || d.startsWith(s.endsWith("/") ? s : `${s}/`)) && + REGISTRY.test(resolvedByName.get(d) ?? ""), + ); +} + +/** + * Bounded Damerau-Levenshtein (optimal string alignment) — counts substitutions, + * insertions, deletions, AND adjacent transpositions as single edits, since + * transpositions (`lodahs` for `lodash`) are a classic typosquat. Stops early + * once the distance is known to exceed `cap`. + */ +export function editDistance(a: string, b: string, cap = 2): number { + if (a === b) return 0; + if (Math.abs(a.length - b.length) > cap) return cap + 1; + const m = a.length; + const n = b.length; + const d: number[][] = Array.from({ length: m + 1 }, () => new Array(n + 1).fill(0)); + for (let i = 0; i <= m; i++) d[i][0] = i; + for (let j = 0; j <= n; j++) d[0][j] = j; + for (let i = 1; i <= m; i++) { + let rowMin = Infinity; + for (let j = 1; j <= n; j++) { + const cost = a[i - 1] === b[j - 1] ? 0 : 1; + let v = Math.min(d[i - 1][j] + 1, d[i][j - 1] + 1, d[i - 1][j - 1] + cost); + if (i > 1 && j > 1 && a[i - 1] === b[j - 2] && a[i - 2] === b[j - 1]) { + v = Math.min(v, d[i - 2][j - 2] + 1); // transposition + } + d[i][j] = v; + if (v < rowMin) rowMin = v; + } + if (rowMin > cap) return cap + 1; + } + return d[m][n]; +} + +/** Deps that look like a near-miss (≤1 edit, incl. transposition) of a popular package. */ +export function findSlopsquat(declaredDeps: string[], corpus: ReadonlySet = TOP_NPM_SET): { name: string; near: string }[] { + const out: { name: string; near: string }[] = []; + for (const d of declaredDeps) { + if (corpus.has(d)) continue; // exact popular package = fine + for (const c of corpus) { + if (Math.abs(c.length - d.length) > 1) continue; + if (editDistance(d, c, 1) === 1) { + out.push({ name: d, near: c }); + break; + } + } + } + return out; +} + +interface PackageJson { + dependencies?: Record; + devDependencies?: Record; +} +interface LockfileV3 { + packages?: Record; +} + +/** Parse an npm lockfile (v3 `packages` map) into a flat LockPkg list. */ +export function parseLockPkgs(lock: LockfileV3): LockPkg[] { + const out: LockPkg[] = []; + for (const [path, meta] of Object.entries(lock.packages ?? {})) { + if (path === "") continue; // the root project entry + const name = meta.name ?? path.split("node_modules/").pop() ?? path; + out.push({ path, name, version: meta.version, resolved: meta.resolved, hasInstallScript: meta.hasInstallScript }); + } + return out; +} + +function result( + name: string, + status: SecurityCheckResult["status"], + detail: string, + severity?: SecurityCheckResult["severity"], + suggestion?: string, +): SecurityCheckResult { + return { category: "supply-chain", name, status, detail, severity, suggestion }; +} + +/** Run all four checks against the project at `cwd`. Read-only; fail-open per file. */ +export function runSupplyChain(cwd: string, internalScopes: string[] = []): SecurityCheckResult[] { + let pkg: PackageJson; + let lock: LockfileV3; + try { + pkg = JSON.parse(readFileSync(resolve(cwd, "package.json"), "utf8")) as PackageJson; + } catch { + return [result("supply-chain", "skip", "no package.json found")]; + } + try { + lock = JSON.parse(readFileSync(resolve(cwd, "package-lock.json"), "utf8")) as LockfileV3; + } catch { + return [result("lockfile", "warn", "no package-lock.json — install-time checks need a committed lockfile", "medium")]; + } + + const declared = [...Object.keys(pkg.dependencies ?? {}), ...Object.keys(pkg.devDependencies ?? {})]; + const lockPkgs = parseLockPkgs(lock); + const lockNames = new Set(lockPkgs.map((p) => p.name)); + const resolvedByName = new Map(lockPkgs.map((p) => [p.name, p.resolved] as const)); + + const out: SecurityCheckResult[] = []; + + const scripts = findInstallScripts(lockPkgs); + out.push( + scripts.length === 0 + ? result("install-scripts", "pass", "no dependencies run install scripts") + : result( + "install-scripts", + "warn", + `${scripts.length} dep(s) run install scripts: ${scripts.slice(0, 8).join(", ")}${scripts.length > 8 ? "…" : ""}`, + "medium", + "review them; install with `npm ci --ignore-scripts` where possible", + ), + ); + + const drift = findLockDrift(declared, lockNames); + const nonReg = findNonRegistryResolved(lockPkgs); + if (drift.length === 0 && nonReg.length === 0) { + out.push(result("lockfile-drift", "pass", "lockfile covers all declared deps; all resolved from the registry")); + } else { + if (drift.length > 0) { + out.push(result("lockfile-drift", "warn", `${drift.length} declared dep(s) missing from the lockfile: ${drift.slice(0, 8).join(", ")}`, "medium", "run `npm install` and commit the lockfile")); + } + if (nonReg.length > 0) { + out.push(result("lockfile-source", "warn", `${nonReg.length} package(s) resolved from a non-registry source (${nonReg.slice(0, 3).map((n) => n.name).join(", ")})`, "high", "verify these http/git tarball sources are trusted")); + } + } + + const confusion = findDepConfusion(declared, resolvedByName, internalScopes); + if (internalScopes.length === 0) { + out.push(result("dep-confusion", "skip", "no internal scopes declared ([supply_chain] internal_scopes)")); + } else if (confusion.length === 0) { + out.push(result("dep-confusion", "pass", "no internal-scoped dep resolves from the public registry")); + } else { + out.push(result("dep-confusion", "fail", `${confusion.length} internal-scoped dep(s) resolved from the PUBLIC registry: ${confusion.join(", ")}`, "high", "a public package shares your internal name — pin to your private registry")); + } + + const slop = findSlopsquat(declared); + out.push( + slop.length === 0 + ? result("slopsquat", "pass", "no dependency name looks like a popular-package look-alike") + : result("slopsquat", "warn", `${slop.length} possible look-alike(s): ${slop.slice(0, 5).map((s) => `${s.name}≈${s.near}`).join(", ")}`, "high", "confirm these are the intended packages, not typosquats"), + ); + + return out; +}