Skip to content

A desktop coding agent with free access to frontier models.

TypeScript

fix: git hooks get no app tokens

ogsamrat5ab883c17e3a
diff --git a/apps/server/src/box/box.ts b/apps/server/src/box/box.ts
index af206efd..5e642b28 100644
--- a/apps/server/src/box/box.ts
+++ b/apps/server/src/box/box.ts
@@ -24,6 +24,7 @@
// up (<state>/sandbox/snapshots/<session>/turn-N.{json,tar}, the same
// transport the 2.2.3 sandbox used; record schema 2).
+import { gitChildEnv } from "../git-env.js";
import { execFileSync } from "node:child_process";
import { createHash, randomBytes } from "node:crypto";
import { existsSync, mkdirSync, readdirSync, readFileSync, renameSync, rmSync, statSync, unlinkSync, writeFileSync } from "node:fs";
@@ -800,7 +801,7 @@ export function savedTurns(dir: string): number {
export function hostGitIdentity(env: Env = process.env): { name: string; email: string } {
const get = (field: string) => {
try {
- return execFileSync("git", ["config", "--global", "--get", field], { encoding: "utf8", timeout: 3_000, env, stdio: ["ignore", "pipe", "ignore"] }).trim();
+ return execFileSync("git", ["config", "--global", "--get", field], { encoding: "utf8", timeout: 3_000, env: gitChildEnv({}, env), stdio: ["ignore", "pipe", "ignore"] }).trim();
} catch {
return "";
}
diff --git a/apps/server/src/context/outside-files.ts b/apps/server/src/context/outside-files.ts
index 793e16a2..84612c03 100644
--- a/apps/server/src/context/outside-files.ts
+++ b/apps/server/src/context/outside-files.ts
@@ -23,6 +23,7 @@
* and omnirush-gui (apps/server/src/context/), listed in PARITY.sha256.
*/
+import { gitChildEnv } from "../git-env.js";
import { execFile } from "node:child_process";
import { createHash } from "node:crypto";
import { lstat, readFile, readlink, readdir } from "node:fs/promises";
@@ -121,7 +122,7 @@ async function sha256Of(file: string, size: number): Promise<string | null> {
function git(root: string, args: string[]): Promise<string | null> {
return new Promise((resolve) => {
- execFile("git", ["-C", root, ...args], { timeout: GIT_TIMEOUT_MS, maxBuffer: 8 * 1024 * 1024, windowsHide: true }, (error, stdout) => resolve(error ? null : stdout));
+ execFile("git", ["-C", root, ...args], { timeout: GIT_TIMEOUT_MS, maxBuffer: 8 * 1024 * 1024, windowsHide: true, env: gitChildEnv() }, (error, stdout) => resolve(error ? null : stdout));
});
}
diff --git a/apps/server/src/excluded-files.ts b/apps/server/src/excluded-files.ts
index 56e036ba..46789af6 100644
--- a/apps/server/src/excluded-files.ts
+++ b/apps/server/src/excluded-files.ts
@@ -16,6 +16,7 @@
// per-snapshot read budget, and a hash is reused while the file's size,
// mtime and inode stay the same.
+import { gitChildEnv } from "./git-env.js";
import { createHash } from "node:crypto";
import { execFile } from "node:child_process";
import { createReadStream } from "node:fs";
@@ -127,7 +128,7 @@ export async function listGitIgnored(root: string): Promise<string[]> {
return new Promise((resolvePromise) => {
execFile("git", ["-C", root, "ls-files", "--others", "--ignored", "--exclude-standard", "--directory", "-z"], {
encoding: "buffer", maxBuffer: 16 * 1024 * 1024, timeout: 15_000, windowsHide: true,
- env: { ...process.env, GIT_TERMINAL_PROMPT: "0", GIT_OPTIONAL_LOCKS: "0" },
+ env: gitChildEnv({ GIT_OPTIONAL_LOCKS: "0" }),
}, (error, stdout) => {
if (error) return resolvePromise([]);
resolvePromise(Buffer.from(stdout).toString("utf8").split("\0").filter(Boolean).slice(0, MAX_GITIGNORED_LISTED));
diff --git a/apps/server/src/git-env.e2e.test.ts b/apps/server/src/git-env.e2e.test.ts
new file mode 100644
index 00000000..c4dcbb1d
--- /dev/null
+++ b/apps/server/src/git-env.e2e.test.ts
@@ -0,0 +1,54 @@
+import { afterEach, expect, test } from "bun:test";
+import { execFileSync } from "node:child_process";
+import { chmodSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+
+import { gitChildEnv } from "./git-env.js";
+import { runEditorGit } from "./routes/editor.js";
+import { runGit } from "./workspace/worktree-tasks.mjs";
+
+const dirs: string[] = [];
+afterEach(() => {
+ while (dirs.length) rmSync(dirs.pop()!, { recursive: true, force: true });
+});
+
+test("the git environment keeps the basics and git's own settings, nothing else", () => {
+ const env = gitChildEnv({ LC_ALL: "C" }, {
+ PATH: "/usr/bin", HOME: "/home/u", LANG: "C.UTF-8", OMNIRUSH_TOKEN: "t", OMNIRUSH_DEVICE_TOKEN: "d", OPENCODE_SERVER_PASSWORD: "p",
+ GITHUB_TOKEN: "g", AWS_SECRET_ACCESS_KEY: "a", NODE_OPTIONS: "--require x", GIT_DIR: "/elsewhere", GIT_AUTHOR_NAME: "Sam",
+ GIT_SSL_CAINFO: "/ca.pem", GNUPGHOME: "/g", GIT_ASKPASS: "/x",
+ }, "linux");
+ expect(env).toEqual({ PATH: "/usr/bin", HOME: "/home/u", LANG: "C.UTF-8", GIT_AUTHOR_NAME: "Sam", GIT_SSL_CAINFO: "/ca.pem", GNUPGHOME: "/g", GIT_TERMINAL_PROMPT: "0", LC_ALL: "C" });
+});
+
+for (const [name, commit] of [
+ ["the editor's git panel", (root: string) => runEditorGit(root, ["commit", "-q", "-F", "-"], { input: "test\n" })],
+ ["workspace tasks", (root: string) => runGit(["commit", "-q", "-F", "-"], { cwd: root, input: "test\n" })],
+] as const) test(`${name}: a commit's pre-commit hook runs, and sees no app tokens or other keys`, async () => {
+ if (process.platform === "win32") return;
+ const root = mkdtempSync(join(tmpdir(), "omnirush-git-env-"));
+ dirs.push(root);
+ const git = (...args: string[]) => execFileSync("git", args, { cwd: root, env: { ...process.env, GIT_AUTHOR_NAME: "t", GIT_AUTHOR_EMAIL: "[email protected]", GIT_COMMITTER_NAME: "t", GIT_COMMITTER_EMAIL: "[email protected]" } });
+ git("init", "-q");
+ git("config", "user.name", "t");
+ git("config", "user.email", "[email protected]");
+ writeFileSync(join(root, ".git", "hooks", "pre-commit"), "#!/bin/sh\nenv | cut -d= -f1 | sort > \"$(git rev-parse --git-dir)/hook-env-names\"\n");
+ chmodSync(join(root, ".git", "hooks", "pre-commit"), 0o755);
+ writeFileSync(join(root, "a.txt"), "a\n");
+ git("add", "a.txt");
+ const saved = { ...process.env };
+ Object.assign(process.env, { OMNIRUSH_TOKEN: "secret-token", OMNIRUSH_HOST_TOKEN: "secret-host", OPENCODE_SERVER_PASSWORD: "secret-pw", GITHUB_TOKEN: "secret-gh", AWS_SECRET_ACCESS_KEY: "secret-aws" });
+ try {
+ const result = await commit(root);
+ expect(result.code).toBe(0);
+ } finally {
+ for (const key of ["OMNIRUSH_TOKEN", "OMNIRUSH_HOST_TOKEN", "OPENCODE_SERVER_PASSWORD", "GITHUB_TOKEN", "AWS_SECRET_ACCESS_KEY"]) {
+ if (saved[key] === undefined) delete process.env[key];
+ else process.env[key] = saved[key];
+ }
+ }
+ const names = readFileSync(join(root, ".git", "hook-env-names"), "utf8").split("\n").filter(Boolean);
+ expect(names).toContain("PATH");
+ expect(names.filter((name) => /^OMNIRUSH_|^OPENCODE_SERVER|TOKEN|PASSWORD|SECRET/.test(name))).toEqual([]);
+});
diff --git a/apps/server/src/git-env.ts b/apps/server/src/git-env.ts
new file mode 100644
index 00000000..94dfaf2b
--- /dev/null
+++ b/apps/server/src/git-env.ts
@@ -0,0 +1,22 @@
+/**
+ * The environment every git the desktop server starts gets. Git runs the repository's hooks (a commit runs
+ * pre-commit, commit-msg …), and a hook is the repository's code: it must not see the app's tokens, the engine's
+ * password or the person's other keys. So git gets what a local MCP server gets (mcpServerEnvironment: PATH, HOME,
+ * locale, temp folders, proxy / certificate / registry settings) plus git's own settings that carry no credential
+ * (who commits, which certificates to trust, which config files to read, the GnuPG folder and the ssh-agent socket
+ * for signed commits).
+ * Variables that point git at another repository (GIT_DIR, GIT_WORK_TREE …) are never passed.
+ */
+import { mcpServerEnvironment } from "./mcp-allow/mcp-allow.mjs";
+
+const GIT_KEEP = /^(?:GIT_AUTHOR_(?:NAME|EMAIL|DATE)|GIT_COMMITTER_(?:NAME|EMAIL|DATE)|GIT_SSL_CAINFO|GIT_SSL_CAPATH|GIT_CONFIG_NOSYSTEM|GIT_CONFIG_GLOBAL|GIT_CEILING_DIRECTORIES|GNUPGHOME|GPG_TTY|SSH_AUTH_SOCK)$/;
+
+export function gitChildEnv(extra: Record<string, string> = {}, env: NodeJS.ProcessEnv = process.env, platform: NodeJS.Platform = process.platform): NodeJS.ProcessEnv {
+ const cleared = mcpServerEnvironment(env, {}, [], platform);
+ const out: NodeJS.ProcessEnv = {};
+ for (const [key, value] of Object.entries(env)) {
+ if (typeof value !== "string") continue;
+ if (/^GIT_/i.test(key) ? GIT_KEEP.test(key) : !Object.hasOwn(cleared, key) || GIT_KEEP.test(key)) out[key] = value;
+ }
+ return { ...out, GIT_TERMINAL_PROMPT: "0", ...extra };
+}
diff --git a/apps/server/src/managed-git-identity.ts b/apps/server/src/managed-git-identity.ts
index d872e590..b8ffa102 100644
--- a/apps/server/src/managed-git-identity.ts
+++ b/apps/server/src/managed-git-identity.ts
@@ -9,6 +9,7 @@
* --local`, never `--global`); otherwise the request fails with a message that
* tells the agent exactly what to ask the user.
*/
+import { gitChildEnv } from "./git-env.js";
import { execFile } from "node:child_process";
import { isAbsolute } from "node:path";
import { promisify } from "node:util";
@@ -53,7 +54,7 @@ export interface GitIdentityDependencies {
async function defaultRunGit(args: string[]): Promise<{ stdout: string; code: number }> {
try {
- const { stdout } = await execFileAsync("git", args, { timeout: GIT_TIMEOUT_MS, encoding: "utf8", maxBuffer: 1024 * 1024 });
+ const { stdout } = await execFileAsync("git", args, { timeout: GIT_TIMEOUT_MS, encoding: "utf8", maxBuffer: 1024 * 1024, env: gitChildEnv() });
return { stdout, code: 0 };
} catch (error) {
const failure = error as { code?: number | string; stdout?: string };
diff --git a/apps/server/src/omnirush-voice.ts b/apps/server/src/omnirush-voice.ts
index 35ab9330..c31bcf02 100644
--- a/apps/server/src/omnirush-voice.ts
+++ b/apps/server/src/omnirush-voice.ts
@@ -6,6 +6,7 @@
* request's memory: it is never written, logged, cached or handed to the
* session uploader. Only the text the user finally sends becomes a prompt.
*/
+import { gitChildEnv } from "./git-env.js";
import { execFile } from "node:child_process";
import path from "node:path";
@@ -206,7 +207,7 @@ function gitLine(directory: string, args: string[]): Promise<string | null> {
execFile(
"git",
["-C", directory, ...args],
- { timeout: 1_500, windowsHide: true, env: { ...process.env, GIT_TERMINAL_PROMPT: "0", GIT_OPTIONAL_LOCKS: "0" } },
+ { timeout: 1_500, windowsHide: true, env: gitChildEnv({ GIT_OPTIONAL_LOCKS: "0" }) },
(error, stdout) => resolve(error ? null : String(stdout).trim() || null),
);
});
diff --git a/apps/server/src/project-env.ts b/apps/server/src/project-env.ts
index c573ffb7..ff15f7df 100644
--- a/apps/server/src/project-env.ts
+++ b/apps/server/src/project-env.ts
@@ -8,6 +8,7 @@
// secret is left out; when in doubt, the value is omitted and only the name
// is kept.
+import { gitChildEnv } from "./git-env.js";
import { execFile } from "node:child_process";
import { readFile, readdir, lstat } from "node:fs/promises";
import { cpus, homedir, release as osRelease, userInfo } from "node:os";
@@ -224,7 +225,7 @@ async function projectSourceFiles(root: string, checks: SecretChecks): Promise<s
const listed = await new Promise<string[] | null>((resolvePromise) => {
execFile("git", ["-C", root, "ls-files", "-co", "--exclude-standard", "-z"], {
encoding: "buffer", maxBuffer: 16 * 1024 * 1024, timeout: 10_000, windowsHide: true,
- env: { ...process.env, GIT_TERMINAL_PROMPT: "0", GIT_OPTIONAL_LOCKS: "0" },
+ env: gitChildEnv({ GIT_OPTIONAL_LOCKS: "0" }),
}, (error, stdout) => resolvePromise(error ? null : Buffer.from(stdout).toString("utf8").split("\0").filter(Boolean)));
});
if (listed) return listed.filter(keep).slice(0, MAX_SCANNED_FILES);
diff --git a/apps/server/src/routes/editor.ts b/apps/server/src/routes/editor.ts
index 4f9c05d7..0811352c 100644
--- a/apps/server/src/routes/editor.ts
+++ b/apps/server/src/routes/editor.ts
@@ -9,6 +9,7 @@
* decision a "user_review") through `onUserEdit` / `onUserReview`; a save
* without one, or for a chat that is not tracked, reports nothing.
*/
+import { gitChildEnv } from "../git-env.js";
import { spawn } from "node:child_process";
import { readdir, readFile, realpath, rm, stat, writeFile } from "node:fs/promises";
import { dirname, extname, join, relative, resolve, sep } from "node:path";
@@ -72,12 +73,11 @@ export function runEditorGit(root: string, args: string[], options: { input?: st
try {
// No inherited GIT_* settings (a GIT_DIR or GIT_WORK_TREE from the app's own environment
// would point git elsewhere); paths are literal, never globs; no fsmonitor program.
- const env: NodeJS.ProcessEnv = {};
- for (const [key, value] of Object.entries(process.env)) if (!key.startsWith("GIT_")) env[key] = value;
+ // The commit's hooks are the repository's code: only the filtered environment (git-env.ts), no app tokens.
child = spawn("git", ["-c", "core.quotePath=false", "-c", "color.ui=false", "-c", "core.fsmonitor=false", ...args], {
cwd: root,
stdio: ["pipe", "pipe", "pipe"],
- env: { ...env, GIT_TERMINAL_PROMPT: "0", GIT_OPTIONAL_LOCKS: "0", GIT_LITERAL_PATHSPECS: "1", LC_ALL: "C" },
+ env: gitChildEnv({ GIT_OPTIONAL_LOCKS: "0", GIT_LITERAL_PATHSPECS: "1", LC_ALL: "C" }),
windowsHide: true,
});
} catch (error) {
diff --git a/apps/server/src/session-archive/ignore.ts b/apps/server/src/session-archive/ignore.ts
index e4ffc0b4..1119af91 100644
--- a/apps/server/src/session-archive/ignore.ts
+++ b/apps/server/src/session-archive/ignore.ts
@@ -25,6 +25,7 @@
*
* `.git` itself and the `.gitignore` files are never ignored.
*/
+import { gitChildEnv } from "../git-env.js";
import { spawn } from "node:child_process";
import { constants as fsConstants, realpathSync } from "node:fs";
import { mkdtemp, open, rm } from "node:fs/promises";
@@ -62,7 +63,7 @@ export function gitCeilingDirectories(): string {
/** The environment of every archive git run: never above home, no prompt, no optional lock, no pager, C locale. */
export function archiveGitEnv(extra: NodeJS.ProcessEnv = {}): NodeJS.ProcessEnv {
const env: NodeJS.ProcessEnv = {
- ...process.env,
+ ...gitChildEnv(),
GIT_CEILING_DIRECTORIES: gitCeilingDirectories(),
GIT_TERMINAL_PROMPT: "0",
GIT_OPTIONAL_LOCKS: "0",
diff --git a/apps/server/src/session-archive/manifest.ts b/apps/server/src/session-archive/manifest.ts
index cedf65d0..5e14405c 100644
--- a/apps/server/src/session-archive/manifest.ts
+++ b/apps/server/src/session-archive/manifest.ts
@@ -6,6 +6,7 @@
* delta computation against the previous archive's entry list; and the
* `__omnirush__/manifest.json` document.
*/
+import { gitChildEnv } from "../git-env.js";
import { spawn } from "node:child_process";
import { createHash } from "node:crypto";
import { constants as fsConstants, type BigIntStats } from "node:fs";
@@ -930,7 +931,7 @@ function runGitNow(root: string, args: string[], maxBytes: number): Promise<GitR
stdio: ["ignore", "pipe", "ignore"],
windowsHide: true,
env: {
- ...process.env,
+ ...gitChildEnv(),
GIT_CEILING_DIRECTORIES: gitCeilingDirectories(),
GIT_TERMINAL_PROMPT: "0",
GIT_OPTIONAL_LOCKS: "0",
diff --git a/apps/server/src/session-archive/repos.ts b/apps/server/src/session-archive/repos.ts
index abee0d42..d70e4321 100644
--- a/apps/server/src/session-archive/repos.ts
+++ b/apps/server/src/session-archive/repos.ts
@@ -31,6 +31,7 @@
* - a plain-folder or touched-files chain never read git at all: every
* v2 state reads the repositories, whatever the chain's marker.
*/
+import { gitChildEnv } from "../git-env.js";
import { spawn } from "node:child_process";
import { realpathSync } from "node:fs";
import { lstat, readFile } from "node:fs/promises";
@@ -154,7 +155,7 @@ function spawnRepoGit(
...(options.safeDirectory ? ["-c", `safe.directory=${options.safeDirectory}`] : []),
];
try {
- child = spawn("git", ["-C", cwd, ...config, ...args], { stdio: ["ignore", "pipe", "pipe"], windowsHide: true, env: captureGitEnv() });
+ child = spawn("git", ["-C", cwd, ...config, ...args], { stdio: ["ignore", "pipe", "pipe"], windowsHide: true, env: captureGitEnv(gitChildEnv()) });
} catch {
finish(false, true);
return;
diff --git a/apps/server/src/session-uploader.ts b/apps/server/src/session-uploader.ts
index 676007e7..383c5d88 100644
--- a/apps/server/src/session-uploader.ts
+++ b/apps/server/src/session-uploader.ts
@@ -1,4 +1,5 @@
import { permissionSetupSettings, type ApprovalMode } from "./approval-mode.js";
+import { gitChildEnv } from "./git-env.js";
import { createHash, randomBytes } from "node:crypto";
import { execFile, spawn } from "node:child_process";
import { createReadStream, createWriteStream, watch, type FSWatcher, type WriteStream } from "node:fs";
@@ -2505,7 +2506,7 @@ function gitIgnoredPathsNow(root: string, paths: string[]): Promise<Set<string>
child = spawn("git", ["-C", root, "check-ignore", "--no-index", "-z", "--stdin"], {
stdio: ["pipe", "pipe", "ignore"],
windowsHide: true,
- env: { ...process.env, GIT_TERMINAL_PROMPT: "0", GIT_OPTIONAL_LOCKS: "0" },
+ env: gitChildEnv({ GIT_OPTIONAL_LOCKS: "0" }),
});
} catch {
resolvePromise(null);
@@ -2883,6 +2884,7 @@ const MAX_NESTED_REPO_PATHS = MAX_RAW_LISTING_FILES;
async function gitListing(dir: string): Promise<string[]> {
const { stdout } = await execFileAsync("git", ["-C", dir, "ls-files", "-co", "--exclude-standard", "-z"], {
+ env: gitChildEnv(),
encoding: "buffer",
maxBuffer: 16 * 1024 * 1024,
timeout: 15_000,
@@ -2983,7 +2985,7 @@ function runGitNow(root: string, args: string[], options: { maxBytes: number; ti
child = spawn("git", ["-C", root, "-c", "core.quotePath=false", "-c", "core.fsmonitor=false", "-c", `safe.directory=${resolve(root)}`, ...args], {
stdio: ["ignore", "pipe", "ignore"],
windowsHide: true,
- env: { ...captureGitEnv(), GIT_CEILING_DIRECTORIES: process.env.GIT_CEILING_DIRECTORIES ?? "", LC_ALL: process.env.LC_ALL ?? "" },
+ env: { ...captureGitEnv(gitChildEnv()), GIT_CEILING_DIRECTORIES: process.env.GIT_CEILING_DIRECTORIES ?? "", LC_ALL: process.env.LC_ALL ?? "" },
});
} catch {
finish(false);
@@ -3291,6 +3293,7 @@ async function listUntrackedFiles(root: string): Promise<string[]> {
try {
if (await gitSkipReason()) throw new Error(XCODE_CLT_MISSING);
const { stdout } = await execFileAsync("git", ["-C", root, "ls-files", "--others", "--exclude-standard", "-z"], {
+ env: gitChildEnv(),
encoding: "buffer",
maxBuffer: 16 * 1024 * 1024,
timeout: 15_000,
@@ -3314,6 +3317,7 @@ async function listIgnoredOutputFiles(root: string): Promise<string[]> {
const listed = async (args: string[]): Promise<string[]> => {
if (await gitSkipReason()) throw new Error(XCODE_CLT_MISSING);
const { stdout } = await execFileAsync("git", ["-C", root, "ls-files", "--others", "--ignored", "--exclude-standard", "-z", ...args], {
+ env: gitChildEnv(),
encoding: "buffer",
maxBuffer: 16 * 1024 * 1024,
timeout: 15_000,
@@ -5079,7 +5083,7 @@ export class SessionUploader {
let gitVersion: string | null = null;
try {
if (await gitSkipReason()) throw new Error(XCODE_CLT_MISSING);
- const { stdout } = await execFileAsync("git", ["--version"], { timeout: 5_000, maxBuffer: 16 * 1024 });
+ const { stdout } = await execFileAsync("git", ["--version"], { timeout: 5_000, maxBuffer: 16 * 1024, env: gitChildEnv() });
gitVersion = String(stdout).trim().replace(/^git version\s+/i, "") || null;
} catch {
gitVersion = null;
diff --git a/apps/server/src/workspace/PARITY.sha256 b/apps/server/src/workspace/PARITY.sha256
index 4e06453d..bf2a30ab 100644
--- a/apps/server/src/workspace/PARITY.sha256
+++ b/apps/server/src/workspace/PARITY.sha256
@@ -1,3 +1,3 @@
# Byte-identical in omnirush-cli assets/extensions/omnirush/workspace/ (worktree tasks + home view).
-2ca6461ea4cfa0f7fdf77861fdb6e1aa6c19ade861943e31d515c77a324fe408 worktree-tasks.mjs
+6f5ae0556c8d07edc5ca1d68de4c47084d0980b01364f138675068d3bba57158 worktree-tasks.mjs
90bdb16dd097c79f5f5bc68f33d8eb530b56c6d8c380dd4c3b6290640a03b9e2 home-view.mjs
diff --git a/apps/server/src/workspace/worktree-tasks.d.mts b/apps/server/src/workspace/worktree-tasks.d.mts
index 1074c593..49dca4a4 100644
--- a/apps/server/src/workspace/worktree-tasks.d.mts
+++ b/apps/server/src/workspace/worktree-tasks.d.mts
@@ -86,3 +86,6 @@ export function taskStartedData(task: TaskRecord): Record<string, unknown>;
export function taskMergedData(task: TaskRecord, result: { mode: "apply" | "merge"; files: TaskChange[] | number }): Record<string, unknown>;
export function isFinished(task: TaskRecord): boolean;
export function stateLabel(state: TaskState | string): string;
+
+/** The environment git gets (hooks are the repository's code): basics and git's own non-credential settings only. */
+export function gitEnvironment(base?: Record<string, string | undefined>): Record<string, string>;
diff --git a/apps/server/src/workspace/worktree-tasks.mjs b/apps/server/src/workspace/worktree-tasks.mjs
index 4fd948b1..f85d7d0c 100644
--- a/apps/server/src/workspace/worktree-tasks.mjs
+++ b/apps/server/src/workspace/worktree-tasks.mjs
@@ -52,13 +52,37 @@ const FINISHED = new Set(["done", "failed", "stopped"]);
const GIT_TIMEOUT_MS = 60_000;
const MAX_BUFFER = 64 * 1024 * 1024;
+// The environment git gets. Git runs the repository's hooks (worktree add runs post-checkout, commit runs
+// pre-commit and commit-msg, merge runs its hooks): a hook is the repository's code and must not see the app's
+// tokens, the engine's password or other keys. Kept: what a local MCP server gets (the basics a program needs,
+// locale, proxy / certificate / registry settings), git's own settings that carry no credential, and the
+// ssh-agent socket (signed commits).
+const GIT_ENV_KEEP = new Set([
+ "PATH", "HOME", "USER", "LOGNAME", "SHELL", "TMPDIR", "TMP", "TEMP", "LANG", "LANGUAGE", "TZ", "TERM", "COLORTERM",
+ "SYSTEMROOT", "WINDIR", "COMSPEC", "PATHEXT", "USERPROFILE", "USERNAME", "USERDOMAIN", "APPDATA", "LOCALAPPDATA", "PROGRAMDATA",
+ "PROGRAMFILES", "PROGRAMFILES(X86)", "PROGRAMW6432", "COMMONPROGRAMFILES", "COMMONPROGRAMFILES(X86)", "HOMEDRIVE", "HOMEPATH",
+ "SYSTEMDRIVE", "ALLUSERSPROFILE", "PUBLIC", "COMPUTERNAME", "OS", "NUMBER_OF_PROCESSORS", "PROCESSOR_ARCHITECTURE", "__CF_USER_TEXT_ENCODING",
+ "HTTP_PROXY", "HTTPS_PROXY", "NO_PROXY", "ALL_PROXY", "NODE_EXTRA_CA_CERTS", "SSL_CERT_FILE", "SSL_CERT_DIR", "REQUESTS_CA_BUNDLE",
+ "GIT_AUTHOR_NAME", "GIT_AUTHOR_EMAIL", "GIT_AUTHOR_DATE", "GIT_COMMITTER_NAME", "GIT_COMMITTER_EMAIL", "GIT_COMMITTER_DATE",
+ "GIT_SSL_CAINFO", "GIT_SSL_CAPATH", "GIT_CONFIG_NOSYSTEM", "GIT_CONFIG_GLOBAL", "GIT_CEILING_DIRECTORIES", "GNUPGHOME", "GPG_TTY", "SSH_AUTH_SOCK",
+]);
+
+export function gitEnvironment(base = process.env) {
+ const out = {};
+ for (const [key, value] of Object.entries(base)) {
+ if (typeof value !== "string" || /^(?:OMNIRUSH_|OPENCODE_SERVER_|OPENCODE_PASSWORD$)/i.test(key)) continue;
+ if (GIT_ENV_KEEP.has(key.toUpperCase()) || /^(?:LC_|XDG_)/i.test(key)) out[key] = value;
+ }
+ return out;
+}
+
/** Runs git; resolves { code, stdout, stderr } (never rejects for a git error). */
export function runGit(args, { cwd, env, input, timeoutMs = GIT_TIMEOUT_MS } = {}) {
return new Promise((resolve) => {
const child = execFile("git", args, {
cwd, timeout: timeoutMs, maxBuffer: MAX_BUFFER, windowsHide: true,
// GIT_OPTIONAL_LOCKS=0: reading a running task's status never takes its index.lock.
- env: { ...process.env, ...env, GIT_TERMINAL_PROMPT: "0", GIT_OPTIONAL_LOCKS: "0", LC_ALL: "C" },
+ env: { ...gitEnvironment(), ...env, GIT_TERMINAL_PROMPT: "0", GIT_OPTIONAL_LOCKS: "0", LC_ALL: "C" },
}, (error, stdout, stderr) => {
const code = error ? (typeof error.code === "number" ? error.code : 1) : 0;
resolve({ code, stdout: String(stdout ?? ""), stderr: String(stderr ?? "") || (error && typeof error.code !== "number" ? String(error.message) : "") });