import { builtinRules, findBuiltinSpans } from "./detectors.ts"; import { type LearnedValue, learnEnvironmentValues, learnedValueSpans, loadDotenvValues, } from "./dotenv.ts"; import { PlaceholderStore } from "./placeholders.ts"; import { isPlainObject } from "./safety.ts"; import { selectSecretSpans } from "./selector.ts"; import { type CompiledCustomRule, compileCustomRegex, customRegexSpans, } from "./settings.ts"; import { findStructureSpans } from "./structures.ts"; import type { DeepRedactionResult, Detector, EngineStats, LeaksSettings, RedactionOrigin, RedactionRecord, RedactionResult, SecretSpan, WarningRecord, } from "./types.ts"; export type LeaksEngineOptions = { settings?: Partial; env?: Record; detectors?: Detector[]; }; export class LeaksEngine { settings: LeaksSettings; private readonly detectors: Detector[]; private readonly warnings: WarningRecord[] = []; private readonly warningKeys = new Set(); private readonly placeholders = new PlaceholderStore({ onWarning: (warning) => this.addWarning(warning), }); private customRules: CompiledCustomRule[] = []; private invalidRegexCount = 0; private learned: LearnedValue[] = []; private lastProviderRedactionCount = 0; private totalProviderRedactionCount = 0; private recentLabels: string[] = []; private latestTags: string[] = []; readonly notifiedPlaceholders = new Set(); constructor(options: LeaksEngineOptions = {}) { this.settings = { regex: options.settings?.regex ?? [] }; this.detectors = options.detectors ?? []; this.compileSettings(); if (options.env) this.learn(process.cwd(), options.env); } reload(cwd = process.cwd(), settings = this.settings, env = process.env) { this.settings = { regex: settings.regex }; this.compileSettings(); this.learn(cwd, env); this.notifiedPlaceholders.clear(); } redactText( text: string, origin: RedactionOrigin = "provider", ): RedactionResult { let spans: SecretSpan[] = [ ...findStructureSpans(text), ...findBuiltinSpans(text), ...customRegexSpans(text, this.customRules), ...learnedValueSpans(text, this.learned), ]; for (const detector of this.detectors) { try { spans = spans.concat(detector(text)); } catch { this.warnOnce( "detector.failure", "detector failure; redaction pass left unchanged", ); if (origin === "provider") this.lastProviderRedactionCount = 0; return { text, count: 0, labels: [], placeholders: [], redactions: [], }; } } const selected = selectSecretSpans(text, spans); let redacted = text; const placeholders: string[] = []; const labels: string[] = []; const redactions: RedactionRecord[] = []; for (const span of selected) { const spanLabels = span.labels.map((label) => label.tag); const placeholder = this.placeholders.create(span.value, span.labels); redacted = `${redacted.slice(0, span.start)}${placeholder}${redacted.slice(span.end)}`; placeholders.push(placeholder); labels.push(...spanLabels); redactions.push({ path: "", labels: spanLabels, placeholders: [placeholder], }); } const count = selected.length; if (origin === "provider") { this.lastProviderRedactionCount = count; this.totalProviderRedactionCount += count; } if (labels.length > 0) this.recentLabels = labels.slice(-12); if (placeholders.length > 0) { this.latestTags = placeholders.map((placeholder) => placeholder .replace(/^__LEAK_?/, "") .replace(/_[a-f0-9]{12}(?:_\d+)?__$/, ""), ); } return { text: redacted, count, labels, placeholders, redactions }; } redactDeep( value: T, origin: RedactionOrigin = "provider", ): DeepRedactionResult { return this.walk(value, origin, false); } restoreText(text: string) { return this.placeholders.restore(text); } restoreDeep(value: T): DeepRedactionResult { return this.walk(value, "provider", true); } clear() { this.placeholders.clear(); this.lastProviderRedactionCount = 0; this.recentLabels = []; this.latestTags = []; this.notifiedPlaceholders.clear(); } stats(): EngineStats { return { active: true, builtInRuleCount: builtinRules.length, customRegexCount: this.customRules.length, regexWarningCount: this.warnings.filter((warning) => warning.code.startsWith("settings.regex."), ).length, warningCount: this.warnings.length, invalidRegexCount: this.invalidRegexCount, learnedCount: this.learned.length, mappingCount: this.placeholders.stats().mappingCount, lastProviderRedactionCount: this.lastProviderRedactionCount, totalProviderRedactionCount: this.totalProviderRedactionCount, recentLabels: [...this.recentLabels], latestTags: [...this.latestTags], warnings: [...this.warnings], }; } private compileSettings() { const compiled = compileCustomRegex(this.settings); this.customRules = compiled.rules; this.invalidRegexCount = compiled.invalidRegexCount; for (const warning of compiled.warnings) this.addWarning(warning); } private learn(cwd: string, env: Record) { const dotenv = loadDotenvValues(cwd); const processEnv = learnEnvironmentValues(env); this.learned = [...dotenv.values, ...processEnv.values].slice(0, 8192); for (const warning of [...dotenv.warnings, ...processEnv.warnings]) this.addWarning(warning); } private walk( input: T, origin: RedactionOrigin, restore: boolean, ): DeepRedactionResult { const seen = new WeakMap(); const redactions: RedactionRecord[] = []; let count = 0; let changed = false; const visit = (value: unknown, depth: number, trace: string): unknown => { if (typeof value === "string") { if (restore) { const next = this.restoreText(value); if (next !== value) { changed = true; count++; } return next; } const result = this.redactText(value, origin); if (result.text !== value) changed = true; count += result.count; for (const item of result.redactions) redactions.push({ ...item, path: trace || "$" }); return result.text; } if (value === null || typeof value !== "object") return value; if (depth >= 64) { this.warnOnce( "traversal.depth", "maximum redaction traversal depth reached", ); return value; } const cached = seen.get(value); if (cached) return cached; if (Array.isArray(value)) { const copy: unknown[] = []; seen.set(value, copy); for (let index = 0; index < value.length; index++) copy.push(visit(value[index], depth + 1, `${trace}[${index}]`)); if (copy.some((item, index) => item !== value[index])) changed = true; return copy; } if (!isPlainObject(value)) return value; const source = value as Record; const copy: Record = {}; seen.set(value, copy); for (const [key, item] of Object.entries(source)) copy[key] = visit(item, depth + 1, childPath(trace, key)); if (Object.keys(copy).some((key) => copy[key] !== source[key])) changed = true; return copy; }; const value = visit(input, 0, "") as T; if (origin === "provider" && !restore) this.lastProviderRedactionCount = count; return { value, changed, count, redactions }; } private warnOnce(code: string, message: string) { if (this.warningKeys.has(code)) return; this.warningKeys.add(code); this.addWarning({ code, message, severity: "warning" }); } private addWarning(warning: WarningRecord) { this.warnings.push(warning); } } function childPath(parent: string, key: string) { if (/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(key)) return parent ? `${parent}.${key}` : key; return `${parent}[${JSON.stringify(key)}]`; }