Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 3 additions & 2 deletions docs/dev/site-access.md
Original file line number Diff line number Diff line change
Expand Up @@ -40,8 +40,9 @@ handler's answer and is left alone), and `forModel` on every step result a worke
once in the shared loop after the step settles (`forModel` in `agent-loop.ts`: a tool's answer, a read-only try, a
precheck, a dispatch that threw, a denial), which records the raw text in the execution log's `key` (`tool`/`scrubbed`). Extension pages (the popup, the DevTools panel, Settings) are answered unscrubbed: they are where
a person diagnoses a wrong URL. `SET_MODEL`'s unknown-model error lists only the models the filter allows.
The forms (`secretsOf`): the URL, its origin, host and host name (as typed and as parsed, any letter case; not a dotless
or loopback name such as `ollama` or `localhost`, which are ordinary words), each also JSON-escaped and percent-encoded;
The forms (`secretsOf`): the URL, its origin, host and host name (as typed and as parsed, any letter case; a host with a
port always, while a name without one is skipped when it is dotless or loopback, such as `ollama` or `localhost`, which
are ordinary words), each also JSON-escaped and percent-encoded;
the key only from 12 characters (a shorter one is a placeholder like `ollama`); the filter in its error form `(/re/)`,
and bare only when it holds a regex character other than `.` (else it is a model's name). A quoted backend body is cut
clear of a secret (`clipClear`), never through it. Every key ending in `error` is scrubbed (`transportError` too). The
Expand Down
19 changes: 12 additions & 7 deletions docs/spec/SECRET_HANDLES.md
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ characters, matched as written and in its JSON, percent, base64 and shell forms)
| A session row leaving the worker (lists, search, the hub, the HUD) | `[REDACTED:<NAME>]` | built (ruling 61) |
| Bytes read from `/files` (`ml.fs`, Python's mount) | an occurrence of a registered value reads as its session fake, every other byte of a match as `*`, so sizes and offsets hold; a fake or marker written back to its own file is restored | built (#2205, rulings 100 and 101) |
| A file's NAME under `/files` that holds a registered value | the listing shows it with its registered values masked, as the file block of the turn does, and a shown name opens its file | built (#2166) |
| A GitHub token, registered or not | `[a GitHub token]`, by its shape, in what crosses `scrubSecrets` (a tool result and an error bound for the model or a page, the stored render the sidebar and both exports draw) and in a file's name under `/files` (`maskName`); a file's bytes read from `/files` show it as `*`, and a live output's view (`forLive`) shows it until the step settles. Not in what the person or a page sends (the turn, its files' text, the page context, a page's own model request) until ruling 39's detector: "Known limits" below | built for those paths, the one pattern there is |
| A GitHub token, registered or not | `[a GitHub token]`, by its shape, in what crosses `scrubSecrets` (a tool result and an error bound for the model or a page, the stored render the sidebar and both exports draw), an `ml.sh.read` range that cuts it included, and in a file's name under `/files` (`maskName`); a file's bytes read from `/files` show it as `*`, and a live output's view (`forLive`) shows it until the step settles. Not in what the person or a page sends (the turn, its files' text, the page context, a page's own model request) until ruling 39's detector: "Known limits" below | built for those paths, the one pattern there is |
| Any other unregistered key shape (`sk-`, `AKIA`, a JWT, a PEM block, URL userinfo) | the value | not built (scrub PR 2; ruling 39's detector for the person's input) |
| A value in a password field of a page | the value | ruled (30), not built |
| A value of a hidden file that a program the person allowed prints | the value, unless it is registered | open design ("Open questions", below) |
Expand Down Expand Up @@ -272,11 +272,13 @@ on real captured output in its PR.
- **The host does not scrub.** A process's held output stays its raw bytes, so a registered value can pass between
the stages of a pipe on the host (an OS pipe, which never crosses into the worker); it is scrubbed before any script
or model reads it. `done`'s `sha256` and `size` are over the raw bytes. A scrubbed read says so: a text range comes
back with its matches replaced, a binary range as scrubbed bytes with `scrubbed: <n>`, and either may be shorter or
longer than `length`.
- **A cut never lets a prefix through.** A read range is fetched with a margin of the longest registered form on each
side and scrubbed whole, and a match that overlaps the range is replaced where it overlaps. A head whose last bytes
are the start of a registered form is cut before them, and its `complete` is false.
back with its matches replaced, a binary range as scrubbed bytes with `scrubbed: <n>` (registered matches and GitHub
tokens alike), and either may be shorter or longer than `length`.
- **A cut never lets a prefix through.** A read range is fetched with a margin of the longest registered form, and
never less than the longest GitHub token (266 characters), on each side and scrubbed whole, and a match that overlaps
the range is replaced where it overlaps: a registered form, or a GitHub token matched by its shape. A head whose
last bytes are the start of a registered form or of a GitHub token's body is cut before them (for a token, at most
`ghp_` and 35 characters, 39 bytes), and its `complete` is false.
- **The registry**, by name and value, is `ml_secret_registry` in `chrome.storage.local` (never sync), declared in the
state registry beside its store. It is class secret under [`MODEL_SETTINGS.md`](MODEL_SETTINGS.md) ("Not settings,
never writable"): never in `GET_CONFIG`, `ml.settings()` or an answer to any page-reachable message, never written by
Expand All @@ -300,7 +302,10 @@ on real captured output in its PR.
`1 secret redacted (PLUG_PASSWORD)`, names and a count, never a value. What the run stores and exports is what the
model saw, so the sidebar (its live output included), the run log and both exports never hold a registered value
that arrived after it was registered.
- **Known limits**: images; what the person or a page sends is scrubbed by registered value only (ruling 39, PR 1: the
- **Known limits**: `forLive` applies the registered forms only, so a GitHub token that is not registered shows in a
live output's stream until the step settles (the settled step, what is stored and what the model reads carry
`[a GitHub token]`); ruling 39's shape detector is where that is repaired; images; what the person or a page sends
is scrubbed by registered value only (ruling 39, PR 1: the
turn's words, a right-clicked element, its files' text and the page context a run starts with, behind
`scrubPersonInput`), so a token in it that is neither registered nor the extension's own key reaches the model until
the shape detector (ruling 39, PR 3); a value that was transformed or only partly echoed (threat 2); a value
Expand Down
36 changes: 27 additions & 9 deletions src/secret-registry.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
// secret-registry.ts — the values the person registered as secret (a name and a value each) and the pure matching over them: the forms a value is written in, the scrub of a text, of bytes and of a read range, and how much of a cut text's end to hold back.

import type { SecretSub } from "./secret-scrub";
import { GITHUB_TOKEN, GITHUB_TOKEN_MAX, GITHUB_TOKEN_PUT, type SecretSub } from "./secret-scrub";

/** One registered secret: the NAME written into model-facing text in its place, and the value that is never shown. */
export interface RegistryEntry { name: string; value: string }
Expand Down Expand Up @@ -259,12 +259,24 @@ export function heldTail(text: string, subs: readonly RegistrySub[]): number {
}

/**
* How far a read range must be widened on each side to see every match that overlaps it.
* How many characters at the end of a text to hold back because they begin a GitHub token's body: `GITHUB_TOKEN`
* needs 36 characters after `gh?_` (22 after `github_pat_`), so a cut inside a token's body leaves a front the shape
* never matches. A body already that long is a match, not a front; the most held is `ghp_` and 35 characters (39).
* @param text the text so far, already scrubbed
* @returns the length of the token front at the end, 0 when none
*/
export function tokenTail(text: string): number {
return /\b(?:gh[pousr]_[A-Za-z0-9]{0,35}|github_pat_[A-Za-z0-9_]{0,21})$/.exec(text)?.[0].length ?? 0;
}

/**
* How far a read range must be widened on each side to see every match that overlaps it: a registered form or a
* GitHub token, which `scrubRange` matches by shape.
* @param subs from `registrySubs`
* @returns the longest form's length, 0 when there are none
* @returns the longest form's length, and never less than the longest GitHub token
*/
export function margin(subs: readonly RegistrySub[]): number {
return subs.reduce((n, s) => Math.max(n, s.find.length), 0);
return subs.reduce((n, s) => Math.max(n, s.find.length), GITHUB_TOKEN_MAX);
}

/**
Expand Down Expand Up @@ -317,28 +329,34 @@ export function scrubBytes(bytes: Uint8Array, subs: readonly RegistrySub[]): { b
/**
* The slice [from, to) of a text fetched with a margin on both sides, scrubbed: matches are found in the whole window,
* and one that overlaps the slice becomes its marker (once, its outside part dropped), so a cut never shows a prefix.
* A GitHub token is matched by its shape the same way (first, as `scrubSecrets` does) and counted apart, in `tokens`:
* it has no registered name. The window must be widened by `margin`, so a token the slice cuts is still whole in it.
* @param window the fetched text
* @param from the start of the wanted slice, in the window
* @param to the end of the wanted slice, exclusive
* @param subs from `registrySubs`
* @returns the slice and the counts of the matches that overlap it
* @returns the slice, the counts of the registered matches that overlap it, and how many GitHub tokens overlap it
*/
export function scrubRange(window: string, from: number, to: number, subs: readonly RegistrySub[]): { text: string; counts: Record<string, number> } {
export function scrubRange(window: string, from: number, to: number, subs: readonly RegistrySub[]): { text: string; counts: Record<string, number>; tokens: number } {
const lo = Math.max(0, from);
const hi = Math.min(window.length, to);
const counts: Record<string, number> = {};
let out = "";
let pos = lo;
for (const h of findHits(window, subs)) {
let tokenCount = 0;
const tokens: Hit[] = [...window.matchAll(new RegExp(GITHUB_TOKEN))].map((m) => ({ start: m.index, end: m.index + m[0].length, put: GITHUB_TOKEN_PUT, name: "" }));
const free = (h: Hit): boolean => !tokens.some((t) => h.start < t.end && t.start < h.end);
const hits = [...tokens, ...findHits(window, subs).filter(free)].sort((a, b) => a.start - b.start);
for (const h of hits) {
if (h.end <= lo) continue;
if (h.start >= hi) break;
if (h.start > pos) out += window.slice(pos, h.start);
out += h.put;
pos = Math.max(pos, h.end);
counts[h.name] = (counts[h.name] ?? 0) + 1;
if (h.name) counts[h.name] = (counts[h.name] ?? 0) + 1; else tokenCount++;
}
if (pos < hi) out += window.slice(pos, hi);
return { text: out, counts };
return { text: out, counts, tokens: tokenCount };
}

/**
Expand Down
3 changes: 3 additions & 0 deletions src/secret-scrub.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,9 @@ export const GITHUB_TOKEN = /\b(?:gh[pousr]_[A-Za-z0-9]{36,255}|github_pat_[A-Za
/** What stands in for one. */
export const GITHUB_TOKEN_PUT = "[a GitHub token]";

/** The longest text `GITHUB_TOKEN` matches: `github_pat_` and 255 characters. */
export const GITHUB_TOKEN_MAX = 266;

/** Shorter than this, an API key is a placeholder (`ollama`, `EMPTY`, `sk-1234`) and also an ordinary word. */
const MIN_KEY = 12;

Expand Down
20 changes: 10 additions & 10 deletions src/sw/sw-shell-call.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ import { MAX_DETAIL_STRING } from "../log/housekeeping";
import { ASKED_TAIL_CHARS, PEEK_DEFAULT_BYTES, peekBytesFor, peekDetail } from "../shell/sh-tail";
import { forModel } from "./sw-scrub";
import { registryReady, registrySubsNow } from "./sw-secret-registry";
import { cutsInJson, heldTail, margin, scrubRange, shiftCuts, type RedactionCut, type RegistrySub } from "../secret-registry";
import { cutsInJson, heldTail, margin, scrubRange, shiftCuts, tokenTail, type RedactionCut, type RegistrySub } from "../secret-registry";
import { holdOutput, shellHost, ShellUnavailable, withShell, type ShellHost } from "./sw-shell";
import { hideRuleWords, spawnBound } from "./sw-spawn";
import { manifestsReady, storedManifests } from "./sw-manifests";
Expand Down Expand Up @@ -625,8 +625,9 @@ async function keep(ctx: ShCallContext, h: ShellHost, s: HostStream, f: ShFacts)

/**
* A stream's head as it crosses into the script: the config's and the registered secrets taken out (`forModel`), and,
* when the head is cut, any tail that begins a registered value held back, so the script never holds a secret or the
* front of one. The run's token store keeps this text, never the raw head. A binary head is a note, with nothing to take.
* when the head is cut, any tail that begins a registered value or a GitHub token's body held back, so the script never
* holds a secret or the front of one. The run's token store keeps this text, never the raw head. A binary head is a
* note, with nothing to take.
* @param out the stream as `shOut` shaped it
* @param head the head's bytes
* @param size the stream's whole size
Expand All @@ -641,7 +642,7 @@ async function scrubbedHead(out: ShOut, head: Uint8Array, size: number, counted:
let text = s.text;
let kept = text.length;
if (!whole) {
kept = text.length - heldTail(text, registrySubsNow());
kept = text.length - Math.max(heldTail(text, registrySubsNow()), tokenTail(text));
text = `${text.slice(0, kept)}… [first ${head.length} of ${size} bytes]`;
}
const scrubbed = { ...out, text };
Expand Down Expand Up @@ -719,9 +720,9 @@ export async function shRead(ctx: ShCallContext, args: readonly unknown[]): Prom
if (h.client !== x.client) { forgetClient(x.client); return refuse("Refused", `${ref}: the process host restarted, and the output went with it`); }
await registryReady();
const subs = registrySubsNow();
// Widened by the longest registered form on each side, so a value the range cuts is still seen whole and
// replaced where it overlaps (SECRET_HANDLES.md, "A cut never lets a prefix through"); the range shrinks to keep
// the widened read inside the host's cap.
// Widened by the longest registered form or GitHub token on each side, so a value the range cuts is still seen
// whole and replaced where it overlaps (SECRET_HANDLES.md, "A cut never lets a prefix through"); the range
// shrinks to keep the widened read inside the host's cap.
const m = margin(subs), want = Math.min(length, SH_READ_MAX - 2 * m);
const lo = Math.max(0, offset - m);
const r = await h.client.read(x.ptr, lo, want + (offset - lo) + m);
Expand All @@ -730,10 +731,9 @@ export async function shRead(ctx: ShCallContext, args: readonly unknown[]): Prom
const eof = r.eof && offset - lo + want >= win.length;
const base = { offset, length: bytes.length, size: r.size, eof };
if (binaryKind(bytes)) {
if (!m) return { ok: { ...base, bytes: r.data } };
const sc = scrubRange(latin1(win), offset - lo, offset - lo + bytes.length, bytewise(subs));
noteInnerCuts(ctx, sc.counts);
const n = Object.values(sc.counts).reduce((a, b) => a + b, 0);
const n = Object.values(sc.counts).reduce((a, b) => a + b, 0) + sc.tokens;
const out = Uint8Array.from(sc.text, (c) => c.charCodeAt(0));
return { ok: { ...base, bytes: { $bytes: base64Of(out) }, ...(n ? { scrubbed: n } : {}) } };
}
Expand All @@ -748,7 +748,7 @@ export async function shRead(ctx: ShCallContext, args: readonly unknown[]): Prom
while (cont(b)) b++;
const from = dec(win.subarray(0, a)).length, to = dec(win.subarray(0, b)).length;
const sc = scrubRange(dec(win), from, to, subs);
const n = Object.values(sc.counts).reduce((a, b) => a + b, 0);
const n = Object.values(sc.counts).reduce((a, b) => a + b, 0) + sc.tokens;
const m2 = await forModel(sc.text);
noteInnerCuts(ctx, addCounts(sc.counts, m2.counts));
return { ok: { ...base, text: m2.text, ...(n ? { scrubbed: n } : {}) } };
Expand Down
Loading