Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
4 changes: 2 additions & 2 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -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",
Expand Down
45 changes: 45 additions & 0 deletions src/cli.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4280,6 +4280,50 @@ async function cmdSentinel(): Promise<boolean> {
return true;
}

async function cmdScan(): Promise<boolean> {
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<boolean> {
const jsonMode = hasFlag(process.argv, "--json");

Expand Down Expand Up @@ -5022,6 +5066,7 @@ async function main(): Promise<void> {
"supply-chain": cmdSupplyChain,
"agent-audit": cmdAgentAudit,
sentinel: cmdSentinel,
scan: cmdScan,
init: cmdInit,
upgrade: cmdUpgrade,
install: cmdInstall,
Expand Down
62 changes: 62 additions & 0 deletions src/scanners.test.ts
Original file line number Diff line number Diff line change
@@ -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
});
});
117 changes: 117 additions & 0 deletions src/scanners.ts
Original file line number Diff line number Diff line change
@@ -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<string, number> = { 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<string, MergedFinding>();
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<string | null>;
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 };
}
Loading