// THE DISPLAYERS' ENGINE (demo epic D4): a compiled rule list applied to a // string a page is about to draw. Pure and client-safe — no node imports — so // the editor and umtool call it on the server (privacy-server.ts) and in the // browser (components/PrivacyProvider.tsx) alike. // // NULL RULES ARE THE IDENTITY: `applyPrivacy(null, s)` returns `s` itself, the // same string, which is what keeps every page byte-identical while the // `privacy` settings block is absent or at its defaults (compile.ts compiles // null then). // // THREE KINDS OF STEP, three costs: // - literal steps (paths, hostnames, a literal alias, a denylist line): one // linear pass over the whole string; // - the e-mail step: code, not a regex — every `@` is looked at once and the // address around it walked by hand (maskEmails), linear in the input; // - an OPERATOR's regex or glob (`bounded`): it passed regexSafety.ts's // static rule, so its match is at most `maxLen` long. It runs per line in // windows of PRIVACY_REGEX_MAX_INPUT that OVERLAP by more than `maxLen`; // each window resumes where the last match ended, so the matches are the // ones a whole-line scan would find and none straddling a cut is missed. // A match long enough to have used its capped quantifier (`.*` is run as // `.{0,256}`) to the cap hides the REST OF THE LINE with it. Each WINDOW // is timed: a rule that ever takes longer than PRIVACY_RULE_SLOW_MS on one // is disabled for the rest of the process and runs in FALLBACK, as a rule // compile.ts refused does: its literal fragments shown as [hidden] — or, // when it has none, every non-empty line it would run on. Never a no-op. // `onSlowRule` hears it, by the rule's number. // // Display only. Nothing here is ever applied to a value that is stored, // logged, sent to a job, written to a record, put in an href/src, or copied by // a copy button. export type PrivacyStep = { // A JS RegExp source and its flags (always global). re: string; flags: string; // A JS replacement string ($1, $, $$). to: string; // What the step is for, for a test, a warning or the audit: never its text. why: string; // From the operator's private rule files: never leaves the server. secret?: true; // An operator-written regex or glob: windowed, timed, disabled when slow. bounded?: true; // Its longest possible match (regexSafety.ts). maxLen?: number; // Its CERTAIN literal fragments (regex sources; compile.ts certainFragments) // for when it runs in fallback: on a line holding one, the text from a // leading fragment to the line's end — or the whole line, for a fragment // that does not start every match — is shown as [hidden]; with none, every // non-empty line it would run on is. fallback?: Array<{ re: string; lead: boolean }>; // Refused at compile time: its pattern never runs, only its fallback. refused?: true; // A match this long may have used its rewritten (capped) quantifier to the // cap: the rest of the line is hidden with it (regexSafety.ts capTrigger). capAt?: number; // Where this matches, the operator's pattern may match PAST the cap: the // line is hidden from there (regexSafety.ts capProbe). capProbe?: string; // Code rather than a regex: "email" masks addresses (re/flags unused). kind?: "email"; }; export type PrivacyRules = { v: 1; steps: PrivacyStep[] }; export type Displayer = (s: string) => string; /** The window an operator regex runs over at once (plus its overlaps). */ export const PRIVACY_REGEX_MAX_INPUT = 4096; /** One call of one operator rule longer than this disables the rule. */ export const PRIVACY_RULE_SLOW_MS = 50; export const HIDDEN = "[hidden]"; type Compiled = { rx: RegExp; to: string; step: PrivacyStep; bounded: boolean; email: boolean; overlap: number; fallback: Array<{ rx: RegExp; lead: boolean }>; capAt: number | null; probe: RegExp | null; }; const compiled = new WeakMap(); // Rules disabled for being slow, for the rest of the process. const disabled = new WeakSet(); let slowReporter: ((why: string, ms: number) => void) | null = null; /** Who hears that a rule was disabled (the server's log; the console otherwise). */ export function onSlowRule(fn: ((why: string, ms: number) => void) | null): void { slowReporter = fn; } function stepsOf(rules: PrivacyRules): Compiled[] { let c = compiled.get(rules); if (!c) { c = []; for (const s of rules.steps) { try { const flags = s.flags.includes("g") ? s.flags : `${s.flags}g`; c.push({ rx: new RegExp(s.kind === "email" ? "@" : s.re, flags), to: s.to, step: s, bounded: s.bounded === true, email: s.kind === "email", overlap: Math.max(64, (s.maxLen ?? 0) + 64), capAt: typeof s.capAt === "number" ? s.capAt : null, probe: s.capProbe ? new RegExp(s.capProbe, flags) : null, fallback: (s.fallback ?? []).flatMap((f) => { try { return [{ rx: new RegExp(f.re, "g"), lead: f.lead === true }]; } catch { return []; } }), }); } catch { // compile.ts only emits steps that compile; a hand-made rule list that // does not is a programming error, and a step dropped here is one less // rewrite — never an exception on a page. } } compiled.set(rules, c); } return c; } // ── e-mail, linear ─────────────────────────────────────────────────────────── // Character classes as lookup tables: 1 = a local-part character, 2 = a // domain character (both: letters, digits, `.` and `-`). const CLASS = new Uint8Array(128); for (let c = 0; c < 128; c++) { const ch = String.fromCharCode(c); if (/[A-Za-z0-9.-]/.test(ch)) CLASS[c] = 3; else if (/[_%+]/.test(ch)) CLASS[c] = 1; } const isLocal = (s: string, i: number) => { const c = s.charCodeAt(i); return c < 128 && (CLASS[c] & 1) !== 0; }; const isDomain = (s: string, i: number) => { const c = s.charCodeAt(i); return c < 128 && (CLASS[c] & 2) !== 0; }; const isAlpha = (c: number) => (c >= 65 && c <= 90) || (c >= 97 && c <= 122); /** Every e-mail address in `s` as `to`. Each character is looked at O(1) times. */ export function maskEmails(s: string, to: string): string { let at = s.indexOf("@"); if (at === -1) return s; const parts: string[] = []; let pos = 0; // emitted up to here let floor = 0; // a local part may not start before this while (at !== -1) { let a = at; while (a > floor && at - a < 64 && isLocal(s, a - 1)) a--; let b = at + 1; let doubleDot = false; while (b < s.length && b - at <= 253 && isDomain(s, b)) { if (s.charCodeAt(b) === 46 && s.charCodeAt(b - 1) === 46) doubleDot = true; b++; } let end = b; // A domain never ends with a dot or a hyphen ("mail a@b.co." ends a sentence). while (end > at + 1 && (s.charCodeAt(end - 1) === 46 || s.charCodeAt(end - 1) === 45)) end--; let ok = a < at && end > at + 1 && !doubleDot; if (ok) { // The last label: 2–24 letters, after a dot that is not the domain's first character. let t = end; while (t > at + 1 && isAlpha(s.charCodeAt(t - 1))) t--; const tld = end - t; ok = tld >= 2 && tld <= 24 && t - 1 > at + 1 && s.charCodeAt(t - 1) === 46; } if (ok && a >= pos) { parts.push(s.slice(pos, a), to); pos = end; floor = end; } else { floor = at + 1; } at = s.indexOf("@", Math.max(at + 1, floor)); } parts.push(s.slice(pos)); return parts.join(""); } // ── operator regexes, windowed ─────────────────────────────────────────────── /** One match's replacement, as String.replace builds it. */ function applyTemplate(m: RegExpExecArray, to: string): string { return to.replace(/\$(\$|&|\d{1,2}|<([^>]*)>)/g, (whole, t: string, name?: string) => { if (t === "$") return "$"; if (t === "&") return m[0]; if (name !== undefined) return m.groups?.[name] ?? ""; const n = Number(t); if (n >= 1 && n < m.length) return m[n] ?? ""; return whole; }); } /** What one displayText / displayPath call may spend on operator rules, in all. */ export const PRIVACY_CALL_BUDGET_MS = 150; // One call's budget across every operator rule and window. type Call = { deadline: number; spent: boolean }; class OutOfBudget extends Error { constructor(readonly emitted: string) { super("budget"); } } class Slow extends Error { constructor(readonly ms: number) { super("slow"); } } const now = () => (typeof performance !== "undefined" ? performance.now() : Date.now()); /** * One line, in windows of PRIVACY_REGEX_MAX_INPUT that overlap by more than * the rule's longest match. Each window resumes where the last match ended * (rx.lastIndex), so the matches are the ones a whole-line scan finds; a match * belongs to the window it starts in. A match long enough to have used the * capped quantifier to its cap (capAt) hides the rest of the line with it. * Each window is timed: one slower than PRIVACY_RULE_SLOW_MS throws Slow. */ function windows(line: string, overlap: number): Array<{ start: number; from: number; win: string; own0: number }> { const W = PRIVACY_REGEX_MAX_INPUT; const out = []; for (let start = 0; start < line.length || start === 0; start += W) { const from = Math.max(0, start - overlap); out.push({ start, from, win: line.slice(from, start + W + overlap), own0: start - from }); if (line.length === 0) break; } return out; } /** Where the cap probe first matches in the line (the rule may match past its cap there), or null. */ function probeAt(line: string, c: Compiled, call: Call): number | null { if (!c.probe) return null; const W = PRIVACY_REGEX_MAX_INPUT; for (const w of windows(line, c.overlap)) { // Out of the call's budget before the probe has looked everywhere: the // line is hidden from the window it had not read (fail closed). if (now() > call.deadline) { call.spent = true; return w.start; } const t0 = now(); c.probe.lastIndex = w.own0; const m = c.probe.exec(w.win); const took = now() - t0; if (took > PRIVACY_RULE_SLOW_MS) throw new Slow(took); if (m && m.index < w.own0 + W) return w.from + m.index; } return null; } function scanLine(line: string, c: Compiled, call: Call): string { const W = PRIVACY_REGEX_MAX_INPUT; const rx = c.rx; const stopAt = probeAt(line, c, call); let out = ""; let pos = 0; let rest = false; for (const { from, win, own0 } of windows(line, c.overlap)) { if (now() > call.deadline) { // Out of the call's budget: what was read stays as it was drawn, the // rest of this line is hidden. call.spent = true; throw new OutOfBudget(out + (line.slice(pos).trim() ? HIDDEN : line.slice(pos))); } rx.lastIndex = Math.max(0, pos - from); const t0 = now(); let m: RegExpExecArray | null; let stop = false; while ((m = rx.exec(win))) { if (m[0] === "") { rx.lastIndex++; continue; } if (m.index >= own0 + W) break; // the next window's const ms = from + m.index; if (stopAt !== null && ms > stopAt) { stop = true; break; } out += line.slice(pos, ms) + applyTemplate(m, c.to); pos = ms + m[0].length; if (c.capAt !== null && m[0].length >= c.capAt) { pos = line.length; rest = true; stop = true; break; } if (stopAt !== null && ms === stopAt) { stop = true; break; } } const took = now() - t0; if (took > PRIVACY_RULE_SLOW_MS) throw new Slow(took); if (stop) break; } if (stopAt !== null && !rest) { // From the probe's match on, the line is hidden (whatever a match there // already replaced stays replaced). out += pos <= stopAt ? line.slice(pos, stopAt) + HIDDEN : HIDDEN; return out; } return out + line.slice(pos); } const hideLines = (lines: string[]) => lines.map((line) => (line.trim() ? HIDDEN : line)); /** Line by line; out of the call's budget, every line not yet read is hidden. */ function boundedReplace(s: string, c: Compiled, call: Call): string { const lines = s.split("\n"); const out: string[] = []; for (let i = 0; i < lines.length; i++) { try { out.push(scanLine(lines[i], c, call)); } catch (err) { if (!(err instanceof OutOfBudget)) throw err; out.push(err.emitted, ...hideLines(lines.slice(i + 1))); return out.join("\n"); } } return out.join("\n"); } /** * A rule in FALLBACK (refused, or disabled for a slow window): on a line that * holds one of its certain fragments, from a leading fragment's first * occurrence to the line's end — or the whole line, for a fragment that does * not start every match — is shown as [hidden]; a rule with no certain * fragment hides every non-empty line. Never a no-op, never only the literal. */ function fallbackReplace(s: string, c: Compiled): string { if (!c.fallback.length) return hideLines(s.split("\n")).join("\n"); return s .split("\n") .map((line) => { let from = -1; for (const f of c.fallback) { f.rx.lastIndex = 0; const m = f.rx.exec(line); if (!m) continue; if (!f.lead) return HIDDEN; if (from === -1 || m.index < from) from = m.index; } return from === -1 ? line : line.slice(0, from) + HIDDEN; }) .join("\n"); } const budgetSaid = new Set(); let budgetReporter: ((why: string) => void) | null = null; /** Who hears that a rule ran out of a call's budget (once per rule per process). */ export function onBudget(fn: ((why: string) => void) | null): void { budgetReporter = fn; } /** Forget which rules were told about the budget (tests). */ export function resetBudgetNotes(): void { budgetSaid.clear(); } function runBounded(s: string, c: Compiled, call: Call): string { if (c.step.refused || disabled.has(c.step)) return fallbackReplace(s, c); const sayBudget = () => { if (budgetSaid.has(c.step.why)) return; budgetSaid.add(c.step.why); const say = budgetReporter ?? ((why: string) => console.warn( `[privacy] ${why} ran out of one call's budget (${PRIVACY_CALL_BUDGET_MS} ms for every operator rule): the text it had not read is shown as [hidden], one per line; the rule stays on`, )); say(c.step.why); }; if (call.spent) { // An operator rule that has not run on this call's text at all. sayBudget(); return hideLines(s.split("\n")).join("\n"); } try { const out = boundedReplace(s, c, call); if (call.spent) sayBudget(); return out; } catch (err) { if (!(err instanceof Slow)) throw err; disabled.add(c.step); const say = slowReporter ?? ((why: string, t: number) => console.warn( `[privacy] ${why} took ${Math.round(t)} ms on one window; disabled, it now runs in fallback (on a line holding one of its certain fragments, from that fragment or the whole line; with none, every non-empty line, shown as [hidden])`, )); say(c.step.why, err.ms); return fallbackReplace(s, c); } } /** Was this step disabled for being slow (tests)? */ export function isDisabled(step: PrivacyStep): boolean { return disabled.has(step); } /** `s` as a page shows it under `rules`. Null rules: `s` itself. */ export function applyPrivacy(rules: PrivacyRules | null | undefined, s: string): string { if (!rules || typeof s !== "string" || s === "") return s; let out = s; // ORDER: the steps run in compile.ts's order (roots, home, mounts, volumes, // host, user, aliases, the private files' rules, e-mail). The built-in and // literal ones always run on all the text; only an operator regex or glob // spends the call's budget, and one that finds it spent shows the text it // could not read as [hidden] (one per non-empty line). The budget is the // input's problem, not the rule's: it is not disabled for it. const call: Call = { deadline: now() + PRIVACY_CALL_BUDGET_MS, spent: false }; for (const c of stepsOf(rules)) { if (c.email) out = maskEmails(out, c.to); else if (c.bounded) out = runBounded(out, c, call); else out = out.replace(c.rx, c.to); } return out; } /** The two displayers bound to one rule list (identity for null). */ export function displayersOf(rules: PrivacyRules | null | undefined): { displayPath: Displayer; displayText: Displayer } { if (!rules) return IDENTITY; const displayText: Displayer = (s) => applyPrivacy(rules, s); return { displayPath: displayText, displayText }; } const identity: Displayer = (s) => s; export const IDENTITY: { displayPath: Displayer; displayText: Displayer } = { displayPath: identity, displayText: identity }; /** The rules a browser may hold: every secret step dropped. Null when none is left. */ export function publicRules(rules: PrivacyRules | null | undefined): PrivacyRules | null { if (!rules) return null; const steps = rules.steps.filter((s) => !s.secret); return steps.length ? { v: 1, steps } : null; }