@bramvanoploo/sandbox-runtime 0.0.0-stage → 0.5.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 (136) hide show
  1. package/LICENSE +201 -0
  2. package/README.md +93 -2
  3. package/dist/cli.d.ts +3 -0
  4. package/dist/cli.d.ts.map +1 -0
  5. package/dist/cli.js +285 -0
  6. package/dist/cli.js.map +1 -0
  7. package/dist/index.d.ts +16 -0
  8. package/dist/index.d.ts.map +1 -0
  9. package/dist/index.js +12 -0
  10. package/dist/index.js.map +1 -0
  11. package/dist/sandbox/credential-decode.d.ts +87 -0
  12. package/dist/sandbox/credential-decode.d.ts.map +1 -0
  13. package/dist/sandbox/credential-decode.js +143 -0
  14. package/dist/sandbox/credential-decode.js.map +1 -0
  15. package/dist/sandbox/credential-extract.d.ts +67 -0
  16. package/dist/sandbox/credential-extract.d.ts.map +1 -0
  17. package/dist/sandbox/credential-extract.js +122 -0
  18. package/dist/sandbox/credential-extract.js.map +1 -0
  19. package/dist/sandbox/credential-mask-env.d.ts +33 -0
  20. package/dist/sandbox/credential-mask-env.d.ts.map +1 -0
  21. package/dist/sandbox/credential-mask-env.js +155 -0
  22. package/dist/sandbox/credential-mask-env.js.map +1 -0
  23. package/dist/sandbox/credential-mask-files.d.ts +120 -0
  24. package/dist/sandbox/credential-mask-files.d.ts.map +1 -0
  25. package/dist/sandbox/credential-mask-files.js +285 -0
  26. package/dist/sandbox/credential-mask-files.js.map +1 -0
  27. package/dist/sandbox/credential-sentinel.d.ts +88 -0
  28. package/dist/sandbox/credential-sentinel.d.ts.map +1 -0
  29. package/dist/sandbox/credential-sentinel.js +177 -0
  30. package/dist/sandbox/credential-sentinel.js.map +1 -0
  31. package/dist/sandbox/domain-pattern.d.ts +36 -0
  32. package/dist/sandbox/domain-pattern.d.ts.map +1 -0
  33. package/dist/sandbox/domain-pattern.js +60 -0
  34. package/dist/sandbox/domain-pattern.js.map +1 -0
  35. package/dist/sandbox/generate-seccomp-filter.d.ts +20 -0
  36. package/dist/sandbox/generate-seccomp-filter.d.ts.map +1 -0
  37. package/dist/sandbox/generate-seccomp-filter.js +168 -0
  38. package/dist/sandbox/generate-seccomp-filter.js.map +1 -0
  39. package/dist/sandbox/http-proxy.d.ts +85 -0
  40. package/dist/sandbox/http-proxy.d.ts.map +1 -0
  41. package/dist/sandbox/http-proxy.js +379 -0
  42. package/dist/sandbox/http-proxy.js.map +1 -0
  43. package/dist/sandbox/linux-sandbox-utils.d.ts +162 -0
  44. package/dist/sandbox/linux-sandbox-utils.d.ts.map +1 -0
  45. package/dist/sandbox/linux-sandbox-utils.js +1179 -0
  46. package/dist/sandbox/linux-sandbox-utils.js.map +1 -0
  47. package/dist/sandbox/linux-violation-monitor.d.ts +48 -0
  48. package/dist/sandbox/linux-violation-monitor.d.ts.map +1 -0
  49. package/dist/sandbox/linux-violation-monitor.js +168 -0
  50. package/dist/sandbox/linux-violation-monitor.js.map +1 -0
  51. package/dist/sandbox/listen-in-range.d.ts +12 -0
  52. package/dist/sandbox/listen-in-range.d.ts.map +1 -0
  53. package/dist/sandbox/listen-in-range.js +43 -0
  54. package/dist/sandbox/listen-in-range.js.map +1 -0
  55. package/dist/sandbox/macos-sandbox-utils.d.ts +57 -0
  56. package/dist/sandbox/macos-sandbox-utils.d.ts.map +1 -0
  57. package/dist/sandbox/macos-sandbox-utils.js +810 -0
  58. package/dist/sandbox/macos-sandbox-utils.js.map +1 -0
  59. package/dist/sandbox/mitm-ca.d.ts +112 -0
  60. package/dist/sandbox/mitm-ca.d.ts.map +1 -0
  61. package/dist/sandbox/mitm-ca.js +380 -0
  62. package/dist/sandbox/mitm-ca.js.map +1 -0
  63. package/dist/sandbox/mitm-leaf.d.ts +28 -0
  64. package/dist/sandbox/mitm-leaf.d.ts.map +1 -0
  65. package/dist/sandbox/mitm-leaf.js +132 -0
  66. package/dist/sandbox/mitm-leaf.js.map +1 -0
  67. package/dist/sandbox/mux-proxy.d.ts +59 -0
  68. package/dist/sandbox/mux-proxy.d.ts.map +1 -0
  69. package/dist/sandbox/mux-proxy.js +161 -0
  70. package/dist/sandbox/mux-proxy.js.map +1 -0
  71. package/dist/sandbox/parent-proxy.d.ts +118 -0
  72. package/dist/sandbox/parent-proxy.d.ts.map +1 -0
  73. package/dist/sandbox/parent-proxy.js +469 -0
  74. package/dist/sandbox/parent-proxy.js.map +1 -0
  75. package/dist/sandbox/request-filter.d.ts +56 -0
  76. package/dist/sandbox/request-filter.d.ts.map +1 -0
  77. package/dist/sandbox/request-filter.js +109 -0
  78. package/dist/sandbox/request-filter.js.map +1 -0
  79. package/dist/sandbox/sandbox-config.d.ts +1347 -0
  80. package/dist/sandbox/sandbox-config.d.ts.map +1 -0
  81. package/dist/sandbox/sandbox-config.js +917 -0
  82. package/dist/sandbox/sandbox-config.js.map +1 -0
  83. package/dist/sandbox/sandbox-manager.d.ts +48 -0
  84. package/dist/sandbox/sandbox-manager.d.ts.map +1 -0
  85. package/dist/sandbox/sandbox-manager.js +1498 -0
  86. package/dist/sandbox/sandbox-manager.js.map +1 -0
  87. package/dist/sandbox/sandbox-schemas.d.ts +90 -0
  88. package/dist/sandbox/sandbox-schemas.d.ts.map +1 -0
  89. package/dist/sandbox/sandbox-schemas.js +3 -0
  90. package/dist/sandbox/sandbox-schemas.js.map +1 -0
  91. package/dist/sandbox/sandbox-temp-dir.d.ts +9 -0
  92. package/dist/sandbox/sandbox-temp-dir.d.ts.map +1 -0
  93. package/dist/sandbox/sandbox-temp-dir.js +73 -0
  94. package/dist/sandbox/sandbox-temp-dir.js.map +1 -0
  95. package/dist/sandbox/sandbox-utils.d.ts +121 -0
  96. package/dist/sandbox/sandbox-utils.d.ts.map +1 -0
  97. package/dist/sandbox/sandbox-utils.js +642 -0
  98. package/dist/sandbox/sandbox-utils.js.map +1 -0
  99. package/dist/sandbox/sandbox-violation-store.d.ts +19 -0
  100. package/dist/sandbox/sandbox-violation-store.d.ts.map +1 -0
  101. package/dist/sandbox/sandbox-violation-store.js +57 -0
  102. package/dist/sandbox/sandbox-violation-store.js.map +1 -0
  103. package/dist/sandbox/socks-proxy.d.ts +38 -0
  104. package/dist/sandbox/socks-proxy.d.ts.map +1 -0
  105. package/dist/sandbox/socks-proxy.js +123 -0
  106. package/dist/sandbox/socks-proxy.js.map +1 -0
  107. package/dist/sandbox/tls-terminate-proxy.d.ts +63 -0
  108. package/dist/sandbox/tls-terminate-proxy.d.ts.map +1 -0
  109. package/dist/sandbox/tls-terminate-proxy.js +332 -0
  110. package/dist/sandbox/tls-terminate-proxy.js.map +1 -0
  111. package/dist/sandbox/windows-sandbox-utils.d.ts +625 -0
  112. package/dist/sandbox/windows-sandbox-utils.d.ts.map +1 -0
  113. package/dist/sandbox/windows-sandbox-utils.js +982 -0
  114. package/dist/sandbox/windows-sandbox-utils.js.map +1 -0
  115. package/dist/utils/config-loader.d.ts +24 -0
  116. package/dist/utils/config-loader.d.ts.map +1 -0
  117. package/dist/utils/config-loader.js +65 -0
  118. package/dist/utils/config-loader.js.map +1 -0
  119. package/dist/utils/debug.d.ts +7 -0
  120. package/dist/utils/debug.d.ts.map +1 -0
  121. package/dist/utils/debug.js +25 -0
  122. package/dist/utils/debug.js.map +1 -0
  123. package/dist/utils/platform.d.ts +15 -0
  124. package/dist/utils/platform.d.ts.map +1 -0
  125. package/dist/utils/platform.js +52 -0
  126. package/dist/utils/platform.js.map +1 -0
  127. package/dist/utils/shell-quote.d.ts +27 -0
  128. package/dist/utils/shell-quote.d.ts.map +1 -0
  129. package/dist/utils/shell-quote.js +47 -0
  130. package/dist/utils/shell-quote.js.map +1 -0
  131. package/dist/utils/which.d.ts +9 -0
  132. package/dist/utils/which.d.ts.map +1 -0
  133. package/dist/utils/which.js +28 -0
  134. package/dist/utils/which.js.map +1 -0
  135. package/package.json +85 -4
  136. package/vendor/seccomp/x64/apply-seccomp +0 -0
@@ -0,0 +1,810 @@
1
+ import { quote } from '../utils/shell-quote.js';
2
+ import { spawn } from 'child_process';
3
+ import * as path from 'path';
4
+ import { createInterface } from 'node:readline';
5
+ import { logForDebugging } from '../utils/debug.js';
6
+ import { whichSync } from '../utils/which.js';
7
+ import { normalizePathForSandbox, generateProxyEnvVars, encodeSandboxedCommand, decodeSandboxedCommand, containsGlobChars, globToRegex, globBaseDir, } from './sandbox-utils.js';
8
+ const defaultSessionSuffix = `_${Math.random().toString(36).slice(2, 11)}_SBX`;
9
+ /**
10
+ * Generate a unique log tag for sandbox monitoring
11
+ * @param command - The command being executed (will be base64 encoded)
12
+ */
13
+ function generateLogTag(command, sessionSuffix = defaultSessionSuffix) {
14
+ const encodedCommand = encodeSandboxedCommand(command);
15
+ return `CMD64_${encodedCommand}_END_${sessionSuffix}`;
16
+ }
17
+ /**
18
+ * Get all ancestor directories for a path, up to (but not including) root
19
+ * Example: /private/tmp/test/file.txt -> ["/private/tmp/test", "/private/tmp", "/private"]
20
+ */
21
+ function getAncestorDirectories(pathStr) {
22
+ const ancestors = [];
23
+ let currentPath = path.dirname(pathStr);
24
+ // Walk up the directory tree until we reach root
25
+ while (currentPath !== '/' && currentPath !== '.') {
26
+ ancestors.push(currentPath);
27
+ const parentPath = path.dirname(currentPath);
28
+ // Break if we've reached the top (path.dirname returns the same path for root)
29
+ if (parentPath === currentPath) {
30
+ break;
31
+ }
32
+ currentPath = parentPath;
33
+ }
34
+ return ancestors;
35
+ }
36
+ /**
37
+ * Generate deny rules for file movement (file-write-unlink) and creation
38
+ * (file-write-create) to protect paths. This prevents bypassing read or write
39
+ * restrictions by moving files/directories, and prevents replacing a
40
+ * not-yet-existing protected path (or one of its ancestors) with an
41
+ * attacker-controlled symlink.
42
+ *
43
+ * @param pathPatterns - Array of path patterns to protect (can include globs)
44
+ * @param logTag - Log tag for sandbox violations
45
+ * @returns Array of sandbox profile rule lines
46
+ */
47
+ function generateMoveBlockingRules(pathPatterns, logTag) {
48
+ const rules = [];
49
+ const ops = ['file-write-unlink', 'file-write-create'];
50
+ for (const pathPattern of pathPatterns) {
51
+ const normalizedPath = normalizePathForSandbox(pathPattern);
52
+ if (containsGlobChars(normalizedPath)) {
53
+ // Use regex matching for glob patterns
54
+ const regexPattern = globToRegex(normalizedPath);
55
+ // Block moving/renaming files matching this pattern
56
+ for (const op of ops) {
57
+ rules.push(`(deny ${op}`, ` (regex ${escapePath(regexPattern)})`, ` (with message "${logTag}"))`);
58
+ }
59
+ // For glob patterns, extract the static prefix and block ancestor moves
60
+ const baseDir = globBaseDir(normalizedPath, false);
61
+ if (baseDir) {
62
+ // Block moves of the base directory itself
63
+ for (const op of ops) {
64
+ rules.push(`(deny ${op}`, ` (literal ${escapePath(baseDir)})`, ` (with message "${logTag}"))`);
65
+ }
66
+ // Block moves of ancestor directories
67
+ for (const ancestorDir of getAncestorDirectories(baseDir)) {
68
+ for (const op of ops) {
69
+ rules.push(`(deny ${op}`, ` (literal ${escapePath(ancestorDir)})`, ` (with message "${logTag}"))`);
70
+ }
71
+ }
72
+ }
73
+ }
74
+ else {
75
+ // Use subpath matching for literal paths
76
+ // Block moving/renaming the denied path itself
77
+ for (const op of ops) {
78
+ rules.push(`(deny ${op}`, ` (subpath ${escapePath(normalizedPath)})`, ` (with message "${logTag}"))`);
79
+ }
80
+ // Block moves of ancestor directories
81
+ for (const ancestorDir of getAncestorDirectories(normalizedPath)) {
82
+ for (const op of ops) {
83
+ rules.push(`(deny ${op}`, ` (literal ${escapePath(ancestorDir)})`, ` (with message "${logTag}"))`);
84
+ }
85
+ }
86
+ }
87
+ }
88
+ return rules;
89
+ }
90
+ /**
91
+ * Generate filesystem read rules for sandbox profile
92
+ *
93
+ * Supports two layers:
94
+ * 1. denyOnly: deny reads from these paths (broad regions like /Users)
95
+ * 2. allowWithinDeny: re-allow reads within denied regions (like CWD)
96
+ * allowWithinDeny takes precedence over denyOnly.
97
+ *
98
+ * In Seatbelt profiles, later rules take precedence, so we emit:
99
+ * (allow file-read*) ← default: allow everything
100
+ * (deny file-read* ...) ← deny broad regions
101
+ * (allow file-read* ...) ← re-allow specific paths within denied regions
102
+ */
103
+ function generateReadRules(config, logTag, writeAllowPaths) {
104
+ if (!config) {
105
+ return [`(allow file-read*)`];
106
+ }
107
+ const rules = [];
108
+ let deniesRoot = false;
109
+ // Start by allowing everything
110
+ rules.push(`(allow file-read*)`);
111
+ // Then deny specific paths
112
+ for (const pathPattern of config.denyOnly || []) {
113
+ const normalizedPath = normalizePathForSandbox(pathPattern);
114
+ if (normalizedPath === '/')
115
+ deniesRoot = true;
116
+ if (containsGlobChars(normalizedPath)) {
117
+ // Use regex matching for glob patterns
118
+ const regexPattern = globToRegex(normalizedPath);
119
+ rules.push(`(deny file-read*`, ` (regex ${escapePath(regexPattern)})`, ` (with message "${logTag}"))`);
120
+ }
121
+ else {
122
+ // Use subpath matching for literal paths
123
+ rules.push(`(deny file-read*`, ` (subpath ${escapePath(normalizedPath)})`, ` (with message "${logTag}"))`);
124
+ }
125
+ }
126
+ // (subpath "/") denies the root inode itself; allowWithinDeny subpaths don't
127
+ // cover "/", so dyld aborts before exec. Re-allow the literal root so path
128
+ // traversal works. This exposes `ls /` dirent names but no subtree contents.
129
+ if (deniesRoot) {
130
+ rules.push(`(allow file-read* (literal "/"))`);
131
+ }
132
+ // Re-allow specific paths within denied regions (allowWithinDeny takes precedence)
133
+ const allowedSubpaths = [];
134
+ const allowedGlobRegexes = [];
135
+ for (const pathPattern of config.allowWithinDeny || []) {
136
+ const normalizedPath = normalizePathForSandbox(pathPattern);
137
+ if (containsGlobChars(normalizedPath)) {
138
+ const regexPattern = globToRegex(normalizedPath);
139
+ allowedGlobRegexes.push(new RegExp(regexPattern));
140
+ rules.push(`(allow file-read*`, ` (regex ${escapePath(regexPattern)})`, ` (with message "${logTag}"))`);
141
+ }
142
+ else {
143
+ allowedSubpaths.push(normalizedPath);
144
+ rules.push(`(allow file-read*`, ` (subpath ${escapePath(normalizedPath)})`, ` (with message "${logTag}"))`);
145
+ }
146
+ }
147
+ // A denyOnly path nested inside an allowWithinDeny path would
148
+ // otherwise be re-allowed (last-match-wins). Re-emit it so the
149
+ // more-specific deny lands last. A literal deny is more specific when it
150
+ // lies strictly under an allowed subpath or matches an allowed glob.
151
+ for (const denyPath of config.denyOnly || []) {
152
+ const normalized = normalizePathForSandbox(denyPath);
153
+ if (containsGlobChars(normalized)) {
154
+ const baseDir = globBaseDir(normalized, false);
155
+ if (baseDir &&
156
+ (allowedSubpaths.some(a => baseDir === a || baseDir.startsWith(a + '/')) ||
157
+ allowedGlobRegexes.some(re => re.test(baseDir)))) {
158
+ rules.push(`(deny file-read*`, ` (regex ${escapePath(globToRegex(normalized))})`, ` (with message "${logTag}"))`);
159
+ }
160
+ continue;
161
+ }
162
+ if (allowedSubpaths.some(a => normalized.startsWith(a + '/')) ||
163
+ allowedGlobRegexes.some(re => re.test(normalized))) {
164
+ rules.push(`(deny file-read*`, ` (subpath ${escapePath(normalized)})`, ` (with message "${logTag}"))`);
165
+ }
166
+ }
167
+ // Allow stat/lstat on all directories so that realpath() can traverse
168
+ // path components within denied regions. Without this, C realpath() fails
169
+ // when resolving symlinks because it needs to lstat every intermediate
170
+ // directory (e.g. /Users, /Users/chris) even if only a subdirectory like
171
+ // ~/.local is in allowWithinDeny. This only allows metadata reads on
172
+ // directories — not listing contents (readdir) or reading files.
173
+ if (config.denyOnly.length > 0) {
174
+ rules.push(`(allow file-read-metadata`, ` (vnode-type DIRECTORY))`);
175
+ }
176
+ // Block file movement to prevent bypass via mv/rename
177
+ rules.push(...generateMoveBlockingRules(config.denyOnly || [], logTag));
178
+ // Re-allow file-write-unlink / file-write-create for paths that are explicitly
179
+ // write-allowed. The move-blocking rules above emit broad
180
+ // (deny file-write-unlink (subpath "/Users")) to prevent bypassing read
181
+ // restrictions by moving files out of denied regions.
182
+ // However, in macOS Seatbelt, a specific (deny file-write-unlink) is not overridden
183
+ // by a later (allow file-write*) wildcard — the specific operation deny wins.
184
+ // This means file deletions are blocked even in write-allowed directories like
185
+ // the project directory. We fix this by explicitly re-allowing file-write-unlink
186
+ // and file-write-create for write-allowed paths after the move-blocking deny rules.
187
+ //
188
+ // Note: denyWithinAllow paths are not excluded here because the write section's
189
+ // generateMoveBlockingRules() runs later in the profile and re-denies
190
+ // file-write-unlink for those paths (Seatbelt uses last-match-wins). This
191
+ // depends on read rules being emitted before write rules in generateSandboxProfile().
192
+ if (writeAllowPaths && writeAllowPaths.length > 0) {
193
+ const normalizedWriteAllows = [];
194
+ for (const pathPattern of writeAllowPaths) {
195
+ const normalizedPath = normalizePathForSandbox(pathPattern);
196
+ normalizedWriteAllows.push(normalizedPath);
197
+ for (const op of ['file-write-unlink', 'file-write-create']) {
198
+ if (containsGlobChars(normalizedPath)) {
199
+ const regexPattern = globToRegex(normalizedPath);
200
+ rules.push(`(allow ${op}`, ` (regex ${escapePath(regexPattern)})`, ` (with message "${logTag}"))`);
201
+ }
202
+ else {
203
+ rules.push(`(allow ${op}`, ` (subpath ${escapePath(normalizedPath)})`, ` (with message "${logTag}"))`);
204
+ }
205
+ }
206
+ }
207
+ // Re-emit move-blocking rules for any denyOnly path nested under an
208
+ // allowWrite path so mv/rename inside a writable workspace cannot move
209
+ // a read-denied or masked file out of its denied path.
210
+ const denyUnderWrite = (config.denyOnly || []).filter(d => {
211
+ const nd = normalizePathForSandbox(d);
212
+ const checkPath = containsGlobChars(nd)
213
+ ? (globBaseDir(nd, false) ?? nd)
214
+ : nd;
215
+ return normalizedWriteAllows.some(w => {
216
+ if (containsGlobChars(w))
217
+ return true;
218
+ return checkPath === w || checkPath.startsWith(w + '/');
219
+ });
220
+ });
221
+ if (denyUnderWrite.length > 0) {
222
+ rules.push(...generateMoveBlockingRules(denyUnderWrite, logTag));
223
+ }
224
+ }
225
+ return rules;
226
+ }
227
+ /**
228
+ * Generate filesystem write rules for sandbox profile
229
+ */
230
+ function generateWriteRules(config, logTag) {
231
+ if (!config) {
232
+ return [`(allow file-write*)`];
233
+ }
234
+ const rules = [];
235
+ // Generate allow rules
236
+ for (const pathPattern of config.allowOnly || []) {
237
+ const normalizedPath = normalizePathForSandbox(pathPattern);
238
+ if (containsGlobChars(normalizedPath)) {
239
+ // Use regex matching for glob patterns
240
+ const regexPattern = globToRegex(normalizedPath);
241
+ rules.push(`(allow file-write*`, ` (regex ${escapePath(regexPattern)})`, ` (with message "${logTag}"))`);
242
+ }
243
+ else {
244
+ // Use subpath matching for literal paths
245
+ rules.push(`(allow file-write*`, ` (subpath ${escapePath(normalizedPath)})`, ` (with message "${logTag}"))`);
246
+ }
247
+ }
248
+ const denyPaths = config.denyWithinAllow || [];
249
+ for (const pathPattern of denyPaths) {
250
+ const normalizedPath = normalizePathForSandbox(pathPattern);
251
+ if (containsGlobChars(normalizedPath)) {
252
+ // Use regex matching for glob patterns
253
+ const regexPattern = globToRegex(normalizedPath);
254
+ rules.push(`(deny file-write*`, ` (regex ${escapePath(regexPattern)})`, ` (with message "${logTag}"))`);
255
+ }
256
+ else {
257
+ // Use subpath matching for literal paths
258
+ rules.push(`(deny file-write*`, ` (subpath ${escapePath(normalizedPath)})`, ` (with message "${logTag}"))`);
259
+ }
260
+ }
261
+ // Block file movement to prevent bypass via mv/rename
262
+ rules.push(...generateMoveBlockingRules(denyPaths, logTag));
263
+ return rules;
264
+ }
265
+ /**
266
+ * Generate complete sandbox profile
267
+ */
268
+ function generateSandboxProfile({ readConfig, writeConfig, httpProxyPort, socksProxyPort, needsNetworkRestriction, allowUnixSockets, allowAllUnixSockets, allowLocalBinding, allowMachLookup, allowPty, allowBrowserProcess = false, allowProcessSignals = false, enableWeakerNetworkIsolation = false, allowAppleEvents = false, logTag, }) {
269
+ const profile = [
270
+ '(version 1)',
271
+ `(deny default (with message "${logTag}"))`,
272
+ '',
273
+ `; LogTag: ${logTag}`,
274
+ '',
275
+ '; Essential permissions - based on Chrome sandbox policy',
276
+ '; Process permissions',
277
+ '(allow process-exec)',
278
+ '(allow process-fork)',
279
+ '(allow process-info* (target same-sandbox))',
280
+ allowProcessSignals
281
+ ? '(allow signal)'
282
+ : '(allow signal (target same-sandbox))',
283
+ '(allow mach-priv-task-port (target same-sandbox))',
284
+ '',
285
+ '; User preferences',
286
+ '(allow user-preference-read)',
287
+ '',
288
+ '; Mach IPC - specific services only (no wildcard)',
289
+ '(allow mach-lookup',
290
+ ' (global-name "com.apple.audio.systemsoundserver")',
291
+ ' (global-name "com.apple.distributed_notifications@Uv3")',
292
+ ' (global-name "com.apple.FontObjectsServer")',
293
+ ' (global-name "com.apple.fonts")',
294
+ ' (global-name "com.apple.logd")',
295
+ ' (global-name "com.apple.lsd.mapdb")',
296
+ ' (global-name "com.apple.PowerManagement.control")',
297
+ ' (global-name "com.apple.system.logger")',
298
+ ' (global-name "com.apple.system.notification_center")',
299
+ ' (global-name "com.apple.system.opendirectoryd.libinfo")',
300
+ ' (global-name "com.apple.system.opendirectoryd.membership")',
301
+ ' (global-name "com.apple.bsd.dirhelper")',
302
+ ' (global-name "com.apple.securityd.xpc")',
303
+ ' (global-name "com.apple.coreservices.launchservicesd")',
304
+ ')',
305
+ '',
306
+ ...(enableWeakerNetworkIsolation
307
+ ? [
308
+ '; trustd.agent - needed for Go TLS certificate verification (weaker network isolation)',
309
+ '(allow mach-lookup (global-name "com.apple.trustd.agent"))',
310
+ '; configd - needed for Rust/Go programs that query system proxy/network config (uv, cargo)',
311
+ '(allow mach-lookup (global-name "com.apple.SystemConfiguration.configd"))',
312
+ ]
313
+ : []),
314
+ ...(allowAppleEvents
315
+ ? [
316
+ '; Apple Events - opt-in; needed for open/osascript to talk to other apps (appleeventsd)',
317
+ '(allow appleevent-send)',
318
+ '(allow mach-lookup (global-name "com.apple.coreservices.appleevents"))',
319
+ '; Launch Services open requests need the lsopen operation plus, on',
320
+ '; macOS 14/15, coreservicesd and the quarantine resolver - without',
321
+ '; these open fails with -10822 kLSServerCommunicationErr or -54',
322
+ '(allow lsopen)',
323
+ '(allow mach-lookup (global-name "com.apple.CoreServices.coreservicesd"))',
324
+ '(allow mach-lookup (global-name "com.apple.coreservices.quarantine-resolver"))',
325
+ ]
326
+ : []),
327
+ ...(allowMachLookup && allowMachLookup.length > 0
328
+ ? [
329
+ '; User-specified XPC/Mach services',
330
+ ...allowMachLookup.map(name => name.endsWith('*')
331
+ ? `(allow mach-lookup (global-name-prefix ${escapePath(name.slice(0, -1))}))`
332
+ : `(allow mach-lookup (global-name ${escapePath(name)}))`),
333
+ ]
334
+ : []),
335
+ '',
336
+ '; POSIX IPC - shared memory',
337
+ '(allow ipc-posix-shm)',
338
+ '',
339
+ '; POSIX IPC - semaphores for Python multiprocessing',
340
+ '(allow ipc-posix-sem)',
341
+ '',
342
+ '; IOKit - specific operations only',
343
+ '(allow iokit-open',
344
+ ' (iokit-registry-entry-class "IOSurfaceRootUserClient")',
345
+ ' (iokit-registry-entry-class "RootDomainUserClient")',
346
+ ' (iokit-user-client-class "IOSurfaceSendRight")',
347
+ ')',
348
+ '',
349
+ '; IOKit properties',
350
+ '(allow iokit-get-properties)',
351
+ '',
352
+ "; Specific safe system-sockets, doesn't allow network access",
353
+ '(allow system-socket (require-all (socket-domain AF_SYSTEM) (socket-protocol 2)))',
354
+ '',
355
+ '; sysctl - specific sysctls only',
356
+ '(allow sysctl-read',
357
+ ' (sysctl-name "hw.activecpu")',
358
+ ' (sysctl-name "hw.busfrequency_compat")',
359
+ ' (sysctl-name "hw.byteorder")',
360
+ ' (sysctl-name "hw.cacheconfig")',
361
+ ' (sysctl-name "hw.cachelinesize_compat")',
362
+ ' (sysctl-name "hw.cpufamily")',
363
+ ' (sysctl-name "hw.cpufrequency")',
364
+ ' (sysctl-name "hw.cpufrequency_compat")',
365
+ ' (sysctl-name "hw.cputype")',
366
+ ' (sysctl-name "hw.l1dcachesize_compat")',
367
+ ' (sysctl-name "hw.l1icachesize_compat")',
368
+ ' (sysctl-name "hw.l2cachesize_compat")',
369
+ ' (sysctl-name "hw.l3cachesize_compat")',
370
+ ' (sysctl-name "hw.logicalcpu")',
371
+ ' (sysctl-name "hw.logicalcpu_max")',
372
+ ' (sysctl-name "hw.machine")',
373
+ ' (sysctl-name "hw.memsize")',
374
+ ' (sysctl-name "hw.ncpu")',
375
+ ' (sysctl-name "hw.nperflevels")',
376
+ ' (sysctl-name "hw.packages")',
377
+ ' (sysctl-name "hw.pagesize_compat")',
378
+ ' (sysctl-name "hw.pagesize")',
379
+ ' (sysctl-name "hw.physicalcpu")',
380
+ ' (sysctl-name "hw.physicalcpu_max")',
381
+ ' (sysctl-name "hw.tbfrequency_compat")',
382
+ ' (sysctl-name "hw.vectorunit")',
383
+ ' (sysctl-name "kern.argmax")',
384
+ ' (sysctl-name "kern.bootargs")',
385
+ ' (sysctl-name "kern.hostname")',
386
+ ' (sysctl-name "kern.maxfiles")',
387
+ ' (sysctl-name "kern.maxfilesperproc")',
388
+ ' (sysctl-name "kern.maxproc")',
389
+ ' (sysctl-name "kern.ngroups")',
390
+ ' (sysctl-name "kern.osproductversion")',
391
+ ' (sysctl-name "kern.osrelease")',
392
+ ' (sysctl-name "kern.ostype")',
393
+ ' (sysctl-name "kern.osvariant_status")',
394
+ ' (sysctl-name "kern.osversion")',
395
+ ' (sysctl-name "kern.secure_kernel")',
396
+ ' (sysctl-name "kern.tcsm_available")',
397
+ ' (sysctl-name "kern.tcsm_enable")',
398
+ ' (sysctl-name "kern.usrstack64")',
399
+ ' (sysctl-name "kern.version")',
400
+ ' (sysctl-name "kern.willshutdown")',
401
+ ' (sysctl-name "machdep.cpu.brand_string")',
402
+ ' (sysctl-name "machdep.ptrauth_enabled")',
403
+ ' (sysctl-name "security.mac.lockdown_mode_state")',
404
+ ' (sysctl-name "sysctl.proc_cputype")',
405
+ ' (sysctl-name "vm.loadavg")',
406
+ ' (sysctl-name-prefix "hw.optional.arm")',
407
+ ' (sysctl-name-prefix "hw.optional.arm.")',
408
+ ' (sysctl-name-prefix "hw.optional.armv8_")',
409
+ ' (sysctl-name-prefix "hw.perflevel")',
410
+ ' (sysctl-name-prefix "kern.proc.all")',
411
+ ' (sysctl-name-prefix "kern.proc.pgrp.")',
412
+ ' (sysctl-name-prefix "kern.proc.pid.")',
413
+ ' (sysctl-name-prefix "machdep.cpu.")',
414
+ ' (sysctl-name-prefix "net.routetable.")',
415
+ ')',
416
+ '',
417
+ '; V8 thread calculations',
418
+ '(allow sysctl-write',
419
+ ' (sysctl-name "kern.tcsm_enable")',
420
+ ')',
421
+ '',
422
+ '; Distributed notifications',
423
+ '(allow distributed-notification-post)',
424
+ '',
425
+ '; Specific mach-lookup permissions for security operations',
426
+ '(allow mach-lookup (global-name "com.apple.SecurityServer"))',
427
+ '',
428
+ '; File I/O on device files',
429
+ '(allow file-ioctl (literal "/dev/null"))',
430
+ '(allow file-ioctl (literal "/dev/zero"))',
431
+ '(allow file-ioctl (literal "/dev/random"))',
432
+ '(allow file-ioctl (literal "/dev/urandom"))',
433
+ '(allow file-ioctl (literal "/dev/dtracehelper"))',
434
+ '(allow file-ioctl (literal "/dev/tty"))',
435
+ '',
436
+ '(allow file-ioctl file-read-data file-write-data',
437
+ ' (require-all',
438
+ ' (literal "/dev/null")',
439
+ ' (vnode-type CHARACTER-DEVICE)',
440
+ ' )',
441
+ ')',
442
+ '',
443
+ ];
444
+ // Network rules
445
+ profile.push('; Network');
446
+ if (!needsNetworkRestriction) {
447
+ profile.push('(allow network*)');
448
+ }
449
+ else {
450
+ // Allow local binding if requested.
451
+ //
452
+ // bind/inbound use (local ip "*:*") instead of "localhost:*" because modern
453
+ // runtimes (Java, etc.) create IPv6 dual-stack sockets by default; binding
454
+ // such a socket to 127.0.0.1 is represented in the kernel as
455
+ // ::ffff:127.0.0.1, which Seatbelt's "localhost" filter does not match.
456
+ // Seatbelt only accepts "localhost" or "*" as the host token, so "*:*" is
457
+ // the only way to admit the IPv4-mapped form. bind/inbound are local
458
+ // operations (no remote endpoint), so wildcarding them does not grant
459
+ // egress.
460
+ //
461
+ // outbound uses (remote ip "localhost:*") so the egress allowlist remains
462
+ // enforced when allowLocalBinding is set (#225, #88). A (local ip ...)
463
+ // filter on network-outbound is evaluated against the source address,
464
+ // which for an unbound socket is INADDR_ANY (0.0.0.0 / ::) at connect()
465
+ // time — Seatbelt's "localhost" matches the any-address, so any
466
+ // (local ip ...) host value admits every outbound connection. (remote ip
467
+ // "localhost:*") matches connect() to 127.0.0.1 and ::1 but not
468
+ // ::ffff:127.0.0.1; runtimes that connect to loopback via dual-stack
469
+ // sockets need to use AF_INET (see JAVA_TOOL_OPTIONS injection below).
470
+ if (allowLocalBinding) {
471
+ profile.push('(allow network-bind (local ip "*:*"))');
472
+ profile.push('(allow network-inbound (local ip "*:*"))');
473
+ profile.push('(allow network-outbound (remote ip "localhost:*"))');
474
+ }
475
+ // Unix domain sockets for local IPC (SSH agent, Docker, Gradle, etc.)
476
+ // Three separate operations must be allowed:
477
+ // 1. system-socket: socket(AF_UNIX, ...) syscall — creates the socket fd (no path context)
478
+ // 2. network-bind: bind() to a local Unix socket path
479
+ // 3. network-outbound: connect() to a remote Unix socket path
480
+ // Note: (subpath ...) and (path-regex ...) are path-based filters that can only match
481
+ // bind/connect operations — socket() creation has no path, so it requires system-socket.
482
+ if (allowAllUnixSockets) {
483
+ // Allow creating AF_UNIX sockets and all Unix socket paths
484
+ profile.push('(allow system-socket (socket-domain AF_UNIX))');
485
+ profile.push('(allow network-bind (local unix-socket (path-regex #"^/")))');
486
+ profile.push('(allow network-outbound (remote unix-socket (path-regex #"^/")))');
487
+ }
488
+ else if (allowUnixSockets && allowUnixSockets.length > 0) {
489
+ // Allow creating AF_UNIX sockets (required for any Unix socket use)
490
+ profile.push('(allow system-socket (socket-domain AF_UNIX))');
491
+ // Allow specific Unix socket paths
492
+ for (const socketPath of allowUnixSockets) {
493
+ const normalizedPath = normalizePathForSandbox(socketPath);
494
+ profile.push(`(allow network-bind (local unix-socket (subpath ${escapePath(normalizedPath)})))`);
495
+ profile.push(`(allow network-outbound (remote unix-socket (subpath ${escapePath(normalizedPath)})))`);
496
+ }
497
+ }
498
+ // If both allowAllUnixSockets and allowUnixSockets are false/undefined/empty, Unix sockets are blocked by default
499
+ // Allow localhost TCP operations for the HTTP proxy
500
+ if (httpProxyPort !== undefined) {
501
+ profile.push(`(allow network-bind (local ip "localhost:${httpProxyPort}"))`);
502
+ profile.push(`(allow network-inbound (local ip "localhost:${httpProxyPort}"))`);
503
+ profile.push(`(allow network-outbound (remote ip "localhost:${httpProxyPort}"))`);
504
+ }
505
+ // Allow localhost TCP operations for the SOCKS proxy. Skip when it's
506
+ // the same port as the HTTP proxy (the mux serves both on one port);
507
+ // SBPL accepts duplicate allow clauses but there's no need to emit them.
508
+ if (socksProxyPort !== undefined && socksProxyPort !== httpProxyPort) {
509
+ profile.push(`(allow network-bind (local ip "localhost:${socksProxyPort}"))`);
510
+ profile.push(`(allow network-inbound (local ip "localhost:${socksProxyPort}"))`);
511
+ profile.push(`(allow network-outbound (remote ip "localhost:${socksProxyPort}"))`);
512
+ }
513
+ }
514
+ profile.push('');
515
+ // Read rules
516
+ // Pass write-allowed paths so that move-blocking deny rules in the read section
517
+ // can be overridden for paths where file deletion should be permitted.
518
+ const writeAllowPaths = writeConfig?.allowOnly;
519
+ profile.push('; File read');
520
+ profile.push(...generateReadRules(readConfig, logTag, writeAllowPaths));
521
+ profile.push('');
522
+ // Write rules
523
+ profile.push('; File write');
524
+ profile.push(...generateWriteRules(writeConfig, logTag));
525
+ // Pseudo-terminal (pty) support
526
+ if (allowPty) {
527
+ profile.push('');
528
+ profile.push('; Pseudo-terminal (pty) support');
529
+ profile.push('(allow pseudo-tty)');
530
+ profile.push('(allow file-ioctl');
531
+ profile.push(' (literal "/dev/ptmx")');
532
+ profile.push(' (regex #"^/dev/ttys")');
533
+ profile.push(')');
534
+ profile.push('(allow file-read* file-write*');
535
+ profile.push(' (literal "/dev/ptmx")');
536
+ profile.push(' (regex #"^/dev/ttys")');
537
+ profile.push(')');
538
+ }
539
+ // Browser process support (Chrome/Chromium)
540
+ //
541
+ // Chromium-based browsers need significantly broader OS permissions than
542
+ // typical CLI tools. The default Seatbelt profile is designed for commands
543
+ // like git, node, and npm — Chrome's multi-process architecture requires
544
+ // Mach IPC for inter-process communication, window server access, GPU
545
+ // drivers, crash reporting (Crashpad), and more. These services vary by
546
+ // macOS version and hardware, making an exhaustive allowlist impractical.
547
+ //
548
+ // This option grants:
549
+ // - All Mach operations (mach*): IPC, bootstrap registration, service
550
+ // lookups, task ports, cross-domain lookups. Needed for Crashpad,
551
+ // window server (CoreGraphics/SkyLight), CoreDisplay, GPU process, etc.
552
+ // - Unrestricted process-info: Chrome manages renderer, GPU, utility,
553
+ // and crashpad child processes outside the same sandbox boundary.
554
+ // - Broad IOKit access: GPU process and display management.
555
+ // - Unrestricted IPC shared memory: renderer ↔ GPU communication.
556
+ //
557
+ // Security note: this significantly widens the Mach IPC and process
558
+ // inspection surface. Filesystem and network restrictions remain fully
559
+ // enforced. Only enable when browser automation (e.g. agent-browser) is
560
+ // needed.
561
+ if (allowBrowserProcess) {
562
+ profile.push('');
563
+ profile.push('; Browser process support (Chrome/Chromium)');
564
+ profile.push('; All Mach operations — Chrome requires bootstrap registration');
565
+ profile.push('; (Crashpad), service lookups (window server, CoreDisplay, GPU),');
566
+ profile.push('; task ports, and cross-domain lookups that vary by OS version');
567
+ profile.push('(allow mach*)');
568
+ profile.push('');
569
+ profile.push('; Process info for all processes — Chrome manages renderer, GPU,');
570
+ profile.push('; utility, and crashpad child processes outside the same sandbox');
571
+ profile.push('(allow process-info*)');
572
+ profile.push('');
573
+ profile.push('; Broader IOKit access — needed for GPU process and display management');
574
+ profile.push('(allow iokit-open)');
575
+ profile.push('');
576
+ profile.push('; Shared memory with non-sandboxed processes (e.g. renderer ↔ GPU)');
577
+ profile.push('(allow ipc-posix-shm*)');
578
+ }
579
+ return profile.join('\n');
580
+ }
581
+ /**
582
+ * Escape path for sandbox profile using JSON.stringify for proper escaping
583
+ */
584
+ function escapePath(pathStr) {
585
+ return JSON.stringify(pathStr);
586
+ }
587
+ /**
588
+ * Wrap command with macOS sandbox
589
+ */
590
+ export function wrapCommandWithSandboxMacOS(params) {
591
+ const { command, needsNetworkRestriction, httpProxyPort, socksProxyPort, proxyAuthToken, caCertPath, allowUnixSockets, allowAllUnixSockets, allowLocalBinding, allowMachLookup, readConfig: readConfigIn, writeConfig, unsetEnvVars, setEnvVars, maskedFileBinds, allowPty, allowBrowserProcess = false, allowProcessSignals = false, enableWeakerNetworkIsolation = false, allowAppleEvents = false, binShell, sessionSuffix, } = params;
592
+ // SBPL cannot redirect a read to different bytes, so whole-file masking
593
+ // degrades to read-deny on macOS: the sandboxed process gets EPERM
594
+ // instead of the sentinel. The DYLD interposer (a later step) lifts
595
+ // this. Folding the masked paths into denyOnly here means the existing
596
+ // generateReadRules() emits the (deny file-read* …) rule unchanged.
597
+ let readConfig = readConfigIn;
598
+ if (maskedFileBinds && maskedFileBinds.length > 0) {
599
+ logForDebugging('[Sandbox macOS] file mask degrades to deny on macOS until the ' +
600
+ 'interposer lands');
601
+ readConfig = {
602
+ denyOnly: [
603
+ ...(readConfigIn?.denyOnly ?? []),
604
+ ...maskedFileBinds.map(b => b.realPath),
605
+ ],
606
+ allowWithinDeny: readConfigIn?.allowWithinDeny,
607
+ };
608
+ }
609
+ // Determine if we have restrictions to apply
610
+ // Read: denyOnly pattern - empty array means no restrictions
611
+ // Write: allowOnly pattern - undefined means no restrictions, any config means restrictions
612
+ const hasReadRestrictions = readConfig && readConfig.denyOnly.length > 0;
613
+ const hasWriteRestrictions = writeConfig !== undefined;
614
+ const hasEnvRestrictions = (unsetEnvVars !== undefined && unsetEnvVars.length > 0) ||
615
+ (setEnvVars !== undefined && Object.keys(setEnvVars).length > 0);
616
+ // No sandboxing needed
617
+ if (!needsNetworkRestriction &&
618
+ !hasReadRestrictions &&
619
+ !hasWriteRestrictions &&
620
+ !hasEnvRestrictions) {
621
+ return command;
622
+ }
623
+ const logTag = generateLogTag(command, sessionSuffix);
624
+ const profile = generateSandboxProfile({
625
+ readConfig,
626
+ writeConfig,
627
+ httpProxyPort,
628
+ socksProxyPort,
629
+ needsNetworkRestriction,
630
+ allowUnixSockets,
631
+ allowAllUnixSockets,
632
+ allowLocalBinding,
633
+ allowMachLookup,
634
+ allowPty,
635
+ allowBrowserProcess,
636
+ allowProcessSignals,
637
+ enableWeakerNetworkIsolation,
638
+ allowAppleEvents,
639
+ logTag,
640
+ });
641
+ // Generate proxy environment variables using shared utility
642
+ const proxyEnvArgs = generateProxyEnvVars(httpProxyPort, socksProxyPort, caCertPath, proxyAuthToken, writeConfig === undefined);
643
+ // Seatbelt's (remote ip "localhost:*") filter — used for the
644
+ // allowLocalBinding outbound rule above — matches 127.0.0.1 and ::1 but not
645
+ // the IPv4-mapped IPv6 form ::ffff:127.0.0.1. Modern Java defaults to
646
+ // AF_INET6 dual-stack sockets, so a Java client connecting to 127.0.0.1
647
+ // reaches the kernel as ::ffff:127.0.0.1 and is denied. Forcing the IPv4
648
+ // stack makes Java open AF_INET sockets so loopback connect matches the
649
+ // Seatbelt filter. The flag is appended after any inherited
650
+ // JAVA_TOOL_OPTIONS unless that var is on the credential-deny list, in
651
+ // which case the inherited value is dropped so the deny holds.
652
+ if (allowLocalBinding && needsNetworkRestriction) {
653
+ const flag = '-Djava.net.preferIPv4Stack=true';
654
+ const denied = (unsetEnvVars ?? []).includes('JAVA_TOOL_OPTIONS');
655
+ const inherited = denied ? '' : (process.env.JAVA_TOOL_OPTIONS ?? '');
656
+ const value = inherited.includes(flag)
657
+ ? inherited
658
+ : [inherited, flag].filter(Boolean).join(' ');
659
+ proxyEnvArgs.push(`JAVA_TOOL_OPTIONS=${value}`);
660
+ }
661
+ // Use the user's shell (zsh, bash, etc.) to ensure aliases/snapshots work
662
+ // Resolve the full path to the shell binary
663
+ const shellName = binShell || 'bash';
664
+ const shell = whichSync(shellName);
665
+ if (!shell) {
666
+ throw new Error(`Shell '${shellName}' not found in PATH`);
667
+ }
668
+ // Drop denied credential env vars from the inherited environment. The -u
669
+ // flags must precede the VAR=VALUE assignments so SRT's own proxy plumbing
670
+ // vars survive even if a caller lists one of them as a denied credential.
671
+ const unsetEnvArgs = (unsetEnvVars ?? []).flatMap(name => ['-u', name]);
672
+ // Masked credentials override the inherited real value with a sentinel.
673
+ // Placed before the proxy plumbing assignments for the same precedence
674
+ // reason as the -u flags.
675
+ const setEnvArgs = Object.entries(setEnvVars ?? {}).map(([name, value]) => `${name}=${value}`);
676
+ // Use `env` command to set environment variables - each VAR=value is a separate
677
+ // argument that quote() escapes properly, avoiding shell quoting issues
678
+ const wrappedCommand = quote([
679
+ 'env',
680
+ ...unsetEnvArgs,
681
+ ...setEnvArgs,
682
+ ...proxyEnvArgs,
683
+ '/usr/bin/sandbox-exec',
684
+ '-p',
685
+ profile,
686
+ shell,
687
+ '-c',
688
+ command,
689
+ ]);
690
+ logForDebugging(`[Sandbox macOS] Applied restrictions - network: ${!!(httpProxyPort || socksProxyPort)}, read: ${readConfig ? 'denyAllExcept' : 'none'}, write: ${writeConfig ? 'denyAllExcept' : 'none'}`);
691
+ return wrappedCommand;
692
+ }
693
+ /**
694
+ * Start monitoring macOS system logs for sandbox violations
695
+ * Look for sandbox-related kernel deny events ending in {logTag}
696
+ */
697
+ export function startMacOSSandboxLogMonitor(callback, ignoreViolations, sessionSuffix = defaultSessionSuffix) {
698
+ // Pre-compile regex patterns for better performance
699
+ const cmdExtractRegex = /CMD64_(.+?)_END/;
700
+ const sandboxExtractRegex = /Sandbox:\s+(.+)$/;
701
+ // Pre-process ignore patterns for faster lookup
702
+ const wildcardPaths = ignoreViolations?.['*'] || [];
703
+ const commandPatterns = ignoreViolations
704
+ ? Object.entries(ignoreViolations).filter(([pattern]) => pattern !== '*')
705
+ : [];
706
+ // Stream and filter kernel logs for all sandbox violations
707
+ // We can't filter by specific logTag since it's dynamic per command
708
+ const logProcess = spawn('log', [
709
+ 'stream',
710
+ '--predicate',
711
+ `(eventMessage ENDSWITH "${sessionSuffix}")`,
712
+ '--style',
713
+ 'compact',
714
+ ]);
715
+ const emitViolation = (violationLine, commandLine) => {
716
+ const sandboxMatch = violationLine.match(sandboxExtractRegex);
717
+ if (!sandboxMatch?.[1])
718
+ return;
719
+ const violationDetails = sandboxMatch[1];
720
+ let command;
721
+ const cmdSource = commandLine ?? violationLine;
722
+ const cmdMatch = cmdSource.match(cmdExtractRegex);
723
+ const encodedCommand = cmdMatch?.[1];
724
+ if (encodedCommand) {
725
+ try {
726
+ command = decodeSandboxedCommand(encodedCommand);
727
+ }
728
+ catch {
729
+ // Failed to decode, continue without command
730
+ }
731
+ }
732
+ // Always filter out noisy violations
733
+ if (violationDetails.includes('mDNSResponder') ||
734
+ violationDetails.includes('mach-lookup com.apple.diagnosticd') ||
735
+ violationDetails.includes('mach-lookup com.apple.analyticsd')) {
736
+ return;
737
+ }
738
+ // Wildcard ignores apply regardless of whether command was decoded
739
+ if (wildcardPaths.length > 0 &&
740
+ wildcardPaths.some(p => violationDetails.includes(p))) {
741
+ return;
742
+ }
743
+ if (command) {
744
+ for (const [pattern, paths] of commandPatterns) {
745
+ if (command.includes(pattern) &&
746
+ paths.some(p => violationDetails.includes(p))) {
747
+ return;
748
+ }
749
+ }
750
+ }
751
+ callback({
752
+ line: violationDetails,
753
+ command,
754
+ encodedCommand,
755
+ timestamp: new Date(),
756
+ });
757
+ };
758
+ let pendingViolation;
759
+ let flushTimer;
760
+ const flushPending = (commandLine) => {
761
+ if (flushTimer) {
762
+ clearTimeout(flushTimer);
763
+ flushTimer = undefined;
764
+ }
765
+ if (!pendingViolation)
766
+ return;
767
+ const v = pendingViolation;
768
+ pendingViolation = undefined;
769
+ emitViolation(v, commandLine);
770
+ };
771
+ const rl = logProcess.stdout
772
+ ? createInterface({ input: logProcess.stdout })
773
+ : undefined;
774
+ rl?.on('line', line => {
775
+ if (line.includes('Sandbox:') && line.includes('deny')) {
776
+ flushPending();
777
+ if (cmdExtractRegex.test(line)) {
778
+ emitViolation(line);
779
+ }
780
+ else {
781
+ pendingViolation = line;
782
+ flushTimer = setTimeout(() => flushPending(), 20);
783
+ flushTimer.unref?.();
784
+ }
785
+ return;
786
+ }
787
+ if (pendingViolation && line.startsWith('CMD64_')) {
788
+ flushPending(line);
789
+ return;
790
+ }
791
+ flushPending();
792
+ });
793
+ rl?.on('close', () => flushPending());
794
+ logProcess.stderr?.on('data', (data) => {
795
+ logForDebugging(`[Sandbox Monitor] Log stream stderr: ${data.toString()}`);
796
+ });
797
+ logProcess.on('error', (error) => {
798
+ logForDebugging(`[Sandbox Monitor] Failed to start log stream: ${error.message}`);
799
+ });
800
+ logProcess.on('exit', (code) => {
801
+ logForDebugging(`[Sandbox Monitor] Log stream exited with code: ${code}`);
802
+ });
803
+ return () => {
804
+ logForDebugging('[Sandbox Monitor] Stopping log monitor');
805
+ rl?.close();
806
+ flushPending();
807
+ logProcess.kill('SIGTERM');
808
+ };
809
+ }
810
+ //# sourceMappingURL=macos-sandbox-utils.js.map