repositories / pi-ext

pi-ext

bugabingas pi extensions

owned by bugabinga

extensions/leaks/src/settings.ts

Raw
import { isPlainObject } from "./safety.ts";
import type {
	CustomRegexInput,
	LeaksSettings,
	SecretSpan,
	WarningRecord,
} from "./types.ts";

export type LoadedSettings = {
	settings: LeaksSettings;
	warnings: WarningRecord[];
};

export type CompiledCustomRule = {
	pattern: string;
	regex: RegExp;
	label: string;
	captureGroup: number;
};

export type CompiledCustomRegex = {
	rules: CompiledCustomRule[];
	warnings: WarningRecord[];
	invalidRegexCount: number;
};

const LABEL_RE = /^[A-Z0-9_]{1,64}$/;

export function loadLeaksSettings(raw: unknown): LoadedSettings {
	const warnings: WarningRecord[] = [];
	const leaks = isPlainObject(raw) && isPlainObject(raw.leaks) ? raw.leaks : {};
	const input = Array.isArray(leaks.regex) ? leaks.regex : [];
	const regex: CustomRegexInput[] = [];
	for (const entry of input) {
		if (!isPlainObject(entry)) continue;
		const unsupported = Object.keys(entry).filter(
			(key) => key !== "pattern" && key !== "label" && key !== "flags",
		);
		if (unsupported.length > 0)
			warnings.push(
				warn(
					"settings.regex.unsupported-field",
					"unsupported regex setting fields ignored",
				),
			);
		if ("flags" in entry)
			warnings.push(
				warn(
					"settings.regex.flags",
					"regex flags are not supported and were ignored",
				),
			);
		regex.push({ pattern: entry.pattern, label: entry.label });
	}
	return { settings: { regex }, warnings };
}

export function compileCustomRegex(
	settings: LeaksSettings,
): CompiledCustomRegex {
	const rules: CompiledCustomRule[] = [];
	const warnings: WarningRecord[] = [];
	let invalidRegexCount = 0;
	for (const entry of settings.regex) {
		if (typeof entry.pattern !== "string" || entry.pattern.length === 0) {
			warnings.push(
				warn("settings.regex.missing-pattern", "custom regex pattern missing"),
			);
			invalidRegexCount++;
			continue;
		}
		if (entry.pattern.length > 512) {
			warnings.push(
				warn(
					"settings.regex.pattern-too-long",
					"custom regex pattern too long",
				),
			);
			invalidRegexCount++;
			continue;
		}
		if (isUnsafeRegex(entry.pattern)) {
			warnings.push(
				warn("settings.regex.unsafe", "custom regex rejected by safety checks"),
			);
			invalidRegexCount++;
			continue;
		}

		let label = "CUSTOM_REGEX";
		if (typeof entry.label !== "string" || entry.label.length === 0) {
			warnings.push(
				warn(
					"settings.regex.missing-label",
					"custom regex label missing; using CUSTOM_REGEX",
				),
			);
		} else if (!LABEL_RE.test(entry.label)) {
			warnings.push(
				warn(
					"settings.regex.invalid-label",
					"custom regex label invalid; using CUSTOM_REGEX",
				),
			);
		} else {
			label = entry.label;
		}

		const captures = countCaptures(entry.pattern);
		if (captures > 1)
			warnings.push(
				warn(
					"settings.regex.multiple-captures",
					"custom regex has multiple captures; using group 1",
				),
			);

		try {
			rules.push({
				pattern: entry.pattern,
				regex: new RegExp(entry.pattern, "dg"),
				label,
				captureGroup: captures === 0 ? 0 : 1,
			});
		} catch {
			warnings.push(
				warn("settings.regex.syntax", "custom regex syntax invalid"),
			);
			invalidRegexCount++;
		}
	}
	return { rules, warnings, invalidRegexCount };
}

export function customRegexSpans(
	text: string,
	rules: CompiledCustomRule[],
): SecretSpan[] {
	const spans: SecretSpan[] = [];
	for (const rule of rules) {
		rule.regex.lastIndex = 0;
		let match = rule.regex.exec(text);
		while (match) {
			const range = match.indices?.[rule.captureGroup];
			const value = match[rule.captureGroup];
			if (range && typeof value === "string" && value.length > 0) {
				spans.push({
					start: range[0],
					end: range[1],
					value,
					labels: [{ tag: rule.label, priority: 30, source: "custom" }],
					kind: "custom",
					confidence: 80,
					wholeSpan: false,
				});
			}
			if (match[0] === "") rule.regex.lastIndex++;
			match = rule.regex.exec(text);
		}
	}
	return spans;
}

export function countCaptures(pattern: string): number {
	let count = 0;
	for (let index = 0; index < pattern.length; index++) {
		if (pattern[index] !== "(" || escaped(pattern, index)) continue;
		if (pattern[index + 1] === "?") continue;
		count++;
	}
	return count;
}

export function isUnsafeRegex(pattern: string): boolean {
	if (/\\[1-9]/.test(pattern)) return true;
	if (/\(\?<[^=!]|\(\?[=!<]/.test(pattern)) return true;
	if (/\([^)]*[+*][^)]*\)[+*{]/.test(pattern)) return true;
	if (/\([^)]*\|[^)]*\)[+*{]/.test(pattern)) return true;
	if (/(^|\()\||\|(\)|$)/.test(pattern)) return true;
	if (/\.\*/.test(pattern)) return true;
	return false;
}

function escaped(text: string, index: number) {
	let count = 0;
	for (let pos = index - 1; pos >= 0 && text[pos] === "\\"; pos--) count++;
	return count % 2 === 1;
}

function warn(code: string, message: string): WarningRecord {
	return { code, message, severity: "warning" };
}