repositories / pi-ext
pi-ext
bugabingas pi extensions
owned by bugabinga
extensions/leaks/src/engine.ts
RawFile outline
- LeaksEngineOptions line 28
- LeaksEngine line 34
- settings line 35
- detectors line 36
- warnings line 37
- warningKeys line 38
- placeholders line 39
- customRules line 42
- invalidRegexCount line 43
- learned line 44
- lastProviderRedactionCount line 45
- totalProviderRedactionCount line 46
- recentLabels line 47
- latestTags line 48
- constructor line 50
- reload line 57
- redactText line 63
- redactDeep line 113
- restoreText line 120
- restoreDeep line 124
- clear line 128
- stats line 135
- compileSettings line 155
- learn line 162
- walk line 170
- visit line 178
- warnOnce line 223
- addWarning line 229
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,
RedactionResult,
SecretSpan,
WarningRecord,
} from "./types.ts";
export type LeaksEngineOptions = {
settings?: Partial<LeaksSettings>;
env?: Record<string, string | undefined>;
detectors?: Detector[];
};
export class LeaksEngine {
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 customRules: CompiledCustomRule[] = [];
private invalidRegexCount = 0;
private learned: LearnedValue[] = [];
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 ?? [];
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);
}
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: [] };
}
}
const selected = selectSecretSpans(text, spans);
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> {
return this.walk(value, origin, false);
}
restoreText(text: string) {
return this.placeholders.restore(text);
}
restoreDeep<T>(value: T): DeepRedactionResult<T> {
return this.walk(value, "provider", true);
}
clear() {
this.placeholders.clear();
this.lastProviderRedactionCount = 0;
this.recentLabels = [];
this.latestTags = [];
}
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<string, string | undefined>) {
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<T>(
input: T,
origin: RedactionOrigin,
restore: boolean,
): DeepRedactionResult<T> {
const seen = new WeakMap<object, unknown>();
let count = 0;
let changed = false;
const visit = (value: unknown, depth: number): 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;
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 (const item of value) copy.push(visit(item, depth + 1));
if (copy.some((item, index) => item !== value[index])) changed = true;
return copy;
}
if (!isPlainObject(value)) return value;
const source = value as Record<string, unknown>;
const copy: Record<string, unknown> = {};
seen.set(value, copy);
for (const [key, item] of Object.entries(source))
copy[key] = visit(item, depth + 1);
if (Object.keys(copy).some((key) => copy[key] !== source[key]))
changed = true;
return copy;
};
return { value: visit(input, 0) as T, changed, count };
}
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);
}
}