repositories / pi-ext

pi-ext

bugabingas pi extensions

owned by bugabinga

extensions/leaks/src/placeholders.ts

Raw
File outline
import { createHmac, randomBytes } from "node:crypto";
import { sanitizeTag } from "./safety.ts";
import type { SpanLabel, WarningRecord } from "./types.ts";

const CAP = 8192;
const PLACEHOLDER_RE = /__LEAK(?:_[A-Z0-9]{1,64})*_[a-f0-9]{12}(?:_\d+)?__/g;
const SOURCE_RANK: Record<SpanLabel["source"], number> = {
	dotenv: 0,
	env: 0,
	structure: 1,
	custom: 2,
	builtin: 3,
	generic: 4,
};

type PlaceholderStoreOptions = {
	digest?: (value: string) => string;
	onWarning?: (warning: WarningRecord) => void;
	cap?: number;
};

export class PlaceholderStore {
	private readonly key = randomBytes(32);
	private readonly digestOverride?: (value: string) => string;
	private readonly onWarning?: (warning: WarningRecord) => void;
	private readonly cap: number;
	private readonly secretToPlaceholder = new Map<string, string>();
	private readonly placeholderToSecret = new Map<string, string>();
	private readonly overflowPlaceholders = new Set<string>();
	private warnedCap = false;
	private overflowNonce = 1;

	constructor(options: PlaceholderStoreOptions = {}) {
		this.digestOverride = options.digest;
		this.onWarning = options.onWarning;
		this.cap = options.cap ?? CAP;
	}

	create(value: string, labels: SpanLabel[]): string {
		const known = this.secretToPlaceholder.get(value);
		if (known) return known;

		const base = this.format(value, labels);
		if (this.secretToPlaceholder.size >= this.cap) {
			this.warnCap();
			return this.nonRestorable(base);
		}

		const placeholder = this.nextAvailable(base);
		this.secretToPlaceholder.set(value, placeholder);
		this.placeholderToSecret.set(placeholder, value);
		return placeholder;
	}

	restore(text: string): string {
		return text.replace(PLACEHOLDER_RE, (placeholder) => {
			return this.placeholderToSecret.get(placeholder) ?? placeholder;
		});
	}

	clear() {
		this.secretToPlaceholder.clear();
		this.placeholderToSecret.clear();
		this.overflowPlaceholders.clear();
		this.warnedCap = false;
		this.overflowNonce = 1;
	}

	stats() {
		return { mappingCount: this.secretToPlaceholder.size };
	}

	private format(value: string, labels: SpanLabel[]) {
		const tags = labels
			.toSorted((left, right) => {
				const rank = SOURCE_RANK[left.source] - SOURCE_RANK[right.source];
				if (rank !== 0) return rank;
				return left.priority - right.priority;
			})
			.map((label) => sanitizeTag(label.tag))
			.filter((tag, index, all) => all.indexOf(tag) === index)
			.slice(0, 6);
		const tagText = tags.length === 0 ? "" : `_${tags.join("_")}`;
		return `__LEAK${tagText}_${this.digest(value)}__`;
	}

	private digest(value: string) {
		const raw =
			this.digestOverride?.(value) ??
			createHmac("sha256", this.key).update(value).digest("hex");
		return raw
			.toLowerCase()
			.replace(/[^a-f0-9]/g, "0")
			.slice(0, 12)
			.padEnd(12, "0");
	}

	private nextAvailable(base: string) {
		if (!this.placeholderToSecret.has(base)) return base;
		let index = 2;
		while (true) {
			const candidate = base.replace(/__$/, `_${index}__`);
			if (!this.placeholderToSecret.has(candidate)) return candidate;
			index++;
		}
	}

	private nonRestorable(base: string) {
		let candidate = base;
		while (
			this.placeholderToSecret.has(candidate) ||
			this.overflowPlaceholders.has(candidate)
		) {
			this.overflowNonce++;
			candidate = base.replace(/__$/, `_${this.overflowNonce}__`);
		}
		this.overflowPlaceholders.add(candidate);
		this.overflowNonce++;
		return candidate;
	}

	private warnCap() {
		if (this.warnedCap) return;
		this.warnedCap = true;
		this.onWarning?.({
			code: "placeholder.cap",
			message:
				"placeholder mapping cap reached; new placeholders are not restorable",
			severity: "warning",
		});
	}
}