/** * sealed-guard — the sealed-output guard (field wave CD4), shared by the * managed pre-push hook (bin/gstack-redact-prepush) and the standalone * preflight `gstack-pregate sealed [--range ]`. * * A repo opts in with a `sealed` key in `.gstack/pregate.json`: * paths globs that may never be published (held-out sets, cells) * transcripts globs of per-cell transcripts * answer_markers regexes for a quoted sealed answer in added text * seed_patterns regexes for a sampling seed in added text * local_paths true: a local home path (/home//, /Users//) in added text * allow_paths globs exempt from the path rules (read from the base branch only; never folds case) * case_insensitive true: `paths` and `transcripts` match regardless of case * label_keys field names whose records may not also carry an identifier (lib/sealed-join.ts; off when empty) * identifier_keys field-name globs that count as identifiers (default DEFAULT_IDENTIFIER_KEYS) * visibility "public" | "private": the destination override (reviewed on the base branch) * * The publication boundary is every commit the push publishes: the local sha * minus everything the destination remote already has (`git rev-list * --not --remotes= ^`); a destination with no refs means * everything reachable. Path rules see every path a commit adds, renames or * copies, independent of content (binary, empty, add-then-delete); text rules * see each commit's added lines. The effective policy is the union of the * destination base branch's `sealed` and the pushed one (a push can tighten, * never relax); `allow_paths` exceptions come only from the base branch's * policy and remove path findings before waivers, which come only from the * base branch's `.gstack/sealed-allow.tsv` and must name the full commit sha. A malformed or unreadable policy refuses (fail * closed). Visibility: the base override, else a cache under the state root * (a `public` answer for 24 h, a `private` one for 1 h before it may * downgrade a refusal), else `gh repo view` (5 s); unknown counts as public. * Findings name file, line, rule and commit, never the matched text. * * Skipping (on when a base resolves; `--no-skip` turns it off): a listed * commit the destination already holds as an ancestor of `refs/pull//head`, * for a squash `(#n)` on the base since the merge-base (at most 50 refs, a * 20 s budget, fetched from the destination remote), is not rescanned, nor is * one whose own `git patch-id --verbatim` and diff equal a base commit's * since the merge-base (off above 2,000 base or 400 listed commits). A * landed patch skips only the path and text rules: `sealed.label_join` judges * the whole file at the commit, which the base may never have held. No * combined-diff matching; any lookup failure scans everything. */ import { spawnSync } from './spawn-sync'; import { createHash } from 'node:crypto'; import * as fs from 'node:fs'; import * as os from 'node:os'; import * as path from 'node:path'; import { sha256Hex, writeReceipt } from './egress-receipt'; import { containedRelative, globToRegExp } from './ship-policy'; import { DEFAULT_IDENTIFIER_KEYS, identifierKeyError, joinFindings, labelKeyError } from './sealed-join'; import { resolveStateRoot } from './state-root'; export const SEALED_CONFIG_PATH = '.gstack/pregate.json'; export const SEALED_ALLOW_PATH = '.gstack/sealed-allow.tsv'; export const VISIBILITY_OVERRIDE_KEY = 'sealed.visibility'; export type SealedRule = 'sealed.path' | 'sealed.transcript' | 'sealed.answer' | 'sealed.seed' | 'sealed.local_path' | 'sealed.label_join' | 'sealed.label_join_unchecked'; export interface SealedPolicy { paths: string[]; transcripts: string[]; answer_markers: string[]; seed_patterns: string[]; local_paths: boolean; allow_paths: string[]; case_insensitive: boolean; label_keys: string[]; identifier_keys: string[]; visibility?: 'public' | 'private' } export interface SealedFinding { rule: SealedRule; file: string; line?: number; commit: string; keys?: string[] } export type ExemptFinding = SealedFinding & { glob: string }; export interface AllowEntry { rule: string; path: string; sha: string; reason: string } export type Visibility = 'public' | 'private' | 'unknown'; const KEYS = ['paths', 'transcripts', 'answer_markers', 'seed_patterns', 'local_paths', 'allow_paths', 'case_insensitive', 'label_keys', 'identifier_keys', 'visibility']; const MAX_ENTRIES = 64; const MAX_REGEX = 256; const LOCAL_PATH_RE = /(?:^|[^A-Za-z0-9_.~-]|\$\{!?(?:[A-Za-z_][A-Za-z0-9_]*(?:\[[^\]\s]{0,64}\])?|[0-9]+|[@*#?$!-]):?-)(?:\/home\/[^/\s'"`]+\/|\/Users\/[^/\s'"`]+\/|[A-Za-z]:\\+Users\\+[^\\\s'"`]+\\)/; const PUBLIC_TTL_MS = 24 * 3600_000; const PRIVATE_TTL_MS = 3600_000; /** `: ` errors for a `sealed` value; empty when valid. Shared with lib/pregate/config.ts. */ export function sealedErrors(raw: unknown): Array<{ path: string; message: string }> { const errors: Array<{ path: string; message: string }> = []; if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return [{ path: 'sealed', message: `must be an object { ${KEYS.join(', ')} }` }]; const o = raw as Record; for (const k of Object.keys(o)) if (!KEYS.includes(k)) errors.push({ path: `sealed.${k}`, message: `unknown key; valid keys: ${KEYS.join(', ')} (if the key comes from a newer gstack, upgrade gstack on this machine)` }); const list = (key: string, check: (s: string) => string | null) => { if (!(key in o)) return; const v = o[key]; if (!Array.isArray(v) || v.some(s => typeof s !== 'string')) { errors.push({ path: `sealed.${key}`, message: 'must be an array of strings' }); return; } if (v.length > MAX_ENTRIES) errors.push({ path: `sealed.${key}`, message: `more than ${MAX_ENTRIES} entries` }); (v as string[]).forEach((s, i) => { const why = check(s); if (why) errors.push({ path: `sealed.${key}[${i}]`, message: `${JSON.stringify(s)} ${why}` }); }); }; const glob = (g: string) => { const why = containedRelative(g); if (why) return why; try { globToRegExp(g); return null; } catch (e: any) { return e.message; } }; const regex = (r: string) => { if (!r || r.length > MAX_REGEX) return `must be 1-${MAX_REGEX} characters`; try { new RegExp(r); return null; } catch (e: any) { return `is not a valid regex (${e.message})`; } }; const exception = (g: string) => { const name = g.split('/').pop()!; return glob(g) ?? (name.includes('**') || /^[*?]+(\.|$)/.test(name) ? 'has a wildcard file name, which would exempt whole directories or file types; name the file (e.g. **/sealed/*/MANIFEST.json)' : null); }; list('paths', glob); list('transcripts', glob); list('answer_markers', regex); list('seed_patterns', regex); list('allow_paths', exception); list('label_keys', labelKeyError); list('identifier_keys', identifierKeyError); for (const k of ['local_paths', 'case_insensitive']) if (k in o && typeof o[k] !== 'boolean') errors.push({ path: `sealed.${k}`, message: 'must be true or false' }); if ('visibility' in o && o.visibility !== 'public' && o.visibility !== 'private') errors.push({ path: 'sealed.visibility', message: 'must be "public" or "private"' }); return errors; } const GIT_TIMEOUT_MS = 120_000; function git(repoRoot: string, args: string[], input?: string, encoding: BufferEncoding = 'utf8'): { ok: boolean; out: string; err: string } { const r = spawnSync('git', args, { cwd: repoRoot, encoding, input, timeout: GIT_TIMEOUT_MS, maxBuffer: 256 * 1024 * 1024 }); return { ok: r.status === 0, out: r.stdout ?? '', err: (r.stderr ?? '').trim() }; } /** Test seams for the streamed reads: read size, git binary and timeout. */ export interface GitStreamOptions { chunkBytes?: number; bin?: string; timeoutMs?: number } type GitStdin = { text: string } | { file: string } | null; /** Runs git with stdout written to a private temp file, so no output size meets spawnSync's maxBuffer, and passes that file to `use` only after git exits 0. A spawn error, timeout, signal or non-zero exit throws `git