repositories / pi-ext

pi-ext

bugabingas pi extensions

owned by bugabinga

extensions/leaks/src/dotenv.ts

Raw
File outline
import { existsSync, readdirSync, readFileSync } from "node:fs";
import path from "node:path";
import { isWeakValue, sanitizeTag } from "./safety.ts";
import type { SecretSpan, SpanLabel, WarningRecord } from "./types.ts";

const CAP = 8192;
const PUBLIC_PREFIX_RE = /^(?:PUBLIC|NEXT_PUBLIC|VITE)[_-]/i;
const SENSITIVE = new Set([
	"TOKEN",
	"SECRET",
	"PASSWORD",
	"PASSWD",
	"PASS",
	"PEPPER",
	"API_KEY",
	"ACCESS_KEY",
	"PRIVATE_KEY",
	"KEY",
	"KEY_DATA",
	"PAT",
	"PASSPHRASE",
	"LICENSE_KEY",
	"MASTER_KEY",
	"ROUTING_KEY",
	"ENCRYPTION_KEY",
	"SECRET_KEY_BASE",
	"SEED",
	"UNSEAL_KEY",
	"MNEMONIC",
	"CLIENT_SECRET",
	"AUTH",
	"CREDENTIAL",
	"SESSION",
	"COOKIE",
	"JWT",
	"DATABASE_URL",
	"MONGO_URL",
	"REDIS_URL",
]);

export type LearnedValue = {
	value: string;
	labels: SpanLabel[];
};

export type LearnedValues = {
	values: LearnedValue[];
	warnings: WarningRecord[];
};

export function discoverDotenvFiles(cwd: string): string[] {
	const direct = [".env", ".env.local"]
		.map((file) => path.join(cwd, file))
		.filter((file) => existsSync(file));
	const local = readdirSync(cwd, { withFileTypes: true })
		.filter((entry) => entry.isFile())
		.map((entry) => entry.name)
		.filter((name) => /^\.env\..+\.local$/.test(name))
		.sort()
		.map((file) => path.join(cwd, file));
	return [...direct, ...local];
}

export function parseDotenv(
	text: string,
): Array<{ key: string; value: string }> {
	const rows: Array<{ key: string; value: string }> = [];
	for (const raw of text.split(/\r?\n/)) {
		let line = raw.trim();
		if (!line || line.startsWith("#")) continue;
		line = line.replace(/^export\s+/, "");
		const match = /^([A-Za-z_][A-Za-z0-9_-]*)\s*=\s*(.*)$/.exec(line);
		if (!match) continue;
		let value = match[2] as string;
		if (
			(value.startsWith("'") && value.includes("'", 1)) ||
			(value.startsWith('"') && value.includes('"', 1))
		) {
			const quote = value[0];
			const end = value.indexOf(quote, 1);
			value = value.slice(1, end);
		} else {
			value = value.replace(/\s+#.*$/, "").trim();
		}
		rows.push({ key: match[1], value });
	}
	return rows;
}

export function loadDotenvValues(cwd: string): LearnedValues {
	const pairs: Record<string, string> = {};
	for (const file of discoverDotenvFiles(cwd)) {
		for (const item of parseDotenv(readFileSync(file, "utf8")))
			pairs[item.key] = item.value;
	}
	return learnKeyValues(pairs, "dotenv");
}

export function learnEnvironmentValues(
	env: Record<string, string | undefined>,
	cap = CAP,
): LearnedValues {
	const pairs: Record<string, string> = {};
	for (const [key, value] of Object.entries(env))
		if (typeof value === "string") pairs[key] = value;
	return learnKeyValues(pairs, "env", cap);
}

export function isSensitiveKey(key: string): boolean {
	const normalized = normalizeKey(key.replace(PUBLIC_PREFIX_RE, ""));
	if (SENSITIVE.has(normalized)) return true;
	return [...SENSITIVE].some(
		(sensitive) =>
			normalized.endsWith(`_${sensitive}`) ||
			normalized.startsWith(`${sensitive}_`),
	);
}

export function highConfidenceSecretShape(value: string): boolean {
	return /^(?:sk-or-v1-[A-Za-z0-9]{32,}|sk-proj-[A-Za-z0-9_-]{32,}|sk-ant-api03-[A-Za-z0-9_-]{32,}|ghp_[A-Za-z0-9]{36}|hf_[A-Za-z0-9]{32,})$/.test(
		value,
	);
}

export function learnedValueSpans(
	text: string,
	values: LearnedValue[],
): SecretSpan[] {
	const spans: SecretSpan[] = [];
	for (const learned of values) {
		let start = text.indexOf(learned.value);
		while (start !== -1) {
			spans.push({
				start,
				end: start + learned.value.length,
				value: learned.value,
				labels: learned.labels,
				kind: "exact",
				confidence: 70,
				wholeSpan: false,
			});
			start = text.indexOf(learned.value, start + learned.value.length);
		}
	}
	return spans;
}

function learnKeyValues(
	pairs: Record<string, string>,
	source: "dotenv" | "env",
	cap = CAP,
): LearnedValues {
	const values: LearnedValue[] = [];
	const warnings: WarningRecord[] = [];
	let warned = false;
	for (const [key, value] of Object.entries(pairs)) {
		if (values.length >= cap) {
			if (!warned) {
				warnings.push({
					code: "learned.cap",
					message:
						"learned value cap reached; further dotenv/env values ignored",
					severity: "warning",
				});
				warned = true;
			}
			continue;
		}
		const publicPrefixed = PUBLIC_PREFIX_RE.test(key);
		const secretShape = highConfidenceSecretShape(value);
		if (
			(!publicPrefixed && isSensitiveKey(key) && !isWeakValue(value)) ||
			secretShape
		) {
			values.push({
				value,
				labels: [
					{
						tag: source === "env" ? "ENV_KEY" : sanitizeTag(key),
						priority: 10,
						source,
					},
				],
			});
		}
	}
	return { values, warnings };
}

function normalizeKey(key: string) {
	return key.toUpperCase().replace(/[-]+/g, "_").replace(/_\d+$/, "");
}