@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,917 @@
1
+ /**
2
+ * Configuration for Sandbox Runtime
3
+ * This is the main configuration interface that consumers pass to SandboxManager.initialize()
4
+ */
5
+ import { isAbsolute, win32 } from 'node:path';
6
+ import { z } from 'zod/v3';
7
+ import { isInjectHostCoveredByAllowedDomains } from './domain-pattern.js';
8
+ /**
9
+ * Schema for domain patterns (e.g., "example.com", "*.npmjs.org")
10
+ * Validates that domain patterns are safe and don't include overly broad wildcards
11
+ */
12
+ const domainPatternSchema = z.string().refine(val => {
13
+ // Reject protocols, paths, ports, whitespace, etc.
14
+ if (val.includes('://') ||
15
+ val.includes('/') ||
16
+ val.includes(':') ||
17
+ /\s/.test(val)) {
18
+ return false;
19
+ }
20
+ // Allow localhost
21
+ if (val === 'localhost')
22
+ return true;
23
+ // Strip optional leading wildcard `*.`, then reject any remaining `*`.
24
+ let domain = val;
25
+ if (val.startsWith('*.')) {
26
+ domain = val.slice(2);
27
+ }
28
+ if (domain.includes('*')) {
29
+ return false;
30
+ }
31
+ // Require at least two dot-separated non-empty DNS/hostname labels.
32
+ if (!domain.includes('.') ||
33
+ domain.startsWith('.') ||
34
+ domain.endsWith('.')) {
35
+ return false;
36
+ }
37
+ const parts = domain.split('.');
38
+ const labelRe = /^[A-Za-z0-9](?:[A-Za-z0-9-]*[A-Za-z0-9])?$/;
39
+ return parts.length >= 2 && parts.every(p => labelRe.test(p));
40
+ }, {
41
+ message: 'Invalid domain pattern. Must be a valid domain (e.g., "example.com") or wildcard (e.g., "*.example.com"). Overly broad patterns like "*.com" or "*" are not allowed for security reasons.',
42
+ });
43
+ /**
44
+ * Schema for filesystem paths
45
+ */
46
+ const filesystemPathSchema = z.string().min(1, 'Path cannot be empty');
47
+ /**
48
+ * Schema for an absolute path to an external binary.
49
+ * Relative paths are rejected to prevent PATH/CWD-based hijacking — these
50
+ * overrides are intended for admin-managed installs at fixed locations.
51
+ */
52
+ const binaryPathSchema = z
53
+ .string()
54
+ .min(1, 'Path cannot be empty')
55
+ .refine(val => isAbsolute(val), {
56
+ message: 'Binary path must be absolute',
57
+ });
58
+ /**
59
+ * Schema for MITM proxy configuration
60
+ * Allows routing specific domains through an upstream MITM proxy via Unix socket
61
+ */
62
+ const MitmProxyConfigSchema = z.object({
63
+ socketPath: z.string().min(1).describe('Unix socket path to the MITM proxy'),
64
+ domains: z
65
+ .array(domainPatternSchema)
66
+ .min(1)
67
+ .describe('Domains to route through the MITM proxy (e.g., ["api.example.com", "*.internal.org"])'),
68
+ });
69
+ /**
70
+ * Schema for upstream/parent HTTP proxy configuration.
71
+ * Used when SRT itself runs behind a corporate proxy and cannot make direct
72
+ * outbound connections.
73
+ */
74
+ const httpProxyUrlSchema = z
75
+ .string()
76
+ .url()
77
+ .refine(val => /^https?:\/\//i.test(val), {
78
+ message: 'Parent proxy URL must use http:// or https:// scheme',
79
+ });
80
+ const ParentProxyConfigSchema = z.object({
81
+ http: httpProxyUrlSchema
82
+ .optional()
83
+ .describe('Upstream proxy URL for plain HTTP traffic'),
84
+ https: httpProxyUrlSchema
85
+ .optional()
86
+ .describe('Upstream proxy URL for HTTPS/CONNECT traffic (falls back to http if unset)'),
87
+ noProxy: z
88
+ .string()
89
+ .optional()
90
+ .describe('Comma-separated NO_PROXY list (hostname suffixes and CIDR ranges). ' +
91
+ 'Matching destinations connect directly instead of via the parent proxy.'),
92
+ });
93
+ /**
94
+ * Schema for the access mode of a declared credential source.
95
+ *
96
+ * - `deny` — the sandboxed process cannot read the file / does not see the
97
+ * environment variable.
98
+ * - `mask` — the sandboxed process sees a per-session sentinel value; the
99
+ * host proxy substitutes sentinel→real on egress to `injectHosts`.
100
+ * For files this is whole-file masking (Linux only; degrades to `deny`
101
+ * on macOS — see {@link CredentialFileConfigSchema}).
102
+ */
103
+ const credentialModeSchema = z.enum(['deny', 'mask']);
104
+ /**
105
+ * Schema for an environment variable name. Restricted to POSIX identifiers so
106
+ * the name can never be parsed as a flag by `env -u` (macOS) or bwrap
107
+ * `--unsetenv` (Linux).
108
+ */
109
+ const envVarNameSchema = z
110
+ .string()
111
+ .regex(/^[A-Za-z_][A-Za-z0-9_]*$/, 'Environment variable name must start with a letter or underscore and contain only letters, digits, and underscores');
112
+ /**
113
+ * Schema for the optional structured-extraction regex on a masked file.
114
+ *
115
+ * Validates that the string compiles as a JavaScript RegExp and declares at
116
+ * least one capturing group — capture group 1 is the contract for "the
117
+ * credential value to mask". A pattern with zero groups would silently mask
118
+ * nothing useful, so it is rejected at config time rather than at runtime.
119
+ *
120
+ * Group count is determined by appending `|` (alternation with empty) and
121
+ * matching the empty string: the result array length is `1 + groupCount`,
122
+ * which counts capturing groups (including named ones) and ignores
123
+ * non-capturing `(?:…)`.
124
+ */
125
+ const extractPatternSchema = z.string().superRefine((val, ctx) => {
126
+ let re;
127
+ try {
128
+ re = new RegExp(val);
129
+ }
130
+ catch (err) {
131
+ ctx.addIssue({
132
+ code: z.ZodIssueCode.custom,
133
+ message: `extract is not a valid regular expression: ${err.message}`,
134
+ });
135
+ return;
136
+ }
137
+ const groupCount = new RegExp(re.source + '|').exec('').length - 1;
138
+ if (groupCount < 1) {
139
+ ctx.addIssue({
140
+ code: z.ZodIssueCode.custom,
141
+ message: 'extract must contain at least one capturing group — group 1 is ' +
142
+ 'the credential value to mask (e.g. "token:\\s*(\\S+)").',
143
+ });
144
+ }
145
+ });
146
+ /**
147
+ * Schema for a single credential file/directory entry.
148
+ *
149
+ * `mode: "mask"` without `extract` is **whole-file** masking: the entire
150
+ * file content is replaced inside the sandbox with one sentinel string,
151
+ * and the proxy substitutes that sentinel back to the real bytes on egress.
152
+ * This works for files whose content *is* the credential (a token file, a
153
+ * single-line secret).
154
+ *
155
+ * `mode: "mask"` with `extract` is **structured** masking: the regex is
156
+ * applied globally to the real file, capture group 1 of each match is a
157
+ * credential value, and only those captured spans are replaced with
158
+ * sentinels — the rest of the file is preserved byte-for-byte. This lets a
159
+ * tool that parses the file (`.netrc`, JSON/YAML configs) still succeed
160
+ * inside the sandbox while the credential values are protected. If the
161
+ * pattern matches nothing, behaviour is governed by `onExtractNoMatch`
162
+ * (default `"warn"` — the file is left readable as-is and a stderr
163
+ * warning is emitted).
164
+ *
165
+ * `mode: "mask"` with `decode: "jwt"` extends structured masking into
166
+ * encoded values: where `extract` opens plain text to mask a span inside
167
+ * it, `decode` opens the encoding so masking can target fields inside the
168
+ * decoded payload (`maskClaims`):
169
+ *
170
+ * - **Default pattern**: when `extract` is absent, a built-in JWT regex is
171
+ * used (every JWT starts `eyJ` — base64url of `{"`), so authors don't
172
+ * hand-write it. An explicit `extract` wins; its group-1 captures are the
173
+ * candidates.
174
+ * - **Decode-verification**: each candidate must actually BE a JWT (three
175
+ * segments, JSON header/payload, `alg` in the header) before it is
176
+ * masked; candidates failing verification are left untouched.
177
+ * - **Claim-level masking** (`maskClaims`): each named top-level payload
178
+ * claim present with a string value is replaced by its own sentinel and
179
+ * the token is rebuilt around the modified payload (original header,
180
+ * filler signature). All other claims stay real, so a client that
181
+ * decodes the token and reads a non-secret claim keeps working. The
182
+ * proxy substitutes both the whole rebuilt token (sent as a bearer
183
+ * credential) and each claim sentinel (extracted and sent alone).
184
+ * - **Whole-token fallback** (no `maskClaims`): the whole decoded value is
185
+ * treated as the credential — for bearer-style usage where the token
186
+ * itself is the secret — and replaced with a structurally valid fake JWT
187
+ * (parseable header/payload, far-future `exp`), so client-side token
188
+ * parsing inside the sandbox doesn't break. Its header declares
189
+ * `alg: HS256` (not `alg: none`, which misconfigured validators accept)
190
+ * with a garbage signature, so any validator the unswapped fake reaches
191
+ * rejects it.
192
+ * - **No verified candidate**: if nothing matches, no candidate verifies,
193
+ * or (with `maskClaims`) no named claim matches in any verified token,
194
+ * behaviour is governed by `onExtractNoMatch` — same as a non-matching
195
+ * `extract` (default `"warn"`: stderr warning, file left readable
196
+ * as-is).
197
+ *
198
+ * `maskDuplicates: true` (only meaningful with `extract` or `decode`)
199
+ * additionally replaces every verbatim occurrence of each masked value
200
+ * *outside* the regex-matched spans — for a secret repeated where the
201
+ * regex does not reach (e.g. pasted into a comment). The scan is raw
202
+ * substring matching, so a short or common captured value may also hit
203
+ * unrelated content that happens to contain it; intended for long,
204
+ * high-entropy secrets. Composed with `decode`, only captures that passed
205
+ * verification are scanned — a duplicate is the same value and reuses the
206
+ * verified capture's fake without re-verification.
207
+ *
208
+ * On macOS, SBPL cannot redirect reads, so `mode: "mask"` (with or without
209
+ * `extract`/`decode`) currently degrades to `mode: "deny"` (the file is
210
+ * unreadable inside the sandbox).
211
+ */
212
+ export const CredentialFileConfigSchema = z.object({
213
+ path: filesystemPathSchema.describe('Path to a credential file or directory. Supports the same path forms as ' +
214
+ 'filesystem.denyRead (absolute paths and ~ expansion).'),
215
+ mode: credentialModeSchema.describe('Access mode for this path'),
216
+ extract: extractPatternSchema
217
+ .optional()
218
+ .describe('Optional regex for structured masking. Applied globally; capture ' +
219
+ 'group 1 of each match is masked, the rest of the file is preserved. ' +
220
+ 'If the pattern matches nothing, behaviour is governed by ' +
221
+ 'onExtractNoMatch (default "warn"). Only meaningful when mode is ' +
222
+ '"mask"; accepted but ignored for "deny".'),
223
+ /**
224
+ * What to do when `extract` matches nothing in the file at runtime —
225
+ * or, with `decode`, when no candidate survives verification.
226
+ *
227
+ * - `"warn"` (default): emit a stderr warning and leave the file
228
+ * readable as-is inside the sandbox (fail-open). A non-matching
229
+ * pattern is treated as a config error to surface and fix, not a
230
+ * reason to break a tool that needs the file when the credential is
231
+ * legitimately absent.
232
+ * - `"deny"`: degrade the entry to `mode: "deny"` so the file is
233
+ * unreadable inside the sandbox (fail-closed). The operator declared
234
+ * this file as containing a credential; if the regex cannot find it,
235
+ * block access rather than expose it.
236
+ * - `"error"`: throw at wrap time so nothing runs until the operator
237
+ * fixes the config.
238
+ *
239
+ * Only meaningful when `mode` is `"mask"` and `extract` or `decode` is
240
+ * set; accepted but ignored otherwise.
241
+ */
242
+ onExtractNoMatch: z
243
+ .enum(['warn', 'deny', 'error'])
244
+ .optional()
245
+ .describe('What to do when extract matches nothing (or, with decode, no ' +
246
+ 'candidate verifies): "warn" (default — stderr warning, file left ' +
247
+ 'readable), "deny" (degrade to mode "deny" — file unreadable), or ' +
248
+ '"error" (throw at wrap time). Only meaningful with mode "mask" ' +
249
+ 'and extract or decode set.'),
250
+ decode: z
251
+ .enum(['jwt'])
252
+ .optional()
253
+ .describe('Optional encoded-credential format. "jwt": decodes recognized JWTs ' +
254
+ 'so masking can target fields inside them (see maskClaims). ' +
255
+ 'Candidates are located with a built-in JWT regex (or the explicit ' +
256
+ 'extract pattern, if set) and verified to actually be JWTs before ' +
257
+ 'masking. Without maskClaims, the whole decoded value is treated ' +
258
+ 'as the credential and replaced with a structurally valid fake ' +
259
+ 'JWT, so client-side token parsing keeps working. If no candidate ' +
260
+ 'verifies, behaviour is governed by onExtractNoMatch (default ' +
261
+ '"warn"). Only meaningful when mode is "mask"; accepted but ' +
262
+ 'ignored for "deny".'),
263
+ /**
264
+ * Names of top-level payload claims to mask inside each decoded value —
265
+ * the claim-level counterpart of `extract`: where `extract` opens plain
266
+ * text to mask a span inside it, `decode` + `maskClaims` opens the
267
+ * encoding to mask a field inside the decoded payload.
268
+ *
269
+ * For each verified JWT candidate, every named claim present with a
270
+ * string value is replaced by its own sentinel and the token is rebuilt
271
+ * around the modified payload (original header, filler signature). All
272
+ * other claims are preserved verbatim, so a tool that decodes the token
273
+ * and reads a non-secret claim (issuer, audience, user id) keeps
274
+ * working while the secret claim is protected. A named claim that is
275
+ * absent or non-string in a given token is skipped. If no named claim
276
+ * matches in any verified token, behaviour is governed by
277
+ * `onExtractNoMatch` — same as no candidate verifying.
278
+ *
279
+ * Requires `decode` (there is no payload to look inside otherwise); an
280
+ * explicitly empty list is rejected — see the superRefine below.
281
+ */
282
+ maskClaims: z
283
+ .array(z.string().min(1))
284
+ .optional()
285
+ .describe('Names of top-level payload claims to mask inside each decoded ' +
286
+ 'value, instead of replacing the whole token. Each named claim ' +
287
+ 'present with a string value gets its own sentinel; all other ' +
288
+ 'claims are preserved so claim-reading clients keep working. ' +
289
+ 'Requires decode. If no named claim matches in any verified ' +
290
+ 'token, behaviour is governed by onExtractNoMatch (default ' +
291
+ '"warn"). Only meaningful when mode is "mask"; accepted but ' +
292
+ 'ignored for "deny".'),
293
+ maskDuplicates: z
294
+ .boolean()
295
+ .optional()
296
+ .describe('If true, verbatim occurrences of each captured credential value ' +
297
+ 'outside the regex-matched spans are also replaced with the ' +
298
+ 'corresponding sentinel — for a secret repeated where the regex ' +
299
+ 'does not reach (e.g. in a comment). Matches raw substrings: short ' +
300
+ 'or common credential values may corrupt unrelated content, so ' +
301
+ 'this is intended for long, high-entropy secrets. With decode, ' +
302
+ 'only values that passed verification are scanned; duplicates ' +
303
+ "reuse the verified value's fake without re-verification. " +
304
+ 'Defaults to false. Only meaningful with mode "mask" and extract ' +
305
+ 'or decode set; accepted but ignored otherwise.'),
306
+ injectHosts: z
307
+ .array(domainPatternSchema)
308
+ .optional()
309
+ .describe('Optional narrowing of where the proxy substitutes this credential. ' +
310
+ 'If unset, defaults to network.allowedDomains — the credential is ' +
311
+ 'injected at every reachable host. Only meaningful when mode is ' +
312
+ '"mask"; accepted but ignored for "deny".'),
313
+ });
314
+ /**
315
+ * Schema for a single credential environment variable entry.
316
+ *
317
+ * `mode: "mask"` replaces the variable's value inside the sandbox with a
318
+ * per-session sentinel; the proxy substitutes sentinel→real on egress to
319
+ * the credential's injectHosts. A masked var that is unset on the host is
320
+ * skipped — there is nothing to protect.
321
+ *
322
+ * `mode: "mask"` without `extract` is **whole-value** masking: the entire
323
+ * value is replaced inside the sandbox with one sentinel string, and the
324
+ * proxy substitutes that sentinel back to the real value on egress. This
325
+ * works for variables whose value *is* the credential (a bare token).
326
+ *
327
+ * `mode: "mask"` with `extract` is **structured** masking: the regex is
328
+ * applied globally to the real value, capture group 1 of each match is a
329
+ * credential value, and only those captured spans are replaced with
330
+ * sentinels — the rest of the value is preserved byte-for-byte. This lets
331
+ * a tool that parses the value (a `DATABASE_URL` connection string, a
332
+ * composite `KEY:SECRET` pair) still succeed inside the sandbox while the
333
+ * credential spans are protected. If the pattern matches nothing,
334
+ * behaviour is governed by `onExtractNoMatch` (default `"warn"` — the
335
+ * variable passes through unmasked and a stderr warning is emitted).
336
+ *
337
+ * `mode: "mask"` with `decode: "jwt"` handles a variable whose whole value
338
+ * is a JWT (CI OIDC tokens, Supabase keys, ...). `decode` opens the encoded
339
+ * value for masking: without claim-level configuration the entire token is
340
+ * replaced by a structurally valid fake JWT — parseable three-segment shape
341
+ * with JSON header/payload and far-future `exp`, so a tool that inspects
342
+ * the token before sending it (segment count, exp, claims) keeps working.
343
+ * The fake's header declares `alg: HS256` — never `alg: none`, which
344
+ * misconfigured validators accept — with a filler signature, so a verifier
345
+ * the unswapped fake ever reaches rejects it cryptographically. The proxy
346
+ * swaps the whole fake token for the real one on egress.
347
+ *
348
+ * `decode: "jwt"` with `maskClaims` masks at the claim level instead: each
349
+ * named top-level payload claim present with a string value is replaced by
350
+ * its own sentinel and the token is rebuilt around the modified payload
351
+ * (original header segment, filler signature). All other claims stay real,
352
+ * so a client that decodes the token and reads a non-secret claim keeps
353
+ * working. The proxy substitutes both the whole rebuilt token (sent as a
354
+ * bearer credential) and each claim sentinel (extracted and sent alone).
355
+ *
356
+ * If the variable is set but its value does not verify as a JWT — or, with
357
+ * `maskClaims`, no named claim is present as a string — nothing was masked:
358
+ * the entry currently fails open — the real value stays in the sandbox
359
+ * environment and a loud stderr warning names the variable.
360
+ */
361
+ export const CredentialEnvVarConfigSchema = z.object({
362
+ name: envVarNameSchema.describe('Environment variable name'),
363
+ mode: credentialModeSchema.describe('Access mode for this environment variable'),
364
+ extract: extractPatternSchema
365
+ .optional()
366
+ .describe('Optional regex for structured masking. Applied globally; capture ' +
367
+ 'group 1 of each match is masked, the rest of the value is ' +
368
+ 'preserved. If the pattern matches nothing, behaviour is governed ' +
369
+ 'by onExtractNoMatch (default "warn"). Only meaningful when mode ' +
370
+ 'is "mask"; accepted but ignored for "deny".'),
371
+ /**
372
+ * What to do when `extract` matches nothing in the value at runtime.
373
+ *
374
+ * - `"warn"` (default): emit a stderr warning and let the variable pass
375
+ * through unmasked inside the sandbox (fail-open). A non-matching
376
+ * pattern is treated as a config error to surface and fix, not a
377
+ * reason to break a tool that needs the variable when the credential
378
+ * is legitimately absent from it.
379
+ * - `"deny"`: unset the variable inside the sandbox (fail-closed) — the
380
+ * env analog of degrading a file to `mode: "deny"`. The operator
381
+ * declared this variable as containing a credential; if the regex
382
+ * cannot find it, withhold the value rather than expose it.
383
+ * - `"error"`: throw at wrap time so nothing runs until the operator
384
+ * fixes the regex.
385
+ *
386
+ * Only meaningful when `mode` is `"mask"` and `extract` is set;
387
+ * accepted but ignored otherwise.
388
+ */
389
+ onExtractNoMatch: z
390
+ .enum(['warn', 'deny', 'error'])
391
+ .optional()
392
+ .describe('What to do when extract matches nothing: "warn" (default — stderr ' +
393
+ 'warning, variable passes through unmasked), "deny" (variable ' +
394
+ 'unset inside the sandbox), or "error" (throw at wrap time). Only ' +
395
+ 'meaningful with mode "mask" and extract set.'),
396
+ decode: z
397
+ .enum(['jwt'])
398
+ .optional()
399
+ .describe('Optional encoded-credential format. "jwt": the variable\'s whole ' +
400
+ 'value is verified to actually be a JWT and replaced with a ' +
401
+ 'structurally valid fake JWT so client-side token parsing keeps ' +
402
+ 'working; the proxy swaps the whole fake token on egress. If the ' +
403
+ 'value does not verify, the variable is left unmasked with a ' +
404
+ 'stderr warning (fail-open). Only meaningful when mode is "mask"; ' +
405
+ 'accepted but ignored for "deny".'),
406
+ /**
407
+ * Names of top-level payload claims to mask inside the decoded value —
408
+ * the env-var counterpart of the `maskClaims` on a file entry: `decode`
409
+ * opens the variable's encoded value so masking can target a field
410
+ * inside the decoded payload instead of replacing the whole token.
411
+ *
412
+ * Every named claim present with a string value is replaced by its own
413
+ * sentinel and the token is rebuilt around the modified payload
414
+ * (original header segment, filler signature). All other claims are
415
+ * preserved verbatim, so a tool that decodes the token and reads a
416
+ * non-secret claim (issuer, audience, user id) keeps working while the
417
+ * secret claim is protected. A named claim that is absent or non-string
418
+ * is skipped. If no named claim matches, nothing was masked and the
419
+ * entry fails open with a stderr warning — same path as a value that
420
+ * does not verify as a JWT.
421
+ *
422
+ * Requires `decode` (there is no payload to look inside otherwise); an
423
+ * explicitly empty list is rejected — see the superRefine below.
424
+ */
425
+ maskClaims: z
426
+ .array(z.string().min(1))
427
+ .optional()
428
+ .describe('Names of top-level payload claims to mask inside the decoded ' +
429
+ 'value, instead of replacing the whole token. Each named claim ' +
430
+ 'present with a string value gets its own sentinel; all other ' +
431
+ 'claims are preserved so claim-reading clients keep working. ' +
432
+ 'Requires decode. If no named claim matches, the variable is left ' +
433
+ 'unmasked with a stderr warning (fail-open). Only meaningful when ' +
434
+ 'mode is "mask"; accepted but ignored for "deny".'),
435
+ injectHosts: z
436
+ .array(domainPatternSchema)
437
+ .optional()
438
+ .describe('Optional narrowing of where the proxy substitutes this credential. ' +
439
+ 'If unset, defaults to network.allowedDomains — the credential is ' +
440
+ 'injected at every reachable host. Only meaningful when mode is ' +
441
+ '"mask"; accepted but ignored for "deny".'),
442
+ });
443
+ /**
444
+ * Credentials configuration schema for validation.
445
+ *
446
+ * Declares credential sources (files and environment variables) with a
447
+ * per-source mode:
448
+ * - `deny` blocks the source inside the sandbox (file reads are denied via the
449
+ * filesystem read-deny mechanism, env vars are unset in the child).
450
+ *
451
+ * Additional modes (e.g. `mask`) will be added in future releases.
452
+ *
453
+ * Only the sources declared here are affected; the section applies no
454
+ * implicit restrictions beyond them.
455
+ */
456
+ export const CredentialsConfigSchema = z
457
+ .object({
458
+ files: z
459
+ .array(CredentialFileConfigSchema)
460
+ .optional()
461
+ .describe('Credential files or directories to protect'),
462
+ envVars: z
463
+ .array(CredentialEnvVarConfigSchema)
464
+ .optional()
465
+ .describe('Environment variables to protect'),
466
+ allowPlaintextInject: z
467
+ .boolean()
468
+ .optional()
469
+ .describe('Allow sentinel→real substitution on the plain-HTTP proxy path. ' +
470
+ 'Defaults to false: without TLS termination the upstream identity ' +
471
+ 'is unverified and the credential travels in cleartext. Set only ' +
472
+ 'for trusted-network test fixtures.'),
473
+ })
474
+ // Reject unknown keys so a stale `credentials.injectHosts` (the removed
475
+ // block-level default) fails loudly instead of being silently stripped.
476
+ .strict();
477
+ /**
478
+ * Network configuration schema for validation
479
+ */
480
+ export const NetworkConfigSchema = z.object({
481
+ allowedDomains: z
482
+ .array(domainPatternSchema)
483
+ .describe('List of allowed domains (e.g., ["github.com", "*.npmjs.org"])'),
484
+ deniedDomains: z
485
+ .array(z.union([z.literal('*'), domainPatternSchema]))
486
+ .describe('List of denied domains. Unlike allowedDomains, a bare "*" is accepted here (deny-all).'),
487
+ strictAllowlist: z
488
+ .boolean()
489
+ .optional()
490
+ .describe('If true, hosts not in allowedDomains are denied without consulting the ask callback. Set this when allowedDomains is policy enforcement, not a prompt-suppression hint.'),
491
+ allowUnixSockets: z
492
+ .array(z.string())
493
+ .optional()
494
+ .describe('macOS only: Unix socket paths to allow. Ignored on Linux (seccomp cannot filter by path).'),
495
+ allowAllUnixSockets: z
496
+ .boolean()
497
+ .optional()
498
+ .describe('If true, allow all Unix sockets (disables blocking on both platforms). On Linux this also unblocks VM sockets (AF_VSOCK).'),
499
+ allowLocalBinding: z
500
+ .boolean()
501
+ .optional()
502
+ .describe('Whether to allow binding to local ports (default: false)'),
503
+ allowMachLookup: z
504
+ .array(z.string().refine(val => {
505
+ const prefix = val.endsWith('*') ? val.slice(0, -1) : val;
506
+ return !prefix.includes('*');
507
+ }, {
508
+ message: 'Wildcards are only allowed as a single trailing "*" (e.g., "com.example.*" or "*" for all services).',
509
+ }))
510
+ .optional()
511
+ .describe('macOS only: Additional XPC/Mach service names to allow looking up. Supports trailing-wildcard prefix matching (e.g., "2BUA8C4S2C.com.1password.*"). Needed for tools like 1Password CLI, Playwright, or the iOS Simulator that communicate via XPC.'),
512
+ httpProxyPort: z
513
+ .number()
514
+ .int()
515
+ .min(1)
516
+ .max(65535)
517
+ .optional()
518
+ .describe('Port of an external HTTP proxy to use instead of starting a local one. When provided, the library will skip starting its own HTTP proxy and use this port. The external proxy must handle domain filtering.'),
519
+ socksProxyPort: z
520
+ .number()
521
+ .int()
522
+ .min(1)
523
+ .max(65535)
524
+ .optional()
525
+ .describe('Port of an external SOCKS proxy to use instead of starting a local one. When provided, the library will skip starting its own SOCKS proxy and use this port. The external proxy must handle domain filtering.'),
526
+ allowUnauthenticatedSocksProxy: z
527
+ .boolean()
528
+ .optional()
529
+ .describe('Allow unauthenticated access to the local SOCKS proxy. This enables Git-over-SSH with the built-in macOS nc, but lets other local processes use the proxy while it is running.'),
530
+ mitmProxy: MitmProxyConfigSchema.optional().describe('Optional MITM proxy configuration. Routes matching domains through an upstream proxy via Unix socket while SRT still handles allow/deny filtering.'),
531
+ filterRequest: z
532
+ .custom(v => typeof v === 'function', {
533
+ message: 'filterRequest must be a function',
534
+ })
535
+ .optional()
536
+ .describe('Per-request filter callback. Receives the parsed HTTP request ' +
537
+ '(web-standard Request) and returns {action, reason?}. Denied ' +
538
+ 'requests get a 403 with the reason. If the callback throws, the ' +
539
+ 'request is denied. Applies to plain HTTP through the proxy and, ' +
540
+ 'when tlsTerminate is configured, to terminated HTTPS. SRT does not ' +
541
+ 'provide a policy language; library consumers own matching.'),
542
+ tlsTerminate: z
543
+ .object({
544
+ caCertPath: z
545
+ .string()
546
+ .min(1)
547
+ .optional()
548
+ .describe('Path to a PEM-encoded CA certificate. The sandboxed child is ' +
549
+ 'configured to trust this CA, and the TLS-terminating proxy uses ' +
550
+ 'it to sign per-host certificates. If omitted, SRT generates an ' +
551
+ 'ephemeral CA into a temp directory for the lifetime of the ' +
552
+ 'session.'),
553
+ caKeyPath: z
554
+ .string()
555
+ .min(1)
556
+ .optional()
557
+ .describe('Path to the PEM-encoded private key for caCertPath.'),
558
+ excludeDomains: z
559
+ .array(domainPatternSchema)
560
+ .optional()
561
+ .describe('Domain patterns (same syntax as allowedDomains) whose HTTPS ' +
562
+ 'connections are NOT terminated. Matching CONNECTs are opaque ' +
563
+ 'byte tunnels: still subject to the allow/deny domain lists, ' +
564
+ 'but the sandboxed client completes its own TLS handshake with ' +
565
+ 'the upstream, so filterRequest and credential injection do not ' +
566
+ 'apply to their HTTPS traffic (plain-HTTP requests to the same ' +
567
+ 'hosts keep the normal request pipeline). Use for hosts the ' +
568
+ 'proxy must not re-originate: ' +
569
+ 'mTLS upstreams (only the client holds the client certificate) ' +
570
+ 'and clients that pin the upstream certificate and would reject ' +
571
+ 'the MITM CA. Hosts still need to be reachable via ' +
572
+ 'allowedDomains; this list only changes how they are tunnelled.'),
573
+ extraCaCertPaths: z
574
+ .array(z.string().min(1))
575
+ .optional()
576
+ .describe('Paths to PEM CA certificate files appended to the trust bundle ' +
577
+ 'the sandboxed child is pointed at, after the MITM CA and the ' +
578
+ "host's regular roots. Use for site-local roots (e.g. an " +
579
+ 'internal mTLS CA) presented by excluded/passthrough hosts, so ' +
580
+ 'the child can verify them itself. Only the CERTIFICATE blocks ' +
581
+ 'of each file are copied; files that are missing, unreadable, ' +
582
+ 'or contain no PEM CERTIFICATE block are skipped (with a debug ' +
583
+ 'log), so paths that exist on only some hosts are safe to list.'),
584
+ })
585
+ .refine(o => !o.caCertPath === !o.caKeyPath, {
586
+ message: 'caCertPath and caKeyPath must be provided together',
587
+ })
588
+ .optional()
589
+ .describe('[EXPERIMENTAL] Enable in-process TLS termination so HTTPS ' +
590
+ 'request/response bodies are visible to SRT. Provide a CA cert+key, ' +
591
+ 'or omit both to have SRT generate an ephemeral one.'),
592
+ parentProxy: ParentProxyConfigSchema.optional().describe("Upstream HTTP proxy for outbound connections. When set, SRT's proxy " +
593
+ 'tunnels non-mitmProxy traffic through this parent instead of ' +
594
+ 'connecting directly. Falls back to HTTP_PROXY/HTTPS_PROXY/NO_PROXY ' +
595
+ 'env vars if unset.'),
596
+ });
597
+ /**
598
+ * Filesystem configuration schema for validation
599
+ */
600
+ export const FilesystemConfigSchema = z.object({
601
+ disabled: z
602
+ .boolean()
603
+ .optional()
604
+ .describe('Disable all filesystem policy enforcement. When true, no read or write rules are emitted: ' +
605
+ 'denyRead/allowRead/allowWrite/denyWrite are ignored. Use only when the sandboxed process ' +
606
+ 'is trusted with full host filesystem access. Network and credential-env restrictions ' +
607
+ 'still apply. On Linux, /dev is still replaced by the bwrap minimal devtmpfs.'),
608
+ denyRead: z.array(filesystemPathSchema).describe('Paths denied for reading'),
609
+ allowRead: z
610
+ .array(filesystemPathSchema)
611
+ .optional()
612
+ .describe('Paths to re-allow reading within denied regions (takes precedence over denyRead). ' +
613
+ 'Use with denyRead to deny a broad region then allow back specific subdirectories.'),
614
+ allowWrite: z
615
+ .array(filesystemPathSchema)
616
+ .describe('Paths allowed for writing'),
617
+ denyWrite: z
618
+ .array(filesystemPathSchema)
619
+ .describe('Paths denied for writing (takes precedence over allowWrite)'),
620
+ });
621
+ /**
622
+ * Configuration schema for ignoring specific sandbox violations
623
+ * Maps command patterns to filesystem paths to ignore violations for.
624
+ */
625
+ export const IgnoreViolationsConfigSchema = z
626
+ .record(z.string(), z.array(z.string()))
627
+ .describe('Map of command patterns to filesystem paths to ignore violations for. Use "*" to match all commands');
628
+ /**
629
+ * Configuration for locating/invoking the `srt-win` helper (Windows
630
+ * only). An embedder that links `srt-win`'s CLI into its own
631
+ * multicall binary points `path` at that binary; spawns then pass
632
+ * `--srt-win` as `argv[1]` (see `SRT_WIN_DISPATCH_ARG1` in
633
+ * `windows-sandbox-utils.ts` / `srt_win::SRT_WIN_DISPATCH_ARG1`) so
634
+ * the embedder's dispatcher can route to `srt_win::run_from_args`.
635
+ * Windows cannot reliably preserve a spoofed `argv[0]` across
636
+ * `CreateProcessWithLogonW` / `ShellExecuteExW(runas)`, so dispatch
637
+ * keys on `argv[1]`, not on `argv[0]` like
638
+ * {@link SeccompConfigSchema} does on Linux.
639
+ */
640
+ const srtWinPathSchema = z
641
+ .string()
642
+ .min(1, 'Path cannot be empty')
643
+ .refine(val => isAbsolute(val) || win32.isAbsolute(val), {
644
+ message: 'Binary path must be absolute',
645
+ });
646
+ export const SrtWinConfigSchema = z.object({
647
+ path: srtWinPathSchema
648
+ .optional()
649
+ .describe('Path to the srt-win binary. When unset, getSrtWinPath() resolves ' +
650
+ 'the packaged vendor/srt-win/<arch>/srt-win.exe. When set, the ' +
651
+ 'binary is spawned with the `--srt-win` argv[1] sentinel so a ' +
652
+ "multicall dispatcher can route to srt-win's CLI."),
653
+ });
654
+ /**
655
+ * Windows-specific configuration schema. See
656
+ * `windows-sandbox-utils.ts` for the install flow these settings
657
+ * must agree with.
658
+ *
659
+ * Canonical: `sublayerGuid`; the `wfpSublayerGuid` alias is resolved
660
+ * at read sites (`sublayerGuid ?? wfpSublayerGuid`) rather than via
661
+ * `.transform()` so this stays a plain `ZodObject` for consumers that
662
+ * `.extend()`/`.shape` it.
663
+ */
664
+ export const WindowsConfigSchema = z.object({
665
+ sublayerGuid: z
666
+ .string()
667
+ .uuid()
668
+ .optional()
669
+ .describe('WFP sublayer GUID under which the filters were installed. Omit to ' +
670
+ 'use the srt-win compile-time default. Set this when filters were ' +
671
+ 'installed by enterprise tooling under a custom sublayer.'),
672
+ wfpSublayerGuid: z
673
+ .string()
674
+ .uuid()
675
+ .optional()
676
+ .describe('Deprecated alias for sublayerGuid.'),
677
+ proxyPortRange: z
678
+ .tuple([z.number().int().min(1), z.number().int().max(65535)])
679
+ .refine(([lo, hi]) => lo <= hi && hi - lo <= 64, {
680
+ message: 'low must be ≤ high and range width ≤ 64',
681
+ })
682
+ .optional()
683
+ .describe('Inclusive [low, high] port range the JS mux proxy listeners bind ' +
684
+ 'inside. MUST match the range passed to `srt-win install ' +
685
+ '--proxy-port-range` (default 60080–60089) — the WFP loopback ' +
686
+ 'permit only covers ports in that range.'),
687
+ srtWin: SrtWinConfigSchema.optional().describe('How to locate/invoke the srt-win helper binary. Omit to resolve the ' +
688
+ 'packaged vendor binary; set when embedding srt-win into a multicall ' +
689
+ 'binary.'),
690
+ });
691
+ /**
692
+ * Seccomp configuration schema (Linux only)
693
+ */
694
+ const SeccompConfigSchema = z.object({
695
+ applyPath: z.string().optional().describe('Path to the apply-seccomp binary'),
696
+ argv0: z
697
+ .string()
698
+ .optional()
699
+ .describe('Invoke apply-seccomp as a multicall binary that dispatches on the ' +
700
+ 'ARGV0 environment variable. When set, applyPath is used verbatim ' +
701
+ '(no existence check) and the invocation inside bwrap is prefixed ' +
702
+ 'with ARGV0=<this value>. The caller is responsible for ensuring ' +
703
+ 'applyPath resolves inside the bwrap namespace and that the target ' +
704
+ 'binary implements the apply-seccomp interface when ARGV0 matches.'),
705
+ });
706
+ /**
707
+ * Main configuration schema for Sandbox Runtime validation
708
+ */
709
+ export const SandboxRuntimeConfigSchema = z
710
+ .object({
711
+ network: NetworkConfigSchema.describe('Network restrictions configuration'),
712
+ filesystem: FilesystemConfigSchema.describe('Filesystem restrictions configuration'),
713
+ credentials: CredentialsConfigSchema.optional().describe('Credential handling configuration. Only the explicitly declared files ' +
714
+ 'and environment variables are restricted.'),
715
+ ignoreViolations: IgnoreViolationsConfigSchema.optional().describe('Optional configuration for ignoring specific violations'),
716
+ enableWeakerNestedSandbox: z
717
+ .boolean()
718
+ .optional()
719
+ .describe('Enable weaker nested sandbox mode (for Docker environments)'),
720
+ enableWeakerNetworkIsolation: z
721
+ .boolean()
722
+ .optional()
723
+ .describe('Enable weaker network isolation to allow access to com.apple.trustd.agent (macOS only). ' +
724
+ 'This is needed for Go programs (gh, gcloud, terraform, kubectl, etc.) to verify TLS certificates ' +
725
+ 'when using httpProxyPort with a MITM proxy and custom CA. Enabling this opens a potential data ' +
726
+ 'exfiltration vector through the trustd service. Only enable if you need Go TLS verification.'),
727
+ allowAppleEvents: z
728
+ .boolean()
729
+ .optional()
730
+ .describe('Allow sending Apple Events and Launch Services open requests from the sandbox (macOS only). ' +
731
+ 'Needed for open, osascript, and anything that opens URLs or scripts other apps via AppleScript. ' +
732
+ 'This removes code-execution isolation: sandboxed commands can launch other applications ' +
733
+ 'unsandboxed with no user prompt (launched apps are not subject to the sandbox filesystem or ' +
734
+ 'network restrictions), and can script running apps subject to TCC automation consent. ' +
735
+ 'Default: false.'),
736
+ allowProcessSignals: z
737
+ .boolean()
738
+ .optional()
739
+ .describe('Allow signaling processes outside the current sandbox (macOS only). ' +
740
+ 'Useful for stopping a dev server started by an earlier sandboxed command. ' +
741
+ 'Normal OS signal permissions still apply, but this also allows signaling ' +
742
+ 'unrelated processes owned by the user. Only enable from trusted configuration. ' +
743
+ 'Default: false.'),
744
+ allowPty: z
745
+ .boolean()
746
+ .optional()
747
+ .describe('Allow pseudo-terminal (pty) operations (macOS only)'),
748
+ allowBrowserProcess: z
749
+ .boolean()
750
+ .optional()
751
+ .describe('Allow browser process operations (macOS only). Grants the additional Mach IPC, ' +
752
+ 'Mach bootstrap registration, and IOKit permissions that Chromium-based browsers ' +
753
+ 'need to launch and run inside the sandbox. Required for tools like agent-browser ' +
754
+ 'that spawn a Chrome/Chromium subprocess. Without this, Chrome will crash on startup ' +
755
+ 'due to denied Mach service lookups and bootstrap registrations.'),
756
+ seccomp: SeccompConfigSchema.optional().describe('Custom seccomp binary paths (Linux only).'),
757
+ bwrapPath: binaryPathSchema
758
+ .optional()
759
+ .describe('Linux only: absolute path to the bwrap (bubblewrap) binary. ' +
760
+ 'When set, this path is used directly instead of resolving "bwrap" via PATH.'),
761
+ socatPath: binaryPathSchema
762
+ .optional()
763
+ .describe('Linux only: absolute path to the socat binary. ' +
764
+ 'When set, this path is used directly instead of resolving "socat" via PATH.'),
765
+ windows: WindowsConfigSchema.optional().describe('Windows-specific settings (WFP sublayer, proxy port range).'),
766
+ })
767
+ .superRefine((cfg, ctx) => {
768
+ if (cfg.network.tlsTerminate && cfg.network.mitmProxy) {
769
+ ctx.addIssue({
770
+ code: z.ZodIssueCode.custom,
771
+ path: ['network', 'tlsTerminate'],
772
+ message: 'network.tlsTerminate and network.mitmProxy are mutually exclusive',
773
+ });
774
+ }
775
+ const creds = cfg.credentials;
776
+ if (!creds)
777
+ return;
778
+ // Every per-entry injectHosts pattern must be reachable via
779
+ // allowedDomains — semantic (wildcard-aware) coverage, not literal
780
+ // string membership, so `injectHosts: ['api.github.com']` is accepted
781
+ // when `allowedDomains: ['*.github.com']`.
782
+ const allowed = cfg.network.allowedDomains;
783
+ const checkSubset = (hosts, path) => {
784
+ for (const [i, host] of hosts.entries()) {
785
+ if (!isInjectHostCoveredByAllowedDomains(host, allowed)) {
786
+ ctx.addIssue({
787
+ code: z.ZodIssueCode.custom,
788
+ path: [...path, i],
789
+ message: `injectHosts entry "${host}" is not reachable via ` +
790
+ `network.allowedDomains — add "${host}" (or a covering ` +
791
+ `wildcard) to allowedDomains, or remove it from injectHosts.`,
792
+ });
793
+ }
794
+ }
795
+ };
796
+ // Per-credential checks. Substitution is gated per sentinel; an entry
797
+ // with no injectHosts defaults to network.allowedDomains (every
798
+ // reachable host), so absence is fine. An *explicit* empty list is
799
+ // rejected — "mask but never inject" is self-contradictory and almost
800
+ // certainly a config mistake. Applies to both env vars and files.
801
+ let hasMasked = false;
802
+ const checkMaskedEntry = (entry, path) => {
803
+ if (entry.mode !== 'mask')
804
+ return;
805
+ hasMasked = true;
806
+ if (entry.injectHosts) {
807
+ checkSubset(entry.injectHosts, [...path, 'injectHosts']);
808
+ }
809
+ // Credential substitution only runs on the TLS-terminated path, so a
810
+ // host covered by tlsTerminate.excludeDomains can never receive the
811
+ // real value — the upstream sees the placeholder. Reject the
812
+ // spellings that are *entirely* self-contradictory:
813
+ // - an explicit injectHosts entry whose every concrete host is
814
+ // excluded (isInjectHostCoveredByAllowedDomains is the generic
815
+ // "pattern fully covered by pattern list" predicate);
816
+ // - no injectHosts (= every allowedDomain) while excludeDomains
817
+ // covers all of allowedDomains, i.e. injection could never
818
+ // happen anywhere.
819
+ // A *partial* overlap is legitimate (excluded hosts simply don't get
820
+ // the credential) and is reported at runtime instead.
821
+ const exclude = cfg.network.tlsTerminate?.excludeDomains;
822
+ if (exclude?.length) {
823
+ if (entry.injectHosts) {
824
+ for (const [i, host] of entry.injectHosts.entries()) {
825
+ if (isInjectHostCoveredByAllowedDomains(host, exclude)) {
826
+ ctx.addIssue({
827
+ code: z.ZodIssueCode.custom,
828
+ path: [...path, 'injectHosts', i],
829
+ message: `injectHosts entry "${host}" is entirely covered by ` +
830
+ `network.tlsTerminate.excludeDomains. Credential ` +
831
+ `injection only runs on TLS-terminated connections, so ` +
832
+ `this host would receive the placeholder instead of the ` +
833
+ `credential. Remove it from one of the two lists.`,
834
+ });
835
+ }
836
+ }
837
+ }
838
+ else if (allowed.length > 0 &&
839
+ allowed.every(p => isInjectHostCoveredByAllowedDomains(p, exclude))) {
840
+ ctx.addIssue({
841
+ code: z.ZodIssueCode.custom,
842
+ path,
843
+ message: `This masked credential has no injectHosts, so it defaults ` +
844
+ `to network.allowedDomains — but ` +
845
+ `network.tlsTerminate.excludeDomains covers every allowed ` +
846
+ `domain, so it could never be injected anywhere. Credential ` +
847
+ `injection only runs on TLS-terminated connections.`,
848
+ });
849
+ }
850
+ }
851
+ if (entry.injectHosts !== undefined && entry.injectHosts.length === 0) {
852
+ ctx.addIssue({
853
+ code: z.ZodIssueCode.custom,
854
+ path,
855
+ message: `injectHosts is explicitly empty — the credential would be ` +
856
+ `masked but never injected. Omit injectHosts to default to ` +
857
+ `network.allowedDomains, or list the intended hosts.`,
858
+ });
859
+ }
860
+ };
861
+ const checkMaskClaims = (entry, path) => {
862
+ if (entry.maskClaims !== undefined && entry.decode === undefined) {
863
+ ctx.addIssue({
864
+ code: z.ZodIssueCode.custom,
865
+ path: [...path, 'maskClaims'],
866
+ message: `maskClaims requires decode — it names claims inside the ` +
867
+ `decoded payload. Set decode (e.g. "jwt"), or remove ` +
868
+ `maskClaims to mask the whole value.`,
869
+ });
870
+ }
871
+ if (entry.maskClaims !== undefined && entry.maskClaims.length === 0) {
872
+ ctx.addIssue({
873
+ code: z.ZodIssueCode.custom,
874
+ path: [...path, 'maskClaims'],
875
+ message: `maskClaims is explicitly empty — no claim would ever be ` +
876
+ `masked. Omit maskClaims to mask the whole token, or list ` +
877
+ `the claims to protect.`,
878
+ });
879
+ }
880
+ };
881
+ for (const [idx, v] of (creds.envVars ?? []).entries()) {
882
+ checkMaskedEntry(v, ['credentials', 'envVars', idx]);
883
+ checkMaskClaims(v, ['credentials', 'envVars', idx]);
884
+ }
885
+ for (const [idx, f] of (creds.files ?? []).entries()) {
886
+ checkMaskedEntry(f, ['credentials', 'files', idx]);
887
+ checkMaskClaims(f, ['credentials', 'files', idx]);
888
+ // Whole-file masking replaces one file's bytes with one sentinel;
889
+ // a directory has no single content to mask. The hard check is at
890
+ // runtime (stat after path normalization) — this catches the obvious
891
+ // syntactic case (trailing slash) early with a clearer error.
892
+ if (f.mode === 'mask' && f.path.endsWith('/')) {
893
+ ctx.addIssue({
894
+ code: z.ZodIssueCode.custom,
895
+ path: ['credentials', 'files', idx, 'path'],
896
+ message: `Credential mode "mask" applies to a single file, not a ` +
897
+ `directory. Use mode "deny" for "${f.path}", or point at the ` +
898
+ `credential file inside it.`,
899
+ });
900
+ }
901
+ }
902
+ // Masked credentials require the TLS-terminated proxy path so the real
903
+ // value is only sent to a cert-verified upstream. allowPlaintextInject
904
+ // is the explicit escape hatch.
905
+ if (hasMasked &&
906
+ cfg.network.tlsTerminate === undefined &&
907
+ !creds.allowPlaintextInject) {
908
+ ctx.addIssue({
909
+ code: z.ZodIssueCode.custom,
910
+ path: ['credentials'],
911
+ message: 'Credential masking requires network.tlsTerminate so substitution ' +
912
+ 'runs only over a verified TLS connection. Enable tlsTerminate, or ' +
913
+ 'set credentials.allowPlaintextInject to opt out (not recommended).',
914
+ });
915
+ }
916
+ });
917
+ //# sourceMappingURL=sandbox-config.js.map