commit 5362b71171a6911c4d62d03fc12577e6d06bb45e
parent 200646d65b3437a6e672d95c4a3e7333fb18798c
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date: Fri, 13 Nov 2026 02:21:41 -0500
privacy D4: the settings.privacy block and the displayers' engine
settings.privacy (common/lib/privacySettings.ts): displayPaths full|home|masked,
hideHost, hideUser, hidePrivateSites, aliases (source-mirror scrub lines),
maskEmail and useSourceRules. Every default is today's behaviour; a block that
is present but wrong, or a settings.json that does not parse, is read STRICT
(never silently off) and warned once, by key (unknown keys by count).
SETTINGS.md and settings.json.example regenerated.
common/lib/privacy/: compile.ts turns the block into an ordered rule list
(location roots, the home dir in plain, JSON-escaped and percent-encoded
forms, file:// URLs, media mounts, volume ids, hostname and user name
whole-word in any case, aliases, the private files' rules as SECRET steps,
e-mail by code). display.ts applies it: null rules are the identity; an
operator regex or glob must pass regexSafety.ts's static rule (one unbounded
or large quantifier, no backreference, no lookaround, no repeated group with a
quantifier or alternation, ranges AND alternation branches multiplying to at
most 1,024, a match of at most 2,048 characters, `.*` run as `.{0,256}`); it
runs per line in overlapping windows that resume where the last match ended;
a match that may have used its capped quantifier to the cap, or a place where
the pattern could run past it, hides the rest of the line; each window is
timed, and a slow rule -- like a refused one -- runs in FALLBACK: its literal
fragments hidden, or every line it would run on where it has none (never a
no-op). privacy-server.ts gives the server displayPath / displayText and the
browser rules with every secret step dropped; PrivacyProvider.tsx gives client
components useDisplay() and refreshes the router on a navigation.
parseScrubRules' line split moved unchanged to lib/scrubRuleLine.ts (with
operatorLines); publish/scrubRuleLine.test.ts runs the pre-move
implementation against the new one. No SOURCE_STEP_VERSION bump.
noOperatorNames.test.ts fails if any of the lane's files names the current
account or this machine (computed at test time, never printed).
Co-Authored-By: Claude <noreply@anthropic.com>
Diffstat:
19 files changed, 2270 insertions(+), 28 deletions(-)
diff --git a/SETTINGS.md b/SETTINGS.md
@@ -60,6 +60,7 @@ A copied example PINS every default it spells — including each lane's `autoQue
| [`jobs`](#jobs) | object — see below |
| [`serviceCookies`](#servicecookies) | object — see below |
| [`lookouts`](#lookouts) | object — see below |
+| [`privacy`](#privacy) | object — see below |
## `adminTitle`
@@ -1452,3 +1453,33 @@ Default:
"items": []
}
```
+
+## `privacy`
+
+What the editor's and umtool's pages SHOW of this machine (demo epic D4): local paths with the home directory as `~` or masked, the hostname as a fixed word, private sites left out of the pickers, e-mail addresses masked, and the operator's own display aliases in the source mirror's scrub format. Display only — nothing stored, logged, sent to a job or written to a record changes, and copy buttons copy the real path. Every default is today's behaviour: with the block absent or at its defaults the pages are byte-identical. `archilyzer privacy audit` checks the rendered pages against a denylist. Set with `pnpm ops settings --json '{"patch":{"privacy":{"displayPaths":"home"}}}'`. See PrivacySettings and common/lib/privacy/.
+
+#### `privacy`
+
+| Key | Default | Description |
+|---|---|---|
+| `displayPaths` | `"full"` | How a page shows a local path. `"full"` (default): as it is. `"home"`: the home directory as `~`, and the user's name in a removable-media mount (`/run/media/<user>/…`, `/media/<user>/…`) as `user`. `"masked"`: the home directory as `/home/user`, a storage location's root (and its volume's mountpoint) as `[<its label>]`, any other removable-media mount (`/media/<user>/<volume>`, `/run/media/…`, `/mnt/<uuid>`) as `/media/drive`, and a configured volume's UUID, in any case, as `[volume]`. Either mode also catches the path JSON-escaped (`\/home\/u`) and percent-encoded (`%2Fhome%2Fu`), and a `file://` URL keeps its shape (`file:///home/user/…`); a path ends at punctuation (`/home/u.` is the home dir, `/home/u.bak` is not). Display only: copy buttons copy the real path. While any key is on, the editor's and umtool's pages carry the rules their browser applies — the values they hide included — in the page's script payload (see `useSourceRules`). |
+| `hideHost` | `false` | Show this machine's hostname (os.hostname(), its short form and ARCHILYZER_HOST_ID; three characters or more) as the word `host` wherever a page draws it as text. Matched whole-word, in any case, so a hostname inside another word is left alone (a hostname that is itself an ordinary word is replaced where it stands alone); links and other attributes a page needs to work are never rewritten. Default false. |
+| `hideUser` | `false` | Show this account's user name (three characters or more) as the word `user` wherever a page draws it as a whole word, in any case — a log line's `by: … (name)`, a path segment under `/run/media/`. A name inside another word is left alone. Default false. |
+| `hidePrivateSites` | `false` | Leave the sites marked private (site.json `audience: "private"`) out of the lists and pickers a page DRAWS: the editor's site-scope picker, /channels' Focus bar and a channel's site memberships (a hidden membership is still saved as it was), umtool's home, /projects, /work and its research source pickers (a project is hidden when it belongs to a private site's article). A private site that is the current choice is shown as "A private site". Only what is drawn: every lookup, default and allow-list keeps the private sites, so a case on a private site's source keeps reading it. Not access control: a private site's own pages still open by URL. An article's own `audience` is a different notion and hides nothing. If the sites cannot be read, umtool hides every site's pieces (fail closed). Default false. |
+| `aliases` | `[]` | Display rules in the SOURCE MIRROR's scrub format (common/lib/scrubRuleLine.ts): one rule per entry — `lhs==>rhs` (literal), `literal:lhs==>rhs`, `regex:pattern==>rhs` (`\1` in rhs is group 1) or `glob:pattern==>rhs`; with no `==>` the match shows as `***REMOVED***`. Applied to displayed text after the path and host rules. A `regex:` or `glob:` rule must be cheap to run on every render: at most ONE unbounded or large quantifier (`*`, `+`, `{n,}`, `{n,m}` with m > 64, lazy forms too; it then repeats at most 256 times), no backreference, no repeated group holding a quantifier or an alternation, quantifier ranges multiplying to at most 1,024 and a match of at most 2,048 characters — so a glob has at most one `*`. A rule that breaks this, or does not compile, is not applied: its literal fragments (three characters or more) are shown as `[hidden]` instead (fail closed) and it is reported by its number in the server log and in `archilyzer privacy audit`. A rule that still takes over 50 ms on one call is disabled the same way for the rest of the process. Rules run per line; a line over 4,096 characters is read in overlapping windows. Set with `pnpm ops settings --json '{"patch":{"privacy":{"aliases":["old==>new"]}}}'`. Default []. |
+| `maskEmail` | `false` | Show every e-mail address a page draws as text as `[email]` (mailto links keep working). Default false. |
+| `useSourceRules` | `false` | Also apply the source mirror's private rule files (SOURCE_SCRUB_FILE, default `~/.config/archilyzer/source-scrub.txt`, as aliases; SOURCE_DENYLIST_FILE's literals shown as `[hidden]`). Read by the SERVER only: their rules are applied where a page is rendered on the server and are never sent to a browser, a response, a log or an error (a client-rendered panel does not get them). A missing file is a server-log warning naming its path and error code, and nothing else — `archilyzer privacy audit` is the check that the rules took. Default false. AFTER TURNING PRIVACY ON, RELOAD THE OPEN PAGES: a client-rendered panel on a page already open stays unmasked until it is loaded again (a change while on, or turning it off, reaches them on the next navigation). NOTE, for every rule but these: the browser applies the rules itself, so the page it receives CARRIES the values they hide (the home dir, the hostname, the user name, the volume UUIDs and roots, each alias's left side) in its script payload — view-source shows them; the audit reads only what a page draws, not its scripts. |
+
+Default:
+
+```json
+{
+ "displayPaths": "full",
+ "hideHost": false,
+ "hideUser": false,
+ "hidePrivateSites": false,
+ "aliases": [],
+ "maskEmail": false,
+ "useSourceRules": false
+}
+```
diff --git a/common/components/PrivacyProvider.tsx b/common/components/PrivacyProvider.tsx
@@ -0,0 +1,57 @@
+"use client";
+
+// THE BROWSER'S DISPLAYERS (demo epic D4): `useDisplay()` gives a client
+// component the same `displayPath` / `displayText` pair the server has
+// (lib/privacy/privacy-server.ts), bound to the rules the root layout hands
+// <PrivacyProvider> — `clientPrivacyRules()`, which never holds a rule from
+// the operator's private files (those apply only where a page renders on the
+// server).
+//
+// No provider, no rules: the identity. The root layouts render the provider
+// ONLY while settings.privacy is active, so a page with the block absent
+// carries no extra element and no extra prop.
+//
+// KEEPING THE RULES CURRENT (review round 1, S8a). A client-side navigation
+// does not re-render the root layout, so a changed `privacy` block would
+// leave client panels on the old rules. While the provider is mounted, a
+// navigation asks the router to refresh (at most once every REFRESH_MS),
+// which re-renders the layout with the rules as they are now — a change, or
+// privacy turned OFF, reaches the client panels on the next page. Turning it
+// ON from off reaches them at the next full load (in the editor, also at its
+// auto-refresh tick, which re-renders the layout too).
+//
+// The rules here CARRY the values they hide (the home dir, the hostname, the
+// user name, the volume UUIDs and roots, every alias's left side): they are
+// in the page's script payload, which view-source shows. The audit reads only
+// what is drawn. SETTINGS.md says so too.
+
+import { createContext, useContext, useEffect, useMemo, useRef, type ReactNode } from "react";
+import { usePathname, useRouter } from "next/navigation";
+import { displayersOf, IDENTITY, type PrivacyRules } from "../lib/privacy/display";
+
+const PrivacyContext = createContext<PrivacyRules | null>(null);
+
+export const REFRESH_MS = 10_000;
+
+export function PrivacyProvider({ rules, children }: { rules: PrivacyRules; children: ReactNode }) {
+ const router = useRouter();
+ const pathname = usePathname();
+ const first = useRef(true);
+ const last = useRef(0);
+ useEffect(() => {
+ if (first.current) {
+ first.current = false;
+ last.current = Date.now();
+ return;
+ }
+ if (Date.now() - last.current < REFRESH_MS) return;
+ last.current = Date.now();
+ router.refresh();
+ }, [pathname, router]);
+ return <PrivacyContext.Provider value={rules}>{children}</PrivacyContext.Provider>;
+}
+
+export function useDisplay(): typeof IDENTITY {
+ const rules = useContext(PrivacyContext);
+ return useMemo(() => displayersOf(rules), [rules]);
+}
diff --git a/common/lib/privacy/compile.ts b/common/lib/privacy/compile.ts
@@ -0,0 +1,376 @@
+// settings.privacy → the rule list the displayers apply (display.ts). Pure:
+// the server (privacy-server.ts) and `archilyzer privacy audit` hand it what
+// they read — the settings block, the home dir, the hostnames, the storage
+// locations and, only when `useSourceRules` is on, the TEXT of the operator's
+// two private rule files — and it answers rules plus problems.
+//
+// THE ORDER IS THE SOURCE MIRROR'S: the path rules first (as the mirror's
+// built-in home rule is first), then the host, then the operator's aliases,
+// then the private scrub rules and the denylist, then e-mail addresses.
+//
+// A PROBLEM NEVER QUOTES A RULE. It names the rule's source and line number
+// ("aliases line 3", "scrub line 2", as sourceAudit.ts names a literal) and
+// what is wrong; a RegExp's own error message is never kept, because V8's
+// quotes the pattern.
+//
+// FAIL CLOSED. A regex or glob that does not compile, or that could backtrack
+// without bound (a quantified group holding a quantifier or an alternation,
+// or more than two unbounded quantifiers), is not applied — its LITERAL
+// FRAGMENTS (runs of three or more plain characters) are shown as `[hidden]`
+// instead, and the problem is reported by number.
+
+import { DEFAULT_PRIVACY_SETTINGS, PRIVACY_ALIAS_MAX_CHARS, type PrivacySettings } from "../privacySettings";
+import { SCRUB_REMOVED, isScrubSkip, operatorLines, splitScrubLine, type ScrubLine } from "../scrubRuleLine";
+import type { PrivacyRules, PrivacyStep } from "./display";
+import { analyzeRegex } from "./regexSafety";
+
+/** The home dir in "masked" mode: the source mirror's HOME_REPLACEMENT. */
+export const MASKED_HOME = "/home/user";
+export const HOST_WORD = "host";
+export const EMAIL_WORD = "[email]";
+export const HIDDEN_WORD = "[hidden]";
+export const DRIVE_WORD = "/media/drive";
+export const VOLUME_WORD = "[volume]";
+export const USER_WORD = "user";
+
+export type PrivacyLocation = {
+ id: string;
+ label: string;
+ root: string;
+ volume?: { uuid?: string; mountpoint?: string };
+};
+
+export type PrivacyCompileInput = {
+ privacy: PrivacySettings | null | undefined;
+ homeDir: string;
+ hostnames: readonly string[];
+ // The account's name (os.userInfo().username); default the home dir's last segment.
+ username?: string | null;
+ locations: readonly PrivacyLocation[];
+ // The private files' text, read by the server only when useSourceRules.
+ scrubText?: string | null;
+ denyText?: string | null;
+};
+
+export type PrivacyProblem = { source: "aliases" | "scrub" | "denylist"; line: number; what: string };
+
+export function problemLine(p: PrivacyProblem): string {
+ return `${p.source} line ${p.line}: ${p.what}`;
+}
+
+export const escapeRegExp = (s: string) => s.replace(/[.*+?^${}()|[\]\\/]/g, "\\$&");
+const escapeReplacement = (s: string) => s.replace(/\$/g, "$$$$");
+
+// After a path: not more of a name. Before a hostname: not part of a word.
+// A path ends where a name cannot go on: `/home/u.` and `/home/u,` end at
+// the punctuation, `/home/u.bak` and `/home/u2` are other names.
+const PATH_END = "(?![A-Za-z0-9_-]|\\.[A-Za-z0-9_-])";
+const WORD_START = "(?<![A-Za-z0-9_-])";
+const WORD_END = "(?![A-Za-z0-9_-])";
+
+/** Python `re.sub` template → a JS replacement string. */
+export function pythonReplacement(rhs: string): string {
+ let out = "";
+ for (let i = 0; i < rhs.length; i++) {
+ const c = rhs[i];
+ if (c === "$") {
+ out += "$$";
+ continue;
+ }
+ if (c !== "\\" || i === rhs.length - 1) {
+ out += c;
+ continue;
+ }
+ const rest = rhs.slice(i + 1);
+ const g = /^g<([A-Za-z_][A-Za-z0-9_]*|\d+)>/.exec(rest);
+ if (g) {
+ out += /^\d+$/.test(g[1]) ? `$${g[1]}` : `$<${g[1]}>`;
+ i += g[0].length;
+ continue;
+ }
+ const d = /^\d{1,2}/.exec(rest);
+ if (d) {
+ out += `$${d[0]}`;
+ i += d[0].length;
+ continue;
+ }
+ const e = rest[0];
+ out += e === "n" ? "\n" : e === "t" ? "\t" : e === "\\" ? "\\" : `\\${e}`;
+ i += 1;
+ }
+ return out;
+}
+
+/** A Python regex as a JS source + flags, or null when it uses what JS lacks. */
+export function pythonRegex(src: string): { re: string; flags: string } | null {
+ let flags = "g";
+ let re = src;
+ const lead = /^\(\?([aiLmsux]+)\)/.exec(re);
+ if (lead) {
+ for (const f of lead[1]) {
+ if (f === "i" || f === "m" || f === "s") flags += f;
+ else if (f !== "u" && f !== "a") return null;
+ }
+ re = re.slice(lead[0].length);
+ }
+ re = re
+ .replace(/\(\?P<([A-Za-z_][A-Za-z0-9_]*)>/g, "(?<$1>")
+ .replace(/\(\?P=([A-Za-z_][A-Za-z0-9_]*)\)/g, "\\k<$1>")
+ .replace(/\\A/g, "^")
+ .replace(/\\Z/g, "$");
+ if (/\(\?[aiLmsux]+\)/.test(re)) return null;
+ return { re, flags: [...new Set(flags)].join("") };
+}
+
+/** fnmatch.translate, as git-filter-repo uses it for `glob:`. */
+export function globRegex(glob: string): string {
+ let out = "";
+ for (let i = 0; i < glob.length; i++) {
+ const c = glob[i];
+ if (c === "*") out += ".*";
+ else if (c === "?") out += ".";
+ else if (c === "[") {
+ const j = glob.indexOf("]", i + 2);
+ if (j === -1) out += "\\[";
+ else {
+ let body = glob.slice(i + 1, j).replace(/\\/g, "\\\\");
+ if (body.startsWith("!")) body = `^${body.slice(1)}`;
+ else if (body.startsWith("^")) body = `\\${body}`;
+ out += `[${body}]`;
+ i = j;
+ }
+ } else out += escapeRegExp(c);
+ }
+ return out;
+}
+
+/**
+ * Would regexSafety.ts refuse this JS regex source? (The rule, M1 of the
+ * review: one unbounded-or-large quantifier at most, no backreference, no
+ * repeated group holding a quantifier or an alternation, a bounded range
+ * product and match length.)
+ */
+export function riskyRegex(re: string): boolean {
+ return !analyzeRegex(re).ok;
+}
+
+/** The runs of three or more plain characters a broken regex or glob still names. */
+export function literalFragments(pattern: string, kind: "regex" | "glob"): string[] {
+ const out: string[] = [];
+ let run = "";
+ const flush = () => {
+ if (run.length >= 3) out.push(run);
+ run = "";
+ };
+ const meta = kind === "glob" ? "*?[]" : ".*+?()[]{}|^$";
+ for (let i = 0; i < pattern.length; i++) {
+ const c = pattern[i];
+ if (kind === "regex" && c === "\\") {
+ const n = pattern[i + 1];
+ i++;
+ if (n !== undefined && /[^A-Za-z0-9]/.test(n)) run += n;
+ else flush();
+ continue;
+ }
+ if (kind === "regex" && (c === "?" || c === "*" || c === "{")) {
+ // The character before an optional or repeated quantifier is not a
+ // certain part of a match.
+ run = run.slice(0, -1);
+ flush();
+ continue;
+ }
+ if (meta.includes(c)) {
+ flush();
+ continue;
+ }
+ run += c;
+ }
+ flush();
+ return [...new Set(out)];
+}
+
+type LineSource = "aliases" | "scrub";
+
+function compileScrubLine(
+ line: ScrubLine,
+ where: { source: LineSource; n: number; tooLong?: boolean },
+ secret: boolean,
+ steps: PrivacyStep[],
+ problems: PrivacyProblem[],
+): void {
+ const mark = secret ? ({ secret: true } as const) : {};
+ const why = `${where.source} line ${where.n}`;
+ const hideFragments = (what: string) => {
+ const frags =
+ line.kind === "regex" || line.kind === "glob"
+ ? literalFragments(line.pattern, line.kind)
+ : line.pattern.length >= 3
+ ? [line.pattern]
+ : [];
+ problems.push({
+ source: where.source,
+ line: where.n,
+ what: `${what}; ${
+ frags.length
+ ? `it runs in fallback: its ${frags.length} literal fragment${frags.length === 1 ? " is" : "s are"} hidden instead`
+ : "it runs in fallback: it has no literal fragment, so every line it would run on is shown as [hidden]"
+ }`,
+ });
+ // A REFUSED step: display.ts never runs its pattern, only its fallback —
+ // the fragments, or the whole line when there are none (never a no-op).
+ steps.push({ re: "(?!)", flags: "g", to: HIDDEN_WORD, why: `${why} (fallback)`, bounded: true, refused: true, fallback: frags.map(escapeRegExp), ...mark });
+ };
+ if (where.tooLong) return hideFragments(`is longer than ${PRIVACY_ALIAS_MAX_CHARS.toLocaleString("en-US")} characters`);
+ if (line.kind === "plain" || line.kind === "literal") {
+ steps.push({
+ re: escapeRegExp(line.pattern),
+ flags: "g",
+ to: line.replacement === null ? SCRUB_REMOVED : escapeReplacement(line.replacement),
+ why,
+ ...mark,
+ });
+ return;
+ }
+ const js = line.kind === "glob" ? { re: globRegex(line.pattern), flags: "gs" } : pythonRegex(line.pattern);
+ if (!js) return hideFragments(`does not compile (${line.kind}: a Python-only construct)`);
+ try {
+ new RegExp(js.re, js.flags);
+ } catch {
+ return hideFragments(`does not compile (${line.kind})`);
+ }
+ const verdict = analyzeRegex(js.re);
+ if (!verdict.ok) return hideFragments(`is refused as possibly slow (${line.kind}: ${verdict.why})`);
+ try {
+ new RegExp(verdict.source, js.flags);
+ } catch {
+ return hideFragments(`does not compile (${line.kind})`);
+ }
+ const to = line.replacement === null ? SCRUB_REMOVED : line.kind === "regex" ? pythonReplacement(line.replacement) : escapeReplacement(line.replacement);
+ // What the rule falls back to if display.ts finds it slow at run time.
+ const fallback = literalFragments(line.pattern, line.kind).map(escapeRegExp);
+ steps.push({
+ re: verdict.source,
+ flags: js.flags,
+ to,
+ why,
+ bounded: true,
+ maxLen: verdict.maxLen,
+ fallback,
+ ...(verdict.capTrigger !== null ? { capAt: verdict.capTrigger } : {}),
+ ...(verdict.capProbe !== null ? { capProbe: verdict.capProbe } : {}),
+ ...mark,
+ });
+}
+
+function compileScrubLines(
+ lines: readonly string[],
+ source: LineSource,
+ secret: boolean,
+ steps: PrivacyStep[],
+ problems: PrivacyProblem[],
+): void {
+ lines.forEach((raw, i) => {
+ if (isScrubSkip(raw)) return;
+ const split = splitScrubLine(raw, i + 1);
+ if (!split.ok) {
+ problems.push({ source, line: i + 1, what: "has an empty left side; it matches nothing" });
+ return;
+ }
+ // The aliases' own cap (the sanitizer drops a longer alias) holds for a
+ // scrub-file line too: a longer one runs in fallback only.
+ compileScrubLine(split.line, { source, n: i + 1, tooLong: raw.length > PRIVACY_ALIAS_MAX_CHARS }, secret, steps, problems);
+ });
+}
+
+/** The denylist's line format (sourceAudit.ts parseDenylist): `i:` = any case. */
+function compileDenylist(text: string, steps: PrivacyStep[]): void {
+ operatorLines(text).forEach((raw, i) => {
+ const line = raw.trim();
+ if (line === "" || line.startsWith("#")) return;
+ const ci = line.startsWith("i:");
+ const lit = ci ? line.slice(2).trim() : line;
+ if (!lit) return;
+ steps.push({ re: escapeRegExp(lit), flags: ci ? "gi" : "g", to: HIDDEN_WORD, why: `denylist line ${i + 1}`, secret: true });
+ });
+}
+
+const cleanPath = (p: string | undefined) => (p ?? "").trim().replace(/\/+$/, "");
+
+// A path's own forms as a page may carry them: plain, JSON-escaped
+// (`\/home\/u`) and percent-encoded (`%2Fhome%2Fu`, either case).
+function pathForms(p: string): Array<{ re: string; flags: string; enc: (s: string) => string }> {
+ const json = p.replace(/\//g, "\\/");
+ const pct = p.replace(/\//g, "%2F");
+ const out: Array<{ re: string; flags: string; enc: (s: string) => string }> = [
+ { re: escapeRegExp(p), flags: "g", enc: (s) => s },
+ ];
+ if (json !== p) out.push({ re: escapeRegExp(json), flags: "g", enc: (s) => s.replace(/\//g, "\\/") });
+ if (pct !== p) out.push({ re: escapeRegExp(pct).replace(/%2F/g, "%2[Ff]"), flags: "g", enc: (s) => s.replace(/\//g, "%2F") });
+ return out;
+}
+
+export function compilePrivacy(input: PrivacyCompileInput): { rules: PrivacyRules | null; problems: PrivacyProblem[] } {
+ const p = input.privacy ?? DEFAULT_PRIVACY_SETTINGS;
+ const steps: PrivacyStep[] = [];
+ const problems: PrivacyProblem[] = [];
+ const home = cleanPath(input.homeDir);
+ const homeOk = home.length > 1 && home !== MASKED_HOME;
+ // The user's name as the home dir and the media mounts spell it.
+ const user = (input.username ?? (homeOk ? home.split("/").pop() : "") ?? "").trim();
+
+ if (p.displayPaths === "masked") {
+ const roots: Array<{ root: string; label: string }> = [];
+ for (const l of input.locations) {
+ const label = (l.label || l.id).trim();
+ for (const r of [cleanPath(l.root), cleanPath(l.volume?.mountpoint)]) {
+ if (r.length > 1 && label) roots.push({ root: r, label });
+ }
+ }
+ roots.sort((a, b) => b.root.length - a.root.length);
+ const seen = new Set<string>();
+ for (const r of roots) {
+ if (seen.has(r.root)) continue;
+ seen.add(r.root);
+ for (const f of pathForms(r.root)) {
+ steps.push({ re: f.re + PATH_END, flags: f.flags, to: escapeReplacement(`[${r.label}]`), why: "location root" });
+ }
+ }
+ }
+ if (p.displayPaths !== "full" && homeOk) {
+ // A file:// URL keeps a path's shape in either mode: `file:///home/user/…`.
+ steps.push({ re: `file://${escapeRegExp(home)}${PATH_END}`, flags: "g", to: `file://${MASKED_HOME}`, why: "home dir (file url)" });
+ for (const f of pathForms(home)) {
+ steps.push({ re: f.re + PATH_END, flags: f.flags, to: escapeReplacement(f.enc(p.displayPaths === "home" ? "~" : MASKED_HOME)), why: "home dir" });
+ }
+ }
+ if (p.displayPaths === "masked") {
+ steps.push({ re: "(?:/run)?/media/[^/\\s\"'<>]+/[^/\\s\"'<>]+", flags: "g", to: DRIVE_WORD, why: "removable-media mount" });
+ steps.push({ re: "/mnt/[0-9A-Fa-f]{4,}(?:-[0-9A-Fa-f]{2,})+" + PATH_END, flags: "g", to: DRIVE_WORD, why: "uuid mount" });
+ const uuids = [...new Set(input.locations.map((l) => (l.volume?.uuid ?? "").trim()).filter((u) => u.length >= 4))];
+ for (const u of uuids) steps.push({ re: `(?<![0-9A-Za-z-])${escapeRegExp(u)}(?![0-9A-Za-z-])`, flags: "gi", to: VOLUME_WORD, why: "volume uuid" });
+ } else if (p.displayPaths === "home" && user.length >= 1) {
+ // "home": a removable-media mount names the user too — that segment only.
+ steps.push({ re: `(/(?:run/)?media/)${escapeRegExp(user)}(?=/|$)`, flags: "g", to: "$1user", why: "media mount user" });
+ }
+ if (p.hideHost) {
+ const names = [...new Set(input.hostnames.flatMap((h) => [h.trim(), h.trim().split(".")[0]]))]
+ .filter((h) => h.length >= 3 && h.toLowerCase() !== "localhost" && h.toLowerCase() !== HOST_WORD)
+ .sort((a, b) => b.length - a.length);
+ if (names.length) {
+ steps.push({ re: `${WORD_START}(?:${names.map(escapeRegExp).join("|")})${WORD_END}`, flags: "gi", to: HOST_WORD, why: "hostname" });
+ }
+ }
+ if (p.hideUser && user.length >= 3 && user.toLowerCase() !== USER_WORD) {
+ steps.push({ re: `${WORD_START}${escapeRegExp(user)}${WORD_END}`, flags: "gi", to: USER_WORD, why: "user name" });
+ }
+ compileScrubLines(p.aliases, "aliases", false, steps, problems);
+ if (p.useSourceRules) {
+ if (input.scrubText) compileScrubLines(operatorLines(input.scrubText), "scrub", true, steps, problems);
+ if (input.denyText) compileDenylist(input.denyText, steps);
+ }
+ if (p.maskEmail) {
+ // Linear, by code (display.ts maskEmails): no regex scans for it.
+ steps.push({ re: "@", flags: "g", to: EMAIL_WORD, why: "e-mail", kind: "email" });
+ }
+ return { rules: steps.length ? { v: 1, steps } : null, problems };
+}
diff --git a/common/lib/privacy/display.test.ts b/common/lib/privacy/display.test.ts
@@ -0,0 +1,164 @@
+// The displayers' engine and compiler (demo epic D4): identity at the
+// defaults, the path / host / alias / e-mail rules, fail-closed broken rules,
+// the regex bound, and secret steps kept off the client.
+//
+// Run with: node_modules/.bin/tsx --test common/lib/privacy/display.test.ts
+
+import { test } from "node:test";
+import assert from "node:assert/strict";
+import { DEFAULT_PRIVACY_SETTINGS, sanitizePrivacy, privacyActive, type PrivacySettings } from "../privacySettings";
+import { compilePrivacy, literalFragments, pythonReplacement, riskyRegex, type PrivacyCompileInput } from "./compile";
+import { applyPrivacy, displayersOf, IDENTITY, PRIVACY_REGEX_MAX_INPUT, publicRules } from "./display";
+
+const HOME = "/home/someone";
+const base = (privacy: Partial<PrivacySettings>, extra: Partial<PrivacyCompileInput> = {}): PrivacyCompileInput => ({
+ privacy: { ...DEFAULT_PRIVACY_SETTINGS, ...privacy },
+ homeDir: HOME,
+ hostnames: ["boxen"],
+ locations: [{ id: "platter", label: "Platter", root: "/run/media/someone/1234-ABCD/archive", volume: { uuid: "1234-ABCD", mountpoint: "/run/media/someone/1234-ABCD" } }],
+ ...extra,
+});
+const show = (privacy: Partial<PrivacySettings>, s: string, extra: Partial<PrivacyCompileInput> = {}) =>
+ applyPrivacy(compilePrivacy(base(privacy, extra)).rules, s);
+
+const CORPUS = [
+ `${HOME}/Projects/x/out.mp4`,
+ "held by pid 12 on boxen since 13:31",
+ "write to someone@example.com",
+ "/run/media/someone/1234-ABCD/archive/chan/media",
+ "",
+ "plain words",
+];
+
+test("defaults: no rules, and every displayer returns its input itself", () => {
+ assert.equal(privacyActive(DEFAULT_PRIVACY_SETTINGS), false);
+ assert.deepEqual(sanitizePrivacy(undefined), DEFAULT_PRIVACY_SETTINGS);
+ // Present but wrong is read STRICT, never as off (review round 1, S3).
+ assert.deepEqual(sanitizePrivacy({ displayPaths: "nope", hideHost: "yes", aliases: [1, "", "a==>b", "x\ny"] }), {
+ ...DEFAULT_PRIVACY_SETTINGS,
+ displayPaths: "masked",
+ hideHost: true,
+ aliases: ["a==>b", "xy"],
+ });
+ const { rules, problems } = compilePrivacy(base({}));
+ assert.equal(rules, null);
+ assert.deepEqual(problems, []);
+ const d = displayersOf(rules);
+ assert.equal(d, IDENTITY);
+ for (const s of CORPUS) {
+ assert.equal(applyPrivacy(null, s), s);
+ assert.equal(d.displayPath(s), s);
+ assert.equal(d.displayText(s), s);
+ }
+});
+
+test("displayPaths home and masked; a longer name is not the home dir", () => {
+ assert.equal(show({ displayPaths: "home" }, `${HOME}/a`), "~/a");
+ assert.equal(show({ displayPaths: "home" }, HOME), "~");
+ assert.equal(show({ displayPaths: "home" }, `${HOME}x/a`), `${HOME}x/a`);
+ assert.equal(show({ displayPaths: "home" }, `${HOME}.bak`), `${HOME}.bak`);
+ assert.equal(show({ displayPaths: "masked" }, `see ${HOME}/a and ${HOME}`), "see /home/user/a and /home/user");
+ // A trailing slash on the home dir is the same home dir.
+ assert.equal(show({ displayPaths: "home" }, `${HOME}/a`, { homeDir: `${HOME}/` }), "~/a");
+ // A home of "/" (a container) rewrites nothing.
+ assert.equal(show({ displayPaths: "masked" }, "/srv/a", { homeDir: "/" }), "/srv/a");
+});
+
+test("masked: a location root becomes its label (longest first), mounts and volume ids are hidden", () => {
+ const m = (s: string) => show({ displayPaths: "masked" }, s);
+ assert.equal(m("Media relocated to /run/media/someone/1234-ABCD/archive/chan/media."), "Media relocated to [Platter]/chan/media.");
+ assert.equal(m("/run/media/someone/1234-ABCD/other"), "[Platter]/other");
+ assert.equal(m("/media/someone/USBSTICK/x"), "/media/drive/x");
+ assert.equal(m("/mnt/0f3c2a1b-9d2e-4c11-8a77-0123456789ab/x"), "/media/drive/x");
+ assert.equal(m("volume 1234-ABCD (ext4)"), "volume [volume] (ext4)");
+ assert.equal(m("job 1234-ABCDE"), "job 1234-ABCDE");
+ // "home" mode labels no root; the user's name in a media mount is `user`.
+ assert.equal(show({ displayPaths: "home" }, "/run/media/someone/1234-ABCD/archive/x"), "/run/media/user/1234-ABCD/archive/x");
+});
+
+test("hideHost: whole word, any case, never inside another word", () => {
+ const h = (s: string, names = ["boxen"]) => show({ hideHost: true }, s, { hostnames: names });
+ assert.equal(h("held on boxen since 13:31"), "held on host since 13:31");
+ assert.equal(h("boxen.lan:3050"), "host.lan:3050");
+ assert.equal(h("an oxen boxenly unboxen boxen-2 Boxen"), "an oxen boxenly unboxen boxen-2 host");
+ // A hostname that is a common word is only replaced as that whole word.
+ assert.equal(h("the desk is a desktop; desk.", ["desk"]), "the host is a desktop; host.");
+ // The short form of a dotted name, and ARCHILYZER_HOST_ID-style extras.
+ assert.equal(h("on boxen and on boxen.example.org", ["boxen.example.org"]), "on host and on host");
+ assert.equal(h("localhost:3001", ["localhost"]), "localhost:3001");
+});
+
+test("aliases in the source mirror's four forms", () => {
+ const a = (aliases: string[], s: string) => show({ aliases }, s);
+ assert.equal(a(["secret-site==>demo-site"], "a secret-site b"), "a demo-site b");
+ assert.equal(a(["literal:a.b==>c$1"], "xa.byaxb"), "xc$1yaxb");
+ assert.equal(a(["regex:proj-(\\d+)==>project \\1"], "proj-42 proj-x"), "project 42 proj-x");
+ assert.equal(a(["regex:(?P<w>sec)ret==>\\g<w>"], "secret"), "sec");
+ assert.equal(a(["regex:(?i)ALPHA==>b"], "alpha Alpha"), "b b");
+ assert.equal(a(["glob:priv*te==>p"], "a private b"), "a p b");
+ assert.equal(a(["glob:p*e==>X"], "pie and pine"), "X");
+ assert.equal(a(["glob:file?.txt==>f"], "file1.txt fileXX.txt"), "f fileXX.txt");
+ assert.equal(a(["gone"], "is gone"), "is ***REMOVED***");
+ assert.equal(a(["# comment", " ", "x==>y"], "x"), "y");
+ assert.equal(pythonReplacement("a\\1$b\\g<2>\\n"), "a$1$$b$2\n");
+});
+
+test("a broken or unbounded regex fails CLOSED: reported by number, its fragments hidden", () => {
+ const { rules, problems } = compilePrivacy(base({ aliases: ["ok==>fine", "regex:jeral(yzer-private==>x", "regex:(a+)+b==>c", "glob:x*y*z*w==>q"] }));
+ assert.deepEqual(
+ problems.map((p) => [p.source, p.line]),
+ [
+ ["aliases", 2],
+ ["aliases", 3],
+ ["aliases", 4],
+ ],
+ );
+ for (const p of problems) assert.ok(!/jeral|yzer|private/.test(p.what), "a problem never quotes the rule");
+ // Rule 2's fragments are hidden; rule 3 has none, so every line it would run
+ // on is hidden whole (review round 2, M-C: a fallback is never a no-op).
+ assert.equal(applyPrivacy(rules, "ok jeralyzer-private"), "[hidden]");
+ const two = compilePrivacy(base({ aliases: ["ok==>fine", "regex:jeral(yzer-private==>x"] }));
+ assert.equal(applyPrivacy(two.rules, "ok jeralyzer-private"), "fine [hidden][hidden]");
+ assert.ok(riskyRegex("(a+)+"));
+ assert.ok(riskyRegex("(a|aa)*"));
+ assert.ok(riskyRegex("((ab)*c)+"));
+ assert.ok(riskyRegex("a*b*c*"));
+ assert.ok(!riskyRegex("proj-(\\d+)"));
+ assert.ok(!riskyRegex("(?:ab)?c+[x*+]"));
+ assert.ok(!riskyRegex("(a|b)?x"));
+ assert.deepEqual(literalFragments("jeral(yzer-private", "regex"), ["jeral", "yzer-private"]);
+ assert.deepEqual(literalFragments("abcd?ef", "regex"), ["abc"]);
+});
+
+test("an operator regex sees at most PRIVACY_REGEX_MAX_INPUT characters at a time", () => {
+ const rules = compilePrivacy(base({ aliases: ["regex:b(\\w)==>B\\1"] })).rules;
+ const long = "a".repeat(PRIVACY_REGEX_MAX_INPUT * 2 + 10) + "bc";
+ const t0 = Date.now();
+ assert.ok(applyPrivacy(rules, long).endsWith("aBc"));
+ assert.ok(Date.now() - t0 < 1000);
+ assert.equal(applyPrivacy(rules, "x bq\ny bz"), "x Bq\ny Bz");
+});
+
+test("maskEmail", () => {
+ assert.equal(show({ maskEmail: true }, "mail a.b+c@mail.example.co.uk or x@y"), "mail [email] or x@y");
+});
+
+test("useSourceRules: the files' rules are secret steps the client never gets", () => {
+ const input = base(
+ { useSourceRules: true, displayPaths: "home" },
+ { scrubText: "\uFEFFMARKER-SCRUB==>alias\r\n# c\nregex:QQQ(ZZZ==>z\n", denyText: "MARKER-DENY\ni:marker-ci\n" },
+ );
+ const { rules, problems } = compilePrivacy(input);
+ assert.equal(applyPrivacy(rules, "MARKER-SCRUB MARKER-DENY Marker-CI QQQZZZ"), "alias [hidden] [hidden] [hidden][hidden]");
+ assert.deepEqual(problems.map((p) => `${p.source}:${p.line}`), ["scrub:3"]);
+ assert.ok(!JSON.stringify(problems).includes("QQQ"));
+ assert.ok(!JSON.stringify(publicRules(rules)).includes("QQQ"));
+ const client = publicRules(rules);
+ assert.ok(client);
+ assert.ok(!JSON.stringify(client).includes("MARKER"), "no secret text reaches the client rules");
+ assert.ok(!JSON.stringify(client).toLowerCase().includes("marker"));
+ assert.equal(applyPrivacy(client, `${HOME}/x`), "~/x");
+ // Off: the files' text is not even compiled.
+ const off = compilePrivacy({ ...input, privacy: { ...input.privacy!, useSourceRules: false } });
+ assert.ok(!JSON.stringify(off).includes("MARKER"));
+});
diff --git a/common/lib/privacy/display.ts b/common/lib/privacy/display.ts
@@ -0,0 +1,361 @@
+// 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, $<name>, $$).
+ 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 literal fragments (regex sources), shown as [hidden] when it runs in
+ // fallback; with none, every line it would run on is shown as [hidden].
+ fallback?: string[];
+ // 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: RegExp[];
+ capAt: number | null;
+ probe: RegExp | null;
+};
+
+const compiled = new WeakMap<PrivacyRules, Compiled[]>();
+// Rules disabled for being slow, for the rest of the process.
+const disabled = new WeakSet<PrivacyStep>();
+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 [new RegExp(f, "g")];
+ } 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;
+ });
+}
+
+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): number | null {
+ if (!c.probe) return null;
+ const W = PRIVACY_REGEX_MAX_INPUT;
+ for (const w of windows(line, c.overlap)) {
+ 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): string {
+ const W = PRIVACY_REGEX_MAX_INPUT;
+ const rx = c.rx;
+ const stopAt = probeAt(line, c);
+ let out = "";
+ let pos = 0;
+ let rest = false;
+ for (const { from, win, own0 } of windows(line, c.overlap)) {
+ 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);
+}
+
+function boundedReplace(s: string, c: Compiled): string {
+ return s.includes("\n") ? s.split("\n").map((line) => scanLine(line, c)).join("\n") : scanLine(s, c);
+}
+
+/** A rule in fallback: its literal fragments hidden — or, with none, every non-empty line it would run on. */
+function fallbackReplace(s: string, c: Compiled): string {
+ if (c.fallback.length) {
+ let out = s;
+ for (const f of c.fallback) out = out.replace(f, HIDDEN);
+ return out;
+ }
+ return s
+ .split("\n")
+ .map((line) => (line.trim() ? HIDDEN : line))
+ .join("\n");
+}
+
+function runBounded(s: string, c: Compiled): string {
+ if (c.step.refused || disabled.has(c.step)) return fallbackReplace(s, c);
+ try {
+ return boundedReplace(s, c);
+ } 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; it now runs in fallback (its literal fragments, or every line it runs on where it has none, 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;
+ for (const c of stepsOf(rules)) {
+ if (c.email) out = maskEmails(out, c.to);
+ else if (c.bounded) out = runBounded(out, c);
+ 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;
+}
diff --git a/common/lib/privacy/noOperatorNames.test.ts b/common/lib/privacy/noOperatorNames.test.ts
@@ -0,0 +1,71 @@
+// THIS LANE'S FILES NEVER NAME THE MACHINE THEY WERE WRITTEN ON (review round
+// 2, M-A). The repository's history is published by the source mirror; a test
+// that spelled the account's user name or the hostname would publish it. This
+// reads the privacy lane's own files and fails if any carries the CURRENT
+// account's user name or this machine's hostname as a whole word — both
+// computed now, at test time, and never printed: the failure names the file
+// and which of the two, nothing else. A test that needs "the current user"
+// must ask os.userInfo() at run time.
+//
+// Run with: node_modules/.bin/tsx --test common/lib/privacy/noOperatorNames.test.ts
+
+import { test } from "node:test";
+import assert from "node:assert/strict";
+import { readdirSync, readFileSync, statSync } from "node:fs";
+import os from "node:os";
+import path from "node:path";
+import { fileURLToPath } from "node:url";
+
+const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..", "..", "..");
+
+// The lane's files: whole directories, and single files.
+const DIRS = ["common/lib/privacy"];
+const FILES = [
+ "common/lib/privacySettings.ts",
+ "common/lib/scrubRuleLine.ts",
+ "common/publish/scrubRuleLine.test.ts",
+ "common/publish/privacyAudit.ts",
+ "common/publish/privacyAudit.test.ts",
+ "common/bin/privacy-audit.ts",
+ "common/components/PrivacyProvider.tsx",
+ "editor/e2e/privacy-audit.spec.ts",
+ "umtool/e2e/privacy-audit.spec.ts",
+ "umtool/lib/privacy.ts",
+ "umtool/lib/privacy.test.ts",
+ "umtool/lib/research/privacySources.test.ts",
+ "editor/app/channels/components/SiteMembershipsSection.test.ts",
+];
+
+function files(): string[] {
+ const out: string[] = [];
+ for (const d of DIRS) {
+ for (const name of readdirSync(path.join(ROOT, d))) {
+ const rel = path.join(d, name);
+ if (statSync(path.join(ROOT, rel)).isFile()) out.push(rel);
+ }
+ }
+ return [...out, ...FILES];
+}
+
+const word = (name: string) => new RegExp(`(?<![A-Za-z0-9_-])${name.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}(?![A-Za-z0-9_-])`, "i");
+
+test("no file of the privacy lane names this account or this machine", () => {
+ let user = "";
+ try {
+ user = os.userInfo().username;
+ } catch {
+ user = "";
+ }
+ const names: Array<[string, string]> = [];
+ if (user.length >= 3) names.push(["the account's user name", user]);
+ const host = os.hostname();
+ for (const h of new Set([host, host.split(".")[0]])) if (h.length >= 3 && h !== "localhost") names.push(["this machine's hostname", h]);
+ const bad: string[] = [];
+ const list = files();
+ assert.ok(list.length > 10, "the lane's files were found");
+ for (const rel of list) {
+ const text = readFileSync(path.join(ROOT, rel), "utf8");
+ for (const [what, name] of names) if (word(name).test(text)) bad.push(`${rel}: ${what}`);
+ }
+ assert.deepEqual(bad, []);
+});
diff --git a/common/lib/privacy/privacy-server.test.ts b/common/lib/privacy/privacy-server.test.ts
@@ -0,0 +1,117 @@
+// The server's displayers over a TEMP settings file and TEMP private rule
+// files (never the operator's): live settings, the useSourceRules opt-in, a
+// marker planted in the rule files that never reaches the client rules, a
+// warning or an error, and the memo following a change.
+//
+// Run with: node_modules/.bin/tsx --test common/lib/privacy/privacy-server.test.ts
+
+import { test } from "node:test";
+import assert from "node:assert/strict";
+import { mkdtempSync, rmSync, writeFileSync, utimesSync } from "node:fs";
+import os, { tmpdir } from "node:os";
+import path from "node:path";
+
+const DIR = mkdtempSync(path.join(tmpdir(), "privacy-server-"));
+const SETTINGS = path.join(DIR, "settings.json");
+const SCRUB = path.join(DIR, "scrub.txt");
+const DENY = path.join(DIR, "deny.txt");
+Object.assign(process.env, { SETTINGS_FILE: SETTINGS, SOURCE_SCRUB_FILE: SCRUB, SOURCE_DENYLIST_FILE: DENY });
+
+const { currentPrivacy, displayPath, displayText, clientPrivacyRules, hidePrivateSites, resetPrivacyMemo } = await import("./privacy-server");
+
+let tick = 0;
+const write = (file: string, text: string) => {
+ writeFileSync(file, text);
+ // A distinct mtime per write, so the memo key moves even within a second.
+ tick += 10;
+ const t = new Date(Date.UTC(2026, 0, 1) + tick * 1000);
+ utimesSync(file, t, t);
+ resetPrivacyMemo();
+};
+const settings = (privacy: unknown) => write(SETTINGS, JSON.stringify(privacy === undefined ? {} : { privacy }));
+
+const HOME = os.homedir();
+
+test("absent: identity, no client rules, nothing hidden", () => {
+ settings(undefined);
+ const s = `${HOME}/x on ${os.hostname()}`;
+ assert.equal(displayPath(s), s);
+ assert.equal(displayText(s), s);
+ assert.equal(clientPrivacyRules(), null);
+ assert.equal(hidePrivateSites(), false);
+ // At its defaults, explicitly: the same.
+ settings({ displayPaths: "full", hideHost: false, hidePrivateSites: false, aliases: [], maskEmail: false, useSourceRules: false });
+ assert.equal(displayText(s), s);
+ assert.equal(clientPrivacyRules(), null);
+});
+
+test("live settings: home mode, hidePrivateSites", () => {
+ settings({ displayPaths: "home", hidePrivateSites: true });
+ assert.equal(displayPath(`${HOME}/a/b`), "~/a/b");
+ assert.equal(hidePrivateSites(), true);
+ assert.ok(clientPrivacyRules());
+ settings({ hidePrivateSites: true });
+ assert.equal(clientPrivacyRules(), null, "a filter flag alone sends no rules");
+});
+
+test("useSourceRules: the files are applied on the server, never handed to the client, never quoted", () => {
+ const warnings: string[] = [];
+ write(SCRUB, "MARKER-SCRUB-7==>stand-in\nregex:MARKER-RX-(==>x\n");
+ write(DENY, "MARKER-DENY-7\n");
+ settings({ useSourceRules: true, displayPaths: "home" });
+ const c = currentPrivacy({ warn: (l) => warnings.push(l) });
+ assert.equal(displayText("a MARKER-SCRUB-7 b MARKER-DENY-7"), "a stand-in b [hidden]");
+ const client = JSON.stringify(clientPrivacyRules());
+ assert.ok(!client.includes("MARKER"), "the client rules carry no private text");
+ assert.ok(!JSON.stringify(c.problems).includes("MARKER"));
+ assert.deepEqual(warnings, ["[privacy] scrub line 2: does not compile (regex); it runs in fallback: its 1 literal fragment is hidden instead"]);
+ for (const w of warnings) assert.ok(!w.includes("MARKER"));
+});
+
+test("useSourceRules with the files missing: a warning naming the path, nothing else", () => {
+ rmSync(SCRUB, { force: true });
+ rmSync(DENY, { force: true });
+ settings({ useSourceRules: true });
+ const warnings: string[] = [];
+ currentPrivacy({ warn: (l) => warnings.push(l) });
+ assert.equal(warnings.length, 2);
+ assert.match(warnings[0], /^\[privacy\] useSourceRules: no scrub rules at .*scrub\.txt \(ENOENT\)/);
+ assert.equal(displayText("plain"), "plain");
+});
+
+test("the memo follows a settings change", () => {
+ settings({ displayPaths: "home" });
+ assert.equal(displayPath(HOME), "~");
+ settings({ displayPaths: "masked" });
+ assert.equal(displayPath(HOME), HOME === "/home/user" ? HOME : "/home/user");
+});
+
+test("a settings.json that does not parse: strict at boot, the last good rules after", () => {
+ // At boot (no good compile yet): strict, warned once.
+ write(SETTINGS, "{ not json");
+ const warnings: string[] = [];
+ const c = currentPrivacy({ warn: (l) => warnings.push(l) });
+ assert.equal(c.settings.displayPaths, "masked");
+ assert.equal(c.settings.hideHost, true);
+ assert.match(warnings.join("\n"), /does not parse: privacy runs strict/);
+ assert.equal(displayPath(`${HOME}/x`), HOME === "/home/user" ? `${HOME}/x` : "/home/user/x");
+ // After a good compile with privacy on, a broken file keeps it.
+ settings({ displayPaths: "home" });
+ assert.equal(displayPath(`${HOME}/x`), "~/x");
+ writeFileSync(SETTINGS, "{ broken");
+ tick += 10;
+ const t = new Date(Date.UTC(2026, 0, 1) + tick * 1000);
+ utimesSync(SETTINGS, t, t);
+ // Let the one-second recheck pass without dropping the memo.
+ const until = Date.now() + 1100;
+ while (Date.now() < until) {
+ /* wait */
+ }
+ assert.equal(displayPath(`${HOME}/x`), "~/x");
+ // A missing file is the defaults: off.
+ rmSync(SETTINGS, { force: true });
+ resetPrivacyMemo();
+ assert.equal(displayPath(`${HOME}/x`), `${HOME}/x`);
+});
+
+test.after(() => rmSync(DIR, { recursive: true, force: true }));
diff --git a/common/lib/privacy/privacy-server.ts b/common/lib/privacy/privacy-server.ts
@@ -0,0 +1,180 @@
+// THE SERVER'S DISPLAYERS (demo epic D4): `displayPath(p)` and
+// `displayText(s)` over settings.privacy, for any server component of the
+// editor or umtool, plus the rules a browser may hold (`clientPrivacyRules`,
+// for components/PrivacyProvider.tsx) and the private-site filter flag.
+//
+// THE OPERATOR'S PRIVATE RULE FILES (getPaths().sourceScrubFile and
+// sourceDenylistFile — the source mirror's) are read here, and only here, and
+// only while `privacy.useSourceRules` is on. Their rules are applied by THIS
+// module's displayers and by nothing else: `clientPrivacyRules` drops them, no
+// response carries them, and nothing logs them — a missing or unreadable file
+// is a warning naming its (tildified) path, a broken rule is a warning naming
+// its line number.
+//
+// Compiled once per change: the key is the settings file's and the rule
+// files' mtime and size, re-checked at most once a second.
+
+import { statSync, readFileSync } from "node:fs";
+import os from "node:os";
+import { getPaths } from "../paths";
+import { getSettings } from "../settings";
+import { DEFAULT_PRIVACY_SETTINGS, STRICT_PRIVACY_SETTINGS, privacyActive, privacyProblems, type PrivacySettings } from "../privacySettings";
+import { compilePrivacy, problemLine, type PrivacyProblem } from "./compile";
+import { applyPrivacy, publicRules, type PrivacyRules } from "./display";
+
+export type CompiledPrivacy = {
+ settings: PrivacySettings;
+ rules: PrivacyRules | null;
+ client: PrivacyRules | null;
+ problems: PrivacyProblem[];
+};
+
+const INACTIVE: CompiledPrivacy = { settings: DEFAULT_PRIVACY_SETTINGS, rules: null, client: null, problems: [] };
+
+const RECHECK_MS = 1000;
+
+let memo: { key: string; at: number; value: CompiledPrivacy } | null = null;
+
+const statKey = (file: string) => {
+ try {
+ const s = statSync(file);
+ return `${s.mtimeMs}:${s.size}`;
+ } catch {
+ return "-";
+ }
+};
+
+export function tildify(p: string): string {
+ const home = os.homedir();
+ return home.length > 1 && (p === home || p.startsWith(`${home}/`)) ? `~${p.slice(home.length)}` : p;
+}
+
+export function userName(): string | null {
+ try {
+ return os.userInfo().username || null;
+ } catch {
+ return null;
+ }
+}
+
+export function hostnames(): string[] {
+ return [os.hostname(), process.env.ARCHILYZER_HOST_ID ?? ""].filter(Boolean);
+}
+
+function readPrivate(file: string, what: string, warn: (line: string) => void): string | null {
+ try {
+ return readFileSync(file, "utf8");
+ } catch (err) {
+ const code = (err as NodeJS.ErrnoException).code ?? "unreadable";
+ // The path names the file; nothing of its text is ever in a message.
+ warn(`[privacy] useSourceRules: no ${what} at ${tildify(file)} (${code}); its rules are not applied`);
+ return null;
+ }
+}
+
+let warned = "";
+
+/** Compile from the live settings (memoised). Never throws. */
+export function currentPrivacy(opts: { warn?: (line: string) => void } = {}): CompiledPrivacy {
+ const now = Date.now();
+ if (memo && now - memo.at < RECHECK_MS) return memo.value;
+ const paths = getPaths();
+ // Three stats at most once a second; the rule files' only matter while
+ // useSourceRules is on, but stating them is cheaper than reading settings.
+ const key = `${statKey(paths.settingsFile)}|${statKey(paths.sourceScrubFile)}|${statKey(paths.sourceDenylistFile)}|${paths.settingsFile}`;
+ if (memo && memo.key === key) {
+ memo.at = now;
+ return memo.value;
+ }
+ let value = INACTIVE;
+ const warnings: string[] = [];
+ // The raw file first (review round 1, S3): getSettings() reads a file that
+ // does not parse as an empty one — which would turn privacy OFF. While the
+ // last good compile had it on, its rules stand, and the server says why.
+ let raw: Record<string, unknown> | null = null;
+ try {
+ const parsed = JSON.parse(readFileSync(paths.settingsFile, "utf8")) as unknown;
+ raw = parsed && typeof parsed === "object" && !Array.isArray(parsed) ? (parsed as Record<string, unknown>) : null;
+ } catch (err) {
+ if ((err as NodeJS.ErrnoException).code !== "ENOENT") raw = null;
+ else raw = {};
+ }
+ if (raw === null && memo && privacyActive(memo.value.settings)) {
+ const w = `[privacy] ${tildify(paths.settingsFile)} does not parse; the last privacy rules stay until it does`;
+ if (w !== warned) (opts.warn ?? ((line: string) => console.warn(line)))(w);
+ warned = w;
+ memo = { key, at: now, value: memo.value };
+ return memo.value;
+ }
+ let settings: PrivacySettings = DEFAULT_PRIVACY_SETTINGS;
+ if (raw === null) {
+ // The file is THERE and does not parse, with no good compile to keep (a
+ // boot, review round 2): strict, as an invalid privacy block is.
+ settings = STRICT_PRIVACY_SETTINGS;
+ warnings.push(`[privacy] ${tildify(paths.settingsFile)} does not parse: privacy runs strict (every hiding key on) until it does`);
+ } else {
+ try {
+ settings = getSettings().privacy ?? DEFAULT_PRIVACY_SETTINGS;
+ } catch {
+ settings = DEFAULT_PRIVACY_SETTINGS;
+ }
+ }
+ for (const p of privacyProblems(raw?.privacy)) warnings.push(`[privacy] settings.json privacy: ${p}`);
+ const warn = opts.warn ?? ((line: string) => console.warn(line));
+ if (privacyActive(settings)) {
+ const locations = (() => {
+ try {
+ return getSettings().storage.locations;
+ } catch {
+ return [];
+ }
+ })();
+ const scrubText = settings.useSourceRules ? readPrivate(paths.sourceScrubFile, "scrub rules", (l) => warnings.push(l)) : null;
+ const denyText = settings.useSourceRules ? readPrivate(paths.sourceDenylistFile, "denylist", (l) => warnings.push(l)) : null;
+ const { rules, problems } = compilePrivacy({
+ privacy: settings,
+ homeDir: os.homedir(),
+ hostnames: hostnames(),
+ username: userName(),
+ locations,
+ scrubText,
+ denyText,
+ });
+ for (const p of problems) warnings.push(`[privacy] ${problemLine(p)}`);
+ value = { settings, rules, client: publicRules(rules), problems };
+ }
+ // Each distinct set of warnings is said once per process, not per render.
+ const said = warnings.join("\n");
+ if (said && said !== warned) for (const w of warnings) warn(w);
+ warned = said;
+ memo = { key, at: now, value };
+ return value;
+}
+
+/** Drop the memo (tests). */
+export function resetPrivacyMemo(): void {
+ memo = null;
+ warned = "";
+}
+
+/** A local path as a page shows it. Identity while privacy is off. */
+export function displayPath(p: string): string {
+ const { rules } = currentPrivacy();
+ return rules ? applyPrivacy(rules, p) : p;
+}
+
+/** Text as a page shows it. Identity while privacy is off. */
+export function displayText(s: string): string {
+ const { rules } = currentPrivacy();
+ return rules ? applyPrivacy(rules, s) : s;
+}
+
+/** The rules a browser may hold — no secret step. Null while there are none. */
+export function clientPrivacyRules(): PrivacyRules | null {
+ return currentPrivacy().client;
+}
+
+/** Are private sites to be left out of the lists and pickers? */
+export function hidePrivateSites(): boolean {
+ return currentPrivacy().settings.hidePrivateSites;
+}
diff --git a/common/lib/privacy/regexSafety.ts b/common/lib/privacy/regexSafety.ts
@@ -0,0 +1,223 @@
+// IS AN OPERATOR'S REGEX SAFE TO RUN ON EVERY RENDER? (demo epic D4, review
+// round 1, M1.) A conservative STATIC rule, checked once at compile time over
+// the JS source a `regex:` or `glob:` display rule compiles to — the
+// settings' aliases and the private scrub file's rules alike:
+//
+// - at most ONE unbounded-or-large quantifier (`*`, `+`, `{n,}`, `{n,m}`
+// with m > 64, lazy forms included);
+// - no backreference (`\1`, `\k<name>`);
+// - no quantified group (one that may repeat) holding a quantifier or an
+// alternation;
+// - no lookahead or lookbehind (they read past a match, and so past the
+// windows display.ts cuts a long line into);
+// - the product of every quantifier's range (max − min + 1) AND of every
+// alternation's number of branches at most QUANTIFIER_PRODUCT_MAX, so
+// three `{0,64}` side by side, or twenty `(a|a)`, are refused too;
+// - a match at most MATCH_MAX characters long: the one unbounded quantifier
+// is REWRITTEN to at most UNBOUNDED_CAP repeats (`.*` → `.{0,256}`), and
+// the longest possible match is computed and refused above MATCH_MAX —
+// which is what lets display.ts cut a long line into overlapping windows
+// that no match can straddle unseen.
+//
+// Anything else is refused; compile.ts then fails closed (the rule's literal
+// fragments shown as [hidden], the rule reported by its number). display.ts
+// also times every operator rule per call and disables one that is slow.
+//
+// Pure, no imports.
+
+export const UNBOUNDED_CAP = 256;
+export const LARGE_QUANTIFIER = 64;
+export const QUANTIFIER_PRODUCT_MAX = 1024;
+export const MATCH_MAX = 2048;
+
+export type RegexVerdict =
+ // capTrigger: a match at least this long MAY have used the rewritten
+ // quantifier up to its cap — display.ts then hides to the end of the line,
+ // never showing the rest of what the operator's pattern would have matched.
+ // capProbe: the pattern up to and including the capped quantifier, that
+ // quantifier at EXACTLY its cap — where it matches, the operator's pattern
+ // may match past the cap, so display.ts hides from there to the line's end.
+ | { ok: true; source: string; maxLen: number; capTrigger: number | null; capProbe: string | null }
+ | { ok: false; why: string };
+
+type Quant = { min: number; max: number; len: number; text: string };
+
+function quantAt(re: string, i: number): Quant | null {
+ const c = re[i];
+ let q: Quant | null = null;
+ if (c === "*") q = { min: 0, max: Infinity, len: 1, text: "*" };
+ else if (c === "+") q = { min: 1, max: Infinity, len: 1, text: "+" };
+ else if (c === "?") q = { min: 0, max: 1, len: 1, text: "?" };
+ else if (c === "{") {
+ const m = /^\{(\d+)(,(\d*))?\}/.exec(re.slice(i));
+ if (!m) return null;
+ const min = Number(m[1]);
+ const max = m[2] ? (m[3] === "" ? Infinity : Number(m[3])) : min;
+ q = { min, max, len: m[0].length, text: m[0] };
+ }
+ if (q && re[i + q.len] === "?") q = { ...q, len: q.len + 1, text: q.text + "?" };
+ return q;
+}
+
+type Node = { maxLen: number; minLen: number; hasQuant: boolean; hasAlt: boolean; out: string };
+
+class Refused extends Error {}
+
+/** The verdict on one JS regex source (no flags needed: `u` is never set). */
+export function analyzeRegex(re: string): RegexVerdict {
+ let i = 0;
+ let large = 0;
+ let product = 1;
+ // The capped quantifier's atom's shortest length, and its own minimum.
+ let capped: { atomMin: number; qMin: number } | null = null;
+ let probe: string | null = null;
+ // The capped term's own atom, until the probe is written; top-level branches.
+ let pendingProbeAtom: string | null = null;
+ let topBranches = 1;
+ // The groups open at this point: each one's prefix (what precedes it in its
+ // own sequence, plus its head) and whether it holds the capped quantifier.
+ const open: Array<{ prefix: string; holds: boolean }> = [];
+ const bound = (what: string) => {
+ if (product > QUANTIFIER_PRODUCT_MAX) throw new Refused(what);
+ };
+
+ const quantify = (atom: Node, q: Quant, isGroup: boolean): Node => {
+ const big = q.max === Infinity || q.max > LARGE_QUANTIFIER;
+ if (big) large++;
+ if (large > 1) throw new Refused("more than one unbounded or large quantifier");
+ if (isGroup && q.max > 1 && (atom.hasQuant || atom.hasAlt)) {
+ throw new Refused("a repeated group holding a quantifier or an alternation");
+ }
+ let max = q.max;
+ let text = q.text;
+ if (max === Infinity) {
+ if (q.min > UNBOUNDED_CAP) throw new Refused("an unbounded quantifier with a minimum above the cap");
+ max = UNBOUNDED_CAP;
+ text = `{${q.min},${UNBOUNDED_CAP}}${q.text.endsWith("?") && q.text !== "?" ? "?" : ""}`;
+ // Its probe (capProbe) is the pattern up to it: well defined unless a
+ // group around it has another branch (refused when that group closes).
+ capped = { atomMin: atom.minLen, qMin: q.min };
+ pendingProbeAtom = atom.out;
+ for (const o of open) o.holds = true;
+ }
+ product *= max - q.min + 1;
+ bound("the quantifiers' ranges and alternations multiply past the bound");
+ return { maxLen: atom.maxLen * max, minLen: atom.minLen * q.min, hasQuant: true, hasAlt: atom.hasAlt, out: atom.out + text };
+ };
+
+ const parseAlternation = (inGroup: boolean): Node => {
+ const alts: Node[] = [parseSequence()];
+ while (re[i] === "|") {
+ i++;
+ alts.push(parseSequence());
+ }
+ if (inGroup && re[i] !== ")") throw new Refused("an unclosed group");
+ if (!inGroup) topBranches = alts.length;
+ if (alts.length > 1) {
+ product *= alts.length;
+ bound("the quantifiers' ranges and alternations multiply past the bound");
+ }
+ return {
+ maxLen: Math.max(...alts.map((a) => a.maxLen)),
+ minLen: Math.min(...alts.map((a) => a.minLen)),
+ hasQuant: alts.some((a) => a.hasQuant),
+ hasAlt: alts.length > 1 || alts.some((a) => a.hasAlt),
+ out: alts.map((a) => a.out).join("|"),
+ };
+ };
+
+ const parseSequence = (): Node => {
+ const node: Node = { maxLen: 0, minLen: 0, hasQuant: false, hasAlt: false, out: "" };
+ while (i < re.length && re[i] !== "|" && re[i] !== ")") {
+ const start = i;
+ let atom: Node;
+ let isGroup = false;
+ let quantifiable = true;
+ const c = re[i];
+ if (c === "(") {
+ i++;
+ let head = "(";
+ if (/^\?(?:=|!|<=|<!)/.test(re.slice(i))) throw new Refused("a lookahead or lookbehind");
+ const m = /^\?(?::|<[A-Za-z_][A-Za-z0-9_]*>)/.exec(re.slice(i));
+ if (m) {
+ head += m[0];
+ i += m[0].length;
+ } else if (re[i] === "?") throw new Refused("an unsupported group");
+ open.push({ prefix: node.out + head, holds: false });
+ const inner = parseAlternation(true);
+ const closed = open.pop()!;
+ if (closed.holds && inner.hasAlt && /\|/.test(inner.out)) {
+ // (A conservative test: any `|` in the group's own source.)
+ throw new Refused("an unbounded quantifier in one branch of an alternation");
+ }
+ i++; // ")"
+ atom = { maxLen: inner.maxLen, minLen: inner.minLen, hasQuant: inner.hasQuant, hasAlt: inner.hasAlt, out: `${head}${inner.out})` };
+ isGroup = true;
+ } else if (c === "[") {
+ let j = i + 1;
+ if (re[j] === "^") j++;
+ if (re[j] === "]") j++;
+ while (j < re.length && re[j] !== "]") j += re[j] === "\\" ? 2 : 1;
+ if (j >= re.length) throw new Refused("an unclosed character class");
+ atom = { maxLen: 1, minLen: 1, hasQuant: false, hasAlt: false, out: re.slice(i, j + 1) };
+ i = j + 1;
+ } else if (c === "\\") {
+ const n = re[i + 1];
+ if (n === undefined) throw new Refused("a trailing backslash");
+ if (/[1-9]/.test(n) || n === "k") throw new Refused("a backreference");
+ let len = 2;
+ if (n === "x") len = 4;
+ else if (n === "u") len = re[i + 2] === "{" ? re.indexOf("}", i) - i + 1 : 6;
+ else if (n === "c") len = 3;
+ const width = n === "b" || n === "B" ? 0 : 1;
+ atom = { maxLen: width, minLen: width, hasQuant: false, hasAlt: false, out: re.slice(i, i + len) };
+ i += len;
+ if (width === 0) quantifiable = false;
+ } else if (c === "^" || c === "$") {
+ atom = { maxLen: 0, minLen: 0, hasQuant: false, hasAlt: false, out: c };
+ i++;
+ quantifiable = false;
+ } else if (c === "*" || c === "+" || c === "?") {
+ throw new Refused("a quantifier with nothing to repeat");
+ } else {
+ atom = { maxLen: 1, minLen: 1, hasQuant: false, hasAlt: false, out: c };
+ i++;
+ }
+ const q = quantAt(re, i);
+ if (q) {
+ if (!quantifiable) throw new Refused("a quantified assertion");
+ i += q.len;
+ atom = quantify(atom, q, isGroup);
+ }
+ if (i === start) throw new Refused("an unparsable pattern");
+ node.maxLen += atom.maxLen;
+ node.minLen += atom.minLen;
+ node.hasQuant ||= atom.hasQuant;
+ node.hasAlt ||= atom.hasAlt;
+ if (pendingProbeAtom !== null) {
+ probe = `${open.map((o) => o.prefix).join("")}${node.out}${pendingProbeAtom}{${UNBOUNDED_CAP}}${")".repeat(open.length)}`;
+ pendingProbeAtom = null;
+ }
+ node.out += atom.out;
+ }
+ return node;
+ };
+
+ try {
+ const top = parseAlternation(false);
+ if (capped && topBranches > 1) throw new Refused("an unbounded quantifier in one branch of an alternation");
+ if (i < re.length) throw new Refused("an unbalanced parenthesis");
+ if (top.maxLen > MATCH_MAX) throw new Refused(`a match could be longer than ${MATCH_MAX.toLocaleString("en-US")} characters`);
+ if (top.maxLen === 0) throw new Refused("it can only match the empty string");
+ // A match can only have used the capped quantifier up to its cap if it is
+ // at least the pattern's shortest match plus the cap's extra repeats of
+ // the atom's shortest form — a NECESSARY condition, so testing it never
+ // misses a capped match (it may also catch an uncapped long one: strict).
+ const c = capped as { atomMin: number; qMin: number } | null;
+ const capTrigger = c ? top.minLen + (UNBOUNDED_CAP - c.qMin) * Math.max(1, c.atomMin) : null;
+ return { ok: true, source: top.out, maxLen: top.maxLen, capTrigger, capProbe: c ? probe : null };
+ } catch (err) {
+ if (err instanceof Refused) return { ok: false, why: err.message };
+ return { ok: false, why: "an unparsable pattern" };
+ }
+}
diff --git a/common/lib/privacy/safety.test.ts b/common/lib/privacy/safety.test.ts
@@ -0,0 +1,281 @@
+// Review round 1 of lane/privacy: the regex rule (M1), the window cut (M3),
+// fail-closed settings (S3), a linear maskEmail (S5), the engine's coverage
+// (S6) and hideUser. Every slow-shape case is under a HARD time assertion.
+//
+// Run with: node_modules/.bin/tsx --test common/lib/privacy/safety.test.ts
+
+import { test } from "node:test";
+import assert from "node:assert/strict";
+import { DEFAULT_PRIVACY_SETTINGS, STRICT_PRIVACY_SETTINGS, privacyProblems, sanitizePrivacy, type PrivacySettings } from "../privacySettings";
+import { compilePrivacy } from "./compile";
+import { applyPrivacy, isDisabled, onSlowRule, PRIVACY_REGEX_MAX_INPUT, type PrivacyRules } from "./display";
+import { analyzeRegex, MATCH_MAX } from "./regexSafety";
+
+const base = (privacy: Partial<PrivacySettings>, extra: Record<string, unknown> = {}) =>
+ compilePrivacy({
+ privacy: { ...DEFAULT_PRIVACY_SETTINGS, ...privacy },
+ homeDir: "/home/zqu",
+ hostnames: ["zqbox.lan"],
+ username: "zqu",
+ locations: [{ id: "d", label: "Drive", root: "/run/media/zqu/BIG", volume: { uuid: "ABCD-1234", mountpoint: "/run/media/zqu/BIG" } }],
+ ...extra,
+ });
+const rulesOf = (aliases: string[], extra: Partial<PrivacySettings> = {}) => base({ ...extra, aliases });
+const applied = (r: ReturnType<typeof base>, n = 1) => r.rules?.steps.some((s) => s.why === `aliases line ${n}` && s.bounded && !s.refused) ?? false;
+const timed = (fn: () => void) => {
+ const t0 = performance.now();
+ fn();
+ return performance.now() - t0;
+};
+const INPUTS = ["a".repeat(4095), " ".repeat(4095), "a".repeat(5000), "a".repeat(100_000)];
+
+// The reviewer's list (probes one.mts / scale.mts): each ran > 10 s on 4 KB.
+const REFUSED = [
+ ".*.*x",
+ "a*a*b",
+ "\\s*\\s*x",
+ "[a-z]*[a-z]*x",
+ "(.*)(.*)x",
+ "a+?a+?b",
+ "(a*)\\1*b",
+ "a{0,4096}a{0,4096}a{0,4096}x",
+ "a{1,9999}a{1,9999}b",
+ "(a+)+b",
+ "(a|aa)*b",
+ "((ab)*c)+",
+ "a{0,64}a{0,64}a{0,64}x",
+ "(?<x>a)\\k<x>",
+ // Review round 2 (M-B): alternation chains multiply; no lookaround at all.
+ "(a|a)".repeat(20) + "x",
+ "(a|b|c)(a|b|c)(a|b|c)(a|b|c)(a|b|c)(a|b|c)(a|b|c)",
+ "KEY(?=a{0,200}!)",
+ "(?<!x)KEY",
+ "KEY(?!y)",
+];
+
+test("M1: every slow shape is refused, fails closed to its fragments, and costs nothing", () => {
+ for (const p of REFUSED) {
+ const r = rulesOf([`regex:${p}==>R`]);
+ assert.equal(applied(r), false, `${p} must not be applied`);
+ assert.equal(r.problems.length, 1, `${p} is reported`);
+ assert.match(r.problems[0].what, /refused as possibly slow|does not compile/);
+ const ms = timed(() => INPUTS.forEach((s) => applyPrivacy(r.rules, s)));
+ assert.ok(ms < 1000, `${p}: ${ms.toFixed(0)} ms`);
+ }
+ // A glob of two stars is two unbounded quantifiers: refused too.
+ assert.equal(applied(rulesOf(["glob:*zz*==>G"])), false);
+});
+
+test("M1: the safe shapes are applied, rewritten to a bounded repeat, and fast on 100 KB", () => {
+ for (const p of ["proj-(\\d+)", "sec[a-z]+", "a.*b", "(?:ab)?c+", "\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}", "(a|b)?x"]) {
+ const r = rulesOf([`regex:${p}==>R`]);
+ assert.equal(applied(r), true, p);
+ const ms = timed(() => INPUTS.forEach((s) => applyPrivacy(r.rules, s)));
+ assert.ok(ms < 1500, `${p}: ${ms.toFixed(0)} ms`);
+ }
+ const v = analyzeRegex(".*x");
+ assert.ok(v.ok && v.source === ".{0,256}x" && v.maxLen === 257);
+ const lazy = analyzeRegex("a+?b");
+ assert.ok(lazy.ok && lazy.source === "a{1,256}?b");
+ assert.equal(analyzeRegex("[a-z]{64}".repeat(40)).ok, false, `a match longer than ${MATCH_MAX}`);
+ assert.equal(applied(rulesOf(["glob:priv*te==>p"])), true);
+});
+
+test("M1: the runtime backstop disables a rule slower than 50 ms on one call, by its number", () => {
+ const said: string[] = [];
+ onSlowRule((why) => said.push(why));
+ try {
+ const r = rulesOf(["regex:zq.*qz==>R"]);
+ const step = r.rules!.steps.find((s) => s.why === "aliases line 1")!;
+ const big = "zq".repeat(400_000);
+ applyPrivacy(r.rules, big);
+ if (isDisabled(step)) {
+ assert.deepEqual(said, ["aliases line 1"]);
+ // Disabled: its fragments only, at once.
+ assert.ok(timed(() => applyPrivacy(r.rules, big)) < 200);
+ assert.equal(applyPrivacy(r.rules, "x zq.qz y"), "x zq.qz y", "no fragment of three characters to hide");
+ } else {
+ // A machine fast enough that no call took 50 ms: nothing said.
+ assert.deepEqual(said, []);
+ }
+ // A hand-made step that is slow on any machine.
+ const slow: PrivacyRules = {
+ v: 1,
+ steps: [{ re: "(x+x+)+y", flags: "g", to: "R", why: "aliases line 9", bounded: true, maxLen: 64, fallback: ["SECRETWORD"] }],
+ };
+ applyPrivacy(slow, "x".repeat(28));
+ assert.equal(isDisabled(slow.steps[0]), true);
+ assert.ok(said.includes("aliases line 9"));
+ assert.equal(applyPrivacy(slow, "a SECRETWORD b"), "a [hidden] b", "fails closed to its fragments");
+ } finally {
+ onSlowRule(null);
+ }
+});
+
+test("M3: nothing straddling a 4,096-character cut is shown raw", () => {
+ const N = PRIVACY_REGEX_MAX_INPUT;
+ const pad = (k: number) => "x".repeat(k);
+ const cases: Array<[string, ReturnType<typeof base>, string, string]> = [
+ ["regex", rulesOf(["regex:SECRET[A-Z]+==>[r]"]), "SECRETWORD", "[r]"],
+ ["glob", rulesOf(["glob:SECRET*WORD==>[g]"]), "SECRETxWORD", "[g]"],
+ [
+ "secret rule",
+ base({ useSourceRules: true }, { scrubText: "regex:SECRET[A-Z]+==>[s]\n", denyText: "" }),
+ "SECRETWORD",
+ "[s]",
+ ],
+ ["e-mail", base({ maskEmail: true }), "person@example.org", "[email]"],
+ ["hostname", base({ hideHost: true }), "zqbox", "host"],
+ ["home path", base({ displayPaths: "masked" }), "/home/zqu/a", "/home/user/a"],
+ ];
+ for (const [name, r, secret, shown] of cases) {
+ for (let off = 1; off < secret.length; off++) {
+ const s = `${pad(N - off)} ${secret} ${pad(N)} ${secret} ${pad(20)}`;
+ const out = applyPrivacy(r.rules, s);
+ assert.ok(!out.includes(secret), `${name} straddling at ${off} is shown raw`);
+ if (name === "glob") {
+ // `SECRET*WORD` is `.*` inside: from its first match it could run to
+ // the line's last WORD, so the rest of the line is hidden (M-D).
+ assert.ok(out.endsWith(`${shown}[hidden]`), `${name} at ${off}: the rest of the line hidden`);
+ continue;
+ }
+ assert.equal(out.split(shown).length - 1, 2, `${name} at ${off}: both shown as ${shown}`);
+ assert.equal(out.length, s.length - 2 * (secret.length - shown.length), `${name} at ${off}: nothing else changed`);
+ }
+ }
+});
+
+test("S5: maskEmail is linear — 5 MB on one line in under a second", () => {
+ const r = base({ maskEmail: true });
+ for (const big of ["a".repeat(5_000_000), "a@".repeat(2_500_000), `${"a.".repeat(2_000_000)}@b`, "@".repeat(5_000_000)]) {
+ const ms = timed(() => applyPrivacy(r.rules, big));
+ assert.ok(ms < 1000, `${ms.toFixed(0)} ms`);
+ }
+ const m = (s: string) => applyPrivacy(r.rules, s);
+ assert.equal(m("a.b+tag@ex.com, ME@EX.ORG; mailto:me@ex.org."), "[email], [email]; mailto:[email].");
+ assert.equal(m("me@localhost x@[127.0.0.1] @x.com a@b"), "me@localhost x@[127.0.0.1] @x.com a@b");
+ assert.equal(m("a@b.co@c.org"), "[email]@c.org");
+});
+
+test("S6: case, punctuation, JSON-escaped, percent-encoded and file:// forms; media mounts in home mode", () => {
+ const home = base({ displayPaths: "home", hideHost: true });
+ const masked = base({ displayPaths: "masked", hideHost: true });
+ const h = (s: string) => applyPrivacy(home.rules, s);
+ const m = (s: string) => applyPrivacy(masked.rules, s);
+ for (const [s, hs, ms] of [
+ ["/home/zqu.", "~.", "/home/user."],
+ ["/home/zqu, /home/zqu) (/home/zqu)", "~, ~) (~)", "/home/user, /home/user) (/home/user)"],
+ ["/home/zqu.bak /home/zqu2/x", "/home/zqu.bak /home/zqu2/x", "/home/zqu.bak /home/zqu2/x"],
+ ['{"p":"\\/home\\/zqu\\/a"}', '{"p":"~\\/a"}', '{"p":"\\/home\\/user\\/a"}'],
+ ["%2Fhome%2Fzqu%2Fa %2fhome%2fzqu", "~%2Fa ~", "%2Fhome%2Fuser%2Fa %2Fhome%2Fuser"],
+ ["file:///home/zqu/a", "file:///home/user/a", "file:///home/user/a"],
+ ["/run/media/zqu/OTHER/x", "/run/media/user/OTHER/x", "/media/drive/x"],
+ ["ZQBOX Zqbox.local zqbox-2 zqbox_x", "host host.local zqbox-2 zqbox_x", "host host.local zqbox-2 zqbox_x"],
+ ["uuid abcd-1234 / ABCD-1234", "uuid abcd-1234 / ABCD-1234", "uuid [volume] / [volume]"],
+ ] as const) {
+ assert.equal(h(s), hs, `home: ${s}`);
+ assert.equal(m(s), ms, `masked: ${s}`);
+ }
+});
+
+test("hideUser: the bare user name as `user`, whole word, any case", () => {
+ const r = base({ hideUser: true }, { username: "zqu" });
+ const u = (s: string) => applyPrivacy(r.rules, s);
+ assert.equal(u("by: umtool queue add (zqu); ZQU; zqu-2"), "by: umtool queue add (user); user; zqu-2");
+ assert.equal(u("zquser zqus mzqu"), "zquser zqus mzqu", "a name inside another word is left alone");
+ assert.equal(base({ hideUser: true }, { username: "al" }).rules, null, "shorter than three: no rule");
+ assert.equal(base({ hideUser: false }, { username: "zqu" }).rules, null);
+});
+
+test("S3: a present but wrong privacy block fails CLOSED, named by key", () => {
+ assert.deepEqual(sanitizePrivacy(undefined), DEFAULT_PRIVACY_SETTINGS);
+ for (const bad of ["on", null, 1, ["masked"]]) {
+ assert.deepEqual(sanitizePrivacy(bad), STRICT_PRIVACY_SETTINGS, JSON.stringify(bad));
+ assert.match(privacyProblems(bad)[0], /not an object/);
+ }
+ const s = sanitizePrivacy({ displayPaths: "Masked", hideHost: "yes", maskEmail: 0, aliases: "x==>y", junk: 1 });
+ assert.equal(s.displayPaths, "masked");
+ assert.equal(s.hideHost, true);
+ assert.equal(s.maskEmail, true);
+ assert.deepEqual(s.aliases, []);
+ assert.equal(s.hideUser, false, "an absent key keeps its default");
+ assert.deepEqual(privacyProblems({ displayPaths: "Masked", hideHost: "yes", maskEmail: 0, aliases: "x==>y", junk: 1 }), [
+ 'displayPaths is not "full", "home" or "masked": read as "masked"',
+ "hideHost is not true or false: read as true",
+ "maskEmail is not true or false: read as true",
+ "aliases is not a list: read as []",
+ "1 key is not a privacy key: ignored",
+ ]);
+ assert.deepEqual(privacyProblems(undefined), []);
+ assert.deepEqual(privacyProblems({ displayPaths: "home", hideHost: false }), []);
+});
+
+test("M-B: a scrub-file line over 1,000 characters runs in fallback only", () => {
+ const long = `regex:LONGRULE${"[a-z]".repeat(250)}==>x`;
+ const r = base({ useSourceRules: true }, { scrubText: `${long}\n`, denyText: "" });
+ assert.equal(r.rules!.steps.some((s) => s.why === "scrub line 1" && !s.refused), false);
+ assert.match(r.problems[0].what, /longer than 1,000 characters; it runs in fallback/);
+ assert.equal(applyPrivacy(r.rules, "a LONGRULE b"), "a [hidden] b");
+});
+
+test("M-C: a rule in fallback with no literal fragment hides every line it would run on — never a no-op", () => {
+ const r = rulesOf(["regex:(a|b)+==>R"]);
+ assert.equal(applied(r), false);
+ assert.match(r.problems[0].what, /no literal fragment, so every line it would run on is shown as \[hidden\]/);
+ assert.equal(applyPrivacy(r.rules, "one\n\ntwo"), "[hidden]\n\n[hidden]");
+ // Disabled at run time, the same: a hand-made slow step with no fragment.
+ const said: string[] = [];
+ onSlowRule((why) => said.push(why));
+ try {
+ const slow: PrivacyRules = { v: 1, steps: [{ re: "(x+x+)+y", flags: "g", to: "R", why: "aliases line 7", bounded: true, maxLen: 64, fallback: [] }] };
+ assert.equal(applyPrivacy(slow, "x".repeat(28)), "[hidden]");
+ assert.deepEqual(said, ["aliases line 7"]);
+ assert.equal(applyPrivacy(slow, "a TOKEN b\nc"), "[hidden]\n[hidden]");
+ } finally {
+ onSlowRule(null);
+ }
+});
+
+test("M-C: the backstop times one WINDOW, not one call — a cheap rule over megabytes stays on", () => {
+ const said: string[] = [];
+ onSlowRule((why) => said.push(why));
+ try {
+ const r = rulesOf(["regex:[A-Z0-9]{20}==>[tok]"]);
+ const big = ("ABCDEFGHIJ0123456789 " + "x".repeat(200)).repeat(20_000);
+ const out = applyPrivacy(r.rules, big);
+ assert.ok(!out.includes("ABCDEFGHIJ0123456789"));
+ assert.deepEqual(said, []);
+ assert.equal(applyPrivacy(r.rules, "id ABCDEFGHIJ0123456789 end"), "id [tok] end");
+ } finally {
+ onSlowRule(null);
+ }
+});
+
+test("M-D: a match that used the capped quantifier to its cap hides the rest of the line", () => {
+ const tail = "q".repeat(600) + "TAILSECRET";
+ for (const a of ["regex:tok-.*==>[t]", "glob:tok-*==>[t]"]) {
+ const r = rulesOf([a]);
+ assert.equal(applyPrivacy(r.rules, `x tok-${tail}`), "x [t]", `${a}: cap hit at the end of the pattern`);
+ assert.equal(applyPrivacy(r.rules, `x tok-${tail}\nnext line`), "x [t]\nnext line", `${a}: only to the end of the line`);
+ assert.equal(applyPrivacy(r.rules, "x tok-short y"), "x [t]", `${a}: a short match, as before`);
+ }
+ // The cap hit in the MIDDLE of a pattern: the rest of the line goes too.
+ const mid = rulesOf(["regex:BEGIN.*END==>[m]"]);
+ // `BEGIN.*END` could match past its cap wherever `BEGIN` has 256 more
+ // characters after it: from there the line is hidden, whatever matched.
+ assert.equal(applyPrivacy(mid.rules, `a BEGIN${"z".repeat(300)}END tail SECRET`), "a [hidden]", "the pattern runs past the cap: hidden from BEGIN");
+ assert.equal(applyPrivacy(mid.rules, `a BEGIN${"z".repeat(254)}END tail SECRET`), "a [m][hidden]", "a match within the cap, more after it: hidden from there");
+ assert.equal(applyPrivacy(mid.rules, `a BEGIN${"z".repeat(10)}END tail`), "a [m] tail", "a short line: as before");
+ // Inside a group, the same.
+ const grp = rulesOf(["regex:id-(\\d+)==>ID"]);
+ assert.equal(applyPrivacy(grp.rules, `x id-${"7".repeat(400)} SECRET`), "x ID", "a capped group match hides the rest of the line");
+ assert.equal(applyPrivacy(grp.rules, "x id-42 y"), "x ID y");
+});
+
+test("windows keep the whole-line match grid", () => {
+ const hex = "FAKE-TEST-VALUE".repeat(1024);
+ for (const n of [7, 13, 30]) {
+ const r = rulesOf([`regex:[0-9a-f]{${n}}==>H`]);
+ assert.equal(applyPrivacy(r.rules, hex), hex.replace(new RegExp(`[0-9a-f]{${n}}`, "g"), "H"), `{${n}}`);
+ }
+});
diff --git a/common/lib/privacySettings.ts b/common/lib/privacySettings.ts
@@ -0,0 +1,182 @@
+// settings.privacy — what the two apps' pages SHOW of the machine they run on
+// (demo epic D4, lib/privacy/). Display only: nothing stored, logged to disk,
+// sent to a job or written to a record changes; a "copy path" button still
+// copies the real path. Pure: the type, its defaults, the sanitizer
+// settingsSchema.ts runs it through and the per-field docs SETTINGS.md renders.
+//
+// EVERY DEFAULT IS TODAY'S BEHAVIOUR. With the block absent or at its defaults
+// lib/privacy/compile.ts compiles NO rules, every displayer returns its input
+// unchanged and no provider is rendered — the pages are byte-identical.
+
+import type { FieldDocs } from "./fieldDocs";
+
+export type DisplayPathsMode = "full" | "home" | "masked";
+
+export const DISPLAY_PATHS_MODES: readonly DisplayPathsMode[] = ["full", "home", "masked"];
+
+export type PrivacySettings = {
+ displayPaths: DisplayPathsMode;
+ hideHost: boolean;
+ hideUser: boolean;
+ hidePrivateSites: boolean;
+ aliases: string[];
+ maskEmail: boolean;
+ useSourceRules: boolean;
+};
+
+export const DEFAULT_PRIVACY_SETTINGS: PrivacySettings = {
+ displayPaths: "full",
+ hideHost: false,
+ hideUser: false,
+ hidePrivateSites: false,
+ aliases: [],
+ maskEmail: false,
+ useSourceRules: false,
+};
+
+// An alias line longer than this is dropped by the sanitizer: an operator's
+// display rule is a name and its stand-in, not a document.
+export const PRIVACY_ALIAS_MAX_CHARS = 1000;
+export const PRIVACY_ALIASES_MAX = 200;
+
+export const PRIVACY_SETTINGS_FIELD_DOCS: FieldDocs<PrivacySettings> = {
+ displayPaths:
+ "How a page shows a local path. `\"full\"` (default): as it is. `\"home\"`: the home directory as `~`, and the " +
+ "user's name in a removable-media mount (`/run/media/<user>/…`, `/media/<user>/…`) as `user`. `\"masked\"`: the " +
+ "home directory as `/home/user`, a storage location's root (and its volume's mountpoint) as `[<its label>]`, any " +
+ "other removable-media mount (`/media/<user>/<volume>`, `/run/media/…`, `/mnt/<uuid>`) as `/media/drive`, and a " +
+ "configured volume's UUID, in any case, as `[volume]`. Either mode also catches the path JSON-escaped " +
+ "(`\\/home\\/u`) and percent-encoded (`%2Fhome%2Fu`), and a `file://` URL keeps its shape (`file:///home/user/…`); " +
+ "a path ends at punctuation (`/home/u.` is the home dir, `/home/u.bak` is not). Display only: copy buttons copy " +
+ "the real path. While any key is on, the editor's and umtool's pages carry the rules their browser applies — " +
+ "the values they hide included — in the page's script payload (see `useSourceRules`).",
+ hideHost:
+ "Show this machine's hostname (os.hostname(), its short form and ARCHILYZER_HOST_ID; three characters or more) " +
+ "as the word `host` wherever a page draws it as text. Matched whole-word, in any case, so a hostname inside " +
+ "another word is left alone (a hostname that is itself an ordinary word is replaced where it stands alone); " +
+ "links and other attributes a page needs to work are never rewritten. Default false.",
+ hideUser:
+ "Show this account's user name (three characters or more) as the word `user` wherever a page draws it as a " +
+ "whole word, in any case — a log line's `by: … (name)`, a path segment under `/run/media/`. A name inside " +
+ "another word is left alone. Default false.",
+ hidePrivateSites:
+ "Leave the sites marked private (site.json `audience: \"private\"`) out of the lists and pickers a page DRAWS: " +
+ "the editor's site-scope picker, /channels' Focus bar and a channel's site memberships (a hidden membership is " +
+ "still saved as it was), umtool's home, /projects, /work and its research source pickers (a project is hidden " +
+ "when it belongs to a private site's article). A private site that is the current choice is shown as \"A " +
+ "private site\". Only what is drawn: every lookup, default and allow-list keeps the private sites, so a case " +
+ "on a private site's source keeps reading it. Not access control: a private site's own pages still open by " +
+ "URL. An article's own `audience` is a different notion and hides nothing. If the sites cannot be read, umtool " +
+ "hides every site's pieces (fail closed). Default false.",
+ aliases:
+ "Display rules in the SOURCE MIRROR's scrub format (common/lib/scrubRuleLine.ts): one rule per entry — " +
+ "`lhs==>rhs` (literal), `literal:lhs==>rhs`, `regex:pattern==>rhs` (`\\1` in rhs is group 1) or " +
+ "`glob:pattern==>rhs`; with no `==>` the match shows as `***REMOVED***`. Applied to displayed text after the " +
+ "path and host rules. A `regex:` or `glob:` rule must be cheap to run on every render: at most ONE unbounded " +
+ "or large quantifier (`*`, `+`, `{n,}`, `{n,m}` with m > 64, lazy forms too; it then repeats at most 256 times), " +
+ "no backreference, no repeated group holding a quantifier or an alternation, quantifier ranges multiplying to " +
+ "at most 1,024 and a match of at most 2,048 characters — so a glob has at most one `*`. A rule that breaks " +
+ "this, or does not compile, is not applied: its literal fragments (three characters or more) are shown as " +
+ "`[hidden]` instead (fail closed) and it is reported by its number in the server log and in `archilyzer " +
+ "privacy audit`. A rule that still takes over 50 ms on one call is disabled the same way for the rest of the " +
+ "process. Rules run per line; a line over 4,096 characters is read in overlapping windows. Set with " +
+ "`pnpm ops settings --json '{\"patch\":{\"privacy\":{\"aliases\":[\"old==>new\"]}}}'`. Default [].",
+ maskEmail: "Show every e-mail address a page draws as text as `[email]` (mailto links keep working). Default false.",
+ useSourceRules:
+ "Also apply the source mirror's private rule files (SOURCE_SCRUB_FILE, default " +
+ "`~/.config/archilyzer/source-scrub.txt`, as aliases; SOURCE_DENYLIST_FILE's literals shown as `[hidden]`). " +
+ "Read by the SERVER only: their rules are applied where a page is rendered on the server and are never sent " +
+ "to a browser, a response, a log or an error (a client-rendered panel does not get them). A missing file is " +
+ "a server-log warning naming its path and error code, and nothing else — `archilyzer privacy audit` is the " +
+ "check that the rules took. Default false. AFTER TURNING PRIVACY ON, RELOAD THE OPEN PAGES: a client-rendered " +
+ "panel on a page already open stays unmasked until it is loaded again (a change while on, or turning it off, " +
+ "reaches them on the next navigation). NOTE, for every rule but these: the browser applies the rules " +
+ "itself, so the page it receives CARRIES the values they hide (the home dir, the hostname, the user name, " +
+ "the volume UUIDs and roots, each alias's left side) in its script payload — view-source shows them; the " +
+ "audit reads only what a page draws, not its scripts.",
+};
+
+export function isDisplayPathsMode(v: unknown): v is DisplayPathsMode {
+ return v === "full" || v === "home" || v === "masked";
+}
+
+// FAIL CLOSED (review round 1, S3). A block that is ABSENT is today's
+// behaviour; one that is PRESENT but is not an object, or a key with a value
+// it cannot take, is read as the STRICTEST valid value — never silently as
+// "off": `"displayPaths": "Masked"` is "masked", `"hideHost": "yes"` is true,
+// `"privacy": "on"` turns every hiding key on. privacyProblems() names what
+// was wrong, by key, for the server's one warning.
+export const STRICT_PRIVACY_SETTINGS: PrivacySettings = {
+ displayPaths: "masked",
+ hideHost: true,
+ hideUser: true,
+ hidePrivateSites: true,
+ aliases: [],
+ maskEmail: true,
+ useSourceRules: true,
+};
+
+const BOOLEAN_KEYS = ["hideHost", "hideUser", "hidePrivateSites", "maskEmail", "useSourceRules"] as const;
+
+function cleanAliases(v: unknown): string[] {
+ return Array.isArray(v)
+ ? v
+ .filter((a): a is string => typeof a === "string")
+ .map((a) => a.replace(/\r?\n/g, ""))
+ .filter((a) => a.trim() !== "" && a.length <= PRIVACY_ALIAS_MAX_CHARS)
+ .slice(0, PRIVACY_ALIASES_MAX)
+ : [];
+}
+
+export function sanitizePrivacy(value: unknown): PrivacySettings {
+ if (value === undefined) return { ...DEFAULT_PRIVACY_SETTINGS, aliases: [] };
+ if (!value || typeof value !== "object" || Array.isArray(value)) return { ...STRICT_PRIVACY_SETTINGS, aliases: [] };
+ const r = value as Record<string, unknown>;
+ const mode = (v: unknown): DisplayPathsMode => {
+ if (v === undefined) return DEFAULT_PRIVACY_SETTINGS.displayPaths;
+ return isDisplayPathsMode(v) ? v : "masked";
+ };
+ const bool = (k: (typeof BOOLEAN_KEYS)[number]) => (r[k] === undefined ? DEFAULT_PRIVACY_SETTINGS[k] : r[k] !== false);
+ return {
+ displayPaths: mode(r.displayPaths),
+ hideHost: bool("hideHost"),
+ hideUser: bool("hideUser"),
+ hidePrivateSites: bool("hidePrivateSites"),
+ aliases: cleanAliases(r.aliases),
+ maskEmail: bool("maskEmail"),
+ useSourceRules: bool("useSourceRules"),
+ };
+}
+
+/** What a present `privacy` block got wrong, by key name — never by value. */
+export function privacyProblems(value: unknown): string[] {
+ if (value === undefined) return [];
+ if (!value || typeof value !== "object" || Array.isArray(value)) return ["the block is not an object: every hiding key is read as on"];
+ const r = value as Record<string, unknown>;
+ const out: string[] = [];
+ if (r.displayPaths !== undefined && !isDisplayPathsMode(r.displayPaths)) out.push("displayPaths is not \"full\", \"home\" or \"masked\": read as \"masked\"");
+ for (const k of BOOLEAN_KEYS) if (r[k] !== undefined && typeof r[k] !== "boolean") out.push(`${k} is not true or false: read as true`);
+ if (r.aliases !== undefined) {
+ if (!Array.isArray(r.aliases)) out.push("aliases is not a list: read as []");
+ else if (cleanAliases(r.aliases).length !== r.aliases.length) out.push("aliases has entries that are not rules (not text, empty, or too long): dropped");
+ }
+ // Unknown keys by COUNT: a key's name is the operator's text.
+ const known = new Set<string>(["displayPaths", "aliases", ...BOOLEAN_KEYS]);
+ const unknown = Object.keys(r).filter((k) => !known.has(k)).length;
+ if (unknown) out.push(`${unknown} key${unknown === 1 ? " is" : "s are"} not a privacy key: ignored`);
+ return out;
+}
+
+/** Is anything on? False is today's behaviour exactly. */
+export function privacyActive(p: PrivacySettings | null | undefined): boolean {
+ if (!p) return false;
+ return (
+ p.displayPaths !== "full" ||
+ p.hideHost ||
+ p.hideUser ||
+ p.hidePrivateSites ||
+ p.aliases.length > 0 ||
+ p.maskEmail ||
+ p.useSourceRules
+ );
+}
diff --git a/common/lib/scrubRuleLine.ts b/common/lib/scrubRuleLine.ts
@@ -0,0 +1,62 @@
+// ONE LINE OF THE SOURCE MIRROR'S SCRUB FORMAT, split — the pure half of
+// parseScrubRules (common/publish/source.ts), moved here unchanged so the
+// display rules (lib/privacy/compile.ts, settings.privacy.aliases) read the
+// same format with the same parser, in any runtime: no node imports.
+//
+// A line is `lhs==>rhs` (split at the LAST `==>`, as git-filter-repo splits
+// it), `literal:lhs==>rhs`, `regex:…==>…` or `glob:…==>…`; a line with no
+// `==>` is replaced by filter-repo's `***REMOVED***`. Lines whose first
+// non-blank character is `#` are comments. An empty left side is an error.
+
+export const SCRUB_REMOVED = "***REMOVED***";
+
+export type ScrubLineKind = "plain" | "literal" | "regex" | "glob";
+
+export type ScrubLine = {
+ kind: ScrubLineKind;
+ // The left side with its prefix removed (plain: the whole left side).
+ pattern: string;
+ // The right side, or null when the line has no `==>`.
+ replacement: string | null;
+};
+
+export type ScrubLineResult = { ok: true; line: ScrubLine } | { ok: false; error: string };
+
+/**
+ * An operator file's text as lines: a UTF-8 byte-order mark at the start is
+ * dropped and CRLF endings become LF. An editor that writes either must not
+ * turn the first rule (and the denial it implies) into one that never matches.
+ */
+export function operatorLines(text: string): string[] {
+ return text.replace(/^\uFEFF/, "").split("\n").map((l) => l.replace(/\r$/, ""));
+}
+
+/** A blank line or a comment: no rule. */
+export function isScrubSkip(line: string): boolean {
+ const t = line.trim();
+ return t === "" || t.startsWith("#");
+}
+
+/** One (non-skip) line, split. `n` is its 1-based line number, for the error. */
+export function splitScrubLine(line: string, n: number): ScrubLineResult {
+ const i = line.lastIndexOf("==>");
+ const lhs = i === -1 ? line : line.slice(0, i);
+ const replacement = i === -1 ? null : line.slice(i + 3);
+ for (const prefix of ["regex:", "glob:", "literal:"] as const) {
+ if (lhs.startsWith(prefix)) {
+ if (lhs.length === prefix.length) {
+ return { ok: false, error: `scrub line ${n} has an empty left side — it would match nothing and deny nothing` };
+ }
+ return { ok: true, line: { kind: prefix.slice(0, -1) as ScrubLineKind, pattern: lhs.slice(prefix.length), replacement } };
+ }
+ }
+ if (i === 0) {
+ return { ok: false, error: `scrub line ${n} has an empty left side — it would match nothing and deny nothing` };
+ }
+ return { ok: true, line: { kind: "plain", pattern: lhs, replacement } };
+}
+
+/** The literal a line denies by implication ("" for regex and glob lines). */
+export function scrubLineDenied(line: ScrubLine): string {
+ return line.kind === "plain" || line.kind === "literal" ? line.pattern : "";
+}
diff --git a/common/lib/settingsDocs.ts b/common/lib/settingsDocs.ts
@@ -17,6 +17,7 @@ import {
JOBS_SETTINGS_FIELD_DOCS,
LOOKOUTS_SETTINGS_FIELD_DOCS,
LOOKOUT_ITEM_FIELD_DOCS,
+ PRIVACY_SETTINGS_FIELD_DOCS,
SERVICE_COOKIES_SETTINGS_FIELD_DOCS,
VOICE_CONVERT_SETTINGS_FIELD_DOCS,
VOICE_ENHANCE_SETTINGS_FIELD_DOCS,
@@ -372,6 +373,13 @@ export function blockTables(d: SiteSettings): Partial<Record<keyof SiteSettings,
},
{ path: "lookouts.items[]", docs: LOOKOUT_ITEM_FIELD_DOCS },
],
+ privacy: [
+ {
+ path: "privacy",
+ docs: PRIVACY_SETTINGS_FIELD_DOCS,
+ defaults: fromObject(d.privacy),
+ },
+ ],
};
}
diff --git a/common/lib/settingsSchema.test.ts b/common/lib/settingsSchema.test.ts
@@ -38,6 +38,7 @@ import type { ClipsSettings } from "./clipSettings";
import type { JobsSettings } from "./jobsSettings";
import type { ServiceCookiesSettings } from "./serviceCookieSettings";
import type { LookoutsSettings } from "./lookoutSettings";
+import type { PrivacySettings } from "./privacySettings";
import type { VoiceSettings } from "./voiceSettings";
import type { GenerationSettings } from "./generationSettings";
import type {
@@ -138,13 +139,15 @@ type PreSchemaSiteSettings = {
serviceCookies: ServiceCookiesSettings;
// Saved lookouts (lane/lookout).
lookouts: LookoutsSettings;
+ // What the pages show of this machine (demo epic D4).
+ privacy: PrivacySettings;
};
// Bracketed so the conditional does not distribute (see commit 8c43231).
type Same<A, B> = [A] extends [B] ? ([B] extends [A] ? true : false) : false;
const shapeUnchanged: Same<SiteSettings, PreSchemaSiteSettings> = true;
-test("SiteSettings keeps its 47 fields, in file order", () => {
+test("SiteSettings keeps its 48 fields, in file order", () => {
assert.equal(shapeUnchanged, true);
assert.deepEqual(Object.keys(siteSettingsSchema.shape), [
"adminTitle",
@@ -195,6 +198,7 @@ test("SiteSettings keeps its 47 fields, in file order", () => {
"jobs",
"serviceCookies",
"lookouts",
+ "privacy",
]);
// A parsed object carries every key, in that order — writeSettings writes
// exactly this, so the order is the on-disk order.
diff --git a/common/lib/settingsSchema.ts b/common/lib/settingsSchema.ts
@@ -86,6 +86,7 @@ import { sanitizeRemoteArchives, type RemoteArchive } from "./remoteArchives";
import { sanitizeClips, type ClipsSettings } from "./clipSettings";
import { sanitizeJobs, type JobsSettings } from "./jobsSettings";
import { sanitizeLookouts, type LookoutsSettings } from "./lookoutSettings";
+import { sanitizePrivacy, type PrivacySettings } from "./privacySettings";
import { sanitizeServiceCookies, type ServiceCookiesSettings } from "./serviceCookieSettings";
import { sanitizeGeneration, type GenerationSettings } from "./generationSettings";
export {
@@ -117,6 +118,7 @@ export { CLIPS_SETTINGS_FIELD_DOCS, type ClipsSettings } from "./clipSettings";
export { JOBS_SETTINGS_FIELD_DOCS, type JobsSettings } from "./jobsSettings";
export { LOOKOUTS_SETTINGS_FIELD_DOCS, LOOKOUT_ITEM_FIELD_DOCS, type LookoutsSettings, type LookoutItem } from "./lookoutSettings";
export { SERVICE_COOKIES_SETTINGS_FIELD_DOCS, type ServiceCookiesSettings } from "./serviceCookieSettings";
+export { PRIVACY_SETTINGS_FIELD_DOCS, type PrivacySettings } from "./privacySettings";
import {
DEFAULT_COOKIE_MODE,
isCookieMode,
@@ -2082,6 +2084,9 @@ export const siteSettingsSchema = z.object({
lookouts: settingsField((v): LookoutsSettings => sanitizeLookouts(v)).describe(
"Saved lookouts (lane/lookout): each names channels, a number of days back and an optional prompt, and a run reads those channels' recent transcripts — by air date, duplicate uploads and stream cut-downs folded in — and answers with video ideas. OFF and empty by default; nothing a lookout writes is published. `pnpm ops get lookouts` is the readout, `pnpm ops lookout-run --json '{\"id\":\"…\",\"dryRun\":true}'` lists what one would read. See LookoutsSettings and common/lib/lookoutSettings.ts.",
),
+ privacy: settingsField((v): PrivacySettings => sanitizePrivacy(v)).describe(
+ "What the editor's and umtool's pages SHOW of this machine (demo epic D4): local paths with the home directory as `~` or masked, the hostname as a fixed word, private sites left out of the pickers, e-mail addresses masked, and the operator's own display aliases in the source mirror's scrub format. Display only — nothing stored, logged, sent to a job or written to a record changes, and copy buttons copy the real path. Every default is today's behaviour: with the block absent or at its defaults the pages are byte-identical. `archilyzer privacy audit` checks the rendered pages against a denylist. Set with `pnpm ops settings --json '{\"patch\":{\"privacy\":{\"displayPaths\":\"home\"}}}'`. See PrivacySettings and common/lib/privacy/.",
+ ),
});
export type SiteSettings = z.infer<typeof siteSettingsSchema>;
diff --git a/common/publish/scrubRuleLine.test.ts b/common/publish/scrubRuleLine.test.ts
@@ -0,0 +1,126 @@
+// parseScrubRules' line split moved to lib/scrubRuleLine.ts (demo epic D4) as
+// a PURE MOVE. This keeps the pre-move implementation, frozen, and asserts the
+// new parseScrubRules answers exactly what it answered — the lines filter-repo
+// reads, every denied literal and where it came from, and every refusal — over
+// a rule file covering all four forms, comments, blanks, a BOM and CRLF.
+//
+// Run with: node_modules/.bin/tsx --test common/publish/scrubRuleLine.test.ts
+
+import { test } from "node:test";
+import assert from "node:assert/strict";
+import { mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import path from "node:path";
+import { parseScrubRules, HOME_REPLACEMENT, BUILT_IN_HOME_RULE, SourceRefusal } from "./source";
+import { isScrubSkip, operatorLines, splitScrubLine, scrubLineDenied } from "../lib/scrubRuleLine";
+import { MASKED_HOME } from "../lib/privacy/compile";
+
+// ── the implementation as it was before the move (06c95c3f), verbatim ────────
+function legacyOperatorLines(text: string): string[] {
+ return text.replace(/^\uFEFF/, "").split("\n").map((l) => l.replace(/\r$/, ""));
+}
+function legacyParseScrubRules(text: string, homeDir: string) {
+ const lines: string[] = [];
+ const denied: Array<{ text: string; from: string }> = [];
+ const home = homeDir.replace(/\/+$/, "");
+ if (home.length > 1 && home !== HOME_REPLACEMENT) {
+ lines.push(`${home}==>${HOME_REPLACEMENT}`);
+ denied.push({ text: home, from: BUILT_IN_HOME_RULE });
+ }
+ legacyOperatorLines(text).forEach((line, n) => {
+ const t = line.trim();
+ if (t === "" || t.startsWith("#")) return;
+ const i = line.lastIndexOf("==>");
+ let lhs = i === -1 ? line : line.slice(0, i);
+ const from = `scrub line ${n + 1} lhs`;
+ for (const prefix of ["regex:", "glob:", "literal:"]) {
+ if (lhs.startsWith(prefix)) {
+ if (lhs.length === prefix.length) {
+ throw new SourceRefusal(`scrub line ${n + 1} has an empty left side — it would match nothing and deny nothing`);
+ }
+ if (prefix === "literal:") lhs = lhs.slice(prefix.length);
+ else lhs = "";
+ break;
+ }
+ }
+ if (i === 0) {
+ throw new SourceRefusal(`scrub line ${n + 1} has an empty left side — it would match nothing and deny nothing`);
+ }
+ lines.push(line);
+ if (lhs) denied.push({ text: lhs, from });
+ });
+ return { lines, denied };
+}
+
+const outcome = (f: () => unknown) => {
+ try {
+ return { ok: f() };
+ } catch (err) {
+ return { err: `${(err as Error).name}: ${(err as Error).message}` };
+ }
+};
+
+const DIR = mkdtempSync(path.join(tmpdir(), "scrub-line-"));
+const FILE = path.join(DIR, "scrub.txt");
+
+const RULE_FILE =
+ "\uFEFFalpha==>beta\r\n" +
+ "# a comment\r\n" +
+ "\r\n" +
+ " \r\n" +
+ " # an indented comment\n" +
+ "literal:gamma==>delta\n" +
+ "regex:ep+silon(\\d+)==>zeta\\1\n" +
+ "glob:eta*theta==>iota\n" +
+ "kappa with no arrow\n" +
+ "lambda==>mu==>nu\n" +
+ "literal:xi==>\n" +
+ "regex:omicron\n" +
+ " spaced ==> rhs \n" +
+ "trailing\r";
+
+test("parseScrubRules answers exactly what it did before the move", () => {
+ writeFileSync(FILE, RULE_FILE);
+ const text = readFileSync(FILE, "utf8");
+ for (const home of ["/home/someone", "/home/someone/", "/", HOME_REPLACEMENT, ""]) {
+ assert.deepEqual(outcome(() => parseScrubRules(text, home)), outcome(() => legacyParseScrubRules(text, home)), home);
+ }
+});
+
+test("the refusals are the same, at the same line", () => {
+ for (const bad of ["==>x\n", "a==>b\nregex:\n", "literal:==>x", "ok==>1\n\nglob:==>y\n", "\uFEFF==>z\r\n"]) {
+ writeFileSync(FILE, bad);
+ const text = readFileSync(FILE, "utf8");
+ const got = outcome(() => parseScrubRules(text, "/home/someone"));
+ assert.deepEqual(got, outcome(() => legacyParseScrubRules(text, "/home/someone")), JSON.stringify(bad));
+ assert.ok("err" in got, JSON.stringify(bad));
+ }
+});
+
+test("the displayers' masked home dir is the mirror's HOME_REPLACEMENT", () => {
+ assert.equal(MASKED_HOME, HOME_REPLACEMENT);
+});
+
+test("operatorLines is the old one", () => {
+ for (const t of [RULE_FILE, "", "\uFEFF", "a\r\nb\r", "\r\n\r\n"]) assert.deepEqual(operatorLines(t), legacyOperatorLines(t));
+});
+
+test("splitScrubLine: the four forms, the missing arrow, the last arrow", () => {
+ const split = (l: string) => {
+ const r = splitScrubLine(l, 1);
+ assert.ok(r.ok);
+ return r.line;
+ };
+ assert.deepEqual(split("a==>b"), { kind: "plain", pattern: "a", replacement: "b" });
+ assert.deepEqual(split("literal:a==>b"), { kind: "literal", pattern: "a", replacement: "b" });
+ assert.deepEqual(split("regex:a+==>b"), { kind: "regex", pattern: "a+", replacement: "b" });
+ assert.deepEqual(split("glob:a*==>b"), { kind: "glob", pattern: "a*", replacement: "b" });
+ assert.deepEqual(split("a"), { kind: "plain", pattern: "a", replacement: null });
+ assert.deepEqual(split("a==>b==>c"), { kind: "plain", pattern: "a==>b", replacement: "c" });
+ assert.equal(scrubLineDenied(split("regex:a==>b")), "");
+ assert.equal(scrubLineDenied(split("literal:a==>b")), "a");
+ assert.equal(isScrubSkip(" # x"), true);
+ assert.equal(isScrubSkip(" x"), false);
+});
+
+test.after(() => rmSync(DIR, { recursive: true, force: true }));
diff --git a/common/publish/source.ts b/common/publish/source.ts
@@ -83,6 +83,7 @@ import {
type Literal,
} from "./sourceAudit";
import { writeTreeIndexes } from "./sourceTree";
+import { isScrubSkip, scrubLineDenied, splitScrubLine } from "../lib/scrubRuleLine";
// Type-only: build.ts imports THIS module lazily, and must not load it (or the
// AWS SDK this would drag in) at import time.
import type { PublishOpts } from "./build";
@@ -223,27 +224,15 @@ export function parseScrubRules(text: string, homeDir: string): ScrubRules {
lines.push(`${home}==>${HOME_REPLACEMENT}`);
denied.push({ text: home, from: BUILT_IN_HOME_RULE });
}
+ // The line split is lib/scrubRuleLine.ts (a pure move: the display rules,
+ // settings.privacy.aliases, read the same format with the same parser).
operatorLines(text).forEach((line, n) => {
- const t = line.trim();
- if (t === "" || t.startsWith("#")) return;
- const i = line.lastIndexOf("==>");
- let lhs = i === -1 ? line : line.slice(0, i);
- const from = `scrub line ${n + 1} lhs`;
- for (const prefix of ["regex:", "glob:", "literal:"]) {
- if (lhs.startsWith(prefix)) {
- if (lhs.length === prefix.length) {
- throw new SourceRefusal(`scrub line ${n + 1} has an empty left side — it would match nothing and deny nothing`);
- }
- if (prefix === "literal:") lhs = lhs.slice(prefix.length);
- else lhs = "";
- break;
- }
- }
- if (i === 0) {
- throw new SourceRefusal(`scrub line ${n + 1} has an empty left side — it would match nothing and deny nothing`);
- }
+ if (isScrubSkip(line)) return;
+ const split = splitScrubLine(line, n + 1);
+ if (!split.ok) throw new SourceRefusal(split.error);
lines.push(line);
- if (lhs) denied.push({ text: lhs, from });
+ const lhs = scrubLineDenied(split.line);
+ if (lhs) denied.push({ text: lhs, from: `scrub line ${n + 1} lhs` });
});
return { lines, denied };
}
diff --git a/common/publish/sourceAudit.ts b/common/publish/sourceAudit.ts
@@ -32,6 +32,7 @@ import path from "node:path";
import { gunzipSync } from "node:zlib";
import { runChildIntoLog } from "../jobs/runChild";
import "../lib/childKillGuard";
+import { operatorLines } from "../lib/scrubRuleLine";
/** A refusal: the step stops, publishes nothing, and says why. */
export class SourceRefusal extends Error {
@@ -65,14 +66,9 @@ export function foldAscii(buf: Uint8Array): Buffer {
return out;
}
-/**
- * An operator file's text as lines: a UTF-8 byte-order mark at the start is
- * dropped and CRLF endings become LF. An editor that writes either must not
- * turn the first rule (and the denial it implies) into one that never matches.
- */
-export function operatorLines(text: string): string[] {
- return text.replace(/^\uFEFF/, "").split("\n").map((l) => l.replace(/\r$/, ""));
-}
+// An operator file's text as lines (BOM dropped, CRLF → LF): moved unchanged
+// to lib/scrubRuleLine.ts, re-exported here for its callers.
+export { operatorLines };
/**
* The denylist file: one literal per line. `i:` in front makes it ASCII
diff --git a/settings.json.example b/settings.json.example
@@ -385,5 +385,14 @@
"enabled": false,
"afterSync": false,
"items": []
+ },
+ "privacy": {
+ "displayPaths": "full",
+ "hideHost": false,
+ "hideUser": false,
+ "hidePrivateSites": false,
+ "aliases": [],
+ "maskEmail": false,
+ "useSourceRules": false
}
}