import { constants } from "node:fs"; import { access, chmod, mkdtemp, readFile, realpath, rm, writeFile, } from "node:fs/promises"; import { tmpdir } from "node:os"; import { delimiter, join } from "node:path"; const POLICY_MARKER = "# pi-git-safe-policy-v1"; const COMMAND_PREFIX_END = "# pi-command-prefix-end"; const BLOCK_REASON = "git-safe blocked --no-verify. Fix the hook failure or ask the user for help."; const DIRECT_COMMAND_GIT_NO_VERIFY_RE = /^\s*command\s+(?:(?:-p|--)\s+)*git(?:\.exe)?\s+(?:am|commit|merge|pull|push|rebase)\s+--no-verify(?:\s|$)/u; export interface GitPolicyRuntime { wrapperDir: string; realGit: string; } function pathKey(env: NodeJS.ProcessEnv): string { return Object.keys(env).find((key) => key.toLowerCase() === "path") ?? "PATH"; } export async function findGitExecutable( env: NodeJS.ProcessEnv = process.env, platform = process.platform, ): Promise { const path = env[pathKey(env)] ?? ""; const names = platform === "win32" ? ["git.exe"] : ["git"]; for (const dir of path.split(delimiter).filter(Boolean)) { for (const name of names) { const candidate = join(dir.replace(/^"|"$/gu, ""), name); try { await access( candidate, platform === "win32" ? constants.F_OK : constants.X_OK, ); return await realpath(candidate); } catch {} } } return undefined; } export async function createGitPolicyRuntime(): Promise { const realGit = await findGitExecutable(); if (!realGit) throw new Error("Git executable not found on PATH"); const wrapperDir = await mkdtemp(join(tmpdir(), "pi-git-safe-policy-")); const wrapper = join(wrapperDir, "git"); try { const template = await readFile( new URL("./git-wrapper.cjs", import.meta.url), "utf8", ); await writeFile( wrapper, template .replace(/^#![^\r\n]*/u, `#!${bashPath(process.execPath)}`) .replace('"__PI_GIT_SAFE_REAL_GIT__"', JSON.stringify(realGit)), "utf8", ); await chmod(wrapper, 0o755); await writeFile( join(wrapperDir, "git.cmd"), `@echo off\r\n"${process.execPath}" "%~dp0git" %*\r\n`, "utf8", ); return { wrapperDir, realGit }; } catch (error) { await rm(wrapperDir, { recursive: true, force: true }).catch(() => {}); throw error; } } export async function removeGitPolicyRuntime( runtime: GitPolicyRuntime | undefined, ): Promise { if (runtime) await rm(runtime.wrapperDir, { recursive: true, force: true }).catch( () => {}, ); } function shellQuote(value: string): string { return `'${value.replaceAll("'", `'\\''`)}'`; } function bashPath(value: string): string { const normalized = value.replaceAll("\\", "/"); const drive = normalized.match(/^([A-Za-z]):\/(.*)$/u); return drive ? `/${drive[1].toLowerCase()}/${drive[2]}` : normalized; } export function blockedGitCommandReason( command: string, runtime?: GitPolicyRuntime, ): string | undefined { if (DIRECT_COMMAND_GIT_NO_VERIFY_RE.test(command)) return BLOCK_REASON; if (!runtime) return undefined; const trimmed = command.trimStart(); const literalPaths = [ runtime.realGit, bashPath(runtime.realGit), shellQuote(runtime.realGit), shellQuote(bashPath(runtime.realGit)), JSON.stringify(runtime.realGit), ]; for (const path of literalPaths) { if (!trimmed.startsWith(`${path} `)) continue; const args = trimmed.slice(path.length).trimStart(); if ( /^(?:am|commit|merge|pull|push|rebase)\s+--no-verify(?:\s|$)/u.test(args) ) return BLOCK_REASON; } return undefined; } export function applyGitPolicy( command: string, runtime: GitPolicyRuntime, ): string { const wrapper = shellQuote(bashPath(join(runtime.wrapperDir, "git"))); return `${POLICY_MARKER} export PATH=${shellQuote(bashPath(runtime.wrapperDir))}:"$PATH" git() { ${wrapper} "$@" } git.exe() { ${wrapper} "$@" } command() { local -a __pi_git_safe_args=("$@") local __pi_git_safe_index=0 while [[ "\${__pi_git_safe_args[$__pi_git_safe_index]}" == "-p" || "\${__pi_git_safe_args[$__pi_git_safe_index]}" == "--" ]]; do ((__pi_git_safe_index++)) done if [[ "\${__pi_git_safe_args[$__pi_git_safe_index]}" == "git" || "\${__pi_git_safe_args[$__pi_git_safe_index]}" == "git.exe" ]]; then ${wrapper} "\${__pi_git_safe_args[@]:$((__pi_git_safe_index + 1))}" else builtin command "$@" fi } env() { local -a __pi_git_safe_args=("$@") local __pi_git_safe_index=0 while (( __pi_git_safe_index < \${#__pi_git_safe_args[@]} )); do case "\${__pi_git_safe_args[$__pi_git_safe_index]}" in --) ((__pi_git_safe_index++)) break ;; --u*=*|--c*=*|--s*=*|--a*=*) ((__pi_git_safe_index++)) ;; -u|--u*|-C|--c*|-S|--s*|--a*) ((__pi_git_safe_index += 2)) ;; -*|*=*) ((__pi_git_safe_index++)) ;; *) break ;; esac done if [[ "\${__pi_git_safe_args[$__pi_git_safe_index]}" == "git" || "\${__pi_git_safe_args[$__pi_git_safe_index]}" == "git.exe" ]]; then __pi_git_safe_args[$__pi_git_safe_index]=${wrapper} fi builtin command env "\${__pi_git_safe_args[@]}" } xargs() { local -a __pi_git_safe_args=("$@") local __pi_git_safe_index=0 while (( __pi_git_safe_index < \${#__pi_git_safe_args[@]} )); do case "\${__pi_git_safe_args[$__pi_git_safe_index]}" in --) ((__pi_git_safe_index++)) break ;; --arg*=*|--e*=*|--r*=*|--m*=*|--d*=*) ((__pi_git_safe_index++)) ;; -a|-E|-I|-L|-n|-P|-s|-d|--arg*|--e*|--r*|--m*|--d*) ((__pi_git_safe_index += 2)) ;; -*) ((__pi_git_safe_index++)) ;; *) break ;; esac done if [[ "\${__pi_git_safe_args[$__pi_git_safe_index]}" == "git" || "\${__pi_git_safe_args[$__pi_git_safe_index]}" == "git.exe" ]]; then __pi_git_safe_args[$__pi_git_safe_index]=${wrapper} fi builtin command xargs "\${__pi_git_safe_args[@]}" } export -f git git.exe command env xargs ${COMMAND_PREFIX_END} ${command}`; }