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
7 changes: 7 additions & 0 deletions .agents/HANDOFF.md
Original file line number Diff line number Diff line change
@@ -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`.
Expand Down
4 changes: 4 additions & 0 deletions .githooks/pre-commit
Original file line number Diff line number Diff line change
@@ -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
4 changes: 4 additions & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
3 changes: 3 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
81 changes: 81 additions & 0 deletions app/secret-scan.test.mjs
Original file line number Diff line number Diff line change
@@ -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("<password>")}\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 });
}
});
8 changes: 8 additions & 0 deletions docs/security.md
Original file line number Diff line number Diff line change
Expand Up @@ -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).
Expand Down
1 change: 1 addition & 0 deletions docs/testing.md
Original file line number Diff line number Diff line change
Expand Up @@ -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)

Expand Down
15 changes: 15 additions & 0 deletions docs/verification.md
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
123 changes: 123 additions & 0 deletions scripts/secret-scan.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,123 @@
#!/usr/bin/env node
// Secret scan for this capsule: stops secrets and local data files before they reach Git.
// node <this file> every tracked file under this capsule (CI)
// node <this file> --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 <folder> 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.`);
Loading