repositories / pi-ext

pi-ext

bugabingas pi extensions

owned by bugabinga

extensions/verboten/src/rules.ts

Raw
import { realpath, stat } from "node:fs/promises";
import { homedir } from "node:os";
import path from "node:path";
import { getAgentDir, SettingsManager } from "@earendil-works/pi-coding-agent";

export type RuleGroup =
	| "built-in static"
	| "built-in resolved"
	| "global setting"
	| "project setting";

export interface VerbotenRule {
	group: RuleGroup;
	label: string;
	pattern: string;
	regex: RegExp;
	original?: string;
}

export interface VerbotenWarning {
	key: string;
	message: string;
}

export interface LoadedVerbotenSettings {
	rules: VerbotenRule[];
	judgeModel: string | null;
	warnings: VerbotenWarning[];
	projectIgnored: boolean;
}

export interface BuiltinEnvironment {
	platform: NodeJS.Platform;
	env: NodeJS.ProcessEnv;
	home: string;
	agentDir: string;
}

const STATIC_RULES: ReadonlyArray<[label: string, pattern: string]> = [
	[
		"dotenv",
		String.raw`(?<![A-Za-z0-9_.-])\.env(?!\.(?:example|sample|template)(?![A-Za-z0-9_.-]))(?:\.[A-Za-z0-9_-]+)*(?![A-Za-z0-9_.-])`,
	],
	["PKCS#12 private key", String.raw`\.(?:p12|pfx)(?![A-Za-z0-9_.-])`],
	["npm credentials", String.raw`(?<![A-Za-z0-9_.-])\.npmrc(?![A-Za-z0-9_.-])`],
	[
		"PyPI credentials",
		String.raw`(?<![A-Za-z0-9_.-])\.pypirc(?![A-Za-z0-9_.-])`,
	],
	[
		"netrc credentials",
		String.raw`(?<![A-Za-z0-9_.-])\.netrc(?![A-Za-z0-9_.-])`,
	],
];

function regexEscape(value: string): string {
	return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
}

function flexibleLiteral(value: string): string {
	return regexEscape(value.replaceAll("\\", "/")).replaceAll(
		"/",
		String.raw`[\\/]`,
	);
}

function exactBoundary(expression: string): string {
	return `(?:${expression})(?=$|[^A-Za-z0-9_.-])`;
}

function directoryBoundary(expression: string): string {
	return `(?:${expression})(?:[\\\\/]|(?=$|[^A-Za-z0-9_.-]))`;
}

function compileRule(
	group: RuleGroup,
	label: string,
	pattern: string,
	original?: string,
): VerbotenRule {
	return {
		group,
		label,
		pattern,
		regex: new RegExp(pattern, "iu"),
		original,
	};
}

function pathApi(
	platform: NodeJS.Platform,
): typeof path.win32 | typeof path.posix {
	return platform === "win32" ? path.win32 : path.posix;
}

function firstEnv(
	env: NodeJS.ProcessEnv,
	...names: string[]
): string | undefined {
	for (const name of names) {
		const direct = env[name];
		if (direct) return direct;
		if (process.platform === "win32") {
			const key = Object.keys(env).find(
				(candidate) => candidate.toLowerCase() === name.toLowerCase(),
			);
			if (key && env[key]) return env[key];
		}
	}
	return undefined;
}

function variableExpressions(name: string): string[] {
	const escaped = regexEscape(name);
	return [
		String.raw`\$${escaped}`,
		String.raw`\$\{${escaped}\}`,
		String.raw`%${escaped}%`,
		String.raw`\$env:${escaped}`,
	];
}

type PathVariable = { name: string; suffix?: string };

function pathExpressions(
	absolute: string,
	home: string,
	platform: NodeJS.Platform,
	variable?: PathVariable | readonly PathVariable[],
): string[] {
	const api = pathApi(platform);
	const expressions = [flexibleLiteral(api.resolve(absolute))];
	const relative = api.relative(api.resolve(home), api.resolve(absolute));
	if (relative && relative !== ".." && !relative.startsWith(`..${api.sep}`)) {
		const suffix = flexibleLiteral(relative);
		expressions.push(
			String.raw`~[\\/]${suffix}`,
			...variableExpressions("HOME").map(
				(prefix) => `${prefix}[\\\\/]${suffix}`,
			),
			...variableExpressions("USERPROFILE").map(
				(prefix) => `${prefix}[\\\\/]${suffix}`,
			),
		);
	}
	for (const item of variable
		? Array.isArray(variable)
			? variable
			: [variable]
		: []) {
		const suffix = item.suffix ? `[\\\\/]${flexibleLiteral(item.suffix)}` : "";
		expressions.push(
			...variableExpressions(item.name).map((prefix) => prefix + suffix),
		);
	}
	return [...new Set(expressions)];
}

function addExact(
	rules: VerbotenRule[],
	environment: BuiltinEnvironment,
	label: string,
	absolute: string,
	original: string,
	variable?: PathVariable | readonly PathVariable[],
): void {
	const expressions = pathExpressions(
		absolute,
		environment.home,
		environment.platform,
		variable,
	);
	rules.push(
		compileRule(
			"built-in resolved",
			label,
			exactBoundary(expressions.join("|")),
			original,
		),
	);
}

function addDirectory(
	rules: VerbotenRule[],
	environment: BuiltinEnvironment,
	label: string,
	absolute: string,
	original: string,
	variable?: PathVariable | readonly PathVariable[],
): void {
	const expressions = pathExpressions(
		absolute,
		environment.home,
		environment.platform,
		variable,
	);
	rules.push(
		compileRule(
			"built-in resolved",
			label,
			directoryBoundary(expressions.join("|")),
			original,
		),
	);
}

function addSshRule(
	rules: VerbotenRule[],
	environment: BuiltinEnvironment,
): void {
	const api = pathApi(environment.platform);
	const directory = api.join(environment.home, ".ssh");
	const prefixes = pathExpressions(
		directory,
		environment.home,
		environment.platform,
	);
	const allowed = String.raw`(?:[^\\/\s"'\x60]+\.pub|authorized_keys2?|known_hosts[^\\/\s"'\x60]*|config)(?=$|[\\/\s"'\x60;,|)&])`;
	const pattern = `(?:${prefixes.join("|")})(?:[\\\\/](?!${allowed})|(?=$|[\\s"'\\x60;,|)&]))`;
	rules.push(
		compileRule(
			"built-in resolved",
			"SSH private files",
			pattern,
			"$HOME/.ssh/<private>",
		),
	);
}

export function buildBuiltinRules(
	overrides: Partial<BuiltinEnvironment> = {},
): VerbotenRule[] {
	const env = overrides.env ?? process.env;
	const platform = overrides.platform ?? process.platform;
	const home =
		overrides.home ?? firstEnv(env, "HOME", "USERPROFILE") ?? homedir();
	const agentDir = overrides.agentDir ?? getAgentDir();
	const environment: BuiltinEnvironment = { platform, env, home, agentDir };
	const api = pathApi(platform);
	const rules = STATIC_RULES.map(([label, pattern]) =>
		compileRule("built-in static", label, pattern),
	);
	const join = (...segments: string[]) => api.join(...segments);
	const xdgConfig = firstEnv(env, "XDG_CONFIG_HOME") ?? join(home, ".config");
	const xdgData =
		firstEnv(env, "XDG_DATA_HOME") ?? join(home, ".local", "share");
	const xdgState =
		firstEnv(env, "XDG_STATE_HOME") ?? join(home, ".local", "state");
	const appData = firstEnv(env, "APPDATA") ?? join(home, "AppData", "Roaming");
	const localAppData =
		firstEnv(env, "LOCALAPPDATA") ?? join(home, "AppData", "Local");

	addSshRule(rules, environment);
	addDirectory(
		rules,
		environment,
		"GnuPG private keys",
		join(home, ".gnupg", "private-keys-v1.d"),
		"$HOME/.gnupg/private-keys-v1.d",
	);
	addExact(
		rules,
		environment,
		"GnuPG secret keyring",
		join(home, ".gnupg", "secring.gpg"),
		"$HOME/.gnupg/secring.gpg",
	);
	addExact(
		rules,
		environment,
		"Pi authentication",
		join(agentDir, "auth.json"),
		"$PI_CODING_AGENT_DIR/auth.json",
		{ name: "PI_CODING_AGENT_DIR", suffix: "auth.json" },
	);

	if (platform !== "darwin") {
		const claudeRoot =
			firstEnv(env, "CLAUDE_CONFIG_DIR") ?? join(home, ".claude");
		addExact(
			rules,
			environment,
			"Claude Code credentials",
			join(claudeRoot, ".credentials.json"),
			"$CLAUDE_CONFIG_DIR/.credentials.json",
			{ name: "CLAUDE_CONFIG_DIR", suffix: ".credentials.json" },
		);
	}
	const codexRoot = firstEnv(env, "CODEX_HOME") ?? join(home, ".codex");
	addExact(
		rules,
		environment,
		"Codex authentication",
		join(codexRoot, "auth.json"),
		"$CODEX_HOME/auth.json",
		{ name: "CODEX_HOME", suffix: "auth.json" },
	);

	const registryAuth = firstEnv(env, "REGISTRY_AUTH_FILE");
	if (registryAuth)
		addExact(
			rules,
			environment,
			"container registry authentication",
			registryAuth,
			"$REGISTRY_AUTH_FILE",
			{ name: "REGISTRY_AUTH_FILE" },
		);
	const runtimeDir = firstEnv(env, "XDG_RUNTIME_DIR");
	if (runtimeDir)
		addExact(
			rules,
			environment,
			"Podman runtime authentication",
			join(runtimeDir, "containers", "auth.json"),
			"$XDG_RUNTIME_DIR/containers/auth.json",
			{ name: "XDG_RUNTIME_DIR", suffix: "containers/auth.json" },
		);
	addExact(
		rules,
		environment,
		"Podman authentication",
		join(home, ".config", "containers", "auth.json"),
		"$HOME/.config/containers/auth.json",
	);
	const dockerRoot = firstEnv(env, "DOCKER_CONFIG") ?? join(home, ".docker");
	addExact(
		rules,
		environment,
		"Docker authentication",
		join(dockerRoot, "config.json"),
		"$DOCKER_CONFIG/config.json",
		{ name: "DOCKER_CONFIG", suffix: "config.json" },
	);

	const ghRoot =
		firstEnv(env, "GH_CONFIG_DIR") ??
		(platform === "win32"
			? join(appData, "GitHub CLI")
			: platform === "darwin"
				? join(home, "Library", "Application Support", "gh")
				: join(xdgConfig, "gh"));
	addExact(
		rules,
		environment,
		"GitHub CLI authentication",
		join(ghRoot, "hosts.yml"),
		"$GH_CONFIG_DIR/hosts.yml",
		[
			{ name: "GH_CONFIG_DIR", suffix: "hosts.yml" },
			...(platform === "win32"
				? [{ name: "APPDATA", suffix: "GitHub CLI/hosts.yml" }]
				: []),
		],
	);
	addExact(
		rules,
		environment,
		"Git credential store",
		join(home, ".git-credentials"),
		"$HOME/.git-credentials",
	);
	addExact(
		rules,
		environment,
		"Git XDG credential store",
		join(xdgConfig, "git", "credentials"),
		"$XDG_CONFIG_HOME/git/credentials",
		{ name: "XDG_CONFIG_HOME", suffix: "git/credentials" },
	);
	addDirectory(
		rules,
		environment,
		"Subversion authentication cache",
		platform === "win32"
			? join(appData, "Subversion", "auth")
			: join(home, ".subversion", "auth"),
		platform === "win32"
			? "%APPDATA%/Subversion/auth"
			: "$HOME/.subversion/auth",
		platform === "win32"
			? { name: "APPDATA", suffix: "Subversion/auth" }
			: undefined,
	);
	const forgejoRoot =
		platform === "win32"
			? join(appData, "Cyborus", "forgejo-cli", "data")
			: join(xdgData, "Cyborus", "forgejo-cli", "data");
	for (const file of ["keys.json", "ui-creds.json"])
		addExact(
			rules,
			environment,
			"Forgejo CLI credentials",
			join(forgejoRoot, file),
			`Forgejo CLI data/${file}`,
			platform === "win32"
				? { name: "APPDATA", suffix: `Cyborus/forgejo-cli/data/${file}` }
				: { name: "XDG_DATA_HOME", suffix: `Cyborus/forgejo-cli/data/${file}` },
		);

	const cargoRoot = firstEnv(env, "CARGO_HOME") ?? join(home, ".cargo");
	for (const file of ["credentials.toml", "credentials"])
		addExact(
			rules,
			environment,
			"Cargo credentials",
			join(cargoRoot, file),
			`$CARGO_HOME/${file}`,
			{ name: "CARGO_HOME", suffix: file },
		);
	const npmUserConfig = firstEnv(env, "NPM_CONFIG_USERCONFIG");
	if (npmUserConfig)
		addExact(
			rules,
			environment,
			"npm user credentials",
			npmUserConfig,
			"$NPM_CONFIG_USERCONFIG",
			{ name: "NPM_CONFIG_USERCONFIG" },
		);

	const awsCredentials =
		firstEnv(env, "AWS_SHARED_CREDENTIALS_FILE") ??
		join(home, ".aws", "credentials");
	addExact(
		rules,
		environment,
		"AWS credentials",
		awsCredentials,
		"$AWS_SHARED_CREDENTIALS_FILE",
		{ name: "AWS_SHARED_CREDENTIALS_FILE" },
	);
	const googleCredentials = firstEnv(env, "GOOGLE_APPLICATION_CREDENTIALS");
	if (googleCredentials)
		addExact(
			rules,
			environment,
			"Google application credentials",
			googleCredentials,
			"$GOOGLE_APPLICATION_CREDENTIALS",
			{ name: "GOOGLE_APPLICATION_CREDENTIALS" },
		);
	const gcloudRoot =
		firstEnv(env, "CLOUDSDK_CONFIG") ??
		(platform === "win32"
			? join(appData, "gcloud")
			: join(xdgConfig, "gcloud"));
	for (const file of [
		"application_default_credentials.json",
		"credentials.db",
		"access_tokens.db",
	])
		addExact(
			rules,
			environment,
			"gcloud credentials",
			join(gcloudRoot, file),
			`$CLOUDSDK_CONFIG/${file}`,
			[
				{ name: "CLOUDSDK_CONFIG", suffix: file },
				platform === "win32"
					? { name: "APPDATA", suffix: `gcloud/${file}` }
					: { name: "XDG_CONFIG_HOME", suffix: `gcloud/${file}` },
			],
		);
	addDirectory(
		rules,
		environment,
		"gcloud legacy credentials",
		join(gcloudRoot, "legacy_credentials"),
		"$CLOUDSDK_CONFIG/legacy_credentials",
		[
			{ name: "CLOUDSDK_CONFIG", suffix: "legacy_credentials" },
			platform === "win32"
				? { name: "APPDATA", suffix: "gcloud/legacy_credentials" }
				: { name: "XDG_CONFIG_HOME", suffix: "gcloud/legacy_credentials" },
		],
	);
	const kubeConfig = firstEnv(env, "KUBECONFIG");
	const kubePaths = kubeConfig
		? kubeConfig.split(platform === "win32" ? ";" : ":").filter(Boolean)
		: [join(home, ".kube", "config")];
	for (const [index, file] of kubePaths.entries())
		addExact(
			rules,
			environment,
			"Kubernetes credentials",
			file,
			kubeConfig ? `$KUBECONFIG[${index}]` : "$HOME/.kube/config",
			kubeConfig && kubePaths.length === 1 ? { name: "KUBECONFIG" } : undefined,
		);

	const syncthingFiles =
		platform === "win32"
			? [join(localAppData, "Syncthing", "config.xml")]
			: platform === "darwin"
				? [
						join(
							home,
							"Library",
							"Application Support",
							"Syncthing",
							"config.xml",
						),
					]
				: [
						join(xdgState, "syncthing", "config.xml"),
						join(xdgConfig, "syncthing", "config.xml"),
					];
	for (const file of syncthingFiles)
		addExact(
			rules,
			environment,
			"Syncthing API key",
			file,
			"Syncthing config.xml",
			platform === "win32"
				? { name: "LOCALAPPDATA", suffix: "Syncthing/config.xml" }
				: undefined,
		);
	addExact(
		rules,
		environment,
		"aerc accounts",
		join(xdgConfig, "aerc", "accounts.conf"),
		"$XDG_CONFIG_HOME/aerc/accounts.conf",
		{ name: "XDG_CONFIG_HOME", suffix: "aerc/accounts.conf" },
	);

	return rules;
}

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

function compileCustomRules(
	value: unknown,
	group: "global setting" | "project setting",
	warnings: VerbotenWarning[],
): VerbotenRule[] {
	if (value === undefined) return [];
	if (!Array.isArray(value)) {
		warnings.push({
			key: `${group}.patterns.type`,
			message: `${group} verboten.patterns must be an array; ignored`,
		});
		return [];
	}
	const rules: VerbotenRule[] = [];
	for (const [index, pattern] of value.entries()) {
		if (typeof pattern !== "string") {
			warnings.push({
				key: `${group}.patterns.${index}.type`,
				message: `${group} pattern ${index + 1} is not a string; ignored`,
			});
			continue;
		}
		try {
			rules.push(compileRule(group, `${group} pattern ${index + 1}`, pattern));
		} catch (error) {
			warnings.push({
				key: `${group}.patterns.${index}.syntax`,
				message: `${group} pattern ${index + 1} is invalid: ${error instanceof Error ? error.message : String(error)}`,
			});
		}
	}
	return rules;
}

function judgeModelSetting(
	global: Record<string, unknown>,
	project: Record<string, unknown>,
	projectTrusted: boolean,
	warnings: VerbotenWarning[],
): string | null {
	const globalSection = object(global.verboten);
	const projectSection = object(project.verboten);
	const selected =
		projectTrusted && Object.hasOwn(projectSection, "judgeModel")
			? projectSection.judgeModel
			: globalSection.judgeModel;
	if (selected === undefined || selected === null) return null;
	if (typeof selected === "string" && selected.trim()) return selected.trim();
	warnings.push({
		key: "judge-model.invalid",
		message:
			"verboten.judgeModel must be provider/model or null; using current model",
	});
	return null;
}

export function loadVerbotenSettings(
	cwd: string,
	projectTrusted: boolean,
	builtinOverrides: Partial<BuiltinEnvironment> = {},
): LoadedVerbotenSettings {
	const warnings: VerbotenWarning[] = [];
	const manager = SettingsManager.create(
		cwd,
		builtinOverrides.agentDir ?? getAgentDir(),
		{ projectTrusted },
	);
	const global = manager.getGlobalSettings() as Record<string, unknown>;
	const project = manager.getProjectSettings() as Record<string, unknown>;
	for (const failure of manager.drainErrors())
		warnings.push({
			key: `settings.${failure.scope}`,
			message: `could not read ${failure.scope} Pi settings: ${failure.error.message}`,
		});
	const globalSection = object(global.verboten);
	const projectSection = object(project.verboten);
	return {
		rules: [
			...buildBuiltinRules(builtinOverrides),
			...compileCustomRules(globalSection.patterns, "global setting", warnings),
			...(projectTrusted
				? compileCustomRules(
						projectSection.patterns,
						"project setting",
						warnings,
					)
				: []),
		],
		judgeModel: judgeModelSetting(global, project, projectTrusted, warnings),
		warnings,
		projectIgnored: !projectTrusted,
	};
}

function matchesText(text: string, rule: VerbotenRule): boolean {
	rule.regex.lastIndex = 0;
	return rule.regex.test(text);
}

export function matchingRules(
	text: string,
	rules: readonly VerbotenRule[],
): VerbotenRule[] {
	return rules.filter((rule) => matchesText(text, rule));
}

export function lexicalCandidates(rawPath: string, cwd: string): string[] {
	const raw = rawPath.startsWith("@") ? rawPath.slice(1) : rawPath;
	const absolute = path.resolve(cwd, raw).replaceAll("\\", "/");
	return [...new Set([raw, absolute])];
}

export async function resolvedCandidate(
	rawPath: string,
	cwd: string,
): Promise<string | undefined> {
	const raw = rawPath.startsWith("@") ? rawPath.slice(1) : rawPath;
	const absolute = path.resolve(cwd, raw);
	try {
		return (await realpath(absolute)).replaceAll("\\", "/");
	} catch (error) {
		const code = (error as NodeJS.ErrnoException).code;
		if (code !== "ENOENT" && code !== "ENOTDIR") throw error;
	}
	const suffix: string[] = [];
	let cursor = absolute;
	for (;;) {
		try {
			await stat(cursor);
			const base = await realpath(cursor);
			return path.join(base, ...suffix.reverse()).replaceAll("\\", "/");
		} catch (error) {
			const code = (error as NodeJS.ErrnoException).code;
			if (code !== "ENOENT" && code !== "ENOTDIR") throw error;
		}
		const parent = path.dirname(cursor);
		if (parent === cursor) return undefined;
		suffix.push(path.basename(cursor));
		cursor = parent;
	}
}

export interface PathMatch {
	candidates: string[];
	matches: VerbotenRule[];
}

export async function matchPath(
	rawPath: string,
	cwd: string,
	rules: readonly VerbotenRule[],
): Promise<PathMatch> {
	const candidates = lexicalCandidates(rawPath, cwd);
	const resolved = await resolvedCandidate(rawPath, cwd);
	if (resolved) candidates.push(resolved);
	const matches = new Map<string, VerbotenRule>();
	for (const candidate of new Set(candidates))
		for (const rule of matchingRules(candidate, rules))
			matches.set(`${rule.group}\0${rule.pattern}`, rule);
	return {
		candidates: [...new Set(candidates)],
		matches: [...matches.values()],
	};
}

export const __test = {
	STATIC_RULES,
	compileCustomRules,
	flexibleLiteral,
	pathExpressions,
};