@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,19 @@
1
+ import { type SandboxViolationEvent } from './macos-sandbox-utils.js';
2
+ /**
3
+ * In-memory tail for sandbox violations
4
+ */
5
+ export declare class SandboxViolationStore {
6
+ private violations;
7
+ private totalCount;
8
+ private readonly maxSize;
9
+ private listeners;
10
+ addViolation(violation: SandboxViolationEvent): void;
11
+ getViolations(limit?: number): SandboxViolationEvent[];
12
+ getCount(): number;
13
+ getTotalCount(): number;
14
+ getViolationsForCommand(command: string): SandboxViolationEvent[];
15
+ clear(): void;
16
+ subscribe(listener: (violations: SandboxViolationEvent[]) => void): () => void;
17
+ private notifyListeners;
18
+ }
19
+ //# sourceMappingURL=sandbox-violation-store.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"sandbox-violation-store.d.ts","sourceRoot":"","sources":["../../src/sandbox/sandbox-violation-store.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,qBAAqB,EAAE,MAAM,0BAA0B,CAAA;AAGrE;;GAEG;AACH,qBAAa,qBAAqB;IAChC,OAAO,CAAC,UAAU,CAA8B;IAChD,OAAO,CAAC,UAAU,CAAI;IACtB,OAAO,CAAC,QAAQ,CAAC,OAAO,CAAM;IAC9B,OAAO,CAAC,SAAS,CACN;IAEX,YAAY,CAAC,SAAS,EAAE,qBAAqB,GAAG,IAAI;IASpD,aAAa,CAAC,KAAK,CAAC,EAAE,MAAM,GAAG,qBAAqB,EAAE;IAUtD,QAAQ,IAAI,MAAM;IAIlB,aAAa,IAAI,MAAM;IAIvB,uBAAuB,CAAC,OAAO,EAAE,MAAM,GAAG,qBAAqB,EAAE;IAKjE,KAAK,IAAI,IAAI;IAMb,SAAS,CACP,QAAQ,EAAE,CAAC,UAAU,EAAE,qBAAqB,EAAE,KAAK,IAAI,GACtD,MAAM,IAAI;IAQb,OAAO,CAAC,eAAe;CAKxB"}
@@ -0,0 +1,57 @@
1
+ import { encodeSandboxedCommand } from './sandbox-utils.js';
2
+ /**
3
+ * In-memory tail for sandbox violations
4
+ */
5
+ export class SandboxViolationStore {
6
+ constructor() {
7
+ this.violations = [];
8
+ this.totalCount = 0;
9
+ this.maxSize = 100;
10
+ this.listeners = new Set();
11
+ }
12
+ addViolation(violation) {
13
+ this.violations.push(violation);
14
+ this.totalCount++;
15
+ if (this.violations.length > this.maxSize) {
16
+ this.violations = this.violations.slice(-this.maxSize);
17
+ }
18
+ this.notifyListeners();
19
+ }
20
+ getViolations(limit) {
21
+ if (limit === undefined) {
22
+ return [...this.violations];
23
+ }
24
+ if (limit <= 0) {
25
+ return [];
26
+ }
27
+ return this.violations.slice(-limit);
28
+ }
29
+ getCount() {
30
+ return this.violations.length;
31
+ }
32
+ getTotalCount() {
33
+ return this.totalCount;
34
+ }
35
+ getViolationsForCommand(command) {
36
+ const commandBase64 = encodeSandboxedCommand(command);
37
+ return this.violations.filter(v => v.encodedCommand === commandBase64);
38
+ }
39
+ clear() {
40
+ this.violations = [];
41
+ // Don't reset totalCount when clearing
42
+ this.notifyListeners();
43
+ }
44
+ subscribe(listener) {
45
+ this.listeners.add(listener);
46
+ listener(this.getViolations());
47
+ return () => {
48
+ this.listeners.delete(listener);
49
+ };
50
+ }
51
+ notifyListeners() {
52
+ // Always notify with all violations so listeners can track the full count
53
+ const violations = this.getViolations();
54
+ this.listeners.forEach(listener => listener(violations));
55
+ }
56
+ }
57
+ //# sourceMappingURL=sandbox-violation-store.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"sandbox-violation-store.js","sourceRoot":"","sources":["../../src/sandbox/sandbox-violation-store.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,sBAAsB,EAAE,MAAM,oBAAoB,CAAA;AAE3D;;GAEG;AACH,MAAM,OAAO,qBAAqB;IAAlC;QACU,eAAU,GAA4B,EAAE,CAAA;QACxC,eAAU,GAAG,CAAC,CAAA;QACL,YAAO,GAAG,GAAG,CAAA;QACtB,cAAS,GACf,IAAI,GAAG,EAAE,CAAA;IAuDb,CAAC;IArDC,YAAY,CAAC,SAAgC;QAC3C,IAAI,CAAC,UAAU,CAAC,IAAI,CAAC,SAAS,CAAC,CAAA;QAC/B,IAA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CAAA;QACjC,CAAC,CAAA;IACH,CAAC;IAEO,eAAe;QACrB,0EAA0E;QAC1E,MAAM,UAAU,GAAG,IAAI,CAAC,aAAa,EAAE,CAAA;QACvC,IAAI,CAAC,SAAS,CAAC,OAAO,CAAC,QAAQ,CAAC,EAAE,CAAC,QAAQ,CAAC,UAAU,CAAC,CAAC,CAAA;IAC1D,CAAC;CACF"}
@@ -0,0 +1,38 @@
1
+ import type { Socket } from 'net';
2
+ import type { ResolvedParentProxy } from './parent-proxy.js';
3
+ export interface SocksProxyServerOptions {
4
+ filter(port: number, host: string): Promise<boolean> | boolean;
5
+ /**
6
+ * Optional upstream HTTP proxy. When present, SOCKS CONNECT requests are
7
+ * tunnelled through the parent's HTTP CONNECT instead of dialing directly.
8
+ * NO_PROXY-matched hosts still connect directly.
9
+ */
10
+ parentProxy?: ResolvedParentProxy;
11
+ /**
12
+ * Per-session token (same value as the HTTP proxy's). When set, the
13
+ * server requires SOCKS5 username/password auth and only accepts
14
+ * user "srt" with this token as the password.
15
+ */
16
+ proxyAuthToken?: string;
17
+ /**
18
+ * Optional dynamic guard: when returning true (e.g. while `network.filterRequest`
19
+ * is active), SOCKS5 connections are rejected so clients cannot bypass
20
+ * HTTP request inspection via an opaque SOCKS tunnel.
21
+ */
22
+ isBlocked?: () => boolean;
23
+ }
24
+ export interface SocksProxyWrapper {
25
+ /**
26
+ * Hand an already-accepted socket to the SOCKS state machine. Used by the
27
+ * mux front-end after first-byte sniffing. The socket must carry the full
28
+ * SOCKS greeting starting at byte 0 (i.e. any peeked bytes already
29
+ * `unshift()`ed back). Replicates the library's own accept path
30
+ * (`setNoDelay()` + `_handleConnection`) and tracks the socket so
31
+ * `close()` can force-destroy it.
32
+ */
33
+ handleConnection(socket: Socket): void;
34
+ /** Force-destroy all injected connections. */
35
+ close(): Promise<void>;
36
+ }
37
+ export declare function createSocksProxyServer(options: SocksProxyServerOptions): SocksProxyWrapper;
38
+ //# sourceMappingURL=socks-proxy.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"socks-proxy.d.ts","sourceRoot":"","sources":["../../src/sandbox/socks-proxy.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,KAAK,CAAA;AAGjC,OAAO,KAAK,EAAE,mBAAmB,EAAE,MAAM,mBAAmB,CAAA;AAS5D,MAAM,WAAW,uBAAuB;IACtC,MAAM,CAAC,IAAI,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,GAAG,OAAO,CAAC,OAAO,CAAC,GAAG,OAAO,CAAA;IAE9D;;;;OAIG;IACH,WAAW,CAAC,EAAE,mBAAmB,CAAA;IAEjC;;;;OAIG;IACH,cAAc,CAAC,EAAE,MAAM,CAAA;IAEvB;;;;OAIG;IACH,SAAS,CAAC,EAAE,MAAM,OAAO,CAAA;CAC1B;AAED,MAAM,WAAW,iBAAiB;IAChC;;;;;;;OAOG;IACH,gBAAgB,CAAC,MAAM,EAAE,MAAM,GAAG,IAAI,CAAA;IACtC,8CAA8C;IAC9C,KAAK,IAAI,OAAO,CAAC,IAAI,CAAC,CAAA;CACvB;AAED,wBAAgB,sBAAsB,CACpC,OAAO,EAAE,uBAAuB,GAC/B,iBAAiB,CA0InB"}
@@ -0,0 +1,123 @@
1
+ import { createServer } from '@pondwader/socks5-server';
2
+ import { logForDebugging } from '../utils/debug.js';
3
+ import { connectViaParentProxy, dialDirect, isValidHost, selectParentProxyUrl, shouldBypassParentProxy, } from './parent-proxy.js';
4
+ export function createSocksProxyServer(options) {
5
+ const socksServer = createServer();
6
+ if (options.proxyAuthToken) {
7
+ socksServer.setAuthHandler((conn, accept, deny) => {
8
+ if (conn.username === 'srt' && conn.password === options.proxyAuthToken) {
9
+ accept();
10
+ }
11
+ else {
12
+ logForDebugging('SOCKS auth rejected', { level: 'error' });
13
+ deny();
14
+ }
15
+ });
16
+ }
17
+ socksServer.setRulesetValidator(async (conn) => {
18
+ try {
19
+ if (options.isBlocked?.()) {
20
+ logForDebugging('SOCKS connection blocked while network.filterRequest is active', { level: 'warn' });
21
+ return false;
22
+ }
23
+ const hostname = conn.destAddress;
24
+ const port = conn.destPort;
25
+ // SOCKS5 DOMAINNAME is a raw length-prefixed byte string with zero
26
+ // validation from the protocol or the library. Reject control chars
27
+ // (null bytes, CRLF) here so they never reach the allowlist matcher,
28
+ // where string suffix matching would be trivially fooled.
29
+ if (!isValidHost(hostname)) {
30
+ logForDebugging(`Rejecting malformed SOCKS host: ${JSON.stringify(hostname)}`, { level: 'error' });
31
+ return false;
32
+ }
33
+ logForDebugging(`Connection request to ${hostname}:${port}`);
34
+ const allowed = await options.filter(port, hostname);
35
+ if (!allowed) {
36
+ logForDebugging(`Connection blocked to ${hostname}:${port}`, {
37
+ level: 'error',
38
+ });
39
+ return false;
40
+ }
41
+ logForDebugging(`Connection allowed to ${hostname}:${port}`);
42
+ return true;
43
+ }
44
+ catch (error) {
45
+ logForDebugging(`Error validating connection: ${error}`, {
46
+ level: 'error',
47
+ });
48
+ return false;
49
+ }
50
+ });
51
+ // Override the default connection handler so we can route through a parent
52
+ // HTTP proxy when one is configured. The default handler does a straight
53
+ // net.connect() which fails when direct egress is blocked.
54
+ socksServer.setConnectionHandler((conn, sendStatus) => {
55
+ const host = conn.destAddress;
56
+ const port = conn.destPort;
57
+ // Track client liveness so we can abort the upstream dial if they bail.
58
+ let clientGone = false;
59
+ let upstreamRef;
60
+ const dialAc = new AbortController();
61
+ conn.socket.once('close', () => {
62
+ clientGone = true;
63
+ dialAc.abort();
64
+ upstreamRef?.destroy();
65
+ });
66
+ conn.socket.on('error', () => {
67
+ dialAc.abort();
68
+ upstreamRef?.destroy();
69
+ });
70
+ // SOCKS is an opaque TCP tunnel — semantically identical to HTTP
71
+ // CONNECT — so always prefer HTTPS_PROXY if set, regardless of dest port.
72
+ const parentUrl = options.parentProxy && !shouldBypassParentProxy(options.parentProxy, host)
73
+ ? selectParentProxyUrl(options.parentProxy, { isHttps: true })
74
+ : undefined;
75
+ const open = parentUrl
76
+ ? connectViaParentProxy(parentUrl, host, port, dialAc.signal)
77
+ : dialDirect(host, port, undefined, dialAc.signal);
78
+ open
79
+ .then(upstream => {
80
+ upstreamRef = upstream;
81
+ upstream.on('error', () => conn.socket.destroy());
82
+ if (clientGone) {
83
+ upstream.destroy();
84
+ return;
85
+ }
86
+ sendStatus('REQUEST_GRANTED');
87
+ upstream.pipe(conn.socket);
88
+ conn.socket.pipe(upstream);
89
+ upstream.on('close', () => conn.socket.destroy());
90
+ })
91
+ .catch(err => {
92
+ logForDebugging(`SOCKS connect to ${host}:${port} failed: ${err.message}`, { level: 'error' });
93
+ if (!clientGone) {
94
+ try {
95
+ sendStatus('HOST_UNREACHABLE');
96
+ }
97
+ catch {
98
+ // socket may have closed between the check and the write
99
+ }
100
+ }
101
+ });
102
+ });
103
+ // Track every injected client socket so close() can tear them down
104
+ // immediately. A SOCKS connection mid-`dialDirect()` (30s timeout) or
105
+ // mid-relay would otherwise hold reset() open past bun's test timeout.
106
+ // The library's internal net.Server is never .listen()ed — the mux owns
107
+ // accept — so there's no listener to close; we only destroy sockets.
108
+ const openSockets = new Set();
109
+ return {
110
+ handleConnection(socket) {
111
+ socket.setNoDelay();
112
+ openSockets.add(socket);
113
+ socket.once('close', () => openSockets.delete(socket));
114
+ socksServer._handleConnection(socket);
115
+ },
116
+ async close() {
117
+ for (const socket of openSockets)
118
+ socket.destroy();
119
+ openSockets.clear();
120
+ },
121
+ };
122
+ }
123
+ //# sourceMappingURL=socks-proxy.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"socks-proxy.js","sourceRoot":"","sources":["../../src/sandbox/socks-proxy.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,YAAY,EAAE,MAAM,0BAA0B,CAAA;AACvD,OAAO,EAAE,eAAe,EAAE,MAAM,mBAAmB,CAAA;AAEnD,OAAO,EACL,qBAAqB,EACrB,UAAU,EACV,WAAW,EACX,oBAAoB,EACpB,uBAAuB,GACxB,MAAM,mBAAmB,CAAA;AAy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AA;gBAChC,CAAC;gBAAC,MAAM,CAAC;oBACP,yDAAyD;gBAC3D,CAAC;YACH,CAAC;QACH,CAAC,CAAC,CAAA;IACN,CAAC,CAAC,CAAA;IAEF,mEAAmE;IACnE,sEAAsE;IACtE,uEAAuE;IACvE,wEAAwE;IACxE,qEAAqE;IACrE,MAAM,WAAW,GAAG,IAAI,GAAG,EAAU,CAAA;IAErC,OAAO;QACL,gBAAgB,CAAC,MAAc;YAC7B,MAAM,CAAC,UAAU,EAAE,CAAA;YACnB,WAAW,CAAC,GAAG,CAAC,MAAM,CAAC,CAAA;YACvB,MAAM,CAAC,IAAI,CAAC,OAAO,EAAE,GAAG,EAAE,CAAC,WAAW,CAAC,MAAM,CAAC,MAAM,CAAC,CAAC,CAAA;YACtD,WAAW,CAAC,iBAAiB,CAAC,MAAM,CAAC,CAAA;QACvC,CAAC;QACD,KAAK,CAAC,KAAK;YACT,KAAK,MAAM,MAAM,IAAI,WAAW;gBAAE,MAAM,CAAC,OAAO,EAAE,CAAA;YAClD,WAAW,CAAC,KAAK,EAAE,CAAA;QACrB,CAAC;KACF,CAAA;AACH,CAAC"}
@@ -0,0 +1,63 @@
1
+ /**
2
+ * In-process TLS termination for HTTPS traffic through the forward proxy.
3
+ *
4
+ * When a MitmCA is configured, the forward proxy hands CONNECT requests here
5
+ * instead of opening an opaque byte tunnel. We terminate the client's TLS
6
+ * with a per-host leaf cert (see mitm-leaf.ts), parse the decrypted stream
7
+ * as HTTP/1.1, and re-issue each request upstream over a real TLS
8
+ * connection. The optional `filterRequest` callback runs on each parsed
9
+ * request before it is forwarded.
10
+ */
11
+ import type { Duplex } from 'node:stream';
12
+ import type { MitmCA } from './mitm-ca.js';
13
+ import { type FilterRequestCallback, type MutateForwardedHeaders } from './request-filter.js';
14
+ import { type ResolvedParentProxy } from './parent-proxy.js';
15
+ /**
16
+ * True if `buf` starts with a TLS Handshake record header.
17
+ *
18
+ * Three bytes: content type 0x16 (Handshake) + legacy_record_version
19
+ * 0x03,0x00–0x03. RFC 8446 §5.1 froze the record-layer version (TLS 1.3+
20
+ * negotiate via the supported_versions extension, the wire header stays
21
+ * ≤0x0303), so this holds for current and future TLS. Same predicate as
22
+ * mitmproxy `starts_like_tls_record`; nginx `ssl_preread` routes on byte 0
23
+ * alone and HAProxy `req.ssl_hello_type` reads 9 bytes to also extract the
24
+ * handshake type — 3 is the established middle ground for "is this TLS".
25
+ *
26
+ * Routing heuristic, not a security check: a non-TLS stream that happens to
27
+ * start 16 03 0x is handed to the TLS server, which then rejects it properly.
28
+ */
29
+ export declare function looksLikeClientHello(buf: Buffer): boolean;
30
+ export declare function peekForClientHello(socket: Duplex, head: Buffer): Promise<{
31
+ isTLS: boolean;
32
+ head: Buffer;
33
+ }>;
34
+ export type TerminateTarget = {
35
+ hostname: string;
36
+ port: number;
37
+ /**
38
+ * Additional trusted CA(s) for the proxy's outbound TLS leg. Unset → system
39
+ * roots + NODE_EXTRA_CA_CERTS. Primarily a test seam (NODE_EXTRA_CA_CERTS
40
+ * is read at process start, so tests can't set it from inside the suite).
41
+ */
42
+ upstreamCA?: string | Buffer | Array<string | Buffer>;
43
+ /** Optional parent HTTP(S) proxy to tunnel upstream TLS through. */
44
+ parentProxy?: ResolvedParentProxy;
45
+ };
46
+ /**
47
+ * Terminate the client's TLS on `socket`, parse the decrypted HTTP/1.1
48
+ * stream, and forward each request to `target` over a fresh upstream TLS
49
+ * connection.
50
+ *
51
+ * Preconditions: the caller has already validated `target` against the
52
+ * domain allowlist; this function does not re-check it.
53
+ *
54
+ * Implementation: we stand up a short-lived https.Server on a unix socket
55
+ * and pipe the client socket through it. The Node-idiomatic alternative —
56
+ * feeding the raw socket to a non-listening server via
57
+ * `emit('connection', socket)` — is not implemented by Bun's https.Server,
58
+ * and SRT runs under both runtimes. A per-connection server lets the
59
+ * request handler close over `target` (which carries the originally-
60
+ * requested host:port) without socket-keyed lookups.
61
+ */
62
+ export declare function terminateAndForward(ca: MitmCA, filterRequest: FilterRequestCallback | undefined, mutateHeaders: MutateForwardedHeaders | undefined, socket: Duplex, head: Buffer, target: TerminateTarget): void;
63
+ //# sourceMappingURL=tls-terminate-proxy.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"tls-terminate-proxy.d.ts","sourceRoot":"","sources":["../../src/sandbox/tls-terminate-proxy.ts"],"names":[],"mappings":"AAAA;;;;;;;;;GASG;AAcH,OAAO,KAAK,EAAE,MAAM,EAAY,MAAM,aAAa,CAAA;AAEnD,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,cAAc,CAAA;AAC1C,OAAO,EAEL,KAAK,qBAAqB,EAC1B,KAAK,sBAAsB,EAC5B,MAAM,qBAAqB,CAAA;AAE5B,OAAO,EAKL,KAAK,mBAAmB,EACzB,MAAM,mBAAmB,CAAA;AAG1B;;;;;;;;;;;;;GAaG;AACH,wBAAgB,oBAAoB,CAAC,GAAG,EAAE,MAAM,GAAG,OAAO,CAIzD;AAcD,wBAAgB,kBAAkB,CAChC,MAAM,EAAE,MAAM,EACd,IAAI,EAAE,MAAM,GACX,OAAO,CAAC;IAAE,KAAK,EAAE,OAAO,CAAC;IAAC,IAAI,EAAE,MAAM,CAAA;CAAE,CAAC,CA8B3C;AAED,MAAM,MAAM,eAAe,GAAG;IAC5B,QAAQ,EAAE,MAAM,CAAA;IAChB,IAAI,EAAE,MAAM,CAAA;IACZ;;;;OAIG;IACH,UAAU,CAAC,EAAE,MAAM,GAAG,MAAM,GAAG,KAAK,CAAC,MAAM,GAAG,MAAM,CAAC,CAAA;IACrD,oEAAoE;IACpE,WAAW,CAAC,EAAE,mBAAmB,CAAA;CAClC,CAAA;AAED;;;;;;;;;;;;;;;GAeG;AACH,wBAAgB,mBAAmB,CACjC,EAAE,EAAE,MAAM,EACV,aAAa,EAAE,qBAAqB,GAAG,SAAS,EAChD,aAAa,EAAE,sBAAsB,GAAG,SAAS,EACjD,MAAM,EAAE,MAAM,EACd,IAAI,EAAE,MAAM,EACZ,MAAM,EAAE,eAAe,GACtB,IAAI,CAqGN"}
@@ -0,0 +1,332 @@
1
+ /**
2
+ * In-process TLS termination for HTTPS traffic through the forward proxy.
3
+ *
4
+ * When a MitmCA is configured, the forward proxy hands CONNECT requests here
5
+ * instead of opening an opaque byte tunnel. We terminate the client's TLS
6
+ * with a per-host leaf cert (see mitm-leaf.ts), parse the decrypted stream
7
+ * as HTTP/1.1, and re-issue each request upstream over a real TLS
8
+ * connection. The optional `filterRequest` callback runs on each parsed
9
+ * request before it is forwarded.
10
+ */
11
+ import { createServer as createHttpsServer, request as httpsRequest, } from 'node:https';
12
+ import { request as httpRequest, } from 'node:http';
13
+ import { connect, isIP } from 'node:net';
14
+ import { connect as tlsConnect } from 'node:tls';
15
+ import { unlink } from 'node:fs';
16
+ import { logForDebugging } from '../utils/debug.js';
17
+ import { decideAndRespond, } from './request-filter.js';
18
+ import { mintLeafCert, secureContextFor } from './mitm-leaf.js';
19
+ import { connectViaParentProxy, selectParentProxyUrl, shouldBypassParentProxy, stripHopByHop, } from './parent-proxy.js';
20
+ import { createPrivateUnixSocketPath } from './sandbox-temp-dir.js';
21
+ /**
22
+ * True if `buf` starts with a TLS Handshake record header.
23
+ *
24
+ * Three bytes: content type 0x16 (Handshake) + legacy_record_version
25
+ * 0x03,0x00–0x03. RFC 8446 §5.1 froze the record-layer version (TLS 1.3+
26
+ * negotiate via the supported_versions extension, the wire header stays
27
+ * ≤0x0303), so this holds for current and future TLS. Same predicate as
28
+ * mitmproxy `starts_like_tls_record`; nginx `ssl_preread` routes on byte 0
29
+ * alone and HAProxy `req.ssl_hello_type` reads 9 bytes to also extract the
30
+ * handshake type — 3 is the established middle ground for "is this TLS".
31
+ *
32
+ * Routing heuristic, not a security check: a non-TLS stream that happens to
33
+ * start 16 03 0x is handed to the TLS server, which then rejects it properly.
34
+ */
35
+ export function looksLikeClientHello(buf) {
36
+ return (buf.length >= 3 && buf[0] === 0x16 && buf[1] === 0x03 && buf[2] <= 0x03);
37
+ }
38
+ /**
39
+ * Wait for the client's first post-CONNECT bytes and report whether they look
40
+ * like a TLS ClientHello. The caller must already have written the
41
+ * `200 Connection Established` line — clients don't send until they see it.
42
+ *
43
+ * Any bytes consumed here are returned in `.head` so the caller can forward
44
+ * them to whichever downstream (terminate or opaque tunnel) it picks. The
45
+ * socket is left paused so further bytes buffer until the downstream
46
+ * `pipe()` resumes it.
47
+ */
48
+ const PEEK_TIMEOUT_MS = 10000;
49
+ export function peekForClientHello(socket, head) {
50
+ if (head.length >= 3) {
51
+ return Promise.resolve({ isTLS: looksLikeClientHello(head), head });
52
+ }
53
+ return new Promise(resolve => {
54
+ let buf = head;
55
+ let settled = false;
56
+ const done = () => {
57
+ if (settled)
58
+ return;
59
+ settled = true;
60
+ clearTimeout(timer);
61
+ socket.removeListener('data', onData);
62
+ socket.removeListener('end', done);
63
+ socket.removeListener('close', done);
64
+ resolve({ isTLS: looksLikeClientHello(buf), head: buf });
65
+ };
66
+ const timer = setTimeout(done, PEEK_TIMEOUT_MS);
67
+ timer.unref?.();
68
+ const onData = (chunk) => {
69
+ // Pause synchronously so anything after this chunk buffers for the
70
+ // downstream pipe() rather than being dropped in flowing mode.
71
+ socket.pause();
72
+ buf = buf.length ? Buffer.concat([buf, chunk]) : chunk;
73
+ if (buf.length >= 3)
74
+ return done();
75
+ socket.resume();
76
+ };
77
+ socket.on('data', onData);
78
+ socket.once('end', done);
79
+ socket.once('close', done);
80
+ });
81
+ }
82
+ /**
83
+ * Terminate the client's TLS on `socket`, parse the decrypted HTTP/1.1
84
+ * stream, and forward each request to `target` over a fresh upstream TLS
85
+ * connection.
86
+ *
87
+ * Preconditions: the caller has already validated `target` against the
88
+ * domain allowlist; this function does not re-check it.
89
+ *
90
+ * Implementation: we stand up a short-lived https.Server on a unix socket
91
+ * and pipe the client socket through it. The Node-idiomatic alternative —
92
+ * feeding the raw socket to a non-listening server via
93
+ * `emit('connection', socket)` — is not implemented by Bun's https.Server,
94
+ * and SRT runs under both runtimes. A per-connection server lets the
95
+ * request handler close over `target` (which carries the originally-
96
+ * requested host:port) without socket-keyed lookups.
97
+ */
98
+ export function terminateAndForward(ca, filterRequest, mutateHeaders, socket, head, target) {
99
+ // ALPN advertises HTTP/1.1 only — terminating HTTP/2 would require a frame
100
+ // parser; clients negotiate down. Always pin to target.hostname (ignoring
101
+ // arbitrary client SNI) so a sandboxed process cannot mint certs for
102
+ // unallowed domains or exhaust host memory via random SNI names.
103
+ const baseLeaf = mintLeafCert(ca, target.hostname);
104
+ const inner = createHttpsServer({
105
+ ALPNProtocols: ['http/1.1'],
106
+ cert: baseLeaf.certPem,
107
+ key: baseLeaf.keyPem,
108
+ SNICallback: (_servername, cb) => {
109
+ try {
110
+ cb(null, secureContextFor(ca, target.hostname));
111
+ }
112
+ catch (err) {
113
+ cb(err);
114
+ }
115
+ },
116
+ });
117
+ inner.on('request', (req, res) => {
118
+ void forwardUpstream(filterRequest, mutateHeaders, req, res, target).catch(err => {
119
+ logForDebugging(`[tls-terminate] unexpected forward error: ${err.message}`, { level: 'error' });
120
+ if (!res.headersSent) {
121
+ res.writeHead(500, { 'Content-Type': 'text/plain' });
122
+ res.end('Internal Server Error');
123
+ }
124
+ else {
125
+ res.destroy();
126
+ }
127
+ });
128
+ });
129
+ inner.on('tlsClientError', (err, sock) => {
130
+ logForDebugging(`[tls-terminate] client TLS error for ${target.hostname}: ${err.message}`, { level: 'error' });
131
+ sock.destroy();
132
+ });
133
+ inner.on('upgrade', (_req, sock) => {
134
+ // WebSocket / non-HTTP over TLS — out of scope for now.
135
+ logForDebugging('[tls-terminate] upgrade request refused', {
136
+ level: 'warn',
137
+ });
138
+ sock.destroy();
139
+ });
140
+ const sockPath = createPrivateUnixSocketPath('tt');
141
+ let cleaned = false;
142
+ const cleanup = () => {
143
+ if (cleaned)
144
+ return;
145
+ cleaned = true;
146
+ inner.close();
147
+ unlink(sockPath, () => { });
148
+ };
149
+ socket.once('close', cleanup);
150
+ inner.on('error', err => {
151
+ logForDebugging(`[tls-terminate] inner server listen failed: ${err.message}`, { level: 'error' });
152
+ socket.destroy();
153
+ cleanup();
154
+ });
155
+ inner.listen(sockPath, () => {
156
+ if (socket.destroyed) {
157
+ cleanup();
158
+ return;
159
+ }
160
+ const loop = connect({ path: sockPath });
161
+ loop.on('error', err => {
162
+ logForDebugging(`[tls-terminate] inner loopback failed: ${err.message}`, {
163
+ level: 'error',
164
+ });
165
+ socket.destroy();
166
+ cleanup();
167
+ });
168
+ loop.once('connect', () => {
169
+ // Single-use listener: close & unlink immediately once the loopback
170
+ // connection is established; active sockets continue until close.
171
+ cleanup();
172
+ // The caller wrote `200 Connection Established` before sniffing for the
173
+ // ClientHello; `head` holds whatever the sniff consumed.
174
+ if (head.length)
175
+ loop.write(head);
176
+ socket.pipe(loop);
177
+ loop.pipe(socket);
178
+ });
179
+ socket.on('error', () => loop.destroy());
180
+ socket.once('close', () => {
181
+ loop.destroy();
182
+ cleanup();
183
+ });
184
+ loop.once('close', () => {
185
+ socket.destroy();
186
+ cleanup();
187
+ });
188
+ });
189
+ inner.unref();
190
+ }
191
+ async function forwardUpstream(filterRequest, mutateHeaders, req, res, target) {
192
+ const path = originFormPath(req.url);
193
+ if (path === null) {
194
+ res.writeHead(400, { 'Content-Type': 'text/plain' });
195
+ res.end('Bad Request');
196
+ return;
197
+ }
198
+ const hostBracketed = isIP(target.hostname) === 6 ? `[${target.hostname}]` : target.hostname;
199
+ const host = target.port === 443 ? hostBracketed : `${hostBracketed}:${target.port}`;
200
+ let body = req;
201
+ if (filterRequest) {
202
+ const ac = new AbortController();
203
+ res.once('close', () => ac.abort());
204
+ // Always derive the URL from the verified CONNECT target so
205
+ // filterRequest sees the actual upstream destination.
206
+ const out = await decideAndRespond(filterRequest, req, res, `https://${host}${path}`, ac.signal);
207
+ if (out === null)
208
+ return;
209
+ body = out;
210
+ }
211
+ // Bun's https.request verifies the upstream cert against headers.host
212
+ // verbatim (including ":port"), which never matches a SAN. Drop the host
213
+ // header and let the runtime derive it from {host, port} — same wire value,
214
+ // correct verification under both Node and Bun.
215
+ const fwdHeaders = stripHopByHop(req.headers);
216
+ delete fwdHeaders.host;
217
+ // Header mutation runs after the allow decision and before the outbound
218
+ // request. The upstream TLS handshake completes before any HTTP bytes are
219
+ // written, so mutated headers never reach an unverified server.
220
+ mutateHeaders?.(fwdHeaders, target.hostname);
221
+ const parentUrl = target.parentProxy &&
222
+ !shouldBypassParentProxy(target.parentProxy, target.hostname)
223
+ ? selectParentProxyUrl(target.parentProxy, { isHttps: true })
224
+ : undefined;
225
+ let upstream;
226
+ if (parentUrl) {
227
+ let tunnelSocket;
228
+ try {
229
+ tunnelSocket = await connectViaParentProxy(parentUrl, target.hostname, target.port);
230
+ }
231
+ catch (err) {
232
+ logForDebugging(`[tls-terminate] parent proxy connect to ${target.hostname}:${target.port} failed: ${err.message}`, { level: 'error' });
233
+ if (!res.headersSent) {
234
+ res.writeHead(502, { 'Content-Type': 'text/plain' });
235
+ res.end('Bad Gateway');
236
+ }
237
+ else {
238
+ res.destroy();
239
+ }
240
+ return;
241
+ }
242
+ if (res.destroyed) {
243
+ tunnelSocket.destroy();
244
+ return;
245
+ }
246
+ const tlsSocket = await new Promise((resolve, reject) => {
247
+ const ts = tlsConnect({
248
+ socket: tunnelSocket,
249
+ ...(isIP(target.hostname) ? {} : { servername: target.hostname }),
250
+ ...(target.upstreamCA ? { ca: target.upstreamCA } : {}),
251
+ });
252
+ const onErr = (err) => {
253
+ ts.destroy();
254
+ tunnelSocket.destroy();
255
+ reject(err);
256
+ };
257
+ ts.once('error', onErr);
258
+ ts.once('secureConnect', () => {
259
+ ts.removeListener('error', onErr);
260
+ resolve(ts);
261
+ });
262
+ }).catch(err => {
263
+ logForDebugging(`[tls-terminate] upstream TLS over parent proxy failed: ${err.message}`, { level: 'error' });
264
+ if (!res.headersSent) {
265
+ res.writeHead(502, { 'Content-Type': 'text/plain' });
266
+ res.end('Bad Gateway');
267
+ }
268
+ else {
269
+ res.destroy();
270
+ }
271
+ return null;
272
+ });
273
+ if (!tlsSocket)
274
+ return;
275
+ fwdHeaders.host = host;
276
+ upstream = httpRequest({
277
+ createConnection: () => tlsSocket,
278
+ path,
279
+ method: req.method,
280
+ headers: fwdHeaders,
281
+ agent: false,
282
+ }, upRes => {
283
+ res.writeHead(upRes.statusCode ?? 502, stripHopByHop(upRes.headers));
284
+ upRes.pipe(res);
285
+ });
286
+ }
287
+ else {
288
+ upstream = httpsRequest({
289
+ host: target.hostname,
290
+ port: target.port,
291
+ path,
292
+ method: req.method,
293
+ headers: fwdHeaders,
294
+ ...(isIP(target.hostname) ? {} : { servername: target.hostname }),
295
+ ...(target.upstreamCA ? { ca: target.upstreamCA } : {}),
296
+ agent: false,
297
+ }, upRes => {
298
+ res.writeHead(upRes.statusCode ?? 502, stripHopByHop(upRes.headers));
299
+ upRes.pipe(res);
300
+ });
301
+ }
302
+ upstream.on('error', err => {
303
+ logForDebugging(`[tls-terminate] upstream ${target.hostname}:${target.port} failed: ${err.message}`, { level: 'error' });
304
+ if (!res.headersSent) {
305
+ res.writeHead(502, { 'Content-Type': 'text/plain' });
306
+ res.end('Bad Gateway');
307
+ }
308
+ else {
309
+ res.destroy();
310
+ }
311
+ });
312
+ body.on('error', () => upstream.destroy());
313
+ res.on('close', () => upstream.destroy());
314
+ body.pipe(upstream);
315
+ }
316
+ function originFormPath(reqUrl) {
317
+ const raw = reqUrl ?? '/';
318
+ if (raw.startsWith('/'))
319
+ return raw;
320
+ if (raw === '*')
321
+ return '/';
322
+ try {
323
+ const u = new URL(raw);
324
+ if (u.protocol !== 'http:' && u.protocol !== 'https:')
325
+ return null;
326
+ return `${u.pathname}${u.search}` || '/';
327
+ }
328
+ catch {
329
+ return null;
330
+ }
331
+ }
332
+ //# sourceMappingURL=tls-terminate-proxy.js.map