From ab9cbfb9957320274479f6a4c4748c7864827048 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 21 Nov 2026 18:06:04 +0700 Subject: [PATCH] feat: secret scan before a commit and in CI scripts/secret-scan.mjs refuses secrets (token formats, private keys, JSON Web Tokens, database URLs with a password, filled secrets in configuration files) and local data files (env files, keys, databases, dumps). It never prints the value it found and needs only Node and Git. .githooks/pre-commit runs it on staged content once the clone sets core.hooksPath; the CI Lint job runs it over every tracked file. Seven tests run it for real in a temporary Git repository. Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_012ta9C9QGH3qLAAqc7fEucC --- .agents/HANDOFF.md | 7 +++ .githooks/pre-commit | 4 ++ .github/workflows/ci.yml | 4 ++ README.md | 3 + app/secret-scan.test.mjs | 81 ++++++++++++++++++++++++++ docs/security.md | 8 +++ docs/testing.md | 1 + docs/verification.md | 15 +++++ scripts/secret-scan.mjs | 123 +++++++++++++++++++++++++++++++++++++++ 9 files changed, 246 insertions(+) create mode 100755 .githooks/pre-commit create mode 100644 app/secret-scan.test.mjs create mode 100644 scripts/secret-scan.mjs diff --git a/.agents/HANDOFF.md b/.agents/HANDOFF.md index 4717afc..2297637 100644 --- a/.agents/HANDOFF.md +++ b/.agents/HANDOFF.md @@ -1,5 +1,12 @@ # HANDOFF +## 2026-11-21 - Secret scan before a commit and in CI (Claude) + +- Branch `chore/secret-scan-2026-11-21`, cut from `main` (`e8ca1ac`). Owner approved a pre-commit secret scan on 2026-11-21. +- New `scripts/secret-scan.mjs` (zero dependencies: Node and Git) refuses token formats, private keys, JSON Web Tokens, database URLs with a password, filled secrets in configuration files, and local data files by name. It never prints the value. `.githooks/pre-commit` runs it on staged content once a clone sets `git config core.hooksPath .githooks`; the CI Lint job runs it over every tracked file. +- New `app/secret-scan.test.mjs` (7 tests, RED first: all 7 failed before the script existed) runs the scanner in a temporary Git repository. +- Verified: `lint`, `typecheck` exit 0; `test` 70/70; scanner over the whole tree: no findings. NOT RUN: `build`, `deploy:dry-run` (no runtime file changed), `test:e2e`, live Vera. + ## 2026-11-21 - Capsule-local ignore tests (Claude) - Branch `fix/capsule-local-ignore-tests-2026-11-21`, cut from `main` (`bc8364e`). Test-only change in `app/env-contract.test.mjs`. diff --git a/.githooks/pre-commit b/.githooks/pre-commit new file mode 100755 index 0000000..8635faa --- /dev/null +++ b/.githooks/pre-commit @@ -0,0 +1,4 @@ +#!/bin/sh +# Refuses a commit that stages a secret or a local data file. +# Install once per clone: git config core.hooksPath .githooks +exec node "$(dirname "$0")/../scripts/secret-scan.mjs" --staged diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index fe5a342..5a3151f 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -37,6 +37,10 @@ jobs: - name: Run ESLint run: pnpm lint + # Refuses secrets and local data files in any tracked file; needs only Node and Git. + - name: Secret scan + run: node scripts/secret-scan.mjs + test: name: Unit tests runs-on: ubuntu-latest diff --git a/README.md b/README.md index 6ba081c..fddf81a 100644 --- a/README.md +++ b/README.md @@ -364,6 +364,9 @@ node scripts/pnpm.mjs run dev Open **http://127.0.0.1:4346**. +Recommended once per clone: `git config core.hooksPath .githooks`, so a commit that stages a secret or a local data +file is refused (`scripts/secret-scan.mjs`). + To run a local production build: ```bash diff --git a/app/secret-scan.test.mjs b/app/secret-scan.test.mjs new file mode 100644 index 0000000..8e1b2ab --- /dev/null +++ b/app/secret-scan.test.mjs @@ -0,0 +1,81 @@ +import assert from "node:assert/strict"; +import { spawnSync } from "node:child_process"; +import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { dirname, join } from "node:path"; +import { test } from "node:test"; +import { fileURLToPath } from "node:url"; + +// The scanner runs for real against a throwaway Git repository. Every "secret" below is assembled from pieces at +// run time, so this file holds no token-shaped text itself. +const script = join(dirname(fileURLToPath(import.meta.url)), "..", "scripts", "secret-scan.mjs"); +const gitEnv = Object.fromEntries(Object.entries(process.env).filter(([name]) => !name.startsWith("GIT_"))); +const git = (cwd, ...args) => spawnSync("git", args, { cwd, env: gitEnv, encoding: "utf8" }); +const gitInstalled = git(tmpdir(), "--version").status === 0; + +const privateKey = ["-----BEGIN", "PRIVATE KEY-----"].join(" "); +const githubToken = "ghp_" + "a1B2".repeat(9); +const databaseUrl = (password) => ["postgres", "://", "app", ":", password, "@", "db.internal:5432/app"].join(""); + +function scan(files, { stage = Object.keys(files), mode = ["--staged"] } = {}) { + const repo = mkdtempSync(join(tmpdir(), "secret-scan-")); + try { + git(repo, "init", "--quiet"); + for (const [path, text] of Object.entries(files)) { + mkdirSync(dirname(join(repo, path)), { recursive: true }); + writeFileSync(join(repo, path), text); + } + if (stage.length > 0) git(repo, "add", "--force", "--", ...stage); + const run = spawnSync(process.execPath, [script, "--root", repo, ...mode], { env: gitEnv, encoding: "utf8" }); + return { status: run.status, output: run.stdout + run.stderr }; + } finally { + rmSync(repo, { recursive: true, force: true }); + } +} + +test("a clean staged change passes", { skip: !gitInstalled && "git is not installed" }, () => { + const result = scan({ "src/app.mjs": "export const greeting = 'halo';\n", ".env.example": "API_KEY=\nDATABASE_URL=\n" }); + assert.equal(result.status, 0, result.output); +}); + +test("a staged token or private key is refused and never echoed", { skip: !gitInstalled && "git is not installed" }, () => { + const result = scan({ "notes.md": `first line\n${privateKey}\n`, "src/client.mjs": `const token = "${githubToken}";\n` }); + assert.equal(result.status, 1, result.output); + assert.match(result.output, /notes\.md:2 {2}private key block/); + assert.match(result.output, /src\/client\.mjs:1 {2}GitHub token/); + assert.ok(!result.output.includes(githubToken), "the token itself must not be printed"); +}); + +test("local env files, key files and database files are refused by name", { skip: !gitInstalled && "git is not installed" }, () => { + const result = scan({ ".env.local": "PORT=3000\n", "deploy/server.pem": "x\n", "data/local.sqlite": "x\n" }); + assert.equal(result.status, 1, result.output); + for (const path of [".env.local", "deploy/server.pem", "data/local.sqlite"]) assert.ok(result.output.includes(`${path} forbidden file`), path); +}); + +test("a database URL fails with a real-looking password and passes with a placeholder", { skip: !gitInstalled && "git is not installed" }, () => { + assert.equal(scan({ "docs/setup.md": `${databaseUrl("Zk7pQ2mW9x")}\n` }).status, 1); + assert.equal(scan({ "docs/setup.md": `${databaseUrl("postgres")}\n${databaseUrl("")}\n` }).status, 0); +}); + +test("a filled secret in a config file fails; an empty one, a hash and a marked example pass", { skip: !gitInstalled && "git is not installed" }, () => { + const value = "q7Rk2ZtM9vB4xL1nP8sD5wH3"; + assert.equal(scan({ "deploy/app.env": `SERVICE_API_KEY=${value}\n` }).status, 1); + const harmless = `SERVICE_API_KEY=\nSERVICE_TOKEN_HASH=${value}\nSERVICE_API_KEY=${value} # secret-scan:allow\n`; + assert.equal(scan({ "deploy/app.env": harmless }).status, 0); +}); + +test("--staged looks only at what is staged; the default mode looks at every tracked file", { skip: !gitInstalled && "git is not installed" }, () => { + const files = { "a.md": "fine\n", "b.md": `${privateKey}\n` }; + assert.equal(scan(files, { stage: ["a.md"] }).status, 0); + assert.equal(scan(files, { mode: [] }).status, 1); +}); + +test("outside a Git working tree it stops with exit code 2", () => { + const folder = mkdtempSync(join(tmpdir(), "secret-scan-nogit-")); + try { + const run = spawnSync(process.execPath, [script, "--root", folder], { env: { ...gitEnv, GIT_CEILING_DIRECTORIES: dirname(folder) }, encoding: "utf8" }); + assert.equal(run.status, 2, run.stdout + run.stderr); + } finally { + rmSync(folder, { recursive: true, force: true }); + } +}); diff --git a/docs/security.md b/docs/security.md index ddf191c..d6ff877 100644 --- a/docs/security.md +++ b/docs/security.md @@ -23,6 +23,14 @@ Assets, controls and known gaps. Data classes are in [`data.md`](data.md). `frame-ancestors 'none'`. - **No identity.** There is no login, role or session; nothing to authorise. +## Secret scan + +`scripts/secret-scan.mjs` refuses secrets (token formats, private keys, JSON Web Tokens, database URLs with a +password, filled secrets in configuration files) and local data files (env files, keys, databases, dumps). CI runs +it over every tracked file in the Lint job. To run it before each commit on your own clone, once: +`git config core.hooksPath .githooks`. It never prints the value it found. A deliberate, harmless example line can +carry the marker `secret-scan:allow`. + ## Known gaps and risks - The CSP allows `'unsafe-inline'` and `'unsafe-eval'` for scripts (Next.js and GSAP inline needs). diff --git a/docs/testing.md b/docs/testing.md index 7e19ce4..2756a8c 100644 --- a/docs/testing.md +++ b/docs/testing.md @@ -30,6 +30,7 @@ with no runtime relative imports. | `signal.test.mjs`, `handoff.test.mjs`, `tactile.test.mjs` | Activity cycle, carrier handoff, pointer placement | | `app/api/vera/chat/limit.test.mjs` | Daily limit with TTL, hashed IP only, fallback when store is down or absent | | `app/env-contract.test.mjs` | Every variable the site reads is in `.env.example` with no secret value; `.gitignore` blocks env files, databases, dumps and keys | +| `app/secret-scan.test.mjs` | `scripts/secret-scan.mjs` run for real in a temporary Git repository: a staged token, private key, filled secret, real-looking database password, local env file, key file or database file is refused and never echoed; placeholders, hashes and marked examples pass; `--staged` reads only the index | ## End-to-end (Playwright, Chromium) diff --git a/docs/verification.md b/docs/verification.md index e9f353e..80a249c 100644 --- a/docs/verification.md +++ b/docs/verification.md @@ -12,6 +12,21 @@ A change is acceptable when, from the capsule root: 3. Vera changes are exercised against a stub or closed upstream (no real Dify calls in tests); 4. the result is recorded here and in `.agents/HANDOFF.md`. +## 2026-11-21 — secret scan before a commit and in CI (Claude Fable 5.2) + +Branch `chore/secret-scan-2026-11-21`, cut from `main` (`e8ca1ac`). Linux, Node 24.22.3, pnpm 11.21.0. Adds +`scripts/secret-scan.mjs`, `.githooks/pre-commit`, `app/secret-scan.test.mjs` and a Secret scan step in the CI Lint +job. No runtime file changed. + +| Command | Exit | Result | +| --- | --- | --- | +| `node --test app/secret-scan.test.mjs` before the script existed | 1 | 7 of 7 failed (expected) | +| `lint`, `typecheck` | 0 | No findings | +| `test` | 0 | 70/70 | +| `node scripts/secret-scan.mjs` | 0 | every tracked file checked, no findings | + +NOT RUN: `build`, `deploy:dry-run`, `test:e2e`, live Vera. + ## 2026-11-21 — capsule-local ignore tests (Claude Fable 5.2) Branch `fix/capsule-local-ignore-tests-2026-11-21`, cut from `main` (`bc8364e`). Linux, Node 24.22.3, diff --git a/scripts/secret-scan.mjs b/scripts/secret-scan.mjs new file mode 100644 index 0000000..4c83770 --- /dev/null +++ b/scripts/secret-scan.mjs @@ -0,0 +1,123 @@ +#!/usr/bin/env node +// Secret scan for this capsule: stops secrets and local data files before they reach Git. +// node every tracked file under this capsule (CI) +// node --staged only what is staged for the next commit (.githooks/pre-commit) +// Exit 0 = clean, 1 = findings, 2 = could not run. A finding names the file, the line and the rule; the matched +// text is never printed. Zero dependencies: Node and Git only, and nothing outside this capsule is read. +// A line that has to stay can carry the marker "secret-scan:allow"; a path prefix listed in .secret-scan-allow +// (one per line, "#" for comments) is skipped. --root scans another working tree (used by the tests). +import { spawnSync } from "node:child_process"; +import { existsSync, readFileSync } from "node:fs"; +import { basename, dirname, join } from "node:path"; +import { fileURLToPath } from "node:url"; + +const args = process.argv.slice(2); +const staged = args.includes("--staged"); +const rootFlag = args.indexOf("--root"); +const root = rootFlag >= 0 ? args[rootFlag + 1] : join(dirname(fileURLToPath(import.meta.url)), ".."); + +const MAX_BYTES = 2 * 1024 * 1024; +const ALLOW_MARKER = "secret-scan:allow"; + +// Files that never belong in Git, whatever they contain. Matched against the file name. +const FORBIDDEN_FILES = [ + ["local env file", /^\.env(?:\.(?!(?:example|sample|template)$).+)?$/], + ["key or certificate file", /\.(?:pem|key|p12|pfx)$/i], + ["SSH private key", /^id_(?:rsa|ed25519)/], + ["database, dump or backup file", /\.(?:sqlite3?|db|dump|pgdump|bak|backup)$|\.sql\.gz$/i], + ["credentials file", /^(?:service-account|credentials).*\.json$/i], +]; + +// Formats that are secrets wherever they appear. +const TOKEN_RULES = [ + ["private key block", /-----BEGIN [A-Z ]*PRIVATE KEY-----/], + ["Anthropic or OpenAI key", /\bsk-(?:ant|proj|live)-[A-Za-z0-9_-]{16,}/], + ["Stripe live key", /\b[sr]k_live_[A-Za-z0-9]{16,}/], + ["Supabase secret key", /\bsb_secret_[A-Za-z0-9_-]{16,}/], + ["GitHub token", /\b(?:gh[pousr]_[A-Za-z0-9]{30,}|github_pat_[A-Za-z0-9_]{30,})/], + ["AWS access key", /\bAKIA[0-9A-Z]{16}\b/], + ["Google API key", /\bAIza[0-9A-Za-z_-]{35}\b/], + ["Slack token", /\bxox[abprs]-[0-9A-Za-z-]{10,}/], + ["JSON Web Token", /\beyJ[A-Za-z0-9_-]{20,}\.eyJ[A-Za-z0-9_-]{20,}\.[A-Za-z0-9_-]{10,}/], +]; + +const DATABASE_URL = /\b(?:postgres(?:ql)?|mysql|mariadb|mongodb(?:\+srv)?|rediss?|amqps?):\/\/[^\s:/@"'`]+:([^\s@/"'`]+)@/g; +const PLACEHOLDER = /^(?:postgres|password|passwd|pass|secret|example|changeme|change-me|user|username|test|dummy|x+|\*+|\.{3}|<.*>|\[.*\]|\$\{?[A-Za-z_][A-Za-z0-9_]*\}?|your[-_a-z]*)$/i; + +// NAME=value pairs are checked only in configuration-like files, where a long value next to a secret name is a secret. +const CONFIG_FILE = /^(?:\.env.*|.*\.(?:env|ya?ml|toml|ini|conf|cfg|properties|json|sh|ps1|service)|Dockerfile.*)$/i; +const ASSIGNED = /\b([A-Z][A-Z0-9_]*(?:SECRET|TOKEN|PASSWORD|PASSCODE|API_KEY|PRIVATE_KEY)[A-Z0-9_]*)["']?\s*[:=]\s*["']?([^\s"'#,]{20,})/g; +const NOT_A_SECRET_NAME = /_(?:HASH|FILE|ID|URL|DIR|PATH|NAME)$/; +const NOT_A_SECRET_VALUE = /^[$<{/.]|example|placeholder|changeme|your[-_]|x{6,}/i; + +function git(gitArgs) { + const result = spawnSync("git", gitArgs, { cwd: root, encoding: "buffer", maxBuffer: 256 * 1024 * 1024 }); + if (result.status !== 0) return null; + return result.stdout; +} + +function candidates() { + const listed = staged + ? git(["diff", "--cached", "--name-only", "--diff-filter=ACMR", "-z", "--relative"]) + : git(["ls-files", "-z"]); + if (listed === null) return null; + return listed.toString("utf8").split("\0").filter(Boolean); +} + +function contentOf(path) { + if (staged) return git(["show", `:./${path}`]); + const file = join(root, path); + return existsSync(file) ? readFileSync(file) : null; +} + +function allowedPrefixes() { + const file = join(root, ".secret-scan-allow"); + if (!existsSync(file)) return []; + return readFileSync(file, "utf8").split(/\r?\n/).map((line) => line.trim()).filter((line) => line && !line.startsWith("#")); +} + +function scanText(path, text) { + const findings = []; + const configFile = CONFIG_FILE.test(basename(path)); + text.split(/\r?\n/).forEach((line, index) => { + if (line.includes(ALLOW_MARKER)) return; + for (const [rule, pattern] of TOKEN_RULES) if (pattern.test(line)) findings.push(`${path}:${index + 1} ${rule}`); + for (const match of line.matchAll(DATABASE_URL)) { + if (!PLACEHOLDER.test(match[1])) findings.push(`${path}:${index + 1} database URL with a password`); + } + if (!configFile) return; + for (const match of line.matchAll(ASSIGNED)) { + const [, name, value] = match; + const looksReal = /[A-Za-z]/.test(value) && /[0-9]/.test(value) && !NOT_A_SECRET_VALUE.test(value); + if (!NOT_A_SECRET_NAME.test(name) && looksReal) findings.push(`${path}:${index + 1} value assigned to ${name}`); + } + }); + return findings; +} + +const files = candidates(); +if (files === null) { + console.error("secret-scan: could not list files; run it inside a Git working tree."); + process.exit(2); +} +const allowed = allowedPrefixes(); +const findings = []; +for (const path of files) { + if (allowed.some((prefix) => path === prefix || path.startsWith(prefix))) continue; + const forbidden = FORBIDDEN_FILES.find(([, pattern]) => pattern.test(basename(path))); + if (forbidden) { + findings.push(`${path} forbidden file: ${forbidden[0]}`); + continue; + } + const content = contentOf(path); + if (content === null || content.length > MAX_BYTES || content.subarray(0, 8000).includes(0)) continue; + findings.push(...scanText(path, content.toString("utf8"))); +} + +if (findings.length > 0) { + console.error(`secret-scan: ${findings.length} finding(s). Nothing was committed or printed in full.`); + for (const finding of findings) console.error(` ${finding}`); + console.error(`Remove the secret or the file. If a line is a deliberate, harmless example, add "${ALLOW_MARKER}" to it.`); + process.exit(1); +} +console.log(`secret-scan: ${files.length} file(s) checked${staged ? " (staged)" : ""}, no findings.`);