diff --git a/CHANGELOG.md b/CHANGELOG.md index 2c4e667f..370c293e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,11 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/). ## [Unreleased] +## [1.20.0] - 2026-06-23 + +### Added +- **Scanner-runner registry (`kit scan`) — runs external scanners and merges them into one local verdict.** kit's consolidation play: a data-driven registry (Snyk, Trivy, Grype, Semgrep, OSV-scanner) runs each applicable+installed scanner (resolved mise-first; cleanly skipped when not installed / its token is missing / not applicable), pipes the SARIF/OSV output through the #48 ingest adapter, and **merges + dedups** the results — the same CVE/GHSA reported by multiple scanners collapses to one row with max severity and the union of which scanners flagged it. Local-first, zero-server, deterministic. Pure registry/merge/dedup fixture-tested; orchestration is dependency-injected. Complements `kit check`'s native scanners (socket/semgrep/trivy/osv/trufflehog/bumblebee). (#62) + ## [1.19.0] - 2026-06-23 ### Added diff --git a/package-lock.json b/package-lock.json index 9a5df019..c4e754e9 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "sandstream-kit", - "version": "1.19.0", + "version": "1.20.0", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "sandstream-kit", - "version": "1.19.0", + "version": "1.20.0", "license": "MIT", "workspaces": [ "packages/*" diff --git a/package.json b/package.json index 50e58b32..148272f7 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "sandstream-kit", - "version": "1.19.0", + "version": "1.20.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 1714a9e5..f5fac4f0 100644 --- a/src/cli.ts +++ b/src/cli.ts @@ -4280,6 +4280,50 @@ async function cmdSentinel(): Promise { return true; } +async function cmdScan(): Promise { + const jsonMode = hasFlag(process.argv, "--json"); + const { runScanners } = await import("./scanners.js"); + const { resolveToolBin } = await import("./utils/resolveTool.js"); + const { execFileNoThrow } = await import("./utils/execFileNoThrow.js"); + const cwd = process.cwd(); + + const { merged, runs } = await runScanners({ + resolve: (bin) => resolveToolBin(bin), + run: async (bin, args) => { + const r = await execFileNoThrow(bin, args, { timeout: 180_000 }); + return { ok: r.ok, stdout: r.stdout }; + }, + hasEnv: (name) => Boolean(process.env[name]), + detect: (markers) => markers.some((m) => existsSync(resolve(cwd, m))), + }); + + const bad = merged.filter((m) => m.severity === "critical" || m.severity === "high").length; + + if (jsonMode) { + console.log(JSON.stringify({ runs, findings: merged }, null, 2)); + return bad === 0; + } + + console.log(`${c.bold}kit scan${c.reset} ${c.dim}external scanners → one merged verdict${c.reset}`); + for (const r of runs) { + const mark = r.status === "ran" ? `${c.green}✓${c.reset}` : r.status === "error" ? `${c.red}✗${c.reset}` : `${c.dim}−${c.reset}`; + const note = r.status === "ran" ? `${r.findings} finding(s)` : r.status; + console.log(` ${mark} ${r.id} ${c.dim}${note}${c.reset}`); + } + console.log(""); + if (merged.length === 0) { + console.log(` ${c.green}no findings from the scanners that ran${c.reset}`); + } else { + for (const m of merged) { + const sev = m.severity ?? "low"; + const color = sev === "critical" || sev === "high" ? c.red : sev === "medium" ? c.yellow : c.dim; + console.log(` ${color}${sev.toUpperCase().padEnd(8)}${c.reset} ${m.name} ${c.dim}[${m.scanners.join("+")}]${c.reset}`); + } + } + if (bad > 0) console.log(`${c.red}${bad} high/critical${c.reset}`); + return bad === 0; +} + async function cmdWhoami(): Promise { const jsonMode = hasFlag(process.argv, "--json"); @@ -5022,6 +5066,7 @@ async function main(): Promise { "supply-chain": cmdSupplyChain, "agent-audit": cmdAgentAudit, sentinel: cmdSentinel, + scan: cmdScan, init: cmdInit, upgrade: cmdUpgrade, install: cmdInstall, diff --git a/src/scanners.test.ts b/src/scanners.test.ts new file mode 100644 index 00000000..9750b923 --- /dev/null +++ b/src/scanners.test.ts @@ -0,0 +1,62 @@ +import { describe, it } from "node:test"; +import assert from "node:assert/strict"; +import { dedupKey, mergeFindings, runScanners, type ScanDeps, type ScannerDef } from "./scanners.js"; +import type { SecurityCheckResult } from "./check-security.js"; + +const f = (name: string, severity: SecurityCheckResult["severity"], detail = ""): SecurityCheckResult => ({ + category: "dependency", name, status: "fail", detail, severity, +}); + +describe("dedupKey", () => { + it("uses the CVE/GHSA id when present, else the name", () => { + assert.equal(dedupKey(f("lodash@1: CVE-2021-23337", "high")), "CVE-2021-23337"); + assert.equal(dedupKey(f("pkg: GHSA-jf85-cpcp-j695", "high")), "GHSA-JF85-CPCP-J695"); + assert.equal(dedupKey(f("some-rule finding", "low")), "some-rule finding"); + }); +}); + +describe("mergeFindings", () => { + it("collapses the same CVE across scanners, keeps max severity + unions scanners", () => { + const merged = mergeFindings([ + { id: "trivy", findings: [f("lodash: CVE-2021-23337", "medium")] }, + { id: "snyk", findings: [f("lodash@4: CVE-2021-23337", "high")] }, + { id: "grype", findings: [f("other: CVE-2020-1", "low")] }, + ]); + assert.equal(merged.length, 2); + const shared = merged.find((m) => dedupKey(m) === "CVE-2021-23337")!; + assert.equal(shared.severity, "high"); // max of medium/high + assert.deepEqual(shared.scanners.sort(), ["snyk", "trivy"]); + }); + it("sorts by severity (critical first)", () => { + const merged = mergeFindings([ + { id: "a", findings: [f("low: CVE-2020-1", "low"), f("crit: CVE-2020-2", "critical")] }, + ]); + assert.equal(merged[0].severity, "critical"); + }); +}); + +describe("runScanners (injected deps)", () => { + const SARIF = JSON.stringify({ + runs: [{ tool: { driver: { name: "trivy" } }, results: [{ ruleId: "CVE-2021-23337", level: "error", message: { text: "lodash CVE-2021-23337" } }] }], + }); + const defs: ScannerDef[] = [ + { id: "snyk", bin: "snyk", args: [], format: "sarif", needsToken: "SNYK_TOKEN" }, + { id: "trivy", bin: "trivy", args: [], format: "sarif" }, + { id: "grype", bin: "grype", args: [], format: "sarif" }, + ]; + + it("skips not-installed + no-token, runs the rest, merges", async () => { + const deps: ScanDeps = { + resolve: async (bin) => (bin === "grype" ? null : `/usr/bin/${bin}`), // grype absent + run: async () => ({ ok: false, stdout: SARIF }), // non-zero exit + SARIF (findings present) + hasEnv: () => false, // no SNYK_TOKEN + detect: () => true, + }; + const { merged, runs } = await runScanners(deps, defs); + const byId = Object.fromEntries(runs.map((r) => [r.id, r.status])); + assert.equal(byId.snyk, "no-token"); + assert.equal(byId.grype, "not-installed"); + assert.equal(byId.trivy, "ran"); + assert.equal(merged.length, 1); // trivy's one CVE + }); +}); diff --git a/src/scanners.ts b/src/scanners.ts new file mode 100644 index 00000000..effd549e --- /dev/null +++ b/src/scanners.ts @@ -0,0 +1,117 @@ +/** + * Scanner-runner registry — kit's consolidation play (#62, anchored by #50). + * + * A data-driven registry of external scanners that emit SARIF/OSV. `kit scan` + * runs the applicable+installed ones, pipes each output through the #48 ingest + * adapter, and MERGES the results locally into one deduped verdict — the same + * CVE/GHSA reported by multiple scanners collapses to one row (max severity, + * union of which scanners flagged it). Local-first, zero-server, deterministic. + * + * Pure parts (registry, dedup, merge) are fixture-tested; `runScanners` takes + * injectable deps so the orchestration is testable without real scanners. + */ +import type { SecurityCheckResult } from "./check-security.js"; +import { ingest, type IngestFormat } from "./adapters/ingest.js"; + +export interface ScannerDef { + id: string; + /** executable, resolved mise-first */ + bin: string; + /** args that emit SARIF/OSV on stdout */ + args: string[]; + format: IngestFormat; + /** env var that must be set (e.g. SNYK_TOKEN) */ + needsToken?: string; + /** marker files that make the scanner applicable; undefined = always */ + detect?: string[]; +} + +export const SCANNERS: ScannerDef[] = [ + { id: "snyk", bin: "snyk", args: ["test", "--sarif"], format: "sarif", needsToken: "SNYK_TOKEN" }, + { id: "trivy", bin: "trivy", args: ["fs", "--format", "sarif", "--quiet", "."], format: "sarif" }, + { id: "grype", bin: "grype", args: ["dir:.", "-o", "sarif", "-q"], format: "sarif" }, + { id: "semgrep", bin: "semgrep", args: ["scan", "--sarif", "--quiet", "--config", "auto", "."], format: "sarif" }, + { id: "osv-scanner", bin: "osv-scanner", args: ["--format", "json", "-r", "."], format: "osv" }, +]; + +const RANK: Record = { critical: 4, high: 3, medium: 2, low: 1 }; + +/** Cross-scanner dedup key: a CVE/GHSA id if present in the finding, else its name. */ +export function dedupKey(f: SecurityCheckResult): string { + const m = /(CVE-\d{4}-\d{1,7}|GHSA-[a-z0-9]{4}-[a-z0-9]{4}-[a-z0-9]{4})/i.exec(`${f.name} ${f.detail ?? ""}`); + return m ? m[1].toUpperCase() : f.name; +} + +export interface MergedFinding extends SecurityCheckResult { + /** which scanners reported this finding */ + scanners: string[]; +} + +/** Collapse findings from many scanners by dedupKey — max severity, union of scanners. */ +export function mergeFindings(perScanner: { id: string; findings: SecurityCheckResult[] }[]): MergedFinding[] { + const byKey = new Map(); + for (const { id, findings } of perScanner) { + for (const f of findings) { + const key = dedupKey(f); + const existing = byKey.get(key); + if (!existing) { + byKey.set(key, { ...f, scanners: [id] }); + continue; + } + if (!existing.scanners.includes(id)) existing.scanners.push(id); + if ((RANK[f.severity ?? "low"] ?? 0) > (RANK[existing.severity ?? "low"] ?? 0)) { + existing.severity = f.severity; + } + } + } + return [...byKey.values()].sort((a, b) => (RANK[b.severity ?? "low"] ?? 0) - (RANK[a.severity ?? "low"] ?? 0)); +} + +export type ScannerStatus = "ran" | "not-installed" | "no-token" | "not-applicable" | "error"; +export interface ScannerRun { + id: string; + status: ScannerStatus; + findings: number; +} + +export interface ScanDeps { + resolve(bin: string): Promise; + run(bin: string, args: string[]): Promise<{ ok: boolean; stdout: string }>; + hasEnv(name: string): boolean; + detect(markers: string[]): boolean; +} + +/** Run each applicable+installed scanner, ingest its output, merge into one verdict. */ +export async function runScanners( + deps: ScanDeps, + scanners: ScannerDef[] = SCANNERS, +): Promise<{ merged: MergedFinding[]; runs: ScannerRun[] }> { + const runs: ScannerRun[] = []; + const perScanner: { id: string; findings: SecurityCheckResult[] }[] = []; + for (const s of scanners) { + if (s.detect && !deps.detect(s.detect)) { + runs.push({ id: s.id, status: "not-applicable", findings: 0 }); + continue; + } + const bin = await deps.resolve(s.bin); + if (!bin) { + runs.push({ id: s.id, status: "not-installed", findings: 0 }); + continue; + } + if (s.needsToken && !deps.hasEnv(s.needsToken)) { + runs.push({ id: s.id, status: "no-token", findings: 0 }); + continue; + } + const res = await deps.run(bin, s.args); + // Most scanners exit non-zero WHEN findings exist — parse stdout regardless; + // only a truly empty + failed run is an error. + if (!res.stdout && !res.ok) { + runs.push({ id: s.id, status: "error", findings: 0 }); + continue; + } + const findings = res.stdout ? ingest(s.format, res.stdout) : []; + perScanner.push({ id: s.id, findings }); + runs.push({ id: s.id, status: "ran", findings: findings.length }); + } + return { merged: mergeFindings(perScanner), runs }; +}