@sysid/sandbox-runtime-improved 0.0.42-sysid.1

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 +676 -0
  3. package/dist/cli.d.ts +3 -0
  4. package/dist/cli.d.ts.map +1 -0
  5. package/dist/cli.js +166 -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 +19 -0
  16. package/dist/sandbox/http-proxy.d.ts.map +1 -0
  17. package/dist/sandbox/http-proxy.js +295 -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 +41 -0
  24. package/dist/sandbox/macos-sandbox-utils.d.ts.map +1 -0
  25. package/dist/sandbox/macos-sandbox-utils.js +672 -0
  26. package/dist/sandbox/macos-sandbox-utils.js.map +1 -0
  27. package/dist/sandbox/sandbox-config.d.ts +307 -0
  28. package/dist/sandbox/sandbox-config.d.ts.map +1 -0
  29. package/dist/sandbox/sandbox-config.js +195 -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 +796 -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 +116 -0
  40. package/dist/sandbox/sandbox-utils.d.ts.map +1 -0
  41. package/dist/sandbox/sandbox-utils.js +463 -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 +22 -0
  64. package/dist/utils/ripgrep.d.ts.map +1 -0
  65. package/dist/utils/ripgrep.js +45 -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,672 @@
1
+ import shellquote from 'shell-quote';
2
+ import { spawn } from 'child_process';
3
+ import * as path from 'path';
4
+ import { logForDebugging } from '../utils/debug.js';
5
+ import { whichSync } from '../utils/which.js';
6
+ import { normalizePathForSandbox, generateProxyEnvVars, encodeSandboxedCommand, decodeSandboxedCommand, containsGlobChars, globToRegex, DANGEROUS_FILES, getDangerousDirectories, } from './sandbox-utils.js';
7
+ /**
8
+ * Get mandatory deny patterns as glob patterns (no filesystem scanning).
9
+ * macOS sandbox profile supports regex/glob matching directly via globToRegex().
10
+ */
11
+ export function macGetMandatoryDenyPatterns(allowGitConfig = false) {
12
+ const cwd = process.cwd();
13
+ const denyPaths = [];
14
+ // Dangerous files - static paths in CWD + glob patterns for subtree
15
+ for (const fileName of DANGEROUS_FILES) {
16
+ denyPaths.push(path.resolve(cwd, fileName));
17
+ denyPaths.push(`**/${fileName}`);
18
+ }
19
+ // Dangerous directories
20
+ for (const dirName of getDangerousDirectories()) {
21
+ denyPaths.push(path.resolve(cwd, dirName));
22
+ denyPaths.push(`**/${dirName}/**`);
23
+ }
24
+ // Git hooks are always blocked for security
25
+ denyPaths.push(path.resolve(cwd, '.git/hooks'));
26
+ denyPaths.push('**/.git/hooks/**');
27
+ // Git config - conditionally blocked based on allowGitConfig setting
28
+ if (!allowGitConfig) {
29
+ denyPaths.push(path.resolve(cwd, '.git/config'));
30
+ denyPaths.push('**/.git/config');
31
+ }
32
+ return [...new Set(denyPaths)];
33
+ }
34
+ const sessionSuffix = `_${Math.random().toString(36).slice(2, 11)}_SBX`;
35
+ /**
36
+ * Generate a unique log tag for sandbox monitoring
37
+ * @param command - The command being executed (will be base64 encoded)
38
+ */
39
+ function generateLogTag(command) {
40
+ const encodedCommand = encodeSandboxedCommand(command);
41
+ return `CMD64_${encodedCommand}_END_${sessionSuffix}`;
42
+ }
43
+ /**
44
+ * Get all ancestor directories for a path, up to (but not including) root
45
+ * Example: /private/tmp/test/file.txt -> ["/private/tmp/test", "/private/tmp", "/private"]
46
+ */
47
+ function getAncestorDirectories(pathStr) {
48
+ const ancestors = [];
49
+ let currentPath = path.dirname(pathStr);
50
+ // Walk up the directory tree until we reach root
51
+ while (currentPath !== '/' && currentPath !== '.') {
52
+ ancestors.push(currentPath);
53
+ const parentPath = path.dirname(currentPath);
54
+ // Break if we've reached the top (path.dirname returns the same path for root)
55
+ if (parentPath === currentPath) {
56
+ break;
57
+ }
58
+ currentPath = parentPath;
59
+ }
60
+ return ancestors;
61
+ }
62
+ /**
63
+ * Generate deny rules for file movement (file-write-unlink) to protect paths
64
+ * This prevents bypassing read or write restrictions by moving files/directories
65
+ *
66
+ * @param pathPatterns - Array of path patterns to protect (can include globs)
67
+ * @param logTag - Log tag for sandbox violations
68
+ * @returns Array of sandbox profile rule lines
69
+ */
70
+ function generateMoveBlockingRules(pathPatterns, logTag) {
71
+ const rules = [];
72
+ for (const pathPattern of pathPatterns) {
73
+ const normalizedPath = normalizePathForSandbox(pathPattern);
74
+ if (containsGlobChars(normalizedPath)) {
75
+ // Use regex matching for glob patterns
76
+ const regexPattern = globToRegex(normalizedPath);
77
+ // Block moving/renaming files matching this pattern
78
+ rules.push(`(deny file-write-unlink`, ` (regex ${escapePath(regexPattern)})`, ` (with message "${logTag}"))`);
79
+ // For glob patterns, extract the static prefix and block ancestor moves
80
+ // Remove glob characters to get the directory prefix
81
+ const staticPrefix = normalizedPath.split(/[*?[\]]/)[0];
82
+ if (staticPrefix && staticPrefix !== '/') {
83
+ // Get the directory containing the glob pattern
84
+ const baseDir = staticPrefix.endsWith('/')
85
+ ? staticPrefix.slice(0, -1)
86
+ : path.dirname(staticPrefix);
87
+ // Block moves of the base directory itself
88
+ rules.push(`(deny file-write-unlink`, ` (literal ${escapePath(baseDir)})`, ` (with message "${logTag}"))`);
89
+ // Block moves of ancestor directories
90
+ for (const ancestorDir of getAncestorDirectories(baseDir)) {
91
+ rules.push(`(deny file-write-unlink`, ` (literal ${escapePath(ancestorDir)})`, ` (with message "${logTag}"))`);
92
+ }
93
+ }
94
+ }
95
+ else {
96
+ // Use subpath matching for literal paths
97
+ // Block moving/renaming the denied path itself
98
+ rules.push(`(deny file-write-unlink`, ` (subpath ${escapePath(normalizedPath)})`, ` (with message "${logTag}"))`);
99
+ // Block moves of ancestor directories
100
+ for (const ancestorDir of getAncestorDirectories(normalizedPath)) {
101
+ rules.push(`(deny file-write-unlink`, ` (literal ${escapePath(ancestorDir)})`, ` (with message "${logTag}"))`);
102
+ }
103
+ }
104
+ }
105
+ return rules;
106
+ }
107
+ /**
108
+ * Generate filesystem read rules for sandbox profile
109
+ *
110
+ * Supports two layers:
111
+ * 1. denyOnly: deny reads from these paths (broad regions like /Users)
112
+ * 2. allowWithinDeny: re-allow reads within denied regions (like CWD)
113
+ * allowWithinDeny takes precedence over denyOnly.
114
+ *
115
+ * In Seatbelt profiles, later rules take precedence, so we emit:
116
+ * (allow file-read*) ← default: allow everything
117
+ * (deny file-read* ...) ← deny broad regions
118
+ * (allow file-read* ...) ← re-allow specific paths within denied regions
119
+ */
120
+ function generateReadRules(config, logTag) {
121
+ if (!config) {
122
+ return [`(allow file-read*)`];
123
+ }
124
+ const rules = [];
125
+ // Start by allowing everything
126
+ rules.push(`(allow file-read*)`);
127
+ // Then deny specific paths
128
+ for (const pathPattern of config.denyOnly || []) {
129
+ const normalizedPath = normalizePathForSandbox(pathPattern);
130
+ if (containsGlobChars(normalizedPath)) {
131
+ // Use regex matching for glob patterns
132
+ const regexPattern = globToRegex(normalizedPath);
133
+ rules.push(`(deny file-read*`, ` (regex ${escapePath(regexPattern)})`, ` (with message "${logTag}"))`);
134
+ }
135
+ else {
136
+ // Use subpath matching for literal paths
137
+ rules.push(`(deny file-read*`, ` (subpath ${escapePath(normalizedPath)})`, ` (with message "${logTag}"))`);
138
+ }
139
+ }
140
+ // Re-allow specific paths within denied regions (allowWithinDeny takes precedence)
141
+ for (const pathPattern of config.allowWithinDeny || []) {
142
+ const normalizedPath = normalizePathForSandbox(pathPattern);
143
+ if (containsGlobChars(normalizedPath)) {
144
+ const regexPattern = globToRegex(normalizedPath);
145
+ rules.push(`(allow file-read*`, ` (regex ${escapePath(regexPattern)})`, ` (with message "${logTag}"))`);
146
+ }
147
+ else {
148
+ rules.push(`(allow file-read*`, ` (subpath ${escapePath(normalizedPath)})`, ` (with message "${logTag}"))`);
149
+ }
150
+ }
151
+ // Allow stat/lstat on all directories so that realpath() can traverse
152
+ // path components within denied regions. Without this, C realpath() fails
153
+ // when resolving symlinks because it needs to lstat every intermediate
154
+ // directory (e.g. /Users, /Users/chris) even if only a subdirectory like
155
+ // ~/.local is in allowWithinDeny. This only allows metadata reads on
156
+ // directories — not listing contents (readdir) or reading files.
157
+ if (config.denyOnly.length > 0) {
158
+ rules.push(`(allow file-read-metadata`, ` (vnode-type DIRECTORY))`);
159
+ }
160
+ // Block file movement to prevent bypass via mv/rename
161
+ rules.push(...generateMoveBlockingRules(config.denyOnly || [], logTag));
162
+ return rules;
163
+ }
164
+ /**
165
+ * Generate filesystem write rules for sandbox profile
166
+ */
167
+ function generateWriteRules(config, logTag, allowGitConfig = false) {
168
+ if (!config) {
169
+ return [`(allow file-write*)`];
170
+ }
171
+ const rules = [];
172
+ // Automatically allow TMPDIR parent on macOS when write restrictions are enabled
173
+ const tmpdirParents = getTmpdirParentIfMacOSPattern();
174
+ for (const tmpdirParent of tmpdirParents) {
175
+ const normalizedPath = normalizePathForSandbox(tmpdirParent);
176
+ rules.push(`(allow file-write*`, ` (subpath ${escapePath(normalizedPath)})`, ` (with message "${logTag}"))`);
177
+ }
178
+ // Generate allow rules
179
+ for (const pathPattern of config.allowOnly || []) {
180
+ const normalizedPath = normalizePathForSandbox(pathPattern);
181
+ if (containsGlobChars(normalizedPath)) {
182
+ // Use regex matching for glob patterns
183
+ const regexPattern = globToRegex(normalizedPath);
184
+ rules.push(`(allow file-write*`, ` (regex ${escapePath(regexPattern)})`, ` (with message "${logTag}"))`);
185
+ }
186
+ else {
187
+ // Use subpath matching for literal paths
188
+ rules.push(`(allow file-write*`, ` (subpath ${escapePath(normalizedPath)})`, ` (with message "${logTag}"))`);
189
+ }
190
+ }
191
+ // Combine user-specified and mandatory deny patterns (no ripgrep needed on macOS)
192
+ const denyPaths = [
193
+ ...(config.denyWithinAllow || []),
194
+ ...macGetMandatoryDenyPatterns(allowGitConfig),
195
+ ];
196
+ for (const pathPattern of denyPaths) {
197
+ const normalizedPath = normalizePathForSandbox(pathPattern);
198
+ if (containsGlobChars(normalizedPath)) {
199
+ // Use regex matching for glob patterns
200
+ const regexPattern = globToRegex(normalizedPath);
201
+ rules.push(`(deny file-write*`, ` (regex ${escapePath(regexPattern)})`, ` (with message "${logTag}"))`);
202
+ }
203
+ else {
204
+ // Use subpath matching for literal paths
205
+ rules.push(`(deny file-write*`, ` (subpath ${escapePath(normalizedPath)})`, ` (with message "${logTag}"))`);
206
+ }
207
+ }
208
+ // Block file movement to prevent bypass via mv/rename
209
+ rules.push(...generateMoveBlockingRules(denyPaths, logTag));
210
+ return rules;
211
+ }
212
+ /**
213
+ * Generate complete sandbox profile
214
+ */
215
+ function generateSandboxProfile({ readConfig, writeConfig, httpProxyPort, socksProxyPort, needsNetworkRestriction, allowUnixSockets, allowAllUnixSockets, allowLocalBinding, allowPty, allowBrowserProcess = false, allowGitConfig = false, enableWeakerNetworkIsolation = false, logTag, }) {
216
+ const profile = [
217
+ '(version 1)',
218
+ `(deny default (with message "${logTag}"))`,
219
+ '',
220
+ `; LogTag: ${logTag}`,
221
+ '',
222
+ '; Essential permissions - based on Chrome sandbox policy',
223
+ '; Process permissions',
224
+ '(allow process-exec)',
225
+ '(allow process-fork)',
226
+ '(allow process-info* (target same-sandbox))',
227
+ '(allow signal (target same-sandbox))',
228
+ '(allow mach-priv-task-port (target same-sandbox))',
229
+ '',
230
+ '; User preferences',
231
+ '(allow user-preference-read)',
232
+ '',
233
+ '; Mach IPC - specific services only (no wildcard)',
234
+ '(allow mach-lookup',
235
+ ' (global-name "com.apple.audio.systemsoundserver")',
236
+ ' (global-name "com.apple.distributed_notifications@Uv3")',
237
+ ' (global-name "com.apple.FontObjectsServer")',
238
+ ' (global-name "com.apple.fonts")',
239
+ ' (global-name "com.apple.logd")',
240
+ ' (global-name "com.apple.lsd.mapdb")',
241
+ ' (global-name "com.apple.PowerManagement.control")',
242
+ ' (global-name "com.apple.system.logger")',
243
+ ' (global-name "com.apple.system.notification_center")',
244
+ ' (global-name "com.apple.system.opendirectoryd.libinfo")',
245
+ ' (global-name "com.apple.system.opendirectoryd.membership")',
246
+ ' (global-name "com.apple.bsd.dirhelper")',
247
+ ' (global-name "com.apple.securityd.xpc")',
248
+ ' (global-name "com.apple.coreservices.launchservicesd")',
249
+ ' (global-name "com.apple.SystemConfiguration.configd")',
250
+ ')',
251
+ '',
252
+ ...(enableWeakerNetworkIsolation
253
+ ? [
254
+ '; trustd.agent - needed for Go TLS certificate verification (weaker network isolation)',
255
+ '(allow mach-lookup (global-name "com.apple.trustd.agent"))',
256
+ ]
257
+ : []),
258
+ '',
259
+ '; POSIX IPC - shared memory',
260
+ '(allow ipc-posix-shm)',
261
+ '',
262
+ '; POSIX IPC - semaphores for Python multiprocessing',
263
+ '(allow ipc-posix-sem)',
264
+ '',
265
+ '; IOKit - specific operations only',
266
+ '(allow iokit-open',
267
+ ' (iokit-registry-entry-class "IOSurfaceRootUserClient")',
268
+ ' (iokit-registry-entry-class "RootDomainUserClient")',
269
+ ' (iokit-user-client-class "IOSurfaceSendRight")',
270
+ ')',
271
+ '',
272
+ '; IOKit properties',
273
+ '(allow iokit-get-properties)',
274
+ '',
275
+ "; Specific safe system-sockets, doesn't allow network access",
276
+ '(allow system-socket (require-all (socket-domain AF_SYSTEM) (socket-protocol 2)))',
277
+ '',
278
+ '; sysctl - specific sysctls only',
279
+ '(allow sysctl-read',
280
+ ' (sysctl-name "hw.activecpu")',
281
+ ' (sysctl-name "hw.busfrequency_compat")',
282
+ ' (sysctl-name "hw.byteorder")',
283
+ ' (sysctl-name "hw.cacheconfig")',
284
+ ' (sysctl-name "hw.cachelinesize_compat")',
285
+ ' (sysctl-name "hw.cpufamily")',
286
+ ' (sysctl-name "hw.cpufrequency")',
287
+ ' (sysctl-name "hw.cpufrequency_compat")',
288
+ ' (sysctl-name "hw.cputype")',
289
+ ' (sysctl-name "hw.l1dcachesize_compat")',
290
+ ' (sysctl-name "hw.l1icachesize_compat")',
291
+ ' (sysctl-name "hw.l2cachesize_compat")',
292
+ ' (sysctl-name "hw.l3cachesize_compat")',
293
+ ' (sysctl-name "hw.logicalcpu")',
294
+ ' (sysctl-name "hw.logicalcpu_max")',
295
+ ' (sysctl-name "hw.machine")',
296
+ ' (sysctl-name "hw.memsize")',
297
+ ' (sysctl-name "hw.ncpu")',
298
+ ' (sysctl-name "hw.nperflevels")',
299
+ ' (sysctl-name "hw.packages")',
300
+ ' (sysctl-name "hw.pagesize_compat")',
301
+ ' (sysctl-name "hw.pagesize")',
302
+ ' (sysctl-name "hw.physicalcpu")',
303
+ ' (sysctl-name "hw.physicalcpu_max")',
304
+ ' (sysctl-name "hw.tbfrequency_compat")',
305
+ ' (sysctl-name "hw.vectorunit")',
306
+ ' (sysctl-name "kern.argmax")',
307
+ ' (sysctl-name "kern.bootargs")',
308
+ ' (sysctl-name "kern.hostname")',
309
+ ' (sysctl-name "kern.maxfiles")',
310
+ ' (sysctl-name "kern.maxfilesperproc")',
311
+ ' (sysctl-name "kern.maxproc")',
312
+ ' (sysctl-name "kern.ngroups")',
313
+ ' (sysctl-name "kern.osproductversion")',
314
+ ' (sysctl-name "kern.osrelease")',
315
+ ' (sysctl-name "kern.ostype")',
316
+ ' (sysctl-name "kern.osvariant_status")',
317
+ ' (sysctl-name "kern.osversion")',
318
+ ' (sysctl-name "kern.secure_kernel")',
319
+ ' (sysctl-name "kern.tcsm_available")',
320
+ ' (sysctl-name "kern.tcsm_enable")',
321
+ ' (sysctl-name "kern.usrstack64")',
322
+ ' (sysctl-name "kern.version")',
323
+ ' (sysctl-name "kern.willshutdown")',
324
+ ' (sysctl-name "machdep.cpu.brand_string")',
325
+ ' (sysctl-name "machdep.ptrauth_enabled")',
326
+ ' (sysctl-name "security.mac.lockdown_mode_state")',
327
+ ' (sysctl-name "sysctl.proc_cputype")',
328
+ ' (sysctl-name "vm.loadavg")',
329
+ ' (sysctl-name-prefix "hw.optional.arm")',
330
+ ' (sysctl-name-prefix "hw.optional.arm.")',
331
+ ' (sysctl-name-prefix "hw.optional.armv8_")',
332
+ ' (sysctl-name-prefix "hw.perflevel")',
333
+ ' (sysctl-name-prefix "kern.proc.all")',
334
+ ' (sysctl-name-prefix "kern.proc.pgrp.")',
335
+ ' (sysctl-name-prefix "kern.proc.pid.")',
336
+ ' (sysctl-name-prefix "machdep.cpu.")',
337
+ ' (sysctl-name-prefix "net.routetable.")',
338
+ ')',
339
+ '',
340
+ '; V8 thread calculations',
341
+ '(allow sysctl-write',
342
+ ' (sysctl-name "kern.tcsm_enable")',
343
+ ')',
344
+ '',
345
+ '; Distributed notifications',
346
+ '(allow distributed-notification-post)',
347
+ '',
348
+ '; Specific mach-lookup permissions for security operations',
349
+ '(allow mach-lookup (global-name "com.apple.SecurityServer"))',
350
+ '',
351
+ '; File I/O on device files',
352
+ '(allow file-ioctl (literal "/dev/null"))',
353
+ '(allow file-ioctl (literal "/dev/zero"))',
354
+ '(allow file-ioctl (literal "/dev/random"))',
355
+ '(allow file-ioctl (literal "/dev/urandom"))',
356
+ '(allow file-ioctl (literal "/dev/dtracehelper"))',
357
+ '(allow file-ioctl (literal "/dev/tty"))',
358
+ '',
359
+ '(allow file-ioctl file-read-data file-write-data',
360
+ ' (require-all',
361
+ ' (literal "/dev/null")',
362
+ ' (vnode-type CHARACTER-DEVICE)',
363
+ ' )',
364
+ ')',
365
+ '',
366
+ ];
367
+ // Network rules
368
+ profile.push('; Network');
369
+ if (!needsNetworkRestriction) {
370
+ profile.push('(allow network*)');
371
+ }
372
+ else {
373
+ // Allow local binding if requested
374
+ // Use "*:*" instead of "localhost:*" because modern runtimes (Java, etc.) create
375
+ // IPv6 dual-stack sockets by default. When binding such a socket to 127.0.0.1,
376
+ // the kernel represents it as ::ffff:127.0.0.1 (IPv4-mapped IPv6). Seatbelt's
377
+ // "localhost" filter only matches 127.0.0.1 and ::1, NOT ::ffff:127.0.0.1.
378
+ // Using (local ip "*:*") is safe because it only matches the LOCAL endpoint —
379
+ // internet-bound connections originate from non-loopback interfaces, so they
380
+ // remain blocked by (deny default).
381
+ if (allowLocalBinding) {
382
+ profile.push('(allow network-bind (local ip "*:*"))');
383
+ profile.push('(allow network-inbound (local ip "*:*"))');
384
+ profile.push('(allow network-outbound (local ip "*:*"))');
385
+ }
386
+ // Unix domain sockets for local IPC (SSH agent, Docker, Gradle, etc.)
387
+ // Three separate operations must be allowed:
388
+ // 1. system-socket: socket(AF_UNIX, ...) syscall — creates the socket fd (no path context)
389
+ // 2. network-bind: bind() to a local Unix socket path
390
+ // 3. network-outbound: connect() to a remote Unix socket path
391
+ // Note: (subpath ...) and (path-regex ...) are path-based filters that can only match
392
+ // bind/connect operations — socket() creation has no path, so it requires system-socket.
393
+ if (allowAllUnixSockets) {
394
+ // Allow creating AF_UNIX sockets and all Unix socket paths
395
+ profile.push('(allow system-socket (socket-domain AF_UNIX))');
396
+ profile.push('(allow network-bind (local unix-socket (path-regex #"^/")))');
397
+ profile.push('(allow network-outbound (remote unix-socket (path-regex #"^/")))');
398
+ }
399
+ else if (allowUnixSockets && allowUnixSockets.length > 0) {
400
+ // Allow creating AF_UNIX sockets (required for any Unix socket use)
401
+ profile.push('(allow system-socket (socket-domain AF_UNIX))');
402
+ // Allow specific Unix socket paths
403
+ for (const socketPath of allowUnixSockets) {
404
+ const normalizedPath = normalizePathForSandbox(socketPath);
405
+ profile.push(`(allow network-bind (local unix-socket (subpath ${escapePath(normalizedPath)})))`);
406
+ profile.push(`(allow network-outbound (remote unix-socket (subpath ${escapePath(normalizedPath)})))`);
407
+ }
408
+ }
409
+ // If both allowAllUnixSockets and allowUnixSockets are false/undefined/empty, Unix sockets are blocked by default
410
+ // Allow localhost TCP operations for the HTTP proxy
411
+ if (httpProxyPort !== undefined) {
412
+ profile.push(`(allow network-bind (local ip "localhost:${httpProxyPort}"))`);
413
+ profile.push(`(allow network-inbound (local ip "localhost:${httpProxyPort}"))`);
414
+ profile.push(`(allow network-outbound (remote ip "localhost:${httpProxyPort}"))`);
415
+ }
416
+ // Allow localhost TCP operations for the SOCKS proxy
417
+ if (socksProxyPort !== undefined) {
418
+ profile.push(`(allow network-bind (local ip "localhost:${socksProxyPort}"))`);
419
+ profile.push(`(allow network-inbound (local ip "localhost:${socksProxyPort}"))`);
420
+ profile.push(`(allow network-outbound (remote ip "localhost:${socksProxyPort}"))`);
421
+ }
422
+ }
423
+ profile.push('');
424
+ // Read rules
425
+ profile.push('; File read');
426
+ profile.push(...generateReadRules(readConfig, logTag));
427
+ profile.push('');
428
+ // Write rules
429
+ profile.push('; File write');
430
+ profile.push(...generateWriteRules(writeConfig, logTag, allowGitConfig));
431
+ // Pseudo-terminal (pty) support
432
+ if (allowPty) {
433
+ profile.push('');
434
+ profile.push('; Pseudo-terminal (pty) support');
435
+ profile.push('(allow pseudo-tty)');
436
+ profile.push('(allow file-ioctl');
437
+ profile.push(' (literal "/dev/ptmx")');
438
+ profile.push(' (regex #"^/dev/ttys")');
439
+ profile.push(')');
440
+ profile.push('(allow file-read* file-write*');
441
+ profile.push(' (literal "/dev/ptmx")');
442
+ profile.push(' (regex #"^/dev/ttys")');
443
+ profile.push(')');
444
+ }
445
+ // Browser process support (Chrome/Chromium)
446
+ //
447
+ // Chromium-based browsers need significantly broader OS permissions than
448
+ // typical CLI tools. The default Seatbelt profile is designed for commands
449
+ // like git, node, and npm — Chrome's multi-process architecture requires
450
+ // Mach IPC for inter-process communication, window server access, GPU
451
+ // drivers, crash reporting (Crashpad), and more. These services vary by
452
+ // macOS version and hardware, making an exhaustive allowlist impractical.
453
+ //
454
+ // This option grants:
455
+ // - All Mach operations (mach*): IPC, bootstrap registration, service
456
+ // lookups, task ports, cross-domain lookups. Needed for Crashpad,
457
+ // window server (CoreGraphics/SkyLight), CoreDisplay, GPU process, etc.
458
+ // - Unrestricted process-info: Chrome manages renderer, GPU, utility,
459
+ // and crashpad child processes outside the same sandbox boundary.
460
+ // - Broad IOKit access: GPU process and display management.
461
+ // - Unrestricted IPC shared memory: renderer ↔ GPU communication.
462
+ //
463
+ // Security note: this significantly widens the Mach IPC and process
464
+ // inspection surface. Filesystem and network restrictions remain fully
465
+ // enforced. Only enable when browser automation (e.g. agent-browser) is
466
+ // needed.
467
+ if (allowBrowserProcess) {
468
+ profile.push('');
469
+ profile.push('; Browser process support (Chrome/Chromium)');
470
+ profile.push('; All Mach operations — Chrome requires bootstrap registration');
471
+ profile.push('; (Crashpad), service lookups (window server, CoreDisplay, GPU),');
472
+ profile.push('; task ports, and cross-domain lookups that vary by OS version');
473
+ profile.push('(allow mach*)');
474
+ profile.push('');
475
+ profile.push('; Process info for all processes — Chrome manages renderer, GPU,');
476
+ profile.push('; utility, and crashpad child processes outside the same sandbox');
477
+ profile.push('(allow process-info*)');
478
+ profile.push('');
479
+ profile.push('; Broader IOKit access — needed for GPU process and display management');
480
+ profile.push('(allow iokit-open)');
481
+ profile.push('');
482
+ profile.push('; Shared memory with non-sandboxed processes (e.g. renderer ↔ GPU)');
483
+ profile.push('(allow ipc-posix-shm*)');
484
+ }
485
+ return profile.join('\n');
486
+ }
487
+ /**
488
+ * Escape path for sandbox profile using JSON.stringify for proper escaping
489
+ */
490
+ function escapePath(pathStr) {
491
+ return JSON.stringify(pathStr);
492
+ }
493
+ /**
494
+ * Get TMPDIR parent directory if it matches macOS pattern /var/folders/XX/YYY/T/
495
+ * Returns both /var/ and /private/var/ versions since /var is a symlink
496
+ */
497
+ function getTmpdirParentIfMacOSPattern() {
498
+ const tmpdir = process.env.TMPDIR;
499
+ if (!tmpdir)
500
+ return [];
501
+ const match = tmpdir.match(/^\/(private\/)?var\/folders\/[^/]{2}\/[^/]+\/T\/?$/);
502
+ if (!match)
503
+ return [];
504
+ const parent = tmpdir.replace(/\/T\/?$/, '');
505
+ // Return both /var/ and /private/var/ versions since /var is a symlink
506
+ if (parent.startsWith('/private/var/')) {
507
+ return [parent, parent.replace('/private', '')];
508
+ }
509
+ else if (parent.startsWith('/var/')) {
510
+ return [parent, '/private' + parent];
511
+ }
512
+ return [parent];
513
+ }
514
+ /**
515
+ * Wrap command with macOS sandbox
516
+ */
517
+ export function wrapCommandWithSandboxMacOS(params) {
518
+ const { command, needsNetworkRestriction, httpProxyPort, socksProxyPort, allowUnixSockets, allowAllUnixSockets, allowLocalBinding, readConfig, writeConfig, allowPty, allowBrowserProcess = false, allowGitConfig = false, enableWeakerNetworkIsolation = false, binShell, } = params;
519
+ // Determine if we have restrictions to apply
520
+ // Read: denyOnly pattern - empty array means no restrictions
521
+ // Write: allowOnly pattern - undefined means no restrictions, any config means restrictions
522
+ const hasReadRestrictions = readConfig && readConfig.denyOnly.length > 0;
523
+ const hasWriteRestrictions = writeConfig !== undefined;
524
+ // No sandboxing needed
525
+ if (!needsNetworkRestriction &&
526
+ !hasReadRestrictions &&
527
+ !hasWriteRestrictions) {
528
+ return command;
529
+ }
530
+ const logTag = generateLogTag(command);
531
+ const profile = generateSandboxProfile({
532
+ readConfig,
533
+ writeConfig,
534
+ httpProxyPort,
535
+ socksProxyPort,
536
+ needsNetworkRestriction,
537
+ allowUnixSockets,
538
+ allowAllUnixSockets,
539
+ allowLocalBinding,
540
+ allowPty,
541
+ allowBrowserProcess,
542
+ allowGitConfig,
543
+ enableWeakerNetworkIsolation,
544
+ logTag,
545
+ });
546
+ // Generate proxy environment variables using shared utility
547
+ const proxyEnvArgs = generateProxyEnvVars(httpProxyPort, socksProxyPort);
548
+ // Use the user's shell (zsh, bash, etc.) to ensure aliases/snapshots work
549
+ // Resolve the full path to the shell binary
550
+ const shellName = binShell || 'bash';
551
+ const shell = whichSync(shellName);
552
+ if (!shell) {
553
+ throw new Error(`Shell '${shellName}' not found in PATH`);
554
+ }
555
+ // Use `env` command to set environment variables - each VAR=value is a separate
556
+ // argument that shellquote handles properly, avoiding shell quoting issues
557
+ const wrappedCommand = shellquote.quote([
558
+ 'env',
559
+ ...proxyEnvArgs,
560
+ 'sandbox-exec',
561
+ '-p',
562
+ profile,
563
+ shell,
564
+ '-c',
565
+ command,
566
+ ]);
567
+ logForDebugging(`[Sandbox macOS] Applied restrictions - network: ${!!(httpProxyPort || socksProxyPort)}, read: ${readConfig
568
+ ? 'allowAllExcept' in readConfig
569
+ ? 'allowAllExcept'
570
+ : 'denyAllExcept'
571
+ : 'none'}, write: ${writeConfig
572
+ ? 'allowAllExcept' in writeConfig
573
+ ? 'allowAllExcept'
574
+ : 'denyAllExcept'
575
+ : 'none'}`);
576
+ return wrappedCommand;
577
+ }
578
+ /**
579
+ * Start monitoring macOS system logs for sandbox violations
580
+ * Look for sandbox-related kernel deny events ending in {logTag}
581
+ */
582
+ export function startMacOSSandboxLogMonitor(callback, ignoreViolations) {
583
+ // Pre-compile regex patterns for better performance
584
+ const cmdExtractRegex = /CMD64_(.+?)_END/;
585
+ const sandboxExtractRegex = /Sandbox:\s+(.+)$/;
586
+ // Pre-process ignore patterns for faster lookup
587
+ const wildcardPaths = ignoreViolations?.['*'] || [];
588
+ const commandPatterns = ignoreViolations
589
+ ? Object.entries(ignoreViolations).filter(([pattern]) => pattern !== '*')
590
+ : [];
591
+ // Stream and filter kernel logs for all sandbox violations
592
+ // We can't filter by specific logTag since it's dynamic per command
593
+ const logProcess = spawn('log', [
594
+ 'stream',
595
+ '--predicate',
596
+ `(eventMessage ENDSWITH "${sessionSuffix}")`,
597
+ '--style',
598
+ 'compact',
599
+ ]);
600
+ logProcess.stdout?.on('data', (data) => {
601
+ const lines = data.toString().split('\n');
602
+ // Get violation and command lines
603
+ const violationLine = lines.find(line => line.includes('Sandbox:') && line.includes('deny'));
604
+ const commandLine = lines.find(line => line.startsWith('CMD64_'));
605
+ if (!violationLine)
606
+ return;
607
+ // Extract violation details
608
+ const sandboxMatch = violationLine.match(sandboxExtractRegex);
609
+ if (!sandboxMatch?.[1])
610
+ return;
611
+ const violationDetails = sandboxMatch[1];
612
+ // Try to get command
613
+ let command;
614
+ let encodedCommand;
615
+ if (commandLine) {
616
+ const cmdMatch = commandLine.match(cmdExtractRegex);
617
+ encodedCommand = cmdMatch?.[1];
618
+ if (encodedCommand) {
619
+ try {
620
+ command = decodeSandboxedCommand(encodedCommand);
621
+ }
622
+ catch {
623
+ // Failed to decode, continue without command
624
+ }
625
+ }
626
+ }
627
+ // Always filter out noisey violations
628
+ if (violationDetails.includes('mDNSResponder') ||
629
+ violationDetails.includes('mach-lookup com.apple.diagnosticd') ||
630
+ violationDetails.includes('mach-lookup com.apple.analyticsd')) {
631
+ return;
632
+ }
633
+ // Check if we should ignore this violation
634
+ if (ignoreViolations && command) {
635
+ // Check wildcard patterns first
636
+ if (wildcardPaths.length > 0) {
637
+ const shouldIgnore = wildcardPaths.some(path => violationDetails.includes(path));
638
+ if (shouldIgnore)
639
+ return;
640
+ }
641
+ // Check command-specific patterns
642
+ for (const [pattern, paths] of commandPatterns) {
643
+ if (command.includes(pattern)) {
644
+ const shouldIgnore = paths.some(path => violationDetails.includes(path));
645
+ if (shouldIgnore)
646
+ return;
647
+ }
648
+ }
649
+ }
650
+ // Not ignored - report the violation
651
+ callback({
652
+ line: violationDetails,
653
+ command,
654
+ encodedCommand,
655
+ timestamp: new Date(), // We could parse the timestamp from the log but this feels more reliable
656
+ });
657
+ });
658
+ logProcess.stderr?.on('data', (data) => {
659
+ logForDebugging(`[Sandbox Monitor] Log stream stderr: ${data.toString()}`);
660
+ });
661
+ logProcess.on('error', (error) => {
662
+ logForDebugging(`[Sandbox Monitor] Failed to start log stream: ${error.message}`);
663
+ });
664
+ logProcess.on('exit', (code) => {
665
+ logForDebugging(`[Sandbox Monitor] Log stream exited with code: ${code}`);
666
+ });
667
+ return () => {
668
+ logForDebugging('[Sandbox Monitor] Stopping log monitor');
669
+ logProcess.kill('SIGTERM');
670
+ };
671
+ }
672
+ //# sourceMappingURL=macos-sandbox-utils.js.map