repositories / pi-ext

pi-ext

bugabingas pi extensions

owned by bugabinga

extensions/leaks/src/structures.ts

Raw
File outline
import { highConfidenceSecretShape, isSensitiveKey } from "./dotenv.ts";
import { isWeakValue } from "./safety.ts";
import type { SecretSpan, SpanLabel } from "./types.ts";

const URL_CREDENTIAL_RE =
	/\b[a-z][a-z0-9+.-]*:\/\/([^\s:@/]*)?:([^\s@/]+)@[^\s]+/dgi;
const QUERY_RE =
	/([?&])([A-Za-z0-9_-]*(?:token|key|secret|password|auth)[A-Za-z0-9_-]*)=([^&#\s'"`]+)/dgi;
const AUTH_RE = /Authorization:\s*(Bearer|Basic)\s+([^\s'"`]+)/dgi;
const X_API_RE = /\b(X-API-Key|X-Api-Key|Api-Key):\s*([^\s'"`]+)/dg;
const COOKIE_LINE_RE = /Cookie:\s*([^\n]+)/dgi;
// Keys that look like assignments but are common programming nouns, not secrets.
// Scoped to findAssignmentSpans only — does NOT affect dotenv/env learning
// or structure non-assignment detectors. Excludes any key in dotenv.SENSITIVE
// (TOKEN, KEY, SECRET, …) since those remain real secret indicators. 'seed' is
// the lone SENSITIVE key in this list: it dominates as a programming term in
// tool-arg JSON, and users with real SEED secrets can use a custom regex.
const ASSIGNMENT_STOP_KEYS = new Set([
	"seed",
	"id",
	"name",
	"count",
	"type",
	"value",
	"path",
	"ts",
	"time",
	"date",
	"idx",
	"mode",
	"flag",
	"opts",
	"params",
	"args",
	"options",
	"label",
	"field",
	"tag",
	"node",
	"host",
	"port",
	"version",
]);

const ASSIGN_RE =
	/(?:^|[\n\r\s{,;])(?:export\s+)?["']?([A-Za-z_][A-Za-z0-9_-]*)["']?\s*(?:=|:|=>)\s*["']?([^\s'",;}]{1,512})["']?/dgi;
const XML_RE = /<([A-Za-z_][A-Za-z0-9_-]*)>([^<]{1,512})<\/\1>/dgi;
const JWT_RE =
	/\b[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{8,}\b/dg;
const PRIVATE_KEY_RE =
	/-----BEGIN ([A-Z0-9 ]*PRIVATE KEY)-----[\s\S]*?-----END \1-----/dg;

export const structureRegexFuzzTargets = [
	["url-credential", URL_CREDENTIAL_RE],
	["query", QUERY_RE],
	["auth-header", AUTH_RE],
	["api-header", X_API_RE],
	["cookie-line", COOKIE_LINE_RE],
	["assignment", ASSIGN_RE],
	["xml", XML_RE],
	["jwt", JWT_RE],
	["private-key", PRIVATE_KEY_RE],
].map(([name, regex]) => ({
	name: `structure:${name}`,
	regex: regex as RegExp,
}));

export function findStructureSpans(text: string): SecretSpan[] {
	return [
		...findPrivateKeySpans(text),
		...findJwtSpans(text),
		...findCredentialedUrlSpans(text),
		...findSensitiveQuerySpans(text),
		...findHeaderSpans(text),
		...findCookieSpans(text),
		...findAssignmentSpans(text),
	];
}

export function findCredentialedUrlSpans(text: string): SecretSpan[] {
	return matches(URL_CREDENTIAL_RE, text, 2, "DB_PASSWORD");
}

export function findSensitiveQuerySpans(text: string): SecretSpan[] {
	const spans: SecretSpan[] = [];
	for (const match of text.matchAll(QUERY_RE)) {
		const value = match[3] as string;
		if (isWeakValue(value)) continue;
		spans.push(
			makeSpan(
				match,
				3,
				value,
				[label(match[2] as string, "structure")],
				"structure",
			),
		);
	}
	return spans;
}

export function findHeaderSpans(text: string): SecretSpan[] {
	return [
		...matches(
			AUTH_RE,
			text,
			2,
			"AUTHORIZATION",
			(match) => `AUTHORIZATION_${match[1]?.toUpperCase()}`,
		),
		...matches(X_API_RE, text, 2, "X_API_KEY"),
	];
}

export function findCookieSpans(text: string): SecretSpan[] {
	const spans: SecretSpan[] = [];
	for (const line of text.matchAll(COOKIE_LINE_RE)) {
		const body = line[1] as string;
		let offset = (line.indices?.[1] as [number, number])[0];
		for (const part of body.split(";")) {
			const trimmed = part.trim();
			const eq = trimmed.indexOf("=");
			if (eq === -1) {
				offset += part.length + 1;
				continue;
			}
			const name = trimmed.slice(0, eq);
			const value = trimmed.slice(eq + 1);
			const localStart = part.indexOf(value);
			if (isSensitiveCookie(name) && !isWeakValue(value)) {
				const start = offset + Math.max(localStart, 0);
				spans.push({
					start,
					end: start + value.length,
					value,
					labels: [label(`COOKIE_${name}`, "structure")],
					kind: "structure",
					confidence: 85,
					wholeSpan: false,
				});
			}
			offset += part.length + 1;
		}
	}
	return spans;
}

export function findAssignmentSpans(text: string): SecretSpan[] {
	const spans: SecretSpan[] = [];
	for (const regex of [ASSIGN_RE, XML_RE]) {
		regex.lastIndex = 0;
		for (const match of text.matchAll(regex)) {
			const key = match[1] as string;
			const value = match[2] as string;
			if (ASSIGNMENT_STOP_KEYS.has(key.toLowerCase())) continue;
			if (!isSensitiveKey(key)) continue;
			if (isCodeReference(value)) continue;
			if (isWeakValue(value) && !highConfidenceSecretShape(value)) continue;
			spans.push(
				makeSpan(match, 2, value, [label(key, "structure")], "structure"),
			);
		}
	}
	return spans;
}

export function findJwtSpans(text: string): SecretSpan[] {
	return [...text.matchAll(JWT_RE)].map((match) => {
		const start = match.index as number;
		return {
			start,
			end: start + match[0].length,
			value: match[0],
			labels: [label("JWT", "builtin")],
			kind: "jwt",
			confidence: 100,
			wholeSpan: true,
		};
	});
}

export function findPrivateKeySpans(text: string): SecretSpan[] {
	return [...text.matchAll(PRIVATE_KEY_RE)].map((match) => {
		const start = match.index as number;
		const keyType = match[1] as string;
		return {
			start,
			end: start + match[0].length,
			value: match[0],
			labels: [label(keyType.replace(/ /g, "_"), "builtin")],
			kind: "private-key",
			confidence: 100,
			wholeSpan: true,
		};
	});
}

function isCodeReference(value: string) {
	const text = value.trim();
	return (
		text.startsWith("$") ||
		/[()[\]{}]/.test(text) ||
		/^[A-Z][A-Za-z0-9_$]*$/.test(text) ||
		/^(?:[A-Za-z_$][A-Za-z0-9_$]*\.)+[A-Za-z_$][A-Za-z0-9_$]*$/.test(text)
	);
}

function matches(
	regex: RegExp,
	text: string,
	group: number,
	fallback: string,
	tag?: (match: RegExpMatchArray) => string,
): SecretSpan[] {
	regex.lastIndex = 0;
	const spans: SecretSpan[] = [];
	for (const match of text.matchAll(regex)) {
		const value = match[group] as string;
		if (isWeakValue(value)) continue;
		spans.push(
			makeSpan(
				match,
				group,
				value,
				[label(tag ? tag(match) : fallback, "structure")],
				"structure",
			),
		);
	}
	return spans;
}

function makeSpan(
	match: RegExpMatchArray,
	group: number,
	value: string,
	labels: SpanLabel[],
	kind: SecretSpan["kind"],
): SecretSpan {
	const range = match.indices?.[group] as [number, number];
	const start = range[0];
	return {
		start,
		end: range[1],
		value,
		labels,
		kind,
		confidence: 85,
		wholeSpan: false,
	};
}

function label(tag: string, source: SpanLabel["source"]): SpanLabel {
	return { tag, priority: source === "builtin" ? 40 : 20, source };
}

function isSensitiveCookie(name: string) {
	return /(?:session|token|auth|secret|key|jwt)/i.test(name);
}