@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,379 @@
1
+ import { Agent, createServer } from 'node:http';
2
+ import { request as httpRequest } from 'node:http';
3
+ import { request as httpsRequest } from 'node:https';
4
+ import { connect } from 'node:net';
5
+ import { URL } from 'node:url';
6
+ import { logForDebugging } from '../utils/debug.js';
7
+ import { CRL_PATH } from './mitm-ca.js';
8
+ import { decideAndRespond, } from './request-filter.js';
9
+ import { peekForClientHello, terminateAndForward, } from './tls-terminate-proxy.js';
10
+ import { canonicalizeHost, connectViaParentProxy, dialDirect, openConnectTunnel, proxyAuthHeader, selectParentProxyUrl, shouldBypassParentProxy, stripBrackets, stripHopByHop, } from './parent-proxy.js';
11
+ export function createHttpProxyServer(options) {
12
+ const server = createServer();
13
+ const mitmAgents = new Map();
14
+ server.once('close', () => {
15
+ for (const agent of mitmAgents.values()) {
16
+ agent.destroy();
17
+ }
18
+ mitmAgents.clear();
19
+ });
20
+ const checkAuth = (got) => {
21
+ if (!options.proxyAuthToken)
22
+ return true;
23
+ const m = /^basic\s+([a-z0-9+/=]+)\s*$/i.exec(got ?? '');
24
+ if (!m)
25
+ return false;
26
+ const decoded = Buffer.from(m[1], 'base64').toString('utf8');
27
+ const sep = decoded.indexOf(':');
28
+ return sep > 0 && decoded.slice(sep + 1) === options.proxyAuthToken;
29
+ };
30
+ // Handle CONNECT requests for HTTPS traffic
31
+ server.on('connect', async (req, socket, head) => {
32
+ ;
33
+ socket.setNoDelay(true);
34
+ // Attach error handler immediately to prevent unhandled errors
35
+ socket.on('error', err => {
36
+ logForDebugging(`Client socket error: ${err.message}`, { level: 'error' });
37
+ });
38
+ // Track client liveness so we can abort the upstream dial if they bail.
39
+ let clientGone = false;
40
+ let wrote200 = false;
41
+ const dialAc = new AbortController();
42
+ socket.once('close', () => {
43
+ clientGone = true;
44
+ dialAc.abort();
45
+ });
46
+ try {
47
+ if (!checkAuth(req.headers['proxy-authorization'])) {
48
+ socket.end('HTTP/1.1 407 Proxy Authentication Required\r\n' +
49
+ 'Proxy-Authenticate: Basic realm="srt"\r\n\r\n');
50
+ return;
51
+ }
52
+ const target = parseConnectTarget(req.url);
53
+ if (!target) {
54
+ logForDebugging(`Invalid CONNECT request: ${req.url}`, {
55
+ level: 'error',
56
+ });
57
+ socket.end('HTTP/1.1 400 Bad Request\r\n\r\n');
58
+ return;
59
+ }
60
+ const { hostname: rawHostname, port } = target;
61
+ const hostname = canonicalizeHost(rawHostname) ?? rawHostname;
62
+ const allowed = await options.filter(port, rawHostname, socket);
63
+ if (!allowed) {
64
+ logForDebugging(`Connection blocked to ${hostname}:${port}`, {
65
+ level: 'error',
66
+ });
67
+ socket.end('HTTP/1.1 403 Forbidden\r\n' +
68
+ 'Content-Type: text/plain\r\n' +
69
+ 'X-Proxy-Error: blocked-by-allowlist\r\n' +
70
+ '\r\n' +
71
+ 'Connection blocked by network allowlist');
72
+ return;
73
+ }
74
+ const activeFilterRequest = options.getFilterRequest?.() ?? options.filterRequest;
75
+ const activeMutateHeaders = options.getMutateHeaders?.() ?? options.mutateHeaders;
76
+ // Decide upstream route:
77
+ // in-process TLS termination
78
+ // > external MITM unix socket
79
+ // > parent HTTP proxy
80
+ // > direct
81
+ if (options.mitmCA &&
82
+ (options.shouldTerminateTLS?.(hostname, port) ?? true)) {
83
+ if (clientGone)
84
+ return;
85
+ socket.write('HTTP/1.1 200 Connection Established\r\n\r\n');
86
+ wrote200 = true;
87
+ const peeked = await peekForClientHello(socket, head);
88
+ if (clientGone)
89
+ return;
90
+ if (peeked.isTLS) {
91
+ terminateAndForward(options.mitmCA, activeFilterRequest, activeMutateHeaders, socket, peeked.head, {
92
+ hostname,
93
+ port,
94
+ upstreamCA: options.tlsTerminateUpstreamCA,
95
+ parentProxy: options.parentProxy,
96
+ });
97
+ return;
98
+ }
99
+ if (activeFilterRequest) {
100
+ logForDebugging(`[tls-terminate] blocking non-TLS CONNECT to ${hostname}:${port} while filterRequest is active`, { level: 'warn' });
101
+ socket.destroy();
102
+ return;
103
+ }
104
+ logForDebugging(`[tls-terminate] non-TLS bytes on CONNECT ${hostname}:${port}; opaque-tunnelling`);
105
+ head = peeked.head;
106
+ }
107
+ else if (options.mitmCA) {
108
+ logForDebugging(`[tls-terminate] policy exempts ${hostname}:${port}; opaque-tunnelling`);
109
+ }
110
+ const mitmSocketPath = options.getMitmSocketPath?.(hostname);
111
+ const parentUrl = !mitmSocketPath &&
112
+ options.parentProxy &&
113
+ !shouldBypassParentProxy(options.parentProxy, hostname)
114
+ ? selectParentProxyUrl(options.parentProxy, { isHttps: true })
115
+ : undefined;
116
+ let upstream;
117
+ try {
118
+ if (mitmSocketPath) {
119
+ logForDebugging(`Routing CONNECT ${hostname}:${port} through MITM proxy at ${mitmSocketPath}`);
120
+ upstream = await openConnectTunnel({
121
+ dial: () => connect({ path: mitmSocketPath }),
122
+ readyEvent: 'connect',
123
+ destHost: hostname,
124
+ destPort: port,
125
+ signal: dialAc.signal,
126
+ });
127
+ }
128
+ else if (parentUrl) {
129
+ upstream = await connectViaParentProxy(parentUrl, hostname, port, dialAc.signal);
130
+ }
131
+ else {
132
+ upstream = await dialDirect(hostname, port, undefined, dialAc.signal);
133
+ }
134
+ upstream.setNoDelay(true);
135
+ }
136
+ catch (err) {
137
+ logForDebugging(`CONNECT tunnel failed: ${err.message}`, {
138
+ level: 'error',
139
+ });
140
+ // If we already sent 200 (mitmCA sniff path), an HTTP status line now
141
+ // would land inside the tunnel as payload. Just close.
142
+ if (wrote200)
143
+ socket.destroy();
144
+ else
145
+ socket.end('HTTP/1.1 502 Bad Gateway\r\n\r\n');
146
+ return;
147
+ }
148
+ if (clientGone) {
149
+ upstream.on('error', () => { }); // swallow post-resolve errors
150
+ upstream.destroy();
151
+ return;
152
+ }
153
+ if (!wrote200) {
154
+ socket.write('HTTP/1.1 200 Connection Established\r\n\r\n');
155
+ }
156
+ // Forward any bytes the client sent in the same packet as the CONNECT
157
+ // (Node delivers these as the `head` buffer, not via the socket stream),
158
+ // plus anything the ClientHello sniff consumed when mitmCA is on.
159
+ if (head.length)
160
+ upstream.write(head);
161
+ upstream.pipe(socket);
162
+ socket.pipe(upstream);
163
+ upstream.on('error', err => {
164
+ logForDebugging(`CONNECT tunnel failed: ${err.message}`, {
165
+ level: 'error',
166
+ });
167
+ socket.destroy();
168
+ });
169
+ socket.on('close', () => upstream.destroy());
170
+ upstream.on('close', () => socket.destroy());
171
+ }
172
+ catch (err) {
173
+ logForDebugging(`Error handling CONNECT: ${err}`, { level: 'error' });
174
+ if (wrote200)
175
+ socket.destroy();
176
+ else
177
+ socket.end('HTTP/1.1 500 Internal Server Error\r\n\r\n');
178
+ }
179
+ });
180
+ // Handle regular HTTP requests
181
+ server.on('request', async (req, res) => {
182
+ try {
183
+ // Serve the empty CRL for Schannel's revocation check on MITM-minted
184
+ // leaves (see MitmCA.crlDer). CryptoAPI fetches the leaf's
185
+ // cRLDistributionPoints URL over plain HTTP with no
186
+ // Proxy-Authorization, so this must precede both the auth check and
187
+ // the `new URL(req.url)` parse below (which requires absolute-form).
188
+ // Match on pathname so both origin-form (`GET /srt.crl`, what
189
+ // CryptoAPI sends) and absolute-form (`GET http://…/srt.crl`, what a
190
+ // proxy-aware fetcher would send) resolve; the base is ignored for
191
+ // the absolute case.
192
+ if (options.mitmCA && req.method === 'GET' && isCrlRequest(req.url)) {
193
+ res.writeHead(200, {
194
+ 'Content-Type': 'application/pkix-crl',
195
+ 'Content-Length': options.mitmCA.crlDer.length,
196
+ });
197
+ res.end(options.mitmCA.crlDer);
198
+ return;
199
+ }
200
+ if (!checkAuth(req.headers['proxy-authorization'])) {
201
+ res.writeHead(407, { 'Proxy-Authenticate': 'Basic realm="srt"' });
202
+ res.end();
203
+ return;
204
+ }
205
+ const url = new URL(req.url);
206
+ if (url.protocol !== 'http:' && url.protocol !== 'https:') {
207
+ res.writeHead(400, { 'Content-Type': 'text/plain' });
208
+ res.end('Bad Request');
209
+ return;
210
+ }
211
+ const rawHostname = stripBrackets(url.hostname);
212
+ const hostname = canonicalizeHost(rawHostname) ?? rawHostname;
213
+ const port = url.port
214
+ ? parseInt(url.port, 10)
215
+ : url.protocol === 'https:'
216
+ ? 443
217
+ : 80;
218
+ const hostBracketed = hostname.includes(':') ? `[${hostname}]` : hostname;
219
+ const normalizedHostHeader = url.port
220
+ ? `${hostBracketed}:${url.port}`
221
+ : hostBracketed;
222
+ const allowed = await options.filter(port, rawHostname, req.socket);
223
+ if (!allowed) {
224
+ logForDebugging(`HTTP request blocked to ${hostname}:${port}`, {
225
+ level: 'error',
226
+ });
227
+ res.writeHead(403, {
228
+ 'Content-Type': 'text/plain',
229
+ 'X-Proxy-Error': 'blocked-by-allowlist',
230
+ });
231
+ res.end('Connection blocked by network allowlist');
232
+ return;
233
+ }
234
+ // Client may have disconnected while we awaited the filter; bail now
235
+ // rather than dialing an upstream nobody will read from.
236
+ if (req.socket.destroyed)
237
+ return;
238
+ const fwdHeaders = {
239
+ ...stripHopByHop(req.headers),
240
+ host: normalizedHostHeader,
241
+ };
242
+ const activeMutatePlaintext = options.getMutateHeadersPlaintext?.() ?? options.mutateHeadersPlaintext;
243
+ activeMutatePlaintext?.(fwdHeaders, hostname);
244
+ // Decide upstream route: MITM unix socket > parent HTTP proxy > direct.
245
+ const mitmSocketPath = options.getMitmSocketPath?.(hostname);
246
+ const parentUrl = !mitmSocketPath &&
247
+ options.parentProxy &&
248
+ !shouldBypassParentProxy(options.parentProxy, hostname)
249
+ ? selectParentProxyUrl(options.parentProxy, {
250
+ isHttps: url.protocol === 'https:',
251
+ })
252
+ : undefined;
253
+ // Reconstruct the absolute URI from canonicalized components rather than
254
+ // forwarding the client's raw req.url. This ensures filterRequest and the
255
+ // upstream proxy see exactly the host we allowlist-checked.
256
+ const absUrl = `${url.protocol}//${normalizedHostHeader}${url.pathname}${url.search}`;
257
+ // Per-request filter applies to plain HTTP too — otherwise a sandboxed
258
+ // client could bypass it by using http:// where the upstream serves it.
259
+ const activeFilterRequest = options.getFilterRequest?.() ?? options.filterRequest;
260
+ let body = req;
261
+ if (activeFilterRequest) {
262
+ const ac = new AbortController();
263
+ res.once('close', () => ac.abort());
264
+ const out = await decideAndRespond(activeFilterRequest, req, res, absUrl, ac.signal);
265
+ if (out === null)
266
+ return;
267
+ body = out;
268
+ }
269
+ const forwardResponse = (proxyRes) => {
270
+ res.writeHead(proxyRes.statusCode, stripHopByHop(proxyRes.headers));
271
+ proxyRes.pipe(res);
272
+ };
273
+ let proxyReq;
274
+ if (mitmSocketPath) {
275
+ logForDebugging(`Routing HTTP ${req.method} ${hostname}:${port} through MITM proxy at ${mitmSocketPath}`);
276
+ let mitmAgent = mitmAgents.get(mitmSocketPath);
277
+ if (!mitmAgent) {
278
+ mitmAgent = new Agent({
279
+ // @ts-expect-error - socketPath is valid but not in types
280
+ socketPath: mitmSocketPath,
281
+ });
282
+ mitmAgents.set(mitmSocketPath, mitmAgent);
283
+ }
284
+ proxyReq = httpRequest({
285
+ agent: mitmAgent,
286
+ path: absUrl,
287
+ method: req.method,
288
+ headers: fwdHeaders,
289
+ }, forwardResponse);
290
+ }
291
+ else if (parentUrl) {
292
+ const parentHost = stripBrackets(parentUrl.hostname);
293
+ const parentPort = Number(parentUrl.port) || (parentUrl.protocol === 'https:' ? 443 : 80);
294
+ const auth = proxyAuthHeader(parentUrl);
295
+ const requestFn = parentUrl.protocol === 'https:' ? httpsRequest : httpRequest;
296
+ proxyReq = requestFn({
297
+ hostname: parentHost,
298
+ port: parentPort,
299
+ path: absUrl,
300
+ method: req.method,
301
+ headers: auth
302
+ ? { ...fwdHeaders, 'proxy-authorization': auth }
303
+ : fwdHeaders,
304
+ }, forwardResponse);
305
+ }
306
+ else {
307
+ const requestFn = url.protocol === 'https:' ? httpsRequest : httpRequest;
308
+ proxyReq = requestFn({
309
+ hostname,
310
+ port,
311
+ path: url.pathname + url.search,
312
+ method: req.method,
313
+ headers: fwdHeaders,
314
+ }, forwardResponse);
315
+ }
316
+ proxyReq.on('error', err => {
317
+ logForDebugging(`Proxy request failed: ${err.message}`, {
318
+ level: 'error',
319
+ });
320
+ if (!res.headersSent) {
321
+ res.writeHead(502, { 'Content-Type': 'text/plain' });
322
+ res.end('Bad Gateway');
323
+ }
324
+ else {
325
+ res.destroy();
326
+ }
327
+ });
328
+ body.on('error', () => proxyReq.destroy());
329
+ // Tear down the upstream request if the client goes away mid-flight.
330
+ res.on('close', () => proxyReq.destroy());
331
+ body.pipe(proxyReq);
332
+ }
333
+ catch (err) {
334
+ logForDebugging(`Error handling HTTP request: ${err}`, { level: 'error' });
335
+ if (!res.headersSent) {
336
+ res.writeHead(500, { 'Content-Type': 'text/plain' });
337
+ res.end('Internal Server Error');
338
+ }
339
+ else {
340
+ res.destroy();
341
+ }
342
+ }
343
+ });
344
+ function isCrlRequest(rawUrl) {
345
+ if (!rawUrl)
346
+ return false;
347
+ if (rawUrl === CRL_PATH)
348
+ return true;
349
+ try {
350
+ const parsed = new URL(rawUrl);
351
+ if (parsed.pathname !== CRL_PATH)
352
+ return false;
353
+ const addr = server.address();
354
+ const boundPort = addr?.port ? String(addr.port) : undefined;
355
+ if (boundPort && parsed.port !== boundPort)
356
+ return false;
357
+ const host = stripBrackets(parsed.hostname.toLowerCase());
358
+ return host === '127.0.0.1' || host === 'localhost' || host === '::1';
359
+ }
360
+ catch {
361
+ return false;
362
+ }
363
+ }
364
+ return server;
365
+ }
366
+ /**
367
+ * Parse a CONNECT request-target into host + port. Handles both plain
368
+ * `host:port` and bracketed IPv6 `[::1]:port`.
369
+ */
370
+ function parseConnectTarget(target) {
371
+ const m = /^\[([^\]]+)\]:(\d+)$/.exec(target) ?? /^([^:]+):(\d+)$/.exec(target);
372
+ if (!m)
373
+ return undefined;
374
+ const port = Number(m[2]);
375
+ if (!Number.isInteger(port) || port < 1 || port > 65535)
376
+ return undefined;
377
+ return { hostname: m[1], port };
378
+ }
379
+ //# sourceMappingURL=http-proxy.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"http-proxy.js","sourceRoot":"","sources":["../../src/sandbox/http-proxy.ts"],"names":[],"mappings":"AAGA,OAAO,EAAE,KAAK,EAAE,YAAY,EAAE,MAAM,WAAW,CAAA;AAC/C,OAAO,EAAE,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AAI,CAAC,CAAC;QAAE,OAAO,SAAS,CAAA;IACxB,MAAM,IAAI,GAAG,MAAM,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAA;IACzB,IAAI,CAAC,MAAM,CAAC,SAAS,CAAC,IAAI,CAAC,IAAI,IAAI,GAAG,CAAC,IAAI,IAAI,GAAG,KAAK;QAAE,OAAO,SAAS,CAAA;IACzE,OAAO,EAAE,QAAQ,EAAE,CAAC,CAAC,CAAC,CAAE,EAAE,IAAI,EAAE,CAAA;AAClC,CAAC"}
@@ -0,0 +1,162 @@
1
+ import type { ChildProcess } from 'node:child_process';
2
+ import type { FsReadRestrictionConfig, FsWriteRestrictionConfig } from './sandbox-schemas.js';
3
+ import type { SeccompConfig } from './sandbox-config.js';
4
+ export interface LinuxNetworkBridgeContext {
5
+ httpSocketPath: string;
6
+ socksSocketPath: string;
7
+ httpBridgeProcess: ChildProcess;
8
+ socksBridgeProcess: ChildProcess;
9
+ httpProxyPort: number;
10
+ socksProxyPort: number;
11
+ }
12
+ export interface LinuxSandboxParams {
13
+ command: string;
14
+ needsNetworkRestriction: boolean;
15
+ httpSocketPath?: string;
16
+ socksSocketPath?: string;
17
+ httpProxyPort?: number;
18
+ socksProxyPort?: number;
19
+ /** Per-session proxy auth token; embedded in proxy env URLs. */
20
+ proxyAuthToken?: string;
21
+ /** Path to the TLS-termination CA cert; injected as trust env vars. */
22
+ caCertPath?: string;
23
+ readConfig?: FsReadRestrictionConfig;
24
+ writeConfig?: FsWriteRestrictionConfig;
25
+ /** Environment variable names to unset inside the sandbox (bwrap --unsetenv) */
26
+ unsetEnvVars?: string[];
27
+ /** Environment variables to set inside the sandbox (bwrap --setenv NAME VALUE) */
28
+ setEnvVars?: Record<string, string>;
29
+ /**
30
+ * Whole-file credential masks: bind fakePath (sentinel content) over
31
+ * realPath read-only so the sandbox reads the sentinel.
32
+ */
33
+ maskedFileBinds?: Array<{
34
+ realPath: string;
35
+ fakePath: string;
36
+ }>;
37
+ /**
38
+ * Host directory holding the fake files. Ro-bound over itself so the
39
+ * sandbox cannot write the bind sources even if allowWrite covers it.
40
+ */
41
+ maskedFileStoreDir?: string;
42
+ enableWeakerNestedSandbox?: boolean;
43
+ allowAllUnixSockets?: boolean;
44
+ binShell?: string;
45
+ /** Custom seccomp binary paths */
46
+ seccompConfig?: SeccompConfig;
47
+ /** Absolute path to the bwrap binary (default: resolve "bwrap" via PATH) */
48
+ bwrapPath?: string;
49
+ /** Absolute path to the socat binary (default: resolve "socat" via PATH) */
50
+ socatPath?: string;
51
+ /** Filesystem unix socket bound by the Linux violation monitor. When set,
52
+ * the socket is bind-mounted into the sandbox and apply-seccomp is told
53
+ * (via SRT_OBSERVE_SOCK) to install a USER_NOTIF observation filter and
54
+ * stream observed write-intent paths over that socket as newline JSON. */
55
+ observeSocketPath?: string;
56
+ }
57
+ /**
58
+ * Clean up mount point files created by bwrap for non-existent deny paths.
59
+ *
60
+ * When protecting non-existent deny paths, bwrap creates empty files on the
61
+ * host filesystem as mount points for --ro-bind. These files persist after
62
+ * bwrap exits. This function removes them.
63
+ *
64
+ * This should be called after each sandboxed command completes to prevent
65
+ * ghost dotfiles (e.g. .bashrc, .gitconfig) from appearing in the working
66
+ * directory. It is also called automatically on process exit as a safety net.
67
+ *
68
+ * Each command-completion call decrements the active-sandbox counter incremented by
69
+ * wrapCommandWithSandboxLinux(). File deletion is deferred until the counter
70
+ * reaches zero. Deleting a mount point file on the host while another bwrap
71
+ * instance is still running detaches that instance's bind mount (the dentry
72
+ * is unhashed, so path lookup no longer finds the mount) and the deny rule
73
+ * stops applying inside that sandbox.
74
+ *
75
+ * Pass `{ completed: false }` during manager teardown to leave other commands'
76
+ * counts untouched. `{ force: true }` is reserved for process exit.
77
+ */
78
+ export declare function cleanupBwrapMountPoints(opts?: {
79
+ force?: boolean;
80
+ completed?: boolean;
81
+ }): void;
82
+ /**
83
+ * Detailed status of Linux sandbox dependencies
84
+ */
85
+ export type SandboxDependencyCheck = {
86
+ warnings: string[];
87
+ errors: string[];
88
+ };
89
+ /**
90
+ * Options for Linux dependency checks. Explicit binary paths, when set,
91
+ * are checked directly instead of resolving via PATH.
92
+ */
93
+ export type LinuxDependencyOptions = {
94
+ seccompConfig?: SeccompConfig;
95
+ bwrapPath?: string;
96
+ socatPath?: string;
97
+ /**
98
+ * When false (the default secure mode), dependency checks probe whether
99
+ * bwrap can mount a private /proc. This fails in unprivileged containers
100
+ * (e.g. Docker's default), where the fix is to enable the weaker nested
101
+ * sandbox. Skip the probe when the weaker mode is already requested.
102
+ */
103
+ enableWeakerNestedSandbox?: boolean;
104
+ };
105
+ /**
106
+ * Check sandbox dependencies and return structured result
107
+ */
108
+ export declare function checkLinuxDependencies(opts?: LinuxDependencyOptions): SandboxDependencyCheck;
109
+ export declare function initializeLinuxNetworkBridge(httpProxyPort: number, socksProxyPort: number, socatPath?: string): Promise<LinuxNetworkBridgeContext>;
110
+ /**
111
+ * Wrap a command with sandbox restrictions on Linux
112
+ *
113
+ * UNIX SOCKET BLOCKING (APPLY-SECCOMP):
114
+ * This implementation uses a custom apply-seccomp binary to block Unix domain socket
115
+ * creation for user commands while allowing network infrastructure:
116
+ *
117
+ * Stage 1: Outer bwrap - Network and filesystem isolation (NO seccomp)
118
+ * - Bubblewrap starts with isolated network namespace (--unshare-net)
119
+ * - Bubblewrap applies PID namespace isolation (--unshare-pid and --proc)
120
+ * - Filesystem restrictions are applied (read-only mounts, bind mounts, etc.)
121
+ * - Socat processes start and connect to Unix socket bridges (can use socket(AF_UNIX, ...))
122
+ *
123
+ * Stage 2: apply-seccomp - Nested PID namespace + seccomp filter
124
+ * - apply-seccomp creates a nested user+PID+mount namespace and remounts /proc
125
+ * - Inside, apply-seccomp becomes PID 1 (non-dumpable init/reaper)
126
+ * - Forks, sets PR_SET_NO_NEW_PRIVS, applies seccomp via prctl(PR_SET_SECCOMP)
127
+ * - Execs user command with seccomp active (cannot create new Unix sockets)
128
+ * - User command cannot see or ptrace bwrap/bash/socat (separate PID namespace)
129
+ *
130
+ * This solves the conflict between:
131
+ * - Security: Blocking arbitrary Unix socket creation in user commands
132
+ * - Functionality: Network sandboxing requires socat to call socket(AF_UNIX, ...) for bridge connections
133
+ *
134
+ * The seccomp-bpf filter blocks socket(AF_UNIX, ...) syscalls, preventing:
135
+ * - Creating new Unix domain socket file descriptors
136
+ *
137
+ * It also blocks socket(AF_VSOCK, ...): the network namespace does not fence
138
+ * VM sockets, so one would reach out of the sandbox past the proxies.
139
+ *
140
+ * Security limitations:
141
+ * - Does NOT block operations (bind, connect, sendto, etc.) on inherited Unix socket FDs
142
+ * - Does NOT prevent passing Unix socket FDs via SCM_RIGHTS
143
+ * - For most sandboxing use cases, blocking socket creation is sufficient
144
+ *
145
+ * The filter allows:
146
+ * - All TCP/UDP sockets (AF_INET, AF_INET6) for normal network operations
147
+ * - All other syscalls
148
+ *
149
+ * PLATFORM NOTE:
150
+ * The allowUnixSockets configuration is not path-based on Linux (unlike macOS)
151
+ * because seccomp-bpf cannot inspect user-space memory to read socket paths.
152
+ *
153
+ * Requirements for seccomp filtering:
154
+ * - Pre-built apply-seccomp binaries are included for x64 and ARM64
155
+ * - Pre-generated BPF filters are included for x64 and ARM64
156
+ * - Other architectures are not currently supported (no apply-seccomp binary available)
157
+ * - To use sandboxing without Unix socket blocking on unsupported architectures,
158
+ * set allowAllUnixSockets: true in your configuration
159
+ * Dependencies are checked by checkLinuxDependencies() before enabling the sandbox.
160
+ */
161
+ export declare function wrapCommandWithSandboxLinux(params: LinuxSandboxParams): Promise<string>;
162
+ //# sourceMappingURL=linux-sandbox-utils.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"linux-sandbox-utils.d.ts","sourceRoot":"","sources":["../../src/sandbox/linux-sandbox-utils.ts"],"names":[],"mappings":"AAMA,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,oBAAoB,CAAA;AAStD,OAAO,KAAK,EACV,uBAAuB,EACvB,wBAAwB,EACzB,MAAM,sBAAsB,CAAA;AAE7B,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