diff --git a/CHANGELOG.md b/CHANGELOG.md index 39fc4654..621325f9 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,24 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/). ## [Unreleased] +## [1.4.0] - 2026-06-17 + +### Added +- **`kit context check` — per-project CLI context lock.** Declare each tool's exact account + project in `.kit.toml` `[context]` (gcloud account/project, vercel team/project, github org/remote, git email, npm registry). `kit context check` reads the LIVE tool state and verifies it matches, and **never infers a pairing from whatever happens to be logged in or selected**: a right account with the wrong project is a mismatch, not a pass. Read-only; exits non-zero on a mismatch so it can gate a git hook or an agent before an outward or destructive command. Context pointers are non-secret and live in config; the credentials they authenticate with stay in the vault. (Catches the class of incident where a repo carries a stale deploy connection from a previous purpose, or a CLI is pointed at the wrong org.) +- **`kit hooks add context-check`** — installs a `pre-push` git hook that runs `kit context check` and blocks the push on a mismatch. This is the enforcement: a push to the wrong org/project is stopped before it leaves the machine. +- **`kit context use`** — activates the declared context (gcloud config + repo git identity) so every CLI points at the right account/project atomically. Touches only local config, never an account or a deploy; vercel/npm get guidance rather than an auto-switch. +- **`kit context --prompt`** — a fast, read-only indicator of the active gcloud context (e.g. `[gcp:my-project]`) for your shell prompt, read from gcloud's config files (no subprocess per prompt), so the context you are in is always visible. +- **Rule citations on security checks.** Each `kit check` security finding now carries the rule it enforces (CWE / OWASP Top 10) in the `--json` output and as a `[CWE-…]` tag in the text table, via a local, deterministic rules catalog (`src/rules/catalog.ts`). It cites kit's own checks (gitignore, secrets, dep-pinning, lockfiles, service exposure); a check without a defensible anchor carries no rule rather than a forced one. Foundation for consolidating + citing findings across kit and the scanners it wraps. + +### Changed +- **`kit memory pal add` verify flags:** use `--verify-http [--expect ]` or `--verify-file ` instead of `--verify ""`. For checks these types do not cover, run the check yourself and close the item manually (pal stays a ledger). Raw shell `verify_cmd` from pre-1.4 stores is retained so `kit memory scan` can still find secrets in old rows, but is never auto-executed. + +### Fixed +- **A `--help`/`-h` flag never executes a side-effectful subcommand.** `kit memory --help` (e.g. `kit memory install --help`) previously ran the subcommand instead of printing help, so `kit memory install --help` would actually install the hooks. It now shows help and does nothing else. + +### Security +- **PAL verify is now a declarative, typed check instead of a raw shell command.** `palAutoVerify` no longer runs a stored shell string through `execSync`; it runs a typed check natively (`http-status` via fetch, `file-exists` via fs), never through a shell and never by interpolating a stored value into a command. There is no longer an arbitrary-command-execution sink. This removes a persistence/deferred-execution risk that mattered for kit's agent-native use: a prompt-injected agent could previously store a `verify_cmd` in one (low-trust) session that detonated later when a more-trusted session ran `kit memory pal verify`. The typed model is also deliberately autonomy-friendly: auto-verify needs no human gate, yet a planted or injected value is inert (a defensive parser rejects any unknown shape). Closes the residual `memory/pal.js` finding (Socket AI) at the root rather than by adding a human-in-the-loop gate that would break autonomous agent jobs. + ## [1.3.1] - 2026-06-17 ### Security diff --git a/README.md b/README.md index 9be95dc2..59ae9764 100644 --- a/README.md +++ b/README.md @@ -110,6 +110,7 @@ Complete reference: [`docs/COMMANDS.md`](./docs/COMMANDS.md). The shortlist: - `kit auth {elevate,setup-totp,status,revoke}`: Elevation gate + TOTP - `kit mcp {list,auth,set-token,clear}`: MCP-server orchestrator - `kit env {list,switch,current,diff}`: Environment routing + drift detection +- `kit context {check,use,--prompt}`: Lock each CLI to its declared account + project (no wrong-org pushes) - `kit triage {npm,pip,docker,repo,skill}`: Pre-install security check - `kit security {scan-build,scan-staged,verify-pull,costs,policy}`: Security ops - `kit hooks {install,add,sync}`: Git hooks + bypass detector @@ -249,6 +250,7 @@ migration, to deploy-platform propagation, to destructive history cleanup. - `secret-scan` (pre-commit): Block commits that introduce known credential patterns - `post-pull-audit` (post-merge): Run `verify-pull` after every `git pull` / merge +- `context-check` (pre-push): Block a push when the live CLI context does not match `.kit.toml [context]` (see Context lock) ### Environments + elevation @@ -262,6 +264,26 @@ Production credentials are gated behind explicit env-switching and short-lived e - `kit auth revoke`: Drop the elevation marker early - `kit audit secrets [--since-days N] [--key ]`: Forensics: who touched which key, when +### Context lock + +When you work across several accounts and projects (gcloud, Vercel, GitHub, npm) it is easy to be in the wrong one without noticing, and a logged-in account plus a selected project are not assumed to belong together. Declare the exact pair per repo and kit verifies the live tools against it: + +```toml +[context] +gcloud = { account = "ops@acme.com", project = "acme-prod", config = "acme", region = "europe-west4" } +vercel = { team = "team_…", project = "prj_…" } # the ids in .vercel/project.json +github = { org = "acme", remote = "github.com/acme/app" } +git = { email = "you@acme.com" } +npm = { registry = "https://registry.npmjs.org" } +``` + +- `kit context check`: verify the live account+project of each CLI matches the declaration. A right account with the wrong project is a mismatch, not a pass. Read-only; exits non-zero so it can gate. +- `kit context use`: activate the declared context (gcloud config + repo git identity). Touches only local config, never an account or a deploy. +- `kit context --prompt`: a fast, read-only indicator (e.g. `[gcp:acme-prod]`) for your shell prompt, so the context you are in is always visible. +- `kit hooks add context-check`: install a pre-push hook so a push to the wrong org/project is blocked before it leaves the machine. + +Context pointers are non-secret and live in config; the credentials they authenticate with stay in the vault. + ### Quality gates (baseline-aware) - `kit check --enforce-tests`: Fail when net-new source files lack a sibling `.test.ts` diff --git a/docs/MEMORY.md b/docs/MEMORY.md index 0ffb5674..e83cda4a 100644 --- a/docs/MEMORY.md +++ b/docs/MEMORY.md @@ -92,16 +92,25 @@ source-verifiable: see the table in the repo notes.) ### Pending actions (PAL) A structured "blocked-on-you" ledger on top of the raw log — items that survive -across sessions and **auto-close when their verify command starts passing**. +across sessions and **auto-close when their declarative verify check starts +passing**. A verify is a typed, native check (no shell), so it is safe to +auto-run unattended and a planted value can never execute code: ```bash -kit memory pal # list open items -kit memory pal add "ship the release" --verify "curl -fsS https://… | grep -q 200" +kit memory pal # list open items +kit memory pal add "ship the release" --verify-http https://example.com --expect 200 +kit memory pal add "build artifact exists" --verify-file ./dist/cli.js kit memory pal done | snooze -kit memory pal verify # run verifies: N=2 consecutive passes closes; a regression reopens -kit memory pal import # migrate a legacy ~/.claude/pal/ledger.jsonl +kit memory pal verify # run checks: N=2 consecutive passes closes; a regression reopens +kit memory pal import # migrate a legacy ~/.claude/pal/ledger.jsonl (verifies become manual) ``` +Supported verify checks: `--verify-http [--expect ]` (kit makes the +request and compares the status) and `--verify-file ` (file exists). kit +never runs a shell verify. For a check these types do not cover, run it yourself +and close the item manually. Raw shell `verify_cmd` from pre-1.4 stores is never +auto-executed. + Open items surface in the `UserPromptSubmit` reminder so handed-off tasks stop getting forgotten. Verify commands run in your shell — they are **operator-authored and live in the personal store only**; never put an executable verify on an item @@ -183,8 +192,10 @@ Shared memory is **treated like code**: cell contents. It reports masked findings and exits non-zero if any are found, so you can use it as a gate. - Backups are encrypted (AES-256-GCM, scrypt). The passphrase is never stored. -- Shared writes are secret-scanned fail-closed; executable verify commands never - cross the sharing boundary. +- Shared writes are secret-scanned fail-closed. Verify checks are declarative + and typed (no shell), and a verify imported or merged from another store is + demoted to a manual item, so no executable ever crosses a file, DB, or sharing + boundary and auto-runs. ## Where it sits diff --git a/package.json b/package.json index 45f046d2..fc9cd9f1 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "sandstream-kit", - "version": "1.3.1", + "version": "1.4.0", "description": "developer kit. zero LLM, local-first, multi-vault. one command from git clone to working dev environment.", "license": "MIT", "type": "module", diff --git a/src/check-security.ts b/src/check-security.ts index 253f6c1a..fbed4c10 100644 --- a/src/check-security.ts +++ b/src/check-security.ts @@ -3,6 +3,7 @@ import { promisify } from "node:util"; import { readFile, access } from "node:fs/promises"; import { resolve } from "node:path"; import { execFileNoThrow } from "./utils/execFileNoThrow.js"; +import { ruleForCheck, type RuleRef } from "./rules/catalog.js"; import { ensureBumblebee, runScan, @@ -51,6 +52,7 @@ export interface SecurityCheckResult { severity?: "critical" | "high" | "medium" | "low"; files?: string[]; // Files with issues (for secrets scan) suggestion?: string; // Installation or remediation instructions + rule?: RuleRef; // citation for the rule this check enforces (CWE/OWASP), if mapped } /** @@ -1005,7 +1007,13 @@ export async function checkSecurity(): Promise { const exposureResults = await checkServiceExposure(); results.push(...exposureResults); - return results; + // Attach a rule citation (CWE/OWASP) to each finding whose check is mapped in + // the local rules catalog. Deterministic lookup, no network. Unmapped checks + // pass through unchanged. + return results.map((r) => { + const rule = ruleForCheck(r.name); + return rule ? { ...r, rule } : r; + }); } /** diff --git a/src/cli.ts b/src/cli.ts index f5a76945..a970588d 100644 --- a/src/cli.ts +++ b/src/cli.ts @@ -102,6 +102,7 @@ import { promptConfirm } from "./utils/prompt.js"; import { c } from "./utils/colors.js"; import { gatherStatus } from "./status.js"; import { KIT_FILE, resolveConfigPath } from "./cli-shared.js"; +import { checkContext, applyContext, contextPrompt } from "./context-lock.js"; import { cmdEnv } from "./commands/env.js"; import { cmdAuth } from "./commands/auth.js"; import { cmdAudit } from "./commands/audit.js"; @@ -3367,7 +3368,88 @@ async function cmdOpen(): Promise { } } +async function cmdContextCheck(): Promise { + const jsonMode = hasFlag(process.argv, "--json"); + const config = await loadConfig(resolveConfigPath()); + const findings = await checkContext(config.context); + + if (jsonMode) { + console.log(JSON.stringify(findings, null, 2)); + return findings.every((f) => f.status !== "mismatch"); + } + if (!config.context) { + console.log( + `${c.dim}No [context] declared in .kit.toml. Add one to lock each CLI to its account + project.${c.reset}`, + ); + return true; + } + console.log(`${c.bold}Context lock${c.reset}\n`); + for (const f of findings) { + const icon = + f.status === "ok" + ? `${c.green}✓${c.reset}` + : f.status === "mismatch" + ? `${c.red}✗${c.reset}` + : `${c.yellow}!${c.reset}`; + const actual = f.actual ?? `${c.dim}(unreadable)${c.reset}`; + const detail = + f.status === "ok" + ? `${c.dim}${f.expected}${c.reset}` + : `expected ${c.bold}${f.expected}${c.reset}, live ${c.bold}${actual}${c.reset}`; + console.log(` ${icon} ${f.tool}.${f.field} ${detail}`); + } + const mismatches = findings.filter((f) => f.status === "mismatch"); + if (mismatches.length > 0) { + console.log( + `\n${c.red}${mismatches.length} mismatch(es) — you are NOT locked to the declared account/project. Do not run outward/destructive commands until this is green.${c.reset}`, + ); + } + // Mismatch = non-zero exit so this can gate a hook / agent before acting. + // Unknown (tool absent / unreadable) does not block. + return mismatches.length === 0; +} + +async function cmdContextUse(): Promise { + const config = await loadConfig(resolveConfigPath()); + if (!config.context) { + console.log( + `${c.dim}No [context] declared in .kit.toml. Add one to lock each CLI to its account + project.${c.reset}`, + ); + return true; + } + console.log(`${c.bold}Context use${c.reset}\n`); + const results = await applyContext(config.context, process.cwd()); + for (const r of results) { + const icon = r.ok ? `${c.green}✓${c.reset}` : `${c.red}✗${c.reset}`; + console.log(` ${icon} ${r.step.tool} ${c.dim}${r.step.describe}${c.reset}`); + } + // vercel/npm have no clean per-repo "active" state to switch — guide instead. + if (config.context.vercel) { + console.log( + ` ${c.dim}vercel: pass --scope per command or run \`vercel link\`; kit does not switch the dashboard link.${c.reset}`, + ); + } + if (config.context.npm) { + console.log( + ` ${c.dim}npm: registry is global — set with \`npm config set registry \` if it differs.${c.reset}`, + ); + } + const failed = results.filter((r) => !r.ok).length; + if (failed > 0) { + console.log(`\n${c.yellow}${failed} step(s) failed (tool not installed?). Run kit context check to verify.${c.reset}`); + } + return failed === 0; +} + async function cmdContext(): Promise { + if (process.argv[3] === "check") return cmdContextCheck(); + if (process.argv[3] === "use") return cmdContextUse(); + // Fast, read-only PS1 indicator: `kit context --prompt` -> "[gcp:]". + if (hasFlag(process.argv, "--prompt")) { + console.log(contextPrompt()); + return true; + } + const jsonMode = hasFlag(process.argv, "--json"); try { @@ -3612,6 +3694,9 @@ const COMMAND_HELP: Record = { run: "Execute a command with project env vars loaded", open: "Open service dashboard in browser (stripe, vercel, railway, etc.)", context: "Show project context: tools, services, secrets, environment", + "context check": "Verify each CLI's live account+project matches .kit.toml [context] (exits non-zero on mismatch)", + "context use": "Activate the declared context: gcloud config + repo git identity", + "context --prompt": "Print a compact active-gcloud indicator for your shell prompt (PS1)", mcp: "MCP server over stdio (Claude Code/Cursor/Codex); 'kit mcp list|auth|set-token|clear' manages declared servers", whoami: "Show current agent / user identity", version: "Print kit version", diff --git a/src/commands/hooks.ts b/src/commands/hooks.ts index c9473017..a5106e0d 100644 --- a/src/commands/hooks.ts +++ b/src/commands/hooks.ts @@ -18,6 +18,12 @@ const BUILTIN_HOOKS: Record { diff --git a/src/commands/memory.ts b/src/commands/memory.ts index e7db8382..208c424a 100644 --- a/src/commands/memory.ts +++ b/src/commands/memory.ts @@ -31,6 +31,7 @@ import { palSnooze, palAutoVerify, importLegacyLedger, + type VerifyCheck, } from "../memory/pal.js"; import { saveThread, @@ -43,6 +44,9 @@ import { export async function cmdMemory(): Promise { const subcommand = process.argv[3]; if (!subcommand || subcommand === "--help" || subcommand === "-h") return memHelp(); + // A --help/-h flag after a subcommand means "show help", never run a + // side-effectful subcommand (e.g. `kit memory install --help` must not install). + if (hasFlag(process.argv, "--help") || hasFlag(process.argv, "-h")) return memHelp(); // One handler per subcommand — keeps this dispatcher flat (was a complexity-132 // if-chain). Each handler reads process.argv itself, so no args thread through. @@ -109,13 +113,23 @@ async function memPal(): Promise { const title = process.argv.slice(5).filter((a) => !a.startsWith("--")).join(" ").trim(); if (!title) { console.error( - `${c.red}usage: kit memory pal add [--verify=<cmd>] [--scope=<s>]${c.reset}`, + `${c.red}usage: kit memory pal add <title> [--verify-http <url> [--expect <code>]] [--verify-file <path>] [--scope=<s>]${c.reset}`, ); return false; } + // Declarative verify only (no shell). http-status or file-exists. + const httpUrl = flagValue(process.argv, "--verify-http"); + const filePath = flagValue(process.argv, "--verify-file"); + let check: VerifyCheck | undefined; + if (httpUrl) { + const expect = Number(flagValue(process.argv, "--expect") ?? "200"); + check = { type: "http-status", url: httpUrl, expect: Number.isFinite(expect) ? expect : 200 }; + } else if (filePath) { + check = { type: "file-exists", path: filePath }; + } const id = palAdd(db, { title, - verifyCmd: flagValue(process.argv, "--verify"), + check, scope: flagValue(process.argv, "--scope") ?? basename(getCurrentProjectRoot()), }); console.log(`${c.green}✓${c.reset} added ${c.bold}${id}${c.reset}`); @@ -149,7 +163,7 @@ async function memPal(): Promise<boolean> { return true; } if (action === "verify") { - const r = palAutoVerify(db); + const r = await palAutoVerify(db); console.log( `${c.dim}checked ${r.checked} · closed ${r.closed.length} · reopened ${r.reopened.length}${c.reset}`, ); diff --git a/src/config.ts b/src/config.ts index 6f047a03..ce04b378 100644 --- a/src/config.ts +++ b/src/config.ts @@ -248,6 +248,22 @@ export interface EnvOverride { governance?: GovernanceConfig; } +/** + * Per-project CLI context lock. Each tool declares the EXACT (account, project) + * pair this repo must use. kit verifies the live tool state against these + * declarations and never infers a pairing from whatever happens to be logged in + * or selected (a logged-in account + a selected project are not assumed to belong + * together). These are non-secret pointers; the credentials they authenticate + * with stay in the vault (`[secrets]`). + */ +export interface ContextConfig { + gcloud?: { account?: string; project?: string; config?: string; region?: string }; + vercel?: { team?: string; project?: string }; + github?: { org?: string; remote?: string }; + git?: { email?: string }; + npm?: { registry?: string }; +} + export interface kitConfig { tools?: ToolConfig; services?: Record<string, ServiceConfig>; @@ -255,6 +271,8 @@ export interface kitConfig { skills?: SkillsConfig; governance?: GovernanceConfig; hooks?: HooksConfig; + /** Per-project CLI context lock (account+project per tool). */ + context?: ContextConfig; web?: { search?: WebSearchConfig; }; @@ -444,6 +462,30 @@ const kitConfigSchema = z skills: SkillsConfigSchema.optional(), governance: GovernanceConfigSchema.optional(), hooks: HooksConfigSchema, + context: z + .object({ + gcloud: z + .object({ + account: z.string().optional(), + project: z.string().optional(), + config: z.string().optional(), + region: z.string().optional(), + }) + .passthrough() + .optional(), + vercel: z + .object({ team: z.string().optional(), project: z.string().optional() }) + .passthrough() + .optional(), + github: z + .object({ org: z.string().optional(), remote: z.string().optional() }) + .passthrough() + .optional(), + git: z.object({ email: z.string().optional() }).passthrough().optional(), + npm: z.object({ registry: z.string().optional() }).passthrough().optional(), + }) + .passthrough() + .optional(), web: WebConfigSchema, setup: z .object({ diff --git a/src/context-lock.test.ts b/src/context-lock.test.ts new file mode 100644 index 00000000..f6b266c9 --- /dev/null +++ b/src/context-lock.test.ts @@ -0,0 +1,93 @@ +import { describe, it } from "node:test"; +import assert from "node:assert/strict"; +import { + compareContext, + parseGithubRemote, + planContext, + parseGcloudProject, + type LiveContext, +} from "./context-lock.js"; + +describe("context lock", () => { + it("passes only when the exact declared pair matches", () => { + const declared = { gcloud: { account: "ops@example.com", project: "prod-project" } }; + const live: LiveContext = { gcloud: { account: "ops@example.com", project: "prod-project" } }; + const f = compareContext(declared, live); + assert.equal(f.filter((x) => x.status !== "ok").length, 0); + }); + + it("flags right account + WRONG project as a mismatch (never trust the ambient pair)", () => { + const declared = { gcloud: { account: "ops@example.com", project: "prod-project" } }; + const live: LiveContext = { gcloud: { account: "ops@example.com", project: "other-project" } }; + const proj = compareContext(declared, live).find( + (x) => x.tool === "gcloud" && x.field === "project", + ); + assert.equal(proj?.status, "mismatch"); + assert.equal(proj?.expected, "prod-project"); + assert.equal(proj?.actual, "other-project"); + }); + + it("marks unreadable live state as unknown (does not block)", () => { + const declared = { npm: { registry: "https://registry.npmjs.org" } }; + const live: LiveContext = { npm: { registry: null } }; + assert.equal(compareContext(declared, live)[0]?.status, "unknown"); + }); + + it("only checks declared fields", () => { + const declared = { git: { email: "dev@example.com" } }; + const live: LiveContext = { + gcloud: { account: "x", project: "y" }, + git: { email: "dev@example.com" }, + }; + const f = compareContext(declared, live); + assert.equal(f.length, 1); + assert.equal(f[0]?.tool, "git"); + assert.equal(f[0]?.status, "ok"); + }); + + it("flags a vercel link to the wrong project", () => { + const declared = { vercel: { team: "team_example", project: "prj_canonical" } }; + const live: LiveContext = { vercel: { orgId: "team_example", projectId: "prj_stale" } }; + const proj = compareContext(declared, live).find((x) => x.field === "project(projectId)"); + assert.equal(proj?.status, "mismatch"); + }); + + it("parses github org + remote from ssh and https urls", () => { + assert.deepEqual(parseGithubRemote("git@github.com:example-org/example-repo.git"), { + org: "example-org", + remote: "github.com/example-org/example-repo", + }); + assert.deepEqual(parseGithubRemote("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/example-org/example-repo"), { + org: "example-org", + remote: "github.com/example-org/example-repo", + }); + assert.deepEqual(parseGithubRemote(null), { org: null, remote: null }); + assert.deepEqual(parseGithubRemote("https://gitlab.com/x/y"), { org: null, remote: null }); + }); + + it("plans gcloud + git activation from the declared context (local config only)", () => { + const steps = planContext({ + gcloud: { config: "prod-cfg", account: "ops@example.com", project: "prod-project", region: "europe-west4" }, + git: { email: "dev@example.com" }, + }); + const describes = steps.map((s) => s.describe); + assert.ok(describes.some((d) => d.includes("activate config prod-cfg"))); + assert.ok(describes.some((d) => d.includes("project=prod-project"))); + assert.ok(describes.some((d) => d.includes("account=ops@example.com"))); + // git identity is repo-local, not global + const gitStep = steps.find((s) => s.tool === "git"); + assert.equal(gitStep?.local, true); + assert.deepEqual(gitStep?.argv, ["config", "user.email", "dev@example.com"]); + // nothing planned for vercel/npm (no clean per-repo activation) + assert.equal(steps.some((s) => s.tool === "vercel" || s.tool === "npm"), false); + }); + + it("plans nothing when no activatable context is declared", () => { + assert.deepEqual(planContext({ npm: { registry: "https://registry.npmjs.org" } }), []); + }); + + it("parses the gcloud project from a config INI", () => { + assert.equal(parseGcloudProject("[core]\naccount = a@b.com\nproject = prod-project\n"), "prod-project"); + assert.equal(parseGcloudProject("[core]\naccount = a@b.com\n"), null); + }); +}); diff --git a/src/context-lock.ts b/src/context-lock.ts new file mode 100644 index 00000000..96aa98e9 --- /dev/null +++ b/src/context-lock.ts @@ -0,0 +1,224 @@ +/** + * Per-project CLI context lock. + * + * Verifies that each tool's LIVE (account, project) pair matches what `.kit.toml` + * `[context]` declares. The core rule: a logged-in account and a selected project + * are NEVER assumed to belong together. Only the declared pair is trusted; the + * ambient CLI state is data to be checked against it. A right account paired with + * the wrong project (or vice versa) is a mismatch, not a pass. + * + * Read-only: this never changes any tool's state (that is `kit context use`). + */ +import { execFile } from "node:child_process"; +import { promisify } from "node:util"; +import { readFile } from "node:fs/promises"; +import { readFileSync } from "node:fs"; +import { resolve, join } from "node:path"; +import { homedir } from "node:os"; +import type { ContextConfig } from "./config.js"; + +const exec = promisify(execFile); + +export interface ContextFinding { + tool: string; // gcloud | git | github | npm | vercel + field: string; // account | project | email | org | remote | registry | ... + status: "ok" | "mismatch" | "unknown"; // unknown = live state could not be read + expected: string; + actual: string | null; +} + +/** A snapshot of the live context read from each tool (null = unreadable). */ +export interface LiveContext { + gcloud?: { account: string | null; project: string | null }; + git?: { email: string | null }; + github?: { org: string | null; remote: string | null }; + npm?: { registry: string | null }; + vercel?: { orgId: string | null; projectId: string | null }; +} + +function field( + tool: string, + name: string, + expected: string | undefined, + actual: string | null, +): ContextFinding | null { + if (expected === undefined) return null; // not declared -> not checked + if (actual === null) return { tool, field: name, status: "unknown", expected, actual: null }; + return { tool, field: name, status: actual === expected ? "ok" : "mismatch", expected, actual }; +} + +// One row per checkable (tool, field). Adding a CLI to the lock is one row. +// `declared` returns the expected value (undefined = not declared = not checked); +// `live` returns the read value (null = unreadable). vercel context = the ids in +// .vercel/project.json (deterministic + local): team -> orgId, project -> projectId. +const FIELD_SPECS: { + tool: string; + field: string; + declared: (d: ContextConfig) => string | undefined; + live: (l: LiveContext) => string | null; +}[] = [ + { tool: "gcloud", field: "account", declared: (d) => d.gcloud?.account, live: (l) => l.gcloud?.account ?? null }, + { tool: "gcloud", field: "project", declared: (d) => d.gcloud?.project, live: (l) => l.gcloud?.project ?? null }, + { tool: "git", field: "email", declared: (d) => d.git?.email, live: (l) => l.git?.email ?? null }, + { tool: "github", field: "org", declared: (d) => d.github?.org, live: (l) => l.github?.org ?? null }, + { tool: "github", field: "remote", declared: (d) => d.github?.remote, live: (l) => l.github?.remote ?? null }, + { tool: "npm", field: "registry", declared: (d) => d.npm?.registry, live: (l) => l.npm?.registry ?? null }, + { tool: "vercel", field: "team(orgId)", declared: (d) => d.vercel?.team, live: (l) => l.vercel?.orgId ?? null }, + { tool: "vercel", field: "project(projectId)", declared: (d) => d.vercel?.project, live: (l) => l.vercel?.projectId ?? null }, +]; + +/** + * Compare a declared context against a live snapshot. PURE (no I/O) so the + * principle is unit-testable: only the exact declared pair passes. + */ +export function compareContext(declared: ContextConfig, live: LiveContext): ContextFinding[] { + return FIELD_SPECS.map((s) => field(s.tool, s.field, s.declared(declared), s.live(live))).filter( + (f): f is ContextFinding => f !== null, + ); +} + +async function run(cmd: string, args: string[]): Promise<string | null> { + try { + const { stdout } = await exec(cmd, args, { timeout: 8_000 }); + return stdout.trim() || null; + } catch { + return null; + } +} + +/** github.com[:/]org/repo(.git) -> { org, "github.com/org/repo" }. */ +export function parseGithubRemote(url: string | null): { org: string | null; remote: string | null } { + if (!url) return { org: null, remote: null }; + const m = url.match(/github\.com[:/]([^/]+)\/(.+?)(?:\.git)?$/); + if (!m) return { org: null, remote: null }; + return { org: m[1], remote: `github.com/${m[1]}/${m[2]}` }; +} + +/** Read the live context from each tool. Every read fails soft to null. */ +export async function gatherLive(cwd: string = process.cwd()): Promise<LiveContext> { + const live: LiveContext = {}; + + const gcloudJson = await run("gcloud", ["config", "list", "--format=json"]); + if (gcloudJson !== null) { + try { + const c = JSON.parse(gcloudJson) as { core?: { account?: string; project?: string } }; + live.gcloud = { account: c.core?.account ?? null, project: c.core?.project ?? null }; + } catch { + live.gcloud = { account: null, project: null }; + } + } else { + live.gcloud = { account: null, project: null }; + } + + live.git = { email: await run("git", ["config", "user.email"]) }; + + const remote = await run("git", ["remote", "get-url", "origin"]); + live.github = parseGithubRemote(remote); + + const registry = await run("npm", ["config", "get", "registry"]); + live.npm = { registry: registry ? registry.replace(/\/+$/, "") : null }; + + try { + const raw = await readFile(resolve(cwd, ".vercel", "project.json"), "utf8"); + const j = JSON.parse(raw) as { orgId?: string; projectId?: string }; + live.vercel = { orgId: j.orgId ?? null, projectId: j.projectId ?? null }; + } catch { + live.vercel = { orgId: null, projectId: null }; + } + + return live; +} + +/** Verify the declared context against live tool state. Empty if nothing declared. */ +export async function checkContext( + ctx: ContextConfig | undefined, + cwd: string = process.cwd(), +): Promise<ContextFinding[]> { + if (!ctx) return []; + // Normalize a declared npm registry the same way the live read is normalized. + const declared: ContextConfig = ctx.npm?.registry + ? { ...ctx, npm: { ...ctx.npm, registry: ctx.npm.registry.replace(/\/+$/, "") } } + : ctx; + return compareContext(declared, await gatherLive(cwd)); +} + +// ── kit context use — activate the declared context ────────────────────────── + +export interface ContextStep { + tool: string; + argv: string[]; + /** Run in the repo (cwd) rather than affecting global state — e.g. git config. */ + local?: boolean; + describe: string; +} + +/** + * Plan the commands that would activate the declared context. PURE (no I/O) so + * the mapping is unit-testable. Only LOCAL CLI config is ever touched (gcloud + * config, repo git identity) — never an account or a deploy. vercel/npm are not + * auto-activated (no clean per-repo "active" state); `use` prints guidance. + */ +export function planContext(ctx: ContextConfig): ContextStep[] { + const steps: ContextStep[] = []; + const g = ctx.gcloud; + if (g?.config) + steps.push({ tool: "gcloud", argv: ["config", "configurations", "activate", g.config], describe: `activate config ${g.config}` }); + if (g?.account) + steps.push({ tool: "gcloud", argv: ["config", "set", "account", g.account], describe: `account=${g.account}` }); + if (g?.project) + steps.push({ tool: "gcloud", argv: ["config", "set", "project", g.project], describe: `project=${g.project}` }); + if (g?.region) + steps.push({ tool: "gcloud", argv: ["config", "set", "run/region", g.region], describe: `run/region=${g.region}` }); + if (ctx.git?.email) + steps.push({ tool: "git", argv: ["config", "user.email", ctx.git.email], local: true, describe: `git user.email=${ctx.git.email}` }); + return steps; +} + +export interface ApplyResult { + step: ContextStep; + ok: boolean; +} + +/** Execute the activation plan. Each step runs via execFile (no shell). */ +export async function applyContext( + ctx: ContextConfig, + cwd: string = process.cwd(), +): Promise<ApplyResult[]> { + const results: ApplyResult[] = []; + for (const step of planContext(ctx)) { + let ok = false; + try { + await exec(step.tool, step.argv, { timeout: 8_000, cwd: step.local ? cwd : undefined }); + ok = true; + } catch { + ok = false; + } + results.push({ step, ok }); + } + return results; +} + +// ── kit context --prompt — a fast, read-only PS1 indicator ─────────────────── + +/** Extract `project = <value>` from a gcloud configuration INI. PURE. */ +export function parseGcloudProject(ini: string): string | null { + const m = ini.match(/^\s*project\s*=\s*(.+?)\s*$/m); + return m ? m[1].trim() : null; +} + +/** + * A compact indicator of the ACTIVE gcloud context for a shell prompt, read from + * gcloud's config files (no subprocess, so it is cheap to call per prompt). + * Returns "" if gcloud config cannot be read. Example: "[gcp:cbd-platform]". + */ +export function contextPrompt(): string { + try { + const dir = process.env.CLOUDSDK_CONFIG || join(homedir(), ".config", "gcloud"); + const active = readFileSync(join(dir, "active_config"), "utf8").trim(); + const ini = readFileSync(join(dir, "configurations", `config_${active}`), "utf8"); + const project = parseGcloudProject(ini); + return project ? `[gcp:${project}]` : active ? `[gcp:${active}]` : ""; + } catch { + return ""; + } +} diff --git a/src/memory/db.ts b/src/memory/db.ts index 0ddef293..e8afec4f 100644 --- a/src/memory/db.ts +++ b/src/memory/db.ts @@ -93,6 +93,7 @@ CREATE TABLE IF NOT EXISTS pending_actions ( scope TEXT, kind TEXT NOT NULL DEFAULT 'manual', verify_cmd TEXT, + verify_check TEXT, created_at TEXT DEFAULT CURRENT_TIMESTAMP, next_check TEXT, snooze_until TEXT, @@ -149,6 +150,10 @@ function migrate(db: DatabaseSync): void { // v2: pending_actions.verify_passes (N=2 auto-verify confirmation). Add to // tables created before this column existed. ensureColumn(db, "pending_actions", "verify_passes", "INTEGER NOT NULL DEFAULT 0"); + // v3: pending_actions.verify_check (declarative typed verify replacing raw + // shell verify_cmd). Legacy verify_cmd rows have a NULL verify_check and are + // never auto-executed. + ensureColumn(db, "pending_actions", "verify_check", "TEXT"); const row = db.prepare("SELECT version FROM schema_meta LIMIT 1").get() as | { version: number } | undefined; diff --git a/src/memory/pal.test.ts b/src/memory/pal.test.ts index 4a637202..e23f9f2b 100644 --- a/src/memory/pal.test.ts +++ b/src/memory/pal.test.ts @@ -16,10 +16,13 @@ import { describe("PAL — pending actions", () => { const fresh = () => openMemoryDb(":memory:"); - it("adds + lists; kind inferred from verifyCmd", () => { + it("adds + lists; kind inferred from a verify check", () => { const db = fresh(); const manual = palAdd(db, { title: "ship the harvest branch" }); - const auto = palAdd(db, { title: "endpoint returns 200", verifyCmd: "true" }); + const auto = palAdd(db, { + title: "endpoint returns 200", + check: { type: "http-status", url: "https://example.com", expect: 200 }, + }); assert.match(manual, /^[0-9a-f]{4}$/); const open = palList(db); assert.equal(open.length, 2); @@ -47,29 +50,39 @@ describe("PAL — pending actions", () => { db.close(); }); - it("auto-verify closes after N=2 passes; a failing verify stays open", () => { + it("auto-verify closes after N=2 passes; a failing check stays open", async () => { const db = fresh(); - const passes = palAdd(db, { title: "passing check", verifyCmd: "true" }); - const fails = palAdd(db, { title: "failing check", verifyCmd: "false" }); - let r = palAutoVerify(db); + const tmp = mkdtempSync(join(tmpdir(), "kit-pal-")); + const present = join(tmp, "present"); + writeFileSync(present, "x"); + const missing = join(tmp, "missing"); + const passes = palAdd(db, { title: "passing check", check: { type: "file-exists", path: present } }); + const fails = palAdd(db, { title: "failing check", check: { type: "file-exists", path: missing } }); + let r = await palAutoVerify(db); assert.deepEqual(r.closed, []); // first pass: streak = 1 assert.equal(palList(db).length, 2); - r = palAutoVerify(db); + r = await palAutoVerify(db); assert.deepEqual(r.closed, [passes]); // second consecutive pass closes it const open = palList(db); assert.equal(open.length, 1); assert.equal(open[0]?.id, fails); + rmSync(tmp, { recursive: true, force: true }); db.close(); }); - it("reopens a closed auto item when its verify regresses", () => { + it("reopens a closed auto item when its check regresses", async () => { const db = fresh(); - const id = palAdd(db, { title: "regressing check", verifyCmd: "false" }); + const tmp = mkdtempSync(join(tmpdir(), "kit-pal-")); + const artifact = join(tmp, "artifact"); + writeFileSync(artifact, "x"); + const id = palAdd(db, { title: "regressing check", check: { type: "file-exists", path: artifact } }); palDone(db, id); // force-close assert.equal(palList(db, { status: "closed" }).length, 1); - const r = palAutoVerify(db); // verify 'false' on a closed auto item → reopen + rmSync(artifact); // artifact gone -> the check now fails + const r = await palAutoVerify(db); // fail on a closed auto item -> reopen assert.deepEqual(r.reopened, [id]); assert.equal(palList(db).length, 1); + rmSync(tmp, { recursive: true, force: true }); db.close(); }); @@ -113,7 +126,7 @@ describe("PAL — pending actions", () => { db.close(); }); - it("SECURITY: a verify command imported from a legacy ledger is never auto-executed", () => { + it("SECURITY: a verify command imported from a legacy ledger is never auto-executed", async () => { const db = fresh(); const tmp = mkdtempSync(join(tmpdir(), "kit-pal-sec-")); const led = join(tmp, "ledger.jsonl"); @@ -132,12 +145,30 @@ describe("PAL — pending actions", () => { const item = palList(db).find((p) => p.id === "evil"); assert.equal(item?.kind, "manual"); // demoted: not an auto item assert.equal(item?.verify_cmd ?? null, null); // executable command dropped on import - palAutoVerify(db); // must NOT run `touch ${marker}` + await palAutoVerify(db); // must NOT run `touch ${marker}` assert.equal(existsSync(marker), false, "imported verify_cmd must never execute"); rmSync(tmp, { recursive: true, force: true }); db.close(); }); + it("SECURITY: an unknown/injected verify_check shape is never executed", async () => { + const db = fresh(); + const tmp = mkdtempSync(join(tmpdir(), "kit-pal-sec2-")); + const marker = join(tmp, "PWNED"); + // Simulate DB tampering: inject a row with a bogus verify_check that a naive + // executor might run as a command. parseCheck must reject the unknown shape; + // nothing executes. + db.prepare( + `INSERT INTO pending_actions (id, status, title, kind, verify_check) + VALUES ('evil', 'open', 'injected', 'auto', ?)`, + ).run(JSON.stringify({ type: "shell", cmd: `touch ${marker}` })); + const r = await palAutoVerify(db); + assert.equal(r.checked, 0); // unknown shape -> not even run + assert.equal(existsSync(marker), false, "injected verify_check must never execute"); + rmSync(tmp, { recursive: true, force: true }); + db.close(); + }); + it("scopes the open list to a project (plus globally-scoped items)", () => { const db = fresh(); palAdd(db, { title: "kit item", scope: "kit" }); diff --git a/src/memory/pal.ts b/src/memory/pal.ts index ddc91f35..4fae7c68 100644 --- a/src/memory/pal.ts +++ b/src/memory/pal.ts @@ -3,17 +3,33 @@ * * PAL is the STRUCTURED, actionable layer on top of raw conversation memory: * "blocked-on-you" items that survive sessions and auto-close when their verify - * command starts passing. It lives in the `pending_actions` table of the same - * SQLite store. Deterministic; the only side effect is running operator-defined - * verify commands (local shell, with a timeout). Fail-open / no-info aware. + * check starts passing. It lives in the `pending_actions` table of the same + * SQLite store. + * + * SECURITY: a verify is a DECLARATIVE, typed check (see `VerifyCheck`), executed + * natively (fetch / fs) with a timeout. kit NEVER runs a shell, and never + * interpolates a stored string into a command, so there is no arbitrary-command- + * execution sink: a planted or imported value can only ever do what the fixed + * check types allow (nothing). This is deliberately compatible with autonomous + * agents: auto-verify needs no human gate, yet a prompt-injected agent cannot + * plant a command that detonates later in a more-trusted session. Fail-open / + * no-info aware. */ import { randomBytes } from "node:crypto"; -import { execSync } from "node:child_process"; import { readFileSync, existsSync } from "node:fs"; import { homedir } from "node:os"; import { join } from "node:path"; import type { DatabaseSync } from "node:sqlite"; +/** + * A declarative verify check. Fixed shapes only, executed natively by kit (no + * shell, no arbitrary binary). Add a new shape here only if it can be run as a + * pure data operation that cannot be coerced into command execution. + */ +export type VerifyCheck = + | { type: "http-status"; url: string; expect: number } + | { type: "file-exists"; path: string }; + export interface PendingAction { id: string; status: string; @@ -21,7 +37,11 @@ export interface PendingAction { detail: string | null; scope: string | null; kind: string; + /** Legacy raw shell command from pre-1.4 stores. NEVER executed; kept only so + * `kit memory scan` can still find secrets leaked into old rows. */ verify_cmd: string | null; + /** JSON-encoded VerifyCheck. The only field auto-verify ever executes. */ + verify_check: string | null; created_at: string | null; next_check: string | null; snooze_until: string | null; @@ -34,7 +54,7 @@ export interface PalAddInput { detail?: string; scope?: string; kind?: "manual" | "auto"; - verifyCmd?: string; + check?: VerifyCheck; } function newId(db: DatabaseSync): string { @@ -47,11 +67,12 @@ function newId(db: DatabaseSync): string { export function palAdd(db: DatabaseSync, input: PalAddInput): string { const id = newId(db); - const kind = input.kind ?? (input.verifyCmd ? "auto" : "manual"); + const kind = input.kind ?? (input.check ? "auto" : "manual"); + const verifyCheck = input.check ? JSON.stringify(input.check) : null; db.prepare( - `INSERT INTO pending_actions (id, status, title, detail, scope, kind, verify_cmd) + `INSERT INTO pending_actions (id, status, title, detail, scope, kind, verify_check) VALUES (?, 'open', ?, ?, ?, ?, ?)`, - ).run(id, input.title, input.detail ?? null, input.scope ?? null, kind, input.verifyCmd ?? null); + ).run(id, input.title, input.detail ?? null, input.scope ?? null, kind, verifyCheck); return id; } @@ -95,24 +116,51 @@ export function palSnooze(db: DatabaseSync, id: string, days: number): boolean { } /** - * Run a verify command. true = pass (exit 0), false = ran but failed, null = no-info. - * - * SECURITY: this runs `cmd` through a shell on purpose — verify commands routinely - * need pipes / `&&` (e.g. `curl -fsS … | grep 200`). The trust boundary: `verify_cmd` - * is OPERATOR-AUTHORED and lives only in the PERSONAL store (~/.kit/memory.db); running - * it is equivalent to the operator running their own command — no untrusted data is - * interpolated, so this is not a command-injection sink. INVARIANT for Track D (shared - * memory): shared/synced items must NEVER carry an executable `verify_cmd` that runs - * unreviewed — only manual items or review-gated verifies cross the sharing boundary. + * Parse the stored JSON into a VerifyCheck, defensively. Only known shapes are + * accepted; anything malformed, unknown, or legacy returns null and is never + * executed. This is the gate that makes a planted/imported value inert. */ -function runVerify(cmd: string): boolean | null { +function parseCheck(json: string | null): VerifyCheck | null { + if (!json) return null; + let raw: unknown; try { - execSync(cmd, { stdio: "ignore", timeout: 15_000 }); - return true; - } catch (err) { - const status = (err as { status?: number | null }).status; - if (typeof status === "number") return false; // ran, non-zero exit - return null; // spawn error / timeout → no-info, leave state unchanged + raw = JSON.parse(json); + } catch { + return null; + } + if (!raw || typeof raw !== "object") return null; + const o = raw as Record<string, unknown>; + if (o.type === "file-exists" && typeof o.path === "string") { + return { type: "file-exists", path: o.path }; + } + if (o.type === "http-status" && typeof o.url === "string" && typeof o.expect === "number") { + return { type: "http-status", url: o.url, expect: o.expect }; + } + return null; +} + +/** + * Run a declarative verify check. true = pass, false = ran but failed, null = + * no-info (leave state unchanged). Executed NATIVELY (fetch / fs), never through + * a shell and never by interpolating a stored string into a command, so there is + * no command-execution sink: a check can only do what its fixed type allows. + */ +async function runCheck(check: VerifyCheck): Promise<boolean | null> { + try { + if (check.type === "file-exists") { + return existsSync(check.path); + } + // http-status: kit makes the request itself; the URL is data, not a command. + const controller = new AbortController(); + const timer = setTimeout(() => controller.abort(), 15_000); + try { + const res = await fetch(check.url, { signal: controller.signal, redirect: "manual" }); + return res.status === check.expect; + } finally { + clearTimeout(timer); + } + } catch { + return null; // network/fs error or timeout → no-info } } @@ -127,15 +175,20 @@ export interface AutoVerifyResult { * times is closed (a pass increments the streak, a fail resets it). A CLOSED item * whose verify now FAILS is reopened (reopen-on-regress). No-info leaves it alone. */ -export function palAutoVerify(db: DatabaseSync, confirmPasses = 2): AutoVerifyResult { +export async function palAutoVerify( + db: DatabaseSync, + confirmPasses = 2, +): Promise<AutoVerifyResult> { const out: AutoVerifyResult = { checked: 0, closed: [], reopened: [] }; const rows = db .prepare( - "SELECT * FROM pending_actions WHERE kind='auto' AND verify_cmd IS NOT NULL AND status IN ('open','closed')", + "SELECT * FROM pending_actions WHERE kind='auto' AND verify_check IS NOT NULL AND status IN ('open','closed')", ) .all() as unknown as PendingAction[]; for (const r of rows) { - const result = runVerify(r.verify_cmd as string); + const check = parseCheck(r.verify_check); + if (!check) continue; // malformed/unknown/legacy shape -> never executed + const result = await runCheck(check); if (result === null) continue; // no-info out.checked++; if (r.status === "open") { diff --git a/src/output.ts b/src/output.ts index 7baa5053..2eae0590 100644 --- a/src/output.ts +++ b/src/output.ts @@ -264,7 +264,9 @@ export function printSkillsTable(skills: SkillCheckResult[]): void { ? `${c.dim}[${result.severity}]${c.reset}` : ""; - console.log(` ${icon} ${name} ${statusColor}${result.status}${c.reset} ${detail} ${severity}`); + const ruleTag = result.rule ? ` ${c.dim}[${result.rule.id}]${c.reset}` : ""; + + console.log(` ${icon} ${name} ${statusColor}${result.status}${c.reset} ${detail} ${severity}${ruleTag}`); // Show affected files if available (limit to first 5) if (result.files && result.files.length > 0) { diff --git a/src/rules/catalog.test.ts b/src/rules/catalog.test.ts new file mode 100644 index 00000000..4e006429 --- /dev/null +++ b/src/rules/catalog.test.ts @@ -0,0 +1,34 @@ +import { describe, it } from "node:test"; +import assert from "node:assert/strict"; +import { SECURITY_RULES, ruleForCheck } from "./catalog.js"; + +describe("rules catalog", () => { + const sources = new Set(["cwe", "owasp", "asvs", "kit"]); + + it("every entry is well-formed", () => { + for (const [name, rule] of Object.entries(SECURITY_RULES)) { + assert.ok(name.length > 0, "check name is non-empty"); + assert.ok(rule.id.length > 0, `${name}: id non-empty`); + assert.ok(sources.has(rule.source), `${name}: known source (${rule.source})`); + assert.ok(rule.ref.startsWith("https://"), `${name}: ref is an https URL`); + assert.ok(rule.title.length > 0, `${name}: title non-empty`); + } + }); + + it("looks up a mapped check", () => { + const env = ruleForCheck(".env gitignored"); + assert.equal(env?.id, "CWE-538"); + assert.equal(env?.source, "cwe"); + + const audit = ruleForCheck("npm audit"); + assert.equal(audit?.id, "OWASP-A06"); + + const secrets = ruleForCheck("secrets scan"); + assert.equal(secrets?.id, "CWE-798"); + }); + + it("returns undefined for an unmapped or unknown check", () => { + assert.equal(ruleForCheck("license check"), undefined); // intentionally unmapped + assert.equal(ruleForCheck("does not exist"), undefined); + }); +}); diff --git a/src/rules/catalog.ts b/src/rules/catalog.ts new file mode 100644 index 00000000..ff9e3995 --- /dev/null +++ b/src/rules/catalog.ts @@ -0,0 +1,61 @@ +/** + * Rule citations for kit's deterministic checks. + * + * Each finding can carry a `RuleRef` pointing at the rule it enforces (CWE, + * OWASP Top 10, or a kit-native rule). This is a LOCAL, deterministic lookup + * with no network access. kit only maps the checks it actually implements, so + * the catalog stays bounded to the number of checks, not the full CWE/OWASP + * corpus. A check without a clear, defensible anchor carries no rule (the field + * is optional; a forced weak mapping is worse than none). + * + * Maintenance: this map is co-located with the checks it describes. When you add + * a security check, add its mapping here in the same change. Framework IDs (CWE, + * OWASP Top 10) are low-churn and pinned by ID, so the catalog does not rot. + */ + +export interface RuleRef { + /** Short display id, e.g. "CWE-798" or "OWASP-A06". */ + id: string; + source: "cwe" | "owasp" | "asvs" | "kit"; + /** Canonical reference URL. */ + ref: string; + title: string; +} + +const cwe = (n: number, title: string): RuleRef => ({ + id: `CWE-${n}`, + source: "cwe", + ref: `https://cwe.mitre.org/data/definitions/${n}.html`, + title, +}); + +const owasp = (num: string, slug: string, title: string): RuleRef => ({ + id: `OWASP-${num}`, + source: "owasp", + ref: `https://owasp.org/Top10/${slug}/`, + title, +}); + +/** + * Security check `name` (from check-security.ts `SecurityCheckResult.name`) to + * the rule it enforces. Intentionally unmapped (no single defensible anchor): + * "license check", "semgrep SAST" (an engine; its own findings carry their own + * citations), "requirements.txt" (presence, not a weakness). + */ +export const SECURITY_RULES: Record<string, RuleRef> = { + ".env gitignored": cwe(538, "Insertion of Sensitive Information into Externally-Accessible File or Directory"), + "secrets scan": cwe(798, "Use of Hard-coded Credentials"), + "npm audit": owasp("A06", "A06_2021-Vulnerable_and_Outdated_Components", "A06:2021 Vulnerable and Outdated Components"), + "pip-audit": owasp("A06", "A06_2021-Vulnerable_and_Outdated_Components", "A06:2021 Vulnerable and Outdated Components"), + "trivy container scan": owasp("A06", "A06_2021-Vulnerable_and_Outdated_Components", "A06:2021 Vulnerable and Outdated Components"), + "pinned versions": cwe(1104, "Use of Unmaintained Third Party Components"), + "package-lock.json": owasp("A08", "A08_2021-Software_and_Data_Integrity_Failures", "A08:2021 Software and Data Integrity Failures"), + "socket scan": owasp("A08", "A08_2021-Software_and_Data_Integrity_Failures", "A08:2021 Software and Data Integrity Failures"), + Ollama: cwe(668, "Exposure of Resource to Wrong Sphere"), + "Remote API": cwe(668, "Exposure of Resource to Wrong Sphere"), +}; + +/** Look up the rule a security check enforces, or undefined if unmapped. */ +export function ruleForCheck(name: string): RuleRef | undefined { + return SECURITY_RULES[name]; +}