// 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 = "(?/.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; } export type Fragment = { text: string; lead: boolean }; /** * The CERTAIN literal fragments of a regex or glob (review round 3, M2): runs * of three or more plain characters that EVERY match contains — outside * character classes, quantifier bodies, group syntax and escapes, not made * optional by a quantifier, not in a branch of an alternation. `lead`: the * fragment is where every match starts (nothing variable before it), so a * match containing it starts there. A rule in fallback (display.ts) hides, * on each line where a fragment occurs, from a leading one to the end of the * line — or the WHOLE line for a fragment that is not leading; a rule with no * certain fragment hides every non-empty line it runs on. */ export function certainFragments(pattern: string, kind: "regex" | "glob"): Fragment[] { if (kind === "glob") { const out: Fragment[] = []; let run = ""; let runAt = 0; const flush = () => { if (run.length >= 3) out.push({ text: run, lead: runAt === 0 }); run = ""; }; for (let i = 0; i < pattern.length; i++) { const c = pattern[i]; if (c === "*" || c === "?" || c === "[") { flush(); if (c === "[") { const j = pattern.indexOf("]", i + 2); if (j === -1) break; i = j; } continue; } if (run === "") runAt = i; run += c; } flush(); return dedupeFragments(out); } type Frame = { runs: Array; alt: boolean }; const stack: Frame[] = [{ runs: [], alt: false }]; let run = ""; let runAt = -1; // Where the first matched character of the pattern is (after any leading // `^` and group openings): a fragment there leads every match. let leadAt = -1; let variableSeen = false; const top = () => stack[stack.length - 1]; const flush = () => { if (run.length >= 3) top().runs.push({ text: run, lead: runAt === leadAt && !variableSeen, pos: runAt }); run = ""; }; const quantAfter = (i: number): { min: number; len: number } | null => { const c = pattern[i]; let q: { min: number; len: number } | null = null; if (c === "*") q = { min: 0, len: 1 }; else if (c === "+") q = { min: 1, len: 1 }; else if (c === "?") q = { min: 0, len: 1 }; else if (c === "{") { const m = /^\{(\d+)(,\d*)?\}/.exec(pattern.slice(i)); if (m) q = { min: Number(m[1]), len: m[0].length }; } if (q && pattern[i + q.len] === "?") q.len++; return q; }; for (let i = 0; i < pattern.length; i++) { const c = pattern[i]; if (c === "\\") { flush(); variableSeen = true; if (leadAt === -1) leadAt = -2; const n = pattern[i + 1]; i += n === "x" ? 3 : n === "u" ? (pattern[i + 2] === "{" ? Math.max(1, pattern.indexOf("}", i) - i) : 5) : 1; const q = quantAfter(i + 1); if (q) i += q.len; continue; } if (c === "[") { flush(); if (leadAt === -1) leadAt = -2; variableSeen = true; let j = i + 1; if (pattern[j] === "^") j++; if (pattern[j] === "]") j++; while (j < pattern.length && pattern[j] !== "]") j += pattern[j] === "\\" ? 2 : 1; i = j; const q = quantAfter(i + 1); if (q) i += q.len; continue; } if (c === "(") { flush(); const m = /^\(\?(?::|=|!|<=|)/.exec(pattern.slice(i)); i += m ? m[0].length - 1 : 0; stack.push({ runs: [], alt: false }); continue; } if (c === ")") { flush(); const f = stack.length > 1 ? stack.pop()! : { runs: [], alt: false }; const q = quantAfter(i + 1); if (q) i += q.len; // Kept only when every match goes through the group's text. if (!f.alt && !(q && q.min === 0)) top().runs.push(...f.runs); else variableSeen = true; continue; } if (c === "|") { flush(); top().alt = true; continue; } if (c === "." || c === "^" || c === "$") { flush(); if (c === ".") { variableSeen = true; if (leadAt === -1) leadAt = -2; const q = quantAfter(i + 1); if (q) i += q.len; } continue; } const q = quantAfter(i + 1); if (q) { // The character before a quantifier: optional (min 0) is not certain; // a repeat ends the run (`ab+c` holds "ab", then "c"). if (run === "" && leadAt === -1) leadAt = i; if (run === "") runAt = i; if (q.min > 0) run += c; flush(); variableSeen = true; i += q.len; continue; } if (leadAt === -1) leadAt = i; if (run === "") runAt = i; run += c; } flush(); // An unclosed group (a rule that does not compile): its text counts. while (stack.length > 1) { const f = stack.pop()!; if (!f.alt) top().runs.push(...f.runs); } if (stack[0].alt) return []; return dedupeFragments(stack[0].runs.map(({ text, lead }) => ({ text, lead }))); } function dedupeFragments(list: Fragment[]): Fragment[] { const seen = new Map(); for (const f of list) { const prev = seen.get(f.text); if (!prev) seen.set(f.text, { ...f }); else prev.lead = prev.lead || f.lead; } return [...seen.values()]; } /** The certain fragments' texts (the probes' and the tests' view). */ export function literalFragments(pattern: string, kind: "regex" | "glob"): string[] { return certainFragments(pattern, kind).map((f) => f.text); } 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: Fragment[] = line.kind === "regex" || line.kind === "glob" ? certainFragments(line.pattern, line.kind) : line.pattern.length >= 3 ? [{ text: line.pattern, lead: true }] : []; problems.push({ source: where.source, line: where.n, what: `${what}; ${ frags.length ? `it runs in fallback: on every line holding one of its ${frags.length} certain literal fragment${frags.length === 1 ? "" : "s"}, the text from that fragment (or the whole line, where the fragment does not start the match) is shown as [hidden]` : "it runs in fallback: it has no certain 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((f) => ({ re: escapeRegExp(f.text), lead: f.lead })), ...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 = certainFragments(line.pattern, line.kind).map((f) => ({ re: escapeRegExp(f.text), lead: f.lead })); 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(); 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: `(?= 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 }; }