// 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 | null = null; try { const parsed = JSON.parse(readFileSync(paths.settingsFile, "utf8")) as unknown; raw = parsed && typeof parsed === "object" && !Array.isArray(parsed) ? (parsed as Record) : 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; }