/** * Privacy engine (PR-002, ยง5.1). * * A convenience facade for text-level `redact` / `restore` independent of the * protocol pipeline. Sessions are request-scoped and read-only to callers. */ import { randomUUID } from "node:crypto"; import { resolvePrivacyConfig } from "./config.js"; import { redactRegions, setRegionAction } from "./redact.js"; import { restoreString } from "./restore.js"; import { PrivacySession } from "./session.js"; import type { PrivacyEngine, PrivacyRecognizer, PrivacySessionOptions, PrivacySessionView, RecognizerContext, } from "./types.js"; const DEFAULT_MAX_PLACEHOLDER_LENGTH = 128; export function createPrivacyEngine(): PrivacyEngine { const sessions = new Map(); const createSession = ( id?: string, options: PrivacySessionOptions = {}, ): PrivacySessionView => { const resolved = resolvePrivacyConfig({ recognizers: [{ priority: 0, recognize: () => [] }], mapping: { prefix: options.prefix, tagLength: options.tagLength }, }); const session = new PrivacySession(id ?? randomUUID(), { compiled: resolved.template, namespace: resolved.namespace, }); sessions.set(session.id, session); return session; }; const requireSession = (view: PrivacySessionView): PrivacySession => { if (view instanceof PrivacySession) return view; const found = sessions.get(view.id); if (!found) { throw new Error("privacy session is no longer active"); } return found; }; return { createSession, getSession(id: string): PrivacySessionView | undefined { return sessions.get(id); }, destroySession(id: string): void { sessions.delete(id); }, async redact( text: string, session: PrivacySessionView, recognizers: PrivacyRecognizer[], context?: Partial, ): Promise { const active = requireSession(session); const config = resolvePrivacyConfig({ recognizers, mapping: { prefix: active.compiled.raw, tagLength: active.compiled.tagLength, }, }); const holder = { value: text }; const region = setRegionAction( { channel: context?.channel ?? "text", path: context?.path ?? "text", segments: [ { get: () => holder.value, set: (v: string) => { holder.value = v; }, }, ], }, "redact", ); await redactRegions([region], active, config); return holder.value; }, restore(text: string, session: PrivacySessionView): string { const active = requireSession(session); return restoreString( text, active.compiled, active.snapshot(), DEFAULT_MAX_PLACEHOLDER_LENGTH, ).text; }, }; }