@foldrun/core 24.11.0 → 24.13.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,1274 @@
1
+ /**
2
+ * The walls for a run on a person's own machine (FOL-214): `foldrun code
3
+ * --local` and, later, `foldrun run`. Commands the agent runs — the shell,
4
+ * an MCP server it starts, what those start in turn — go through Anthropic's
5
+ * sandbox-runtime (Apache-2.0): Seatbelt on macOS, bubblewrap + seccomp on
6
+ * Linux. The engine's own file tools run in this process, so they check the
7
+ * same roots here (canRead / canWrite) rather than in the OS.
8
+ *
9
+ * One policy everywhere:
10
+ * - write: the project folder and a private temp folder (plus the few the
11
+ * runtime itself keeps writable, named in describe()), never the git
12
+ * hooks or config that run code on the next git command — the project's
13
+ * repository's, core.hooksPath's, and every nested repository's;
14
+ * - read: everything but the person's credentials (DENY_READ);
15
+ * - network: only the sites listed, through the runtime's proxy — the
16
+ * command has no other way out. An MCP server over HTTP, which this
17
+ * process would reach itself, is not offered inside the walls.
18
+ *
19
+ * The programs that put the walls up are chosen by no one inside them. The
20
+ * launcher is a fixed shell (LAUNCHER) started with a short list of plain
21
+ * variables and a PATH that holds no folder a command may write; while the
22
+ * walls are up this process's own PATH is that one too, because the runtime
23
+ * starts its helpers (which, rg, socat, bwrap, log, npm) by name from it,
24
+ * and the Linux helpers are also pinned to where they were found. The
25
+ * command's own environment travels under other names (FOLDRUN_IN_*) and is
26
+ * set again only inside, so nothing in it (LD_PRELOAD, BASH_ENV, a PATH into
27
+ * the project) touches a program outside, and no value is on a command line.
28
+ * Neither foldrun nor the runtime may be installed where a command can write.
29
+ *
30
+ * FAIL CLOSED: a backend that cannot start, a git question that cannot be
31
+ * answered, or a probe that does not show every wall holding, is a refusal
32
+ * with the reason and how to fix it — never a run without walls. Windows
33
+ * without WSL2 is refused: the runtime's Windows backend is an alpha that
34
+ * needs an elevated install.
35
+ *
36
+ * Known limits, said rather than hidden:
37
+ * - a hard link that already exists in the project to a file outside it
38
+ * is that file (on Linux a command can write through one; Read can read
39
+ * through one);
40
+ * - on Linux, a credential path that does not exist when a command is
41
+ * wrapped is not hidden from that command (bubblewrap masks what is
42
+ * there): a long-lived one, such as an MCP server, could read a
43
+ * credential file made after it started;
44
+ * - a repository a command creates below the project, and configures in
45
+ * that same command, is protected from the next command on (by the
46
+ * runtime's scan and the file tools' pattern), not before;
47
+ * - git's hooks, config and the programs its settings name are protected,
48
+ * but what an existing hook itself runs is project code (husky,
49
+ * lint-staged, `npm test` in a pre-commit): a change the agent made to
50
+ * it runs at the person's next git command, as any change to the
51
+ * project runs when they next run it. Review before committing;
52
+ * - a program setting that builds a file name at run time ($(…), eval)
53
+ * cannot be followed;
54
+ * - a long-lived process (an MCP server) runs under the rules it started
55
+ * with: it is stopped when any later launch, or its own next call,
56
+ * finds them changed, so its lifetime up to then counts as one command.
57
+ * On Linux everything a command starts lives in bubblewrap's own pid
58
+ * namespace and ends with it; on macOS a process that leaves its
59
+ * session (setsid, a daemon) is beyond what foldrun can find and end,
60
+ * and keeps the rules it started with until it exits.
61
+ * The file tools write through a helper inside the walls, so the OS holds
62
+ * their writes; they read through a descriptor checked after it is open.
63
+ */
64
+ import fs from "node:fs";
65
+ import net from "node:net";
66
+ import os from "node:os";
67
+ import path from "node:path";
68
+ import { randomBytes } from "node:crypto";
69
+ import { execFile, spawnSync } from "node:child_process";
70
+ import { fileURLToPath } from "node:url";
71
+
72
+ /** Where a person's credentials live: never readable from inside. Paths
73
+ * under the home folder are written `~/…`, as the runtime expects. */
74
+ export const DENY_READ: readonly string[] = [
75
+ "~/.ssh",
76
+ "~/.aws",
77
+ "~/.azure",
78
+ "~/.config/gcloud",
79
+ "~/.kube",
80
+ "~/.docker/config.json",
81
+ "~/.gnupg",
82
+ "~/.netrc",
83
+ "~/.npmrc",
84
+ "~/.pypirc",
85
+ "~/.git-credentials",
86
+ "~/.config/gh",
87
+ "~/.foldrun",
88
+ "~/.claude.json",
89
+ "~/.claude/.credentials.json",
90
+ "~/.codex",
91
+ "~/Library/Keychains",
92
+ "~/.password-store",
93
+ ];
94
+
95
+ /** What the runtime keeps writable for every command on its own (its
96
+ * SANDBOX_OWN_WRITE_PATHS and home conveniences, 0.0.83): named so
97
+ * describe() tells the truth. The file tools do not get these. */
98
+ const RUNTIME_OWN_WRITES = ["/tmp/claude", "~/.npm/_logs", "~/.claude/debug"];
99
+
100
+ /** The shell the walls are put up from: a fixed program, never a `bash`
101
+ * found on a PATH the project could have changed. */
102
+ export const LAUNCHER = fs.existsSync("/bin/bash") ? "/bin/bash" : "/bin/sh";
103
+
104
+ /** How deep nested repositories are looked for (the runtime's own scan goes
105
+ * as deep), and how many folders: past either, the open is refused. */
106
+ const GIT_SEARCH_DEPTH = 10;
107
+ const GIT_SEARCH_DIRS = 100_000;
108
+
109
+ /** The variables the launcher itself starts with: plain ones a program
110
+ * needs, none that makes a program load or run something. */
111
+ const LAUNCHER_VARS = ["HOME", "USER", "LOGNAME", "LANG", "LC_ALL", "LC_CTYPE", "TERM"];
112
+
113
+ /** What makes a program load a library, run a file or take options before
114
+ * its own work: kept out of this process's environment while the walls
115
+ * are up (the runtime's host helpers inherit it), set again inside. */
116
+ const LOADER_VARS = /^(LD_[A-Z_]+|DYLD_[A-Z_]+|BASH_ENV|ENV|NODE_OPTIONS|NODE_PATH|PERL5OPT|PERL5LIB|PYTHONSTARTUP|PYTHONPATH|RUBYOPT|GIT_EXEC_PATH|GIT_SSH|GIT_SSH_COMMAND|GIT_ASKPASS|SSH_ASKPASS|BASH_FUNC_.*)$/;
117
+
118
+ /** Names a shell can export, less the ones bash keeps read-only. */
119
+ const EXPORTABLE = /^[A-Za-z_][A-Za-z0-9_]*$/;
120
+ const NOT_EXPORTED = new Set(["SHELLOPTS", "BASHOPTS", "BASH_VERSINFO", "EUID", "UID", "PPID"]);
121
+
122
+ export type SandboxBackend = "seatbelt" | "bubblewrap";
123
+
124
+ export interface LocalSandboxPolicy {
125
+ /** The project folder: readable and writable. */
126
+ cwd: string;
127
+ /** More paths a command may not read, beside DENY_READ. */
128
+ denyRead?: string[];
129
+ /** Sites a command may reach (`api.example.com`, `*.example.com`). */
130
+ sites: string[];
131
+ }
132
+
133
+ export interface LocalSandbox {
134
+ backend: SandboxBackend;
135
+ /** The private temp folder: a command's TMPDIR. */
136
+ tmp: string;
137
+ /** How to run `command` inside the walls with `env` as its environment:
138
+ * start LAUNCHER with `-c line` and exactly `env` (the launcher's own).
139
+ * Refuses once this handle is closed. */
140
+ launch(command: string, env: Record<string, string | undefined>): Promise<{ line: string; env: Record<string, string>; token: string }>;
141
+ /** Whether a process launched with `token` runs under the protections as
142
+ * they are now: found again, compared. */
143
+ fresh(token: string): boolean;
144
+ /** Told the new token whenever a launch finds the protections changed. */
145
+ onChange(listener: (token: string) => void | Promise<void>): () => void;
146
+ /** Whether the engine's own file tools may read / write this path (false
147
+ * for everything once this handle is closed). */
148
+ canRead(file: string): boolean;
149
+ canWrite(file: string): boolean;
150
+ /** For the session's record and the CLI. */
151
+ describe(): string;
152
+ /** Give this handle back; the walls come down when the last one is. */
153
+ close(): Promise<void>;
154
+ }
155
+
156
+ export interface SandboxRefusal {
157
+ refused: string;
158
+ /** What the person can do about it, when there is something. */
159
+ hint?: string;
160
+ }
161
+
162
+ export const isRefusal = (x: LocalSandbox | SandboxRefusal): x is SandboxRefusal => "refused" in x;
163
+
164
+ const home = () => os.homedir();
165
+ /** `~` and `~/…` as the home folder, joined as text: a `..` after it is
166
+ * left for the links on the way to decide. */
167
+ const expand = (p: string) => {
168
+ if (p === "~") return home();
169
+ if (p.startsWith("~/")) return `${home()}${path.sep}${p.slice(2)}`;
170
+ // ~name/…: this person's own name is their home; another person's home
171
+ // is not looked up, so a path written that way is refused.
172
+ const m = /^~([A-Za-z0-9._-]+)(\/.*)?$/.exec(p);
173
+ if (m) {
174
+ const me = os.userInfo();
175
+ if (m[1] === me.username) return `${me.homedir}${m[2] ?? ""}`;
176
+ throw new Error(`${p} names another user's home folder, which foldrun does not look up`);
177
+ }
178
+ return p;
179
+ };
180
+ /** A path the runtime must take as the name it is, never as a pattern. */
181
+ const lit = (p: string) => ({ path: p, literal: true as const });
182
+
183
+ /** A path as the file system names it — links followed, and in its own
184
+ * case (realpathSync.native: on a case-insensitive Mac volume the plain
185
+ * realpath keeps whatever case it was given, so `~/.SSH` would not look
186
+ * like `~/.ssh`). A file that does not exist yet is judged by where it
187
+ * would land: its nearest existing parent, resolved, joined with the rest. */
188
+ export function realish(p: string): string {
189
+ // Handed to realpath(3) as written: it takes `..` after a link the way
190
+ // the kernel does, where path.resolve would drop `link/..` as text first.
191
+ const given = path.isAbsolute(p) ? p : `${process.cwd()}${path.sep}${p}`;
192
+ let dir = given;
193
+ const rest: string[] = [];
194
+ for (;;) {
195
+ try {
196
+ return path.join(fs.realpathSync.native(dir), ...rest.reverse());
197
+ } catch {
198
+ const up = path.dirname(dir);
199
+ if (up === dir) return path.resolve(given);
200
+ rest.push(path.basename(dir));
201
+ dir = up;
202
+ }
203
+ }
204
+ }
205
+
206
+ /** Denies compare without case on macOS and Windows, whose usual volumes
207
+ * ignore it: a deny is never weaker for a spelling. */
208
+ const foldCase = (platform: NodeJS.Platform) => (s: string) => (platform === "darwin" || platform === "win32" ? s.toLowerCase() : s);
209
+
210
+ const within = (file: string, root: string) => file === root || file.startsWith(root.endsWith(path.sep) ? root : root + path.sep);
211
+ const overlaps = (a: string, b: string) => within(a, b) || within(b, a);
212
+
213
+ /** `PATH` with every entry a command could have written removed (and every
214
+ * relative one): what the launcher may look programs up in. */
215
+ export function trustedPath(pathVar: string | undefined, writable: string[], platform: NodeJS.Platform = process.platform): string {
216
+ const fold = foldCase(platform);
217
+ const roots = writable.map((r) => fold(realish(r)));
218
+ // Each kept by where it really is, so a link swapped later changes nothing.
219
+ const kept = (pathVar ?? "")
220
+ .split(path.delimiter)
221
+ .filter((d) => path.isAbsolute(d))
222
+ .map((d) => realish(d))
223
+ .filter((d) => !roots.some((r) => overlaps(fold(d), r)));
224
+ const out = [...new Set(kept)];
225
+ return out.length ? out.join(path.delimiter) : ["/usr/bin", "/bin", "/usr/sbin", "/sbin"].join(path.delimiter);
226
+ }
227
+
228
+ /** `rel` taken from `base` as text, the way git and the kernel take it:
229
+ * no `..` dropped before the links on the way are followed. */
230
+ const textJoin = (base: string, rel: string) => (path.isAbsolute(rel) ? rel : `${base}${path.sep}${rel}`);
231
+
232
+ /** Every link met on the way to `file`, resolved one component at a time
233
+ * (folders on the way too), and where it lands: each one a place a change
234
+ * could redirect it. A dangling end is where it would land. */
235
+ export function linkHops(file: string): string[] {
236
+ const hops: string[] = [];
237
+ const parts = (p: string) => p.split(path.sep).filter(Boolean);
238
+ // Taken as the kernel takes it: `..` after a link is the link's target's
239
+ // parent, so nothing is normalised before the links are followed.
240
+ let todo = parts(path.isAbsolute(file) ? file : `${process.cwd()}${path.sep}${file}`);
241
+ let cur: string = path.sep;
242
+ for (let n = 0; todo.length && n < 40; ) {
243
+ const c = todo.shift()!;
244
+ if (c === ".") continue;
245
+ if (c === "..") {
246
+ cur = path.dirname(cur);
247
+ continue;
248
+ }
249
+ const next = path.join(cur, c);
250
+ let st: fs.Stats;
251
+ try {
252
+ st = fs.lstatSync(next);
253
+ } catch {
254
+ hops.push(path.join(next, ...todo));
255
+ return hops;
256
+ }
257
+ if (!st.isSymbolicLink()) {
258
+ cur = next;
259
+ continue;
260
+ }
261
+ n++;
262
+ hops.push(next);
263
+ const target = fs.readlinkSync(next);
264
+ todo = [...parts(target), ...todo];
265
+ if (path.isAbsolute(target)) cur = path.sep;
266
+ }
267
+ hops.push(cur);
268
+ return hops;
269
+ }
270
+
271
+ /** Whether every step on the way to `file` — each folder, each link and
272
+ * where it points, resolved one component at a time — lies outside the
273
+ * folders a command may write: any of them inside could be changed later. */
274
+ export function chainOutside(file: string, roots: string[], platform: NodeJS.Platform = process.platform): boolean {
275
+ const fold = foldCase(platform);
276
+ const rs = roots.map((r) => fold(realish(r)));
277
+ const parts = (p: string) => p.split(path.sep).filter(Boolean);
278
+ let todo = parts(path.isAbsolute(file) ? file : `${process.cwd()}${path.sep}${file}`);
279
+ let cur: string = path.sep;
280
+ for (let hops = 0; todo.length; ) {
281
+ const c = todo.shift()!;
282
+ if (c === ".") continue;
283
+ if (c === "..") {
284
+ cur = path.dirname(cur);
285
+ continue;
286
+ }
287
+ const next = path.join(cur, c);
288
+ if (rs.some((r) => within(fold(next), r))) return false;
289
+ let st: fs.Stats;
290
+ try {
291
+ st = fs.lstatSync(next);
292
+ } catch {
293
+ return false; // not there: whatever appears there later is unknown
294
+ }
295
+ if (!st.isSymbolicLink()) {
296
+ cur = next;
297
+ continue;
298
+ }
299
+ if (++hops > 40) return false;
300
+ const target = fs.readlinkSync(next);
301
+ todo = [...parts(target), ...todo];
302
+ if (path.isAbsolute(target)) cur = path.sep;
303
+ }
304
+ return true;
305
+ }
306
+
307
+ /** A program found on a trusted PATH, as the file it really is, when that
308
+ * file and every link to it lie outside `roots`; else null. */
309
+ function which(program: string, pathVar: string, roots: string[] = []): string | null {
310
+ for (const dir of pathVar.split(path.delimiter)) {
311
+ const full = path.join(dir, program);
312
+ try {
313
+ fs.accessSync(full, fs.constants.X_OK);
314
+ if (!fs.statSync(full).isFile()) continue;
315
+ } catch {
316
+ continue;
317
+ }
318
+ return chainOutside(full, roots) ? fs.realpathSync.native(full) : null;
319
+ }
320
+ return null;
321
+ }
322
+
323
+ /** The programs this process starts by name while the walls are up: the
324
+ * runtime's helpers, git, and what npm needs to answer the runtime. */
325
+ const HOST_HELPERS = ["which", "env", "git", "log", "npm", "node", "rg", "bwrap", "socat", "sandbox-exec", "cat", "sh", "bash"];
326
+
327
+ /**
328
+ * A folder only this process writes, holding a link to the real file of
329
+ * each helper the person's PATH would run (first found, as exec finds it):
330
+ * while the walls are up it is this process's whole PATH, so no lookup by
331
+ * name ever sees a folder, a link or a file a command could change. A
332
+ * helper whose real file lies in such a folder is a refusal.
333
+ */
334
+ export function helperFolder(pathVar: string | undefined, roots: string[], platform: NodeJS.Platform = process.platform): { dir: string } | { refused: string } {
335
+ const fold = foldCase(platform);
336
+ const rs = roots.map((r) => fold(realish(r)));
337
+ const inside = (real: string) => rs.some((r) => within(fold(real), r));
338
+ for (const fixed of [LAUNCHER, "/bin/cat", process.execPath]) {
339
+ if (!chainOutside(fixed, roots, platform)) return { refused: `${fixed} is, or leads to, a file a command could change` };
340
+ }
341
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), "foldrun-bin-"));
342
+ if (inside(realish(dir))) {
343
+ fs.rmSync(dir, { recursive: true, force: true });
344
+ return { refused: "no folder outside the project for foldrun's own helpers" };
345
+ }
346
+ const dirs = (pathVar ?? "").split(path.delimiter).filter((d) => path.isAbsolute(d));
347
+ for (const program of HOST_HELPERS) {
348
+ for (const d of dirs) {
349
+ const full = path.join(d, program);
350
+ let real: string;
351
+ try {
352
+ if (!fs.statSync(full).isFile()) continue;
353
+ fs.accessSync(full, fs.constants.X_OK);
354
+ real = fs.realpathSync.native(full);
355
+ } catch {
356
+ continue;
357
+ }
358
+ if (inside(real)) {
359
+ fs.rmSync(dir, { recursive: true, force: true });
360
+ return { refused: `${full} leads to ${real}, a file a command could change, and foldrun would run it outside the walls` };
361
+ }
362
+ fs.symlinkSync(real, path.join(dir, program));
363
+ break;
364
+ }
365
+ }
366
+ return { dir: realish(dir) };
367
+ }
368
+
369
+ /**
370
+ * The git paths that run code on a later git command: the hooks (or the
371
+ * folder core.hooksPath names) and every config file git reads (config,
372
+ * config.worktree, included files) of the repository the project is in and
373
+ * of every repository nested below it. Asked of git on the host, with a git
374
+ * found on a trusted PATH. A question git cannot answer, a repository with
375
+ * no git to ask, or a project too large to search, is an error, never an
376
+ * empty answer: a hooks folder dropped by a failed lookup would be writable.
377
+ */
378
+ export function gitProtected(cwd: string, pathVar = trustedPath(process.env.PATH, [cwd]), hostEnv: NodeJS.ProcessEnv = process.env, writeRoots: string[] = [cwd]): string[] {
379
+ const out: string[] = [];
380
+ const fold = foldCase(process.platform);
381
+ const repos = [cwd, ...nestedRepos(cwd)];
382
+ const inRepo = repos.length > 1 || hasGitAbove(cwd) || looksBare(cwd);
383
+ // A selector in the environment would point every question below at one
384
+ // repository, whatever folder it is asked from.
385
+ const selector = ["GIT_DIR", "GIT_WORK_TREE", "GIT_COMMON_DIR", "GIT_CONFIG_PARAMETERS"].find((k) => hostEnv[k]);
386
+ if (selector) throw new Error(`${selector} is set in this shell, so git would answer for that repository instead of the project's — unset it to use the local sandbox`);
387
+ // A .git that is a file names the git folder: it is protected as well.
388
+ for (const r of repos) for (const f of [".git", ...["hooks", "config", "config.worktree", "commondir", "gitdir"].map((x) => path.join(".git", x))]) out.push(path.join(r, f));
389
+ const gitBin = which("git", pathVar, [cwd]);
390
+ // Without git nothing can say which config files and hooks a later git
391
+ // command would use (its includes, its global file): refused.
392
+ const spellings = (p: string) => {
393
+ const hops = linkHops(p);
394
+ return [path.resolve(p), ...hops, realish(hops[hops.length - 1]!)];
395
+ };
396
+ if (!gitBin) throw new Error(inRepo ? "this project is a git repository, and no git was found to ask where its hooks and config are" : "no git was found to read git's settings (its config files may name files in the project)");
397
+ const git = (dir: string, args: string[]) => {
398
+ // The person's own git settings (XDG_CONFIG_HOME, GIT_CONFIG_GLOBAL…)
399
+ // decide what the next git command reads: ask with those, and nothing
400
+ // that makes git load or run anything else.
401
+ const r = spawnSync(gitBin, ["-C", dir, ...args], { encoding: "utf8", timeout: 10_000, env: gitEnv(hostEnv, pathVar) });
402
+ return { status: r.status, out: r.stdout ?? "", err: (r.stderr || r.error?.message || "").trim().split("\n")[0] ?? "" };
403
+ };
404
+ const must = (dir: string, args: string[], what: string) => {
405
+ const r = git(dir, args);
406
+ if (r.status !== 0) throw new Error(`git could not say ${what} for ${dir}: ${r.err || `exit ${r.status}`}`);
407
+ return r.out.trim();
408
+ };
409
+ for (const dir of repos) {
410
+ const probe = git(dir, ["rev-parse", "--is-bare-repository"]);
411
+ // Only the project folder may be no repository (a nested one has a .git,
412
+ // or is a bare one); its global and system config are still read below.
413
+ let isRepo = true;
414
+ if (probe.status !== 0) {
415
+ if (/not a git repository/i.test(probe.err) && dir === cwd && !hasGitAbove(cwd) && !looksBare(cwd)) isRepo = false;
416
+ else throw new Error(`git could not read the repository at ${dir}: ${probe.err || `exit ${probe.status}`}`);
417
+ }
418
+ const bare = isRepo && probe.out.trim() === "true";
419
+ const gitDirs: string[] = [];
420
+ if (isRepo) {
421
+ for (const which of ["--git-dir", "--git-common-dir"]) {
422
+ const d = must(dir, ["rev-parse", "--path-format=absolute", which], "the git folder");
423
+ gitDirs.push(d);
424
+ for (const f of ["hooks", "config", "config.worktree", "commondir", "gitdir"]) out.push(path.join(d, f));
425
+ }
426
+ }
427
+ const top = !isRepo ? dir : bare ? gitDirs[0]! : must(dir, ["rev-parse", "--show-toplevel"], "the top folder");
428
+ // A nested repository must answer as itself, not as the one around it.
429
+ if (isRepo && dir !== cwd && fold(realish(bare ? gitDirs[0]! : top)) !== fold(realish(dir))) throw new Error(`git answered for ${top} when asked about ${dir}`);
430
+ const hookBases = [top, ...gitDirs];
431
+ const hooksAt = (h: string) => {
432
+ const x = expand(h);
433
+ // A relative one is taken from where git runs a hook: the work tree
434
+ // for most, the git folder for those a push runs. Both.
435
+ for (const d of path.isAbsolute(x) ? [x] : hookBases.map((b) => `${b}${path.sep}${x}`)) {
436
+ out.push(d, ...linkHops(d));
437
+ hookEntries(d);
438
+ }
439
+ };
440
+ // Each hook that is a link: every hop to the script it runs.
441
+ const hookEntries = (d: string) => {
442
+ let names: string[];
443
+ try {
444
+ names = fs.readdirSync(d);
445
+ } catch (err) {
446
+ const code = (err as NodeJS.ErrnoException).code;
447
+ if (code === "ENOENT" || code === "ENOTDIR") return;
448
+ throw new Error(`the hooks folder ${d} could not be listed (${code ?? String(err)})`);
449
+ }
450
+ for (const n of names) out.push(`${d}${path.sep}${n}`, ...linkHops(`${d}${path.sep}${n}`));
451
+ };
452
+ for (const d of gitDirs) hookEntries(path.join(d, "hooks"));
453
+ // `config --get` exits 1 for "not set": that is an answer.
454
+ const hooks = git(dir, ["config", "--type=path", "--get", "core.hooksPath"]);
455
+ if (hooks.status === 0 && hooks.out.trim()) hooksAt(hooks.out.trim());
456
+ else if (hooks.status !== 1) throw new Error(`git could not say core.hooksPath for ${dir}: ${hooks.err || `exit ${hooks.status}`}`);
457
+ // Every file git took its settings from, then each one read on its own
458
+ // with every include it names followed — conditional ones too, active
459
+ // or not, there or not yet: what they say could apply tomorrow.
460
+ const origins = git(dir, ["config", "--list", "--show-origin", "--name-only", "-z"]);
461
+ if (origins.status !== 0) throw new Error(`git could not list the config files of ${dir}: ${origins.err || `exit ${origins.status}`}`);
462
+ const files = new Set<string>();
463
+ const parts = origins.out.split("\0");
464
+ for (let i = 0; i + 1 < parts.length; i += 2) if (parts[i]!.startsWith("file:")) files.add(textJoin(dir, expand(parts[i]!.slice(5))));
465
+ for (const d of gitDirs) for (const f of ["config", "config.worktree"]) files.add(path.join(d, f));
466
+ // The global and system files wherever this shell says they are, there
467
+ // or not, empty or not: they apply to every later git command.
468
+ for (const f of [hostEnv.GIT_CONFIG_GLOBAL, hostEnv.GIT_CONFIG_SYSTEM, path.join(hostEnv.XDG_CONFIG_HOME || path.join(home(), ".config"), "git", "config"), path.join(home(), ".gitconfig")]) {
469
+ if (f) files.add(textJoin(dir, expand(f)));
470
+ }
471
+ for (const v of ["GIT_CONFIG_GLOBAL", "GIT_CONFIG_SYSTEM"]) {
472
+ const r = git(dir, ["var", v]);
473
+ if (r.status === 0) for (const f of r.out.split("\n").map((x) => x.trim()).filter(Boolean)) files.add(textJoin(dir, expand(f)));
474
+ }
475
+ const queue = [...files];
476
+ // The person's PATH as their own git will have it ('' and '.' are the
477
+ // folder git runs in).
478
+ // And git's own folder of programs (git-<name>): where this shell's
479
+ // GIT_EXEC_PATH says, and where git says it is.
480
+ const execPath = git(dir, ["--exec-path"]);
481
+ const personDirs = [...(hostEnv.PATH ?? "").split(path.delimiter), hostEnv.GIT_EXEC_PATH ?? "", execPath.status === 0 ? execPath.out.trim() : ""]
482
+ .map((d, i, all) => (d === "" && i >= all.length - 2 ? null : d === "" || d === "." ? top : textJoin(top, d)))
483
+ .filter((d): d is string => d !== null);
484
+ const rootsF = writeRoots.map((r) => fold(realish(r)));
485
+ const inRoots = (x: string) => rootsF.some((r) => within(x, r));
486
+ const protectWord = (key: string, x: string) => {
487
+ const bare = !x.includes("/");
488
+ // A bare name is a program looked up on the person's PATH: in each
489
+ // folder of it a command may write, that name is theirs to plant.
490
+ const viaPath = bare ? personDirs.map((d) => `${d}${path.sep}${x}`) : [];
491
+ for (const at of [...(path.isAbsolute(x) ? [x] : hookBases.map((b) => `${b}${path.sep}${x}`)), ...viaPath]) {
492
+ // In a writable folder by its name, by where it leads, or by a
493
+ // link on the way: each of those can be swapped.
494
+ const hops = linkHops(at);
495
+ if (!hops.some((h) => inRoots(fold(h))) && !inRoots(fold(path.resolve(at)))) continue;
496
+ if (/[*?[]/.test(x)) throw new Error(`the git setting ${key} names files in the project by a pattern (${x}), and which ones it runs cannot be told`);
497
+ out.push(at, ...hops);
498
+ }
499
+ };
500
+ const consider = (key: string, value: string, from: string, rawKey = key): void => {
501
+ if (/^include(if\..*)?\.path$/.test(key) && value) {
502
+ const t = expand(value);
503
+ const target = textJoin(from, t);
504
+ if (!files.has(target)) {
505
+ files.add(target);
506
+ queue.push(target);
507
+ }
508
+ } else if (key === "core.hookspath" && value) hooksAt(value);
509
+ else if (PROGRAM_KEY.test(key)) {
510
+ // A setting that runs a program: every word of it, as a file in the
511
+ // work tree or a git folder, is code a later git command may run on
512
+ // the host. Variables are taken from this shell first.
513
+ // The words as a shell reads them (quotes, escapes, variables from
514
+ // this shell, expanded only where the shell would), and crude splits
515
+ // of the raw and the expanded text besides, each quoted group whole:
516
+ // a name is protected in every spelling it could be read in.
517
+ // An alias's leading ! is git's, not part of the command.
518
+ const raw = value;
519
+ value = value.replace(/^\s*!/, "");
520
+ const expanded = value.replace(/\$\{?([A-Za-z_][A-Za-z0-9_]*)\}?/g, (_m, n: string) => hostEnv[n] ?? "");
521
+ const crude = (t: string) => t.split(/[\s|;&<>()`'"]+/);
522
+ const quoted = [...value.matchAll(/"([^"]*)"|'([^']*)'/g)].map((m) => m[1] ?? m[2] ?? "");
523
+ const all = [...shellWords(value, hostEnv), ...crude(value), ...crude(expanded), ...quoted].filter(Boolean);
524
+ // `NAME=value prog`: the value may be a path too; the whole word stays.
525
+ // The whole value too: some settings are one literal program path
526
+ // (GIT_SSH, gpg.program), spaces and all.
527
+ const words = [...all, raw, value, value.trim(), ...all.filter((w) => w.includes("=")).map((w) => w.slice(w.indexOf("=") + 1))].filter(Boolean);
528
+ // A helper named without a path is git-credential-<name>; an alias
529
+ // that is not a shell command runs git-<name> when it is no builtin.
530
+ const first = shellWords(value, hostEnv)[0];
531
+ if (first && !first.includes("/") && !raw.trimStart().startsWith("!")) {
532
+ if (/^credential(\..+)?\.helper$/.test(key)) words.push(`git-credential-${first}`);
533
+ if (key.startsWith("alias.")) words.push(`git-${first}`);
534
+ }
535
+ // Each word as written (a quoted ~ is a folder named ~) and with ~
536
+ // taken as home (an unquoted one).
537
+ for (const x of [...new Set(words.flatMap((w) => [w, expand(w)]))]) protectWord(key, x);
538
+ }
539
+ // A remote helper: git runs git-remote-<transport>, found by name.
540
+ const helper = remoteHelper(rawKey, value);
541
+ if (helper) protectWord(key, `git-remote-${helper}`);
542
+ };
543
+ // Settings given in this shell's environment count as a file's do.
544
+ const count = Number(hostEnv.GIT_CONFIG_COUNT ?? 0);
545
+ const envPathKey = /^(include(if\..*)?\.path|core\.hookspath)$/i;
546
+ for (let i = 0; i < (Number.isInteger(count) ? count : 0); i++) {
547
+ const k = hostEnv[`GIT_CONFIG_KEY_${i}`];
548
+ if (k && !envPathKey.test(k)) consider(k.toLowerCase(), hostEnv[`GIT_CONFIG_VALUE_${i}`] ?? "", dir, k);
549
+ }
550
+ // Those path settings as git expands them, from every scope (the
551
+ // environment's "command line" one included).
552
+ const typedAll = git(dir, ["config", "--show-origin", "--type=path", "-z", "--get-regexp", "^(include(if\\..*)?\\.path|core\\.hookspath)$"]);
553
+ if (typedAll.status !== 0 && typedAll.status !== 1) throw new Error(`git could not expand its path settings for ${dir}: ${typedAll.err || `exit ${typedAll.status}`}`);
554
+ if (typedAll.status === 0) {
555
+ const q = typedAll.out.split("\0");
556
+ for (let i = 0; i + 1 < q.length; i += 2) {
557
+ if (!q[i]!.startsWith("command line:")) continue; // files are read below
558
+ const entry = q[i + 1]!;
559
+ const nl = entry.indexOf("\n");
560
+ consider((nl < 0 ? entry : entry.slice(0, nl)).toLowerCase(), nl < 0 ? "" : entry.slice(nl + 1), dir);
561
+ }
562
+ }
563
+ // Programs this shell's environment hands git (or what git starts).
564
+ for (const k of ["GIT_SSH_COMMAND", "GIT_SSH", "GIT_ASKPASS", "SSH_ASKPASS", "GIT_EDITOR", "GIT_SEQUENCE_EDITOR", "GIT_PAGER", "GIT_EXTERNAL_DIFF", "GIT_PROXY_COMMAND", "EDITOR", "VISUAL", "PAGER"]) {
565
+ const v = hostEnv[k];
566
+ if (v) consider("core.pager", v, top);
567
+ }
568
+ while (queue.length) {
569
+ const f = queue.shift()!;
570
+ out.push(f, ...linkHops(f));
571
+ if (!fs.existsSync(f)) continue;
572
+ const r = git(dir, ["config", "-f", f, "--list", "-z"]);
573
+ if (r.status !== 0) throw new Error(`git could not read ${f}: ${r.err || `exit ${r.status}`}`);
574
+ const pathKey = /^(include(if\..*)?\.path|core\.hookspath)$/;
575
+ for (const entry of r.out.split("\0")) {
576
+ if (!entry) continue;
577
+ const nl = entry.indexOf("\n");
578
+ const rawKey = nl < 0 ? entry : entry.slice(0, nl);
579
+ const key = rawKey.toLowerCase();
580
+ if (pathKey.test(key)) continue; // below, as git expands them
581
+ consider(key, nl < 0 ? "" : entry.slice(nl + 1), path.dirname(f), rawKey);
582
+ }
583
+ // Include and hooks paths as git itself expands them (~, ~user,
584
+ // %(prefix)/): its answer, or a refusal when it cannot give one.
585
+ const typed = git(dir, ["config", "-f", f, "--type=path", "-z", "--get-regexp", "^(include(if\\..*)?\\.path|core\\.hookspath)$"]);
586
+ if (typed.status !== 0 && typed.status !== 1) throw new Error(`git could not expand the paths in ${f}: ${typed.err || `exit ${typed.status}`}`);
587
+ if (typed.status === 0) {
588
+ for (const entry of typed.out.split("\0")) {
589
+ if (!entry) continue;
590
+ const nl = entry.indexOf("\n");
591
+ consider((nl < 0 ? entry : entry.slice(0, nl)).toLowerCase(), nl < 0 ? "" : entry.slice(nl + 1), path.dirname(f));
592
+ }
593
+ }
594
+ }
595
+ }
596
+ // Each by the name git uses, by every link on the way and by where it
597
+ // lands as the kernel walks it (`..` after a link included).
598
+ return [...new Set(out.flatMap(spellings))];
599
+ }
600
+
601
+ /** What git needs to answer about its config, from the person's
602
+ * environment: where config lives and which repository, never a variable
603
+ * that makes a program load a library or run a file. */
604
+ const GIT_VARS = /^(HOME|LANG|LC_ALL|XDG_CONFIG_HOME|GIT_CONFIG_GLOBAL|GIT_CONFIG_SYSTEM|GIT_CONFIG_NOSYSTEM|GIT_CONFIG_COUNT|GIT_CONFIG_KEY_\d+|GIT_CONFIG_VALUE_\d+|GIT_CONFIG_PARAMETERS|GIT_CEILING_DIRECTORIES|GIT_DISCOVERY_ACROSS_FILESYSTEM)$/;
605
+ function gitEnv(from: NodeJS.ProcessEnv, pathVar: string): NodeJS.ProcessEnv {
606
+ const out: Record<string, string> = { PATH: pathVar };
607
+ for (const [k, v] of Object.entries(from)) if (typeof v === "string" && GIT_VARS.test(k)) out[k] = v;
608
+ return out as NodeJS.ProcessEnv;
609
+ }
610
+
611
+ /** A shell line's words, as the shell reads them: quotes and backslash
612
+ * escapes taken, `$NAME` / `${NAME}` taken from `env` outside single
613
+ * quotes, split at blanks and the shell's operators. */
614
+ export function shellWords(t: string, env: Record<string, string | undefined> = {}): string[] {
615
+ const out: string[] = [];
616
+ let cur = "";
617
+ let q: string | null = null;
618
+ const variable = (i: number): [string, number] | null => {
619
+ const m = /^\$(?:\{([A-Za-z_][A-Za-z0-9_]*)\}|([A-Za-z_][A-Za-z0-9_]*))/.exec(t.slice(i));
620
+ return m ? [env[m[1] ?? m[2]!] ?? "", m[0].length] : null;
621
+ };
622
+ for (let i = 0; i < t.length; i++) {
623
+ const c = t[i]!;
624
+ if (q === "'") {
625
+ if (c === "'") q = null;
626
+ else cur += c;
627
+ continue;
628
+ }
629
+ if (c === "$") {
630
+ const v = variable(i);
631
+ if (v) {
632
+ cur += v[0];
633
+ i += v[1] - 1;
634
+ continue;
635
+ }
636
+ }
637
+ if (q === '"') {
638
+ if (c === '"') q = null;
639
+ else if (c === "\\" && i + 1 < t.length) cur += t[++i];
640
+ else cur += c;
641
+ continue;
642
+ }
643
+ if (c === "'" || c === '"') q = c;
644
+ else if (c === "\\" && i + 1 < t.length) cur += t[++i];
645
+ else if (/[\s|;&<>()`]/.test(c)) {
646
+ if (cur) out.push(cur);
647
+ cur = "";
648
+ } else cur += c;
649
+ }
650
+ if (cur) out.push(cur);
651
+ return out;
652
+ }
653
+
654
+ /** The transport a remote setting makes git run git-remote-<it> for, or
655
+ * null: `remote.<n>.vcs`, a `<transport>::address` URL, a scheme git does
656
+ * not speak itself, and the same in a `url.<base>.insteadOf` base. */
657
+ export function remoteHelper(key: string, value: string): string | null {
658
+ // Section and variable names ignore case; a subsection (the rewrite
659
+ // base) and the transport keep theirs, as git keeps them.
660
+ if (/^remote\..+\.vcs$/i.test(key)) return value.trim() || null;
661
+ let url: string | null = null;
662
+ if (/^remote\..+\.(url|pushurl)$/i.test(key)) url = value;
663
+ const rewrite = /^url\.(.+)\.(insteadof|pushinsteadof)$/i.exec(key);
664
+ if (rewrite) url = rewrite[1]!;
665
+ if (!url) return null;
666
+ const helper = /^([A-Za-z][A-Za-z0-9+.-]*)::/.exec(url);
667
+ if (helper) return helper[1]!;
668
+ const scheme = /^([A-Za-z][A-Za-z0-9+.-]*):\/\//.exec(url);
669
+ if (scheme && !["ssh", "git", "file", "git+ssh", "ssh+git"].includes(scheme[1]!.toLowerCase())) return scheme[1]!;
670
+ return null;
671
+ }
672
+
673
+ /** Settings whose value git runs as a program (or a hook folder). */
674
+ const PROGRAM_KEY =
675
+ /(command|cmd|program|helper|driver|textconv|editor|pager|askpass|hook|proxy|process|clean|smudge|fsmonitor|difffilter|browser|external|variant|receivepack|uploadpack|smtpserver|httpd)$|^submodule\..+\.update$|^(core\.(fsmonitor|pager|editor|sshcommand|askpass|gitproxy)|sequence\.editor|diff\.external|diff\..+\.(textconv|command)|merge\..+\.driver|filter\..+\.(clean|smudge|process)|credential(\..+)?\.helper|gpg(\..+)?\.program|alias\..+|uploadpack\.packobjectshook|interactive\.difffilter|pager\..+|web\.browser|browser\..+\.(cmd|path)|man\..+\.(cmd|path)|(merge|diff)tool\..+\.(cmd|path))$/;
676
+
677
+ /** A bare repository: HEAD, objects/ and refs/ with no work tree. */
678
+ function looksBare(dir: string): boolean {
679
+ try {
680
+ return fs.statSync(path.join(dir, "HEAD")).isFile() && fs.statSync(path.join(dir, "objects")).isDirectory() && fs.statSync(path.join(dir, "refs")).isDirectory();
681
+ } catch {
682
+ return false;
683
+ }
684
+ }
685
+
686
+ /** Whether `dir` or a folder above it holds a `.git`. */
687
+ function hasGitAbove(dir: string): boolean {
688
+ for (let d = path.resolve(dir); ; d = path.dirname(d)) {
689
+ if (fs.existsSync(path.join(d, ".git"))) return true;
690
+ if (path.dirname(d) === d) return false;
691
+ }
692
+ }
693
+
694
+ /** Folders below `cwd` that hold a repository of their own (a `.git`).
695
+ * Links are not followed. A folder that cannot be read, or a project past
696
+ * the depth or size limit, is an error: a repository missed is a hooks
697
+ * folder left writable. */
698
+ function nestedRepos(cwd: string): string[] {
699
+ const found: string[] = [];
700
+ const stack: { dir: string; depth: number }[] = [{ dir: cwd, depth: 0 }];
701
+ let seen = 0;
702
+ while (stack.length) {
703
+ const { dir, depth } = stack.pop()!;
704
+ if (++seen > GIT_SEARCH_DIRS) throw new Error(`the project has more than ${GIT_SEARCH_DIRS} folders to search for nested git repositories`);
705
+ let entries: fs.Dirent[];
706
+ try {
707
+ entries = fs.readdirSync(dir, { withFileTypes: true });
708
+ } catch (err) {
709
+ throw new Error(`${dir} could not be searched for nested git repositories (${(err as NodeJS.ErrnoException).code ?? String(err)})`);
710
+ }
711
+ for (const e of entries) {
712
+ if (!e.isDirectory() || e.name === ".git") continue;
713
+ const sub = path.join(dir, e.name);
714
+ if (fs.existsSync(path.join(sub, ".git")) || looksBare(sub)) found.push(sub);
715
+ if (depth + 1 >= GIT_SEARCH_DEPTH) {
716
+ if (fs.readdirSync(sub, { withFileTypes: true }).some((x) => x.isDirectory())) throw new Error(`the project's folders go deeper than ${GIT_SEARCH_DEPTH} levels (${sub})`);
717
+ continue;
718
+ }
719
+ stack.push({ dir: sub, depth: depth + 1 });
720
+ }
721
+ }
722
+ return found;
723
+ }
724
+
725
+ /** A `.git/hooks`, `.git/config` or `.git/config.worktree` anywhere below:
726
+ * a repository made later. */
727
+ const NESTED_GIT = new RegExp(`(^|\\${path.sep})\\.git\\${path.sep}(hooks(\\${path.sep}|$)|config$|config\\.worktree$|commondir$)`, "i");
728
+
729
+ /** The in-process half of the policy: what the file tools may touch. Pure
730
+ * but for the paths it is given, so it is tested without a sandbox. */
731
+ export function fileRules(policy: LocalSandboxPolicy, tmp: string, protectedWrites: string[] = [], platform: NodeJS.Platform = process.platform) {
732
+ const fold = foldCase(platform);
733
+ const writable = [policy.cwd, tmp].map(realish);
734
+ // Each deny by the name it was given and by where it leads today: a link
735
+ // there now, replaced later by the real file, stays denied.
736
+ const given = [...DENY_READ, ...(policy.denyRead ?? [])].map((p) => path.resolve(expand(p)));
737
+ const denied = [...new Set([...given, ...given.map((p) => realish(p))].map(fold))];
738
+ const noWrite = [...new Set([...protectedWrites.map((p) => path.resolve(p)), ...protectedWrites.map((p) => realish(p))].map(fold))];
739
+ return {
740
+ canRead: (file: string) => {
741
+ const names = [fold(path.resolve(file)), fold(realish(file))];
742
+ return !names.some((f) => denied.some((d) => within(f, d)));
743
+ },
744
+ canWrite: (file: string) => {
745
+ const real = realish(file);
746
+ const names = [fold(path.resolve(file)), fold(real)];
747
+ if (names.some((f) => denied.some((d) => within(f, d)))) return false;
748
+ if (names.some((f) => noWrite.some((d) => within(f, d)))) return false;
749
+ if (NESTED_GIT.test(real)) return false;
750
+ return writable.some((root) => within(real, root));
751
+ },
752
+ };
753
+ }
754
+
755
+ /** Ubuntu 24.04+ restricts unprivileged user namespaces through AppArmor,
756
+ * and bubblewrap then cannot start. */
757
+ export function appArmorRestrictsUserns(read = (f: string) => fs.readFileSync(f, "utf8")): boolean {
758
+ try {
759
+ return read("/proc/sys/kernel/apparmor_restrict_unprivileged_userns").trim() === "1";
760
+ } catch {
761
+ return false;
762
+ }
763
+ }
764
+
765
+ /** The fix for that block. Never "turn the restriction off". */
766
+ export const APPARMOR_HINT =
767
+ "Ubuntu restricts unprivileged user namespaces, so bubblewrap cannot start. Allow bubblewrap alone with the profile Ubuntu ships: " +
768
+ "sudo cp /usr/share/apparmor/extra-profiles/bwrap-userns-restrict /etc/apparmor.d/ && sudo apparmor_parser -r /etc/apparmor.d/bwrap-userns-restrict";
769
+
770
+ /** How to install what the backend needs, per OS. */
771
+ function installHint(platform: NodeJS.Platform): string {
772
+ if (platform === "darwin") return "Install ripgrep: brew install ripgrep";
773
+ return "Install bubblewrap, socat and ripgrep: sudo apt-get install bubblewrap socat ripgrep (dnf / pacman: the same names)";
774
+ }
775
+
776
+ /** End a process and every process below it (SIGKILL), found from the
777
+ * process table: a server's children do not outlive it. */
778
+ export function killTree(pid: number): void {
779
+ const table = spawnSync("/bin/ps", ["-A", "-o", "pid=,ppid="], { encoding: "utf8" });
780
+ const kids = new Map<number, number[]>();
781
+ for (const line of (table.stdout ?? "").split("\n")) {
782
+ const [p, pp] = line.trim().split(/\s+/).map(Number);
783
+ if (!p || pp === undefined || Number.isNaN(pp)) continue;
784
+ kids.set(pp, [...(kids.get(pp) ?? []), p]);
785
+ }
786
+ const all: number[] = [];
787
+ const walk = (p: number) => {
788
+ all.push(p);
789
+ for (const c of kids.get(p) ?? []) walk(c);
790
+ };
791
+ walk(pid);
792
+ for (const p of all.reverse()) {
793
+ try {
794
+ process.kill(p, "SIGKILL");
795
+ } catch {
796
+ /* gone */
797
+ }
798
+ }
799
+ }
800
+
801
+ /** One word for a shell, single-quoted. */
802
+ export const q = (s: string) => `'${s.replaceAll("'", `'\\''`)}'`;
803
+
804
+ /** The environment the probe starts from: a program needs these, and none
805
+ * of them is a secret. */
806
+ export function bareEnv(from: NodeJS.ProcessEnv = process.env, extra: Record<string, string> = {}): Record<string, string> {
807
+ const out: Record<string, string> = {};
808
+ for (const k of ["PATH", "HOME", "USER", "LOGNAME", "LANG", "LC_ALL", "TERM", "SHELL"]) if (typeof from[k] === "string") out[k] = from[k]!;
809
+ return { ...out, ...extra };
810
+ }
811
+
812
+ type Runtime = typeof import("@anthropic-ai/sandbox-runtime");
813
+
814
+ /** Run a wrapped line, its output. Async: the runtime's proxy answers from
815
+ * this process, so a synchronous child would wait on a proxy that cannot. */
816
+ function runLine(line: string, cwd: string, env: Record<string, string>, ms = 30_000): Promise<{ code: number | null; out: string; err: string }> {
817
+ return new Promise((resolve) =>
818
+ execFile(LAUNCHER, ["-c", line], { cwd, env: env as NodeJS.ProcessEnv, timeout: ms, encoding: "utf8" }, (e, out, err) =>
819
+ resolve({ code: e ? (typeof (e as { code?: unknown }).code === "number" ? (e as { code: number }).code : null) : 0, out: String(out), err: String(err || (e ? e.message : "")).trim() }),
820
+ ),
821
+ );
822
+ }
823
+
824
+ /** Where a module's file lives, or null. */
825
+ function moduleFile(spec: string): string | null {
826
+ try {
827
+ return fileURLToPath(import.meta.resolve(spec));
828
+ } catch {
829
+ return null;
830
+ }
831
+ }
832
+
833
+ /** The folder of the package a file belongs to: the nearest one above it
834
+ * with a package.json (named `name`, when given). */
835
+ function packageRoot(file: string, name?: string): string {
836
+ for (let d = path.dirname(realish(file)); ; d = path.dirname(d)) {
837
+ try {
838
+ const pkg = JSON.parse(fs.readFileSync(path.join(d, "package.json"), "utf8")) as { name?: string };
839
+ if (!name || pkg.name === name) return d;
840
+ } catch {
841
+ /* none here */
842
+ }
843
+ if (path.dirname(d) === d) return path.dirname(realish(file));
844
+ }
845
+ }
846
+
847
+ /** The code this process runs to keep the walls: the runtime, foldrun's
848
+ * core, the program started (the CLI) and node itself. */
849
+ function installTrees(): { what: string; dir: string }[] {
850
+ const out: { what: string; dir: string }[] = [];
851
+ const srt = moduleFile("@anthropic-ai/sandbox-runtime");
852
+ if (srt) out.push({ what: "the sandbox runtime", dir: packageRoot(srt, "@anthropic-ai/sandbox-runtime") });
853
+ out.push({ what: "foldrun", dir: packageRoot(fileURLToPath(import.meta.url), "@foldrun/core") });
854
+ if (process.argv[1]) out.push({ what: "the program running foldrun", dir: packageRoot(process.argv[1]) });
855
+ out.push({ what: "node", dir: path.dirname(path.dirname(realish(process.execPath))) });
856
+ return out;
857
+ }
858
+
859
+ /** The one set of walls this process has up, shared by its handles. */
860
+ interface Walls {
861
+ key: string;
862
+ gen: number;
863
+ users: number;
864
+ down: boolean;
865
+ wrapRaw(command: string): Promise<{ line: string; token: string }>;
866
+ fingerprint(): string;
867
+ listeners: Set<(token: string) => void | Promise<void>>;
868
+ last: string;
869
+ /** Discovery, comparison and the ending of stale processes, one launch
870
+ * at a time: none can pass a revocation still under way. */
871
+ gate: Promise<unknown>;
872
+ hostEnv: Record<string, string>;
873
+ /** This process's PATH before the walls put the helper folder there. */
874
+ personPath: string | undefined;
875
+ rules: { canRead(f: string): boolean; canWrite(f: string): boolean };
876
+ backend: SandboxBackend;
877
+ tmp: string;
878
+ describe: string;
879
+ teardown(): Promise<void>;
880
+ }
881
+ let walls: Walls | null = null;
882
+ let generation = 0;
883
+ /** Opens and teardowns, one at a time: the runtime is one per process. */
884
+ let queue: Promise<unknown> = Promise.resolve();
885
+ const inQueue = <T>(job: () => Promise<T>): Promise<T> => {
886
+ const next = queue.then(job);
887
+ queue = next.catch(() => undefined);
888
+ return next;
889
+ };
890
+
891
+ /**
892
+ * A command's environment carried past the launcher: each variable rides
893
+ * as FOLDRUN_IN_<name> (only names are on the line, never values) and is
894
+ * set again inside — PATH always, the rest where the runtime has not set
895
+ * its own (its proxy, its temp folder).
896
+ */
897
+ export function carry(env: Record<string, string | undefined>): { inner: string; outer: Record<string, string> } {
898
+ const outer: Record<string, string> = {};
899
+ const lines: string[] = [];
900
+ for (const [k, v] of Object.entries(env)) {
901
+ if (typeof v !== "string" || !EXPORTABLE.test(k) || NOT_EXPORTED.has(k) || k.startsWith("FOLDRUN_IN_")) continue;
902
+ outer[`FOLDRUN_IN_${k}`] = v;
903
+ lines.push(k === "PATH" ? `export PATH="$FOLDRUN_IN_PATH"` : `[ -n "\${${k}+x}" ] || export ${k}="$FOLDRUN_IN_${k}"`);
904
+ }
905
+ if (!lines.length) return { inner: "", outer };
906
+ lines.push(`unset ${Object.keys(outer).join(" ")}`);
907
+ return { inner: lines.join("\n"), outer };
908
+ }
909
+
910
+ /** A handle of its own for each open: closing it revokes it alone. */
911
+ function handleOf(w: Walls): LocalSandbox {
912
+ let released = false;
913
+ const live = () => !released && !w.down;
914
+ return {
915
+ backend: w.backend,
916
+ tmp: w.tmp,
917
+ launch: async (command, env) => {
918
+ if (!live()) throw new Error("the sandbox is closed");
919
+ const gen = w.gen;
920
+ // An environment built from this process after the walls went up
921
+ // has the helper folder for PATH: the person's own goes inside.
922
+ const { inner, outer } = carry(env.PATH === w.hostEnv.PATH ? { ...env, PATH: w.personPath } : env);
923
+ const { line, token } = await w.wrapRaw(inner ? `${inner}\n${command}` : command);
924
+ // Made under this handle's walls, still up: a line from a later
925
+ // policy, or for a handle given back meanwhile, is not handed out.
926
+ if (!live() || w.gen !== gen || walls !== w) throw new Error("the sandbox closed while the command was being wrapped");
927
+ if (!line || typeof line !== "string") throw new Error("the sandbox returned no command line");
928
+ return { line, env: { ...w.hostEnv, ...outer }, token };
929
+ },
930
+ onChange: (listener) => {
931
+ w.listeners.add(listener);
932
+ return () => w.listeners.delete(listener);
933
+ },
934
+ fresh: (token) => {
935
+ if (!live()) return false;
936
+ try {
937
+ return w.fingerprint() === token;
938
+ } catch {
939
+ return false;
940
+ }
941
+ },
942
+ canRead: (file) => live() && w.rules.canRead(file),
943
+ canWrite: (file) => live() && w.rules.canWrite(file),
944
+ describe: () => w.describe,
945
+ close: async () => {
946
+ if (released) return;
947
+ released = true;
948
+ if (--w.users === 0) await inQueue(() => w.teardown());
949
+ },
950
+ };
951
+ }
952
+
953
+ /**
954
+ * Start the walls for one session, or say why they cannot be had. The
955
+ * runtime is one per process: a second open with the same policy gets a
956
+ * handle of its own on the same walls (they come down when the last handle
957
+ * is closed); one with another policy is refused while they are up.
958
+ */
959
+ export function openLocalSandbox(
960
+ policy: LocalSandboxPolicy,
961
+ opts: { platform?: NodeJS.Platform; load?: () => Promise<Runtime> } = {},
962
+ ): Promise<LocalSandbox | SandboxRefusal> {
963
+ return inQueue(() => openNow(policy, opts));
964
+ }
965
+
966
+ async function openNow(policy: LocalSandboxPolicy, opts: { platform?: NodeJS.Platform; load?: () => Promise<Runtime> }): Promise<LocalSandbox | SandboxRefusal> {
967
+ const platform = opts.platform ?? process.platform;
968
+ if (platform === "win32") {
969
+ return { refused: "Windows has no local sandbox for the agent's commands.", hint: "Run foldrun inside WSL2, or send the task to the cloud." };
970
+ }
971
+ if (platform !== "darwin" && platform !== "linux") return { refused: `no local sandbox on ${platform}.`, hint: "Send the task to the cloud." };
972
+ // The launcher and the probe's network check are bash's.
973
+ if (!opts.load && LAUNCHER !== "/bin/bash") return { refused: "the local sandbox needs bash at /bin/bash.", hint: "Install bash, or send the task to the cloud." };
974
+ let isDir = false;
975
+ try {
976
+ isDir = fs.statSync(policy.cwd).isDirectory();
977
+ } catch {
978
+ /* refused below */
979
+ }
980
+ if (!isDir) return { refused: `${policy.cwd} is not a folder that exists.` };
981
+ const cwd = realish(policy.cwd);
982
+ const fold = foldCase(platform);
983
+ // A project folder that holds the home folder (or is /) would make all of
984
+ // it writable: there is no "outside" left to wall off.
985
+ if (within(fold(realish(home())), fold(cwd))) {
986
+ return { refused: `${cwd} holds your home folder — every file in it would be writable.`, hint: "Start foldrun code in a project folder." };
987
+ }
988
+ // One inside a credential folder: on Linux the runtime binds a writable
989
+ // folder back into the folder it hides, so it would show through.
990
+ const denies = [...DENY_READ, ...(policy.denyRead ?? [])].map((p) => fold(realish(expand(p))));
991
+ if (denies.some((d) => within(fold(cwd), d))) return { refused: `${cwd} is inside a folder that holds credentials.`, hint: "Start foldrun code in a project folder." };
992
+ const key = JSON.stringify({ ...policy, cwd });
993
+ if (walls) {
994
+ if (walls.key === key && !walls.down) {
995
+ walls.users++;
996
+ return handleOf(walls);
997
+ }
998
+ return { refused: "another local session's sandbox is open in this process with a different policy." };
999
+ }
1000
+
1001
+ // While the walls are up this process looks programs up only where no
1002
+ // command can write: the runtime starts its helpers by name from here.
1003
+ const ownWrites = RUNTIME_OWN_WRITES.map(expand);
1004
+ const early = [cwd, ...ownWrites].map(realish);
1005
+ // The code that keeps the walls may not sit where a command can write,
1006
+ // nor hold such a folder — checked before any of the runtime is loaded.
1007
+ for (const { what, dir } of installTrees()) {
1008
+ const hit = early.find((root) => overlaps(fold(realish(dir)), fold(root)));
1009
+ if (hit) return { refused: `${what} (${dir}) overlaps ${hit}, a folder a command may write — it could rewrite it before the next run.`, hint: "Install foldrun globally (npm i -g foldrun) and run it from outside the project." };
1010
+ }
1011
+ const helpers = opts.load ? { dir: trustedPath(process.env.PATH, early, platform) } : helperFolder(trustedPath(process.env.PATH, early, platform), early, platform);
1012
+ if ("refused" in helpers) return { refused: helpers.refused, hint: "Install that program outside the project folder." };
1013
+ // And nothing in this process's environment that makes a helper the
1014
+ // runtime starts here load a library or run a file first: the runtime
1015
+ // starts them with this environment.
1016
+ const personEnv: NodeJS.ProcessEnv = { ...process.env };
1017
+ const loaderVars = Object.keys(process.env).filter((k) => LOADER_VARS.test(k));
1018
+ const saved: Record<string, string | undefined> = { PATH: process.env.PATH, CLAUDE_CODE_TMPDIR: process.env.CLAUDE_CODE_TMPDIR };
1019
+ for (const k of loaderVars) saved[k] = process.env[k];
1020
+ const restoreEnv = () => {
1021
+ for (const [k, v] of Object.entries(saved)) {
1022
+ if (v === undefined) delete process.env[k];
1023
+ else process.env[k] = v;
1024
+ }
1025
+ if (!opts.load) fs.rmSync(helpers.dir, { recursive: true, force: true });
1026
+ };
1027
+ process.env.PATH = helpers.dir;
1028
+ for (const k of loaderVars) delete process.env[k];
1029
+ let up: LocalSandbox | SandboxRefusal;
1030
+ try {
1031
+ up = await bringUp(policy, { ...opts, platform }, cwd, key, ownWrites, restoreEnv, personEnv);
1032
+ } catch (err) {
1033
+ up = { refused: `the sandbox could not start: ${err instanceof Error ? err.message : String(err)}` };
1034
+ }
1035
+ if (isRefusal(up)) restoreEnv();
1036
+ return up;
1037
+ }
1038
+
1039
+ async function bringUp(
1040
+ policy: LocalSandboxPolicy,
1041
+ opts: { platform: NodeJS.Platform; load?: () => Promise<Runtime> },
1042
+ cwd: string,
1043
+ key: string,
1044
+ ownWrites: string[],
1045
+ restoreEnv: () => void,
1046
+ personEnv: NodeJS.ProcessEnv,
1047
+ ): Promise<LocalSandbox | SandboxRefusal> {
1048
+ const personPath = personEnv.PATH;
1049
+ const platform = opts.platform;
1050
+ const fold = foldCase(platform);
1051
+ const denies = [...DENY_READ, ...(policy.denyRead ?? [])].map((p) => fold(realish(expand(p))));
1052
+ let rt: Runtime;
1053
+ try {
1054
+ rt = await (opts.load ?? (() => import("@anthropic-ai/sandbox-runtime")))();
1055
+ } catch (err) {
1056
+ return { refused: `the sandbox runtime did not load: ${err instanceof Error ? err.message : String(err)}`, hint: "Reinstall foldrun: npm i -g foldrun@latest" };
1057
+ }
1058
+ const M = rt.SandboxManager;
1059
+ if (!M.isSupportedPlatform()) return { refused: `the sandbox runtime does not support this ${platform} host.` };
1060
+ // This process's PATH is the helper folder now; the Linux helpers are
1061
+ // also pinned to their real files.
1062
+ const trusted = process.env.PATH!;
1063
+ const early = [cwd, ...ownWrites];
1064
+ const pinned = platform === "linux" ? { rg: which("rg", trusted, early), bwrap: which("bwrap", trusted, early), socat: which("socat", trusted, early) } : { rg: null, bwrap: null, socat: null };
1065
+ const deps = M.checkDependencies(pinned.rg ? { command: pinned.rg } : undefined);
1066
+ const userns = () => platform === "linux" && appArmorRestrictsUserns();
1067
+ if (deps.errors.length) return { refused: `the sandbox cannot start: ${deps.errors.join("; ")}`, hint: userns() ? APPARMOR_HINT : installHint(platform) };
1068
+ // Without seccomp a Linux command can reach any Unix socket it can see —
1069
+ // a host service outside the site proxy. Not walls enough to call walls.
1070
+ const noSeccomp = deps.warnings.find((w) => /seccomp/i.test(w));
1071
+ if (platform === "linux" && noSeccomp) return { refused: `the sandbox cannot block Unix sockets here: ${noSeccomp}`, hint: "Use an x86-64 or arm64 machine, where foldrun ships the seccomp filter." };
1072
+
1073
+ const tmp = realish(fs.mkdtempSync(path.join(os.tmpdir(), "foldrun-sbx-")));
1074
+ const rmTmp = () => fs.rmSync(tmp, { recursive: true, force: true });
1075
+ if (denies.some((d) => within(fold(tmp), d))) {
1076
+ rmTmp();
1077
+ return { refused: `the temp folder ${tmp} is inside a folder that holds credentials.` };
1078
+ }
1079
+ const writeRoots = [cwd, tmp, ...ownWrites].map(realish);
1080
+ const hostPATH = process.env.PATH!;
1081
+ // What would let a command change the code that keeps the walls: none of
1082
+ // it may sit in a folder a command may write, nor hold one.
1083
+ for (const { what, dir } of installTrees()) {
1084
+ const hit = writeRoots.find((root) => overlaps(fold(realish(dir)), fold(root)));
1085
+ if (hit) {
1086
+ rmTmp();
1087
+ return { refused: `${what} (${dir}) overlaps ${hit}, a folder a command may write — it could rewrite it before the next run.`, hint: "Install foldrun globally (npm i -g foldrun) and run it from outside the project." };
1088
+ }
1089
+ }
1090
+ const credWrites = [...DENY_READ, ...(policy.denyRead ?? [])].flatMap((p) => [path.resolve(expand(p)), realish(expand(p))]);
1091
+ let protectedWrites: string[];
1092
+ try {
1093
+ // Asked with the person's own PATH (the helper folder is only this
1094
+ // process's): a bare program name in git's settings is found on it.
1095
+ // The person's whole environment as it was (their GIT_EXEC_PATH,
1096
+ // GIT_SSH_COMMAND, PAGER…): what their own next git command will have.
1097
+ protectedWrites = gitProtected(cwd, hostPATH, personEnv, writeRoots);
1098
+ } catch (err) {
1099
+ rmTmp();
1100
+ return { refused: `the git paths to protect could not be found: ${err instanceof Error ? err.message : String(err)}` };
1101
+ }
1102
+
1103
+ // The probe's fixtures, made by the host outside every writable root: a
1104
+ // folder it can write and read (the outside-write check), and a separate
1105
+ // denied one with a "credential" in it (the read check).
1106
+ const fixtureRoot = within(fold(realish(home())), fold(tmp)) ? os.tmpdir() : home();
1107
+ const outsideDir = realish(fs.mkdtempSync(path.join(fixtureRoot, ".foldrun-probe-w-")));
1108
+ const deniedDir = realish(fs.mkdtempSync(path.join(fixtureRoot, ".foldrun-probe-r-")));
1109
+ const secret = path.join(deniedDir, "secret");
1110
+ fs.writeFileSync(secret, "probe");
1111
+ const cleanupProbe = () => {
1112
+ fs.rmSync(outsideDir, { recursive: true, force: true });
1113
+ fs.rmSync(deniedDir, { recursive: true, force: true });
1114
+ };
1115
+ if ([outsideDir, deniedDir].some((p) => [cwd, tmp].some((root) => within(fold(p), fold(root))))) {
1116
+ cleanupProbe();
1117
+ rmTmp();
1118
+ return { refused: "no folder outside the project to prove the walls against." };
1119
+ }
1120
+
1121
+ try {
1122
+ await M.initialize({
1123
+ network: { allowedDomains: [...new Set(policy.sites)], deniedDomains: [] },
1124
+ filesystem: {
1125
+ denyRead: [...DENY_READ, ...(policy.denyRead ?? []), deniedDir].map(lit),
1126
+ allowWrite: [lit(cwd), lit(tmp)],
1127
+ // Credentials are not written either: a project that holds one of
1128
+ // those folders would otherwise grant writes into it.
1129
+ denyWrite: [...new Set([...protectedWrites, ...credWrites])].map(lit),
1130
+ },
1131
+ mandatoryDenySearchDepth: GIT_SEARCH_DEPTH,
1132
+ ...(pinned.rg ? { ripgrep: { command: pinned.rg } } : {}),
1133
+ ...(pinned.bwrap ? { bwrapPath: pinned.bwrap } : {}),
1134
+ ...(pinned.socat ? { socatPath: pinned.socat } : {}),
1135
+ });
1136
+ } catch (err) {
1137
+ cleanupProbe();
1138
+ rmTmp();
1139
+ return { refused: `the sandbox did not start: ${err instanceof Error ? err.message : String(err)}`, hint: userns() ? APPARMOR_HINT : undefined };
1140
+ }
1141
+
1142
+ const backend: SandboxBackend = platform === "darwin" ? "seatbelt" : "bubblewrap";
1143
+ // A wrapped command's TMPDIR is the runtime's, read from this process when
1144
+ // it wraps (CLAUDE_CODE_TMPDIR, else /tmp/claude, which need not exist):
1145
+ // the session's own temp folder instead, restored when it comes down.
1146
+ process.env.CLAUDE_CODE_TMPDIR = tmp;
1147
+ const launcherEnv: Record<string, string> = { PATH: hostPATH, TMPDIR: tmp };
1148
+ for (const k of LAUNCHER_VARS) if (typeof process.env[k] === "string") launcherEnv[k] = process.env[k]!;
1149
+ const w: Walls = {
1150
+ key,
1151
+ gen: ++generation,
1152
+ users: 1,
1153
+ down: false,
1154
+ // Git's protections are found again for every launch: a repository a
1155
+ // command made, or a hooks path it set, since the walls went up counts
1156
+ // from the next command on. Not found = not launched.
1157
+ wrapRaw: async (command) => {
1158
+ // Found first, and a change told (its stale processes ended) before
1159
+ // anything is wrapped, one launch at a time. A discovery that fails
1160
+ // makes every token unverifiable; a listener that cannot end what it
1161
+ // holds refuses the launch.
1162
+ const revoke = async (token: string) => {
1163
+ const done = await Promise.allSettled([...w.listeners].map((l) => Promise.resolve().then(() => l(token))));
1164
+ if (done.some((d) => d.status === "rejected")) throw new Error("a process running under the earlier rules could not be ended");
1165
+ };
1166
+ const step = w.gate.then(async () => {
1167
+ let now: string[];
1168
+ try {
1169
+ now = gitProtected(cwd, hostPATH, personEnv, writeRoots);
1170
+ } catch (err) {
1171
+ w.last = "\0unverifiable";
1172
+ await revoke(w.last).catch(() => undefined);
1173
+ throw err;
1174
+ }
1175
+ w.rules = fileRules({ ...policy, cwd }, tmp, now, platform);
1176
+ const deny = [...new Set([...now, ...credWrites])].sort();
1177
+ const token = deny.join("\0");
1178
+ if (token !== w.last) {
1179
+ await revoke(token);
1180
+ w.last = token;
1181
+ }
1182
+ return { deny, token };
1183
+ });
1184
+ w.gate = step.catch(() => undefined);
1185
+ const { deny, token } = await step;
1186
+ const filesystem = { denyWrite: deny.map(lit) };
1187
+ const line = await M.wrapWithSandbox(command, LAUNCHER, { filesystem } as unknown as Parameters<typeof M.wrapWithSandbox>[2]);
1188
+ // A newer launch found other rules while this one was wrapped: this
1189
+ // line is not handed out.
1190
+ if (w.last !== token) throw new Error("the sandbox's rules changed while the command was being wrapped");
1191
+ return { line, token };
1192
+ },
1193
+ listeners: new Set(),
1194
+ last: "",
1195
+ gate: Promise.resolve(),
1196
+ fingerprint: () => [...new Set([...gitProtected(cwd, hostPATH, personEnv, writeRoots), ...credWrites])].sort().join("\0"),
1197
+ hostEnv: launcherEnv,
1198
+ personPath,
1199
+ rules: fileRules({ ...policy, cwd }, tmp, protectedWrites, platform),
1200
+ backend,
1201
+ tmp,
1202
+ describe:
1203
+ `${backend === "seatbelt" ? "macOS Seatbelt" : "bubblewrap + seccomp"} — writes: ${cwd}, its temp folder and the runtime's own (${RUNTIME_OWN_WRITES.join(", ")}); ` +
1204
+ `never git hooks or config; credentials unreadable; network: ${policy.sites.length} sites through the sandbox's proxy`,
1205
+ teardown: async () => {
1206
+ if (w.down) return;
1207
+ w.down = true;
1208
+ try {
1209
+ await M.reset();
1210
+ } catch {
1211
+ /* already down */
1212
+ }
1213
+ restoreEnv();
1214
+ rmTmp();
1215
+ if (walls === w) walls = null;
1216
+ },
1217
+ };
1218
+ walls = w;
1219
+
1220
+ // The probe: every wall is shown to hold, by an explicit answer from
1221
+ // inside and a check from outside, before anything runs. A write in the
1222
+ // project must land; a write to the outside folder must not; the
1223
+ // credential must not be read; a direct connection to a listener on this
1224
+ // machine (no proxy) must not get through; and the script must finish.
1225
+ let hits = 0;
1226
+ const server = net.createServer((sock) => {
1227
+ hits++;
1228
+ sock.destroy();
1229
+ });
1230
+ try {
1231
+ await new Promise<void>((resolve, reject) => server.listen(0, "127.0.0.1", resolve).once("error", reject));
1232
+ const port = (server.address() as net.AddressInfo).port;
1233
+ // The control: the same connection, unwalled, must get through, or the
1234
+ // check below would pass for a shell that cannot make it at all.
1235
+ const control = await runLine(`(exec 3<>/dev/tcp/127.0.0.1/${port}) && echo NET_OPEN`, cwd, w.hostEnv);
1236
+ for (let i = 0; i < 50 && hits === 0; i++) await new Promise((r) => setTimeout(r, 20));
1237
+ if (!control.out.includes("NET_OPEN") || hits === 0) throw new Error("the network check does not work in this shell");
1238
+ hits = 0;
1239
+ const mark = `.foldrun-sbx-${randomBytes(6).toString("hex")}`;
1240
+ const inside = path.join(cwd, mark);
1241
+ const outside = path.join(outsideDir, "written");
1242
+ const script = [
1243
+ "export PATH=/usr/bin:/bin:/usr/sbin:/sbin",
1244
+ `if touch ${q(inside)} 2>/dev/null; then echo IN_OK; else echo IN_DENIED; fi`,
1245
+ `if (echo x > ${q(outside)}) 2>/dev/null; then echo OUT_WROTE; else echo OUT_DENIED; fi`,
1246
+ `if cat ${q(secret)} >/dev/null 2>&1; then echo READ_OK; else echo READ_DENIED; fi`,
1247
+ `if (exec 3<>/dev/tcp/127.0.0.1/${port}) 2>/dev/null; then echo NET_OPEN; else echo NET_DENIED; fi`,
1248
+ "exit 0",
1249
+ ].join("; ");
1250
+ const { line } = await w.wrapRaw(script);
1251
+ const r = await runLine(line, cwd, w.hostEnv);
1252
+ const said = new Set(r.out.split("\n").map((l) => l.trim()).filter(Boolean));
1253
+ const wrote = fs.existsSync(inside);
1254
+ fs.rmSync(inside, { force: true });
1255
+ const leaked = fs.existsSync(outside);
1256
+ const fails: string[] = [];
1257
+ if (r.code !== 0) fails.push(`the check did not finish (${r.err.split("\n")[0] || `exit ${r.code}`})`);
1258
+ if (!said.has("IN_OK") || !wrote) fails.push("a command could not write the project");
1259
+ if (!said.has("OUT_DENIED") || leaked) fails.push("a write outside the project was not stopped");
1260
+ if (!said.has("READ_DENIED")) fails.push("a credential could be read");
1261
+ if (!said.has("NET_DENIED") || hits > 0) fails.push("a direct connection was not stopped");
1262
+ if (fails.length) {
1263
+ await w.teardown();
1264
+ return { refused: `the sandbox did not hold: ${fails.join("; ")}`, hint: userns() ? APPARMOR_HINT : undefined };
1265
+ }
1266
+ } catch (err) {
1267
+ await w.teardown();
1268
+ return { refused: `the sandbox could not be checked: ${err instanceof Error ? err.message : String(err)}`, hint: userns() ? APPARMOR_HINT : undefined };
1269
+ } finally {
1270
+ server.close();
1271
+ cleanupProbe();
1272
+ }
1273
+ return handleOf(w);
1274
+ }