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
8 changes: 8 additions & 0 deletions .agents/HANDOFF.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,13 @@
# HANDOFF

## 2026-11-21 - Review fixes for the secret scan and ignore rules (Claude)

- Branch `fix/review-findings-2026-11-21`, cut from `main` (`47b1b56`). An independent review of the day's work found no critical defect and six important ones; this branch fixes them.
- Scanner: adds the provider keys this site uses (Dify, OpenRouter, Resend, Clerk), URLs with a password (empty user, http basic auth), short, letters-only and lower-case secrets in configuration files, database dumps by header, data exports by name, UTF-16 text; names the files it could not read; the allow file must be tracked and exact, the marker must be a trailing comment, env files can never be allowed; a crash exits 2, not 1.
- Ignore rules: `*dump*.sql`, `*backup*.sql`, `backups/` and `dumps/` could hide a migration or a route; they are now narrowed and anchored. SQLite side files and `.envrc` are ignored. `.gitattributes` keeps the hook file LF.
- `app/env-contract.test.mjs` also sees `process.env['X']` and `const { X } = process.env`. CI runs the scan as the first step of the Lint job.
- Verified: the 12 scanner tests failed 9 of 12 on the old scanner and pass on the new one; `lint`, `typecheck` exit 0; `test` 75/75; scanner over the whole tree: no findings. NOT RUN: `build`, `deploy:dry-run`, `test:e2e`, live Vera.

## 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.
Expand Down
2 changes: 2 additions & 0 deletions .gitattributes
Original file line number Diff line number Diff line change
Expand Up @@ -38,3 +38,5 @@

# Diff drivers
*.md diff=markdown
# The commit hooks are shell scripts: they keep LF line endings on every platform.
/.githooks/* text eol=lf
8 changes: 4 additions & 4 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,10 @@ jobs:
- name: Checkout
uses: actions/checkout@v4

# First step: refuses secrets and data files in any tracked file. Needs only the runner's Node and Git.
- name: Secret scan
run: node scripts/secret-scan.mjs

- name: Setup pnpm
uses: pnpm/action-setup@v4
with:
Expand All @@ -37,10 +41,6 @@ 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
14 changes: 10 additions & 4 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -42,10 +42,16 @@ pnpm-debug.log*
*.bak
*.backup
*.sql.gz
*dump*.sql
*backup*.sql
backups/
dumps/
dump*.sql
*[-_.]dump.sql
backup*.sql
*[-_.]backup.sql
/backups/
/dumps/
*.sqlite-*
*.sqlite3-*
*.db-*
.envrc

# Keys and credential files
*.key
Expand Down
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -698,7 +698,7 @@ The following results distinguish **past recorded tests** from **checks performe
| <small><small>Install</small></small> | <small><small>**PASS — 20 Nov 2026 record**</small></small> | <small><small>`node scripts/pnpm.mjs install --frozen-lockfile`</small></small> | <small><small>Historical evidence in `docs/verification.md`.</small></small> |
| <small><small>Typecheck</small></small> | <small><small>**PASS — 20 Nov 2026 record**</small></small> | <small><small>`node scripts/pnpm.mjs run typecheck`</small></small> | <small><small>Not rerun for README revision.</small></small> |
| <small><small>Lint</small></small> | <small><small>**PASS — 20 Nov 2026 record**</small></small> | <small><small>`node scripts/pnpm.mjs run lint`</small></small> | <small><small>Not rerun for README revision.</small></small> |
| <small><small>Unit tests</small></small> | <small><small>**63/63 — 21 Nov 2026 record**</small></small> | <small><small>`node scripts/pnpm.mjs run test`</small></small> | <small><small>Does not cover full Vera widget / route.</small></small> |
| <small><small>Unit tests</small></small> | <small><small>**75/75 — 21 Nov 2026 record**</small></small> | <small><small>`node scripts/pnpm.mjs run test`</small></small> | <small><small>Does not cover full Vera widget / route.</small></small> |
| <small><small>Build</small></small> | <small><small>**PASS — 20 Nov 2026 record**</small></small> | <small><small>`node scripts/pnpm.mjs run build`</small></small> | <small><small>Not rerun for README revision.</small></small> |
| <small><small>Deployment dry-run</small></small> | <small><small>**PASS WITH LIMITATION — recorded**</small></small> | <small><small>`node scripts/pnpm.mjs run deploy:dry-run`</small></small> | <small><small>Secret-name check currently uses an empty list.</small></small> |
| <small><small>Playwright E2E</small></small> | <small><small>**24/24 — 9 Oct 2026 record**</small></small> | <small><small>`node scripts/pnpm.mjs run test:e2e`</small></small> | <small><small>Predates Vera; not rerun on this revision.</small></small> |
Expand Down
18 changes: 16 additions & 2 deletions app/env-contract.test.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,15 @@ function variablesReadByTheSite() {
const names = new Set();
for (const dir of RUNTIME_DIRS) {
for (const file of sourceFiles(join(root, dir))) {
for (const [, name] of readFileSync(file, 'utf8').matchAll(/process\.env\.([A-Z][A-Z0-9_]*)/g)) names.add(name);
const text = readFileSync(file, 'utf8');
for (const [, dotted, bracketed] of text.matchAll(/process\.env(?:\.([A-Z][A-Z0-9_]*)|\[["']([A-Z][A-Z0-9_]*)["']\])/g)) names.add(dotted ?? bracketed);
// const { A, B: alias } = process.env
for (const [, body] of text.matchAll(/\{([^{}]*)\}\s*=\s*process\.env\b/g)) {
for (const part of body.split(',')) {
const name = part.split(/[:=]/)[0].trim();
if (/^[A-Z][A-Z0-9_]*$/.test(name)) names.add(name);
}
}
}
}
return [...names].filter((name) => !PLATFORM_VARIABLES.has(name)).sort();
Expand Down Expand Up @@ -82,6 +90,11 @@ test('.gitignore keeps local env files, databases, dumps and keys out of Git', {
'.env.production',
'apps/web/.env',
'data.sqlite',
'local.db-wal',
'local.sqlite-journal',
'.envrc',
'dump.sql',
'prod-backup.sql',
'local.sqlite3',
'dev.db',
'prod.dump',
Expand All @@ -98,5 +111,6 @@ test('.gitignore keeps local env files, databases, dumps and keys out of Git', {
});

test('.gitignore still lets .env.example be committed', { skip: !gitInstalled && 'git is not installed' }, () => {
assert.deepEqual(ignoredByThisCapsule(['.env.example']), []);
// A migration or a route whose name merely contains "backup" or "dump" must not vanish from Git.
assert.deepEqual(ignoredByThisCapsule(['.env.example', 'db/migrations/0006_backup_codes.sql', 'app/backups/page.tsx', 'src/dumps/index.ts']), []);
});
121 changes: 96 additions & 25 deletions app/secret-scan.test.mjs
Original file line number Diff line number Diff line change
@@ -1,21 +1,24 @@
import assert from "node:assert/strict";
import { spawnSync } from "node:child_process";
import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
import { existsSync, 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 here = dirname(fileURLToPath(import.meta.url));
const script = [join(here, "..", "scripts", "secret-scan.mjs"), join(here, "secret-scan.mjs")].find(existsSync) ?? join(here, "..", "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 skip = git(tmpdir(), "--version").status !== 0 && "git is not installed";

const mix = (prefix, length) => prefix + "a1B2c3D4e5F6g7H8".repeat(8).slice(0, length);
const privateKey = ["-----BEGIN", "PRIVATE KEY-----"].join(" ");
const githubToken = "ghp_" + "a1B2".repeat(9);
const databaseUrl = (password) => ["postgres", "://", "app", ":", password, "@", "db.internal:5432/app"].join("");
const githubToken = mix("ghp_", 36);
const url = (scheme, user, password) => [scheme, "://", user, ":", password, "@", "db.internal:5432/app"].join("");
const longValue = mix("", 24);

function scan(files, { stage = Object.keys(files), mode = ["--staged"] } = {}) {
const repo = mkdtempSync(join(tmpdir(), "secret-scan-"));
Expand All @@ -32,49 +35,117 @@ function scan(files, { stage = Object.keys(files), mode = ["--staged"] } = {}) {
rmSync(repo, { recursive: true, force: true });
}
}
const status = (files, options) => scan(files, options).status;

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" });
test("a clean staged change passes", { skip }, () => {
const result = scan({ "src/app.mjs": "export const greeting = 'halo';\n", ".env.example": "API_KEY=\nDATABASE_URL=\n", "db/migrations/0006_backup_codes.sql": "create table backup_codes (id int);\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" }, () => {
test("a staged token or private key is refused and never echoed", { skip }, () => {
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" });
test("the provider keys these projects use are refused in any text file", { skip }, () => {
const keys = {
"Dify app key": mix("app-", 24),
"OpenAI or OpenRouter key": mix("sk-or-v1-", 48),
"Resend key": `${mix("re_", 8)}_${mix("", 24)}`,
"Stripe or Clerk secret key": mix("sk_test_", 40),
"webhook signing secret": mix("whsec_", 32),
};
for (const [rule, key] of Object.entries(keys)) {
const result = scan({ "lib/client.ts": `const key = "${key}";\n` });
assert.equal(result.status, 1, `${rule}: ${result.output}`);
assert.ok(result.output.includes(rule) && !result.output.includes(key), rule);
}
assert.equal(status({ "lib/client.ts": `const key = "sk-ant-${"x".repeat(24)}"; const cls = "app-shell";\n` }), 0, "placeholders and ordinary identifiers pass");
});

test("env files, key files, databases and data exports are refused by name", { skip }, () => {
const paths = [".env.local", ".envrc", "deploy/server.pem", "data/local.sqlite", "data/local.db-wal", "exports/rekap.xlsx", "exports/pasien.csv"];
const result = scan(Object.fromEntries(paths.map((path) => [path, "x\n"])));
assert.equal(result.status, 1, result.output);
for (const path of paths) assert.ok(result.output.includes(`${path} forbidden file`), path);
assert.equal(status({ "keys/id_rsa.pub": "ssh-rsa AAAA\n" }), 0, "a public key is not a secret");
});

test("a database dump is refused whatever it is called; a migration passes", { skip }, () => {
const dump = "--\n-- PostgreSQL database dump\n--\nCOPY public.patients (id, name) FROM stdin;\n";
const result = scan({ "exports/melinda_2026-11-21.sql": dump });
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);
assert.match(result.output, /melinda_2026-11-21\.sql:2 {2}database dump/);
assert.equal(status({ "db/migrations/0001_init.sql": "create table profile (user_id text primary key);\n" }), 0);
});

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 URL that carries a password fails; templates and placeholders pass", { skip }, () => {
for (const line of [url("postgres", "app", "Zk7pQ2mW9x"), url("rediss", "", "Zk7pQ2mW9x"), url("https", "deploy", "Zk7pQ2mW9x")]) {
assert.equal(status({ "docs/setup.md": `${line}\n` }), 1, line.split(":")[0]);
}
const harmless = [url("postgres", "postgres", "postgres"), url("postgres", "app", "<password>"), url("postgres", "${process.env.DB_USER}", "${process.env.DB_PASS}"), url("mysql", "%s", "%s")];
assert.equal(status({ "docs/setup.md": `${harmless.join("\n")}\n` }), 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("a filled secret in a config file fails, also short, letters-only or lower-case ones", { skip }, () => {
const filled = [
["deploy/app.env", `SERVICE_API_KEY=${longValue}\n`],
["deploy/app.env", `MEDIFY_PASSWORD=${["Rahasia", "2026"].join("-")}\n`],
["deploy/app.env", `CRON_SECRET=${"abcdefghijklmnopqrstuvwx"}\n`],
["deploy/app.env", `REVIEW_PASSCODE=${["482", "913"].join("")}\n`],
["deploy/config.yml", `api_key: "${longValue}"\n`],
["deploy/config.json", `{ "apiKey": "${longValue}" }\n`],
[".npmrc", `//registry.npmjs.org/:_authToken=${longValue}\n`],
];
for (const [path, text] of filled) assert.equal(status({ [path]: text }), 1, text.split(/[=:]/)[0]);
const harmless = [
"SERVICE_API_KEY=", `SERVICE_TOKEN_HASH=${longValue}`, "SERVICE_TOKEN_FILE=/run/secrets/token", "POSTGRES_PASSWORD=postgres",
"API_KEY=${{ secrets.API_KEY }}", "MAX_TOKENS=100000000", "TOKEN_TTL=360000000", `SERVICE_API_KEY=${longValue} # secret-scan:allow example`,
];
const result = scan({ "deploy/app.env": `${harmless.join("\n")}\n` });
assert.equal(result.status, 0, result.output);
assert.match(result.output, /1 line\(s\) allowed on purpose/);
});

test("the allow marker counts only as a trailing comment", { skip }, () => {
assert.equal(status({ "deploy/app.env": `SERVICE_API_KEY=${longValue}secret-scan:allow\n` }), 1);
});

test("the allow file must be tracked and exact, and can never allow an env file", { skip }, () => {
const files = { "data/sources.csv": "id,title\n1,UU\n", ".secret-scan-allow": "# reviewed: public list\ndata/sources.csv\n" };
assert.equal(status(files, { stage: ["data/sources.csv"] }), 1, "an untracked allow file does not count");
const allowed = scan(files);
assert.equal(allowed.status, 0, allowed.output);
assert.match(allowed.output, /1 path\(s\) and 0 line\(s\) allowed on purpose/);
assert.equal(status({ "data-private/x.csv": "a\n", ".secret-scan-allow": "data\n" }), 1, "a name is not a prefix");
assert.equal(status({ "data/x.csv": "a\n", ".secret-scan-allow": "data/\n" }), 0, "a folder ends with a slash");
assert.equal(status({ ".env.production": "PORT=1\n", ".secret-scan-allow": ".env.production\n" }), 1);
});

test("UTF-16 text is read, and files it cannot read are named", { skip }, () => {
const utf16 = Buffer.concat([Buffer.from([0xff, 0xfe]), Buffer.from(`${privateKey}\n`, "utf16le")]);
assert.equal(status({ "notes.txt": utf16 }), 1);
const result = scan({ "logo.bin": Buffer.from([1, 0, 2, 0, 3]) });
assert.equal(result.status, 0, result.output);
assert.match(result.output, /1 not read \(binary, link or over 20 MB\): logo\.bin/);
});

test("--staged looks only at what is staged; the default mode looks at every tracked file", { skip: !gitInstalled && "git is not installed" }, () => {
test("--staged looks only at what is staged; the default mode looks at every tracked file", { skip }, () => {
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);
assert.equal(status(files, { stage: ["a.md"] }), 0);
assert.equal(status(files, { stage: ["a.md"], mode: ["--staged\r"] }), 0, "a hook file saved with Windows line endings still means --staged");
assert.equal(status(files, { mode: [] }), 1);
});

test("outside a Git working tree it stops with exit code 2", () => {
test("it stops with exit code 2 when it cannot run", () => {
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);
const env = { ...gitEnv, GIT_CEILING_DIRECTORIES: dirname(folder) };
assert.equal(spawnSync(process.execPath, [script, "--root", folder], { env, encoding: "utf8" }).status, 2);
assert.equal(spawnSync(process.execPath, [script, "--root"], { env, encoding: "utf8" }).status, 2);
} finally {
rmSync(folder, { recursive: true, force: true });
}
Expand Down
24 changes: 19 additions & 5 deletions docs/security.md
Original file line number Diff line number Diff line change
Expand Up @@ -25,11 +25,25 @@ Assets, controls and known gaps. Data classes are in [`data.md`](data.md).

## 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`.
`scripts/secret-scan.mjs` needs only Node and Git and never prints the value it found.

- **Refuses:** known token formats (Dify, OpenAI and OpenRouter, Anthropic, Clerk and Stripe secret keys, Resend,
Supabase, GitHub, npm, AWS, Google, Slack, webhook signing secrets, JSON Web Tokens), private keys, URLs that carry
a password, filled secrets in configuration files (a name ending in `KEY`, `TOKEN`, `SECRET`, `PASSWORD` or
`PASSCODE`), database dumps by their header, and by name: env files, key files, databases and data exports
(spreadsheets, CSV and similar).
- **Cannot do:** tell real data from sample data inside an ordinary text, JSON or SQL file, or recognise a secret
that has no known shape. It is a net, not a proof; review still decides.
- **When it runs:** the CI Lint job runs it first, over every tracked file, on each push; that is after the push is
already public. To stop a secret before it leaves your machine, activate the hook once per clone:
`git config core.hooksPath .githooks`. Inside the monorepo, leave its own hooks path alone and call the script
from there.
- **Exceptions are visible:** a line may end with a comment holding `secret-scan:allow`; a tracked
`.secret-scan-allow` file may list exact paths or folders ending in `/`. Env files can never be listed. Every
exception used is counted in the output.

For blocking at GitHub itself, turn on secret scanning push protection in the repository settings; that is the
owner's switch and is independent of this script.

## Known gaps and risks

Expand Down
Loading
Loading