coremind-tools 1.0.0 → 1.2.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.
Files changed (89) hide show
  1. package/README.md +2 -0
  2. package/dist/index.d.ts +1 -0
  3. package/dist/index.d.ts.map +1 -1
  4. package/dist/index.js.map +1 -1
  5. package/dist/internal.d.ts +5 -1
  6. package/dist/internal.d.ts.map +1 -1
  7. package/dist/internal.js +4 -1
  8. package/dist/internal.js.map +1 -1
  9. package/dist/linux-sandbox-backend.d.ts +33 -0
  10. package/dist/linux-sandbox-backend.d.ts.map +1 -0
  11. package/dist/linux-sandbox-backend.js +119 -0
  12. package/dist/linux-sandbox-backend.js.map +1 -0
  13. package/dist/linux-sandbox.d.ts +2 -2
  14. package/dist/linux-sandbox.d.ts.map +1 -1
  15. package/dist/linux-sandbox.js +5 -19
  16. package/dist/linux-sandbox.js.map +1 -1
  17. package/dist/mcp-authentication-types.d.ts +49 -0
  18. package/dist/mcp-authentication-types.d.ts.map +1 -0
  19. package/dist/mcp-authentication-types.js +2 -0
  20. package/dist/mcp-authentication-types.js.map +1 -0
  21. package/dist/mcp-authentication.d.ts +26 -0
  22. package/dist/mcp-authentication.d.ts.map +1 -0
  23. package/dist/mcp-authentication.js +702 -0
  24. package/dist/mcp-authentication.js.map +1 -0
  25. package/dist/mcp-client.d.ts +74 -0
  26. package/dist/mcp-client.d.ts.map +1 -0
  27. package/dist/mcp-client.js +399 -0
  28. package/dist/mcp-client.js.map +1 -0
  29. package/dist/mcp-http-client.d.ts +18 -0
  30. package/dist/mcp-http-client.d.ts.map +1 -0
  31. package/dist/mcp-http-client.js +21 -0
  32. package/dist/mcp-http-client.js.map +1 -0
  33. package/dist/mcp-http-fetch.d.ts +54 -0
  34. package/dist/mcp-http-fetch.d.ts.map +1 -0
  35. package/dist/mcp-http-fetch.js +603 -0
  36. package/dist/mcp-http-fetch.js.map +1 -0
  37. package/dist/mcp-http-transport.d.ts +31 -0
  38. package/dist/mcp-http-transport.d.ts.map +1 -0
  39. package/dist/mcp-http-transport.js +179 -0
  40. package/dist/mcp-http-transport.js.map +1 -0
  41. package/dist/mcp-stdio-client.d.ts +30 -0
  42. package/dist/mcp-stdio-client.d.ts.map +1 -0
  43. package/dist/mcp-stdio-client.js +17 -0
  44. package/dist/mcp-stdio-client.js.map +1 -0
  45. package/dist/mcp-stdio-error.d.ts +6 -0
  46. package/dist/mcp-stdio-error.d.ts.map +1 -0
  47. package/dist/mcp-stdio-error.js +10 -0
  48. package/dist/mcp-stdio-error.js.map +1 -0
  49. package/dist/mcp-stdio-transport.d.ts +41 -0
  50. package/dist/mcp-stdio-transport.d.ts.map +1 -0
  51. package/dist/mcp-stdio-transport.js +294 -0
  52. package/dist/mcp-stdio-transport.js.map +1 -0
  53. package/dist/platform-execution-environment.d.ts.map +1 -1
  54. package/dist/platform-execution-environment.js +3 -3
  55. package/dist/platform-execution-environment.js.map +1 -1
  56. package/dist/registry.d.ts +4 -0
  57. package/dist/registry.d.ts.map +1 -1
  58. package/dist/registry.js +21 -3
  59. package/dist/registry.js.map +1 -1
  60. package/dist/script-tool.d.ts +1 -1
  61. package/dist/script-tool.d.ts.map +1 -1
  62. package/dist/script-tool.js +4 -2
  63. package/dist/script-tool.js.map +1 -1
  64. package/dist/vendor/linux-sandbox/LICENSE +201 -0
  65. package/dist/vendor/linux-sandbox/backend.d.mts +13 -0
  66. package/dist/vendor/linux-sandbox/backend.mjs +1291 -0
  67. package/dist/vendor/linux-sandbox/bin/arm64/apply-seccomp +0 -0
  68. package/dist/vendor/linux-sandbox/bin/x64/apply-seccomp +0 -0
  69. package/dist/vendor/linux-sandbox/manifest.json +31 -0
  70. package/dist/vendor/linux-sandbox/metafile.json +320 -0
  71. package/dist/vendor/windows-mcp/THIRD-PARTY-LICENSES.txt +408 -0
  72. package/dist/vendor/windows-mcp/guard.dll +0 -0
  73. package/dist/vendor/windows-mcp/host.exe +0 -0
  74. package/dist/vendor/windows-mcp/manifest.json +325 -0
  75. package/dist/vendor/windows-mcp/metafile.json +3894 -0
  76. package/dist/vendor/windows-mcp/service.mjs +7446 -0
  77. package/dist/windows-mcp-job.d.ts +20 -0
  78. package/dist/windows-mcp-job.d.ts.map +1 -0
  79. package/dist/windows-mcp-job.js +353 -0
  80. package/dist/windows-mcp-job.js.map +1 -0
  81. package/dist/windows-mcp-service-identity.d.ts +6 -0
  82. package/dist/windows-mcp-service-identity.d.ts.map +1 -0
  83. package/dist/windows-mcp-service-identity.js +7 -0
  84. package/dist/windows-mcp-service-identity.js.map +1 -0
  85. package/dist/windows-mcp-service.d.mts +2 -0
  86. package/dist/windows-mcp-service.d.mts.map +1 -0
  87. package/dist/windows-mcp-service.mjs +110 -0
  88. package/dist/windows-mcp-service.mjs.map +1 -0
  89. package/package.json +9 -8
@@ -0,0 +1,1291 @@
1
+ // 固定来源的私有 Linux 安全后端;由构建脚本生成,请勿手工修改。
2
+
3
+ // node_modules/@anthropic-ai/sandbox-runtime/dist/utils/shell-quote.js
4
+ function quote(args) {
5
+ return args.map((arg) => {
6
+ if (arg === "") {
7
+ return "''";
8
+ }
9
+ if (/^[A-Za-z0-9_./:@+,-][A-Za-z0-9_./:=@+,-]*$/.test(arg)) {
10
+ return arg;
11
+ }
12
+ return "'" + arg.replace(/'/g, `'"'"'`) + "'";
13
+ }).join(" ");
14
+ }
15
+
16
+ // node_modules/@anthropic-ai/sandbox-runtime/dist/utils/debug.js
17
+ function logForDebugging(message, options) {
18
+ if (!process.env.SRT_DEBUG) {
19
+ return;
20
+ }
21
+ const level = options?.level || "info";
22
+ const prefix = "[SandboxDebug]";
23
+ switch (level) {
24
+ case "error":
25
+ console.error(`${prefix} ${message}`);
26
+ break;
27
+ case "warn":
28
+ console.warn(`${prefix} ${message}`);
29
+ break;
30
+ default:
31
+ console.error(`${prefix} ${message}`);
32
+ }
33
+ }
34
+
35
+ // node_modules/@anthropic-ai/sandbox-runtime/dist/utils/which.js
36
+ import { spawnSync } from "node:child_process";
37
+ function whichSync(bin) {
38
+ if (typeof globalThis.Bun !== "undefined") {
39
+ return globalThis.Bun.which(bin);
40
+ }
41
+ const result = spawnSync("which", [bin], {
42
+ encoding: "utf8",
43
+ stdio: ["ignore", "pipe", "ignore"],
44
+ timeout: 1e3
45
+ });
46
+ if (result.status === 0 && result.stdout) {
47
+ return result.stdout.trim();
48
+ }
49
+ return null;
50
+ }
51
+
52
+ // node_modules/@anthropic-ai/sandbox-runtime/dist/sandbox/linux-sandbox-utils.js
53
+ import * as fs3 from "fs";
54
+ import { tmpdir } from "node:os";
55
+ import path2, { join as join3 } from "node:path";
56
+
57
+ // node_modules/@anthropic-ai/sandbox-runtime/dist/utils/ripgrep.js
58
+ import { spawn } from "child_process";
59
+ import { text } from "node:stream/consumers";
60
+ function hasRipgrepSync() {
61
+ return whichSync("rg") !== null;
62
+ }
63
+ async function ripGrep(args, target, abortSignal, config = { command: "rg" }) {
64
+ const { command, args: commandArgs = [], argv0 } = config;
65
+ const child = spawn(command, [...commandArgs, ...args, target], {
66
+ argv0,
67
+ signal: abortSignal,
68
+ timeout: 1e4,
69
+ windowsHide: true
70
+ });
71
+ const [stdout, stderr, code] = await Promise.all([
72
+ text(child.stdout),
73
+ text(child.stderr),
74
+ new Promise((resolve2, reject) => {
75
+ child.on("close", resolve2);
76
+ child.on("error", reject);
77
+ })
78
+ ]);
79
+ if (code === 0) {
80
+ return stdout.trim().split("\n").filter(Boolean);
81
+ }
82
+ if (code === 1) {
83
+ return [];
84
+ }
85
+ throw new Error(`ripgrep failed with exit code ${code}: ${stderr}`);
86
+ }
87
+
88
+ // node_modules/@anthropic-ai/sandbox-runtime/dist/sandbox/sandbox-utils.js
89
+ import { homedir } from "os";
90
+ import * as path from "path";
91
+ import * as fs from "fs";
92
+
93
+ // node_modules/@anthropic-ai/sandbox-runtime/dist/utils/platform.js
94
+ function getPlatform() {
95
+ switch (process.platform) {
96
+ case "darwin":
97
+ return "macos";
98
+ case "linux":
99
+ return "linux";
100
+ case "win32":
101
+ return "windows";
102
+ default:
103
+ return "unknown";
104
+ }
105
+ }
106
+
107
+ // node_modules/@anthropic-ai/sandbox-runtime/dist/sandbox/sandbox-utils.js
108
+ var DANGEROUS_FILES = [
109
+ ".gitconfig",
110
+ ".gitmodules",
111
+ ".bashrc",
112
+ ".bash_profile",
113
+ ".zshrc",
114
+ ".zprofile",
115
+ ".profile",
116
+ ".ripgreprc",
117
+ ".mcp.json"
118
+ ];
119
+ var DANGEROUS_DIRECTORIES = [".git", ".vscode", ".idea"];
120
+ function getDangerousDirectories() {
121
+ return [
122
+ ...DANGEROUS_DIRECTORIES.filter((d) => d !== ".git"),
123
+ ".claude/commands",
124
+ ".claude/agents"
125
+ ];
126
+ }
127
+ function normalizeCaseForComparison(pathStr) {
128
+ return pathStr.toLowerCase();
129
+ }
130
+ function containsGlobChars(pathPattern) {
131
+ return pathPattern.includes("*") || pathPattern.includes("?") || pathPattern.includes("[") || pathPattern.includes("]");
132
+ }
133
+ function containsGlobCharsWin(p) {
134
+ return p.includes("*") || p.includes("?");
135
+ }
136
+ function containsGlobCharsForPlatform(p) {
137
+ return getPlatform() === "windows" ? containsGlobCharsWin(p) : containsGlobChars(p);
138
+ }
139
+ function stripExtendedPathPrefix(p) {
140
+ if (/^\\\\\?\\unc\\/i.test(p))
141
+ return "\\\\" + p.slice(8);
142
+ if (p.startsWith("\\\\?\\"))
143
+ return p.slice(4);
144
+ return p;
145
+ }
146
+ function isUncPath(p) {
147
+ const ns = path.win32.toNamespacedPath(p);
148
+ return /^[\\/]{2}[?.][\\/]unc[\\/]/i.test(ns);
149
+ }
150
+ function isSymlinkOutsideBoundary(originalPath, resolvedPath) {
151
+ const normalizedOriginal = path.normalize(originalPath);
152
+ const normalizedResolved = path.normalize(resolvedPath);
153
+ if (normalizedResolved === normalizedOriginal) {
154
+ return false;
155
+ }
156
+ if (normalizedOriginal.startsWith("/tmp/") && normalizedResolved === "/private" + normalizedOriginal) {
157
+ return false;
158
+ }
159
+ if (normalizedOriginal.startsWith("/var/") && normalizedResolved === "/private" + normalizedOriginal) {
160
+ return false;
161
+ }
162
+ if (normalizedOriginal.startsWith("/private/tmp/") && normalizedResolved === normalizedOriginal) {
163
+ return false;
164
+ }
165
+ if (normalizedOriginal.startsWith("/private/var/") && normalizedResolved === normalizedOriginal) {
166
+ return false;
167
+ }
168
+ if (normalizedResolved === "/") {
169
+ return true;
170
+ }
171
+ const resolvedParts = normalizedResolved.split("/").filter(Boolean);
172
+ if (resolvedParts.length <= 1) {
173
+ return true;
174
+ }
175
+ if (normalizedOriginal.startsWith(normalizedResolved + "/")) {
176
+ return true;
177
+ }
178
+ let canonicalOriginal = normalizedOriginal;
179
+ if (normalizedOriginal.startsWith("/tmp/")) {
180
+ canonicalOriginal = "/private" + normalizedOriginal;
181
+ } else if (normalizedOriginal.startsWith("/var/")) {
182
+ canonicalOriginal = "/private" + normalizedOriginal;
183
+ }
184
+ if (canonicalOriginal !== normalizedOriginal && canonicalOriginal.startsWith(normalizedResolved + "/")) {
185
+ return true;
186
+ }
187
+ const resolvedStartsWithOriginal = normalizedResolved.startsWith(normalizedOriginal + "/");
188
+ const resolvedStartsWithCanonical = canonicalOriginal !== normalizedOriginal && normalizedResolved.startsWith(canonicalOriginal + "/");
189
+ const resolvedIsCanonical = canonicalOriginal !== normalizedOriginal && normalizedResolved === canonicalOriginal;
190
+ const resolvedIsSame = normalizedResolved === normalizedOriginal;
191
+ if (!resolvedIsSame && !resolvedIsCanonical && !resolvedStartsWithOriginal && !resolvedStartsWithCanonical) {
192
+ return true;
193
+ }
194
+ return false;
195
+ }
196
+ function expandTilde(p) {
197
+ if (p === "~")
198
+ return homedir();
199
+ if (p.startsWith("~/") || process.platform === "win32" && p.startsWith("~\\")) {
200
+ return homedir() + p.slice(1);
201
+ }
202
+ return p;
203
+ }
204
+ function expandWindowsEnvRefs(p) {
205
+ const home = homedir();
206
+ const drive = /^[A-Za-z]:/.test(home) ? home.slice(0, 2) : "";
207
+ const homePath = drive ? home.slice(2) : home;
208
+ return p.replace(/%USERPROFILE%/gi, home).replace(/%HOMEDRIVE%/gi, drive).replace(/%HOMEPATH%/gi, homePath);
209
+ }
210
+ function normalizePathForSandbox(pathPattern) {
211
+ const cwd = process.cwd();
212
+ if (getPlatform() === "windows") {
213
+ pathPattern = stripExtendedPathPrefix(expandWindowsEnvRefs(pathPattern));
214
+ if (/^[a-z]:/.test(pathPattern)) {
215
+ pathPattern = pathPattern[0].toUpperCase() + pathPattern.slice(1);
216
+ }
217
+ if (isUncPath(pathPattern) && !containsGlobCharsWin(pathPattern)) {
218
+ return path.win32.normalize(pathPattern);
219
+ }
220
+ }
221
+ if (getPlatform() !== "windows" && pathPattern.endsWith("/") && pathPattern !== "/" && !containsGlobCharsForPlatform(pathPattern)) {
222
+ pathPattern = pathPattern.replace(/\/+$/, "") || "/";
223
+ }
224
+ let normalizedPath = expandTilde(pathPattern);
225
+ if (normalizedPath !== pathPattern) {
226
+ } else if (pathPattern.startsWith("./") || pathPattern.startsWith("../")) {
227
+ normalizedPath = path.resolve(cwd, pathPattern);
228
+ } else if (!path.isAbsolute(pathPattern)) {
229
+ normalizedPath = path.resolve(cwd, pathPattern);
230
+ }
231
+ if (containsGlobCharsForPlatform(normalizedPath)) {
232
+ const splitRe = getPlatform() === "windows" ? /[*?]/ : /[*?[\]]/;
233
+ const staticPrefix = normalizedPath.split(splitRe)[0];
234
+ if (staticPrefix && staticPrefix !== "/") {
235
+ const baseDir = staticPrefix.endsWith("/") ? staticPrefix.slice(0, -1) : path.dirname(staticPrefix);
236
+ try {
237
+ const resolvedBaseDir = fs.realpathSync(baseDir);
238
+ if (!isSymlinkOutsideBoundary(baseDir, resolvedBaseDir)) {
239
+ const patternSuffix = normalizedPath.slice(baseDir.length);
240
+ return resolvedBaseDir + patternSuffix;
241
+ }
242
+ } catch {
243
+ }
244
+ }
245
+ return normalizedPath;
246
+ }
247
+ try {
248
+ const resolvedPath = fs.realpathSync(normalizedPath);
249
+ if (isSymlinkOutsideBoundary(normalizedPath, resolvedPath)) {
250
+ } else {
251
+ normalizedPath = resolvedPath;
252
+ }
253
+ } catch {
254
+ }
255
+ return normalizedPath;
256
+ }
257
+ function getDefaultWritePaths() {
258
+ const homeDir = homedir();
259
+ const recommendedPaths = [
260
+ "/dev/stdout",
261
+ "/dev/stderr",
262
+ "/dev/null",
263
+ "/dev/tty",
264
+ "/dev/dtracehelper",
265
+ "/dev/autofs_nowait",
266
+ "/tmp/claude",
267
+ "/private/tmp/claude",
268
+ path.join(homeDir, ".npm/_logs"),
269
+ path.join(homeDir, ".claude/debug")
270
+ ];
271
+ return recommendedPaths;
272
+ }
273
+ var CA_TRUST_VARS = [
274
+ "NODE_EXTRA_CA_CERTS",
275
+ "SSL_CERT_FILE",
276
+ "CURL_CA_BUNDLE",
277
+ "REQUESTS_CA_BUNDLE",
278
+ "PIP_CERT",
279
+ "GIT_SSL_CAINFO",
280
+ "AWS_CA_BUNDLE",
281
+ "CARGO_HTTP_CAINFO",
282
+ "DENO_CERT",
283
+ // gcloud ignores SSL_CERT_FILE/REQUESTS_CA_BUNDLE; this is its dedicated
284
+ // override (maps to core/custom_ca_certs_file).
285
+ "CLOUDSDK_CORE_CUSTOM_CA_CERTS_FILE",
286
+ // Nix-built binaries are patched to read this instead of SSL_CERT_FILE, and
287
+ // it's typically pre-set to the Nix system bundle in the parent env, so we
288
+ // must override it explicitly.
289
+ "NIX_SSL_CERT_FILE"
290
+ ];
291
+ function generateProxyEnvVars(httpProxyPort, socksProxyPort, caCertPath, proxyAuthToken, skipTmpdir, encodedCommand) {
292
+ const userRaw = proxyUsernameFor(encodedCommand);
293
+ const userPct = userRaw === PROXY_AUTH_USER ? userRaw : encodeURIComponent(userRaw);
294
+ const auth = proxyAuthToken ? `${userPct}:${proxyAuthToken}@` : "";
295
+ const envVars = [`SANDBOX_RUNTIME=1`];
296
+ if (!skipTmpdir) {
297
+ const tmpdir2 = process.env.CLAUDE_CODE_TMPDIR || process.env.CLAUDE_TMPDIR || "/tmp/claude";
298
+ envVars.push(`TMPDIR=${tmpdir2}`);
299
+ }
300
+ if (caCertPath) {
301
+ for (const v of CA_TRUST_VARS) {
302
+ envVars.push(`${v}=${caCertPath}`);
303
+ }
304
+ }
305
+ if (!httpProxyPort && !socksProxyPort) {
306
+ return envVars;
307
+ }
308
+ const noProxyAddresses = [
309
+ "localhost",
310
+ "127.0.0.1",
311
+ "::1",
312
+ "169.254.0.0/16",
313
+ // Link-local
314
+ "10.0.0.0/8",
315
+ // Private network
316
+ "172.16.0.0/12",
317
+ // Private network
318
+ "192.168.0.0/16"
319
+ // Private network
320
+ ].join(",");
321
+ envVars.push(`NO_PROXY=${noProxyAddresses}`);
322
+ envVars.push(`no_proxy=${noProxyAddresses}`);
323
+ if (httpProxyPort) {
324
+ envVars.push(`HTTP_PROXY=http://${auth}localhost:${httpProxyPort}`);
325
+ envVars.push(`HTTPS_PROXY=http://${auth}localhost:${httpProxyPort}`);
326
+ envVars.push(`http_proxy=http://${auth}localhost:${httpProxyPort}`);
327
+ envVars.push(`https_proxy=http://${auth}localhost:${httpProxyPort}`);
328
+ if (proxyAuthToken) {
329
+ envVars.push(`GIT_CONFIG_PARAMETERS='http.proxyAuthMethod=basic'`);
330
+ }
331
+ }
332
+ const connectProxyUrl = httpProxyPort ? `http://${auth}localhost:${httpProxyPort}` : `socks5h://${auth}localhost:${socksProxyPort}`;
333
+ envVars.push(`ALL_PROXY=${connectProxyUrl}`);
334
+ envVars.push(`all_proxy=${connectProxyUrl}`);
335
+ envVars.push(`GRPC_PROXY=${connectProxyUrl}`);
336
+ envVars.push(`grpc_proxy=${connectProxyUrl}`);
337
+ if (socksProxyPort) {
338
+ const sshMuxOverride = "-o ControlMaster=no -o ControlPath=none";
339
+ const platform = getPlatform();
340
+ if (platform === "macos") {
341
+ envVars.push(`GIT_SSH_COMMAND=ssh ${sshMuxOverride} -o ProxyCommand='nc -X 5 -x localhost:${socksProxyPort} %h %p'`);
342
+ } else if (platform === "linux" && httpProxyPort) {
343
+ const socatAuth = proxyAuthToken ? `,proxyauth=${userRaw}:${proxyAuthToken}` : "";
344
+ envVars.push(`GIT_SSH_COMMAND=ssh ${sshMuxOverride} -o ProxyCommand='socat - PROXY:localhost:%h:%p,proxyport=${httpProxyPort}${socatAuth}'`);
345
+ }
346
+ envVars.push(`FTP_PROXY=socks5h://${auth}localhost:${socksProxyPort}`);
347
+ envVars.push(`ftp_proxy=socks5h://${auth}localhost:${socksProxyPort}`);
348
+ envVars.push(`RSYNC_PROXY=localhost:${socksProxyPort}`);
349
+ envVars.push(`DOCKER_HTTP_PROXY=http://${auth}localhost:${httpProxyPort || socksProxyPort}`);
350
+ envVars.push(`DOCKER_HTTPS_PROXY=http://${auth}localhost:${httpProxyPort || socksProxyPort}`);
351
+ if (httpProxyPort) {
352
+ envVars.push(`CLOUDSDK_PROXY_TYPE=http`);
353
+ envVars.push(`CLOUDSDK_PROXY_ADDRESS=localhost`);
354
+ envVars.push(`CLOUDSDK_PROXY_PORT=${httpProxyPort}`);
355
+ if (proxyAuthToken) {
356
+ envVars.push(`CLOUDSDK_PROXY_USERNAME=${userRaw}`);
357
+ envVars.push(`CLOUDSDK_PROXY_PASSWORD=${proxyAuthToken}`);
358
+ }
359
+ }
360
+ }
361
+ return envVars;
362
+ }
363
+ var SAFE_DIRECTORY_WILDCARD_THRESHOLD = 8;
364
+ function buildGitConfigEnv(opts) {
365
+ if (opts.baseEnv?.GIT_CONFIG_COUNT === "0")
366
+ return {};
367
+ const parsed = Number.parseInt(opts.baseEnv?.GIT_CONFIG_COUNT ?? "", 10);
368
+ const start = Number.isFinite(parsed) && parsed >= 0 ? parsed : 0;
369
+ let n = start;
370
+ const out = {};
371
+ const emit = (key, value) => {
372
+ out[`GIT_CONFIG_KEY_${n}`] = key;
373
+ out[`GIT_CONFIG_VALUE_${n}`] = value;
374
+ n++;
375
+ };
376
+ const dirs = [
377
+ ...new Set(opts.safeDirs.filter((d) => !!d).map((d) => {
378
+ const fwd = d.replace(/\\/g, "/");
379
+ const stripped = fwd.replace(/\/+$/, "");
380
+ if (stripped === "" || /^[A-Za-z]:$/.test(stripped)) {
381
+ return `${stripped}/`;
382
+ }
383
+ return stripped;
384
+ }))
385
+ ];
386
+ if (dirs.length > SAFE_DIRECTORY_WILDCARD_THRESHOLD) {
387
+ emit("safe.directory", "*");
388
+ } else {
389
+ for (const d of dirs) {
390
+ emit("safe.directory", d);
391
+ emit("safe.directory", d.endsWith("/") ? `${d}*` : `${d}/*`);
392
+ }
393
+ }
394
+ if (opts.schannelCa) {
395
+ emit("http.schannelUseSSLCAInfo", "true");
396
+ emit("http.schannelCheckRevoke", "false");
397
+ }
398
+ if (n === start)
399
+ return {};
400
+ out.GIT_CONFIG_COUNT = String(n);
401
+ return out;
402
+ }
403
+ function buildPosixGitSafeDirEnv(opts) {
404
+ const baseEnv = {
405
+ GIT_CONFIG_COUNT: process.env.GIT_CONFIG_COUNT
406
+ };
407
+ for (const k of opts.unsetEnvVars ?? [])
408
+ delete baseEnv[k];
409
+ Object.assign(baseEnv, opts.setEnvVars ?? {});
410
+ return buildGitConfigEnv({ safeDirs: opts.safeDirs, baseEnv });
411
+ }
412
+ function encodeSandboxedCommand(command) {
413
+ const truncatedCommand = command.slice(0, 100);
414
+ return Buffer.from(truncatedCommand).toString("base64");
415
+ }
416
+ var PROXY_AUTH_USER = "srt";
417
+ function proxyUsernameFor(encodedCommand) {
418
+ if (!encodedCommand)
419
+ return PROXY_AUTH_USER;
420
+ const user = `${PROXY_AUTH_USER}.${encodedCommand}`;
421
+ return Buffer.byteLength(user) <= 255 ? user : PROXY_AUTH_USER;
422
+ }
423
+
424
+ // node_modules/@anthropic-ai/sandbox-runtime/dist/sandbox/generate-seccomp-filter.js
425
+ import { join as join2, dirname as dirname2 } from "node:path";
426
+ import { fileURLToPath } from "node:url";
427
+ import * as fs2 from "node:fs";
428
+ import { execSync } from "node:child_process";
429
+ import { homedir as homedir2 } from "node:os";
430
+ var applySeccompPathCache = /* @__PURE__ */ new Map();
431
+ var cachedGlobalNpmPaths = null;
432
+ function getGlobalNpmPaths() {
433
+ if (cachedGlobalNpmPaths)
434
+ return cachedGlobalNpmPaths;
435
+ const paths = [];
436
+ try {
437
+ const npmRoot = execSync("npm root -g", {
438
+ encoding: "utf8",
439
+ timeout: 5e3,
440
+ stdio: ["pipe", "pipe", "ignore"]
441
+ }).trim();
442
+ if (npmRoot) {
443
+ paths.push(join2(npmRoot, "@anthropic-ai", "sandbox-runtime"));
444
+ }
445
+ } catch {
446
+ }
447
+ const home = homedir2();
448
+ paths.push(
449
+ // npm global (Linux/macOS)
450
+ join2("/usr", "lib", "node_modules", "@anthropic-ai", "sandbox-runtime"),
451
+ join2("/usr", "local", "lib", "node_modules", "@anthropic-ai", "sandbox-runtime"),
452
+ // npm global with prefix (common on macOS with homebrew)
453
+ join2("/opt", "homebrew", "lib", "node_modules", "@anthropic-ai", "sandbox-runtime"),
454
+ // User-local npm global
455
+ join2(home, ".npm", "lib", "node_modules", "@anthropic-ai", "sandbox-runtime"),
456
+ join2(home, ".npm-global", "lib", "node_modules", "@anthropic-ai", "sandbox-runtime")
457
+ );
458
+ cachedGlobalNpmPaths = paths;
459
+ return paths;
460
+ }
461
+ function getVendorArchitecture() {
462
+ const arch = process.arch;
463
+ switch (arch) {
464
+ case "x64":
465
+ case "x86_64":
466
+ return "x64";
467
+ case "arm64":
468
+ case "aarch64":
469
+ return "arm64";
470
+ case "ia32":
471
+ case "x86":
472
+ logForDebugging(`[SeccompFilter] 32-bit x86 (ia32) is not currently supported due to missing socketcall() syscall blocking. The current seccomp filter only blocks socket(AF_UNIX, ...), but on 32-bit x86, socketcall() can be used to bypass this.`, { level: "error" });
473
+ return null;
474
+ default:
475
+ logForDebugging(`[SeccompFilter] Unsupported architecture: ${arch}. Only x64 and arm64 are supported.`);
476
+ return null;
477
+ }
478
+ }
479
+ function getLocalSeccompPaths(filename) {
480
+ const arch = getVendorArchitecture();
481
+ if (!arch)
482
+ return [];
483
+ const baseDir = dirname2(fileURLToPath(import.meta.url));
484
+ const relativePath = join2("vendor", "seccomp", arch, filename);
485
+ return [
486
+ join2(baseDir, relativePath),
487
+ // bundled: same directory as bundle (e.g., when bundled into claude-cli)
488
+ join2(baseDir, "..", "..", relativePath),
489
+ // package root: vendor/seccomp/...
490
+ join2(baseDir, "..", relativePath)
491
+ // dist: dist/vendor/seccomp/...
492
+ ];
493
+ }
494
+ function getApplySeccompBinaryPath(seccompBinaryPath) {
495
+ const cacheKey = seccompBinaryPath ?? "";
496
+ if (applySeccompPathCache.has(cacheKey)) {
497
+ return applySeccompPathCache.get(cacheKey);
498
+ }
499
+ const result = findApplySeccompPath(seccompBinaryPath);
500
+ applySeccompPathCache.set(cacheKey, result);
501
+ return result;
502
+ }
503
+ function findApplySeccompPath(seccompBinaryPath) {
504
+ if (seccompBinaryPath) {
505
+ if (fs2.existsSync(seccompBinaryPath)) {
506
+ logForDebugging(`[SeccompFilter] Using apply-seccomp binary from explicit path: ${seccompBinaryPath}`);
507
+ return seccompBinaryPath;
508
+ }
509
+ logForDebugging(`[SeccompFilter] Explicit path provided but file not found: ${seccompBinaryPath}`);
510
+ }
511
+ const arch = getVendorArchitecture();
512
+ if (!arch) {
513
+ logForDebugging(`[SeccompFilter] Cannot find apply-seccomp binary: unsupported architecture ${process.arch}`);
514
+ return null;
515
+ }
516
+ logForDebugging(`[SeccompFilter] Looking for apply-seccomp binary for architecture: ${arch}`);
517
+ for (const binaryPath of getLocalSeccompPaths("apply-seccomp")) {
518
+ if (fs2.existsSync(binaryPath)) {
519
+ logForDebugging(`[SeccompFilter] Found apply-seccomp binary: ${binaryPath} (${arch})`);
520
+ return binaryPath;
521
+ }
522
+ }
523
+ for (const globalBase of getGlobalNpmPaths()) {
524
+ const binaryPath = join2(globalBase, "vendor", "seccomp", arch, "apply-seccomp");
525
+ if (fs2.existsSync(binaryPath)) {
526
+ logForDebugging(`[SeccompFilter] Found apply-seccomp binary in global install: ${binaryPath} (${arch})`);
527
+ return binaryPath;
528
+ }
529
+ }
530
+ logForDebugging(`[SeccompFilter] apply-seccomp binary not found in any expected location (${arch})`);
531
+ return null;
532
+ }
533
+
534
+ // node_modules/@anthropic-ai/sandbox-runtime/dist/sandbox/linux-sandbox-utils.js
535
+ var DEFAULT_MANDATORY_DENY_SEARCH_DEPTH = 3;
536
+ function findSymlinkInPath(targetPath, allowedWritePaths) {
537
+ const parts = targetPath.split(path2.sep);
538
+ let currentPath = "";
539
+ for (const part of parts) {
540
+ if (!part)
541
+ continue;
542
+ const nextPath = currentPath + path2.sep + part;
543
+ try {
544
+ const stats = fs3.lstatSync(nextPath);
545
+ if (stats.isSymbolicLink()) {
546
+ const isWithinAllowedPath = allowedWritePaths.some((allowedPath) => nextPath.startsWith(allowedPath + "/") || nextPath === allowedPath);
547
+ if (isWithinAllowedPath) {
548
+ return nextPath;
549
+ }
550
+ }
551
+ } catch {
552
+ break;
553
+ }
554
+ currentPath = nextPath;
555
+ }
556
+ return null;
557
+ }
558
+ var MAX_SYMLINK_RESOLUTION_DEPTH = 40;
559
+ function resolveSymlinkedDenyPath(targetPath) {
560
+ let current = targetPath;
561
+ for (let i = 0; i < MAX_SYMLINK_RESOLUTION_DEPTH; i++) {
562
+ try {
563
+ return fs3.realpathSync(current);
564
+ } catch {
565
+ }
566
+ let ancestor = current;
567
+ const remainder = [];
568
+ let resolvedAncestor = null;
569
+ while (resolvedAncestor === null) {
570
+ const parent = path2.dirname(ancestor);
571
+ if (parent === ancestor) {
572
+ return null;
573
+ }
574
+ remainder.unshift(path2.basename(ancestor));
575
+ ancestor = parent;
576
+ try {
577
+ resolvedAncestor = fs3.realpathSync(ancestor);
578
+ } catch {
579
+ }
580
+ }
581
+ const firstMissing = path2.join(resolvedAncestor, remainder[0]);
582
+ let linkTarget = null;
583
+ try {
584
+ linkTarget = fs3.readlinkSync(firstMissing);
585
+ } catch {
586
+ }
587
+ if (linkTarget === null) {
588
+ return path2.join(resolvedAncestor, ...remainder);
589
+ }
590
+ current = path2.join(path2.resolve(path2.dirname(firstMissing), linkTarget), ...remainder.slice(1));
591
+ }
592
+ return null;
593
+ }
594
+ function hasFileAncestor(targetPath) {
595
+ const parts = targetPath.split(path2.sep);
596
+ let currentPath = "";
597
+ for (const part of parts) {
598
+ if (!part)
599
+ continue;
600
+ const nextPath = currentPath + path2.sep + part;
601
+ try {
602
+ const stat = fs3.statSync(nextPath);
603
+ if (stat.isFile() || stat.isSymbolicLink()) {
604
+ return true;
605
+ }
606
+ } catch {
607
+ break;
608
+ }
609
+ currentPath = nextPath;
610
+ }
611
+ return false;
612
+ }
613
+ function findFirstNonExistentComponent(targetPath) {
614
+ const parts = targetPath.split(path2.sep);
615
+ let currentPath = "";
616
+ for (const part of parts) {
617
+ if (!part)
618
+ continue;
619
+ const nextPath = currentPath + path2.sep + part;
620
+ if (!fs3.existsSync(nextPath)) {
621
+ return nextPath;
622
+ }
623
+ currentPath = nextPath;
624
+ }
625
+ return targetPath;
626
+ }
627
+ async function linuxGetMandatoryDenyPaths(ripgrepConfig = { command: "rg" }, maxDepth = DEFAULT_MANDATORY_DENY_SEARCH_DEPTH, allowGitConfig = false, abortSignal) {
628
+ const cwd = process.cwd();
629
+ const fallbackController = new AbortController();
630
+ const signal = abortSignal ?? fallbackController.signal;
631
+ const dangerousDirectories = getDangerousDirectories();
632
+ const denyPaths = [
633
+ // Dangerous files in CWD
634
+ ...DANGEROUS_FILES.map((f) => path2.resolve(cwd, f)),
635
+ // Dangerous directories in CWD
636
+ ...dangerousDirectories.map((d) => path2.resolve(cwd, d))
637
+ ];
638
+ const dotGitPath = path2.resolve(cwd, ".git");
639
+ let dotGitIsDirectory = false;
640
+ try {
641
+ dotGitIsDirectory = fs3.statSync(dotGitPath).isDirectory();
642
+ } catch {
643
+ }
644
+ if (dotGitIsDirectory) {
645
+ denyPaths.push(path2.resolve(cwd, ".git/hooks"));
646
+ if (!allowGitConfig) {
647
+ denyPaths.push(path2.resolve(cwd, ".git/config"));
648
+ }
649
+ }
650
+ const iglobArgs = [];
651
+ for (const fileName of DANGEROUS_FILES) {
652
+ iglobArgs.push("--iglob", fileName);
653
+ }
654
+ for (const dirName of dangerousDirectories) {
655
+ iglobArgs.push("--iglob", `**/${dirName}/**`);
656
+ }
657
+ iglobArgs.push("--iglob", "**/.git/hooks/**");
658
+ if (!allowGitConfig) {
659
+ iglobArgs.push("--iglob", "**/.git/config");
660
+ }
661
+ let matches = [];
662
+ try {
663
+ matches = await ripGrep([
664
+ "--files",
665
+ "--hidden",
666
+ "--max-depth",
667
+ String(maxDepth),
668
+ ...iglobArgs,
669
+ "-g",
670
+ "!**/node_modules/**"
671
+ ], cwd, signal, ripgrepConfig);
672
+ } catch (error) {
673
+ logForDebugging(`[Sandbox] ripgrep scan failed: ${error}`);
674
+ }
675
+ for (const match of matches) {
676
+ const absolutePath = path2.resolve(cwd, match);
677
+ let foundDir = false;
678
+ for (const dirName of [...dangerousDirectories, ".git"]) {
679
+ const normalizedDirName = normalizeCaseForComparison(dirName);
680
+ const segments = absolutePath.split(path2.sep);
681
+ const dirIndex = segments.findIndex((s) => normalizeCaseForComparison(s) === normalizedDirName);
682
+ if (dirIndex !== -1) {
683
+ if (dirName === ".git") {
684
+ const gitDir = segments.slice(0, dirIndex + 1).join(path2.sep);
685
+ if (match.includes(".git/hooks")) {
686
+ denyPaths.push(path2.join(gitDir, "hooks"));
687
+ } else if (match.includes(".git/config")) {
688
+ denyPaths.push(path2.join(gitDir, "config"));
689
+ }
690
+ } else {
691
+ denyPaths.push(segments.slice(0, dirIndex + 1).join(path2.sep));
692
+ }
693
+ foundDir = true;
694
+ break;
695
+ }
696
+ }
697
+ if (!foundDir) {
698
+ denyPaths.push(absolutePath);
699
+ }
700
+ }
701
+ return [...new Set(denyPaths)];
702
+ }
703
+ var bwrapMountPoints = /* @__PURE__ */ new Set();
704
+ var activeSandboxCount = 0;
705
+ var exitHandlerRegistered = false;
706
+ function registerExitCleanupHandler() {
707
+ if (exitHandlerRegistered) {
708
+ return;
709
+ }
710
+ process.on("exit", () => {
711
+ cleanupBwrapMountPoints({ force: true });
712
+ });
713
+ exitHandlerRegistered = true;
714
+ }
715
+ function cleanupBwrapMountPoints(opts) {
716
+ if (!opts?.force) {
717
+ if (activeSandboxCount > 0) {
718
+ activeSandboxCount--;
719
+ }
720
+ if (activeSandboxCount > 0) {
721
+ logForDebugging(`[Sandbox Linux] Deferring mount point cleanup \u2014 ${activeSandboxCount} sandbox(es) still active`);
722
+ return;
723
+ }
724
+ } else {
725
+ activeSandboxCount = 0;
726
+ }
727
+ for (const mountPoint of bwrapMountPoints) {
728
+ try {
729
+ const stat = fs3.statSync(mountPoint);
730
+ if (stat.isFile() && stat.size === 0) {
731
+ fs3.unlinkSync(mountPoint);
732
+ logForDebugging(`[Sandbox Linux] Cleaned up bwrap mount point (file): ${mountPoint}`);
733
+ } else if (stat.isDirectory()) {
734
+ const entries = fs3.readdirSync(mountPoint);
735
+ if (entries.length === 0) {
736
+ fs3.rmdirSync(mountPoint);
737
+ logForDebugging(`[Sandbox Linux] Cleaned up bwrap mount point (dir): ${mountPoint}`);
738
+ }
739
+ }
740
+ } catch {
741
+ }
742
+ }
743
+ bwrapMountPoints.clear();
744
+ }
745
+ function isExecutable(p) {
746
+ try {
747
+ fs3.accessSync(p, fs3.constants.X_OK);
748
+ return true;
749
+ } catch {
750
+ return false;
751
+ }
752
+ }
753
+ function checkLinuxDependencies(opts) {
754
+ const { seccompConfig, bwrapPath, socatPath } = opts ?? {};
755
+ const errors = [];
756
+ const warnings = [];
757
+ if (bwrapPath) {
758
+ if (!isExecutable(bwrapPath))
759
+ errors.push(`bubblewrap (bwrap) not executable at ${bwrapPath}`);
760
+ } else if (whichSync("bwrap") === null) {
761
+ errors.push("bubblewrap (bwrap) not installed");
762
+ }
763
+ if (socatPath) {
764
+ if (!isExecutable(socatPath))
765
+ errors.push(`socat not executable at ${socatPath}`);
766
+ } else if (whichSync("socat") === null) {
767
+ errors.push("socat not installed");
768
+ }
769
+ if (!seccompConfig?.argv0 && getApplySeccompBinaryPath(seccompConfig?.applyPath) === null) {
770
+ warnings.push("seccomp not available - unix socket access not restricted");
771
+ }
772
+ return { warnings, errors };
773
+ }
774
+ function resolveApplySeccompPrefix(applyPath, argv0) {
775
+ if (argv0) {
776
+ if (!applyPath) {
777
+ throw new Error("seccompConfig.argv0 requires seccompConfig.applyPath");
778
+ }
779
+ return `ARGV0=${quote([argv0])} ${quote([applyPath])} `;
780
+ }
781
+ const binary = getApplySeccompBinaryPath(applyPath);
782
+ return binary ? `${quote([binary])} ` : void 0;
783
+ }
784
+ function buildSandboxCommand(httpSocketPath, socksSocketPath, userCommand, applySeccompPrefix, shell, socatPath) {
785
+ const shellPath = shell || "bash";
786
+ const socat = quote([socatPath ?? "socat"]);
787
+ const socatCommands = [
788
+ `${socat} TCP-LISTEN:3128,fork,reuseaddr UNIX-CONNECT:${httpSocketPath} >/dev/null 2>&1 &`,
789
+ `${socat} TCP-LISTEN:1080,fork,reuseaddr UNIX-CONNECT:${socksSocketPath} >/dev/null 2>&1 &`,
790
+ 'trap "kill %1 %2 2>/dev/null; exit" EXIT'
791
+ ];
792
+ if (applySeccompPrefix) {
793
+ const applySeccompCmd = applySeccompPrefix + quote([shellPath, "-c", userCommand]);
794
+ const innerScript = [...socatCommands, applySeccompCmd].join("\n");
795
+ return `${shellPath} -c ${quote([innerScript])}`;
796
+ } else {
797
+ const innerScript = [...socatCommands, `eval ${quote([userCommand])}`].join("\n");
798
+ return `${shellPath} -c ${quote([innerScript])}`;
799
+ }
800
+ }
801
+ function resolveSymlinkDenyDest(normalizedPath) {
802
+ try {
803
+ if (fs3.lstatSync(normalizedPath).isSymbolicLink()) {
804
+ return fs3.realpathSync(normalizedPath);
805
+ }
806
+ } catch {
807
+ }
808
+ return normalizedPath;
809
+ }
810
+ function pushReadDenyDirMounts(args, normalizedPath, allowedWritePaths, readAllowPaths) {
811
+ const denySep = normalizedPath === "/" ? "/" : normalizedPath + "/";
812
+ args.push("--tmpfs", normalizedPath);
813
+ for (const writePath of allowedWritePaths) {
814
+ if (writePath.startsWith(denySep) || writePath === normalizedPath) {
815
+ args.push("--bind", writePath, writePath);
816
+ logForDebugging(`[Sandbox Linux] Re-bound write path wiped by denyRead tmpfs: ${writePath}`);
817
+ }
818
+ }
819
+ for (const allowPath of readAllowPaths) {
820
+ if (allowPath.startsWith(denySep) || allowPath === normalizedPath) {
821
+ if (!fs3.existsSync(allowPath)) {
822
+ logForDebugging(`[Sandbox Linux] Skipping non-existent read allow path: ${allowPath}`);
823
+ continue;
824
+ }
825
+ if (allowedWritePaths.some((w) => (w.startsWith(denySep) || w === normalizedPath) && (allowPath === w || allowPath.startsWith(w + "/")))) {
826
+ continue;
827
+ }
828
+ args.push("--ro-bind", allowPath, allowPath);
829
+ logForDebugging(`[Sandbox Linux] Re-allowed read access within denied region: ${allowPath}`);
830
+ }
831
+ }
832
+ }
833
+ async function generateFilesystemArgs(readConfig, writeConfig, maskedFileBinds, maskedFileStoreDir, ripgrepConfig = { command: "rg" }, mandatoryDenySearchDepth = DEFAULT_MANDATORY_DENY_SEARCH_DEPTH, allowGitConfig = false, abortSignal) {
834
+ const args = [];
835
+ const allowedWritePaths = [];
836
+ const denyWriteArgs = [];
837
+ const readOnlyDenyDirSpellings = /* @__PURE__ */ new Map();
838
+ const denyWriteRawDests = /* @__PURE__ */ new Map();
839
+ if (writeConfig) {
840
+ args.push("--ro-bind", "/", "/");
841
+ for (const pathPattern of writeConfig.allowOnly || []) {
842
+ const normalizedPath = normalizePathForSandbox(pathPattern).replace(/\/+$/, "") || "/";
843
+ logForDebugging(`[Sandbox Linux] Processing write path: ${pathPattern} -> ${normalizedPath}`);
844
+ if (normalizedPath.startsWith("/dev/")) {
845
+ logForDebugging(`[Sandbox Linux] Skipping /dev path: ${normalizedPath}`);
846
+ continue;
847
+ }
848
+ if (!fs3.existsSync(normalizedPath)) {
849
+ logForDebugging(`[Sandbox Linux] Skipping non-existent write path: ${normalizedPath}`);
850
+ continue;
851
+ }
852
+ try {
853
+ const resolvedPath = fs3.realpathSync(normalizedPath);
854
+ const normalizedForComparison = normalizedPath.replace(/\/+$/, "");
855
+ if (resolvedPath !== normalizedForComparison && isSymlinkOutsideBoundary(normalizedPath, resolvedPath)) {
856
+ logForDebugging(`[Sandbox Linux] Skipping symlink write path pointing outside expected location: ${pathPattern} -> ${resolvedPath}`);
857
+ continue;
858
+ }
859
+ } catch {
860
+ logForDebugging(`[Sandbox Linux] Skipping write path that could not be resolved: ${normalizedPath}`);
861
+ continue;
862
+ }
863
+ args.push("--bind", normalizedPath, normalizedPath);
864
+ allowedWritePaths.push(normalizedPath);
865
+ }
866
+ let stubSkipVetoInputs;
867
+ const getStubSkipVetoInputs = () => {
868
+ if (stubSkipVetoInputs !== void 0) {
869
+ return stubSkipVetoInputs;
870
+ }
871
+ const allowedWritePathsBothForms = [];
872
+ for (const writePath of allowedWritePaths) {
873
+ allowedWritePathsBothForms.push(writePath);
874
+ try {
875
+ const canonical = fs3.realpathSync(writePath);
876
+ if (canonical !== writePath) {
877
+ allowedWritePathsBothForms.push(canonical);
878
+ }
879
+ } catch {
880
+ }
881
+ }
882
+ const prospectiveReadDenyTmpfsDirsBothForms = [];
883
+ if (readConfig) {
884
+ const effectiveReadDenyPaths = [];
885
+ const rootSkipForGuard = /* @__PURE__ */ new Set(["proc", "dev", "sys"]);
886
+ for (const denyReadPattern of readConfig.denyOnly || []) {
887
+ if (normalizePathForSandbox(denyReadPattern) === "/") {
888
+ try {
889
+ for (const child of fs3.readdirSync("/")) {
890
+ if (!rootSkipForGuard.has(child))
891
+ effectiveReadDenyPaths.push("/" + child);
892
+ }
893
+ } catch {
894
+ }
895
+ } else {
896
+ effectiveReadDenyPaths.push(denyReadPattern);
897
+ }
898
+ }
899
+ if (fs3.existsSync("/etc/ssh/ssh_config.d")) {
900
+ effectiveReadDenyPaths.push("/etc/ssh/ssh_config.d");
901
+ }
902
+ for (const effectiveReadDenyPath of effectiveReadDenyPaths) {
903
+ const denyReadPath = normalizePathForSandbox(effectiveReadDenyPath);
904
+ let isDirectory = false;
905
+ try {
906
+ isDirectory = fs3.statSync(denyReadPath).isDirectory();
907
+ } catch {
908
+ continue;
909
+ }
910
+ if (!isDirectory) {
911
+ continue;
912
+ }
913
+ prospectiveReadDenyTmpfsDirsBothForms.push(denyReadPath);
914
+ try {
915
+ const canonical = fs3.realpathSync(denyReadPath);
916
+ if (canonical !== denyReadPath) {
917
+ prospectiveReadDenyTmpfsDirsBothForms.push(canonical);
918
+ }
919
+ } catch {
920
+ }
921
+ }
922
+ }
923
+ stubSkipVetoInputs = {
924
+ allowedWritePathsBothForms,
925
+ prospectiveReadDenyTmpfsDirsBothForms
926
+ };
927
+ return stubSkipVetoInputs;
928
+ };
929
+ const isWithinAnyAllowedWritePath = (candidatePath) => allowedWritePaths.some((allowedPath) => candidatePath.startsWith(allowedPath + "/") || candidatePath === allowedPath);
930
+ const denyPaths = [
931
+ ...writeConfig.denyWithinAllow || [],
932
+ ...await linuxGetMandatoryDenyPaths(ripgrepConfig, mandatoryDenySearchDepth, allowGitConfig, abortSignal)
933
+ ];
934
+ const seenDenyWrite = /* @__PURE__ */ new Set();
935
+ for (const pathPattern of denyPaths) {
936
+ const rawPath = normalizePathForSandbox(pathPattern);
937
+ if (rawPath.startsWith("/dev/")) {
938
+ continue;
939
+ }
940
+ const resolvedPath = resolveSymlinkedDenyPath(rawPath);
941
+ if (resolvedPath === null || resolvedPath.startsWith("/dev/")) {
942
+ continue;
943
+ }
944
+ if (findSymlinkInPath(resolvedPath, allowedWritePaths)) {
945
+ continue;
946
+ }
947
+ let isDirectory = false;
948
+ try {
949
+ isDirectory = fs3.statSync(resolvedPath).isDirectory();
950
+ } catch {
951
+ continue;
952
+ }
953
+ if (!isDirectory) {
954
+ continue;
955
+ }
956
+ if (isWithinAnyAllowedWritePath(resolvedPath)) {
957
+ let spellings = readOnlyDenyDirSpellings.get(resolvedPath);
958
+ if (spellings === void 0) {
959
+ spellings = /* @__PURE__ */ new Set();
960
+ readOnlyDenyDirSpellings.set(resolvedPath, spellings);
961
+ }
962
+ spellings.add(rawPath);
963
+ }
964
+ }
965
+ const coveringDirUnsafeVerdicts = /* @__PURE__ */ new Map();
966
+ const coveringDirIsUnsafe = (denyDir) => {
967
+ const cached = coveringDirUnsafeVerdicts.get(denyDir);
968
+ if (cached !== void 0) {
969
+ return cached;
970
+ }
971
+ const { allowedWritePathsBothForms, prospectiveReadDenyTmpfsDirsBothForms } = getStubSkipVetoInputs();
972
+ const unsafe = (
973
+ // (i) an allowed write path strictly beneath the dir: the
974
+ // re-application's effect would re-bind it writable.
975
+ allowedWritePathsBothForms.some((writePath) => writePath.startsWith(denyDir + "/")) || // (ii) a read-deny tmpfs at or beneath the dir: the re-application's
976
+ // trigger.
977
+ prospectiveReadDenyTmpfsDirsBothForms.some((tmpfsDir) => tmpfsDir === denyDir || tmpfsDir.startsWith(denyDir + "/")) || // (iii) a read-deny tmpfs CONTAINING the dir or any raw spelling it
978
+ // was reached through: the dir's own --ro-bind can be dropped as
979
+ // hidden-by-the-tmpfs at emission, and a tmpfs above it can
980
+ // re-bind an allowed path around it — either way the directory
981
+ // is not reliably read-only in the sandbox.
982
+ prospectiveReadDenyTmpfsDirsBothForms.some((tmpfsDir) => [denyDir, ...readOnlyDenyDirSpellings.get(denyDir) ?? []].some((spelling) => spelling === tmpfsDir || spelling.startsWith(tmpfsDir + "/")))
983
+ );
984
+ coveringDirUnsafeVerdicts.set(denyDir, unsafe);
985
+ return unsafe;
986
+ };
987
+ const readOnlyDenyDirs = [...readOnlyDenyDirSpellings.keys()];
988
+ for (const pathPattern of denyPaths) {
989
+ const rawPath = normalizePathForSandbox(pathPattern);
990
+ if (rawPath.startsWith("/dev/")) {
991
+ continue;
992
+ }
993
+ const normalizedPath = resolveSymlinkedDenyPath(rawPath);
994
+ if (normalizedPath === null) {
995
+ const unresolvableSymlink = findSymlinkInPath(rawPath, allowedWritePaths);
996
+ if (unresolvableSymlink && !seenDenyWrite.has(unresolvableSymlink)) {
997
+ seenDenyWrite.add(unresolvableSymlink);
998
+ denyWriteArgs.push("--ro-bind", "/dev/null", unresolvableSymlink);
999
+ denyWriteRawDests.set(unresolvableSymlink, rawPath);
1000
+ }
1001
+ logForDebugging(`[Sandbox Linux] Deny path could not be resolved through symlinks, failing closed: ${rawPath}`);
1002
+ continue;
1003
+ }
1004
+ if (normalizedPath !== rawPath) {
1005
+ logForDebugging(`[Sandbox Linux] Resolved symlinked deny path: ${rawPath} -> ${normalizedPath}`);
1006
+ }
1007
+ if (normalizedPath.startsWith("/dev/")) {
1008
+ continue;
1009
+ }
1010
+ if (seenDenyWrite.has(normalizedPath))
1011
+ continue;
1012
+ seenDenyWrite.add(normalizedPath);
1013
+ const symlinkInPath = findSymlinkInPath(normalizedPath, allowedWritePaths);
1014
+ if (symlinkInPath) {
1015
+ if (!seenDenyWrite.has(symlinkInPath)) {
1016
+ seenDenyWrite.add(symlinkInPath);
1017
+ denyWriteArgs.push("--ro-bind", "/dev/null", symlinkInPath);
1018
+ denyWriteRawDests.set(symlinkInPath, rawPath);
1019
+ }
1020
+ logForDebugging(`[Sandbox Linux] Mounted /dev/null at symlink ${symlinkInPath} to prevent symlink replacement attack`);
1021
+ continue;
1022
+ }
1023
+ if (!fs3.existsSync(normalizedPath)) {
1024
+ if (hasFileAncestor(normalizedPath)) {
1025
+ logForDebugging(`[Sandbox Linux] Skipping deny path with file ancestor (cannot create paths under a file): ${normalizedPath}`);
1026
+ continue;
1027
+ }
1028
+ let ancestorPath = path2.dirname(normalizedPath);
1029
+ while (ancestorPath !== "/" && !fs3.existsSync(ancestorPath)) {
1030
+ ancestorPath = path2.dirname(ancestorPath);
1031
+ }
1032
+ const ancestorIsWithinAllowedPath = isWithinAnyAllowedWritePath(ancestorPath) || isWithinAnyAllowedWritePath(normalizedPath);
1033
+ const coveringReadOnlyDenyDirs = readOnlyDenyDirs.filter((denyDir) => ancestorPath === denyDir || ancestorPath.startsWith(denyDir + "/"));
1034
+ const ancestorIsWithinReadOnlyDeny = coveringReadOnlyDenyDirs.length > 0 && !coveringReadOnlyDenyDirs.some(coveringDirIsUnsafe);
1035
+ if (ancestorIsWithinAllowedPath && !ancestorIsWithinReadOnlyDeny) {
1036
+ const firstNonExistent = findFirstNonExistentComponent(normalizedPath);
1037
+ if (firstNonExistent !== normalizedPath) {
1038
+ const emptyDir = fs3.mkdtempSync(path2.join(tmpdir(), "claude-empty-"));
1039
+ denyWriteArgs.push("--ro-bind", emptyDir, firstNonExistent);
1040
+ denyWriteRawDests.set(firstNonExistent, rawPath);
1041
+ bwrapMountPoints.add(firstNonExistent);
1042
+ registerExitCleanupHandler();
1043
+ logForDebugging(`[Sandbox Linux] Mounted empty dir at ${firstNonExistent} to block creation of ${normalizedPath}`);
1044
+ } else {
1045
+ denyWriteArgs.push("--ro-bind", "/dev/null", firstNonExistent);
1046
+ denyWriteRawDests.set(firstNonExistent, rawPath);
1047
+ bwrapMountPoints.add(firstNonExistent);
1048
+ registerExitCleanupHandler();
1049
+ logForDebugging(`[Sandbox Linux] Mounted /dev/null at ${firstNonExistent} to block creation of ${normalizedPath}`);
1050
+ }
1051
+ } else if (ancestorIsWithinReadOnlyDeny) {
1052
+ logForDebugging(`[Sandbox Linux] Skipping non-existent deny path inside a read-only denied directory (already uncreatable): ${normalizedPath}`);
1053
+ } else {
1054
+ logForDebugging(`[Sandbox Linux] Skipping non-existent deny path not within allowed paths: ${normalizedPath}`);
1055
+ }
1056
+ continue;
1057
+ }
1058
+ const isWithinAllowedPath = isWithinAnyAllowedWritePath(normalizedPath);
1059
+ if (isWithinAllowedPath) {
1060
+ denyWriteArgs.push("--ro-bind", normalizedPath, normalizedPath);
1061
+ denyWriteRawDests.set(normalizedPath, rawPath);
1062
+ } else {
1063
+ logForDebugging(`[Sandbox Linux] Skipping deny path not within allowed paths: ${normalizedPath}`);
1064
+ }
1065
+ }
1066
+ } else {
1067
+ args.push("--bind", "/", "/");
1068
+ }
1069
+ const readDenyPaths = [];
1070
+ const readAllowPaths = (readConfig?.allowWithinDeny || []).map((p) => normalizePathForSandbox(p));
1071
+ const maskedFiles = /* @__PURE__ */ new Map();
1072
+ const tmpfsDirs = [];
1073
+ const rootSkip = /* @__PURE__ */ new Set(["proc", "dev", "sys"]);
1074
+ for (const p of readConfig?.denyOnly || []) {
1075
+ if (normalizePathForSandbox(p) === "/") {
1076
+ for (const child of fs3.readdirSync("/")) {
1077
+ if (!rootSkip.has(child))
1078
+ readDenyPaths.push("/" + child);
1079
+ }
1080
+ } else {
1081
+ readDenyPaths.push(p);
1082
+ }
1083
+ }
1084
+ if (readConfig && fs3.existsSync("/etc/ssh/ssh_config.d")) {
1085
+ readDenyPaths.push("/etc/ssh/ssh_config.d");
1086
+ }
1087
+ const normalizedDenyPaths = readDenyPaths.map((p) => normalizePathForSandbox(p)).sort((a, b) => a.split("/").length - b.split("/").length);
1088
+ for (const normalizedPath of normalizedDenyPaths) {
1089
+ if (!fs3.existsSync(normalizedPath)) {
1090
+ logForDebugging(`[Sandbox Linux] Skipping non-existent read deny path: ${normalizedPath}`);
1091
+ continue;
1092
+ }
1093
+ const readDenyStat = fs3.statSync(normalizedPath);
1094
+ if (readDenyStat.isDirectory()) {
1095
+ tmpfsDirs.push(normalizedPath);
1096
+ pushReadDenyDirMounts(args, normalizedPath, allowedWritePaths, readAllowPaths);
1097
+ } else {
1098
+ if (readAllowPaths.includes(normalizedPath)) {
1099
+ logForDebugging(`[Sandbox Linux] Skipping read deny for re-allowed path: ${normalizedPath}`);
1100
+ continue;
1101
+ }
1102
+ const denyDest = resolveSymlinkDenyDest(normalizedPath);
1103
+ args.push("--ro-bind", "/dev/null", denyDest);
1104
+ maskedFiles.set(denyDest, "/dev/null");
1105
+ maskedFiles.set(normalizedPath, "/dev/null");
1106
+ }
1107
+ }
1108
+ for (const { realPath, fakePath } of maskedFileBinds ?? []) {
1109
+ const dest = resolveSymlinkDenyDest(realPath);
1110
+ args.push("--ro-bind", fakePath, dest);
1111
+ maskedFiles.set(dest, fakePath);
1112
+ maskedFiles.set(realPath, fakePath);
1113
+ }
1114
+ const isHiddenByTmpfs = (dest) => tmpfsDirs.some((tmpfsDir) => {
1115
+ const underTmpfs = dest === tmpfsDir || dest.startsWith(tmpfsDir + "/");
1116
+ if (!underTmpfs)
1117
+ return false;
1118
+ const reExposedByWriteBind = allowedWritePaths.some((writePath) => (writePath === tmpfsDir || writePath.startsWith(tmpfsDir + "/")) && (dest === writePath || dest.startsWith(writePath + "/")));
1119
+ return !reExposedByWriteBind;
1120
+ });
1121
+ const emittedDenyWriteDests = [];
1122
+ for (let i = 0; i < denyWriteArgs.length; i += 3) {
1123
+ const dest = denyWriteArgs[i + 2];
1124
+ const rawDest = denyWriteRawDests.get(dest) ?? dest;
1125
+ if (maskedFiles.has(dest))
1126
+ continue;
1127
+ if (isHiddenByTmpfs(dest) || isHiddenByTmpfs(rawDest)) {
1128
+ logForDebugging(`[Sandbox Linux] Skipping denyWrite bind already hidden by denyRead tmpfs: ${dest}`);
1129
+ continue;
1130
+ }
1131
+ args.push(denyWriteArgs[i], denyWriteArgs[i + 1], dest);
1132
+ emittedDenyWriteDests.push(dest);
1133
+ if (rawDest !== dest)
1134
+ emittedDenyWriteDests.push(rawDest);
1135
+ }
1136
+ for (const tmpfsDir of tmpfsDirs) {
1137
+ if (emittedDenyWriteDests.some((dest) => tmpfsDir.startsWith(dest + "/"))) {
1138
+ logForDebugging(`[Sandbox Linux] Re-applying denyRead tmpfs re-exposed by denyWrite bind: ${tmpfsDir}`);
1139
+ pushReadDenyDirMounts(args, tmpfsDir, allowedWritePaths, readAllowPaths);
1140
+ }
1141
+ }
1142
+ for (const [maskedFile, source] of maskedFiles) {
1143
+ if (emittedDenyWriteDests.some((dest) => maskedFile.startsWith(dest + "/"))) {
1144
+ if (resolveSymlinkDenyDest(maskedFile) !== maskedFile)
1145
+ continue;
1146
+ logForDebugging(`[Sandbox Linux] Re-applying file mask re-exposed by denyWrite bind: ${maskedFile}`);
1147
+ args.push("--ro-bind", source, maskedFile);
1148
+ }
1149
+ }
1150
+ if (maskedFileStoreDir !== void 0) {
1151
+ args.push("--ro-bind", maskedFileStoreDir, maskedFileStoreDir);
1152
+ }
1153
+ return args;
1154
+ }
1155
+ async function wrapCommandWithSandboxLinux(params) {
1156
+ const { command, commandId, needsNetworkRestriction, httpSocketPath, socksSocketPath, httpProxyPort, socksProxyPort, proxyAuthToken, caCertPath, readConfig, writeConfig, unsetEnvVars, setEnvVars, maskedFileBinds, maskedFileStoreDir, enableWeakerNestedSandbox, allowAllUnixSockets, binShell, ripgrepConfig = { command: "rg" }, mandatoryDenySearchDepth = DEFAULT_MANDATORY_DENY_SEARCH_DEPTH, allowGitConfig = false, gitSafeDirectories, seccompConfig, bwrapPath, socatPath, observeSocketPath, abortSignal } = params;
1157
+ const hasReadRestrictions = readConfig && readConfig.denyOnly.length > 0 || maskedFileBinds !== void 0 && maskedFileBinds.length > 0;
1158
+ const hasWriteRestrictions = writeConfig !== void 0;
1159
+ const hasEnvRestrictions = unsetEnvVars !== void 0 && unsetEnvVars.length > 0 || setEnvVars !== void 0 && Object.keys(setEnvVars).length > 0;
1160
+ const hasGitConfig = (gitSafeDirectories?.length ?? 0) > 0;
1161
+ if (!needsNetworkRestriction && !hasReadRestrictions && !hasWriteRestrictions && !hasEnvRestrictions && !hasGitConfig) {
1162
+ return command;
1163
+ }
1164
+ activeSandboxCount++;
1165
+ const bwrapArgs = ["--new-session", "--die-with-parent"];
1166
+ let applySeccompPrefix;
1167
+ try {
1168
+ if (!allowAllUnixSockets) {
1169
+ applySeccompPrefix = resolveApplySeccompPrefix(seccompConfig?.applyPath, seccompConfig?.argv0);
1170
+ if (!applySeccompPrefix) {
1171
+ logForDebugging("[Sandbox Linux] apply-seccomp binary not available - unix socket blocking disabled. Install @anthropic-ai/sandbox-runtime globally for full protection.", { level: "warn" });
1172
+ } else {
1173
+ logForDebugging("[Sandbox Linux] Applying seccomp filter for Unix socket blocking");
1174
+ }
1175
+ } else {
1176
+ logForDebugging("[Sandbox Linux] Skipping seccomp filter - allowAllUnixSockets is enabled");
1177
+ }
1178
+ if (observeSocketPath && applySeccompPrefix) {
1179
+ if (fs3.existsSync(observeSocketPath)) {
1180
+ bwrapArgs.push("--bind", observeSocketPath, observeSocketPath);
1181
+ bwrapArgs.push("--setenv", "SRT_OBSERVE_SOCK", observeSocketPath);
1182
+ bwrapArgs.push("--setenv", "SRT_ENCODED_CMD", encodeSandboxedCommand(commandId ?? command));
1183
+ } else {
1184
+ logForDebugging("[Sandbox Linux] observe socket missing \u2014 supervisor not running; continuing without violation monitoring");
1185
+ }
1186
+ }
1187
+ if (hasEnvRestrictions) {
1188
+ for (const name of unsetEnvVars ?? []) {
1189
+ bwrapArgs.push("--unsetenv", name);
1190
+ }
1191
+ for (const [name, value] of Object.entries(setEnvVars ?? {})) {
1192
+ bwrapArgs.push("--setenv", name, value);
1193
+ }
1194
+ }
1195
+ if (gitSafeDirectories && gitSafeDirectories.length > 0) {
1196
+ const gitCfg = buildPosixGitSafeDirEnv({
1197
+ safeDirs: gitSafeDirectories,
1198
+ unsetEnvVars,
1199
+ setEnvVars
1200
+ });
1201
+ for (const [name, value] of Object.entries(gitCfg)) {
1202
+ bwrapArgs.push("--setenv", name, value);
1203
+ }
1204
+ }
1205
+ if (needsNetworkRestriction) {
1206
+ bwrapArgs.push("--unshare-net");
1207
+ if (httpSocketPath && socksSocketPath) {
1208
+ if (!fs3.existsSync(httpSocketPath)) {
1209
+ throw new Error(`Linux HTTP bridge socket does not exist: ${httpSocketPath}. The bridge process may have died. Try reinitializing the sandbox.`);
1210
+ }
1211
+ if (!fs3.existsSync(socksSocketPath)) {
1212
+ throw new Error(`Linux SOCKS bridge socket does not exist: ${socksSocketPath}. The bridge process may have died. Try reinitializing the sandbox.`);
1213
+ }
1214
+ bwrapArgs.push("--bind", httpSocketPath, httpSocketPath);
1215
+ if (socksSocketPath !== httpSocketPath) {
1216
+ bwrapArgs.push("--bind", socksSocketPath, socksSocketPath);
1217
+ }
1218
+ const proxyEnv = generateProxyEnvVars(
1219
+ 3128,
1220
+ // Internal HTTP listener port
1221
+ 1080,
1222
+ // Internal SOCKS listener port
1223
+ caCertPath,
1224
+ proxyAuthToken,
1225
+ writeConfig === void 0,
1226
+ encodeSandboxedCommand(commandId ?? command)
1227
+ );
1228
+ bwrapArgs.push(...proxyEnv.flatMap((env) => {
1229
+ const firstEq = env.indexOf("=");
1230
+ const key = env.slice(0, firstEq);
1231
+ const value = env.slice(firstEq + 1);
1232
+ return ["--setenv", key, value];
1233
+ }));
1234
+ if (httpProxyPort !== void 0) {
1235
+ bwrapArgs.push("--setenv", "CLAUDE_CODE_HOST_HTTP_PROXY_PORT", String(httpProxyPort));
1236
+ }
1237
+ if (socksProxyPort !== void 0) {
1238
+ bwrapArgs.push("--setenv", "CLAUDE_CODE_HOST_SOCKS_PROXY_PORT", String(socksProxyPort));
1239
+ }
1240
+ }
1241
+ }
1242
+ const fsArgs = await generateFilesystemArgs(readConfig, writeConfig, maskedFileBinds, maskedFileStoreDir, ripgrepConfig, mandatoryDenySearchDepth, allowGitConfig, abortSignal);
1243
+ bwrapArgs.push(...fsArgs);
1244
+ bwrapArgs.push("--dev", "/dev");
1245
+ bwrapArgs.push("--unshare-pid");
1246
+ if (!enableWeakerNestedSandbox) {
1247
+ bwrapArgs.push("--unshare-user", "--cap-drop", "ALL", "--proc", "/proc");
1248
+ } else {
1249
+ bwrapArgs.push("--unshare-user", "--bind", "/proc", "/proc");
1250
+ }
1251
+ const shellName = binShell || "bash";
1252
+ const shell = whichSync(shellName);
1253
+ if (!shell) {
1254
+ throw new Error(`Shell '${shellName}' not found in PATH`);
1255
+ }
1256
+ bwrapArgs.push("--", shell, "-c");
1257
+ if (needsNetworkRestriction && httpSocketPath && socksSocketPath) {
1258
+ const sandboxCommand = buildSandboxCommand(httpSocketPath, socksSocketPath, command, applySeccompPrefix, shell, socatPath);
1259
+ bwrapArgs.push(sandboxCommand);
1260
+ } else if (applySeccompPrefix) {
1261
+ const applySeccompCmd = applySeccompPrefix + quote([shell, "-c", command]);
1262
+ bwrapArgs.push(applySeccompCmd);
1263
+ } else {
1264
+ bwrapArgs.push(command);
1265
+ }
1266
+ const wrappedCommand = quote([bwrapPath ?? "bwrap", ...bwrapArgs]);
1267
+ const restrictions = [];
1268
+ if (needsNetworkRestriction)
1269
+ restrictions.push("network");
1270
+ if (hasReadRestrictions || hasWriteRestrictions)
1271
+ restrictions.push("filesystem");
1272
+ if (hasEnvRestrictions)
1273
+ restrictions.push("env");
1274
+ if (applySeccompPrefix)
1275
+ restrictions.push("seccomp(unix-block)");
1276
+ logForDebugging(`[Sandbox Linux] Wrapped command with bwrap (${restrictions.join(", ")} restrictions)`);
1277
+ return wrappedCommand;
1278
+ } catch (error) {
1279
+ if (activeSandboxCount > 0) {
1280
+ activeSandboxCount--;
1281
+ }
1282
+ throw error;
1283
+ }
1284
+ }
1285
+ export {
1286
+ checkLinuxDependencies,
1287
+ cleanupBwrapMountPoints,
1288
+ getDefaultWritePaths,
1289
+ hasRipgrepSync,
1290
+ wrapCommandWithSandboxLinux
1291
+ };