Files
gstack/lib/redact-engine.ts
caba78fefa v1.83.0.0 feat: Memorable recall bridge, opt-in and receipted (supersedes #2831) (#2836)
* feat: add optional Memorable workflow memory

(cherry picked from commit 6bd5d477b2)

* fix: refuse the second registration, and say what leaves the machine

Two things the first cut got wrong.

Memorable's own installer registers the same UserPromptSubmit hook, under its
own name and outside gstack's table. `memorable start`, `memorable setup` and
`memorable install-hooks` all do it, and that is the documented way to install
the CLI, so on most machines it is already there before gstack is asked.
Registering ours beside it ran the same command twice on every prompt: context
injected twice, and the session captured twice against the user's own
extraction allowance. `enable` now looks for it and refuses, naming the entry
and the file it lives in; `status` says who registered it rather than reporting
none. Matched on the command rather than on a tag, for the reason the hook
table already gives: Claude Code rewrites settings and private tags do not
survive it.

The removal instruction says to delete the entry by hand because Memorable has
no command that removes its own hook. `uninstall-hooks` is not a command in
0.5.18; it answers "unknown command".

The README said "Memorable, not gstack, owns the captured data and any network
access", which answers the question by pointing away from it. It now carries a
per-command table of exactly what leaves the machine, in the shape the adopted
gbrain section uses, and it is explicit that the hook makes no network call of
its own, that every row is the third-party CLI acting under its own consent,
and that `gstack-egress` will therefore not show any of it. Under it, the split
between what gstack pin-tests (the gating and the wiring) and what is
Memorable's claim (storage, sending, and what disable and forget erase).

The CHANGELOG entry is removed. This file has never carried an [Unreleased]
heading; every entry is a version and a date, written at release. The text is
in the pull request for whoever cuts the next one.

Three tests added: enable refuses and touches neither consent nor settings when
Memorable already holds the hook, status names that registration, and a foreign
UserPromptSubmit hook is not mistaken for Memorable's.

(cherry picked from commit e0899afa8c)

* docs: a guide for the Memorable bridge, in the gbrain-sync shape

README carries the section and the egress table; this is the page it links to
for anyone who wants the whole thing. Same shape as docs/gbrain-sync.md, which
is the closest thing in the repo: an optional integration whose interesting
questions are all about what leaves the machine and how to turn it off.

What it covers that the README cannot at that length: that the hook sees every
Claude Code prompt rather than only the ones a skill produced; that capture is
a separate consent from this bridge, so turning the bridge off does not turn
capture off; what to do when Memorable has already registered the hook itself,
which is the common case because its own installer does it; and why the hook
has no loud failure path.

The egress table is repeated here rather than linked, because the sentence it
is answering ("what does this send") is the one somebody arrives on this page
already asking.

Co-authored-by: Advaiyt Sane <advaiyt.sane@gmail.com>
Co-authored-by: Nikhil Krishnaswamy <krishnaswamynikhil@gmail.com>
(cherry picked from commit 5c108cc0f7)

* feat(settings-hook): identity-aware remove-source + read-only list-items

remove-source used to inspect only entries still carrying the
_gstack_source tag. Claude Code strips that tag when it rewrites
settings.json, so an off switch built on remove-source alone silently
no-oped on exactly the entries it was written for. Removal is now driven
by KNOWN_HOOKS identity for the requested source (tagged or not), keeps
the tagged-single-item legacy-stray rule, never touches another source's
items, and leaves entries with nothing of ours byte-identical.

list-items is the read-only view of the same identity table: one JSON
string literal per matching hook command, filters (--owned-by,
--command-regex as a JavaScript RegExp) applied inside the JS, empty
stdout for no match, and the mutating verbs' exit codes (1 usage, 3
unparseable settings, 4 unexpected shape) so callers can decide
mutations from its output without parsing raw command strings.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>

* feat(config): memorable_recall consent key (on|off, default off, reject-and-preserve)

The gstack-side gate for the Memorable UserPromptSubmit bridge. `on` lets
a Claude Code hook hand every prompt to a third-party binary, so the key
follows the codex_reviews rule: an invalid value is rejected and the
stored value kept, never coerced in either direction. Registered in all
four places gstack-config keeps in sync (annotated header, DEFAULTS
table, the set validator, and both enumeration loops). Memorable's own
capture consent (`memorable enable`) is a separate thing gstack never
sets.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>

* feat(hooks): memorable-user-prompt-hook.ts — consent gate, deny veto, HIGH-tier pre-scan, fail-closed receipt, trust envelope; runExternal in spawn-bin

The PR's hook exec'd the vendor binary with the full environment and
passed its stdout to Claude verbatim. It is now the house pattern: a
fail-open bash shim over a .ts twin that (1) gates on the memorable_recall
consent key, (2) skips repos whose trust policy is deny or read-only,
(3) scans the prompt (raw bytes and decoded string leaves) and refuses to
hand over a HIGH-tier credential shape, (4) writes a fail-closed egress
receipt naming the local executable it ran, (5) spawns the vendor in its
own process group with an allowlisted environment and group-kills it on
timeout, (6) accepts only a string additionalContext back, caps it at
8 KiB on a UTF-8 boundary and wraps it in the trust envelope, and (7)
records an `output-written` outcome after the stdout write completes.
One deadline clock (4.5 s) undercuts Claude Code's 5 s kill and bounds
both ledger writes through the new lockBudgetMs option on
writeReceipt/writeOutcome (default unchanged).

spawn-bin gains runExternal for external executables (detached group,
stderr drained, stdin EPIPE handled, stdout capped, win32 refused).
The wiring test pins the sink fail-closed and sweeps hosts/.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>

* fix(gstack-memorable): canonical hook path, no vendor consent, --timeout 5, identity-based status, verified disable, lifecycle lock

enable used to bake the hook path from whatever tree the CLI ran in and
to run the vendor's own `memorable enable` (its consent for storing AND
uploading session traces) before registering anything. It now resolves
the canonical install like setup does and refuses when that install does
not carry this bridge (version and hook-twin check), registers through
the canonical hook manager with --timeout 5, records gstack's own consent
in memorable_recall, never executes the vendor, and restores the captured
prior state if consent cannot be recorded. disable flips the gate first,
removes the entry by identity (tag or no tag), verifies both states and
reports partial failure instead of a blended success. status reads only:
resolution path, gate, registration by identity (gstack / vendor-own /
both / unknown), mismatch lines, receipt count, recent hook errors. enable
and disable serialise under a lock with stale takeover. Windows is
refused (TODOS.md D21). Exit codes mirror the hook manager (3/4/5).

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>

* fix(setup): --no-team sweep keeps the opt-in gstack-memorable hook

`./setup --no-team` finishes its teardown with `prune-stale --all`, which
removes every KNOWN_HOOKS item. The Memorable bridge hook is a
user-registered opt-in unrelated to team mode, exactly like verify-gate,
so it joins the sweep exclusion list. The verify-gate pin now accepts the
comma-extended list; a schema-aware case proves the exclusion keeps both
opt-ins (tagged or tag-stripped) while the uninstall sweep still removes
them.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>

* fix(uninstall): named gstack-memorable arm, vendor-consent notice, honest kept config

The identity sweep already removed the Memorable bridge hook as an
unnamed stray. It now has a named arm like every other source, so the
summary says what went, and says plainly that Memorable's own consent
(if the user granted it) is theirs to revoke. Under --keep-state the kept
config is set memorable_recall=off so it never claims a hook that is
gone. The canonical-paths pins cover the sixth KNOWN_HOOKS row and the
new uninstall source.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>

* feat(egress): memorable-recall row in gstack-egress grants

`gstack-egress grants` promises every standing consent in force with the
command that revokes it. The Memorable bridge's memorable_recall key is
one, so it gets a row: off by default, granted only when
`gstack-memorable enable` set it, revoked by `gstack-memorable disable`.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>

* docs(memorable): accurate bridge guide; README row, Docs table, privacy pointer; PROJECT_STRUCTURE

The README section becomes one row in the Standalone binaries table (the
shape every other binary uses) plus a Docs-table row and one Privacy
bullet saying that optional third-party bridges are off by default and
receipted. The guide now separates the two consents, says what gstack
hands to the vendor binary and what the receipt can and cannot attest,
attributes every statement about the vendor's network activity to the
vendor, describes the hook manager accurately (identity via KNOWN_HOOKS,
list-items vs list-sources, rollback is whole-file), states the Claude
Code hot-reload behaviour, adds a troubleshooting runbook, and keeps the
contributors' credit in the CHANGELOG idiom.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>

* chore(todos): Memorable bridge follow-ups

Filed from the CEO and eng reviews of the bridge fix-up: the generic
third-party hook seam, Windows support (deferred whole), the envelope
kind parameter, a vendor payload-minimization contract, a latency and
timeout revisit, resolver and canonical-root consolidation, a
non-interactive MEDIUM-tier redaction policy for hooks, and adopting
list-items at setup's plan-tune check.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>

* fix(settings-hook): list-items --owned-by with --command-regex intersects

When both filters are given, an item must satisfy both: owned by the
requested source AND matching the pattern. Before, the regex branch
skipped every owned row, so the combination could never match.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>

* fix(gstack-memorable): compat_check reads list-items output before grepping

Under pipefail, piping the probe straight into grep -q let a non-zero
probe exit mask the match, so a hook manager without list-items was
sometimes reported as compatible. Capture the output, then grep.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>

* test: coverage for the memorable bridge (remove-source regression for every KNOWN_HOOKS source)

- settings-hook: identity removal pinned for each source in KNOWN_HOOKS;
  list-items unknown flag and combined --owned-by/--command-regex
- gstack-memorable: enable/disable failure paths (lock give-up exit 5
  with the test-only lock timeout override, consent-write failures
  guarded by canRevokeWrites, canonical-version mismatch, no-bun status)
- hook: non-object JSON, missing cwd, non-ASCII bytes, held-open stdin,
  shim without bun, stripControl, resolveVendor, runExternal ENOENT
- egress-receipt: lockBudgetMs 0 and writeOutcome on garbage input
- uninstall: no memorable entry present reports nothing removed

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>

* docs(memorable): gbrain backend note and the settings-rewrite race

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>

* perf(redact-engine): line/col by binary search over a per-scan line index

lineColAt walked the input from offset 0 for every finding, so a match-dense
input (a pasted log full of emails and IPs) cost O(findings x bytes): 128 KiB
took ~400 ms and 900 KiB tens of seconds. The line starts are now indexed once
per scan, on the first finding, and each finding is a binary search.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>

* feat(gbrain-repo-policy-client): repoPolicyTier accepts a spawn timeout

The policy script spawn was fixed at 10 s, more than twice the memorable
hook's whole budget. Callers on their own deadline pass what they can afford;
a timeout reads as unreadable and polarity stays the caller's.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>

* fix(spawn-bin): runExternal resolves on the child's exit, keeps stdin errors advisory

- A vendor that exits 0 but leaves a background child holding its pipes was
  held to the deadline, group-killed and reported as a timeout with its
  answer dropped. 'exit' now starts a short stdout drain, then resolves with
  the real exit code and kills whatever still holds the group.
- EPIPE on the child's stdin (it answered before reading a large input) is
  reported as stdinError, separate from error, so a delivered answer is not
  classified as a spawn failure.
- Stdio streams are destroyed and the child unref'd on resolve so a straggler
  cannot pin the hook process; tail/grace/drain sizes are named constants.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>

* fix(hooks): memorable hook closes the review army's gaps

- Vendor failures are logged even with empty stderr (a silently hanging
  vendor taxed every prompt invisibly); the stderr tail is withheld when the
  redaction engine finds a credential or PII shape in it; hook-errors.log is
  created 0600.
- Trust-policy veto fails closed when git cannot run or answer in time (it
  read as 'no remote' before); the policy script spawn is bounded by the
  hook's clock; a payload cwd that is not a directory falls back.
- Each secret scan is admitted by the deadline clock (the engine's cost grows
  with match density); stdin is decoded once.
- The pre-spawn gate re-check logs a config failure instead of swallowing it;
  an incomplete stdin read is named as such, not as 'not JSON'.
- Carriage returns are stripped with the other controls.
- The vendor env allowlist adds the standard proxy, TLS and XDG variables so
  a vendor behind a corporate proxy or private CA still reaches its service.
- A stdin EPIPE on a delivered answer is recorded in the outcome, not treated
  as a spawn error.
- Stage caps and the truncation marker are named constants; a test-only
  GSTACK_MEMORABLE_TEST_BUDGET_MS can shorten (never widen) the budget.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>

* fix(gstack-memorable): lock staleness from the directory mtime; honest messages

- A contender that looked between the holder's mkdir and its ts write read a
  missing ts as 0, called the lock stale and reclaimed it; staleness now comes
  from the lock directory's own mtime (the settings-hook idiom).
- The ensure-event failure is no longer labelled 'warning'; the consent-write
  rollback message says what was actually kept; a removal that left no entry
  is reported on stdout, not as an error; receipts are counted from the
  filtered JSON array, not a formatting artefact; the resolution order and
  lock tuning are named once.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>

* fix(uninstall): memorable_recall goes off whether or not state is kept

gstack-config resolves its root through GSTACK_STATE_ROOT/GSTACK_HOME, which
can differ from the STATE_DIR uninstall removes; a full uninstall could leave
memorable_recall=on in a config that survived. Flipped only when currently on.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>

* test: pin the review-army fixes for the memorable bridge

Nonce-scoped orphan checks (the system-wide ps grep could see another
shard's sleeper); exit-with-lingering-grandchild; advisory stdin EPIPE;
withheld stderr; vendor timeout logged with empty stderr; CR stripping;
budget seam; rate-limit expiry and 0600 log; unreadable policy store fails
closed; file-as-cwd fallback; mtime-based lock staleness and the mkdir gap.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>

* docs(memorable): vendor environment allowlist and stderr policy; two follow-ups

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>

* fix(hooks): memorable hook second-pass review fixes

- Trust-policy lookup fails closed on any git failure that is not 'no such
  remote' or 'not a git repository' (a corrupt or unreadable .git/config and
  dubious ownership exit 128 and used to read as 'no remote').
- pickAdditionalContext takes the first complete top-level JSON object, so a
  vendor whose background helper appends a line to stdout (or prints a banner
  first) does not lose its answer.
- The hook-errors.log rate limiter keys on a stable string (a vendor's
  timestamped stderr no longer defeats it); the log is chmod 0600 on every
  append because sibling hooks create the same file without a mode.
- Scan admission is sized by payload bytes (scan() is uninterruptible).
- The receipt payload class is a stable token; the prose moved to the docs.
- Header, constants and comments match the behaviour (silent skips vs logged
  refusals; HIGH/MEDIUM withholding; STAGE_CAP_MS scope; runExternal in the
  spawn-bin header; the ledger lock budget doc).

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>

* fix(gstack-memorable): stale-lock takeover by atomic rename; comments match behaviour

Two contenders that both saw a stale lock could both reclaim it with rm -rf;
the settings-hook idiom (mv to a private name, exactly one winner) is used
instead. The hook-manager fallback comment now says every verb falls back.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>

* test: second-pass coverage for the memorable bridge

Policy lookup outcomes (plain dir, repo without policy, corrupt .git/config
fails closed); repoPolicyTier timeoutMs; line/col at line starts, after blank
lines, CRLF and first char; tolerant first-JSON-object parsing; keyed rate
limit; uninstall never creates a config just to say off and flips consent in
a GSTACK_STATE_ROOT outside the removed state dir.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>

* docs(memorable): silent skips vs logged refusals; payload class token; D21/D24 anchors

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>

* fix(hooks): memorable hook survives host termination and brace-bearing banners

- The bash shim runs bun as a job and forwards SIGTERM/SIGINT/SIGHUP (bash
  holds a signal until a foreground child exits); the .ts kills the in-flight
  vendor's process group on the way out (runExternal exposes the group kill
  through onSpawn), so a hook the host terminates cannot leave the vendor
  running with the prompt on its stdin.
- The tolerant stdout parser tries every complete top-level object (bounded)
  and takes the first carrying a string additionalContext, so a banner with
  braces or quotes, or a progress object, no longer costs the answer.
- git runs with LC_ALL=C and the not-a-repository check is anchored to the
  start of its message: a localized git or a repository path containing the
  phrase can no longer flip the lookup.
- The rate limiter remembers up to 32 live keys, so alternating failures cost
  two lines, not one per prompt.
- Unicode format characters (bidi overrides, zero-width spaces) are stripped
  from vendor text at egress; the zero-width joiner stays for emoji.
- A killed child (timeout, ENOBUFS) resolves on exit without the stdout drain,
  and the post-kill grace is 100 ms, so the timeout outcome fits the reserve.
- The ledger size warning, which the host discards from an exit-0 hook's
  stderr, is logged where status looks.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>

* fix(gstack-memorable): failed stale-lock takeover reaches the give-up; disable runs without gstack-config; status shows ledger size

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>

* test: host termination kills the vendor group; brace banners, decoys and format characters; non-reclaimable stale lock gives up; ledger line in status

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>

* docs(memorable): the vendor dies with a terminated hook

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>

* test: deterministic stdin EPIPE case for runExternal (child closes stdin, stays alive)

Under parallel shard load a child that merely exits fast raced the write and
the EPIPE was not always observed; closing the read end first makes it so.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>

* fix(hooks): outside-model review fixes for the memorable hook and runExternal

- Nothing in the vendor's process group outlives the call: the group is
  killed on every resolve, the clean 'close' path included (a helper the
  vendor forked with redirected stdio ran on unsupervised before).
- A child that already exited when the deadline fires keeps its result; the
  deadline only ends the drain instead of rewriting a completed exit as a
  timeout.
- The decoded-leaf scan reports when its node/depth bound cut the walk short
  and the hook refuses the hand-off as unscanned; object keys are scanned too.
- git for the trust-policy lookup runs without inherited GIT_* selectors
  (GIT_DIR, GIT_WORK_TREE, GIT_CONFIG_*), so it inspects the session's
  repository and no other; a host cancellation kills that git as well.
- An unmatched brace in a vendor banner no longer hides the answer after it.
- The stderr tail is scanned whole before it is cropped for the log, so a
  credential's prefix cannot be cropped away from its secret half.
- The vendor override reads an empty GSTACK_MEMORABLE_BIN as unset, exactly
  as bin/gstack-memorable does, so enable checks the binary the hook runs.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>

* fix(gstack-memorable): stale-lock reclaim checks the inode it judged and the owner's liveness; status reports a failed receipt query as unknown

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>

* fix(uninstall): revoke memorable_recall independently of the hook manager and name a failed revocation

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>

* test: group kill on clean close, walk exhaustion refused, GIT_DIR cannot bypass the deny, unmatched-brace banner, whole-tail scan, empty-override parity, uninstall revocation without the hook manager

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>

* docs(memorable): the process-group guarantee and its setsid boundary

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>

* chore(release): v1.83.0.0 — Memorable recall bridge, identity-aware hook removal, faster redaction line/col

CHANGELOG entry for the Memorable workflow-memory bridge (opt-in, off by
default, Claude Code only), the identity-aware remove-source and read-only
list-items in the hook manager, the memorable-recall egress sink, runExternal,
lockBudgetMs, and the binary-search line/col index in the redaction engine.
No migration. Contributed by @AdvaiytSane and @NIkhil-cmd-cmd (#2831).

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>

* test: stdin EPIPE observation is scheduling-dependent under shard load; pin the invariant instead

A delivered answer is never reclassified as a spawn error; when the EPIPE is
observed it is reported as stdinError. Whether it is observed before the
child's exit resolves the call is not something the test can force.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>

* docs: list the memorable-recall sink among the fail-closed egress sinks

CLAUDE.md and ARCHITECTURE.md enumerate the receipt sinks that refuse to
send when the ledger cannot be written; the Memorable bridge's per-prompt
hand-off is pinned fail-closed in test/egress-receipt-wiring.test.ts but
was missing from both lists.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>

* test: memorable bridge tests pass on a runner that enforces file modes; scanner-proof key fixture

- The consent-write-failure tests make the state dir read-only, which also
  blocked the bridge lock directory (exit 5 before the path under test);
  the locks dir is pre-created so only the consent write fails.
- The unreadable-store test leaves a 0600 directory behind (the policy
  script chmods the store path); cleanup restores the search bit and the
  suite's afterEach reopens directories before removing.
- The AWS-key-shaped fixture is built by concatenation, as every sibling
  test does, so the CI credential gate does not read it as a live key.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>

* fix(gstack-memorable): name an unwritable state directory when the lock cannot be created

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>

---------

Co-authored-by: AdvaiytSane <advaiyt.sane@gmail.com>
Co-authored-by: Nikhil Krishnaswamy <krishnaswamynikhil@gmail.com>
Co-authored-by: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-08 22:05:41 -07:00

619 lines
23 KiB
TypeScript
Raw Permalink Blame History

This file contains invisible Unicode characters
This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
/**
* redact-engine — pure scanning + auto-redaction over the shared taxonomy.
*
* No I/O. Deterministic. The CLI shim (`bin/gstack-redact`), the pre-push hook
* (`bin/gstack-redact-prepush`), and tests all import from here.
*
* Key behaviors (locked in /plan-eng-review + two Codex passes):
* - Normalization BEFORE matching (NFKC + strip zero-width + decode a small
* set of HTML entities) so Unicode-confusable / zero-width evasion fails.
* Findings map back to ORIGINAL offsets via an index map.
* - ReDoS safety: a hard input-size cap that fails CLOSED (oversize input
* returns a single synthetic HIGH "input too large to scan safely" finding,
* so callers block rather than skip). Patterns are linear-time (lint-tested).
* - NO visibility-based tier mutation. `repoVisibility` is recorded on each
* finding (drives sterner AUQ wording in the skill) but never promotes a
* MEDIUM to HIGH. (TENSION-2-followup.)
* - Placeholder suppression is per-matched-span.
* - Tool-attributed fences (``` ```codex-review ``` / ``` ```greptile ```)
* degrade credential findings to a non-blocking WARN — UNLESS the span is a
* live-format credential the doc-example heuristic can't excuse. No nonce,
* no trust exemption (the marker scheme was dropped as theater).
*/
import {
PATTERNS,
PATTERNS_BY_ID,
isPlaceholderSpan,
type RedactPattern,
type Tier,
type Category,
} from "./redact-patterns";
export type RepoVisibility = "public" | "private" | "unknown";
/** A WARN is a finding that does not block but is surfaced (tool-fence degrade). */
export type Severity = Tier | "WARN";
export interface Finding {
id: string;
tier: Tier;
/** Effective severity after tool-fence degrade. HIGH/MEDIUM/LOW or WARN. */
severity: Severity;
category: Category;
description: string;
/** 1-based line in the ORIGINAL (un-normalized) text. */
line: number;
/** 1-based column in the ORIGINAL text. */
col: number;
/** Safe-masked preview (never more than 4 leading chars of the secret). */
preview: string;
/** Whether this finding offers one-keystroke auto-redact (PII subset). */
autoRedactable: boolean;
/** Repo visibility at scan time — drives sterner AUQ wording, not the tier. */
repoVisibility: RepoVisibility;
/** True when degraded to WARN because it sat in a tool-attributed fence. */
toolFenceDegraded?: boolean;
}
export interface ScanOptions {
repoVisibility?: RepoVisibility;
/** Extra allowlist entries (exact strings) that suppress a matched span. */
allowlist?: string[];
/** The invoking user's own email (from `git config user.email`) — allowlisted. */
selfEmail?: string;
/**
* Emails already public in the repo (git log authors, package.json, CODEOWNERS).
* Suppressed for `pii.email` since they're not a new leak.
*/
repoPublicEmails?: string[];
/** Hard byte cap. Oversize input fails CLOSED. Default 1 MiB. */
maxBytes?: number;
}
export interface ScanResult {
findings: Finding[];
counts: { HIGH: number; MEDIUM: number; LOW: number; WARN: number };
repoVisibility: RepoVisibility;
/** True when the input-size cap tripped (caller should BLOCK). */
oversize: boolean;
}
const DEFAULT_MAX_BYTES = 1024 * 1024; // 1 MiB
const EMAIL_ALLOW_DOMAINS = [/@example\.(com|org|net)$/i, /@example\.[a-z]{2,}$/i];
const EMAIL_ALLOW_LOCALPARTS = [/^noreply@/i, /^no-reply@/i, /^donotreply@/i];
/**
* Hosts whose `git@<host>` is a git transport endpoint, never a person's
* mailbox. Matched EXACTLY — a domain that merely starts with "git"
* (gitmail.com) is a normal domain and must keep firing.
*/
const SSH_GIT_HOSTS = new Set([
"github.com",
"gitlab.com",
"bitbucket.org",
"ssh.dev.azure.com",
]);
// ── Normalization ─────────────────────────────────────────────────────────────
const ZERO_WIDTH = /[]/g;
const HTML_ENTITIES: Record<string, string> = {
"&amp;": "&",
"&lt;": "<",
"&gt;": ">",
"&quot;": '"',
"&#39;": "'",
"&apos;": "'",
};
/**
* Normalize text for matching while producing an index map back to the original.
* Returns the normalized string and a function mapping a normalized offset to
* the corresponding original offset.
*
* Strategy: walk the original char-by-char, applying NFKC per char, dropping
* zero-width chars, and expanding a small fixed set of HTML entities. Each
* emitted normalized char records the original offset it came from. This keeps
* the map exact for the transformations we apply (which are all local).
*/
export function normalizeWithMap(input: string): {
normalized: string;
map: number[];
} {
const out: string[] = [];
const map: number[] = [];
let i = 0;
while (i < input.length) {
// HTML entity expansion (fixed small set; longest first).
let matchedEntity = false;
for (const ent in HTML_ENTITIES) {
if (input.startsWith(ent, i)) {
const rep = HTML_ENTITIES[ent];
for (const ch of rep) {
out.push(ch);
map.push(i);
}
i += ent.length;
matchedEntity = true;
break;
}
}
if (matchedEntity) continue;
const ch = input[i];
if (ZERO_WIDTH.test(ch)) {
ZERO_WIDTH.lastIndex = 0;
i += 1;
continue;
}
ZERO_WIDTH.lastIndex = 0;
const norm = ch.normalize("NFKC");
for (const nch of norm) {
out.push(nch);
map.push(i);
}
i += 1;
}
// Sentinel so an offset == length maps to the original length.
map.push(input.length);
return { normalized: out.join(""), map };
}
// ── Offset → line/col on the ORIGINAL text ────────────────────────────────────
/** Start offset of every line, built once per scan and only when a finding needs it. */
function lineStarts(original: string): number[] {
const starts = [0];
for (let i = 0; i < original.length; i++) if (original[i] === "\n") starts.push(i + 1);
return starts;
}
/**
* Binary search over lineStarts: O(log lines) per finding. The previous walk
* from offset 0 per finding made a match-dense input (a pasted log full of
* emails and IPs) cost O(findings x bytes) — seconds for a few hundred KiB.
*/
function lineColAt(starts: number[], original: string, offset: number): { line: number; col: number } {
const at = Math.min(Math.max(0, offset), original.length);
let lo = 0;
let hi = starts.length - 1;
while (lo < hi) {
const mid = (lo + hi + 1) >> 1;
if (starts[mid] <= at) lo = mid;
else hi = mid - 1;
}
return { line: lo + 1, col: at - starts[lo] + 1 };
}
// ── Safe preview masking ──────────────────────────────────────────────────────
/** Show ≤4 leading chars, mask the rest. Never reconstructable. */
export function maskPreview(span: string): string {
const visible = span.slice(0, 4);
const masked = span.length > 4 ? "*".repeat(Math.min(span.length - 4, 8)) : "";
return `${visible}${masked}${span.length > 12 ? "…" : ""}`;
}
// ── Tool-attributed fence detection ───────────────────────────────────────────
const TOOL_FENCE_INFO = /^```(codex-review|greptile|eval|codex|tool-output)\b/;
/**
* Returns a sorted list of [start, end) offset ranges (in normalized text) that
* sit inside a tool-attributed fenced code block. Credential findings inside
* these ranges degrade to WARN (unless the doc-example heuristic says the span
* is live-format and must still block).
*/
function toolFenceRanges(normalized: string): Array<[number, number]> {
const ranges: Array<[number, number]> = [];
const lines = normalized.split("\n");
let offset = 0;
let inFence = false;
let fenceStart = 0;
for (const ln of lines) {
const isFenceMarker = ln.startsWith("```");
if (isFenceMarker) {
if (!inFence && TOOL_FENCE_INFO.test(ln)) {
inFence = true;
fenceStart = offset + ln.length + 1; // content starts after this line
} else if (inFence) {
ranges.push([fenceStart, offset]); // up to start of closing fence
inFence = false;
}
}
offset += ln.length + 1; // +1 for the \n
}
if (inFence) ranges.push([fenceStart, normalized.length]); // unterminated → still degrade its own body
return ranges;
}
function inRanges(offset: number, ranges: Array<[number, number]>): boolean {
for (const [s, e] of ranges) if (offset >= s && offset < e) return true;
return false;
}
/**
* Doc-example heuristic: a credential span inside a tool fence still BLOCKS if
* it looks like a LIVE credential (not an obvious placeholder/example). We only
* downgrade-to-WARN spans that are clearly illustrative.
*/
function isObviousDocExample(span: string): boolean {
return isPlaceholderSpan(span);
}
// ── Proximity check ───────────────────────────────────────────────────────────
function hasNear(
normalized: string,
matchStart: number,
matchEnd: number,
nearRegex: RegExp,
window: number,
): boolean {
const from = Math.max(0, matchStart - window);
const to = Math.min(normalized.length, matchEnd + window);
const slice = normalized.slice(from, to);
const re = new RegExp(nearRegex.source, nearRegex.flags.replace(/g/g, ""));
return re.test(slice);
}
// ── Email allowlist ───────────────────────────────────────────────────────────
/**
* True when the matched "email" is really the user@host of a git SSH remote.
*
* `pii.email` matches the `git@github.com` inside
* `git@github.com:org/repo.git` — a transport identity, not PII. This keys on
* the surrounding URL SHAPE, not on the `git` local part: allowlisting `git@`
* outright would also suppress a genuine address at a domain that merely
* begins with "git" (e.g. git@gitmail.com), turning a false positive into a
* false negative.
*
* Two accepted shapes:
* - scp-like `<user>@<host>:<path>` where the path ends in `.git`, for any
* host — this covers self-hosted remotes.
* - `git@<known-host>` for the major forges, whose bare form appears in docs
* and in `ssh -T git@github.com` connectivity checks with no path at all.
*/
/** Lookahead window for the scp-path suffix check — long enough for any real
* remote path, bounded so a pathological unbroken line can't grow the scan. */
const SSH_REMOTE_PATH_LOOKAHEAD_CHARS = 512;
function isSshGitRemote(email: string, text: string, spanStart: number): boolean {
const at = email.lastIndexOf("@");
if (at < 0) return false;
const local = email.slice(0, at).toLowerCase();
const host = email.slice(at + 1).toLowerCase();
// Major forges: `git@host`, with or without a trailing path.
if (local === "git" && SSH_GIT_HOSTS.has(host)) return true;
// Any host in `<user>@<host>:<path>.git` position. The path stops at
// whitespace or a quote so a trailing delimiter never defeats the suffix.
const rest = text.slice(
spanStart + email.length,
spanStart + email.length + SSH_REMOTE_PATH_LOOKAHEAD_CHARS,
);
const scp = /^:(?!\/)([^\s'"`<>]*)/.exec(rest);
if (scp && /\.git\/?$/.test(scp[1])) return true;
// ssh:// URL form: ssh://<user>@<host>/<path>.git
const before = text.slice(Math.max(0, spanStart - 16), spanStart);
if (/(?:git\+)?ssh:\/\/$/i.test(before)) {
const slash = /^\/([^\s'"`<>]*)/.exec(rest);
if (slash && /\.git\/?$/.test(slash[1])) return true;
}
return false;
}
function emailAllowed(
email: string,
opts: ScanOptions,
text: string,
spanStart: number,
): boolean {
const lower = email.toLowerCase();
if (opts.selfEmail && lower === opts.selfEmail.toLowerCase()) return true;
if (opts.repoPublicEmails?.some((e) => e.toLowerCase() === lower)) return true;
if (EMAIL_ALLOW_DOMAINS.some((re) => re.test(email))) return true;
if (EMAIL_ALLOW_LOCALPARTS.some((re) => re.test(email))) return true;
if (isSshGitRemote(email, text, spanStart)) return true;
return false;
}
// ── The scan ──────────────────────────────────────────────────────────────────
export function scan(input: string, opts: ScanOptions = {}): ScanResult {
const repoVisibility: RepoVisibility = opts.repoVisibility ?? "unknown";
let starts: number[] | null = null; // line index, built on the first finding
// #1824: ?? only catches null/undefined, not NaN or <= 0. A bad value
// (NaN from a malformed --max-bytes, or a negative) would make `byteLen >
// maxBytes` always false and silently disable the fail-closed oversize guard.
// Guardrail: any non-finite or non-positive value falls back to the default
// cap. The CLI is the layer that rejects bad args; this is belt-and-suspenders
// so the engine never silently runs uncapped.
const maxBytes =
Number.isFinite(opts.maxBytes) && (opts.maxBytes as number) > 0
? (opts.maxBytes as number)
: DEFAULT_MAX_BYTES;
// Fail CLOSED on oversize input. Check byte length BEFORE heavy work.
const byteLen = Buffer.byteLength(input, "utf8");
if (byteLen > maxBytes) {
const finding: Finding = {
id: "engine.input_too_large",
tier: "HIGH",
severity: "HIGH",
category: "secret",
description: `Input too large to scan safely (${byteLen} > ${maxBytes} bytes) — blocking fail-closed`,
line: 1,
col: 1,
preview: "",
autoRedactable: false,
repoVisibility,
};
return {
findings: [finding],
counts: { HIGH: 1, MEDIUM: 0, LOW: 0, WARN: 0 },
repoVisibility,
oversize: true,
};
}
const { normalized, map } = normalizeWithMap(input);
const fenceRanges = toolFenceRanges(normalized);
const allow = new Set(opts.allowlist ?? []);
const findings: Finding[] = [];
// Dedup by (id, original-offset) so overlapping global matches don't double-count.
const seen = new Set<string>();
for (const pat of PATTERNS) {
const re = new RegExp(pat.regex.source, withFlags(pat.regex.flags));
let m: RegExpExecArray | null;
while ((m = re.exec(normalized)) !== null) {
// Guard against zero-width matches looping forever.
if (m.index === re.lastIndex) re.lastIndex++;
const span = m[1] ?? m[0];
const spanStartInMatch = m[1] !== undefined ? m[0].indexOf(m[1]) : 0;
const normOffset = m.index + Math.max(0, spanStartInMatch);
// Per-span placeholder suppression.
if (isPlaceholderSpan(span)) continue;
if (allow.has(span)) continue;
// Pattern-specific validators (Luhn, entropy, RFC1918, etc).
if (pat.validate && !pat.validate(span, m)) continue;
// Proximity requirement.
if (
pat.nearRegex &&
!hasNear(normalized, m.index, m.index + m[0].length, pat.nearRegex, pat.nearWindow ?? 100)
) {
continue;
}
// Email allowlist (layered on top of the pattern).
if (pat.id === "pii.email" && emailAllowed(span, opts, normalized, normOffset))
continue;
const origOffset = map[Math.min(normOffset, map.length - 1)] ?? 0;
const key = `${pat.id}:${origOffset}`;
if (seen.has(key)) continue;
seen.add(key);
starts ??= lineStarts(input);
const { line, col } = lineColAt(starts, input, origOffset);
// Tool-fence degrade: only credential-category, only obvious doc examples.
let severity: Severity = pat.tier;
let toolFenceDegraded = false;
if (
pat.category === "secret" &&
inRanges(normOffset, fenceRanges) &&
isObviousDocExample(span)
) {
severity = "WARN";
toolFenceDegraded = true;
}
findings.push({
id: pat.id,
tier: pat.tier,
severity,
category: pat.category,
description: pat.description,
line,
col,
preview: maskPreview(span),
autoRedactable: !!pat.autoRedactable,
repoVisibility,
...(toolFenceDegraded ? { toolFenceDegraded } : {}),
});
}
}
// Stable order: by line, then col, then id.
findings.sort((a, b) => a.line - b.line || a.col - b.col || a.id.localeCompare(b.id));
const counts = { HIGH: 0, MEDIUM: 0, LOW: 0, WARN: 0 };
for (const f of findings) counts[f.severity] += 1;
return { findings, counts, repoVisibility, oversize: false };
}
function withFlags(flags: string): string {
let f = flags;
if (!f.includes("g")) f += "g";
if (!f.includes("m")) f += "m";
return f;
}
// ── Auto-redaction ────────────────────────────────────────────────────────────
export interface RedactResult {
body: string;
/** ASCII unified-diff preview of the substitutions. */
diff: string;
/** Findings that could NOT be auto-redacted (structural-corruption guard). */
skipped: Finding[];
}
/**
* Substitute redact tokens for the given finding ids, right-to-left so offsets
* stay valid. Refuses to redact a span that sits inside a structural token
* (markdown link target, JSON string value) — those fall back to `skipped` so
* the skill drops the user to manual edit rather than silently mangling output.
*/
export function applyRedactions(
input: string,
findingIds: string[],
opts: ScanOptions = {},
): RedactResult {
const ids = new Set(findingIds);
const { findings } = scan(input, opts);
const targets = findings
.filter((f) => ids.has(f.id) && f.autoRedactable)
.map((f) => ({ f, ...locateSpan(input, f) }))
.filter((t) => t.start >= 0);
// Right-to-left so earlier offsets remain valid after splicing.
targets.sort((a, b) => b.start - a.start);
const skipped: Finding[] = [];
const diffLines: string[] = [];
let body = input;
for (const t of targets) {
const pat = PATTERNS_BY_ID[t.f.id];
const token = pat?.redactToken ?? "<REDACTED>";
if (inStructuralToken(body, t.start, t.end)) {
skipped.push(t.f);
continue;
}
const before = lineContaining(body, t.start);
body = body.slice(0, t.start) + token + body.slice(t.end);
const after = lineContaining(body, t.start);
diffLines.push(`- ${before}`);
diffLines.push(`+ ${after}`);
}
return { body, diff: diffLines.reverse().join("\n"), skipped };
}
/**
* Patterns whose regex captures only a MARKER, not the secret payload itself
* (the PEM header line; the GCP JSON key prefix). Span replacement on these
* would redact the header and forward the key body — so redactFindingSpans
* drops the whole payload instead.
*/
const MARKER_ONLY_PATTERN_IDS = new Set(["pem.private_key", "gcp.service_account"]);
/**
* Replace EVERY finding's span with `<REDACTED-{id}>`, regardless of tier or
* autoRedactable. For machine egress surfaces (telemetry error_message,
* #1947) where structure preservation doesn't matter and fail-closed beats
* fidelity. Returns null — caller must drop the whole payload — when:
* - any finding's span cannot be located, or
* - any finding matched a marker-only pattern (PEM / GCP service-account
* JSON): their regexes capture the header, not the key material, so a
* span splice would leak the body that follows the marker.
* Overlapping spans (e.g. a Bearer token that is also a JWT) are coalesced
* before splicing so stale offsets never leave partial secret bytes behind.
* (Contrast applyRedactions, which is the interactive, autoRedactable-only,
* structure-preserving path.)
*/
export function redactFindingSpans(input: string, opts: ScanOptions = {}): string | null {
const { findings } = scan(input, opts);
if (findings.some((f) => MARKER_ONLY_PATTERN_IDS.has(f.id))) return null;
const targets = findings.map((f) => ({ f, ...locateSpan(input, f) }));
if (targets.some((t) => t.start < 0)) return null;
// Coalesce overlapping/touching ranges — splicing two intersecting spans
// independently applies a stale end offset to already-modified text and
// can leave trailing secret bytes in place.
targets.sort((a, b) => a.start - b.start);
const merged: Array<{ start: number; end: number; ids: string[] }> = [];
for (const t of targets) {
const last = merged[merged.length - 1];
if (last && t.start <= last.end) {
last.end = Math.max(last.end, t.end);
if (!last.ids.includes(t.f.id)) last.ids.push(t.f.id);
} else {
merged.push({ start: t.start, end: t.end, ids: [t.f.id] });
}
}
// Right-to-left so earlier offsets remain valid after splicing.
let body = input;
for (let i = merged.length - 1; i >= 0; i--) {
const m = merged[i];
body = body.slice(0, m.start) + `<REDACTED-${m.ids.join("+")}>` + body.slice(m.end);
}
return body;
}
function locateSpan(input: string, f: Finding): { start: number; end: number } {
// Re-derive the offset from line/col on the original text.
let offset = 0;
let line = 1;
while (line < f.line && offset < input.length) {
if (input[offset] === "\n") line++;
offset++;
}
offset += f.col - 1;
const pat = PATTERNS_BY_ID[f.id];
if (!pat) return { start: -1, end: -1 };
const re = new RegExp(pat.regex.source, withFlags(pat.regex.flags));
re.lastIndex = Math.max(0, offset - 2);
const m = re.exec(input);
if (!m) return { start: -1, end: -1 };
const span = m[1] ?? m[0];
const start = m.index + (m[1] !== undefined ? m[0].indexOf(m[1]) : 0);
return { start, end: start + span.length };
}
function inStructuralToken(body: string, start: number, end: number): boolean {
// Markdown link target: [text](...span...). The span may sit anywhere inside
// the parenthesized target (e.g. an email embedded in a URL). Walk backward
// from the span: if we reach `](` before hitting `)`/whitespace, and forward
// we reach `)` before whitespace, the span is inside a link target.
for (let i = start - 1; i >= 0; i--) {
const ch = body[i];
if (ch === ")" || ch === "\n" || ch === " " || ch === "\t") break;
if (ch === "(" && i > 0 && body[i - 1] === "]") {
for (let j = end; j < body.length; j++) {
const c = body[j];
if (c === " " || c === "\t" || c === "\n") break;
if (c === ")") return true;
}
break;
}
}
// JSON string value: "key": "...span..." — span is inside a quoted value.
const before = body.slice(Math.max(0, start - 80), start);
const after = body.slice(end, Math.min(body.length, end + 4));
if (/:\s*"$/.test(before) && /^"/.test(after)) return true;
return false;
}
function lineContaining(body: string, offset: number): string {
const start = body.lastIndexOf("\n", offset - 1) + 1;
let end = body.indexOf("\n", offset);
if (end === -1) end = body.length;
return body.slice(start, end);
}
// ── Exit-code helper for the CLI shim ─────────────────────────────────────────
/** 0 clean, 2 MEDIUM present (no HIGH), 3 HIGH present. WARN does not gate. */
export function exitCodeFor(result: ScanResult): 0 | 2 | 3 {
if (result.counts.HIGH > 0) return 3;
if (result.counts.MEDIUM > 0) return 2;
return 0;
}