repositories / pi-ext
pi-ext
bugabingas pi extensions
owned by bugabinga
extensions/leaks/src/engine.ts
RawFile outline
- LeaksEngineOptions line 11
- LeaksEngine line 17
- settings line 18
- detectors line 19
- warnings line 20
- warningKeys line 21
- lastProviderRedactionCount line 22
- totalProviderRedactionCount line 23
- constructor line 25
- reload line 31
- redactText line 33
- redactDeep line 49
- restoreText line 59
- restoreDeep line 63
- clear line 67
- stats line 71
- warnOnce line 89
import type {
DeepRedactionResult,
Detector,
EngineStats,
LeaksSettings,
RedactionOrigin,
RedactionResult,
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 lastProviderRedactionCount = 0;
private totalProviderRedactionCount = 0;
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 {
const failed = this.detectors.some((detector) => {
try {
detector(text);
return false;
} catch {
this.warnOnce("detector.failure", "detector failure; redaction pass left unchanged");
return true;
}
});
const result = { text, count: 0, labels: [], placeholders: [] };
if (origin === "provider") this.lastProviderRedactionCount = 0;
if (failed) return result;
return result;
}
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 text;
}
restoreDeep<T>(value: T): DeepRedactionResult<T> {
return { value, changed: false, count: 0 };
}
clear() {
this.lastProviderRedactionCount = 0;
}
stats(): EngineStats {
return {
active: true,
builtInRuleCount: 0,
customRegexCount: this.settings.regex.length,
regexWarningCount: 0,
warningCount: this.warnings.length,
invalidRegexCount: 0,
learnedCount: 0,
mappingCount: 0,
lastProviderRedactionCount: this.lastProviderRedactionCount,
totalProviderRedactionCount: this.totalProviderRedactionCount,
recentLabels: [],
latestTags: [],
warnings: [...this.warnings],
};
}
private warnOnce(code: string, message: string) {
if (this.warningKeys.has(code)) return;
this.warningKeys.add(code);
this.warnings.push({ code, message, severity: "warning" });
}
}