@carderne/sandbox-runtime 0.0.40

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 (83) hide show
  1. package/LICENSE +201 -0
  2. package/README.md +684 -0
  3. package/dist/cli.d.ts +3 -0
  4. package/dist/cli.d.ts.map +1 -0
  5. package/dist/cli.js +163 -0
  6. package/dist/cli.js.map +1 -0
  7. package/dist/index.d.ts +11 -0
  8. package/dist/index.d.ts.map +1 -0
  9. package/dist/index.js +9 -0
  10. package/dist/index.js.map +1 -0
  11. package/dist/sandbox/generate-seccomp-filter.d.ts +71 -0
  12. package/dist/sandbox/generate-seccomp-filter.d.ts.map +1 -0
  13. package/dist/sandbox/generate-seccomp-filter.js +263 -0
  14. package/dist/sandbox/generate-seccomp-filter.js.map +1 -0
  15. package/dist/sandbox/http-proxy.d.ts +13 -0
  16. package/dist/sandbox/http-proxy.d.ts.map +1 -0
  17. package/dist/sandbox/http-proxy.js +217 -0
  18. package/dist/sandbox/http-proxy.js.map +1 -0
  19. package/dist/sandbox/linux-sandbox-utils.d.ts +158 -0
  20. package/dist/sandbox/linux-sandbox-utils.d.ts.map +1 -0
  21. package/dist/sandbox/linux-sandbox-utils.js +875 -0
  22. package/dist/sandbox/linux-sandbox-utils.js.map +1 -0
  23. package/dist/sandbox/macos-sandbox-utils.d.ts +40 -0
  24. package/dist/sandbox/macos-sandbox-utils.d.ts.map +1 -0
  25. package/dist/sandbox/macos-sandbox-utils.js +623 -0
  26. package/dist/sandbox/macos-sandbox-utils.js.map +1 -0
  27. package/dist/sandbox/sandbox-config.d.ts +288 -0
  28. package/dist/sandbox/sandbox-config.d.ts.map +1 -0
  29. package/dist/sandbox/sandbox-config.js +178 -0
  30. package/dist/sandbox/sandbox-config.js.map +1 -0
  31. package/dist/sandbox/sandbox-manager.d.ts +42 -0
  32. package/dist/sandbox/sandbox-manager.d.ts.map +1 -0
  33. package/dist/sandbox/sandbox-manager.js +786 -0
  34. package/dist/sandbox/sandbox-manager.js.map +1 -0
  35. package/dist/sandbox/sandbox-schemas.d.ts +57 -0
  36. package/dist/sandbox/sandbox-schemas.d.ts.map +1 -0
  37. package/dist/sandbox/sandbox-schemas.js +3 -0
  38. package/dist/sandbox/sandbox-schemas.js.map +1 -0
  39. package/dist/sandbox/sandbox-utils.d.ts +109 -0
  40. package/dist/sandbox/sandbox-utils.d.ts.map +1 -0
  41. package/dist/sandbox/sandbox-utils.js +429 -0
  42. package/dist/sandbox/sandbox-utils.js.map +1 -0
  43. package/dist/sandbox/sandbox-violation-store.d.ts +19 -0
  44. package/dist/sandbox/sandbox-violation-store.d.ts.map +1 -0
  45. package/dist/sandbox/sandbox-violation-store.js +54 -0
  46. package/dist/sandbox/sandbox-violation-store.js.map +1 -0
  47. package/dist/sandbox/socks-proxy.d.ts +13 -0
  48. package/dist/sandbox/socks-proxy.d.ts.map +1 -0
  49. package/dist/sandbox/socks-proxy.js +95 -0
  50. package/dist/sandbox/socks-proxy.js.map +1 -0
  51. package/dist/utils/config-loader.d.ts +11 -0
  52. package/dist/utils/config-loader.d.ts.map +1 -0
  53. package/dist/utils/config-loader.js +60 -0
  54. package/dist/utils/config-loader.js.map +1 -0
  55. package/dist/utils/debug.d.ts +7 -0
  56. package/dist/utils/debug.d.ts.map +1 -0
  57. package/dist/utils/debug.js +25 -0
  58. package/dist/utils/debug.js.map +1 -0
  59. package/dist/utils/platform.d.ts +15 -0
  60. package/dist/utils/platform.d.ts.map +1 -0
  61. package/dist/utils/platform.js +49 -0
  62. package/dist/utils/platform.js.map +1 -0
  63. package/dist/utils/ripgrep.d.ts +20 -0
  64. package/dist/utils/ripgrep.d.ts.map +1 -0
  65. package/dist/utils/ripgrep.js +42 -0
  66. package/dist/utils/ripgrep.js.map +1 -0
  67. package/dist/utils/which.d.ts +9 -0
  68. package/dist/utils/which.d.ts.map +1 -0
  69. package/dist/utils/which.js +25 -0
  70. package/dist/utils/which.js.map +1 -0
  71. package/dist/vendor/seccomp/arm64/apply-seccomp +0 -0
  72. package/dist/vendor/seccomp/arm64/unix-block.bpf +0 -0
  73. package/dist/vendor/seccomp/x64/apply-seccomp +0 -0
  74. package/dist/vendor/seccomp/x64/unix-block.bpf +0 -0
  75. package/dist/vendor/seccomp-src/apply-seccomp.c +98 -0
  76. package/dist/vendor/seccomp-src/seccomp-unix-block.c +97 -0
  77. package/package.json +88 -0
  78. package/vendor/seccomp/arm64/apply-seccomp +0 -0
  79. package/vendor/seccomp/arm64/unix-block.bpf +0 -0
  80. package/vendor/seccomp/x64/apply-seccomp +0 -0
  81. package/vendor/seccomp/x64/unix-block.bpf +0 -0
  82. package/vendor/seccomp-src/apply-seccomp.c +98 -0
  83. package/vendor/seccomp-src/seccomp-unix-block.c +97 -0
@@ -0,0 +1,786 @@
1
+ import { createHttpProxyServer } from './http-proxy.js';
2
+ import { createSocksProxyServer } from './socks-proxy.js';
3
+ import { logForDebugging } from '../utils/debug.js';
4
+ import { whichSync } from '../utils/which.js';
5
+ import { cloneDeep } from 'lodash-es';
6
+ import { getPlatform, getWslVersion } from '../utils/platform.js';
7
+ import * as fs from 'fs';
8
+ import { wrapCommandWithSandboxLinux, initializeLinuxNetworkBridge, checkLinuxDependencies, cleanupBwrapMountPoints, } from './linux-sandbox-utils.js';
9
+ import { wrapCommandWithSandboxMacOS, startMacOSSandboxLogMonitor, } from './macos-sandbox-utils.js';
10
+ import { getDefaultWritePaths, containsGlobChars, removeTrailingGlobSuffix, expandGlobPattern, } from './sandbox-utils.js';
11
+ import { SandboxViolationStore } from './sandbox-violation-store.js';
12
+ import { EOL } from 'node:os';
13
+ // ============================================================================
14
+ // Private Module State
15
+ // ============================================================================
16
+ let config;
17
+ let httpProxyServer;
18
+ let socksProxyServer;
19
+ let managerContext;
20
+ let initializationPromise;
21
+ let cleanupRegistered = false;
22
+ let logMonitorShutdown;
23
+ const sandboxViolationStore = new SandboxViolationStore();
24
+ // ============================================================================
25
+ // Private Helper Functions (not exported)
26
+ // ============================================================================
27
+ function registerCleanup() {
28
+ if (cleanupRegistered) {
29
+ return;
30
+ }
31
+ const cleanupHandler = () => reset().catch(e => {
32
+ logForDebugging(`Cleanup failed in registerCleanup ${e}`, {
33
+ level: 'error',
34
+ });
35
+ });
36
+ process.once('exit', cleanupHandler);
37
+ process.once('SIGINT', cleanupHandler);
38
+ process.once('SIGTERM', cleanupHandler);
39
+ cleanupRegistered = true;
40
+ }
41
+ function matchesDomainPattern(hostname, pattern) {
42
+ // Support wildcard patterns like *.example.com
43
+ // This matches any subdomain but not the base domain itself
44
+ if (pattern.startsWith('*.')) {
45
+ const baseDomain = pattern.substring(2); // Remove '*.'
46
+ return hostname.toLowerCase().endsWith('.' + baseDomain.toLowerCase());
47
+ }
48
+ // Exact match for non-wildcard patterns
49
+ return hostname.toLowerCase() === pattern.toLowerCase();
50
+ }
51
+ async function filterNetworkRequest(port, host, sandboxAskCallback) {
52
+ if (!config) {
53
+ logForDebugging('No config available, denying network request');
54
+ return false;
55
+ }
56
+ // Check denied domains first
57
+ for (const deniedDomain of config.network.deniedDomains) {
58
+ if (matchesDomainPattern(host, deniedDomain)) {
59
+ logForDebugging(`Denied by config rule: ${host}:${port}`);
60
+ return false;
61
+ }
62
+ }
63
+ // Check allowed domains
64
+ for (const allowedDomain of config.network.allowedDomains) {
65
+ if (matchesDomainPattern(host, allowedDomain)) {
66
+ logForDebugging(`Allowed by config rule: ${host}:${port}`);
67
+ return true;
68
+ }
69
+ }
70
+ // No matching rules - ask user or deny
71
+ if (!sandboxAskCallback) {
72
+ logForDebugging(`No matching config rule, denying: ${host}:${port}`);
73
+ return false;
74
+ }
75
+ logForDebugging(`No matching config rule, asking user: ${host}:${port}`);
76
+ try {
77
+ const userAllowed = await sandboxAskCallback({ host, port });
78
+ if (userAllowed) {
79
+ logForDebugging(`User allowed: ${host}:${port}`);
80
+ return true;
81
+ }
82
+ else {
83
+ logForDebugging(`User denied: ${host}:${port}`);
84
+ return false;
85
+ }
86
+ }
87
+ catch (error) {
88
+ logForDebugging(`Error in permission callback: ${error}`, {
89
+ level: 'error',
90
+ });
91
+ return false;
92
+ }
93
+ }
94
+ /**
95
+ * Get the MITM proxy socket path for a given host, if configured.
96
+ * Returns the socket path if the host matches any MITM domain pattern,
97
+ * otherwise returns undefined.
98
+ */
99
+ function getMitmSocketPath(host) {
100
+ if (!config?.network.mitmProxy) {
101
+ return undefined;
102
+ }
103
+ const { socketPath, domains } = config.network.mitmProxy;
104
+ for (const pattern of domains) {
105
+ if (matchesDomainPattern(host, pattern)) {
106
+ logForDebugging(`Host ${host} matches MITM pattern ${pattern}`);
107
+ return socketPath;
108
+ }
109
+ }
110
+ return undefined;
111
+ }
112
+ async function startHttpProxyServer(sandboxAskCallback) {
113
+ httpProxyServer = createHttpProxyServer({
114
+ filter: (port, host) => filterNetworkRequest(port, host, sandboxAskCallback),
115
+ getMitmSocketPath,
116
+ });
117
+ return new Promise((resolve, reject) => {
118
+ if (!httpProxyServer) {
119
+ reject(new Error('HTTP proxy server undefined before listen'));
120
+ return;
121
+ }
122
+ const server = httpProxyServer;
123
+ server.once('error', reject);
124
+ server.once('listening', () => {
125
+ const address = server.address();
126
+ if (address && typeof address === 'object') {
127
+ server.unref();
128
+ logForDebugging(`HTTP proxy listening on localhost:${address.port}`);
129
+ resolve(address.port);
130
+ }
131
+ else {
132
+ reject(new Error('Failed to get proxy server address'));
133
+ }
134
+ });
135
+ server.listen(0, '127.0.0.1');
136
+ });
137
+ }
138
+ async function startSocksProxyServer(sandboxAskCallback) {
139
+ socksProxyServer = createSocksProxyServer({
140
+ filter: (port, host) => filterNetworkRequest(port, host, sandboxAskCallback),
141
+ });
142
+ return new Promise((resolve, reject) => {
143
+ if (!socksProxyServer) {
144
+ // This is mostly just for the typechecker
145
+ reject(new Error('SOCKS proxy server undefined before listen'));
146
+ return;
147
+ }
148
+ socksProxyServer
149
+ .listen(0, '127.0.0.1')
150
+ .then((port) => {
151
+ socksProxyServer?.unref();
152
+ resolve(port);
153
+ })
154
+ .catch(reject);
155
+ });
156
+ }
157
+ // ============================================================================
158
+ // Public Module Functions (will be exported via namespace)
159
+ // ============================================================================
160
+ async function initialize(runtimeConfig, sandboxAskCallback, enableLogMonitor = false) {
161
+ // Return if already initializing
162
+ if (initializationPromise) {
163
+ await initializationPromise;
164
+ return;
165
+ }
166
+ // Store config for use by other functions
167
+ config = runtimeConfig;
168
+ // Check dependencies
169
+ const deps = checkDependencies();
170
+ if (deps.errors.length > 0) {
171
+ throw new Error(`Sandbox dependencies not available: ${deps.errors.join(', ')}`);
172
+ }
173
+ // Start log monitor for macOS if enabled
174
+ if (enableLogMonitor && getPlatform() === 'macos') {
175
+ logMonitorShutdown = startMacOSSandboxLogMonitor(sandboxViolationStore.addViolation.bind(sandboxViolationStore), config.ignoreViolations);
176
+ logForDebugging('Started macOS sandbox log monitor');
177
+ }
178
+ // Register cleanup handlers first time
179
+ registerCleanup();
180
+ // Initialize network infrastructure
181
+ initializationPromise = (async () => {
182
+ try {
183
+ // Conditionally start proxy servers based on config
184
+ let httpProxyPort;
185
+ if (config.network.httpProxyPort !== undefined) {
186
+ // Use external HTTP proxy (don't start a server)
187
+ httpProxyPort = config.network.httpProxyPort;
188
+ logForDebugging(`Using external HTTP proxy on port ${httpProxyPort}`);
189
+ }
190
+ else {
191
+ // Start local HTTP proxy
192
+ httpProxyPort = await startHttpProxyServer(sandboxAskCallback);
193
+ }
194
+ let socksProxyPort;
195
+ if (config.network.socksProxyPort !== undefined) {
196
+ // Use external SOCKS proxy (don't start a server)
197
+ socksProxyPort = config.network.socksProxyPort;
198
+ logForDebugging(`Using external SOCKS proxy on port ${socksProxyPort}`);
199
+ }
200
+ else {
201
+ // Start local SOCKS proxy
202
+ socksProxyPort = await startSocksProxyServer(sandboxAskCallback);
203
+ }
204
+ // Initialize platform-specific infrastructure
205
+ let linuxBridge;
206
+ if (getPlatform() === 'linux') {
207
+ linuxBridge = await initializeLinuxNetworkBridge(httpProxyPort, socksProxyPort);
208
+ }
209
+ const context = {
210
+ httpProxyPort,
211
+ socksProxyPort,
212
+ linuxBridge,
213
+ };
214
+ managerContext = context;
215
+ logForDebugging('Network infrastructure initialized');
216
+ return context;
217
+ }
218
+ catch (error) {
219
+ // Clear state on error so initialization can be retried
220
+ initializationPromise = undefined;
221
+ managerContext = undefined;
222
+ reset().catch(e => {
223
+ logForDebugging(`Cleanup failed in initializationPromise ${e}`, {
224
+ level: 'error',
225
+ });
226
+ });
227
+ throw error;
228
+ }
229
+ })();
230
+ await initializationPromise;
231
+ }
232
+ function isSupportedPlatform() {
233
+ const platform = getPlatform();
234
+ if (platform === 'linux') {
235
+ // WSL1 doesn't support bubblewrap
236
+ return getWslVersion() !== '1';
237
+ }
238
+ return platform === 'macos';
239
+ }
240
+ function isSandboxingEnabled() {
241
+ // Sandboxing is enabled if config has been set (via initialize())
242
+ return config !== undefined;
243
+ }
244
+ /**
245
+ * Check sandbox dependencies for the current platform
246
+ * @param ripgrepConfig - Ripgrep command to check. If not provided, uses config from initialization or defaults to 'rg'
247
+ * @returns { warnings, errors } - errors mean sandbox cannot run, warnings mean degraded functionality
248
+ */
249
+ function checkDependencies(ripgrepConfig) {
250
+ if (!isSupportedPlatform()) {
251
+ return { errors: ['Unsupported platform'], warnings: [] };
252
+ }
253
+ const errors = [];
254
+ const warnings = [];
255
+ // Check ripgrep - use provided config, then initialized config, then default 'rg'
256
+ const rgToCheck = ripgrepConfig ?? config?.ripgrep ?? { command: 'rg' };
257
+ if (whichSync(rgToCheck.command) === null) {
258
+ errors.push(`ripgrep (${rgToCheck.command}) not found`);
259
+ }
260
+ const platform = getPlatform();
261
+ if (platform === 'linux') {
262
+ const linuxDeps = checkLinuxDependencies(config?.seccomp);
263
+ errors.push(...linuxDeps.errors);
264
+ warnings.push(...linuxDeps.warnings);
265
+ }
266
+ return { errors, warnings };
267
+ }
268
+ function getFsReadConfig() {
269
+ if (!config) {
270
+ return { denyOnly: [], allowWithinDeny: [] };
271
+ }
272
+ const denyPaths = [];
273
+ for (const p of config.filesystem.denyRead) {
274
+ const stripped = removeTrailingGlobSuffix(p);
275
+ if (getPlatform() === 'linux' && containsGlobChars(stripped)) {
276
+ // Expand glob to concrete paths on Linux (bubblewrap doesn't support globs)
277
+ const expanded = expandGlobPattern(p);
278
+ logForDebugging(`[Sandbox] Expanded glob pattern "${p}" to ${expanded.length} paths on Linux`);
279
+ denyPaths.push(...expanded);
280
+ }
281
+ else {
282
+ denyPaths.push(stripped);
283
+ }
284
+ }
285
+ // Process allowRead paths (re-allow within denied regions)
286
+ const allowPaths = [];
287
+ for (const p of config.filesystem.allowRead ?? []) {
288
+ const stripped = removeTrailingGlobSuffix(p);
289
+ if (getPlatform() === 'linux' && containsGlobChars(stripped)) {
290
+ const expanded = expandGlobPattern(p);
291
+ logForDebugging(`[Sandbox] Expanded allowRead glob pattern "${p}" to ${expanded.length} paths on Linux`);
292
+ allowPaths.push(...expanded);
293
+ }
294
+ else {
295
+ allowPaths.push(stripped);
296
+ }
297
+ }
298
+ return {
299
+ denyOnly: denyPaths,
300
+ allowWithinDeny: allowPaths,
301
+ };
302
+ }
303
+ function getFsWriteConfig() {
304
+ if (!config) {
305
+ return { allowOnly: getDefaultWritePaths(), denyWithinAllow: [] };
306
+ }
307
+ // Filter out glob patterns on Linux/WSL for allowWrite (bubblewrap doesn't support globs)
308
+ const allowPaths = config.filesystem.allowWrite
309
+ .map(path => removeTrailingGlobSuffix(path))
310
+ .filter(path => {
311
+ if (getPlatform() === 'linux' && containsGlobChars(path)) {
312
+ logForDebugging(`Skipping glob pattern on Linux/WSL: ${path}`);
313
+ return false;
314
+ }
315
+ return true;
316
+ });
317
+ // Filter out glob patterns on Linux/WSL for denyWrite (bubblewrap doesn't support globs)
318
+ const denyPaths = config.filesystem.denyWrite
319
+ .map(path => removeTrailingGlobSuffix(path))
320
+ .filter(path => {
321
+ if (getPlatform() === 'linux' && containsGlobChars(path)) {
322
+ logForDebugging(`Skipping glob pattern on Linux/WSL: ${path}`);
323
+ return false;
324
+ }
325
+ return true;
326
+ });
327
+ // Build allowOnly list: default paths + configured allow paths
328
+ const allowOnly = [...getDefaultWritePaths(), ...allowPaths];
329
+ return {
330
+ allowOnly,
331
+ denyWithinAllow: denyPaths,
332
+ };
333
+ }
334
+ function getNetworkRestrictionConfig() {
335
+ if (!config) {
336
+ return {};
337
+ }
338
+ const allowedHosts = config.network.allowedDomains;
339
+ const deniedHosts = config.network.deniedDomains;
340
+ return {
341
+ ...(allowedHosts.length > 0 && { allowedHosts }),
342
+ ...(deniedHosts.length > 0 && { deniedHosts }),
343
+ };
344
+ }
345
+ function getAllowUnixSockets() {
346
+ return config?.network?.allowUnixSockets;
347
+ }
348
+ function getAllowAllUnixSockets() {
349
+ return config?.network?.allowAllUnixSockets;
350
+ }
351
+ function getAllowLocalBinding() {
352
+ return config?.network?.allowLocalBinding;
353
+ }
354
+ function getIgnoreViolations() {
355
+ return config?.ignoreViolations;
356
+ }
357
+ function getEnableWeakerNestedSandbox() {
358
+ return config?.enableWeakerNestedSandbox;
359
+ }
360
+ function getEnableWeakerNetworkIsolation() {
361
+ return config?.enableWeakerNetworkIsolation;
362
+ }
363
+ function getRipgrepConfig() {
364
+ return config?.ripgrep ?? { command: 'rg' };
365
+ }
366
+ function getMandatoryDenySearchDepth() {
367
+ return config?.mandatoryDenySearchDepth ?? 3;
368
+ }
369
+ function getAllowGitConfig() {
370
+ return config?.filesystem?.allowGitConfig ?? false;
371
+ }
372
+ function getSeccompConfig() {
373
+ return config?.seccomp;
374
+ }
375
+ function getProxyPort() {
376
+ return managerContext?.httpProxyPort;
377
+ }
378
+ function getSocksProxyPort() {
379
+ return managerContext?.socksProxyPort;
380
+ }
381
+ function getLinuxHttpSocketPath() {
382
+ return managerContext?.linuxBridge?.httpSocketPath;
383
+ }
384
+ function getLinuxSocksSocketPath() {
385
+ return managerContext?.linuxBridge?.socksSocketPath;
386
+ }
387
+ /**
388
+ * Wait for network initialization to complete if already in progress
389
+ * Returns true if initialized successfully, false otherwise
390
+ */
391
+ async function waitForNetworkInitialization() {
392
+ if (!config) {
393
+ return false;
394
+ }
395
+ if (initializationPromise) {
396
+ try {
397
+ await initializationPromise;
398
+ return true;
399
+ }
400
+ catch {
401
+ return false;
402
+ }
403
+ }
404
+ return managerContext !== undefined;
405
+ }
406
+ async function wrapWithSandbox(command, binShell, customConfig, abortSignal) {
407
+ const platform = getPlatform();
408
+ // Get configs - use custom if provided, otherwise fall back to main config
409
+ // If neither exists, defaults to empty arrays (most restrictive)
410
+ // Always include default system write paths (like /dev/null, /tmp/claude)
411
+ //
412
+ // Strip trailing /** and filter remaining globs on Linux (bwrap needs
413
+ // real paths, not globs; macOS subpath matching is also recursive so
414
+ // stripping is harmless there).
415
+ const stripWriteGlobs = (paths) => paths
416
+ .map(p => removeTrailingGlobSuffix(p))
417
+ .filter(p => {
418
+ if (getPlatform() === 'linux' && containsGlobChars(p)) {
419
+ logForDebugging(`[Sandbox] Skipping glob write pattern on Linux: ${p}`);
420
+ return false;
421
+ }
422
+ return true;
423
+ });
424
+ const userAllowWrite = stripWriteGlobs(customConfig?.filesystem?.allowWrite ?? config?.filesystem.allowWrite ?? []);
425
+ const writeConfig = {
426
+ allowOnly: [...getDefaultWritePaths(), ...userAllowWrite],
427
+ denyWithinAllow: stripWriteGlobs(customConfig?.filesystem?.denyWrite ?? config?.filesystem.denyWrite ?? []),
428
+ };
429
+ const rawDenyRead = customConfig?.filesystem?.denyRead ?? config?.filesystem.denyRead ?? [];
430
+ const expandedDenyRead = [];
431
+ for (const p of rawDenyRead) {
432
+ const stripped = removeTrailingGlobSuffix(p);
433
+ if (getPlatform() === 'linux' && containsGlobChars(stripped)) {
434
+ expandedDenyRead.push(...expandGlobPattern(p));
435
+ }
436
+ else {
437
+ expandedDenyRead.push(stripped);
438
+ }
439
+ }
440
+ const rawAllowRead = customConfig?.filesystem?.allowRead ?? config?.filesystem.allowRead ?? [];
441
+ const expandedAllowRead = [];
442
+ for (const p of rawAllowRead) {
443
+ const stripped = removeTrailingGlobSuffix(p);
444
+ if (getPlatform() === 'linux' && containsGlobChars(stripped)) {
445
+ expandedAllowRead.push(...expandGlobPattern(p));
446
+ }
447
+ else {
448
+ expandedAllowRead.push(stripped);
449
+ }
450
+ }
451
+ const readConfig = {
452
+ denyOnly: expandedDenyRead,
453
+ allowWithinDeny: expandedAllowRead,
454
+ };
455
+ // Check if network config is specified - this determines if we need network restrictions
456
+ // Network restriction is needed when:
457
+ // 1. customConfig has network.allowedDomains defined (even if empty array = block all)
458
+ // 2. OR config has network.allowedDomains defined (even if empty array = block all)
459
+ // An empty allowedDomains array means "no domains allowed" = block all network access
460
+ const hasNetworkConfig = customConfig?.network?.allowedDomains !== undefined ||
461
+ config?.network?.allowedDomains !== undefined;
462
+ // Network RESTRICTION is needed whenever network config is specified
463
+ // This includes empty allowedDomains which means "block all network"
464
+ const needsNetworkRestriction = hasNetworkConfig;
465
+ // Network PROXY is needed whenever network config is specified
466
+ // Even with empty allowedDomains, we route through proxy so that:
467
+ // 1. updateConfig() can enable network access for already-running processes
468
+ // 2. The proxy blocks all requests when allowlist is empty
469
+ const needsNetworkProxy = hasNetworkConfig;
470
+ // Wait for network initialization only if proxy is actually needed
471
+ if (needsNetworkProxy) {
472
+ await waitForNetworkInitialization();
473
+ }
474
+ // Check custom config to allow pseudo-terminal (can be applied dynamically)
475
+ const allowPty = customConfig?.allowPty ?? config?.allowPty;
476
+ switch (platform) {
477
+ case 'macos':
478
+ // macOS sandbox profile supports glob patterns directly, no ripgrep needed
479
+ return wrapCommandWithSandboxMacOS({
480
+ command,
481
+ needsNetworkRestriction,
482
+ // Only pass proxy ports if proxy is running (when there are domains to filter)
483
+ httpProxyPort: needsNetworkProxy ? getProxyPort() : undefined,
484
+ socksProxyPort: needsNetworkProxy ? getSocksProxyPort() : undefined,
485
+ readConfig,
486
+ writeConfig,
487
+ allowUnixSockets: getAllowUnixSockets(),
488
+ allowAllUnixSockets: getAllowAllUnixSockets(),
489
+ allowLocalBinding: getAllowLocalBinding(),
490
+ ignoreViolations: getIgnoreViolations(),
491
+ allowPty,
492
+ allowGitConfig: getAllowGitConfig(),
493
+ enableWeakerNetworkIsolation: getEnableWeakerNetworkIsolation(),
494
+ binShell,
495
+ });
496
+ case 'linux':
497
+ return wrapCommandWithSandboxLinux({
498
+ command,
499
+ needsNetworkRestriction,
500
+ // Only pass socket paths if proxy is running (when there are domains to filter)
501
+ httpSocketPath: needsNetworkProxy
502
+ ? getLinuxHttpSocketPath()
503
+ : undefined,
504
+ socksSocketPath: needsNetworkProxy
505
+ ? getLinuxSocksSocketPath()
506
+ : undefined,
507
+ httpProxyPort: needsNetworkProxy
508
+ ? managerContext?.httpProxyPort
509
+ : undefined,
510
+ socksProxyPort: needsNetworkProxy
511
+ ? managerContext?.socksProxyPort
512
+ : undefined,
513
+ readConfig,
514
+ writeConfig,
515
+ enableWeakerNestedSandbox: getEnableWeakerNestedSandbox(),
516
+ allowAllUnixSockets: getAllowAllUnixSockets(),
517
+ binShell,
518
+ ripgrepConfig: getRipgrepConfig(),
519
+ mandatoryDenySearchDepth: getMandatoryDenySearchDepth(),
520
+ allowGitConfig: getAllowGitConfig(),
521
+ seccompConfig: getSeccompConfig(),
522
+ abortSignal,
523
+ });
524
+ default:
525
+ // Unsupported platform - this should not happen since isSandboxingEnabled() checks platform support
526
+ throw new Error(`Sandbox configuration is not supported on platform: ${platform}`);
527
+ }
528
+ }
529
+ /**
530
+ * Get the current sandbox configuration
531
+ * @returns The current configuration, or undefined if not initialized
532
+ */
533
+ function getConfig() {
534
+ return config;
535
+ }
536
+ /**
537
+ * Update the sandbox configuration
538
+ * @param newConfig - The new configuration to use
539
+ */
540
+ function updateConfig(newConfig) {
541
+ // Deep clone the config to avoid mutations
542
+ config = cloneDeep(newConfig);
543
+ logForDebugging('Sandbox configuration updated');
544
+ }
545
+ /**
546
+ * Lightweight cleanup to call after each sandboxed command completes.
547
+ *
548
+ * On Linux, bwrap creates empty files on the host filesystem as mount points
549
+ * when protecting non-existent deny paths (e.g. ~/.bashrc, ~/.gitconfig).
550
+ * These persist after bwrap exits. This function removes them.
551
+ *
552
+ * Safe to call on any platform — it's a no-op on macOS.
553
+ * Also called automatically by reset() and on process exit as safety nets.
554
+ */
555
+ function cleanupAfterCommand() {
556
+ cleanupBwrapMountPoints();
557
+ }
558
+ async function reset() {
559
+ // Clean up any leftover bwrap mount points
560
+ cleanupAfterCommand();
561
+ // Stop log monitor
562
+ if (logMonitorShutdown) {
563
+ logMonitorShutdown();
564
+ logMonitorShutdown = undefined;
565
+ }
566
+ if (managerContext?.linuxBridge) {
567
+ const { httpSocketPath, socksSocketPath, httpBridgeProcess, socksBridgeProcess, } = managerContext.linuxBridge;
568
+ // Create array to wait for process exits
569
+ const exitPromises = [];
570
+ // Kill HTTP bridge and wait for it to exit
571
+ if (httpBridgeProcess.pid && !httpBridgeProcess.killed) {
572
+ try {
573
+ process.kill(httpBridgeProcess.pid, 'SIGTERM');
574
+ logForDebugging('Sent SIGTERM to HTTP bridge process');
575
+ // Wait for process to exit
576
+ exitPromises.push(new Promise(resolve => {
577
+ httpBridgeProcess.once('exit', () => {
578
+ logForDebugging('HTTP bridge process exited');
579
+ resolve();
580
+ });
581
+ // Timeout after 5 seconds
582
+ setTimeout(() => {
583
+ if (!httpBridgeProcess.killed) {
584
+ logForDebugging('HTTP bridge did not exit, forcing SIGKILL', {
585
+ level: 'warn',
586
+ });
587
+ try {
588
+ if (httpBridgeProcess.pid) {
589
+ process.kill(httpBridgeProcess.pid, 'SIGKILL');
590
+ }
591
+ }
592
+ catch {
593
+ // Process may have already exited
594
+ }
595
+ }
596
+ resolve();
597
+ }, 5000);
598
+ }));
599
+ }
600
+ catch (err) {
601
+ if (err.code !== 'ESRCH') {
602
+ logForDebugging(`Error killing HTTP bridge: ${err}`, {
603
+ level: 'error',
604
+ });
605
+ }
606
+ }
607
+ }
608
+ // Kill SOCKS bridge and wait for it to exit
609
+ if (socksBridgeProcess.pid && !socksBridgeProcess.killed) {
610
+ try {
611
+ process.kill(socksBridgeProcess.pid, 'SIGTERM');
612
+ logForDebugging('Sent SIGTERM to SOCKS bridge process');
613
+ // Wait for process to exit
614
+ exitPromises.push(new Promise(resolve => {
615
+ socksBridgeProcess.once('exit', () => {
616
+ logForDebugging('SOCKS bridge process exited');
617
+ resolve();
618
+ });
619
+ // Timeout after 5 seconds
620
+ setTimeout(() => {
621
+ if (!socksBridgeProcess.killed) {
622
+ logForDebugging('SOCKS bridge did not exit, forcing SIGKILL', {
623
+ level: 'warn',
624
+ });
625
+ try {
626
+ if (socksBridgeProcess.pid) {
627
+ process.kill(socksBridgeProcess.pid, 'SIGKILL');
628
+ }
629
+ }
630
+ catch {
631
+ // Process may have already exited
632
+ }
633
+ }
634
+ resolve();
635
+ }, 5000);
636
+ }));
637
+ }
638
+ catch (err) {
639
+ if (err.code !== 'ESRCH') {
640
+ logForDebugging(`Error killing SOCKS bridge: ${err}`, {
641
+ level: 'error',
642
+ });
643
+ }
644
+ }
645
+ }
646
+ // Wait for both processes to exit
647
+ await Promise.all(exitPromises);
648
+ // Clean up sockets
649
+ if (httpSocketPath) {
650
+ try {
651
+ fs.rmSync(httpSocketPath, { force: true });
652
+ logForDebugging('Cleaned up HTTP socket');
653
+ }
654
+ catch (err) {
655
+ logForDebugging(`HTTP socket cleanup error: ${err}`, {
656
+ level: 'error',
657
+ });
658
+ }
659
+ }
660
+ if (socksSocketPath) {
661
+ try {
662
+ fs.rmSync(socksSocketPath, { force: true });
663
+ logForDebugging('Cleaned up SOCKS socket');
664
+ }
665
+ catch (err) {
666
+ logForDebugging(`SOCKS socket cleanup error: ${err}`, {
667
+ level: 'error',
668
+ });
669
+ }
670
+ }
671
+ }
672
+ // Close servers in parallel (only if they exist, i.e., were started by us)
673
+ const closePromises = [];
674
+ if (httpProxyServer) {
675
+ const server = httpProxyServer; // Capture reference to avoid TypeScript error
676
+ const httpClose = new Promise(resolve => {
677
+ server.close(error => {
678
+ if (error && error.message !== 'Server is not running.') {
679
+ logForDebugging(`Error closing HTTP proxy server: ${error.message}`, {
680
+ level: 'error',
681
+ });
682
+ }
683
+ resolve();
684
+ });
685
+ });
686
+ closePromises.push(httpClose);
687
+ }
688
+ if (socksProxyServer) {
689
+ const socksClose = socksProxyServer.close().catch((error) => {
690
+ logForDebugging(`Error closing SOCKS proxy server: ${error.message}`, {
691
+ level: 'error',
692
+ });
693
+ });
694
+ closePromises.push(socksClose);
695
+ }
696
+ // Wait for all servers to close
697
+ await Promise.all(closePromises);
698
+ // Clear references
699
+ httpProxyServer = undefined;
700
+ socksProxyServer = undefined;
701
+ managerContext = undefined;
702
+ initializationPromise = undefined;
703
+ }
704
+ function getSandboxViolationStore() {
705
+ return sandboxViolationStore;
706
+ }
707
+ function annotateStderrWithSandboxFailures(command, stderr) {
708
+ if (!config) {
709
+ return stderr;
710
+ }
711
+ const violations = sandboxViolationStore.getViolationsForCommand(command);
712
+ if (violations.length === 0) {
713
+ return stderr;
714
+ }
715
+ let annotated = stderr;
716
+ annotated += EOL + '<sandbox_violations>' + EOL;
717
+ for (const violation of violations) {
718
+ annotated += violation.line + EOL;
719
+ }
720
+ annotated += '</sandbox_violations>';
721
+ return annotated;
722
+ }
723
+ /**
724
+ * Returns glob patterns from Edit/Read permission rules that are not
725
+ * fully supported on Linux. Returns empty array on macOS or when
726
+ * sandboxing is disabled.
727
+ *
728
+ * Patterns ending with /** are excluded since they work as subpaths.
729
+ */
730
+ function getLinuxGlobPatternWarnings() {
731
+ // Only warn on Linux/WSL (bubblewrap doesn't support globs)
732
+ // macOS supports glob patterns via regex conversion
733
+ if (getPlatform() !== 'linux' || !config) {
734
+ return [];
735
+ }
736
+ const globPatterns = [];
737
+ // Check filesystem paths for glob patterns
738
+ // Note: denyRead is excluded because globs are now expanded to concrete paths on Linux
739
+ const allPaths = [
740
+ ...config.filesystem.allowWrite,
741
+ ...config.filesystem.denyWrite,
742
+ ];
743
+ for (const path of allPaths) {
744
+ // Strip trailing /** since that's just a subpath (directory and everything under it)
745
+ const pathWithoutTrailingStar = removeTrailingGlobSuffix(path);
746
+ // Only warn if there are still glob characters after removing trailing /**
747
+ if (containsGlobChars(pathWithoutTrailingStar)) {
748
+ globPatterns.push(path);
749
+ }
750
+ }
751
+ return globPatterns;
752
+ }
753
+ // ============================================================================
754
+ // Export as Namespace with Interface
755
+ // ============================================================================
756
+ /**
757
+ * Global sandbox manager that handles both network and filesystem restrictions
758
+ * for this session. This runs outside of the sandbox, on the host machine.
759
+ */
760
+ export const SandboxManager = {
761
+ initialize,
762
+ isSupportedPlatform,
763
+ isSandboxingEnabled,
764
+ checkDependencies,
765
+ getFsReadConfig,
766
+ getFsWriteConfig,
767
+ getNetworkRestrictionConfig,
768
+ getAllowUnixSockets,
769
+ getAllowLocalBinding,
770
+ getIgnoreViolations,
771
+ getEnableWeakerNestedSandbox,
772
+ getProxyPort,
773
+ getSocksProxyPort,
774
+ getLinuxHttpSocketPath,
775
+ getLinuxSocksSocketPath,
776
+ waitForNetworkInitialization,
777
+ wrapWithSandbox,
778
+ cleanupAfterCommand,
779
+ reset,
780
+ getSandboxViolationStore,
781
+ annotateStderrWithSandboxFailures,
782
+ getLinuxGlobPatternWarnings,
783
+ getConfig,
784
+ updateConfig,
785
+ };
786
+ //# sourceMappingURL=sandbox-manager.js.map