repositories / pi-ext

pi-ext

bugabingas pi extensions

owned by bugabinga

extensions/leaks/src/placeholders.ts

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

const CAP = 8192;
const GENERATION_TYPE = "leaks-generation-v1";
const MAPPING_TYPE = "leaks-mapping-v1";
const PLACEHOLDER_RE = new RegExp(V1_PLACEHOLDER_SOURCE, "g");
const EXACT_PLACEHOLDER_RE = new RegExp(`^(?:${V1_PLACEHOLDER_SOURCE})$`);
export const ANY_PLACEHOLDER_RE = new RegExp(ANY_PLACEHOLDER_SOURCE, "g");
const SOURCE_RANK: Record<SpanLabel["source"], number> = {
	dotenv: 0,
	env: 0,
	structure: 1,
	custom: 2,
	builtin: 3,
	generic: 4,
};

export type GenerationRecord = {
	version: 1;
	generationId: string;
	rootKey: string;
};

export type MappingRecord = {
	version: 1;
	generationId: string;
	placeholder: string;
	nonce: string;
	ciphertext: string;
	authTag: string;
};

export type PersistedEntry = {
	type: "custom";
	customType: string;
	data?: unknown;
};

type AppendEntry = (customType: string, data: unknown) => void;

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

export class PlaceholderStore {
	private readonly digestOverride?: (value: string) => string;
	private readonly onWarning?: (warning: WarningRecord) => void;
	private readonly cap: number;
	private append?: AppendEntry;
	private generation?: GenerationRecord;
	private hmacKey?: Buffer;
	private encryptionKey?: Buffer;
	private readonly secretToPlaceholder = new Map<string, string>();
	private readonly placeholderToSecret = new Map<string, string>();
	private warnedCap = false;
	private enabled = true;
	private lastMiss?: string;

	constructor(options: PlaceholderStoreOptions = {}) {
		this.digestOverride = options.digest;
		this.onWarning = options.onWarning;
		this.cap = options.cap ?? CAP;
		if (options.append) this.configure([], options.append);
	}

	configure(entries: PersistedEntry[], append: AppendEntry) {
		this.append = append;
		this.reset();
		let generationIndex = -1;
		for (let index = 0; index < entries.length; index++)
			if (entries[index].customType === GENERATION_TYPE)
				generationIndex = index;
		if (generationIndex < 0) {
			if (
				entries.some((entry) =>
					entry.customType.startsWith("leaks-generation-"),
				)
			)
				this.disable("unsupported leaks generation version");
			else if (
				entries.some((entry) => entry.customType.startsWith("leaks-mapping-"))
			)
				this.disable("mapping record has no generation");
			return;
		}
		const generation = parseGeneration(entries[generationIndex].data);
		if (!generation) {
			this.disable("invalid leaks generation record");
			return;
		}
		this.activate(generation);
		for (const entry of entries.slice(generationIndex + 1)) {
			if (entry.customType.startsWith("leaks-generation-")) {
				this.disable("unsupported leaks generation version");
				continue;
			}
			if (
				entry.customType.startsWith("leaks-mapping-") &&
				entry.customType !== MAPPING_TYPE
			) {
				this.disable("unsupported leaks mapping version");
				continue;
			}
			if (entry.customType !== MAPPING_TYPE) continue;
			const record = parseMapping(entry.data);
			if (!record || record.generationId !== generation.generationId) {
				this.disable("invalid leaks mapping record");
				continue;
			}
			const value = this.decrypt(record);
			if (value === undefined) {
				this.disable("leaks mapping authentication failed");
				continue;
			}
			const existing = this.placeholderToSecret.get(record.placeholder);
			const reverse = this.secretToPlaceholder.get(value);
			if (existing === value && reverse === record.placeholder) continue;
			if (
				(existing !== undefined && existing !== value) ||
				(reverse !== undefined && reverse !== record.placeholder)
			) {
				this.disable("conflicting leaks mapping record");
				continue;
			}
			if (this.placeholderToSecret.size >= this.cap) {
				this.disable("persisted mapping cap exceeded");
				continue;
			}
			this.placeholderToSecret.set(record.placeholder, value);
			this.secretToPlaceholder.set(value, record.placeholder);
		}
	}

	create(value: string, labels: SpanLabel[]): string | undefined {
		this.lastMiss = undefined;
		const known = this.secretToPlaceholder.get(value);
		if (known) return known;
		if (this.enabled && (!this.generation || !this.encryptionKey))
			this.startGeneration();
		if (!this.enabled || !this.generation || !this.encryptionKey) {
			this.lastMiss = "PERSISTENCE_DISABLED";
			return undefined;
		}
		if (this.secretToPlaceholder.size >= this.cap) {
			this.lastMiss = "MAPPING_CAP";
			this.warnCap();
			return undefined;
		}
		const placeholder = this.format(value, labels);
		const collision = this.placeholderToSecret.get(placeholder);
		if (collision !== undefined && collision !== value) {
			this.lastMiss = "PLACEHOLDER_COLLISION";
			this.warn(
				"placeholder.collision",
				"placeholder collision; value left visible",
			);
			return undefined;
		}
		try {
			const record = this.encrypt(placeholder, value);
			if (!this.append) throw new Error("missing persistence sink");
			this.append(MAPPING_TYPE, record);
		} catch {
			this.lastMiss = "PERSISTENCE_FAILURE";
			this.disable("mapping persistence failed");
			return undefined;
		}
		this.secretToPlaceholder.set(value, placeholder);
		this.placeholderToSecret.set(placeholder, value);
		return placeholder;
	}

	restore(text: string): string {
		let current = text;
		const seen = new Set<string>();
		for (let pass = 0; pass <= this.placeholderToSecret.size; pass++) {
			if (seen.has(current)) return current;
			seen.add(current);
			const next = current.replace(
				PLACEHOLDER_RE,
				(placeholder) =>
					this.placeholderToSecret.get(placeholder) ?? placeholder,
			);
			if (next === current) return current;
			current = next;
		}
		return current;
	}

	takeMiss() {
		const miss = this.lastMiss;
		this.lastMiss = undefined;
		return miss;
	}

	unresolved(text: string) {
		return [...text.matchAll(ANY_PLACEHOLDER_RE)].map((match) => match[0]);
	}

	clear() {
		const generation = newGeneration();
		try {
			if (!this.append) throw new Error("missing persistence sink");
			this.append(GENERATION_TYPE, generation);
			this.reset();
			this.activate(generation);
			return true;
		} catch {
			this.disable("generation persistence failed; mappings kept active");
			return false;
		}
	}

	taint(message = "persistence previously failed") {
		this.disable(message);
	}

	stats() {
		return {
			mappingCount: this.secretToPlaceholder.size,
			generationId: this.generation?.generationId,
			persistenceEnabled: this.enabled,
		};
	}

	private startGeneration() {
		const generation = newGeneration();
		try {
			if (!this.append) throw new Error("missing persistence sink");
			this.append(GENERATION_TYPE, generation);
			this.activate(generation);
		} catch {
			this.disable("generation persistence failed");
		}
	}

	private activate(generation: GenerationRecord) {
		const root = Buffer.from(generation.rootKey, "base64url");
		this.generation = generation;
		this.hmacKey = derive(root, "leaks-placeholder-hmac-v1");
		this.encryptionKey = derive(root, "leaks-mapping-encryption-v1");
	}

	private reset() {
		this.generation = undefined;
		this.hmacKey = undefined;
		this.encryptionKey = undefined;
		this.secretToPlaceholder.clear();
		this.placeholderToSecret.clear();
		this.warnedCap = false;
		this.enabled = true;
		this.lastMiss = undefined;
	}

	private format(value: string, labels: SpanLabel[]) {
		const tags = labels
			.toSorted((left, right) => {
				const rank = SOURCE_RANK[left.source] - SOURCE_RANK[right.source];
				return rank || left.priority - right.priority;
			})
			.map((item) => sanitizeTag(item.tag))
			.filter((tag, index, all) => tag && all.indexOf(tag) === index)
			.slice(0, 6);
		const tagText = tags.length > 0 ? tags.join("_") : "SECRET";
		const digest =
			this.digestOverride?.(value) ??
			createHmac("sha256", this.hmacKey as Buffer)
				.update(encodeValue(value))
				.digest("hex");
		const hmac32 = digest
			.toLowerCase()
			.replace(/[^a-f0-9]/g, "0")
			.slice(0, 32)
			.padEnd(32, "0");
		return `__LEAK_V1_${tagText}_${hmac32}__`;
	}

	private encrypt(placeholder: string, value: string): MappingRecord {
		const generation = this.generation as GenerationRecord;
		const nonce = randomBytes(12);
		const cipher = createCipheriv(
			"aes-256-gcm",
			this.encryptionKey as Buffer,
			nonce,
			{ authTagLength: 16 },
		);
		cipher.setAAD(aad(generation.generationId, placeholder));
		const ciphertext = Buffer.concat([
			cipher.update(encodeValue(value)),
			cipher.final(),
		]);
		return {
			version: 1,
			generationId: generation.generationId,
			placeholder,
			nonce: nonce.toString("base64url"),
			ciphertext: ciphertext.toString("base64url"),
			authTag: cipher.getAuthTag().toString("base64url"),
		};
	}

	private decrypt(record: MappingRecord) {
		try {
			const decipher = createDecipheriv(
				"aes-256-gcm",
				this.encryptionKey as Buffer,
				Buffer.from(record.nonce, "base64url"),
				{ authTagLength: 16 },
			);
			decipher.setAAD(aad(record.generationId, record.placeholder));
			decipher.setAuthTag(Buffer.from(record.authTag, "base64url"));
			const bytes = Buffer.concat([
				decipher.update(Buffer.from(record.ciphertext, "base64url")),
				decipher.final(),
			]);
			if (bytes.length % 2 !== 0) return undefined;
			return bytes.toString("utf16le");
		} catch {
			return undefined;
		}
	}

	private disable(message: string) {
		this.enabled = false;
		this.warn("placeholder.state", `${message}; new redaction disabled`);
	}

	private warnCap() {
		if (this.warnedCap) return;
		this.warnedCap = true;
		this.warn(
			"placeholder.cap",
			"placeholder mapping cap reached; value left visible",
		);
	}

	private warn(code: string, message: string) {
		this.onWarning?.({ code, message, severity: "warning" });
	}
}

function encodeValue(value: string) {
	return Buffer.from(value, "utf16le");
}

function newGeneration(): GenerationRecord {
	return {
		version: 1,
		generationId: randomBytes(16).toString("hex"),
		rootKey: randomBytes(32).toString("base64url"),
	};
}

function derive(root: Buffer, info: string) {
	return Buffer.from(hkdfSync("sha256", root, Buffer.alloc(0), info, 32));
}

function aad(generationId: string, placeholder: string) {
	return Buffer.from(`1\0${generationId}\0${placeholder}`);
}

function parseGeneration(data: unknown): GenerationRecord | undefined {
	if (!isRecord(data) || data.version !== 1) return undefined;
	if (
		typeof data.generationId !== "string" ||
		!/^[a-f0-9]{32}$/.test(data.generationId)
	)
		return undefined;
	if (typeof data.rootKey !== "string" || !canonicalBase64Url(data.rootKey, 32))
		return undefined;
	return data as GenerationRecord;
}

function parseMapping(data: unknown): MappingRecord | undefined {
	if (!isRecord(data) || data.version !== 1) return undefined;
	for (const key of [
		"generationId",
		"placeholder",
		"nonce",
		"ciphertext",
		"authTag",
	])
		if (typeof data[key] !== "string") return undefined;
	if (!EXACT_PLACEHOLDER_RE.test(data.placeholder as string)) return undefined;
	if (!/^[a-f0-9]{32}$/.test(data.generationId as string)) return undefined;
	if (!canonicalBase64Url(data.nonce as string, 12)) return undefined;
	if (!canonicalBase64Url(data.authTag as string, 16)) return undefined;
	if (!canonicalBase64Url(data.ciphertext as string)) return undefined;
	return data as MappingRecord;
}

function canonicalBase64Url(value: string, length?: number) {
	if (!/^[A-Za-z0-9_-]*$/.test(value)) return false;
	const decoded = Buffer.from(value, "base64url");
	return (
		(length === undefined || decoded.length === length) &&
		decoded.toString("base64url") === value
	);
}

function isRecord(value: unknown): value is Record<string, unknown> {
	return value !== null && typeof value === "object" && !Array.isArray(value);
}