SLOPSHOPPER

secrets-veil

Masks secret values in tool results before the model reads them: named vendor variables, value-shape patterns, and high-entropy tokens. No reveal path.

guardtoaststatustimer
★ 298v0.0.9MITupdated 2026-10-25yonatangross/orchestkit/mods/secrets-veil
A shopper browsing a rack in a slop shop
Preview · a replayed session in a sandbox
claude · ~/work/app · secrets-veil
› fix the failing auth test and add an audit log call ╭────────────────────────╮ │ secrets-veil │ ● secrets-veil: masked 1 value in Bash, 35 bytes in, 24 bytes out; result 291 bytes before,│ masked 1 value in Bash │ ⏺ Read(src/auth.ts) ╰────────────────────────╯ ⎿ Read 6 lines ⏺ Update(src/auth.ts) ⎿ Added 2 lines, removed 1 line ⏺ Bash(bun test) ⎿ 3 pass, 1 fail ● Done. refresh now rejects expired claims and logs an audit event. ✻ Worked for 42s · done 4:20 PM ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── › ? for shortcuts ⚠ secrets-veil: 1 masked this session
README

secrets-veil

A Claude Code mod that masks secret values in tool results before the model reads them. It arms once per session and covers every tool result afterwards. There is no reveal path: once a value is covered, it stays covered for the session.

How it works

Three layers, checked on every tool result:

  1. Named masking. At session.start the mod reads 21 widely known vendor variable names with one literal $.env.get call site per name:

ANTHROPIC_API_KEY OPENAI_API_KEY GEMINI_API_KEY GOOGLE_API_KEY MISTRAL_API_KEY GROQ_API_KEY OPENROUTER_API_KEY HF_TOKEN GITHUB_TOKEN GH_TOKEN GITLAB_TOKEN NPM_TOKEN AWS_ACCESS_KEY_ID AWS_SECRET_ACCESS_KEY AWS_SESSION_TOKEN AZURE_OPENAI_API_KEY STRIPE_SECRET_KEY SLACK_BOT_TOKEN VERCEL_TOKEN CLOUDFLARE_API_TOKEN OP_SERVICE_ACCOUNT_TOKEN

A resolved value is kept only if it is at least 8 characters. Every occurrence of a kept value is masked in tool output.

  1. Value shapes. Vendor prefixes and markers: sk-ant-, ops_, ghp_, github_pat_, xoxb-, AKIA, Bearer (20 or more following characters), and PEM private key blocks.
  1. High entropy. A token of 20 or more characters from [A-Za-z0-9+/=_-] whose Shannon entropy is at or above 4.3 bits per character is masked. The threshold is chosen so that counting alone, not luck, protects git output: any hex string (a 40-char git sha, a 64-char hash) has entropy at most 4.0, a UUID at most 4.09, both below the bar always. Uniform random tokens over the same alphabet measured a median of 4.60 bits/char (200k samples, 2026-09-16). Ordinary words, paths and identifiers measured 2.9 to 4.0. Masked output never reveals length beyond an 8-bullet floor.

Tokens this layer skips (the named-value and prefix layers still run on them): a Subresource Integrity value (sha512-...), and since 0.0.8 a token that is exactly an Anthropic API id: toolu_01, srvtoolu_01, msg_01 or req_011C followed by 18 to 26 letters and digits. These ids are public request handles; 890 of 1000 generated toolu_ ids crossed the bar, so tool ids showed as bullets in transcripts and logs.

One exception: an image payload passes byte-equal. An image payload is one long high-entropy run, so masking it made the API reject every image Read. It passes only when all of these hold:

  • it sits in a real image block at the top of the tool's output: the Read tool's own shape { type: "image", file: { base64, type, ... } } (what tool.call sees on Claude Code 2.1.304) or the API block { type: "image", source: { type: "base64", media_type, data } }, as the output itself, an element of an output array, or an element of the output's content array. A look-alike deeper in a result is masked;
  • its media type is PNG, JPEG or GIF (an exact allowlist);
  • it is strict base64 under 16 million characters, and the WHOLE decoded file is a real image of its type, not only its framing: PNG with a valid IHDR, at least one IDAT, right CRCs and IEND at the end; JPEG with a quantization table, a frame header of nonzero size, a scan with data and EOI at the end; GIF with at least one image block of nonzero size and the trailer at the end. PNG pixel data must also inflate (bounded, 64 MiB) to exactly its expected rows, each with a legal filter byte. WebP is not on the list: its bitstream cannot be proven without a full decoder, so a WebP Read stays masked while the veil is on;
  • its metadata can be read: a PNG with compressed text (zTXt, or iTXt with compression on) is not exempt;
  • no named value appears in the decoded bytes (as Latin-1, UTF-8 or UTF-16LE) or in the base64 text, and no vendor shape (sk-ant-, AKIA, a PEM header, ...) appears in the decoded bytes. If one does, the whole result is withheld, never shown with corrupted image bytes. Every other field of the block is masked as usual.

What this exemption does not cover, in plain words:

  • The veil does not see inside the pixels. A secret drawn in the image reaches the model; text kept in metadata is checked for named values and vendor shapes only.
  • PDF reads stay masked. The API reads the text of a PDF, and the veil cannot, so a PDF payload is masked and a PDF Read fails while the veil is on.
  • Any producer of the same shape gets the same pass. The veil cannot tell a Read from another tool at this layer, so an image block of the same shape at the top of another tool's output passes under the same checks.

If zero named values resolve at session.start, the mod emits one $.ui.notice saying the veil is running on value patterns and entropy only. Silence is not allowed: an operator must know the named layer is empty.

It fails closed. A tool result is never returned unmasked. If a tool.call arrives before session.start has armed the veil (a mod enabled or hot-reloaded mid-session; on CC 2.1.282 a reload re-dispatches session.start about a second after "reloaded"), the mod arms itself on the spot with the same named reads. If those reads fail it falls back to value shapes and entropy alone, and if a result cannot be masked at all it is withheld with { deny } rather than shown. The same holds for a result, or a single value in it, that is larger than a fixed size cap, a value the veil cannot rebuild faithfully (a Buffer, a Map), and any failure the runtime sees in the hook: each is withheld, none is passed through.

Seeing it work

When a tool result had at least one value covered, the mod says so where you can see it (Claude Code shows each line with the plugin name in front):

  • a toast: masked 1 value in Bash;
  • a status line under the prompt: 3 masked this session;
  • the byte counts in the debug log only, via $.ui.log(text, { to: "debug" }): 40 bytes in, 24 bytes out (UTF-8 bytes of the covered values, then of the bullets that replaced them; a bullet is 3 bytes, at most 8 per value), plus the whole result's byte size before and after masking. Without to: "debug" a $.ui.log line lands in the transcript, and a per-secret byte length is a hint about the secret, so it stays out of anything a human or the transcript sees.

These lines carry counts only, never a value. Nothing is shown when nothing was masked. A refused toast or status never unmasks a result. Every awaited UI call has a deadline through $.clock.after (a mod has no ambient timers): 3 s for engine calls, 120 s for the copy question, so a stuck call never holds the masked result.

Copy to your clipboard (opt-in)

Opt in with SECRETS_VEIL_OFFER_COPY=1, and only when **no other installed mod hooks ui.copy, ui.* or ***. Claude Code dispatches ui.copy as a hookable event (wildcard hooks included) before the clipboard write, so any other installed mod on that event receives the raw value and could log it or send it on. This mod never passes the value to Claude; whether anything else sees it depends on the other mods you run.

With the flag set, a masked result also opens the Claude Code question dialog ($.ui.ask): "Copy the masked value to your clipboard? This mod sends it to the clipboard only, never to Claude; another installed mod that hooks clipboard events could still receive it." The answers are Copy to clipboard and Keep hidden. Copy to clipboard hands the first covered value to $.ui.copy (OSC 52 in the terminal) and nothing else: the tool result the model reads stays masked, and the question, the toast, the status line and this mod's log carry counts only. A missing dialog, a refused or timed-out copy, a question nobody answers within 120 s, or Keep hidden all leave the value covered. The option is off by default because a dialog on every masked result would be noise.

What a copy leaves behind, outside this mod:

  • Claude Code's own debug log records the copied value's length (for example $.ui.copy (secrets-veil): 40 chars, ... copied), never the value.
  • The clipboard keeps the value until something replaces it, and clipboard managers, pbcopy/pbpaste history tools and terminal multiplexer buffers (tmux, screen) may keep their own copies. Clear them if that matters.

Measured on CC 2.1.282 (2026-09-25): the model read 8 bullets, the debug log said $.ui.copy (secrets-veil): 40 chars, path native, OSC 52 written; copied, and the clipboard held 40 bytes.

What this mod deliberately does not do

  • No reveal to the model. There is no hover reveal, no /veil command, no ui.render, no ui.press, no command.register. A reveal path re-arms the secret one interaction away from the model and the transcript. The opt-in copy above goes to the human's clipboard only.
  • No network, no process, no storage. Negative pins: process.run, http.fetch and store.* are absent from the module. Its $.ui calls are notice, toast, status and log, each carrying counts, never a value, plus ask and copy when the copy offer is opted in; only copy ever receives a value. $.clock.after arms the UI deadlines.
  • No reuse of the unmasked run. Core 2.1.282 reuses a run's own messages when a tool.call answer names it by ref and its result is undefined or deep-equal. A masked answer always carries a changed result; one without a result has its ref dropped.
  • No names beyond the 21. The mod reads only the names listed above.

Why your own variable names are not listed

This is a public repository. A deployment's own variable names are sensitive even without values: they disclose infrastructure and client relationships. They cannot be listed in this public mod, and this mod does not read any config file to collect them.

A team that wants its own names masked should keep a private fork of this mod, in a private repository, that adds its own literal $.env.get call sites in hooks/register.ts. The validator records environment reads statically, so each name must appear as a string literal at its own call site. Do not commit that fork's name list anywhere public.

Layout

  • hooks/register.ts - session arming and result masking (the only I/O)
  • src/mask.ts - pure masking logic: table build, patterns, entropy
  • src/types.ts - shared types, no reveal surface
  • tests/register.test.ts - drives the shipped hook module
  • tests/mask.test.ts - pure unit tests, including the 5 ms / 1 MB budget

Verifying locally

cd mods/secrets-veil
npm ci
npx tsc --noEmit
claude plugin validate .
npx vitest run

Tests use synthetic values built in the test files and non-vendor names prefixed VEIL_TEST_. No real secret value or name appears in this repository.

Source 5 files
hooks/register.ts 584 lines
1/**
2 * Hook registration for secrets-veil (literal-only design).
3 *
4 * A secret that appears in a tool result is masked before the model reads it.
5 *
6 * Events:
7 * - session.start: read the 21 vendor variable names, one literal $.env.get
8 *   call site per name, and arm the mask table (named values + shape
9 *   patterns + high-entropy tokens). If zero named values resolve, emit one
10 *   $.ui.notice: the veil runs on value patterns and entropy only.
11 * - tool.call: run the tool via next(), then deep-mask every string in the
12 *   result (plain text, result.stdout, and any nested field). When at least
13 *   one value was masked, say so where the human can see it: one $.ui.toast
14 *   and one $.ui.status line with the count only. The UTF-8 byte counts
15 *   (bytes of the covered values in, bytes of the bullets out) go to the
16 *   debug log only ($.ui.log with { to: "debug" }), because a per-secret
17 *   byte length is itself a hint about the secret. Every awaited UI call has
18 *   a timeout, so a stuck dialog or engine call never holds the result.
19 *
20 * There is no reveal path: no ui.render, no ui.press, no command.register,
21 * no hover. Once covered, a value stays covered for the session.
22 * Negative pins: no process.run, no http.fetch, no store.*.
23 *
24 * The 21 names below are the widely known vendor variable names and are the
25 * only names this mod reads. A deployment's own variable names cannot be
26 * listed in a public mod; see README.md. The validator records env reads
27 * statically, so every read must be a string literal at its call site
28 * (measured: a variable argument is refused, probe B, rc=1, 2026-09-16).
29 */
30
31import { buildTable, mask, DEFAULT_PATTERNS } from "../src/mask.js";
32import { holdsSecret, validImage } from "../src/media.js";
33import type { DollarAPI, MaskTable, ToolCallEvent, ToolCallResult } from "../src/types.js";
34
35/** A named value shorter than this is not worth a table entry. */
36const MIN_NAMED_VALUE_LENGTH = 8;
37
38/** Synthetic id for the session.start notice (there is no toolUseId yet). */
39const NOTICE_ID = "secrets-veil";
40
41/** Module-scope state (per session): the armed mask table. */
42let table: MaskTable | null = null;
43
44/** Module-scope state (per session): values masked since session.start. */
45let maskedThisSession = 0;
46
47/** Module-scope state (per session): SECRETS_VEIL_OFFER_COPY=1 turns the copy offer on. */
48let offerCopy = false;
49
50/** The two answers the copy offer gives. */
51export const COPY = "Copy to clipboard";
52export const KEEP = "Keep hidden";
53
54/**
55 * The copy offer's question. It names the count and the tool, never a value:
56 * the question is drawn in the terminal and may be logged.
57 */
58export function copyQuestion(values: number, tool: string): string {
59  const which = values === 1 ? "the masked value" : `the first of ${values} masked values`;
60  return `secrets-veil covered a secret in ${tool}. Copy ${which} to your clipboard? This mod sends it to the clipboard only, never to Claude; another installed mod that hooks clipboard events could still receive it.`;
61}
62
63/** What one tool result's masking did, in counts and UTF-8 bytes. */
64export interface MaskStats {
65  /** Number of values covered. */
66  values: number;
67  /** UTF-8 bytes of the covered values. */
68  bytesIn: number;
69  /** UTF-8 bytes of the bullets that replaced them. */
70  bytesOut: number;
71}
72
73const encoder = new TextEncoder();
74
75/** UTF-8 byte length of a string. */
76export function utf8Bytes(text: string): number {
77  return encoder.encode(text).length;
78}
79
80/**
81 * Deep-mask every string in a tool result. Strings are masked in place in a
82 * fresh structure; numbers, booleans and nulls pass through untouched.
83 * Covers plain text results (result), structured results (result.stdout,
84 * result.stderr) and any nested field. Adds what it covered to stats.
85 */
86/** Most characters of string content one result may carry before it is withheld. */
87export const MAX_MASK_CHARS = 8_000_000;
88
89/**
90 * Longest single string handed to mask(). mask() is one synchronous call,
91 * so the time cap below cannot interrupt it; a string over this length is
92 * withheld before the call instead.
93 */
94export const MAX_STRING_CHARS = 1_000_000;
95
96/** Most milliseconds masking one result may take (well inside the hook's own budget). */
97export const MAX_MASK_MS = 4_000;
98
99/** Thrown when a result is too large, too slow, or of a shape the veil will not rebuild. */
100export class VeilRefusal extends Error {}
101
102/** Work budget shared by one maskDeep walk. */
103interface MaskBudget {
104  chars: number;
105  deadline: number;
106}
107
108/** A plain object or array: the only containers maskDeep rebuilds faithfully. */
109function isPlainContainer(value: object): boolean {
110  if (Array.isArray(value)) return true;
111  const proto = Object.getPrototypeOf(value);
112  return proto === Object.prototype || proto === null;
113}
114
115/**
116 * Where an image payload may pass unmasked: ONLY at the image block shapes a
117 * tool result really uses, and only at the top of the result (Codex XREVIEW
118 * HOLD 6288472542 on orchestkit#4801, finding 2). Anything that merely looks
119 * like one deeper in a structured result is masked like every other string.
120 *   - Read tool output (what tool.call sees on Claude Code 2.1.304, binary
121 *     `type:"image",file:{base64:...,type:...}`): { type: "image", file: { base64, type, ... } }
122 *   - API content block: { type: "image", source: { type: "base64", media_type, data } }
123 * Accepted as the result itself, an element of a result array, or an element
124 * of the result's `content` array. The payload must also pass validImage
125 * (whole-file structure, strict base64, Map allowlist) and hold no secret.
126 */
127type ImageSlot = { holder: "file" | "source"; key: "base64" | "data"; mediaType: unknown; data: unknown };
128
129function imageSlot(value: unknown): ImageSlot | null {
130  if (value === null || typeof value !== "object" || Array.isArray(value) || !isPlainContainer(value)) return null;
131  const block = value as Record<string, unknown>;
132  if (block.type !== "image") return null;
133  const file = Object.prototype.hasOwnProperty.call(block, "file") ? block.file : undefined;
134  if (file !== null && typeof file === "object" && !Array.isArray(file) && isPlainContainer(file)) {
135    const f = file as Record<string, unknown>;
136    if (Object.prototype.hasOwnProperty.call(f, "base64")) {
137      return { holder: "file", key: "base64", mediaType: f.type, data: f.base64 };
138    }
139  }
140  const source = Object.prototype.hasOwnProperty.call(block, "source") ? block.source : undefined;
141  if (source !== null && typeof source === "object" && !Array.isArray(source) && isPlainContainer(source)) {
142    const src = source as Record<string, unknown>;
143    if (src.type === "base64" && Object.prototype.hasOwnProperty.call(src, "data")) {
144      return { holder: "source", key: "data", mediaType: src.media_type, data: src.data };
145    }
146  }
147  return null;
148}
149
150/** Named values and vendor shapes of the armed table, for the in-image secret check. */
151function needlesOf(activeTable: MaskTable): { named: string[]; shapes: string[] } {
152  const named: string[] = [];
153  const shapes: string[] = [];
154  for (const entry of activeTable.entries) {
155    if (entry.type === "env") named.push(entry.value);
156    else shapes.push(entry.pattern);
157  }
158  return { named, shapes };
159}
160
161/**
162 * Mask one image block. A payload that passes every check is kept byte-equal;
163 * one that holds a secret withholds the WHOLE result (never corrupted bytes);
164 * one that fails a check is masked like any string. Every other field of the
165 * block is masked.
166 */
167function maskImageBlock(
168  block: Record<string, unknown>,
169  slot: ImageSlot,
170  activeTable: MaskTable,
171  covered: Set<string>,
172  budget: MaskBudget,
173): unknown {
174  const bytes = validImage(slot.mediaType, slot.data);
175  if (bytes === null) return maskDeep(block, activeTable, covered, budget);
176  const { named, shapes } = needlesOf(activeTable);
177  if (holdsSecret(bytes, slot.data as string, named, shapes)) {
178    throw new VeilRefusal("an image holds a masked value");
179  }
180  const out: Record<string, unknown> = {};
181  for (const [key, val] of Object.entries(block)) {
182    if (key !== slot.holder) {
183      out[key] = maskDeep(val, activeTable, covered, budget);
184      continue;
185    }
186    const inner: Record<string, unknown> = {};
187    for (const [k, v] of Object.entries(val as Record<string, unknown>)) {
188      inner[k] = k === slot.key ? v : maskDeep(v, activeTable, covered, budget);
189    }
190    out[key] = inner;
191  }
192  return out;
193}
194
195/**
196 * Mask what tool.call's next() returned: the wrapper { result, ... }. The
197 * tool's own output is wrapper.result; image slots are read there only.
198 * Every other key of the wrapper is masked with no exemption.
199 */
200export function maskResult(wrapper: unknown, activeTable: MaskTable, covered: Set<string>, budget: MaskBudget): unknown {
201  if (wrapper === null || typeof wrapper !== "object" || Array.isArray(wrapper) || !isPlainContainer(wrapper)) {
202    return maskDeep(wrapper, activeTable, covered, budget);
203  }
204  const out: Record<string, unknown> = {};
205  for (const [key, val] of Object.entries(wrapper as Record<string, unknown>)) {
206    out[key] = key === "result" ? maskPayload(val, activeTable, covered, budget) : maskDeep(val, activeTable, covered, budget);
207  }
208  return out;
209}
210
211/** Mask a tool's own output: image slots at its top only, then every other string. */
212function maskPayload(result: unknown, activeTable: MaskTable, covered: Set<string>, budget: MaskBudget): unknown {
213  const top = (value: unknown): unknown => {
214    const slot = imageSlot(value);
215    return slot === null
216      ? maskDeep(value, activeTable, covered, budget)
217      : maskImageBlock(value as Record<string, unknown>, slot, activeTable, covered, budget);
218  };
219  if (Array.isArray(result)) return result.map(top);
220  if (imageSlot(result) !== null) return top(result);
221  if (result !== null && typeof result === "object" && isPlainContainer(result)) {
222    const record = result as Record<string, unknown>;
223    if (Object.prototype.hasOwnProperty.call(record, "content") && Array.isArray(record.content)) {
224      const out: Record<string, unknown> = {};
225      for (const [key, val] of Object.entries(record)) {
226        out[key] = key === "content" ? (val as unknown[]).map(top) : maskDeep(val, activeTable, covered, budget);
227      }
228      return out;
229    }
230  }
231  return maskDeep(result, activeTable, covered, budget);
232}
233
234/** Every string masked, no exemption anywhere: the walk below the top of a result. */
235function maskDeep(value: unknown, activeTable: MaskTable, covered: Set<string>, budget: MaskBudget): unknown {
236  if (Date.now() > budget.deadline) {
237    throw new VeilRefusal("masking ran past its time cap");
238  }
239  if (typeof value === "string") {
240    if (value.length > MAX_STRING_CHARS) {
241      throw new VeilRefusal("a single value is longer than the masking cap");
242    }
243    budget.chars += value.length;
244    if (budget.chars > MAX_MASK_CHARS) {
245      throw new VeilRefusal("result is larger than the masking cap");
246    }
247    const masked = mask(value, activeTable);
248    for (const span of masked.spans) {
249      covered.add(value.slice(span.start, span.end));
250    }
251    return masked.text;
252  }
253  if (value !== null && typeof value === "object") {
254    // A Buffer, Map, Set or class instance would come back as a plain object
255    // the host may reject for shape, and a rejected answer leaves the
256    // original standing. Refuse it instead of rebuilding it wrong.
257    if (!isPlainContainer(value)) {
258      throw new VeilRefusal("result holds a value the veil cannot rebuild");
259    }
260    if (Array.isArray(value)) {
261      return value.map((item) => maskDeep(item, activeTable, covered, budget));
262    }
263    const out: Record<string, unknown> = {};
264    for (const [key, val] of Object.entries(value as Record<string, unknown>)) {
265      out[key] = maskDeep(val, activeTable, covered, budget);
266    }
267    return out;
268  }
269  return value;
270}
271
272/**
273 * Count the distinct values covered in one result. A tool result can carry
274 * the same output twice (a Bash result has it in stdout and in text), so a
275 * value is counted once however many fields it appeared in.
276 */
277export function statsOf(covered: Set<string>): MaskStats {
278  const stats: MaskStats = { values: 0, bytesIn: 0, bytesOut: 0 };
279  for (const value of covered) {
280    stats.values += 1;
281    stats.bytesIn += utf8Bytes(value);
282    stats.bytesOut += utf8Bytes("•".repeat(Math.min(8, value.length)));
283  }
284  return stats;
285}
286
287/**
288 * The toast line for one masked tool result (Claude Code prefixes the plugin
289 * name). Counts only: a byte length would leak the length of a secret.
290 */
291export function toastText(stats: MaskStats, tool: string): string {
292  const noun = stats.values === 1 ? "value" : "values";
293  return `masked ${stats.values} ${noun} in ${tool}`;
294}
295
296/** The debug-only line: the byte counts that prove the masking. */
297export function debugText(stats: MaskStats, tool: string, before: number, after: number): string {
298  return `${toastText(stats, tool)}, ${stats.bytesIn} bytes in, ${stats.bytesOut} bytes out; result ${before} bytes before, ${after} bytes after`;
299}
300
301/** A human answers the copy question; every other UI call is a quick engine call. */
302export const ASK_TIMEOUT_MS = 120_000;
303export const UI_TIMEOUT_MS = 3_000;
304
305/** What withTimeout resolves to when the call did not settle in time. */
306export const TIMED_OUT = Symbol("secrets-veil.timed-out");
307
308/**
309 * Run one UI call with a deadline from $.clock.after (a mod has no ambient
310 * timers). A synchronous throw becomes a rejection. If the clock itself is
311 * unavailable the call is awaited without a deadline.
312 */
313export async function withTimeout($: DollarAPI, call: () => unknown, ms: number): Promise<unknown> {
314  const pending = Promise.resolve().then(call);
315  let expire: (value: typeof TIMED_OUT) => void = () => undefined;
316  const timeout = new Promise<typeof TIMED_OUT>((resolve) => {
317    expire = resolve;
318  });
319  let timer: { cancel?: () => void } | undefined;
320  try {
321    timer = $.clock.after(ms, () => expire(TIMED_OUT));
322  } catch {
323    return pending;
324  }
325  try {
326    return await Promise.race([pending, timeout]);
327  } finally {
328    timer?.cancel?.();
329  }
330}
331
332/**
333 * Keep the engine from reusing the unmasked run. Core 2.1.282 compares a
334 * tool.call answer with the run it names by `ref` and reuses that run's own
335 * messages when `result` is undefined or deep-equal
336 * (Qyn=(e,n)=>e.deny===void 0&&(e.result===void 0||e.result===n.result||Ln(e.result)===Ln(n.result))).
337 * A masked answer with a `result` differs, so keeping `ref` is safe and keeps
338 * the run's metadata. A masked answer WITHOUT `result` would be reused
339 * unmasked, so its `ref` is dropped.
340 *
341 * An errored run (`isError: true`) carries the error text as `result`, a
342 * string. Core schema-checks a changed answer's `result` against the tool's
343 * output shape, so a masked error string fails as "does not match its output
344 * shape" and the model never reads the error (measured on 2.1.309: guard
345 * denials and failed commands alike). A masked error is answered as `{ deny }`
346 * with the masked text instead, which the model reads as the tool's error.
347 */
348export function answerFor(masked: unknown, changed: boolean): unknown {
349  if (!changed || masked === null || typeof masked !== "object") return masked;
350  const answer = masked as Record<string, unknown>;
351  if (answer.isError === true) {
352    return { deny: errorText(answer) };
353  }
354  if ("ref" in answer && answer.result === undefined) {
355    const { ref: _unmaskedRun, ...rest } = answer;
356    return rest;
357  }
358  return masked;
359}
360
361/** The masked error as the model should read it: `text`, else a string `result`, else the result as JSON. */
362function errorText(answer: Record<string, unknown>): string {
363  if (typeof answer.text === "string" && answer.text.length > 0) return answer.text;
364  if (typeof answer.result === "string" && answer.result.length > 0) return answer.result;
365  const json = answer.result === undefined ? undefined : JSON.stringify(answer.result);
366  return json !== undefined && json.length > 0 ? json : WITHHELD;
367}
368
369/**
370 * Offer the human a copy of the first covered value. The value goes to
371 * $.ui.copy and nowhere else: not the tool result, not a toast, not the log.
372 * Any refusal (no dialog, no clipboard) leaves the value covered.
373 */
374async function offerToCopy($: DollarAPI, covered: Set<string>, tool: string): Promise<void> {
375  const [first] = covered;
376  // No presence check: the validator allows $ members only as calls; a missing
377  // ask or copy throws and the catch leaves the value covered.
378  if (first === undefined) return;
379  let answer: unknown = KEEP;
380  try {
381    // A timed-out question counts as Keep hidden.
382    answer = await withTimeout($, () => $.ui.ask(copyQuestion(covered.size, tool), [COPY, KEEP]), ASK_TIMEOUT_MS);
383  } catch {
384    return;
385  }
386  if (answer !== COPY) return;
387  try {
388    const copied = (await withTimeout($, () => $.ui.copy({ text: first }), UI_TIMEOUT_MS)) as
389      | { isCopied: boolean; reason?: string }
390      | typeof TIMED_OUT;
391    const done = copied !== TIMED_OUT && copied.isCopied;
392    const reason = copied === TIMED_OUT ? "timed out" : (copied.reason ?? "no clipboard");
393    // No length in the toast: the length of a secret is a hint about it.
394    await withTimeout(
395      $,
396      () =>
397        $.ui.toast(
398          done
399            ? "copied to your clipboard; Claude still sees dots"
400            : `nothing copied (${reason}); the value stays covered`
401        ),
402      UI_TIMEOUT_MS
403    );
404  } catch {
405    // A refused copy leaves the value covered; masking is already done.
406  }
407}
408
409/**
410 * Read the 21 vendor names, one literal $.env.get call site per name (the
411 * validator records env reads statically). Keep a value only when it is at
412 * least MIN_NAMED_VALUE_LENGTH characters; a rejected read counts as absent.
413 */
414async function readNamed($: DollarAPI): Promise<Record<string, string>> {
415  const named: Record<string, string> = {};
416
417  // One literal call site per vendor name. Keep a value only when it is at
418  // least MIN_NAMED_VALUE_LENGTH characters; a rejected read counts as
419  // absent, never as a failure of the session.
420  const anthropicApiKey = await $.env.get("ANTHROPIC_API_KEY").catch(() => undefined);
421  if (anthropicApiKey && anthropicApiKey.length >= MIN_NAMED_VALUE_LENGTH) named.ANTHROPIC_API_KEY = anthropicApiKey;
422  const openaiApiKey = await $.env.get("OPENAI_API_KEY").catch(() => undefined);
423  if (openaiApiKey && openaiApiKey.length >= MIN_NAMED_VALUE_LENGTH) named.OPENAI_API_KEY = openaiApiKey;
424  const geminiApiKey = await $.env.get("GEMINI_API_KEY").catch(() => undefined);
425  if (geminiApiKey && geminiApiKey.length >= MIN_NAMED_VALUE_LENGTH) named.GEMINI_API_KEY = geminiApiKey;
426  const googleApiKey = await $.env.get("GOOGLE_API_KEY").catch(() => undefined);
427  if (googleApiKey && googleApiKey.length >= MIN_NAMED_VALUE_LENGTH) named.GOOGLE_API_KEY = googleApiKey;
428  const mistralApiKey = await $.env.get("MISTRAL_API_KEY").catch(() => undefined);
429  if (mistralApiKey && mistralApiKey.length >= MIN_NAMED_VALUE_LENGTH) named.MISTRAL_API_KEY = mistralApiKey;
430  const groqApiKey = await $.env.get("GROQ_API_KEY").catch(() => undefined);
431  if (groqApiKey && groqApiKey.length >= MIN_NAMED_VALUE_LENGTH) named.GROQ_API_KEY = groqApiKey;
432  const openrouterApiKey = await $.env.get("OPENROUTER_API_KEY").catch(() => undefined);
433  if (openrouterApiKey && openrouterApiKey.length >= MIN_NAMED_VALUE_LENGTH) named.OPENROUTER_API_KEY = openrouterApiKey;
434  const hfToken = await $.env.get("HF_TOKEN").catch(() => undefined);
435  if (hfToken && hfToken.length >= MIN_NAMED_VALUE_LENGTH) named.HF_TOKEN = hfToken;
436  const githubToken = await $.env.get("GITHUB_TOKEN").catch(() => undefined);
437  if (githubToken && githubToken.length >= MIN_NAMED_VALUE_LENGTH) named.GITHUB_TOKEN = githubToken;
438  const ghToken = await $.env.get("GH_TOKEN").catch(() => undefined);
439  if (ghToken && ghToken.length >= MIN_NAMED_VALUE_LENGTH) named.GH_TOKEN = ghToken;
440  const gitlabToken = await $.env.get("GITLAB_TOKEN").catch(() => undefined);
441  if (gitlabToken && gitlabToken.length >= MIN_NAMED_VALUE_LENGTH) named.GITLAB_TOKEN = gitlabToken;
442  const npmToken = await $.env.get("NPM_TOKEN").catch(() => undefined);
443  if (npmToken && npmToken.length >= MIN_NAMED_VALUE_LENGTH) named.NPM_TOKEN = npmToken;
444  const awsAccessKeyId = await $.env.get("AWS_ACCESS_KEY_ID").catch(() => undefined);
445  if (awsAccessKeyId && awsAccessKeyId.length >= MIN_NAMED_VALUE_LENGTH) named.AWS_ACCESS_KEY_ID = awsAccessKeyId;
446  const awsSecretAccessKey = await $.env.get("AWS_SECRET_ACCESS_KEY").catch(() => undefined);
447  if (awsSecretAccessKey && awsSecretAccessKey.length >= MIN_NAMED_VALUE_LENGTH) named.AWS_SECRET_ACCESS_KEY = awsSecretAccessKey;
448  const awsSessionToken = await $.env.get("AWS_SESSION_TOKEN").catch(() => undefined);
449  if (awsSessionToken && awsSessionToken.length >= MIN_NAMED_VALUE_LENGTH) named.AWS_SESSION_TOKEN = awsSessionToken;
450  const azureOpenaiApiKey = await $.env.get("AZURE_OPENAI_API_KEY").catch(() => undefined);
451  if (azureOpenaiApiKey && azureOpenaiApiKey.length >= MIN_NAMED_VALUE_LENGTH) named.AZURE_OPENAI_API_KEY = azureOpenaiApiKey;
452  const stripeSecretKey = await $.env.get("STRIPE_SECRET_KEY").catch(() => undefined);
453  if (stripeSecretKey && stripeSecretKey.length >= MIN_NAMED_VALUE_LENGTH) named.STRIPE_SECRET_KEY = stripeSecretKey;
454  const slackBotToken = await $.env.get("SLACK_BOT_TOKEN").catch(() => undefined);
455  if (slackBotToken && slackBotToken.length >= MIN_NAMED_VALUE_LENGTH) named.SLACK_BOT_TOKEN = slackBotToken;
456  const vercelToken = await $.env.get("VERCEL_TOKEN").catch(() => undefined);
457  if (vercelToken && vercelToken.length >= MIN_NAMED_VALUE_LENGTH) named.VERCEL_TOKEN = vercelToken;
458  const cloudflareApiToken = await $.env.get("CLOUDFLARE_API_TOKEN").catch(() => undefined);
459  if (cloudflareApiToken && cloudflareApiToken.length >= MIN_NAMED_VALUE_LENGTH) named.CLOUDFLARE_API_TOKEN = cloudflareApiToken;
460  const opServiceAccountToken = await $.env.get("OP_SERVICE_ACCOUNT_TOKEN").catch(() => undefined);
461  if (opServiceAccountToken && opServiceAccountToken.length >= MIN_NAMED_VALUE_LENGTH) named.OP_SERVICE_ACCOUNT_TOKEN = opServiceAccountToken;
462
463  return named;
464}
465
466/**
467 * The table of last resort: value shapes and entropy, no named values. Pure,
468 * no $ call, so it cannot be refused the way an env read can.
469 */
470function shapesOnlyTable(): MaskTable {
471  return buildTable([], {}, DEFAULT_PATTERNS, { entropy: true });
472}
473
474/**
475 * Arm the veil where session.start never did: a module enabled or reloaded
476 * mid-session can see tool.call before (or without) session.start. Measured
477 * on CC 2.1.282 (2026-09-26): a hot reload re-dispatches session.start about
478 * a second after "reloaded", so a call in that window found table === null
479 * and the old code returned the result UNMASKED. Named reads first; if they
480 * fail, shapes and entropy alone. Never null.
481 */
482async function armLazily($: DollarAPI): Promise<MaskTable> {
483  try {
484    const named = await readNamed($);
485    return buildTable(Object.keys(named), named, DEFAULT_PATTERNS, { entropy: true });
486  } catch {
487    // Pure and $-free; if even this throws, tool.call's guard answers { deny }.
488    return shapesOnlyTable();
489  }
490}
491
492/**
493 * Register the secrets-veil hooks.
494 */
495/** What on() returns on CC 2.1.282: a registration that takes one .catch. */
496export interface Registration {
497  catch(handler: (...args: unknown[]) => unknown): unknown;
498}
499
500/** The answer when anything goes wrong after the tool ran: withhold, never pass through. */
501export const WITHHELD = "secrets-veil could not mask this result, so it is withheld rather than shown unmasked.";
502
503export function register(on: (event: string, hook: unknown) => Registration, _options?: unknown): void {
504  on("session.start", async ($: DollarAPI, e: { cwd: string }, next: (ev: { cwd: string }) => Promise<unknown>) => {
505    const named = await readNamed($);
506    const names = Object.keys(named);
507    table = buildTable(names, named, DEFAULT_PATTERNS, { entropy: true });
508    maskedThisSession = 0;
509    // Off unless the human opts in: a dialog on every masked result would be noise.
510    const offer = await $.env.get("SECRETS_VEIL_OFFER_COPY").catch(() => undefined);
511    offerCopy = offer === "1";
512
513    // FAIL LOUD on an empty named list. Silence is not allowed: say plainly
514    // that only the value shapes and entropy are standing guard.
515    if (names.length === 0) {
516      try {
517        await withTimeout(
518          $,
519          () =>
520            $.ui.notice(
521              NOTICE_ID,
522              "secrets-veil: no named secret values resolved from the environment; " +
523                "the veil is running on value patterns and entropy only, with no named secrets."
524            ),
525          UI_TIMEOUT_MS
526        );
527      } catch {
528        // Notice refused; masking continues either way.
529      }
530    }
531    return next(e); // a session.start hook must answer (CC 2.1.282 skips a hook that returns nothing)
532  });
533
534  on("tool.call", async ($: DollarAPI, e: ToolCallEvent, next?: (ev: ToolCallEvent) => Promise<ToolCallResult>) => {
535    // First, let the tool execute.
536    const result = next ? ((await next(e)) ?? {}) : {};
537    // From here on nothing may fail open: on CC 2.1.282 a hook that fails
538    // after next(e) leaves the original (unmasked) result standing, so every
539    // failure below answers { deny } instead. The copy offer runs inside this
540    // block too, so a failure there withholds rather than passes through.
541    try {
542      if (!table) {
543        // A mod enabled or reloaded mid-session can see tool.call first.
544        table = await armLazily($);
545      }
546      const covered = new Set<string>();
547      const masked = maskResult(result, table, covered, { chars: 0, deadline: Date.now() + MAX_MASK_MS });
548      const stats = statsOf(covered);
549      if (stats.values > 0) {
550        maskedThisSession += stats.values;
551        const tool = typeof e?.tool === "string" && e.tool.length > 0 ? e.tool : "a tool result";
552        const line = toastText(stats, tool);
553        // Each UI call is best effort: a refused surface never unmasks or fails the result.
554        try {
555          await withTimeout($, () => $.ui.toast(line), UI_TIMEOUT_MS);
556        } catch {
557          // Toast refused (no surface, or a host without toasts); the result stays masked.
558        }
559        try {
560          await withTimeout($, () => $.ui.status(`${maskedThisSession} masked this session`), UI_TIMEOUT_MS);
561        } catch {
562          // Status refused; the result stays masked.
563        }
564        if (offerCopy) {
565          await offerToCopy($, covered, tool);
566        }
567        try {
568          // Byte counts go to the debug log only, never the transcript.
569          const debugLine = debugText(stats, tool, utf8Bytes(JSON.stringify(result)), utf8Bytes(JSON.stringify(masked)));
570          await withTimeout($, () => $.ui.log(debugLine, { to: "debug" }), UI_TIMEOUT_MS);
571        } catch {
572          // Debug log refused; the result stays masked.
573        }
574      }
575      return answerFor(masked, stats.values > 0);
576    } catch {
577      return { deny: WITHHELD };
578    }
579  })
580    // The runtime's own failure path (a throw it sees, or the hook overrunning
581    // its budget) also answers { deny }: the last resort, never pass-through.
582    .catch(() => ({ deny: WITHHELD }));
583}
584
src/mask.ts 606 lines
1// secrets-veil: mask.ts - pure secret masking logic
2// Reused from commit 30720692 (buildTable, mask, DEFAULT_PATTERNS, wouldMask)
3// with one new layer added: high-entropy token masking. The layer is opt-in
4// per table via buildTable options, so existing callers keep exact behavior.
5
6import type { MaskTable, MaskTableEntry, MaskSpan, MaskResult, EntropyConfig } from "./types";
7
8/**
9 * High-entropy layer constants.
10 *
11 * A token counts as a possible secret when it is at least
12 * ENTROPY_MIN_LENGTH characters from [A-Za-z0-9+/=_-] and its Shannon
13 * entropy per character is at or above ENTROPY_THRESHOLD.
14 *
15 * Why 4.3 bits per char:
16 * - Any string over a 16-symbol alphabet (hex) has entropy at most
17 *   log2(16) = 4.0, and a UUID (hex plus dash) at most log2(17) = 4.09.
18 *   Both are below 4.3 ALWAYS, by counting, not on average: a 40-char git
19 *   sha, a 64-char sha256 and every UUID can never be masked by this layer.
20 * - Measured on this machine (2026-09-16, 200k samples): a uniform random
21 *   32-char token over the 67-symbol veil alphabet has median entropy 4.60
22 *   bits/char (5th percentile 4.35), so most random tokens cross 4.3.
23 * - Ordinary lowercase words and camelCase identifiers measured 2.9 to 4.0
24 *   bits/char, below the threshold. Paths, branch names and URLs reach the
25 *   bar only when scored as one mixed-alphabet run, which the tokenizer rule
26 *   in mask() prevents: ordinary separator runs are split before scoring.
27 * The residual false negatives (very low diversity random tokens) are the
28 * safe direction: the veil misses some tokens rather than masking shas.
29 */
30export const ENTROPY_MIN_LENGTH = 20;
31export const ENTROPY_THRESHOLD = 4.3;
32export const ENTROPY_ALPHABET = "[A-Za-z0-9+/=_-]";
33
34/**
35 * Subresource Integrity value: public in every package-lock.json on the
36 * registry and in this repository, never a secret. A run that is exactly
37 * 'sha1-', 'sha256-', 'sha384-' or 'sha512-' followed by base64 (plus any
38 * padding) is exempt from the entropy layer entirely (FIX ROUND of #4189).
39 */
40export const SRI_VALUE_RE = /^sha(?:1|256|384|512)-[A-Za-z0-9+/=]+$/;
41
42/**
43 * Anthropic API id: a tool_use id (toolu_01, srvtoolu_01), a message id
44 * (msg_01) or a request id (req_011C), each followed by base62. These ids
45 * are public request handles shown in transcripts and logs, never
46 * credentials, yet 890 of 1000 generated toolu_ ids crossed the 4.3 bar
47 * (dogfood 2026-10-20). A token that is exactly one of these ids is exempt
48 * from the entropy layer only; the named-value and vendor-prefix layers
49 * still run on it.
50 */
51export const ANTHROPIC_ID_RE = /^(?:srvtoolu_01|toolu_01|msg_01|req_011C)[A-Za-z0-9]{18,26}$/;
52
53/** True when the entropy layer must skip this whole token. */
54function isEntropyExempt(value: string): boolean {
55  // First-character check before any regex: this runs on every scored run.
56  const c = value.charCodeAt(0);
57  if (c === 0x73 /* s */) {
58    return SRI_VALUE_RE.test(value) || ANTHROPIC_ID_RE.test(value);
59  }
60  if (c === 0x74 /* t */ || c === 0x6d /* m */ || c === 0x72 /* r */) {
61    return ANTHROPIC_ID_RE.test(value);
62  }
63  return false;
64}
65
66/**
67 * Minimum mean chunk length for a mixed-case segment to count as camelCase
68 * or PascalCase and therefore word-like (FIX ROUND B of HOLD 4189).
69 * Human compound identifiers chunk into 3+ character words (ReviewPR ->
70 * Review,PR mean 4; CTAOverlay -> CTA,Overlay mean 5), while random base64
71 * alternates case every 1 to 2 characters (mean chunk 1 to 2).
72 */
73export const CAMELCASE_MIN_MEAN_CHUNK = 3;
74
75const CAMEL_CHUNK_RE = /[A-Z]+(?![a-z])|[A-Z]?[a-z]+|[0-9]+/g;
76
77/**
78 * Mean chunk length of a camelCase/PascalCase segment, or 0 when the chunk
79 * regex does not tile the segment completely. Chunks are uppercase runs not
80 * followed by lowercase, optional single uppercase plus a lowercase run,
81 * and digit runs: ReviewPR -> Review,PR; CTAOverlay -> CTA,Overlay;
82 * aB3dE6fG -> a,B,3,d,E,6,f,G.
83 */
84export function camelChunkMeanLength(seg: string): number {
85  let covered = 0;
86  let count = 0;
87  for (const m of seg.matchAll(CAMEL_CHUNK_RE)) {
88    covered += m[0].length;
89    count++;
90  }
91  if (count === 0 || covered !== seg.length) return 0;
92  return seg.length / count;
93}
94
95/**
96 * Word-likeness of a separator-split segment (HOLD 4189, fix round 3).
97 *
98 * A segment is WORD-LIKE when it is 7 characters or fewer (short pieces
99 * cannot hide a secret on their own), or when it reads like a human word:
100 * letters of a single case (all lower or all upper), digits only, lowercase
101 * letters mixed with digits with no uppercase (hex, slugs), or a camelCase
102 * or PascalCase compound whose chunks average 3+ characters (FIX ROUND B:
103 * ReviewPR, ShowcaseDemo, CTAOverlay are identifier words, not secret
104 * bodies; masking docs/site/public/thumbnails/CIN-ReviewPR.png and
105 * orchestkit-demos/src/components/terminal-flow/CTAOverlay.tsx was a
106 * precision bug). It is RANDOM-LOOKING when it is 8+ characters mixing
107 * upper and lower case, or mixing upper case with digits, without long
108 * word chunks: that is the signature of base64url and base64 secret
109 * bodies, which never appear in paths, branch names or URLs.
110 *
111 * A segment containing any character outside [A-Za-z0-9] is neither and
112 * returns false, so a run holding one keeps its whole-run treatment.
113 */
114export function isWordLikeSegment(seg: string): boolean {
115  if (seg.length === 0) return true; // empty piece from a boundary split
116  if (seg.length <= 7) return true; // short segments are never random
117  let hasUpper = false;
118  let hasLower = false;
119  let hasDigit = false;
120  for (let i = 0; i < seg.length; i++) {
121    const ch = seg[i];
122    if (ch >= "a" && ch <= "z") {
123      hasLower = true;
124    } else if (ch >= "A" && ch <= "Z") {
125      hasUpper = true;
126    } else if (ch >= "0" && ch <= "9") {
127      hasDigit = true;
128    } else {
129      return false;
130    }
131  }
132  if (hasUpper && hasLower) {
133    // mixed case, 8+: word-like only as a camelCase/PascalCase compound
134    // (FIX ROUND B); random base64 alternates case too often to chunk long
135    return camelChunkMeanLength(seg) >= CAMELCASE_MIN_MEAN_CHUNK;
136  }
137  if (hasUpper && hasDigit) {
138    // upper case with digits, 8+: same chunk test (CTA2024 -> 3.5, word;
139    // Ab3dE6fG -> 1.7, random)
140    return camelChunkMeanLength(seg) >= CAMELCASE_MIN_MEAN_CHUNK;
141  }
142  return true;
143}
144
145/**
146 * Shannon entropy of a string, in bits per character, over its empirical
147 * character distribution. Empty strings have entropy 0.
148 */
149export function shannonEntropy(token: string): number {
150  if (token.length === 0) return 0;
151  const freq = new Map<string, number>();
152  for (const ch of token) {
153    freq.set(ch, (freq.get(ch) ?? 0) + 1);
154  }
155  let bits = 0;
156  for (const count of freq.values()) {
157    const p = count / token.length;
158    bits -= p * Math.log2(p);
159  }
160  return bits;
161}
162
163/**
164 * True when a standalone value crosses the entropy bar.
165 */
166export function isHighEntropyToken(token: string): boolean {
167  return (
168    token.length >= ENTROPY_MIN_LENGTH &&
169    shannonEntropy(token) >= ENTROPY_THRESHOLD
170  );
171}
172
173/**
174 * Build the mask table from named values and shape patterns.
175 * Called once at session.start; pure function for testability.
176 * @param envNames - list of VAR names whose values were read at session start
177 * @param envValues - map of name -> value from $.env.get at session start
178 * @param patterns - hardcoded shape patterns (sk-ant-, ghp_, etc.)
179 * @param options - set { entropy: true } to also scan for high-entropy tokens
180 * @returns MaskTable ready for mask() calls
181 */
182export function buildTable(
183  envNames: readonly string[],
184  envValues: Record<string, string>,
185  patterns: readonly string[],
186  options?: { entropy?: boolean }
187): MaskTable {
188  const entries: MaskTableEntry[] = [];
189
190  // Add env values >= 8 chars that are non-empty
191  for (const name of envNames) {
192    const value = envValues[name];
193    if (value && value.length >= 8) {
194      entries.push({
195        type: "env",
196        name,
197        value,
198        pattern: value, // exact match
199      });
200    }
201  }
202
203  // Add shape patterns (prefixes that indicate secrets)
204  for (const pattern of patterns) {
205    entries.push({
206      type: "pattern",
207      pattern,
208    });
209  }
210
211  const entropy: EntropyConfig | null = options?.entropy
212    ? { minLength: ENTROPY_MIN_LENGTH, thresholdBitsPerChar: ENTROPY_THRESHOLD }
213    : null;
214
215  return { entries, entropy };
216}
217
218/**
219 * Default secret patterns (prefixes and patterns).
220 * Vendor prefixes such as sk-ant-, ghp_, xoxb-, AKIA, Bearer, BEGIN PRIVATE KEY.
221 */
222export const DEFAULT_PATTERNS: readonly string[] = [
223  "sk-ant-",
224  "ops_",
225  "ghp_",
226  "github_pat_",
227  "xoxb-",
228  "sk_live_",
229  "rk_live_",
230  "AKIA",
231  "Bearer ",
232  "-----BEGIN ",
233];
234
235/** One raw match: a half-open range, plus the variable name for a named value. */
236interface MatchRecord {
237  start: number;
238  end: number;
239  name?: string;
240}
241
242/**
243 * The same set as the regex class \s (ECMAScript WhiteSpace plus
244 * LineTerminator), tested by char code: a regex call per character was
245 * the dominant cost on long inputs.
246 */
247function isSpaceCode(c: number): boolean {
248  return (
249    c === 0x20 || (c >= 0x09 && c <= 0x0d) || c === 0xa0 || c === 0x1680 ||
250    (c >= 0x2000 && c <= 0x200a) || c === 0x2028 || c === 0x2029 ||
251    c === 0x202f || c === 0x205f || c === 0x3000 || c === 0xfeff
252  );
253}
254
255/**
256 * Push a span when the value crosses the entropy bar (length floor and
257 * threshold). Shared by the whole-run and per-segment paths; the length
258 * check runs first so short values skip entropy scoring entirely (perf).
259 */
260function pushIfHighEntropy(
261  matches: Array<MatchRecord>,
262  start: number,
263  value: string,
264  entropy: EntropyConfig
265): void {
266  if (
267    value.length >= entropy.minLength &&
268    !isEntropyExempt(value) &&
269    shannonEntropy(value) >= entropy.thresholdBitsPerChar
270  ) {
271    matches.push({ start, end: start + value.length });
272  }
273}
274
275/**
276 * Score one '='-split piece of a run, from run[pieceStart] to run[pieceEnd].
277 * The piece splits at '/', '-' and '_' only when every resulting segment is
278 * word-like (isWordLikeSegment); otherwise the piece is scored whole. This
279 * is the round-3 rule that restored recall on base64url secret shapes
280 * (HOLD 5697167579) while keeping paths and branch names split.
281 */
282function scorePiece(
283  matches: Array<MatchRecord>,
284  absStart: number,
285  run: string,
286  pieceStart: number,
287  pieceEnd: number,
288  entropy: EntropyConfig
289): void {
290  const piece = run.slice(pieceStart, pieceEnd);
291  // An exempt piece (an Anthropic id) is skipped before the '_' split, which
292  // would otherwise score its base62 body as a segment on its own.
293  if (isEntropyExempt(piece)) return;
294  let segStart = -1;
295  for (let i = 0; i <= piece.length; i++) {
296    const ch = i < piece.length ? piece[i] : "/"; // sentinel flushes the tail
297    if (ch === "/" || ch === "-" || ch === "_") {
298      if (segStart !== -1 && !isWordLikeSegment(piece.slice(segStart, i))) {
299        // a random-looking segment: the whole piece stays unsplit
300        pushIfHighEntropy(matches, absStart, piece, entropy);
301        return;
302      }
303      segStart = -1;
304    } else if (segStart === -1) {
305      segStart = i;
306    }
307  }
308  // every segment word-like: score each on its own
309  segStart = -1;
310  for (let i = 0; i <= piece.length; i++) {
311    const ch = i < piece.length ? piece[i] : "/";
312    if (ch === "/" || ch === "-" || ch === "_") {
313      if (segStart !== -1) {
314        pushIfHighEntropy(matches, absStart + segStart, piece.slice(segStart, i), entropy);
315        segStart = -1;
316      }
317    } else if (segStart === -1) {
318      segStart = i;
319    }
320  }
321}
322
323/**
324 * Mask secrets in text, returning masked text and spans for UI overlay.
325 * Pure function; no I/O. Must complete in under 5 ms for 1 MB input.
326 * @param text - text to mask
327 * @param table - mask table from buildTable()
328 * @returns MaskResult with masked text and spans (original positions)
329 */
330export function mask(text: string, table: MaskTable): MaskResult {
331  const spans: MaskSpan[] = [];
332  let maskedText = text;
333
334  // Collect all matches with their positions
335  const matches: Array<MatchRecord> = [];
336
337  for (const entry of table.entries) {
338    if (entry.type === "env") {
339      // Exact match for env values
340      let searchPos = 0;
341      while (true) {
342        const idx = maskedText.indexOf(entry.value, searchPos);
343        if (idx === -1) break;
344        matches.push({
345          start: idx,
346          end: idx + entry.value.length,
347          name: entry.name,
348        });
349        // Every occurrence, overlapping ones included: a copy that starts
350        // inside another must not leave a fragment visible. indexOf keeps
351        // this linear; the spans are unioned below.
352        searchPos = idx + 1;
353      }
354    } else {
355      // Pattern prefix match
356      let searchPos = 0;
357      // One forward search for "-----END ": the nearest END at or after a
358      // BEGIN only moves forward, so a cached position (or "none left") is
359      // reused instead of re-searching from every BEGIN (quadratic on many
360      // BEGINs with no END).
361      let endMarkerAt = -2; // -2: not searched yet; -1: none after endSearchFrom
362      let endSearchFrom = 0;
363      while (true) {
364        const idx = maskedText.indexOf(entry.pattern, searchPos);
365        if (idx === -1) break;
366
367        // Determine the end of the secret
368        let end = idx + entry.pattern.length;
369
370        // For Bearer, extend to end of token (non-whitespace)
371        if (entry.pattern === "Bearer ") {
372          while (end < maskedText.length && !isSpaceCode(maskedText.charCodeAt(end))) {
373            end++;
374          }
375          // Require at least 20 chars for Bearer tokens
376          if (end - idx < 26) {
377            // "Bearer " (7) + 20+ chars
378            searchPos = idx + 1;
379            continue;
380          }
381        }
382
383        // For BEGIN ... PRIVATE KEY, find the END marker
384        if (entry.pattern === "-----BEGIN ") {
385          if (endMarkerAt === -2 || (endMarkerAt !== -1 && endMarkerAt < idx)) {
386            endSearchFrom = idx;
387            endMarkerAt = maskedText.indexOf("-----END ", idx);
388          }
389          const endMarker = endMarkerAt !== -1 && idx >= endSearchFrom ? endMarkerAt : -1;
390          if (endMarker !== -1) {
391            const finalDash = maskedText.indexOf("-----", endMarker + 10);
392            if (finalDash !== -1) {
393              end = finalDash + 5;
394            }
395          }
396        }
397
398        // For other patterns, extend to end of token (non-whitespace)
399        if (
400          entry.pattern !== "Bearer " &&
401          entry.pattern !== "-----BEGIN "
402        ) {
403          while (end < maskedText.length && !isSpaceCode(maskedText.charCodeAt(end))) {
404            end++;
405          }
406        }
407
408        matches.push({ start: idx, end });
409        // Resume at the end of this match, never one character later: any
410        // later prefix hit inside [idx, end) would end at the same run end,
411        // so it is already covered, and the overlap step below unions spans
412        // instead of dropping them. Restarting inside the run was quadratic.
413        searchPos = Math.max(end, idx + 1);
414      }
415    }
416  }
417
418  // High-entropy token layer (opt-in per table).
419  //
420  // Tokenizer rule (HOLD 4189, fix round 3): a run is scored WHOLE when it
421  // contains '+' anywhere, or '=' only as trailing padding, or when a
422  // separator split would NOT leave every segment word-like; otherwise it
423  // splits and each segment is scored on its own. A run matching
424  // SRI_VALUE_RE is skipped entirely.
425  //
426  // Why: '+' and '=' padding occur in base64 value runs (an AWS secret
427  // access key is 40 chars of [A-Za-z0-9/+], and standard base64 ends in
428  // '=') but never in path, branch or URL segments, so they mark a run as a
429  // value rather than a location. A mid-run '=' is the opposite: URLs like
430  // ?ref=<branch> put a branch name after '=' (#4189 FIX ROUND), so it
431  // always splits like a key=value boundary. Round 2 also split every '-'
432  // and '_' unconditionally, but those characters are ordinary alphabet in
433  // base64url, which is what JWTs, OpenAI project keys, Google keys and
434  // most modern tokens use: the split cut real secrets into segments under
435  // the 20-char floor and recall collapsed (measured in HOLD 5697167579:
436  // JWT 99.6% -> 13.8%, sk-proj- 100 -> 43.4). The character mix now
437  // decides: '-', '_' and '/' split only when every resulting segment is
438  // word-like (paths, branch names, slugs), and a run with any random-
439  // looking segment is scored whole (secrets). Both directions are pinned
440  // in tests/entropy-corpus.test.ts: the repo-output corpus (paths,
441  // branches, URLs, npm integrity lines) must mask 0 spans (mutation M5),
442  // and 500 seeded samples per real secret shape must mask at >= 98%
443  // (>= 95% for the two threshold-limited shapes) (mutation M4).
444  const entropy = table.entropy;
445  if (entropy) {
446    const tokenRe = new RegExp(`${ENTROPY_ALPHABET}{${entropy.minLength},}`, "g");
447    let m: RegExpExecArray | null;
448    while ((m = tokenRe.exec(maskedText)) !== null) {
449      const run = m[0];
450      if (SRI_VALUE_RE.test(run)) {
451        // public integrity hash, never a secret
452        continue;
453      }
454      if (run.indexOf("+") !== -1 || /^[^=]+=+$/.test(run)) {
455        // base64-like run: '+' anywhere, or '=' only as trailing padding;
456        // score it whole
457        pushIfHighEntropy(matches, m.index, run, entropy);
458      } else {
459        // ordinary run: a mid-run '=' always splits (key=value, round 2);
460        // each piece then splits at '/', '-', '_' only when every segment
461        // is word-like, else the piece is scored whole
462        let pieceStart = 0;
463        for (let i = 0; i <= run.length; i++) {
464          if (i === run.length || run[i] === "=") {
465            if (i > pieceStart) {
466              scorePiece(matches, m.index + pieceStart, run, pieceStart, i, entropy);
467            }
468            pieceStart = i + 1;
469          }
470        }
471      }
472    }
473  }
474
475  // Sort by start, longest first at a tie; skipped when the layers already
476  // produced ascending, non-tied starts (one pattern on a long input).
477  let ordered = true;
478  for (let k = 1; k < matches.length; k++) {
479    if (matches[k].start <= matches[k - 1].start) {
480      ordered = false;
481      break;
482    }
483  }
484  if (!ordered) matches.sort((a, b) => {
485    if (a.start !== b.start) return a.start - b.start;
486    return b.end - a.end; // longer matches first
487  });
488
489  // Union overlapping or touching matches. Dropping a match that starts
490  // inside an earlier one lost its tail whenever it reached further (a
491  // named value ending inside a prefix token, two overlapping named values,
492  // an entropy piece next to a prefix hit), leaving part of a secret
493  // visible. A merged span covers everything any layer matched.
494  const merged: Array<{ start: number; end: number; name?: string; names: number }> = [];
495  for (const match of matches) {
496    const last = merged[merged.length - 1];
497    if (last && match.start <= last.end) {
498      if (match.end > last.end) last.end = match.end;
499      if (match.name !== undefined && match.name !== last.name) last.names += 1;
500    } else {
501      merged.push({ start: match.start, end: match.end, name: match.name, names: match.name === undefined ? 0 : 1 });
502    }
503  }
504
505  // Build the masked text in one pass: slices and bullets joined once
506  // (per-span slice + concat + unshift was quadratic on many spans).
507  const parts: string[] = [];
508  let cursor = 0;
509  for (const span of merged) {
510    parts.push(text.slice(cursor, span.start));
511    parts.push("\u2022".repeat(Math.min(8, span.end - span.start)));
512    cursor = span.end;
513    spans.push({
514      start: span.start,
515      end: span.end,
516      value: text.slice(span.start, span.end),
517      // A span merged from several named values names none of them.
518      name: span.names === 1 ? span.name : undefined,
519    });
520  }
521  parts.push(text.slice(cursor));
522  maskedText = parts.join("");
523
524  return { text: maskedText, spans };
525}
526
527/**
528 * Check if a value would be masked (used for testing).
529 */
530export function wouldMask(value: string, table: MaskTable): boolean {
531  for (const entry of table.entries) {
532    if (entry.type === "env" && entry.value === value) {
533      return true;
534    }
535    if (entry.type === "pattern" && value.startsWith(entry.pattern)) {
536      return true;
537    }
538  }
539  // Same tokenizer rule as mask(): '+' anywhere or '=' as trailing padding
540  // means the value is a base64-like run and is scored whole. Otherwise a
541  // mid-run '=' always splits (round 2), and each piece splits at '/', '-'
542  // and '_' only when every segment is word-like (round 3), else the piece
543  // is scored whole. SRI values are public and never mask.
544  const entropy = table.entropy;
545  if (entropy) {
546    if (isEntropyExempt(value)) {
547      return false;
548    }
549    if (/[+]/.test(value) || /^[^=]+=+$/.test(value)) {
550      return (
551        value.length >= entropy.minLength &&
552        shannonEntropy(value) >= entropy.thresholdBitsPerChar
553      );
554    }
555    let pieceStart = 0;
556    for (let i = 0; i <= value.length; i++) {
557      if (i === value.length || value[i] === "=") {
558        if (i > pieceStart && !isEntropyExempt(value.slice(pieceStart, i))) {
559          const piece = value.slice(pieceStart, i);
560          let segStart = -1;
561          let allWordLike = true;
562          for (let j = 0; j <= piece.length; j++) {
563            const ch = j < piece.length ? piece[j] : "/";
564            if (ch === "/" || ch === "-" || ch === "_") {
565              if (segStart !== -1 && !isWordLikeSegment(piece.slice(segStart, j))) {
566                allWordLike = false;
567                break;
568              }
569              segStart = -1;
570            } else if (segStart === -1) {
571              segStart = j;
572            }
573          }
574          if (allWordLike) {
575            segStart = -1;
576            for (let j = 0; j <= piece.length; j++) {
577              const ch = j < piece.length ? piece[j] : "/";
578              if (ch === "/" || ch === "-" || ch === "_") {
579                if (segStart !== -1) {
580                  const seg = piece.slice(segStart, j);
581                  if (
582                    seg.length >= entropy.minLength &&
583                    shannonEntropy(seg) >= entropy.thresholdBitsPerChar
584                  ) {
585                    return true;
586                  }
587                  segStart = -1;
588                }
589              } else if (segStart === -1) {
590                segStart = j;
591              }
592            }
593          } else if (
594            piece.length >= entropy.minLength &&
595            shannonEntropy(piece) >= entropy.thresholdBitsPerChar
596          ) {
597            return true;
598          }
599        }
600        pieceStart = i + 1;
601      }
602    }
603  }
604  return false;
605}
606
src/media.ts 352 lines
1import { zlibInflate } from "./inflate.js";
2
3/**
4 * Image payloads that may pass the veil unmasked, and the checks they must pass.
5 *
6 * An image payload is one long high-entropy base64 run, so the entropy layer
7 * covered it and the API rejected every image Read (card
8 * image-read-fault-2026-10-18). A payload passes only when ALL hold
9 * (Codex XREVIEW HOLD 6288472542 on orchestkit#4801):
10 *   - its media type is on the allowlist (a Map: no inherited keys);
11 *   - the text is strict base64 (length a multiple of 4, padding only at the
12 *     end) and under the size cap;
13 *   - the WHOLE decoded file has the structure of its type, end to end
14 *     (PNG chunks with CRCs, JPEG segments to EOI, GIF blocks to the trailer,
15 *     WebP RIFF chunks to the exact end), not only a file signature;
16 *   - the caller checks it holds no named value or vendor shape (holdsSecret).
17 * Pure: the mod sandbox may have neither Buffer nor atob.
18 */
19
20/** Most base64 characters one image payload may carry (about 12 MB decoded). */
21export const MAX_MEDIA_CHARS = 16_000_000;
22
23const B64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
24const B64_INDEX = new Map<string, number>(Array.from(B64, (c, i) => [c, i] as [string, number]));
25
26/** Strict base64 to bytes, or null: wrong length, bad padding, a foreign character, or over the cap. */
27export function decodeBase64Strict(text: string): Uint8Array | null {
28  if (typeof text !== "string" || text.length === 0 || text.length % 4 !== 0 || text.length > MAX_MEDIA_CHARS) {
29    return null;
30  }
31  const pad = text.endsWith("==") ? 2 : text.endsWith("=") ? 1 : 0;
32  const body = text.length - pad;
33  const out = new Uint8Array((text.length / 4) * 3 - pad);
34  let o = 0;
35  for (let i = 0; i < text.length; i += 4) {
36    const q: number[] = [];
37    for (let k = 0; k < 4; k++) {
38      const pos = i + k;
39      if (pos >= body) {
40        q.push(0);
41        continue;
42      }
43      const v = B64_INDEX.get(text[pos]);
44      if (v === undefined) return null;
45      q.push(v);
46    }
47    const word = (q[0] << 18) | (q[1] << 12) | (q[2] << 6) | q[3];
48    const bytes = [(word >> 16) & 0xff, (word >> 8) & 0xff, word & 0xff];
49    for (const b of bytes) {
50      if (o < out.length) out[o++] = b;
51    }
52  }
53  // Non-canonical padding bits (e.g. "QR==" for one byte) mean the text is not the canonical encoding.
54  if (pad === 2 && (B64_INDEX.get(text[body - 1])! & 0x0f) !== 0) return null;
55  if (pad === 1 && (B64_INDEX.get(text[body - 1])! & 0x03) !== 0) return null;
56  return out;
57}
58
59let CRC_TABLE: Uint32Array | null = null;
60function crc32(bytes: Uint8Array, start: number, end: number): number {
61  if (CRC_TABLE === null) {
62    CRC_TABLE = new Uint32Array(256);
63    for (let n = 0; n < 256; n++) {
64      let c = n;
65      for (let k = 0; k < 8; k++) c = c & 1 ? 0xedb88320 ^ (c >>> 1) : c >>> 1;
66      CRC_TABLE[n] = c >>> 0;
67    }
68  }
69  let c = 0xffffffff;
70  for (let i = start; i < end; i++) c = CRC_TABLE[(c ^ bytes[i]) & 0xff] ^ (c >>> 8);
71  return (c ^ 0xffffffff) >>> 0;
72}
73
74const u32be = (b: Uint8Array, i: number): number => ((b[i] << 24) | (b[i + 1] << 16) | (b[i + 2] << 8) | b[i + 3]) >>> 0;
75const u32le = (b: Uint8Array, i: number): number => ((b[i + 3] << 24) | (b[i + 2] << 16) | (b[i + 1] << 8) | b[i]) >>> 0;
76const startsWith = (b: Uint8Array, prefix: number[]): boolean => prefix.every((v, i) => b[i] === v);
77const ascii = (s: string): number[] => Array.from(s, (c) => c.charCodeAt(0));
78
79/**
80 * PNG: signature; IHDR first, 13 bytes, nonzero size, a legal bit depth for
81 * its colour type; at least one IDAT; every chunk's CRC right; IEND last and
82 * exactly at the end. Compressed text (zTXt, or iTXt with its compression
83 * flag set) cannot be checked for secrets without inflating it, so such a
84 * file is not exempt (Codex HOLD 6290872512).
85 */
86function validPng(b: Uint8Array): boolean {
87  if (!startsWith(b, [0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a])) return false;
88  let i = 8;
89  let first = true;
90  let idat = 0;
91  const idatParts: Uint8Array[] = [];
92  let idatBytes = 0;
93  let width = 0;
94  let height = 0;
95  let bitsPerPixel = 0;
96  let interlaced = false;
97  while (i + 12 <= b.length) {
98    const len = u32be(b, i);
99    const typeStart = i + 4;
100    const dataStart = typeStart + 4;
101    const dataEnd = dataStart + len;
102    if (len > 0x7fffffff || dataEnd + 4 > b.length) return false;
103    for (let k = typeStart; k < dataStart; k++) {
104      const c = b[k];
105      if (!((c >= 65 && c <= 90) || (c >= 97 && c <= 122))) return false;
106    }
107    const type = String.fromCharCode(b[typeStart], b[typeStart + 1], b[typeStart + 2], b[typeStart + 3]);
108    if (crc32(b, typeStart, dataEnd) !== u32be(b, dataEnd)) return false;
109    if (first) {
110      if (type !== "IHDR" || len !== 13) return false;
111      const w = u32be(b, dataStart);
112      const h = u32be(b, dataStart + 4);
113      const depth = b[dataStart + 8];
114      const colour = b[dataStart + 9];
115      const legal: Record<number, number[]> = { 0: [1, 2, 4, 8, 16], 2: [8, 16], 3: [1, 2, 4, 8], 4: [8, 16], 6: [8, 16] };
116      const depths = Object.prototype.hasOwnProperty.call(legal, colour) ? legal[colour] : undefined;
117      if (w === 0 || h === 0 || w > 0x7fffffff || h > 0x7fffffff || !depths || !depths.includes(depth)) return false;
118      if (b[dataStart + 10] !== 0 || b[dataStart + 11] !== 0 || b[dataStart + 12] > 1) return false;
119      const channels: Record<number, number> = { 0: 1, 2: 3, 3: 1, 4: 2, 6: 4 };
120      width = w;
121      height = h;
122      bitsPerPixel = depth * channels[colour];
123      interlaced = b[dataStart + 12] === 1;
124      first = false;
125    } else if (type === "IHDR") {
126      return false;
127    }
128    if (type === "IDAT" && len > 0) {
129      idat++;
130      idatParts.push(b.subarray(dataStart, dataEnd));
131      idatBytes += len;
132    }
133    if (type === "zTXt") return false;
134    if (type === "iTXt") {
135      const nul = b.indexOf(0, dataStart);
136      if (nul < 0 || nul + 1 >= dataEnd || b[nul + 1] !== 0) return false;
137    }
138    i = dataEnd + 4;
139    if (type === "IEND") {
140      if (len !== 0 || i !== b.length || idat === 0) return false;
141      const z = new Uint8Array(idatBytes);
142      let at = 0;
143      for (const part of idatParts) {
144        z.set(part, at);
145        at += part.length;
146      }
147      return pixelRowsValid(z, width, height, bitsPerPixel, interlaced);
148    }
149  }
150  return false;
151}
152
153/** Most bytes the PNG pixel data may inflate to (64 MiB): a bigger image is not exempt. */
154export const MAX_PNG_RAW_BYTES = 64 * 1024 * 1024;
155
156/**
157 * The IDAT stream must inflate (bounded) to exactly the expected filtered
158 * rows: every row starts with a filter byte 0..4 (Adam7 passes for an
159 * interlaced image). Proves real pixel data, not only PNG framing (Codex
160 * XREVIEW HOLD 6293176280).
161 */
162function pixelRowsValid(z: Uint8Array, w: number, h: number, bpp: number, interlaced: boolean): boolean {
163  const rowBytes = (pw: number): number => Math.ceil((pw * bpp) / 8);
164  const passes: Array<[number, number]> = [];
165  if (!interlaced) {
166    passes.push([w, h]);
167  } else {
168    const adam7 = [[0, 0, 8, 8], [4, 0, 8, 8], [0, 4, 4, 8], [2, 0, 4, 4], [0, 2, 2, 4], [1, 0, 2, 2], [0, 1, 1, 2]];
169    for (const [x0, y0, dx, dy] of adam7) {
170      const pw = Math.ceil((w - x0) / dx);
171      const ph = Math.ceil((h - y0) / dy);
172      if (pw > 0 && ph > 0) passes.push([pw, ph]);
173    }
174  }
175  let expected = 0;
176  for (const [pw, ph] of passes) {
177    expected += ph * (1 + rowBytes(pw));
178    if (expected > MAX_PNG_RAW_BYTES) return false;
179  }
180  const raw = zlibInflate(z, expected + 1);
181  if (raw === null || raw.length !== expected) return false;
182  let at = 0;
183  for (const [pw, ph] of passes) {
184    const stride = 1 + rowBytes(pw);
185    for (let r = 0; r < ph; r++, at += stride) if (raw[at] > 4) return false;
186  }
187  return true;
188}
189
190/**
191 * JPEG: SOI; marker segments with in-bounds lengths; at least one DQT; a
192 * frame header (SOF0..SOF15 minus DHT/JPG/DAC) with nonzero size and 1 to 4
193 * components before the first SOS; non-empty entropy data after SOS; EOI
194 * exactly at the end.
195 */
196function validJpeg(b: Uint8Array): boolean {
197  if (b.length < 4 || b[0] !== 0xff || b[1] !== 0xd8) return false;
198  let i = 2;
199  let dqt = false;
200  let frame = false;
201  let scans = 0;
202  while (i < b.length) {
203    if (b[i] !== 0xff) return false;
204    while (i < b.length && b[i] === 0xff) i++; // fill bytes
205    if (i >= b.length) return false;
206    const m = b[i++];
207    if (m === 0xd9) return i === b.length && dqt && frame && scans > 0; // EOI
208    if (m === 0x01 || (m >= 0xd0 && m <= 0xd7)) continue; // standalone markers
209    if (m === 0x00 || m === 0xd8) return false;
210    if (i + 2 > b.length) return false;
211    const len = (b[i] << 8) | b[i + 1];
212    if (len < 2 || i + len > b.length) return false;
213    if (m === 0xdb) dqt = true;
214    const isSof = m >= 0xc0 && m <= 0xcf && m !== 0xc4 && m !== 0xc8 && m !== 0xcc;
215    if (isSof) {
216      if (len < 8 || frame) return false;
217      const h = (b[i + 3] << 8) | b[i + 4];
218      const w = (b[i + 5] << 8) | b[i + 6];
219      const comps = b[i + 7];
220      if (h === 0 || w === 0 || comps < 1 || comps > 4 || len !== 8 + 3 * comps) return false;
221      frame = true;
222    }
223    i += len;
224    if (m === 0xda) {
225      if (!frame) return false;
226      // Entropy-coded data: runs until a marker other than a stuffed 00 or a restart marker; never empty.
227      const start = i;
228      while (i + 1 < b.length) {
229        if (b[i] === 0xff && b[i + 1] !== 0x00 && !(b[i + 1] >= 0xd0 && b[i + 1] <= 0xd7)) break;
230        i++;
231      }
232      if (i + 1 >= b.length || i === start) return false;
233      scans++;
234    }
235  }
236  return false;
237}
238
239/** GIF: header, logical screen, every block walked, at least one image of nonzero size with data, trailer at the end. */
240function validGif(b: Uint8Array): boolean {
241  if (!(startsWith(b, ascii("GIF87a")) || startsWith(b, ascii("GIF89a"))) || b.length < 14) return false;
242  let i = 13;
243  const flags = b[10];
244  if (flags & 0x80) i += 3 * (1 << ((flags & 0x07) + 1));
245  let images = 0;
246  const subBlocks = (): number => {
247    let total = 0;
248    while (i < b.length) {
249      const n = b[i++];
250      if (n === 0) return total;
251      total += n;
252      i += n;
253    }
254    return -1;
255  };
256  while (i < b.length) {
257    const tag = b[i++];
258    if (tag === 0x3b) return i === b.length && images > 0;
259    if (tag === 0x21) {
260      if (i >= b.length) return false;
261      i++; // label
262      if (subBlocks() < 0) return false;
263    } else if (tag === 0x2c) {
264      if (i + 9 > b.length) return false;
265      const w = b[i + 4] | (b[i + 5] << 8);
266      const h = b[i + 6] | (b[i + 7] << 8);
267      const f = b[i + 8];
268      i += 9;
269      if (w === 0 || h === 0) return false;
270      if (f & 0x80) i += 3 * (1 << ((f & 0x07) + 1));
271      if (i >= b.length) return false;
272      const lzw = b[i++];
273      if (lzw < 2 || lzw > 8) return false;
274      if (subBlocks() <= 0) return false;
275      images++;
276    } else {
277      return false;
278    }
279  }
280  return false;
281}
282
283/**
284 * The media types whose payload may pass, each with its whole-file validator. A Map: no inherited keys.
285 * WebP is not on it (operator decision 2026-10-20): its bitstream cannot be proven without a full
286 * decoder, so a WebP Read stays masked while the veil is on.
287 */
288export const MEDIA_VALIDATORS: ReadonlyMap<string, (b: Uint8Array) => boolean> = new Map([
289  ["image/png", validPng],
290  ["image/jpeg", validJpeg],
291  ["image/gif", validGif],
292]);
293
294/** The decoded image when the payload passes every structural check, else null. */
295export function validImage(mediaType: unknown, data: unknown): Uint8Array | null {
296  if (typeof mediaType !== "string" || typeof data !== "string") return null;
297  const validator = MEDIA_VALIDATORS.get(mediaType);
298  if (validator === undefined) return null;
299  const bytes = decodeBase64Strict(data);
300  if (bytes === null) return null;
301  return validator(bytes) === true ? bytes : null;
302}
303
304/**
305 * True when a secret appears in the image. The caller withholds the result.
306 *   - named values (8+ chars): in the decoded bytes (read as Latin-1, so text
307 *     in a PNG tEXt chunk or EXIF is seen) or in the base64 text itself;
308 *   - vendor shapes (sk-ant-, AKIA, PEM header, ...): in the decoded bytes
309 *     only. In the base64 text a 4-letter shape such as AKIA occurs by chance
310 *     in about 2 % of large images, which would withhold ordinary screenshots.
311 */
312export function holdsSecret(
313  bytes: Uint8Array,
314  base64: string,
315  named: readonly string[],
316  shapes: readonly string[],
317): boolean {
318  if (named.length === 0 && shapes.length === 0) return false;
319  let text = "";
320  const STEP = 0x8000;
321  for (let i = 0; i < bytes.length; i += STEP) {
322    text += String.fromCharCode(...bytes.subarray(i, i + STEP));
323  }
324  // The decoded bytes are read as Latin-1 (one char per byte), so a value is
325  // matched in each byte encoding a metadata field may use: UTF-8 (PNG iTXt,
326  // XMP), UTF-16LE (EXIF XP* tags) and plain Latin-1 (PNG tEXt, GIF comment).
327  // Codex HOLD 6290872512: a non-ASCII named value in UTF-8 metadata was missed.
328  const encodings = (v: string): string[] => {
329    const utf8 = byteString(new TextEncoder().encode(v));
330    // Every UTF-16 code unit by index: Array.from(v) walks code points and would drop the low
331    // surrogate of a supplementary character (Codex HOLD 6293176280).
332    let utf16 = "";
333    for (let k = 0; k < v.length; k++) {
334      const u = v.charCodeAt(k);
335      utf16 += String.fromCharCode(u & 0xff, u >> 8);
336    }
337    return Array.from(new Set([v, utf8, utf16]));
338  };
339  for (const n of named) {
340    if (n.length === 0) continue;
341    if (base64.includes(n)) return true;
342    if (encodings(n).some((e) => text.includes(e))) return true;
343  }
344  return shapes.some((s) => s.length > 0 && encodings(s).some((e) => text.includes(e)));
345}
346
347function byteString(bytes: Uint8Array): string {
348  let out = "";
349  for (const x of bytes) out += String.fromCharCode(x);
350  return out;
351}
352
src/types.ts 149 lines
1// secrets-veil: types.ts - shared type definitions
2// Reused from commit 30720692 and trimmed: the reveal surface (RevealedState,
3// UIPressEvent, CommandRegisterEvent, ui.render/ui.press on OnFn) is gone by
4// design. This mod has no reveal path; its ui calls carry counts, never values.
5
6/**
7 * Configuration for the high-entropy value layer.
8 */
9export interface EntropyConfig {
10  /** Minimum token length to consider */
11  minLength: number;
12  /** Minimum Shannon entropy in bits per character */
13  thresholdBitsPerChar: number;
14}
15
16/**
17 * An entry in the mask table.
18 */
19export type MaskTableEntry =
20  | {
21      type: "env";
22      name: string;
23      value: string;
24      pattern: string;
25    }
26  | {
27      type: "pattern";
28      pattern: string;
29    };
30
31/**
32 * The mask table built at session.start from named values and patterns.
33 * The optional entropy layer is a scan config, not an entry: it applies to
34 * whole tokens found in text, not to a fixed value.
35 */
36export interface MaskTable {
37  entries: readonly MaskTableEntry[];
38  entropy?: EntropyConfig | null;
39}
40
41/**
42 * A span in the original text that was masked.
43 */
44export interface MaskSpan {
45  /** Start position in original text */
46  start: number;
47  /** End position in original text */
48  end: number;
49  /** The original value that was masked */
50  value: string;
51  /** The env var name, if applicable */
52  name?: string;
53}
54
55/**
56 * Result of masking text.
57 */
58export interface MaskResult {
59  /** The masked text (with secrets replaced by bullets) */
60  text: string;
61  /** Spans indicating where secrets were found */
62  spans: MaskSpan[];
63}
64
65/**
66 * The $ dependency object (subset used by secrets-veil).
67 * Deliberately minimal: env reads, one notice, and the three calls that make
68 * masking visible (toast, status, debug log), each carrying counts only,
69 * never a value. No ui.render, no ui.press, no commands, no process, no
70 * http, no store.
71 */
72export interface DollarAPI {
73  env: {
74    get(name: string): Promise<string | undefined>;
75  };
76  clock: {
77    /** One-shot timer; the mod sandbox has no ambient timers. */
78    after(ms: number, fn: () => void): { cancel?: () => void };
79  };
80  ui: {
81    notice(id: string, message: string): void;
82    toast(text: string): Promise<void>;
83    status(line: string): Promise<void>;
84    /** { to: "debug" } writes the debug log only; the default is the transcript. */
85    log(text: string, options?: { to?: "transcript" | "debug" }): Promise<void>;
86    /** Opt-in only: the AskUserQuestion dialog, resolves to the picked label. */
87    ask(question: string, options: readonly string[]): Promise<unknown>;
88    /** Opt-in only: writes to the human's clipboard (OSC 52); the model never sees it. */
89    copy(spec: { text: string }): Promise<{ isCopied: boolean; reason?: string }>;
90  };
91}
92
93/**
94 * Event types for function hooks.
95 */
96export interface ToolCallEvent {
97  tool: string;
98  args: Record<string, unknown>;
99  tool_use_id?: string;
100}
101
102export interface ToolCallResult {
103  deny?: string;
104  result?: unknown;
105  text?: string;
106  isError?: boolean;
107  context?: string[];
108}
109
110export interface SessionStartEvent {
111  surface?: "terminal" | "desktop" | "mobile";
112  isInteractive?: boolean;
113}
114
115/**
116 * Event filter passed to on() (e.g. { component: "ToolResult" }).
117 */
118export type HookMatcher = Record<string, unknown>;
119
120/**
121 * The next() function signature: pass the event down the hook chain
122 * and await the (possibly modified) result.
123 */
124export type NextFn<E, R = unknown> = (event: E) => Promise<R>;
125
126/**
127 * A function-hook handler: receives the $ API, the event and next().
128 */
129export type HookHandler<E, R = unknown> = (
130  api: DollarAPI,
131  event: E,
132  next: NextFn<E, R>
133) => Promise<unknown>;
134
135/**
136 * The on() registrar Claude Code passes to a function-hooks module.
137 * Only two events: session.start arms the veil, tool.call masks results.
138 * There is no ui.render, no ui.press and no command.register on purpose.
139 */
140export interface OnFn {
141  (event: "session.start", matcher: HookMatcher, handler: HookHandler<SessionStartEvent>): void;
142  (event: "tool.call", matcher: HookMatcher, handler: HookHandler<ToolCallEvent, ToolCallResult>): void;
143}
144
145/**
146 * The register() entry point a function-hooks module exports.
147 */
148export type Register = (on: OnFn) => void;
149
src/inflate.ts 222 lines
1/**
2 * A bounded zlib (RFC 1950) + DEFLATE (RFC 1951) decoder, pure: the mod
3 * sandbox may have no zlib. Used to prove a PNG's IDAT data really decodes to
4 * its pixel rows before the payload may pass unmasked (Codex XREVIEW HOLD
5 * 6293176280 on orchestkit#4801). It never writes more than `limit` bytes:
6 * one byte past the limit is a failure, so a crafted stream cannot blow up.
7 * Returns the inflated bytes, or null on any error (bad header, bad code,
8 * distance too far back, truncated input, output over the limit, a trailing
9 * byte, or a wrong Adler-32).
10 */
11
12class Bits {
13  pos = 0;
14  bit = 0;
15  constructor(private readonly b: Uint8Array, start: number, private readonly end: number) {
16    this.pos = start;
17  }
18  /** n bits, least significant first; -1 when the input runs out. */
19  read(n: number): number {
20    let v = 0;
21    for (let i = 0; i < n; i++) {
22      if (this.pos >= this.end) return -1;
23      v |= ((this.b[this.pos] >> this.bit) & 1) << i;
24      if (++this.bit === 8) {
25        this.bit = 0;
26        this.pos++;
27      }
28    }
29    return v;
30  }
31  align(): void {
32    if (this.bit !== 0) {
33      this.bit = 0;
34      this.pos++;
35    }
36  }
37}
38
39/** Canonical Huffman table: counts per length and symbols in code order. */
40interface Huffman {
41  counts: Int32Array;
42  symbols: Int32Array;
43}
44
45/**
46 * kind: "codes" = the code-length tree, "dynamic" = a literal/length or
47 * distance tree of a dynamic block, "fixed" = the RFC 1951 fixed tables.
48 * zlib's rule (inflate_table): an over-subscribed tree is never valid; an
49 * incomplete tree is valid only outside "codes" and only when it holds a
50 * single code of length 1 (RFC 1951 allows one distance code). An all-zero
51 * tree is accepted here and fails on first use, as in zlib. The fixed
52 * distance table (30 codes of length 5) is incomplete by design and is not
53 * checked. Codex XREVIEW HOLD 6293967301: incomplete dynamic trees were
54 * accepted.
55 */
56function huffman(lengths: ArrayLike<number>, n: number, kind: "codes" | "dynamic" | "fixed"): Huffman | null {
57  const counts = new Int32Array(16);
58  let max = 0;
59  for (let i = 0; i < n; i++) {
60    counts[lengths[i]]++;
61    if (lengths[i] > max) max = lengths[i];
62  }
63  counts[0] = 0;
64  let left = 1;
65  for (let len = 1; len < 16; len++) {
66    left = (left << 1) - counts[len];
67    if (left < 0) return null; // over-subscribed
68  }
69  if (kind !== "fixed" && max > 0 && left > 0 && (kind === "codes" || max !== 1)) return null; // incomplete
70  const offs = new Int32Array(16);
71  for (let len = 1; len < 15; len++) offs[len + 1] = offs[len] + counts[len];
72  const symbols = new Int32Array(n);
73  for (let i = 0; i < n; i++) if (lengths[i] !== 0) symbols[offs[lengths[i]]++] = i;
74  return { counts, symbols };
75}
76
77function decodeSym(bits: Bits, h: Huffman): number {
78  let code = 0;
79  let first = 0;
80  let index = 0;
81  for (let len = 1; len < 16; len++) {
82    const bit = bits.read(1);
83    if (bit < 0) return -1;
84    code |= bit;
85    const count = h.counts[len];
86    if (code - count < first) return h.symbols[index + (code - first)];
87    index += count;
88    first += count;
89    first <<= 1;
90    code <<= 1;
91  }
92  return -1;
93}
94
95const LEN_BASE = [3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31, 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258];
96const LEN_EXTRA = [0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 0];
97const DIST_BASE = [1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193, 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145, 8193, 12289, 16385, 24577];
98const DIST_EXTRA = [0, 0, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13];
99const ORDER = [16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15];
100
101let FIXED: { lit: Huffman; dist: Huffman } | null = null;
102function fixedTables(): { lit: Huffman; dist: Huffman } {
103  if (FIXED === null) {
104    const l = new Array<number>(288);
105    for (let i = 0; i < 144; i++) l[i] = 8;
106    for (let i = 144; i < 256; i++) l[i] = 9;
107    for (let i = 256; i < 280; i++) l[i] = 7;
108    for (let i = 280; i < 288; i++) l[i] = 8;
109    FIXED = { lit: huffman(l, 288, "fixed")!, dist: huffman(new Array<number>(30).fill(5), 30, "fixed")! };
110  }
111  return FIXED;
112}
113
114export function zlibInflate(src: Uint8Array, limit: number): Uint8Array | null {
115  if (src.length < 6) return null;
116  const cmf = src[0];
117  const flg = src[1];
118  if ((cmf & 0x0f) !== 8 || cmf >> 4 > 7 || ((cmf << 8) | flg) % 31 !== 0 || flg & 0x20) return null;
119  const out = new Uint8Array(limit);
120  let o = 0;
121  const bits = new Bits(src, 2, src.length - 4);
122  let last = 0;
123  while (!last) {
124    last = bits.read(1);
125    const type = bits.read(2);
126    if (last < 0 || type < 0) return null;
127    if (type === 0) {
128      bits.align();
129      const p = bits.pos;
130      if (p + 4 > src.length - 4) return null;
131      const len = src[p] | (src[p + 1] << 8);
132      const nlen = src[p + 2] | (src[p + 3] << 8);
133      if ((len ^ 0xffff) !== nlen || p + 4 + len > src.length - 4 || o + len > limit) return null;
134      out.set(src.subarray(p + 4, p + 4 + len), o);
135      o += len;
136      bits.pos = p + 4 + len;
137      continue;
138    }
139    let lit: Huffman;
140    let dist: Huffman;
141    if (type === 1) {
142      ({ lit, dist } = fixedTables());
143    } else if (type === 2) {
144      const hlit = bits.read(5) + 257;
145      const hdist = bits.read(5) + 1;
146      const hclen = bits.read(4) + 4;
147      if (hlit < 257 || hdist < 1 || hclen < 4 || hlit > 286 || hdist > 30) return null;
148      const cl = new Array<number>(19).fill(0);
149      for (let i = 0; i < hclen; i++) {
150        const v = bits.read(3);
151        if (v < 0) return null;
152        cl[ORDER[i]] = v;
153      }
154      const clh = huffman(cl, 19, "codes");
155      if (clh === null) return null;
156      const lens: number[] = [];
157      while (lens.length < hlit + hdist) {
158        const sym = decodeSym(bits, clh);
159        if (sym < 0) return null;
160        if (sym < 16) {
161          lens.push(sym);
162        } else {
163          let rep = 0;
164          let val = 0;
165          if (sym === 16) {
166            if (lens.length === 0) return null;
167            val = lens[lens.length - 1];
168            rep = 3 + bits.read(2);
169          } else if (sym === 17) {
170            rep = 3 + bits.read(3);
171          } else {
172            rep = 11 + bits.read(7);
173          }
174          if (rep < 3 || lens.length + rep > hlit + hdist) return null;
175          for (let r = 0; r < rep; r++) lens.push(val);
176        }
177      }
178      if (lens[256] === 0) return null; // no end-of-block code
179      const l = huffman(lens.slice(0, hlit), hlit, "dynamic");
180      const d = huffman(lens.slice(hlit), hdist, "dynamic");
181      if (l === null || d === null) return null;
182      lit = l;
183      dist = d;
184    } else {
185      return null;
186    }
187    for (;;) {
188      const sym = decodeSym(bits, lit);
189      if (sym < 0) return null;
190      if (sym < 256) {
191        if (o >= limit) return null;
192        out[o++] = sym;
193      } else if (sym === 256) {
194        break;
195      } else {
196        const li = sym - 257;
197        if (li >= 29) return null;
198        const le = bits.read(LEN_EXTRA[li]);
199        const ds = decodeSym(bits, dist);
200        if (le < 0 || ds < 0 || ds >= 30) return null;
201        const de = bits.read(DIST_EXTRA[ds]);
202        if (de < 0) return null;
203        const len = LEN_BASE[li] + le;
204        const back = DIST_BASE[ds] + de;
205        if (back > o || o + len > limit) return null;
206        for (let k = 0; k < len; k++, o++) out[o] = out[o - back];
207      }
208    }
209  }
210  bits.align();
211  if (bits.pos !== src.length - 4) return null; // trailing bytes before the checksum
212  let a = 1;
213  let b = 0;
214  for (let i = 0; i < o; i++) {
215    a = (a + out[i]) % 65521;
216    b = (b + a) % 65521;
217  }
218  const adler = (((src[src.length - 4] << 24) | (src[src.length - 3] << 16) | (src[src.length - 2] << 8) | src[src.length - 1]) >>> 0);
219  if ((((b << 16) | a) >>> 0) !== adler) return null;
220  return out.subarray(0, o);
221}
222