barebox 0.1.0 → 0.2.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.
- package/CHANGELOG.md +37 -0
- package/README.md +152 -7
- package/barebox.context.md +76 -0
- package/package.json +40 -3
- package/primitives.json +23 -0
- package/src/certs.js +108 -0
- package/src/cli.js +48 -0
- package/src/holds.js +164 -0
- package/src/index.js +3 -0
- package/src/launcher.js +173 -0
- package/src/proxy.js +768 -0
- package/types/certs.d.ts +24 -0
- package/types/cli.d.ts +2 -0
- package/types/holds.d.ts +104 -0
- package/types/index.d.ts +2 -0
- package/types/launcher.d.ts +44 -0
- package/types/proxy.d.ts +244 -0
- package/.claude/remember/AGENT_RULES.md +0 -291
- package/docs/product/agent-sandbox-prd.md +0 -418
- package/docs/product/agent-sandbox.md +0 -218
- package/poc/m0/README.md +0 -20
- package/poc/m0/func-fx.txt +0 -15
- package/poc/m0/func-fy.txt +0 -15
- package/poc/m0/launch.sh +0 -43
- package/poc/m0/measure.js +0 -53
- package/poc/m0/measure.txt +0 -23
- package/poc/m0/proxy.js +0 -74
- package/poc/m0/proxy.log +0 -28
- package/poc/m0/red-mem.txt +0 -4
- package/poc/m0/red-proxy.log +0 -13
- package/poc/m0/redteam.sh +0 -118
- package/poc/m0/run-m0.sh +0 -136
package/src/proxy.js
ADDED
|
@@ -0,0 +1,768 @@
|
|
|
1
|
+
// Proxy: the front door. Terminates agent TLS with per-host certificates
|
|
2
|
+
// minted on demand, sees every request through a private stdlib http.Server
|
|
3
|
+
// (so HEAD, 204/304, chunked, keep-alive and slow upstreams just work),
|
|
4
|
+
// forwards with https/http.request, and optionally parks matching requests
|
|
5
|
+
// for a human decision. Identity = socket: each agent has its own unix
|
|
6
|
+
// listener, and every log line and hold names the agent, never `c<n>`.
|
|
7
|
+
//
|
|
8
|
+
// Timeout shape: the client idle clock is the server's keep-alive timeout —
|
|
9
|
+
// by construction it only ticks when no request is in flight. The upstream
|
|
10
|
+
// response gets its own much longer clock.
|
|
11
|
+
import net from 'node:net';
|
|
12
|
+
import tls from 'node:tls';
|
|
13
|
+
import http from 'node:http';
|
|
14
|
+
import https from 'node:https';
|
|
15
|
+
import fs from 'node:fs';
|
|
16
|
+
import os from 'node:os';
|
|
17
|
+
import path from 'node:path';
|
|
18
|
+
import { lookup as dnsLookup } from 'node:dns/promises';
|
|
19
|
+
import { ensureCA, certFor } from './certs.js';
|
|
20
|
+
import { createHolds } from './holds.js';
|
|
21
|
+
|
|
22
|
+
const AGENT = Symbol('agent');
|
|
23
|
+
const SECURE = Symbol('secure');
|
|
24
|
+
const IP_RE = /^\d+\.\d+\.\d+\.\d+$/;
|
|
25
|
+
const HOST_RE = /^[A-Za-z0-9.-]+$/;
|
|
26
|
+
const AGENT_RE = /^[a-z0-9][a-z0-9-]{0,31}$/;
|
|
27
|
+
// Linux sun_path: 108 bytes including the NUL.
|
|
28
|
+
const MAX_SOCK_PATH = 107;
|
|
29
|
+
// Hop-by-hop headers must not be forwarded: node's HTTP stack re-frames.
|
|
30
|
+
const HOP_REQ = new Set(['proxy-connection', 'proxy-authorization']);
|
|
31
|
+
const HOP_RESP = new Set(['connection', 'keep-alive', 'proxy-authenticate',
|
|
32
|
+
'proxy-authorization', 'te', 'trailer', 'transfer-encoding', 'upgrade']);
|
|
33
|
+
|
|
34
|
+
// Secrets never land in the audit log verbatim: Authorization-style header
|
|
35
|
+
// values are replaced with a fixed marker before an entry is written. The
|
|
36
|
+
// user's `redact` hook runs after this scrubbing, so it sees (and further
|
|
37
|
+
// shapes) an already-safe entry. Bodies stay logged as-is.
|
|
38
|
+
const REDACTED = '[redacted]';
|
|
39
|
+
const SENSITIVE_HEADERS = new Set(['authorization', 'proxy-authorization']);
|
|
40
|
+
|
|
41
|
+
/**
|
|
42
|
+
* Copy a log entry with sensitive header values replaced by `[redacted]`.
|
|
43
|
+
* The caller's headers object is never mutated.
|
|
44
|
+
*
|
|
45
|
+
* @param {Record<string, unknown>} entry log entry about to be written
|
|
46
|
+
* @returns {Record<string, unknown>} entry with secrets scrubbed
|
|
47
|
+
*/
|
|
48
|
+
function scrubSecrets(entry) {
|
|
49
|
+
const h = entry['headers'];
|
|
50
|
+
if (!h || typeof h !== 'object') return entry;
|
|
51
|
+
const src = /** @type {Record<string, unknown>} */ (h);
|
|
52
|
+
if (!Object.keys(src).some((k) => SENSITIVE_HEADERS.has(k.toLowerCase()))) return entry;
|
|
53
|
+
const headers = { ...src };
|
|
54
|
+
for (const k of Object.keys(headers)) {
|
|
55
|
+
if (SENSITIVE_HEADERS.has(k.toLowerCase())) headers[k] = REDACTED;
|
|
56
|
+
}
|
|
57
|
+
return { ...entry, headers };
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
// --- upstream wall ---------------------------------------------------------
|
|
61
|
+
// Default-deny for loopback, link-local (incl. cloud metadata 169.254/16),
|
|
62
|
+
// the host's own addresses, and private LAN ranges (RFC 1918, CGNAT
|
|
63
|
+
// 100.64/10, IPv6 ULA fc00::/7). The check runs AFTER DNS resolution, so a
|
|
64
|
+
// hostname that resolves to 127.0.0.1 is denied exactly like the literal.
|
|
65
|
+
// Unresolvable names are denied too (fail closed, never 502-then-dial).
|
|
66
|
+
// Only `allowLoopback` (loopback + unspecified) or `allowUpstream(host, ip)`
|
|
67
|
+
// lets a denied destination through; only tests pass those. There is no
|
|
68
|
+
// allowPrivate flag: a private destination passes only via `allowUpstream`.
|
|
69
|
+
|
|
70
|
+
/** Strip brackets/scope, lowercase: one spelling per address. */
|
|
71
|
+
function normIp(ip) {
|
|
72
|
+
let s = String(ip || '').toLowerCase();
|
|
73
|
+
if (s.startsWith('[') && s.endsWith(']')) s = s.slice(1, -1);
|
|
74
|
+
const pct = s.indexOf('%');
|
|
75
|
+
if (pct >= 0) s = s.slice(0, pct);
|
|
76
|
+
return s;
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
/** Embedded IPv4 in `::ffff:1.2.3.4`, or null. */
|
|
80
|
+
function mappedV4(ip) {
|
|
81
|
+
const m = ip.match(/^(?:.*:)?(\d+\.\d+\.\d+\.\d+)$/);
|
|
82
|
+
return m && net.isIP(m[1]) === 4 ? m[1] : null;
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
function v4Parts(ip) {
|
|
86
|
+
return ip.split('.').map((p) => parseInt(p, 10));
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
/** This machine's own interface addresses, one spelling (see `normIp`). */
|
|
90
|
+
function localIps() {
|
|
91
|
+
const out = new Set();
|
|
92
|
+
let ifs = {};
|
|
93
|
+
// networkInterfaces() can throw where interfaces are hidden (a sandbox is
|
|
94
|
+
// exactly where the wall matters most): lose host-local, keep the rest.
|
|
95
|
+
try {
|
|
96
|
+
ifs = os.networkInterfaces();
|
|
97
|
+
} catch {
|
|
98
|
+
return out;
|
|
99
|
+
}
|
|
100
|
+
for (const addrs of Object.values(ifs)) {
|
|
101
|
+
for (const a of addrs ?? []) {
|
|
102
|
+
if (a && a.address) out.add(normIp(a.address));
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
return out;
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
/**
|
|
109
|
+
* Why `ip` (already resolved) is denied, or null when it may go through.
|
|
110
|
+
*
|
|
111
|
+
* @param {string} rawIp resolved destination IP
|
|
112
|
+
* @param {boolean} allowLoopback test-only opt-in for loopback + unspecified
|
|
113
|
+
* @returns {string|null} `loopback` / `unspecified` / `link-local` / `host-local` / `private`, or null
|
|
114
|
+
*/
|
|
115
|
+
export function denyReasonForIp(rawIp, allowLoopback) {
|
|
116
|
+
const ip = normIp(rawIp);
|
|
117
|
+
const v4 = mappedV4(ip) ?? (net.isIP(ip) === 4 ? ip : null);
|
|
118
|
+
if (v4) {
|
|
119
|
+
const [a, b] = v4Parts(v4);
|
|
120
|
+
if (a === 127) return allowLoopback ? null : 'loopback';
|
|
121
|
+
if (a === 0) return allowLoopback ? null : 'unspecified';
|
|
122
|
+
if (a === 169 && b === 254) return 'link-local';
|
|
123
|
+
if (a === 10) return 'private';
|
|
124
|
+
if (a === 172 && b >= 16 && b <= 31) return 'private';
|
|
125
|
+
if (a === 192 && b === 168) return 'private';
|
|
126
|
+
if (a === 100 && b >= 64 && b <= 127) return 'private';
|
|
127
|
+
if (localIps().has(v4)) return 'host-local';
|
|
128
|
+
return null;
|
|
129
|
+
}
|
|
130
|
+
if (net.isIP(ip) === 6) {
|
|
131
|
+
if (ip === '::1') return allowLoopback ? null : 'loopback';
|
|
132
|
+
if (ip === '::') return allowLoopback ? null : 'unspecified';
|
|
133
|
+
const first = parseInt(ip.split(':')[0] || '0', 16);
|
|
134
|
+
if (first >= 0xfe80 && first <= 0xfebf) return 'link-local';
|
|
135
|
+
if (first >= 0xfc00 && first <= 0xfdff) return 'private';
|
|
136
|
+
if (localIps().has(ip)) return 'host-local';
|
|
137
|
+
return null;
|
|
138
|
+
}
|
|
139
|
+
return null;
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
/**
|
|
143
|
+
* Resolve `host` to every IP for the wall. Literals need no DNS.
|
|
144
|
+
* Fail closed: anything that does not resolve is denied, never dialed.
|
|
145
|
+
*
|
|
146
|
+
* @param {string} host CONNECT/request hostname
|
|
147
|
+
* @param {(host: string) => Promise<string[] | string | null>} [stub] test-only DNS stub
|
|
148
|
+
* @returns {Promise<string[] | null>} all resolved IPs, or null when unresolvable
|
|
149
|
+
*/
|
|
150
|
+
async function resolveAllUpstream(host, stub) {
|
|
151
|
+
if (net.isIP(host)) return [host];
|
|
152
|
+
try {
|
|
153
|
+
if (typeof stub === 'function') {
|
|
154
|
+
const r = await stub(host);
|
|
155
|
+
if (!r) return null;
|
|
156
|
+
if (Array.isArray(r)) return r.length ? [...r] : null;
|
|
157
|
+
if (typeof r === 'string') return [r];
|
|
158
|
+
return null;
|
|
159
|
+
}
|
|
160
|
+
const all = await dnsLookup(host, { all: true });
|
|
161
|
+
if (!all || !all.length) return null;
|
|
162
|
+
return all.map((a) => a.address);
|
|
163
|
+
} catch {
|
|
164
|
+
return null;
|
|
165
|
+
}
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
/**
|
|
169
|
+
* The wall: resolve every answer, then default-deny loopback/link-local/
|
|
170
|
+
* host-local/private unless the test-only opt-ins allow it. Denies when ANY
|
|
171
|
+
* answer is walled, denies unresolvable names, and pins the first checked IP
|
|
172
|
+
* so the dial below cannot resolve the name a second time (no rebinding).
|
|
173
|
+
*
|
|
174
|
+
* @param {string} host CONNECT/request hostname
|
|
175
|
+
* @param {{ allowLoopback: boolean, allowUpstream: ((host: string, ip: string) => boolean) | null, resolveUpstream?: (host: string) => Promise<string[] | string | null> }} gate
|
|
176
|
+
* @returns {Promise<{ ok: true, ip: string } | { ok: false, ip: string, reason: string }>}
|
|
177
|
+
*/
|
|
178
|
+
async function checkUpstream(host, gate) {
|
|
179
|
+
const ips = await resolveAllUpstream(host, gate.resolveUpstream);
|
|
180
|
+
if (!ips || !ips.length) {
|
|
181
|
+
return { ok: false, ip: host, reason: `unresolvable upstream denied: ${host}` };
|
|
182
|
+
}
|
|
183
|
+
for (const ip of ips) {
|
|
184
|
+
if (typeof gate.allowUpstream === 'function') {
|
|
185
|
+
let pass = false;
|
|
186
|
+
try { pass = gate.allowUpstream(host, ip) === true; } catch { pass = false; }
|
|
187
|
+
if (pass) continue;
|
|
188
|
+
}
|
|
189
|
+
const kind = denyReasonForIp(ip, gate.allowLoopback);
|
|
190
|
+
if (kind) {
|
|
191
|
+
const where = ip === host ? host : `${host} (${ip})`;
|
|
192
|
+
return { ok: false, ip, reason: `${kind} upstream denied: ${where}` };
|
|
193
|
+
}
|
|
194
|
+
}
|
|
195
|
+
return { ok: true, ip: ips[0] };
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
/**
|
|
199
|
+
* Check an agent name before it reaches the filesystem.
|
|
200
|
+
*
|
|
201
|
+
* @param {string} name agent name
|
|
202
|
+
* @returns {void} throws on `../` and friends
|
|
203
|
+
*/
|
|
204
|
+
export function assertAgentName(name) {
|
|
205
|
+
if (!AGENT_RE.test(name || '')) {
|
|
206
|
+
throw new Error(`bad agent name ${JSON.stringify(name)}: must match ${AGENT_RE}`);
|
|
207
|
+
}
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
/**
|
|
211
|
+
* Resolve symlinks through the nearest existing ancestor: socket paths may
|
|
212
|
+
* not exist yet, so `realpathSync` on the full path would throw. Walks up
|
|
213
|
+
* to the first existing ancestor, resolves that, then re-attaches the rest.
|
|
214
|
+
*
|
|
215
|
+
* @param {string} p any path, existing or not
|
|
216
|
+
* @returns {string} the real (symlink-free) spelling of `p`
|
|
217
|
+
*/
|
|
218
|
+
export function realPathOf(p) {
|
|
219
|
+
const abs = path.resolve(p);
|
|
220
|
+
let cur = abs;
|
|
221
|
+
/** @type {string[]} */
|
|
222
|
+
const rest = [];
|
|
223
|
+
while (!fs.existsSync(cur)) {
|
|
224
|
+
const parent = path.dirname(cur);
|
|
225
|
+
if (parent === cur) break;
|
|
226
|
+
rest.unshift(path.basename(cur));
|
|
227
|
+
cur = parent;
|
|
228
|
+
}
|
|
229
|
+
const real = fs.realpathSync(cur);
|
|
230
|
+
return rest.length ? path.join(real, ...rest) : real;
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
/**
|
|
234
|
+
* The one path both sides agree on: the proxy listens here, the launcher
|
|
235
|
+
* binds it into the sandbox. This function is the single writer of the shape.
|
|
236
|
+
*
|
|
237
|
+
* @param {string} runtime runtime dir
|
|
238
|
+
* @param {string} name agent name
|
|
239
|
+
* @returns {string} `<runtime>/socks/<name>.sock`
|
|
240
|
+
*/
|
|
241
|
+
export function socketPathForAgent(runtime, name) {
|
|
242
|
+
assertAgentName(name);
|
|
243
|
+
const p = path.join(runtime, 'socks', `${name}.sock`);
|
|
244
|
+
if (p.length > MAX_SOCK_PATH) {
|
|
245
|
+
throw new Error(`agent socket path too long (${p.length} > ${MAX_SOCK_PATH}): ${p}`);
|
|
246
|
+
}
|
|
247
|
+
return p;
|
|
248
|
+
}
|
|
249
|
+
|
|
250
|
+
/**
|
|
251
|
+
* Options for {@link createProxy}.
|
|
252
|
+
*
|
|
253
|
+
* @typedef {object} ProxyOptions
|
|
254
|
+
* @property {string} logFile JSON-lines log path (`req`, `resp`, `deny`, `hold`, `decide`, `hold-abandoned`)
|
|
255
|
+
* @property {string} [certDir] dir for the CA + minted host certs (default `<runtime>/certs`).
|
|
256
|
+
* Must live inside `runtime` (compared via {@link realPathOf}, so symlinks
|
|
257
|
+
* cannot smuggle it out): anything else throws before any side effect.
|
|
258
|
+
* The CA private key lives here, and the sandbox bind-mounts only the
|
|
259
|
+
* runtime dir — an outside certDir would expose `ca.key` through the binds.
|
|
260
|
+
* @property {string} [runtime] runtime dir; required for `addAgent`, default parent of `certDir`
|
|
261
|
+
* @property {number} [port] opt-in TCP listener for tests, bound to 127.0.0.1 only (default: none)
|
|
262
|
+
* @property {string} [upstreamCa] extra PEM the proxy trusts for upstream TLS, on top of system roots
|
|
263
|
+
* @property {HoldOptions} [hold] hold queue config, or omit to forward everything
|
|
264
|
+
* @property {string|null} [controlSocket] unix socket path for `pending | approve | deny`.
|
|
265
|
+
* Must live inside `runtime` (compared via {@link realPathOf}, so symlinks
|
|
266
|
+
* cannot smuggle it out): anything else throws before any side effect.
|
|
267
|
+
* No default — omit it when no CLI decisions are needed.
|
|
268
|
+
* @property {number} [upstreamTimeoutMs] give up on an upstream response after this (default 120000)
|
|
269
|
+
* @property {boolean} [allowLoopback] TEST-ONLY opt-in: let loopback and unspecified
|
|
270
|
+
* destinations through (default false). Fixture servers listen on 127.0.0.1,
|
|
271
|
+
* so tests pass this; production never should.
|
|
272
|
+
* @property {(host: string, ip: string) => boolean} [allowUpstream] escape hatch,
|
|
273
|
+
* consulted after DNS with each resolved IP: return true to let through a
|
|
274
|
+
* destination the default wall would deny. Only tests use this.
|
|
275
|
+
* @property {(host: string) => Promise<string[] | string | null>} [resolveUpstream] TEST-ONLY
|
|
276
|
+
* DNS stub: replaces the wall's resolver so rebinding is testable. Production omits it.
|
|
277
|
+
* @property {number} [clientIdleMs] kill a client tunnel idle this long; never fires mid-request (default 60000)
|
|
278
|
+
* @property {number} [maxLogBody] log at most this many request-body bytes, then `truncated: true` (default 1048576)
|
|
279
|
+
* @property {(entry: Record<string, unknown>) => Record<string, unknown>} [redact] log redaction hook, applied after built-in secret scrubbing (default: identity)
|
|
280
|
+
*/
|
|
281
|
+
|
|
282
|
+
/**
|
|
283
|
+
* Hold queue options (the decision seam lives in holds.js).
|
|
284
|
+
*
|
|
285
|
+
* @typedef {object} HoldOptions
|
|
286
|
+
* @property {string} [match] path substring that parks a request (default decision)
|
|
287
|
+
* @property {import('./holds.js').ShouldHold} [shouldHold] decision function; overrides `match`
|
|
288
|
+
* @property {number|string} [timeoutMs] hold deadline in ms, or `'never'` (default 120000)
|
|
289
|
+
* @property {number} [maxBody] bodies over this are denied at the door, never queued (default 1048576)
|
|
290
|
+
*/
|
|
291
|
+
|
|
292
|
+
/**
|
|
293
|
+
* One upstream forwarding: buffered body (approve path) or live stream.
|
|
294
|
+
*
|
|
295
|
+
* @typedef {object} ForwardArgs
|
|
296
|
+
* @property {string} agent agent name (its socket)
|
|
297
|
+
* @property {string} method HTTP method
|
|
298
|
+
* @property {string} url full URL
|
|
299
|
+
* @property {Record<string, string | string[] | undefined>} headers
|
|
300
|
+
* @property {Buffer} [body] buffered body (approve path)
|
|
301
|
+
* @property {import('node:http').IncomingMessage} [stream] live body (direct path)
|
|
302
|
+
* @property {import('node:http').ServerResponse} cres parked or live client response
|
|
303
|
+
*/
|
|
304
|
+
|
|
305
|
+
/**
|
|
306
|
+
* Live proxy. Let `tsc` infer the shape; adopters import the name.
|
|
307
|
+
*
|
|
308
|
+
* @typedef {ReturnType<typeof createProxy>} Proxy
|
|
309
|
+
*/
|
|
310
|
+
|
|
311
|
+
/**
|
|
312
|
+
* Start the front-door proxy. Every request is logged with its method, URL,
|
|
313
|
+
* headers and body; bytes go upstream untouched. Requests the hold rule
|
|
314
|
+
* flags park for a human decision instead of forwarding.
|
|
315
|
+
*
|
|
316
|
+
* @param {ProxyOptions} opts
|
|
317
|
+
* @returns live proxy: `ready` resolves when listeners + CA are up; the shape is inferred, see `Proxy`
|
|
318
|
+
* @when Reach for this HARNESS-ONLY to run the front door: it terminates agent TLS, sees every request, and parks the ones a human must decide. It decides nothing itself; pair with the launcher for sandboxes and `sbx` for decisions.
|
|
319
|
+
* @fails Throws synchronously on a missing `logFile` (or neither `certDir` nor `runtime`). At runtime, dead upstreams, malformed input, over-cap and timed-out holds all become loud logged HTTP errors, never silence and never a crash. A second proxy on the same port rejects `ready`, never crashes the process.
|
|
320
|
+
* @example
|
|
321
|
+
* import { createProxy } from "barebox";
|
|
322
|
+
* const proxy = createProxy({ port: 0, certDir: "./certs", logFile: "./mitm.log" });
|
|
323
|
+
* const { port } = await proxy.ready;
|
|
324
|
+
* await proxy.close();
|
|
325
|
+
*/
|
|
326
|
+
export function createProxy(opts) {
|
|
327
|
+
const { logFile, certDir: certDirOpt, runtime: runtimeOpt, port = null,
|
|
328
|
+
upstreamCa = null, hold = null, controlSocket = null,
|
|
329
|
+
upstreamTimeoutMs = 120000, clientIdleMs = 60000,
|
|
330
|
+
allowLoopback = false, allowUpstream = null, resolveUpstream = null,
|
|
331
|
+
maxLogBody = 1048576, redact = (e) => e } = opts ?? {};
|
|
332
|
+
const gate = { allowLoopback, allowUpstream, resolveUpstream: resolveUpstream ?? undefined };
|
|
333
|
+
if (!logFile) throw new Error('createProxy: logFile is required');
|
|
334
|
+
const runtime = runtimeOpt ?? (certDirOpt ? path.dirname(path.resolve(certDirOpt)) : null);
|
|
335
|
+
const dirOpt = certDirOpt ?? (runtime ? path.join(runtime, 'certs') : null);
|
|
336
|
+
if (!dirOpt) throw new Error('createProxy: certDir or runtime is required');
|
|
337
|
+
// The control socket is the approve-payments capability: it must live
|
|
338
|
+
// inside the runtime dir (the launcher masks exactly that dir), compared
|
|
339
|
+
// on real paths so a symlink cannot smuggle it out. Fail closed here,
|
|
340
|
+
// before the log stream, CA read, or any listener exists.
|
|
341
|
+
if (controlSocket) {
|
|
342
|
+
if (!runtime) {
|
|
343
|
+
throw new Error(`createProxy: controlSocket must live inside the runtime, got ${controlSocket} with no runtime`);
|
|
344
|
+
}
|
|
345
|
+
const realRt = realPathOf(runtime);
|
|
346
|
+
const realCtl = realPathOf(controlSocket);
|
|
347
|
+
if (!realCtl.startsWith(realRt + path.sep)) {
|
|
348
|
+
throw new Error(`createProxy: controlSocket must live inside the runtime: ${realCtl} not under ${realRt}`);
|
|
349
|
+
}
|
|
350
|
+
}
|
|
351
|
+
// The CA private key lives in certDir, and the launcher masks exactly
|
|
352
|
+
// the runtime dir: a certDir outside it would expose ca.key through the
|
|
353
|
+
// read-only binds. Same containment rule as the control socket above —
|
|
354
|
+
// fail closed here, before the log stream, CA read, or any listener.
|
|
355
|
+
// The default `<runtime>/certs` passes trivially.
|
|
356
|
+
if (!runtime) {
|
|
357
|
+
throw new Error(`createProxy: certDir must live inside the runtime, got ${dirOpt} with no runtime`);
|
|
358
|
+
}
|
|
359
|
+
{
|
|
360
|
+
const realRt = realPathOf(runtime);
|
|
361
|
+
const realCerts = realPathOf(dirOpt);
|
|
362
|
+
if (!realCerts.startsWith(realRt + path.sep)) {
|
|
363
|
+
throw new Error(`createProxy: certDir must live inside the runtime: ${realCerts} not under ${realRt}`);
|
|
364
|
+
}
|
|
365
|
+
}
|
|
366
|
+
const certDir = dirOpt;
|
|
367
|
+
const holdMaxBody = hold?.maxBody ?? 1048576;
|
|
368
|
+
|
|
369
|
+
const logStream = fs.createWriteStream(logFile, { flags: 'a', mode: 0o600 });
|
|
370
|
+
const log = (o) => { logStream.write(JSON.stringify(redact(scrubSecrets(o))) + '\n'); };
|
|
371
|
+
let trust = null;
|
|
372
|
+
if (upstreamCa) {
|
|
373
|
+
let extra;
|
|
374
|
+
try { extra = fs.readFileSync(upstreamCa, 'utf8'); }
|
|
375
|
+
catch (e) { throw new Error(`createProxy: cannot read upstreamCa: ${e.message}`); }
|
|
376
|
+
trust = [...tls.rootCertificates, extra];
|
|
377
|
+
}
|
|
378
|
+
|
|
379
|
+
/** @type {Set<import('node:net').Socket>} */
|
|
380
|
+
const clients = new Set();
|
|
381
|
+
/** @type {Set<import('node:http').ClientRequest>} */
|
|
382
|
+
const upstreams = new Set();
|
|
383
|
+
const agentServers = new Map();
|
|
384
|
+
/** @type {import('node:net').Server|null} */
|
|
385
|
+
let tcp = null;
|
|
386
|
+
let closed = false;
|
|
387
|
+
|
|
388
|
+
const agentOf = (sock) => sock[AGENT] ?? 'tcp';
|
|
389
|
+
|
|
390
|
+
function denyRes(cres, code, note) {
|
|
391
|
+
const sock = cres.socket;
|
|
392
|
+
log({ ev: 'deny', agent: agentOf(sock), code, note });
|
|
393
|
+
try {
|
|
394
|
+
if (!cres.headersSent && !sock.destroyed) {
|
|
395
|
+
cres.writeHead(code, { 'content-type': 'text/plain', connection: 'close' });
|
|
396
|
+
}
|
|
397
|
+
if (!sock.destroyed) cres.end(`${note}\n`);
|
|
398
|
+
} catch {}
|
|
399
|
+
}
|
|
400
|
+
|
|
401
|
+
function denyRaw(sock, code, note) {
|
|
402
|
+
log({ ev: 'deny', agent: agentOf(sock), code, note });
|
|
403
|
+
if (sock.destroyed) return;
|
|
404
|
+
try { sock.end(`HTTP/1.1 ${code} ${note}\r\nContent-Type: text/plain\r\nConnection: close\r\n\r\n${note}\n`); }
|
|
405
|
+
catch {}
|
|
406
|
+
}
|
|
407
|
+
|
|
408
|
+
// Enforcement sits here (every forward, incl. the approve path) AND at
|
|
409
|
+
// the door (request handler + CONNECT): a parked hold is re-checked on
|
|
410
|
+
// approve, so a DNS change while parked cannot slip through.
|
|
411
|
+
/** @param {ForwardArgs} args */
|
|
412
|
+
async function forward({ agent, method, url, headers, body, stream, cres }) {
|
|
413
|
+
let u;
|
|
414
|
+
try {
|
|
415
|
+
u = new URL(url);
|
|
416
|
+
} catch {
|
|
417
|
+
denyRes(cres, 400, 'bad request target');
|
|
418
|
+
return;
|
|
419
|
+
}
|
|
420
|
+
const verdict = await checkUpstream(u.hostname, gate);
|
|
421
|
+
if (!verdict.ok) {
|
|
422
|
+
try { stream?.resume(); } catch {}
|
|
423
|
+
denyRes(cres, 403, verdict.reason);
|
|
424
|
+
return;
|
|
425
|
+
}
|
|
426
|
+
// Sync from here: forwardInner answers every failure itself, but a
|
|
427
|
+
// throw before it can answer must still be loud, never a floating reject.
|
|
428
|
+
// The dial is pinned to the checked IP: no second DNS resolution.
|
|
429
|
+
try {
|
|
430
|
+
forwardInner({ agent, method, url, headers, body, stream, cres, u, upstreamIp: verdict.ip });
|
|
431
|
+
} catch (e) {
|
|
432
|
+
// The live stream arrives paused (see handleRequest): unpause so no
|
|
433
|
+
// paused stream leaks on this path.
|
|
434
|
+
try { stream?.resume(); } catch {}
|
|
435
|
+
log({ ev: 'deny', agent, code: 502, note: `upstream failed: ${e.message}` });
|
|
436
|
+
denyRes(cres, 502, `upstream failed: ${e.message}`);
|
|
437
|
+
}
|
|
438
|
+
}
|
|
439
|
+
|
|
440
|
+
/** @param {ForwardArgs & { u: URL, upstreamIp?: string }} args */
|
|
441
|
+
function forwardInner({ agent, method, url, headers, body, stream, cres, u, upstreamIp }) {
|
|
442
|
+
const sock = cres.socket;
|
|
443
|
+
if (!sock) return; // no transport left to answer on
|
|
444
|
+
const secure = u.protocol === 'https:';
|
|
445
|
+
/** @type {Record<string, string | string[] | undefined>} */
|
|
446
|
+
const fwdHeaders = {};
|
|
447
|
+
for (const [k, v] of Object.entries(headers)) {
|
|
448
|
+
if (!HOP_REQ.has(k.toLowerCase())) fwdHeaders[k] = v;
|
|
449
|
+
}
|
|
450
|
+
const pinned = upstreamIp && net.isIP(upstreamIp) ? upstreamIp : null;
|
|
451
|
+
const mod = secure ? https : http;
|
|
452
|
+
const up = mod.request({
|
|
453
|
+
host: u.hostname,
|
|
454
|
+
port: u.port ? parseInt(u.port, 10) : (secure ? 443 : 80),
|
|
455
|
+
// Pinned dial: answer from the checked IP, never DNS again. Node asks
|
|
456
|
+
// with `{ all: true }`, which wants an array back (not the triple).
|
|
457
|
+
...(pinned ? { lookup: (h, o, cb) => {
|
|
458
|
+
const fn = typeof o === 'function' ? o : cb;
|
|
459
|
+
const opts = typeof o === 'function' ? {} : (o ?? {});
|
|
460
|
+
const fam = net.isIP(pinned);
|
|
461
|
+
try {
|
|
462
|
+
if (opts && opts.all) fn(null, [{ address: pinned, family: fam }]);
|
|
463
|
+
else fn(null, pinned, fam);
|
|
464
|
+
} catch (e) { try { /** @type {(err: unknown) => void} */ (fn)(e); } catch {} }
|
|
465
|
+
} } : {}),
|
|
466
|
+
...(secure && !IP_RE.test(u.hostname) ? { servername: u.hostname } : {}),
|
|
467
|
+
...(secure && trust ? { ca: trust } : {}),
|
|
468
|
+
method, path: u.pathname + u.search, headers: fwdHeaders,
|
|
469
|
+
});
|
|
470
|
+
upstreams.add(up);
|
|
471
|
+
let done = false;
|
|
472
|
+
const fail = (note) => {
|
|
473
|
+
if (done) return;
|
|
474
|
+
done = true;
|
|
475
|
+
upstreams.delete(up);
|
|
476
|
+
log({ ev: 'deny', agent, code: 502, note });
|
|
477
|
+
try {
|
|
478
|
+
if (!cres.headersSent && !sock.destroyed) {
|
|
479
|
+
cres.writeHead(502, { 'content-type': 'text/plain', connection: 'close' });
|
|
480
|
+
}
|
|
481
|
+
if (!sock.destroyed) cres.end(`${note}\n`);
|
|
482
|
+
} catch {}
|
|
483
|
+
};
|
|
484
|
+
up.setTimeout(upstreamTimeoutMs, () => { up.destroy(new Error(`upstream timeout after ${upstreamTimeoutMs}ms`)); });
|
|
485
|
+
up.on('response', (ures) => {
|
|
486
|
+
/** @type {Record<string, string | string[] | undefined>} */
|
|
487
|
+
const respHeaders = {};
|
|
488
|
+
for (const [k, v] of Object.entries(ures.headers)) {
|
|
489
|
+
if (!HOP_RESP.has(k.toLowerCase()) && v !== undefined) respHeaders[k] = v;
|
|
490
|
+
}
|
|
491
|
+
if (ures.statusCode === undefined) { fail('upstream sent no status'); up.destroy(); return; }
|
|
492
|
+
log({ ev: 'resp', agent, url, status: ures.statusCode });
|
|
493
|
+
try {
|
|
494
|
+
cres.writeHead(ures.statusCode, respHeaders);
|
|
495
|
+
} catch (e) { fail(`cannot frame upstream response: ${e.message}`); up.destroy(); return; }
|
|
496
|
+
ures.on('end', () => {
|
|
497
|
+
if (done) return;
|
|
498
|
+
done = true;
|
|
499
|
+
upstreams.delete(up);
|
|
500
|
+
});
|
|
501
|
+
ures.on('error', (e) => fail(`upstream body failed: ${e.message}`));
|
|
502
|
+
ures.pipe(cres);
|
|
503
|
+
});
|
|
504
|
+
up.on('error', (e) => fail(`upstream ${u.hostname} failed: ${e.message}`));
|
|
505
|
+
// Client went away mid-flight: stop paying for the upstream.
|
|
506
|
+
cres.on('close', () => {
|
|
507
|
+
if (!done && !cres.writableEnded) { done = true; upstreams.delete(up); up.destroy(); }
|
|
508
|
+
});
|
|
509
|
+
if (body) up.end(body);
|
|
510
|
+
else if (stream) stream.pipe(up);
|
|
511
|
+
else up.end();
|
|
512
|
+
}
|
|
513
|
+
|
|
514
|
+
const holds = hold ? createHolds({
|
|
515
|
+
log,
|
|
516
|
+
shouldHold: hold.shouldHold,
|
|
517
|
+
match: hold.match,
|
|
518
|
+
timeoutMs: hold.timeoutMs,
|
|
519
|
+
maxBody: holdMaxBody,
|
|
520
|
+
controlSocket,
|
|
521
|
+
onApprove: (h) => forward({ agent: h.agent, method: h.method, url: h.url,
|
|
522
|
+
headers: h.headers, body: h.body, cres: h.cres }),
|
|
523
|
+
onDeny: (h, reason) => denyRes(h.cres, 403, `denied: ${reason}`),
|
|
524
|
+
}) : null;
|
|
525
|
+
|
|
526
|
+
const server = http.createServer((creq, cres) => {
|
|
527
|
+
// Async only for the wall's DNS lookup; no body listener is attached
|
|
528
|
+
// before the check, so nothing is lost while it resolves.
|
|
529
|
+
handleRequest(creq, cres).catch((e) => denyRes(cres, 500, `proxy failed: ${e.message}`));
|
|
530
|
+
});
|
|
531
|
+
|
|
532
|
+
async function handleRequest(creq, cres) {
|
|
533
|
+
const sock = creq.socket;
|
|
534
|
+
const agent = agentOf(sock);
|
|
535
|
+
const secure = sock[SECURE] === true;
|
|
536
|
+
const target = creq.url || '';
|
|
537
|
+
let url;
|
|
538
|
+
try {
|
|
539
|
+
if (/^https?:\/\//i.test(target)) url = new URL(target);
|
|
540
|
+
else {
|
|
541
|
+
const host = creq.headers.host;
|
|
542
|
+
if (!host) throw new Error('no host');
|
|
543
|
+
url = new URL(`${secure ? 'https' : 'http'}://${host}${target}`);
|
|
544
|
+
}
|
|
545
|
+
} catch { denyRes(cres, 400, 'bad request target'); return; }
|
|
546
|
+
const method = creq.method;
|
|
547
|
+
if (!method) { denyRes(cres, 400, 'bad request method'); return; }
|
|
548
|
+
const urlStr = url.toString();
|
|
549
|
+
const verdict = await checkUpstream(url.hostname, gate);
|
|
550
|
+
if (!verdict.ok) {
|
|
551
|
+
try { creq.resume(); } catch {}
|
|
552
|
+
denyRes(cres, 403, verdict.reason);
|
|
553
|
+
return;
|
|
554
|
+
}
|
|
555
|
+
const queue = holds;
|
|
556
|
+
const reason = queue ? queue.decide({ agent, method, url: urlStr, headers: creq.headers }) : null;
|
|
557
|
+
|
|
558
|
+
// Tee the body for the log (capped). A held request buffers it whole —
|
|
559
|
+
// bounded by maxBody — so approve can forward it after the human decides.
|
|
560
|
+
// Anything else streams straight through; the tee only feeds the log.
|
|
561
|
+
const chunks = [];
|
|
562
|
+
let size = 0;
|
|
563
|
+
let over = false;
|
|
564
|
+
const finishLog = () => {
|
|
565
|
+
const body = Buffer.concat(chunks);
|
|
566
|
+
log({ ev: 'req', agent, method: creq.method, url: urlStr,
|
|
567
|
+
headers: creq.headers, body: body.toString('utf8'),
|
|
568
|
+
...(over ? { truncated: true, bodyBytes: size } : {}) });
|
|
569
|
+
return body;
|
|
570
|
+
};
|
|
571
|
+
if (!reason || !queue) {
|
|
572
|
+
// Pause before any body listener: the tee below would otherwise put
|
|
573
|
+
// the stream in flowing mode, and forward() awaits a second wall
|
|
574
|
+
// check before forwardInner pipes to upstream — body bytes arriving
|
|
575
|
+
// during that wait would go to the tee only, starving upstream
|
|
576
|
+
// against Content-Length. Buffered here, pipe() resumes the flow,
|
|
577
|
+
// so both the tee and upstream see the whole body.
|
|
578
|
+
creq.pause();
|
|
579
|
+
creq.on('data', (c) => {
|
|
580
|
+
size += c.length;
|
|
581
|
+
if (size > maxLogBody || over) { over = true; return; }
|
|
582
|
+
chunks.push(c);
|
|
583
|
+
});
|
|
584
|
+
creq.on('end', finishLog);
|
|
585
|
+
creq.on('error', () => {});
|
|
586
|
+
forward({ agent, method, url: urlStr,
|
|
587
|
+
headers: { ...creq.headers }, stream: creq, cres });
|
|
588
|
+
return;
|
|
589
|
+
}
|
|
590
|
+
creq.on('data', (c) => {
|
|
591
|
+
size += c.length;
|
|
592
|
+
if (size > holdMaxBody) { over = true; return; }
|
|
593
|
+
chunks.push(c);
|
|
594
|
+
});
|
|
595
|
+
creq.on('error', () => denyRes(cres, 502, 'client body failed'));
|
|
596
|
+
creq.on('end', () => {
|
|
597
|
+
if (over) { denyRes(cres, 403, 'body too large to hold'); return; }
|
|
598
|
+
const body = finishLog();
|
|
599
|
+
// Parked: the tunnel stays open until a human decides.
|
|
600
|
+
queue.add({ agent, method, url: urlStr,
|
|
601
|
+
headers: { ...creq.headers }, body, sock, cres });
|
|
602
|
+
});
|
|
603
|
+
}
|
|
604
|
+
// Idle tunnels die here; a request in flight is never idle by definition.
|
|
605
|
+
server.keepAliveTimeout = clientIdleMs;
|
|
606
|
+
server.on('clientError', (err, sock) => {
|
|
607
|
+
try { sock.destroy(); } catch {}
|
|
608
|
+
});
|
|
609
|
+
|
|
610
|
+
// Dispatch: one CONNECT line, or plain HTTP straight into the same server.
|
|
611
|
+
function admit(sock, agent) {
|
|
612
|
+
sock[AGENT] = agent;
|
|
613
|
+
clients.add(sock);
|
|
614
|
+
sock.setTimeout(clientIdleMs, () => sock.destroy());
|
|
615
|
+
sock.on('error', () => {});
|
|
616
|
+
sock.on('close', () => {
|
|
617
|
+
clients.delete(sock);
|
|
618
|
+
holds?.abandonSocket(sock);
|
|
619
|
+
});
|
|
620
|
+
let buf = Buffer.alloc(0);
|
|
621
|
+
const onData = (ch) => {
|
|
622
|
+
buf = Buffer.concat([buf, ch]);
|
|
623
|
+
const i = buf.indexOf('\r\n\r\n');
|
|
624
|
+
if (i < 0) {
|
|
625
|
+
if (buf.length > 65536) {
|
|
626
|
+
sock.removeListener('data', onData);
|
|
627
|
+
denyRaw(sock, 400, 'head too large');
|
|
628
|
+
}
|
|
629
|
+
return;
|
|
630
|
+
}
|
|
631
|
+
const line = buf.subarray(0, buf.indexOf('\r\n')).toString('latin1');
|
|
632
|
+
const [method, target] = line.split(' ');
|
|
633
|
+
sock.removeListener('data', onData);
|
|
634
|
+
sock.setTimeout(0); // the http.Server owns idle from here
|
|
635
|
+
if (method === 'CONNECT') {
|
|
636
|
+
handleConnect(sock, target, buf.subarray(i + 4), agent);
|
|
637
|
+
} else {
|
|
638
|
+
// Plain HTTP (absolute- or origin-form): same parser, same handler.
|
|
639
|
+
// Push the bytes back so the http.Server sees the whole stream.
|
|
640
|
+
sock.unshift(buf);
|
|
641
|
+
server.emit('connection', sock);
|
|
642
|
+
}
|
|
643
|
+
buf = Buffer.alloc(0);
|
|
644
|
+
};
|
|
645
|
+
sock.on('data', onData);
|
|
646
|
+
}
|
|
647
|
+
|
|
648
|
+
async function handleConnect(sock, target, rest, agent) {
|
|
649
|
+
const [host, portStr] = String(target || '').split(':');
|
|
650
|
+
const portNum = portStr ? parseInt(portStr, 10) : 443;
|
|
651
|
+
if (!HOST_RE.test(host || '') || !Number.isFinite(portNum) || portNum < 1 || portNum > 65535) {
|
|
652
|
+
denyRaw(sock, 400, 'bad connect line');
|
|
653
|
+
return;
|
|
654
|
+
}
|
|
655
|
+
// Deny the tunnel itself: no cert is minted for a walled destination,
|
|
656
|
+
// and the inner request is checked again on arrival anyway.
|
|
657
|
+
const verdict = await checkUpstream(host, gate);
|
|
658
|
+
if (!verdict.ok) {
|
|
659
|
+
denyRaw(sock, 403, verdict.reason);
|
|
660
|
+
return;
|
|
661
|
+
}
|
|
662
|
+
let creds;
|
|
663
|
+
try {
|
|
664
|
+
creds = await certFor(certDir, host);
|
|
665
|
+
} catch (e) {
|
|
666
|
+
denyRaw(sock, 502, `no cert for ${host}: ${e.message}`);
|
|
667
|
+
return;
|
|
668
|
+
}
|
|
669
|
+
if (closed || sock.destroyed) return;
|
|
670
|
+
try { sock.write('HTTP/1.1 200 Connection established\r\n\r\n'); }
|
|
671
|
+
catch { return; }
|
|
672
|
+
if (rest.length) sock.unshift(rest);
|
|
673
|
+
const st = new tls.TLSSocket(sock, { isServer: true, key: creds.key, cert: creds.cert });
|
|
674
|
+
st[AGENT] = agent;
|
|
675
|
+
st[SECURE] = true;
|
|
676
|
+
clients.add(st);
|
|
677
|
+
st.on('error', () => {});
|
|
678
|
+
st.on('close', () => {
|
|
679
|
+
clients.delete(st);
|
|
680
|
+
holds?.abandonSocket(st);
|
|
681
|
+
});
|
|
682
|
+
server.emit('connection', st);
|
|
683
|
+
}
|
|
684
|
+
|
|
685
|
+
// --- listeners -----------------------------------------------------------
|
|
686
|
+
const ready = (async () => {
|
|
687
|
+
await ensureCA(certDir);
|
|
688
|
+
/** @type {number|null} */
|
|
689
|
+
let bound = null;
|
|
690
|
+
if (port !== null && port !== undefined) {
|
|
691
|
+
/** @type {Promise<number|null>} */
|
|
692
|
+
const boundP = new Promise((resolve, reject) => {
|
|
693
|
+
tcp = net.createServer((sock) => {
|
|
694
|
+
if (closed) { sock.destroy(); return; }
|
|
695
|
+
admit(sock, 'tcp');
|
|
696
|
+
});
|
|
697
|
+
tcp.on('error', reject);
|
|
698
|
+
tcp.listen(port, '127.0.0.1', () => {
|
|
699
|
+
const a = tcp?.address();
|
|
700
|
+
resolve(typeof a === 'object' && a !== null ? a.port : 0);
|
|
701
|
+
});
|
|
702
|
+
});
|
|
703
|
+
bound = await boundP;
|
|
704
|
+
}
|
|
705
|
+
return { port: bound };
|
|
706
|
+
})();
|
|
707
|
+
// A rejected `ready` must never become an uncaught process crash.
|
|
708
|
+
ready.catch(() => {});
|
|
709
|
+
|
|
710
|
+
function addAgent(name) {
|
|
711
|
+
if (!runtime) throw new Error('createProxy: addAgent needs the runtime option');
|
|
712
|
+
const sockPath = socketPathForAgent(runtime, name);
|
|
713
|
+
if (agentServers.has(name)) return sockPath;
|
|
714
|
+
try { fs.unlinkSync(sockPath); } catch {}
|
|
715
|
+
fs.mkdirSync(path.join(runtime, 'socks'), { recursive: true });
|
|
716
|
+
const srv = net.createServer((sock) => {
|
|
717
|
+
if (closed) { sock.destroy(); return; }
|
|
718
|
+
admit(sock, name);
|
|
719
|
+
});
|
|
720
|
+
srv.on('error', (e) => log({ ev: 'deny', agent: name, code: 500, note: `agent listener failed: ${e.message}` }));
|
|
721
|
+
srv.listen(sockPath, () => {
|
|
722
|
+
try { fs.chmodSync(sockPath, 0o600); } catch {}
|
|
723
|
+
});
|
|
724
|
+
agentServers.set(name, srv);
|
|
725
|
+
return sockPath;
|
|
726
|
+
}
|
|
727
|
+
|
|
728
|
+
function removeAgent(name) {
|
|
729
|
+
const srv = agentServers.get(name);
|
|
730
|
+
if (!srv) return;
|
|
731
|
+
agentServers.delete(name);
|
|
732
|
+
srv.close();
|
|
733
|
+
if (runtime) {
|
|
734
|
+
try { fs.unlinkSync(socketPathForAgent(runtime, name)); } catch {}
|
|
735
|
+
}
|
|
736
|
+
}
|
|
737
|
+
|
|
738
|
+
async function close() {
|
|
739
|
+
closed = true;
|
|
740
|
+
tcp?.close();
|
|
741
|
+
for (const [, srv] of agentServers) srv.close();
|
|
742
|
+
agentServers.clear();
|
|
743
|
+
// Parked holds settle as denied (guarded writes), timers cleared,
|
|
744
|
+
// control socket closed — all inside holds.close().
|
|
745
|
+
holds?.close();
|
|
746
|
+
for (const up of upstreams) { try { up.destroy(); } catch {} }
|
|
747
|
+
upstreams.clear();
|
|
748
|
+
for (const s of clients) { try { s.destroy(); } catch {} }
|
|
749
|
+
clients.clear();
|
|
750
|
+
server.close();
|
|
751
|
+
logStream.end();
|
|
752
|
+
/** @type {Promise<void>} */
|
|
753
|
+
const flushed = new Promise((resolve) => {
|
|
754
|
+
if (logStream.writableFinished) resolve();
|
|
755
|
+
else logStream.once('finish', () => resolve());
|
|
756
|
+
});
|
|
757
|
+
await flushed;
|
|
758
|
+
}
|
|
759
|
+
|
|
760
|
+
return {
|
|
761
|
+
ready,
|
|
762
|
+
close,
|
|
763
|
+
addAgent,
|
|
764
|
+
removeAgent,
|
|
765
|
+
pending: () => (holds ? holds.pending() : []),
|
|
766
|
+
get caFile() { return path.join(certDir, 'ca.pem'); },
|
|
767
|
+
};
|
|
768
|
+
}
|