@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,132 @@
1
+ /**
2
+ * Per-host leaf certificate minter for the in-process TLS-terminating proxy.
3
+ *
4
+ * Given a MitmCA (see mitm-ca.ts), mints a leaf certificate for a specific
5
+ * hostname on first use and caches it for the lifetime of that CA instance.
6
+ * The leaf is signed by the CA and carries SAN=DNS:<host> (or IP:<addr>),
7
+ * so a client that trusts the CA will accept it for that host.
8
+ */
9
+ import forge from 'node-forge';
10
+ import { isIP } from 'node:net';
11
+ import { createSecureContext } from 'node:tls';
12
+ import { logForDebugging } from '../utils/debug.js';
13
+ import { caSubjectKeyId, daysFromNow, randomSerial, signCertificateNative, } from './mitm-ca.js';
14
+ const { pki } = forge;
15
+ const MAX_LEAF_CACHE = 256;
16
+ function setBounded(map, key, value) {
17
+ if (map.has(key)) {
18
+ map.delete(key);
19
+ }
20
+ else if (map.size >= MAX_LEAF_CACHE) {
21
+ const oldest = map.keys().next().value;
22
+ if (oldest !== undefined)
23
+ map.delete(oldest);
24
+ }
25
+ map.set(key, value);
26
+ }
27
+ /**
28
+ * Mint (or return cached) an RSA-2048 leaf cert for `hostname`, signed by `ca`.
29
+ * The cache lives on `ca.leafCerts`.
30
+ */
31
+ export function mintLeafCert(ca, hostname) {
32
+ const cacheKey = hostname.toLowerCase();
33
+ const cached = ca.leafCerts.get(cacheKey);
34
+ if (cached) {
35
+ setBounded(ca.leafCerts, cacheKey, cached);
36
+ return cached;
37
+ }
38
+ const keys = pki.rsa.generateKeyPair(2048);
39
+ const cert = pki.createCertificate();
40
+ cert.publicKey = keys.publicKey;
41
+ cert.serialNumber = randomSerial();
42
+ const notBefore = daysFromNow(-1);
43
+ cert.validity.notBefore = notBefore;
44
+ cert.validity.notAfter = clampValidity(ca.cert, notBefore);
45
+ cert.setSubject([{ name: 'commonName', value: cacheKey }]);
46
+ cert.setIssuer(ca.cert.subject.attributes);
47
+ cert.setExtensions([
48
+ { name: 'basicConstraints', cA: false, critical: true },
49
+ {
50
+ name: 'keyUsage',
51
+ critical: true,
52
+ digitalSignature: true,
53
+ keyEncipherment: true,
54
+ },
55
+ { name: 'extKeyUsage', serverAuth: true },
56
+ { name: 'subjectAltName', altNames: [sanFor(cacheKey)] },
57
+ { name: 'subjectKeyIdentifier' },
58
+ // Python ≥3.13 enables ssl.VERIFY_X509_STRICT by default, which enforces
59
+ // RFC 5280's "AKI MUST be present on non-self-signed certs". curl/Go/Node
60
+ // don't enforce this, but requests/urllib3/httpx/google-auth all reject
61
+ // a leaf without AKI under 3.13. See caSubjectKeyId() in mitm-ca.ts for
62
+ // why we can't just pass the CA's stored SKI value through.
63
+ { name: 'authorityKeyIdentifier', keyIdentifier: caSubjectKeyId(ca.cert) },
64
+ // Schannel (Windows System32 curl, git's default backend, cargo) checks
65
+ // revocation on the LEAF and hard-fails CRYPT_E_NO_REVOCATION_CHECK when
66
+ // there's no CDP to consult. Point it at the empty CRL the proxy serves
67
+ // on 127.0.0.1 (see MitmCA.crlDer / http-proxy.ts) so the check resolves
68
+ // to "not revoked" instead of "unknown". node-forge encodes CDP with the
69
+ // same {altNames} shape as SAN; type 6 = uniformResourceIdentifier.
70
+ // OpenSSL-backed clients don't check CRLs by default, so a leaf minted
71
+ // before the port is bound (crlUrl unset) works everywhere except
72
+ // Schannel-with-revocation.
73
+ ...(ca.crlUrl
74
+ ? [
75
+ {
76
+ name: 'cRLDistributionPoints',
77
+ altNames: [{ type: 6, value: ca.crlUrl }],
78
+ },
79
+ ]
80
+ : []),
81
+ ]);
82
+ signCertificateNative(cert, ca.keyPem);
83
+ const leaf = {
84
+ certPem: pki.certificateToPem(cert) + ca.certPem,
85
+ keyPem: pki.privateKeyToPem(keys.privateKey),
86
+ };
87
+ setBounded(ca.leafCerts, cacheKey, leaf);
88
+ logForDebugging(`[mitm-leaf] minted RSA leaf for ${cacheKey}`);
89
+ return leaf;
90
+ }
91
+ /**
92
+ * Mint-or-cache a Node TLS SecureContext for `hostname`. Intended as the
93
+ * SNICallback target in the terminating proxy. The cache lives on
94
+ * `ca.secureContexts`.
95
+ */
96
+ export function secureContextFor(ca, hostname) {
97
+ const cacheKey = hostname.toLowerCase();
98
+ const cached = ca.secureContexts.get(cacheKey);
99
+ if (cached) {
100
+ setBounded(ca.secureContexts, cacheKey, cached);
101
+ return cached;
102
+ }
103
+ const { certPem, keyPem } = mintLeafCert(ca, cacheKey);
104
+ const ctx = createSecureContext({ cert: certPem, key: keyPem });
105
+ setBounded(ca.secureContexts, cacheKey, ctx);
106
+ return ctx;
107
+ }
108
+ function sanFor(hostname) {
109
+ // RFC 5280 GeneralName tags: 2 = dNSName, 7 = iPAddress.
110
+ return isIP(hostname) !== 0
111
+ ? { type: 7, ip: hostname }
112
+ : { type: 2, value: hostname };
113
+ }
114
+ /**
115
+ * Leaf validity capped at min(CA notAfter, notBefore+99d).
116
+ *
117
+ * 99d sits below every TLS cert validity ceiling we care about: the current
118
+ * (2026-03) CA/B baseline of 200d, the next step-down to 100d in 2027-03, the
119
+ * historical 398d public cap, and the macOS ~825d ceiling that trips
120
+ * errSecCertificateIsNotStandardsCompliant on user-installed roots. Leaves are
121
+ * re-minted per session, so we don't need the headroom.
122
+ *
123
+ * Anchored at notBefore — not now — because notBefore is backdated by 1 day,
124
+ * so `now+Nd` would produce an (N+1)-day span and lose a day of margin.
125
+ */
126
+ function clampValidity(caCert, notBefore) {
127
+ const caEnd = caCert.validity.notAfter;
128
+ const max = new Date(notBefore);
129
+ max.setDate(max.getDate() + 99);
130
+ return caEnd < max ? new Date(caEnd) : max;
131
+ }
132
+ //# sourceMappingURL=mitm-leaf.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"mitm-leaf.js","sourceRoot":"","sources":["../../src/sandbox/mitm-leaf.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AAEH,OAAO,KAAK,MAAM,YAAY,CAAA;AAC9B,OAAO,EAAE,IAAI,EAAE,MAAM,UAAU,CAAA;AAC/B,OAAO,EAAE,mBAAmB,EAAsB,MAAM,UAAU,CAAA;AAClE,OAAO,EAAE,eAAe,EAAE,MAAM,mBAAmB,CAAA;AACnD,OAAO,EACL,cAAc,EACd,WAAW,EACX,YA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AAK,CAAC;QACzB,CAAC,CAAC,EAAE,IAAI,EAAE,CAAC,EAAE,EAAE,EAAE,QAAQ,EAAE;QAC3B,CAAC,CAAC,EAAE,IAAI,EAAE,CAAC,EAAE,KAAK,EAAE,QAAQ,EAAE,CAAA;AAClC,CAAC;AAED;;;;;;;;;;;GAWG;AACH,SAAS,aAAa,CAAC,MAA6B,EAAE,SAAe;IACnE,MAAM,KAAK,GAAG,MAAM,CAAC,QAAQ,CAAC,QAAQ,CAAA;IACtC,MAAM,GAAG,GAAG,IAAI,IAAI,CAAC,SAAS,CAAC,CAAA;IAC/B,GAAG,CAAC,OAAO,CAAC,GAAG,CAAC,OAAO,EAAE,GAAG,EAAE,CAAC,CAAA;IAC/B,OAAO,KAAK,GAAG,GAAG,CAAC,CAAC,CAAC,IAAI,IAAI,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,GAAG,CAAA;AAC5C,CAAC"}
@@ -0,0 +1,59 @@
1
+ import { type Server, type Socket } from 'node:net';
2
+ import type { Server as HttpServer } from 'node:http';
3
+ export interface MuxProxyOptions {
4
+ /**
5
+ * The HTTP CONNECT/absolute-URI proxy. Must NOT already be listening;
6
+ * the mux owns its listen lifecycle (on a private unix socket on
7
+ * macOS/Linux, or a localhost TCP port on Windows).
8
+ */
9
+ httpServer: HttpServer;
10
+ /**
11
+ * Per-connection SOCKS entry point. The mux calls this with a socket
12
+ * whose peeked first byte has been `unshift()`ed back, so the handler
13
+ * sees the full SOCKS greeting starting at byte 0.
14
+ */
15
+ handleSocksConnection: (socket: Socket) => void;
16
+ /**
17
+ * How long to wait for the client's first byte before destroying the
18
+ * connection. Guards against connect-then-stall clients holding a slot.
19
+ */
20
+ firstByteTimeoutMs?: number;
21
+ /**
22
+ * Windows only: range the HTTP backend's TCP port must fall inside, so
23
+ * the WFP loopback permit covers the mux→backend hop. Ignored on other
24
+ * platforms (unix socket needs no port).
25
+ */
26
+ httpBackendPortRange?: readonly [number, number];
27
+ }
28
+ export interface MuxProxyServer {
29
+ /** The front-end TCP listener. Call `.listen()` on this. */
30
+ server: Server;
31
+ /** Bound front-end port, once listening. */
32
+ getPort(): number | undefined;
33
+ /**
34
+ * Start the HTTP backend listener (unix socket on macOS/Linux, localhost
35
+ * TCP on Windows). Must be awaited before the front-end `.listen()`s so
36
+ * an early HTTP connection never dispatches to an unbound backend.
37
+ * Returns the backend's TCP port on Windows (so the caller can exclude
38
+ * it when binding the front-end in the same range), or undefined on
39
+ * unix-socket platforms.
40
+ */
41
+ listenHttpBackend(): Promise<number | undefined>;
42
+ /** Tear down front-end, backend, and all open client sockets. */
43
+ close(): Promise<void>;
44
+ /** unref() both listeners so they don't keep the event loop alive. */
45
+ unref(): void;
46
+ }
47
+ /**
48
+ * Single-port proxy front-end that dispatches each connection to either the
49
+ * SOCKS handler or the HTTP proxy based on the first byte the client sends.
50
+ *
51
+ * The HTTP leg cannot use `httpServer.emit('connection', socket)` because
52
+ * Bun's `http.Server` does not implement that injection path (Node does).
53
+ * Instead the HTTP backend listens on a private endpoint — a unix socket on
54
+ * macOS/Linux, a localhost TCP port on Windows — and the mux pipes the
55
+ * client socket to it. SOCKS connections are handed directly to the
56
+ * library's per-connection entry, no extra hop.
57
+ */
58
+ export declare function createMuxProxyServer(opts: MuxProxyOptions): MuxProxyServer;
59
+ //# sourceMappingURL=mux-proxy.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"mux-proxy.d.ts","sourceRoot":"","sources":["../../src/sandbox/mux-proxy.ts"],"names":[],"mappings":"AAAA,OAAO,EAAyB,KAAK,MAAM,EAAE,KAAK,MAAM,EAAE,MAAM,UAAU,CAAA;AAC1E,OAAO,KAAK,EAAE,MAAM,IAAI,UAAU,EAAE,MAAM,WAAW,CAAA;AAkBrD,MAAM,WAAW,eAAe;IAC9B;;;;OAIG;IACH,UAAU,EAAE,UAAU,CAAA;IACtB;;;;OAIG;IACH,qBAAqB,EAAE,CAAC,MAAM,EAAE,MAAM,KAAK,IAAI,CAAA;IAC/C;;;OAGG;IACH,kBAAkB,CAAC,EAAE,MAAM,CAAA;IAC3B;;;;OAIG;IACH,oBAAoB,CAAC,EAAE,SAAS,CAAC,MAAM,EAAE,MAAM,CAAC,CAAA;CACjD;AAED,MAAM,WAAW,cAAc;IAC7B,4DAA4D;IAC5D,MAAM,EAAE,MAAM,CAAA;IACd,4CAA4C;IAC5C,OAAO,IAAI,MAAM,GAAG,SAAS,CAAA;IAC7B;;;;;;;OAOG;IACH,iBAAiB,IAAI,OAAO,CAAC,MAAM,GAAG,SAAS,CAAC,CAAA;IAChD,iEAAiE;IACjE,KAAK,IAAI,OAAO,CAAC,IAAI,CAAC,CAAA;IACtB,sEAAsE;IACtE,KAAK,IAAI,IAAI,CAAA;CACd;AAID;;;;;;;;;;GAUG;AACH,wBAAgB,oBAAoB,CAAC,IAAI,EAAE,eAAe,GAAG,cAAc,CAsJ1E"}
@@ -0,0 +1,161 @@
1
+ import { createServer, connect } from 'node:net';
2
+ import { unlink } from 'node:fs/promises';
3
+ import { logForDebugging } from '../utils/debug.js';
4
+ import { getPlatform } from '../utils/platform.js';
5
+ import { listenInRange } from './listen-in-range.js';
6
+ import { createPrivateUnixSocketPath } from './sandbox-temp-dir.js';
7
+ /**
8
+ * First-byte values that select the SOCKS handler. SOCKS5's greeting is
9
+ * `VER NMETHODS METHODS...` with VER=0x05; SOCKS4's CONNECT is
10
+ * `VN CD DSTPORT...` with VN=0x04. Everything else on this port is HTTP:
11
+ * request methods start with an ASCII uppercase letter (>= 0x41 'A'),
12
+ * h2-prior-knowledge starts `PRI ` (0x50), and a stray TLS ClientHello
13
+ * starts 0x16 — none of which collide with 0x04/0x05. A one-byte peek is
14
+ * therefore an unambiguous discriminator.
15
+ */
16
+ const SOCKS_FIRST_BYTES = new Set([0x04, 0x05]);
17
+ const DEFAULT_FIRST_BYTE_TIMEOUT_MS = 10000;
18
+ /**
19
+ * Single-port proxy front-end that dispatches each connection to either the
20
+ * SOCKS handler or the HTTP proxy based on the first byte the client sends.
21
+ *
22
+ * The HTTP leg cannot use `httpServer.emit('connection', socket)` because
23
+ * Bun's `http.Server` does not implement that injection path (Node does).
24
+ * Instead the HTTP backend listens on a private endpoint — a unix socket on
25
+ * macOS/Linux, a localhost TCP port on Windows — and the mux pipes the
26
+ * client socket to it. SOCKS connections are handed directly to the
27
+ * library's per-connection entry, no extra hop.
28
+ */
29
+ export function createMuxProxyServer(opts) {
30
+ const firstByteTimeoutMs = opts.firstByteTimeoutMs ?? DEFAULT_FIRST_BYTE_TIMEOUT_MS;
31
+ const isWindows = getPlatform() === 'windows';
32
+ // Where the HTTP backend listens. Exactly one of these is set after
33
+ // listenHttpBackend() resolves.
34
+ let backendSocketPath;
35
+ let backendTcpPort;
36
+ // Track every accepted client socket so close() can tear them down
37
+ // immediately rather than waiting for in-flight tunnels to drain.
38
+ const openSockets = new Set();
39
+ function dispatchHttp(client) {
40
+ if (backendSocketPath === undefined && backendTcpPort === undefined) {
41
+ // listenHttpBackend() must resolve before the front-end listens; this
42
+ // guard is defense-in-depth in case a future caller reorders them.
43
+ logForDebugging('mux: HTTP dispatch before backend bound; dropping', {
44
+ level: 'error',
45
+ });
46
+ client.destroy();
47
+ return;
48
+ }
49
+ const upstream = backendSocketPath
50
+ ? connect(backendSocketPath)
51
+ : connect(backendTcpPort, '127.0.0.1');
52
+ let connected = false;
53
+ upstream.once('connect', () => {
54
+ connected = true;
55
+ });
56
+ upstream.on('error', err => {
57
+ const code = err.code ?? 'ERR';
58
+ logForDebugging(`mux: HTTP backend dial failed: ${err.message}`, { level: 'error' });
59
+ if (!client.destroyed) {
60
+ if (connected) {
61
+ client.destroy();
62
+ }
63
+ else {
64
+ client.end(`HTTP/1.1 502 Bad Gateway\r\nConnection: close\r\n\r\n` +
65
+ `mux backend dial failed (${code})\n`);
66
+ }
67
+ }
68
+ });
69
+ client.on('error', () => upstream.destroy());
70
+ client.once('close', () => upstream.destroy());
71
+ upstream.once('close', () => client.destroy());
72
+ client.pipe(upstream);
73
+ upstream.pipe(client);
74
+ }
75
+ const server = createServer(client => {
76
+ openSockets.add(client);
77
+ client.on('error', err => logForDebugging(`mux: client socket error: ${err.message}`));
78
+ const timer = setTimeout(() => {
79
+ logForDebugging('mux: first-byte timeout; destroying connection');
80
+ client.destroy();
81
+ }, firstByteTimeoutMs);
82
+ // Don't let a pending sniff keep the process alive.
83
+ if (typeof timer.unref === 'function')
84
+ timer.unref();
85
+ client.once('close', () => {
86
+ clearTimeout(timer);
87
+ openSockets.delete(client);
88
+ });
89
+ client.once('readable', () => {
90
+ clearTimeout(timer);
91
+ const peek = client.read(1);
92
+ if (!peek || peek.length === 0) {
93
+ // EOF before any byte — client connected and closed.
94
+ client.destroy();
95
+ return;
96
+ }
97
+ client.unshift(peek);
98
+ if (SOCKS_FIRST_BYTES.has(peek[0])) {
99
+ opts.handleSocksConnection(client);
100
+ }
101
+ else {
102
+ dispatchHttp(client);
103
+ }
104
+ });
105
+ });
106
+ return {
107
+ server,
108
+ getPort() {
109
+ const addr = server.address();
110
+ return addr && typeof addr === 'object' ? addr.port : undefined;
111
+ },
112
+ async listenHttpBackend() {
113
+ if (!isWindows) {
114
+ const path = createPrivateUnixSocketPath('mux');
115
+ // A prior process with the same PID may have crashed without
116
+ // unlinking; clear any stale file so listen() doesn't EADDRINUSE.
117
+ await unlink(path).catch(() => { });
118
+ await new Promise((resolve, reject) => {
119
+ opts.httpServer.once('error', reject);
120
+ opts.httpServer.listen(path, () => {
121
+ opts.httpServer.removeListener('error', reject);
122
+ resolve();
123
+ });
124
+ });
125
+ backendSocketPath = path;
126
+ logForDebugging(`mux: HTTP backend listening on ${path}`);
127
+ return undefined;
128
+ }
129
+ // Windows: AF_UNIX support under Bun is unverified, so the backend
130
+ // listens on a localhost TCP port inside the WFP-permitted range.
131
+ // The mux→backend hop originates from the parent process (not the
132
+ // sandboxed child), so WFP doesn't strictly require it; staying in
133
+ // range just keeps the port surface predictable.
134
+ await listenInRange(opts.httpServer, p => opts.httpServer.listen(p, '127.0.0.1'), opts.httpBackendPortRange, new Set());
135
+ const addr = opts.httpServer.address();
136
+ backendTcpPort = addr && typeof addr === 'object' ? addr.port : undefined;
137
+ logForDebugging(`mux: HTTP backend listening on 127.0.0.1:${backendTcpPort}`);
138
+ return backendTcpPort;
139
+ },
140
+ async close() {
141
+ for (const s of openSockets)
142
+ s.destroy();
143
+ openSockets.clear();
144
+ await new Promise(resolve => server.close(() => resolve()));
145
+ // The mux owns httpServer's listen lifecycle, so it owns close too.
146
+ // sandbox-manager.reset() additionally calls forceCloseHttpServer()
147
+ // for closeAllConnections() semantics; double-close is a no-op.
148
+ await new Promise(resolve => opts.httpServer.close(() => resolve()));
149
+ if (backendSocketPath) {
150
+ await unlink(backendSocketPath).catch(() => { });
151
+ backendSocketPath = undefined;
152
+ }
153
+ backendTcpPort = undefined;
154
+ },
155
+ unref() {
156
+ server.unref();
157
+ opts.httpServer.unref();
158
+ },
159
+ };
160
+ }
161
+ //# sourceMappingURL=mux-proxy.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"mux-proxy.js","sourceRoot":"","sources":["../../src/sandbox/mux-proxy.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,YAAY,EAAE,OAAO,EAA4B,MAAM,UAAU,CAAA;AAE1E,OAAO,EAAE,MAAM,EAAE,MAAM,kBAAkB,CAAA;AACzC,OAAO,EAAE,eAAe,EAAE,MAAM,mBAAmB,CAAA;AACnD,OAAO,EAAE,WAAW,EAAE,MAAM,sBAAsB,CAAA;AAClD,OAAO,EAAE,aAAa,EAAE,MAAM,sBAAsB,CAAA;AACpD,OAAO,EAAE,2BAA2B,EAAE,MAAM,uBAAuB,CAAA;AAEnE;;;;;;;;GAQG;AACH,MAAM,iBAAiB,GAAG,IAAI,GAAG,CAAC,CAAC,IAAI,EAAE,IAAI,CAAC,CAAC,CAAA;AAgD/C,MAAM,6BAA6B,GAAG,KAAM,CAAA;AAE5C;;;;;;;;;;GAUG;AACH,MAAM,UAAU,oBAAoB,CAAC,IAAqB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AC;gBACtB,MAAM,MAAM,CAAC,iBAAiB,CAAC,CAAC,KAAK,CAAC,GAAG,EAAE,GAAE,CAAC,CAAC,CAAA;gBAC/C,iBAAiB,GAAG,SAAS,CAAA;YAC/B,CAAC;YACD,cAAc,GAAG,SAAS,CAAA;QAC5B,CAAC;QACD,KAAK;YACH,MAAM,CAAC,KAAK,EAAE,CAAA;YACd,IAAI,CAAC,UAAU,CAAC,KAAK,EAAE,CAAA;QACzB,CAAC;KACF,CAAA;AACH,CAAC"}
@@ -0,0 +1,118 @@
1
+ /**
2
+ * Parent/upstream HTTP proxy support.
3
+ *
4
+ * When SRT runs in an environment that requires an HTTP proxy for outbound
5
+ * internet access (e.g. inside a VM on a host behind a corporate proxy),
6
+ * SRT's own proxies must chain through that upstream rather than connecting
7
+ * directly.
8
+ *
9
+ * This module provides:
10
+ * - config resolution (explicit config -> HTTP_PROXY/HTTPS_PROXY/NO_PROXY env)
11
+ * - NO_PROXY matching (hostname suffix + CIDR via net.BlockList). Follows
12
+ * golang.org/x/net/http/httpproxy semantics for suffix matching. Note:
13
+ * port-specific NO_PROXY entries (e.g. `host:8080`) are matched by host
14
+ * only; the port is ignored.
15
+ * - a generic CONNECT-tunnel helper that works over Unix socket, TCP, or TLS
16
+ */
17
+ import type { Socket } from 'node:net';
18
+ import type { IncomingHttpHeaders } from 'node:http';
19
+ import { BlockList } from 'node:net';
20
+ import { URL } from 'node:url';
21
+ import type { ParentProxyConfig } from './sandbox-config.js';
22
+ export interface ResolvedParentProxy {
23
+ httpUrl?: URL;
24
+ httpsUrl?: URL;
25
+ noProxy: NoProxyRules;
26
+ }
27
+ interface NoProxyRules {
28
+ all: boolean;
29
+ suffixes: string[];
30
+ cidr: BlockList;
31
+ }
32
+ /**
33
+ * Resolve the parent proxy config, falling back to the SRT process's own
34
+ * environment. Note: SRT later overwrites HTTP_PROXY etc. in the *sandboxed
35
+ * child's* environment to point at itself — but process.env here reflects the
36
+ * environment SRT itself was launched with, which is what we want.
37
+ */
38
+ export declare function resolveParentProxy(cfg?: ParentProxyConfig): ResolvedParentProxy | undefined;
39
+ /**
40
+ * Returns true if the given host should bypass the parent proxy and connect
41
+ * directly. Always bypasses loopback.
42
+ *
43
+ * NB: the port is not consulted. NO_PROXY entries of the form `host:port` are
44
+ * matched by host only (the port suffix is stripped during parsing).
45
+ */
46
+ export declare function shouldBypassParentProxy(resolved: ResolvedParentProxy, host: string): boolean;
47
+ /**
48
+ * Pick which parent proxy URL to use for a given destination.
49
+ */
50
+ export declare function selectParentProxyUrl(resolved: ResolvedParentProxy, opts: {
51
+ isHttps: boolean;
52
+ }): URL | undefined;
53
+ export interface ConnectTunnelOptions {
54
+ /** Establish the transport to the proxy. */
55
+ dial(): Socket;
56
+ /** Fired when the transport is ready to write (e.g. 'connect'/'secureConnect'). */
57
+ readyEvent: 'connect' | 'secureConnect';
58
+ destHost: string;
59
+ destPort: number;
60
+ authHeader?: string;
61
+ timeoutMs?: number;
62
+ signal?: AbortSignal;
63
+ }
64
+ /**
65
+ * Generic CONNECT-tunnel: dial a proxy transport (unix/tcp/tls), send
66
+ * `CONNECT host:port`, wait for a 2xx, and resolve with the tunnelled socket.
67
+ * Validates destHost to prevent CRLF injection from untrusted callers.
68
+ */
69
+ export declare function openConnectTunnel(opts: ConnectTunnelOptions): Promise<Socket>;
70
+ /**
71
+ * Open a CONNECT tunnel through a parent HTTP(S) proxy specified by URL.
72
+ * Thin wrapper around openConnectTunnel that dials TCP or TLS based on the
73
+ * proxy URL scheme.
74
+ */
75
+ export declare function connectViaParentProxy(proxyUrl: URL, destHost: string, destPort: number, signal?: AbortSignal): Promise<Socket>;
76
+ export declare function proxyAuthHeader(proxyUrl: URL): string | undefined;
77
+ /**
78
+ * Strip hop-by-hop and proxy-specific headers before forwarding upstream.
79
+ * Also strips any headers named in the incoming `Connection` header, per
80
+ * RFC 7230 §6.1.
81
+ */
82
+ export declare function stripHopByHop(h: IncomingHttpHeaders): IncomingHttpHeaders;
83
+ /** Remove surrounding square brackets from an IPv6 literal. */
84
+ export declare function stripBrackets(host: string): string;
85
+ /** Redact userinfo from a URL for safe logging. */
86
+ export declare function redactUrl(u: URL | undefined): string;
87
+ /**
88
+ * Hostname validation: accepts DNS names and IP literals (without zone IDs).
89
+ * Primary purpose is to block control characters (CRLF injection, null-byte
90
+ * DNS truncation) and zone-identifier allowlist bypasses from reaching the
91
+ * wire or the allowlist matcher.
92
+ *
93
+ * IPv6 zone IDs (`fe80::1%eth0`) are rejected because `isIP` accepts a very
94
+ * permissive zone charset including dots — `::ffff:1.2.3.4%x.allowed.com`
95
+ * would pass `isIP`, pass a `.endsWith('.allowed.com')` wildcard check, and
96
+ * then connect to 1.2.3.4 when the OS discards the bogus scope.
97
+ */
98
+ export declare function isValidHost(h: string): boolean;
99
+ /**
100
+ * Canonicalize a host string via the WHATWG URL parser so that string
101
+ * comparisons in the allowlist agree with what `net.connect()`/`getaddrinfo()`
102
+ * will actually dial. This normalizes:
103
+ * - inet_aton shorthand (`127.1` → `127.0.0.1`, `2130706433` → `127.0.0.1`)
104
+ * - hex/octal octets (`0x7f.0.0.1` → `127.0.0.1`)
105
+ * - IPv6 compression (`0:0:0:0:0:0:0:1` → `::1`)
106
+ * - trailing dots, case, brackets
107
+ *
108
+ * Returns undefined if the input is not a valid URL host.
109
+ */
110
+ export declare function canonicalizeHost(h: string): string | undefined;
111
+ /**
112
+ * Dial `host:port` directly with a bounded timeout. Shared by the HTTP and
113
+ * SOCKS direct-connect paths so they get the same timeout behaviour as the
114
+ * CONNECT-tunnelled paths.
115
+ */
116
+ export declare function dialDirect(host: string, port: number, timeoutMs?: number, signal?: AbortSignal): Promise<Socket>;
117
+ export {};
118
+ //# sourceMappingURL=parent-proxy.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"parent-proxy.d.ts","sourceRoot":"","sources":["../../src/sandbox/parent-proxy.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;GAeG;AAEH,OAAO,KAAK,EAAE,MAAM,EA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