repositories / pi-ext

pi-ext

bugabingas pi extensions

owned by bugabinga

extensions/leaks/src/safety.ts

Raw
File outline
export const V1_PLACEHOLDER_SOURCE =
	"__LEAK_V1_[A-Z0-9_]{1,389}_[a-f0-9]{32}__";
export const ANY_PLACEHOLDER_SOURCE =
	"__LEAK_(?:V1_[A-Z0-9_]{1,389}_[a-f0-9]{32}|[A-Z0-9_]{0,390}[a-f0-9]{12}(?:_\\d+)?)__";
const PLACEHOLDER_RE = new RegExp(`^(?:${ANY_PLACEHOLDER_SOURCE})$`);

export function isPlainObject(
	value: unknown,
): value is Record<string, unknown> {
	if (value === null || typeof value !== "object") return false;
	const prototype = Object.getPrototypeOf(value);
	return prototype === Object.prototype || prototype === null;
}

export function sanitizeTag(raw: string): string {
	const tag = raw
		.toUpperCase()
		.replace(/[^A-Z0-9]+/g, "_")
		.replace(/^_+|_+$/g, "")
		.slice(0, 64);
	return tag || "SECRET";
}

export function isExistingPlaceholder(text: string): boolean {
	return PLACEHOLDER_RE.test(text);
}

export function maskDiagnostic(input: string): string {
	const chars = [...input].length;
	const lines = input.length === 0 ? 0 : input.split(/\r?\n/).length;
	return `text chars=${chars} lines=${lines}`;
}

export function isWeakValue(value: string): boolean {
	const text = value.trim();
	if (text.length < 8) return true;
	if (/^(?:true|false|null|nil|none|undefined|yes|no|on|off)$/i.test(text)) {
		return true;
	}
	if (/^[+-]?\d+(?:\.\d+)?$/.test(text)) return true;
	if (/^\$\{?[A-Z_][A-Z0-9_]*\}?$/i.test(text)) return true;
	if (/^\$\{\{\s*secrets\.[A-Z0-9_]+\s*\}\}$/i.test(text)) return true;
	if (/^process\.env\.[A-Z_][A-Z0-9_]*$/i.test(text)) return true;
	if (
		/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(
			text,
		)
	) {
		return true;
	}
	if (/^(?:[a-z0-9-]+\.)+[a-z]{2,}$/i.test(text)) return true;
	try {
		const url = new URL(text);
		if (
			!url.password &&
			!/[?&](?:token|key|secret|password|auth)=/i.test(url.search)
		) {
			return true;
		}
	} catch {}
	if (/^(?:\.\/|\.\.\/|\/|~\/)[^\s]+$/.test(text)) return true;
	return false;
}