repositories / pi-ext

pi-ext

bugabingas pi extensions

owned by bugabinga

extensions/leaks/src/engine.ts

Raw
File outline
import { PlaceholderStore } from "./placeholders.ts";
import type {
	DeepRedactionResult,
	Detector,
	EngineStats,
	LeaksSettings,
	RedactionOrigin,
	RedactionResult,
	SecretSpan,
	WarningRecord,
} from "./types.ts";

export type LeaksEngineOptions = {
	settings?: Partial<LeaksSettings>;
	env?: Record<string, string | undefined>;
	detectors?: Detector[];
};

export class LeaksEngine {
	readonly settings: LeaksSettings;
	private readonly detectors: Detector[];
	private readonly warnings: WarningRecord[] = [];
	private readonly warningKeys = new Set<string>();
	private readonly placeholders = new PlaceholderStore({
		onWarning: (warning) => this.addWarning(warning),
	});
	private lastProviderRedactionCount = 0;
	private totalProviderRedactionCount = 0;
	private recentLabels: string[] = [];
	private latestTags: string[] = [];

	constructor(options: LeaksEngineOptions = {}) {
		this.settings = { regex: options.settings?.regex ?? [] };
		this.detectors = options.detectors ?? [];
		void options.env;
	}

	reload(_cwd = process.cwd(), _settings = this.settings, _env = process.env) {}

	redactText(text: string, origin: RedactionOrigin = "provider"): RedactionResult {
		let spans: SecretSpan[] = [];
		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: [] };
			}
		}

		const selected = spans
			.filter((span) => span.start >= 0 && span.end > span.start && span.end <= text.length)
			.toSorted((left, right) => right.start - left.start);
		let redacted = text;
		const placeholders: string[] = [];
		const labels: string[] = [];
		for (const span of selected) {
			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(...span.labels.map((label) => label.tag));
		}

		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 };
	}

	redactDeep<T>(value: T, origin: RedactionOrigin = "provider"): DeepRedactionResult<T> {
		if (typeof value !== "string") return { value, changed: false, count: 0 };
		const result = this.redactText(value, origin);
		return {
			value: result.text as T,
			changed: result.text !== value,
			count: result.count,
		};
	}

	restoreText(text: string) {
		return this.placeholders.restore(text);
	}

	restoreDeep<T>(value: T): DeepRedactionResult<T> {
		if (typeof value !== "string") return { value, changed: false, count: 0 };
		const restored = this.restoreText(value);
		return { value: restored as T, changed: restored !== value, count: restored === value ? 0 : 1 };
	}

	clear() {
		this.placeholders.clear();
		this.lastProviderRedactionCount = 0;
		this.recentLabels = [];
		this.latestTags = [];
	}

	stats(): EngineStats {
		return {
			active: true,
			builtInRuleCount: 0,
			customRegexCount: this.settings.regex.length,
			regexWarningCount: 0,
			warningCount: this.warnings.length,
			invalidRegexCount: 0,
			learnedCount: 0,
			mappingCount: this.placeholders.stats().mappingCount,
			lastProviderRedactionCount: this.lastProviderRedactionCount,
			totalProviderRedactionCount: this.totalProviderRedactionCount,
			recentLabels: [...this.recentLabels],
			latestTags: [...this.latestTags],
			warnings: [...this.warnings],
		};
	}

	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);
	}
}