barebox 0.2.0 → 0.3.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 +62 -2
- package/README.md +8 -8
- package/barebox.context.md +85 -17
- package/package.json +2 -2
- package/primitives.json +40 -4
- package/src/certs.js +2 -1
- package/src/cli.js +348 -35
- package/src/holds.js +368 -56
- package/src/index.js +2 -0
- package/src/launcher.js +149 -50
- package/src/overlay-walk.js +49 -0
- package/src/overlay.js +1012 -0
- package/src/proxy.js +101 -297
- package/src/run.js +226 -0
- package/src/runtime.js +263 -0
- package/src/wall.js +156 -0
- package/types/certs.d.ts +2 -0
- package/types/holds.d.ts +157 -13
- package/types/index.d.ts +2 -0
- package/types/launcher.d.ts +13 -4
- package/types/overlay-walk.d.ts +1 -0
- package/types/overlay.d.ts +220 -0
- package/types/proxy.d.ts +43 -83
- package/types/run.d.ts +192 -0
- package/types/runtime.d.ts +112 -0
- package/types/wall.d.ts +30 -0
package/src/proxy.js
CHANGED
|
@@ -13,19 +13,15 @@ import tls from 'node:tls';
|
|
|
13
13
|
import http from 'node:http';
|
|
14
14
|
import https from 'node:https';
|
|
15
15
|
import fs from 'node:fs';
|
|
16
|
-
import os from 'node:os';
|
|
17
16
|
import path from 'node:path';
|
|
18
|
-
import {
|
|
19
|
-
import { ensureCA, certFor } from './certs.js';
|
|
17
|
+
import { ensureCA, certFor, HOST_RE } from './certs.js';
|
|
20
18
|
import { createHolds } from './holds.js';
|
|
19
|
+
import { claimRuntime, runtimePaths } from './runtime.js';
|
|
20
|
+
import { checkUpstream } from './wall.js';
|
|
21
21
|
|
|
22
22
|
const AGENT = Symbol('agent');
|
|
23
23
|
const SECURE = Symbol('secure');
|
|
24
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
25
|
// Hop-by-hop headers must not be forwarded: node's HTTP stack re-frames.
|
|
30
26
|
const HOP_REQ = new Set(['proxy-connection', 'proxy-authorization']);
|
|
31
27
|
const HOP_RESP = new Set(['connection', 'keep-alive', 'proxy-authenticate',
|
|
@@ -36,7 +32,9 @@ const HOP_RESP = new Set(['connection', 'keep-alive', 'proxy-authenticate',
|
|
|
36
32
|
// user's `redact` hook runs after this scrubbing, so it sees (and further
|
|
37
33
|
// shapes) an already-safe entry. Bodies stay logged as-is.
|
|
38
34
|
const REDACTED = '[redacted]';
|
|
39
|
-
|
|
35
|
+
// Interim set (M3 replaces this with bareguard's `secrets` redaction): header names whose values never land verbatim.
|
|
36
|
+
const SENSITIVE_HEADERS = new Set(['authorization', 'proxy-authorization',
|
|
37
|
+
'cookie', 'set-cookie', 'x-api-key', 'x-auth-token', 'api-key']);
|
|
40
38
|
|
|
41
39
|
/**
|
|
42
40
|
* Copy a log entry with sensitive header values replaced by `[redacted]`.
|
|
@@ -57,222 +55,22 @@ function scrubSecrets(entry) {
|
|
|
57
55
|
return { ...entry, headers };
|
|
58
56
|
}
|
|
59
57
|
|
|
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
58
|
/**
|
|
251
59
|
* Options for {@link createProxy}.
|
|
252
60
|
*
|
|
253
61
|
* @typedef {object} ProxyOptions
|
|
254
62
|
* @property {string} logFile JSON-lines log path (`req`, `resp`, `deny`, `hold`, `decide`, `hold-abandoned`)
|
|
255
|
-
* @property {string}
|
|
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`
|
|
63
|
+
* @property {string} runtime runtime dir; required. Holds the CA + minted host certs (`certs/`, see `runtime.js`), the agent sockets, and the hold queue files.
|
|
261
64
|
* @property {number} [port] opt-in TCP listener for tests, bound to 127.0.0.1 only (default: none)
|
|
262
65
|
* @property {string} [upstreamCa] extra PEM the proxy trusts for upstream TLS, on top of system roots
|
|
263
66
|
* @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
67
|
* @property {number} [upstreamTimeoutMs] give up on an upstream response after this (default 120000)
|
|
269
|
-
* @property {
|
|
68
|
+
* @property {object} [unsafeTestOnly] TEST-ONLY escape hatch: everything under
|
|
69
|
+
* it weakens the sandbox wall, so production omits it and tests name it loudly.
|
|
70
|
+
* @property {boolean} [unsafeTestOnly.allowLoopback] let loopback and unspecified
|
|
270
71
|
* destinations through (default false). Fixture servers listen on 127.0.0.1,
|
|
271
72
|
* so tests pass this; production never should.
|
|
272
|
-
* @property {(host: string
|
|
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
|
|
73
|
+
* @property {(host: string) => Promise<string[] | string | null>} [unsafeTestOnly.resolveUpstream]
|
|
276
74
|
* DNS stub: replaces the wall's resolver so rebinding is testable. Production omits it.
|
|
277
75
|
* @property {number} [clientIdleMs] kill a client tunnel idle this long; never fires mid-request (default 60000)
|
|
278
76
|
* @property {number} [maxLogBody] log at most this many request-body bytes, then `truncated: true` (default 1048576)
|
|
@@ -287,6 +85,11 @@ export function socketPathForAgent(runtime, name) {
|
|
|
287
85
|
* @property {import('./holds.js').ShouldHold} [shouldHold] decision function; overrides `match`
|
|
288
86
|
* @property {number|string} [timeoutMs] hold deadline in ms, or `'never'` (default 120000)
|
|
289
87
|
* @property {number} [maxBody] bodies over this are denied at the door, never queued (default 1048576)
|
|
88
|
+
* @property {import('./holds.js').OnAsk|null} [onAsk] ask seam (bareguard `humanChannel` shape).
|
|
89
|
+
* When present no files are involved; omit it for the default file checkpoint
|
|
90
|
+
* (`<runtime>/asks` + `<runtime>/answers`, `sbx pending/approve/deny`).
|
|
91
|
+
* @property {number} [pollMs] answer poll interval in ms for the file checkpoint (default 250)
|
|
92
|
+
* @property {import('./holds.js').OnEvent} [onEvent] event callback: `{ type: 'ask' }` on park, `{ type: 'decided' }` on settle
|
|
290
93
|
*/
|
|
291
94
|
|
|
292
95
|
/**
|
|
@@ -316,63 +119,46 @@ export function socketPathForAgent(runtime, name) {
|
|
|
316
119
|
* @param {ProxyOptions} opts
|
|
317
120
|
* @returns live proxy: `ready` resolves when listeners + CA are up; the shape is inferred, see `Proxy`
|
|
318
121
|
* @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`
|
|
122
|
+
* @fails Throws synchronously on a missing `logFile` or `runtime`. Throws when another live proxy owns the runtime; the claim dies with its process; nothing is ever taken over. 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
123
|
* @example
|
|
321
124
|
* import { createProxy } from "barebox";
|
|
322
|
-
* const proxy = createProxy({ port: 0,
|
|
125
|
+
* const proxy = createProxy({ port: 0, runtime: "./sbx-runtime", logFile: "./mitm.log" });
|
|
323
126
|
* const { port } = await proxy.ready;
|
|
324
127
|
* await proxy.close();
|
|
325
128
|
*/
|
|
326
129
|
export function createProxy(opts) {
|
|
327
|
-
const { logFile,
|
|
328
|
-
upstreamCa = null, hold = null,
|
|
130
|
+
const { logFile, runtime, port = null,
|
|
131
|
+
upstreamCa = null, hold = null,
|
|
329
132
|
upstreamTimeoutMs = 120000, clientIdleMs = 60000,
|
|
330
|
-
|
|
133
|
+
unsafeTestOnly = null,
|
|
331
134
|
maxLogBody = 1048576, redact = (e) => e } = opts ?? {};
|
|
332
|
-
const
|
|
135
|
+
const { allowLoopback = false, resolveUpstream = null } = unsafeTestOnly ?? {};
|
|
136
|
+
const gate = { allowLoopback, resolveUpstream: resolveUpstream ?? undefined };
|
|
333
137
|
if (!logFile) throw new Error('createProxy: logFile is required');
|
|
334
|
-
|
|
335
|
-
|
|
336
|
-
|
|
337
|
-
//
|
|
338
|
-
|
|
339
|
-
//
|
|
340
|
-
//
|
|
341
|
-
|
|
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;
|
|
138
|
+
if (typeof runtime !== 'string' || !runtime) throw new Error('createProxy: runtime is required');
|
|
139
|
+
// One live proxy per runtime, enforced here: claimed before the hold
|
|
140
|
+
// queue clears `asks/` and `answers/`, so that clearing can never wipe a
|
|
141
|
+
// live owner's files — only a dead owner's leftovers can be there.
|
|
142
|
+
const releaseClaim = claimRuntime(runtime);
|
|
143
|
+
// Always `<runtime>/certs`: one layout, owned by runtime.js, so there is
|
|
144
|
+
// nothing to contain and no check to fail.
|
|
145
|
+
const certDir = runtimePaths(runtime).certsDir;
|
|
367
146
|
const holdMaxBody = hold?.maxBody ?? 1048576;
|
|
368
147
|
|
|
369
148
|
const logStream = fs.createWriteStream(logFile, { flags: 'a', mode: 0o600 });
|
|
149
|
+
// `mode` applies only at creation: a 0644 log from an older run would stay
|
|
150
|
+
// world-readable while new lines append, so fix it up on every start. A
|
|
151
|
+
// not-yet-created file throws here and is created 0600 by the stream.
|
|
152
|
+
try { fs.chmodSync(logFile, 0o600); } catch {}
|
|
370
153
|
const log = (o) => { logStream.write(JSON.stringify(redact(scrubSecrets(o))) + '\n'); };
|
|
371
154
|
let trust = null;
|
|
372
155
|
if (upstreamCa) {
|
|
373
156
|
let extra;
|
|
374
157
|
try { extra = fs.readFileSync(upstreamCa, 'utf8'); }
|
|
375
|
-
catch (e) {
|
|
158
|
+
catch (e) {
|
|
159
|
+
releaseClaim();
|
|
160
|
+
throw new Error(`createProxy: cannot read upstreamCa: ${e.message}`);
|
|
161
|
+
}
|
|
376
162
|
trust = [...tls.rootCertificates, extra];
|
|
377
163
|
}
|
|
378
164
|
|
|
@@ -387,6 +173,7 @@ export function createProxy(opts) {
|
|
|
387
173
|
|
|
388
174
|
const agentOf = (sock) => sock[AGENT] ?? 'tcp';
|
|
389
175
|
|
|
176
|
+
// The one writer of a proxied HTTP error: logs it, answers it.
|
|
390
177
|
function denyRes(cres, code, note) {
|
|
391
178
|
const sock = cres.socket;
|
|
392
179
|
log({ ev: 'deny', agent: agentOf(sock), code, note });
|
|
@@ -398,6 +185,7 @@ export function createProxy(opts) {
|
|
|
398
185
|
} catch {}
|
|
399
186
|
}
|
|
400
187
|
|
|
188
|
+
// Pre-HTTP raw sockets only (CONNECT line, oversized head, walled CONNECT, cert failure).
|
|
401
189
|
function denyRaw(sock, code, note) {
|
|
402
190
|
log({ ev: 'deny', agent: agentOf(sock), code, note });
|
|
403
191
|
if (sock.destroyed) return;
|
|
@@ -425,20 +213,19 @@ export function createProxy(opts) {
|
|
|
425
213
|
}
|
|
426
214
|
// Sync from here: forwardInner answers every failure itself, but a
|
|
427
215
|
// throw before it can answer must still be loud, never a floating reject.
|
|
428
|
-
// The dial is pinned to the checked
|
|
216
|
+
// The dial is pinned to the checked IPs: no second DNS resolution.
|
|
429
217
|
try {
|
|
430
|
-
forwardInner({ agent, method, url, headers, body, stream, cres, u,
|
|
218
|
+
forwardInner({ agent, method, url, headers, body, stream, cres, u, upstreamIps: verdict.ips });
|
|
431
219
|
} catch (e) {
|
|
432
220
|
// The live stream arrives paused (see handleRequest): unpause so no
|
|
433
221
|
// paused stream leaks on this path.
|
|
434
222
|
try { stream?.resume(); } catch {}
|
|
435
|
-
log({ ev: 'deny', agent, code: 502, note: `upstream failed: ${e.message}` });
|
|
436
223
|
denyRes(cres, 502, `upstream failed: ${e.message}`);
|
|
437
224
|
}
|
|
438
225
|
}
|
|
439
226
|
|
|
440
|
-
/** @param {ForwardArgs & { u: URL,
|
|
441
|
-
function forwardInner({ agent, method, url, headers, body, stream, cres, u,
|
|
227
|
+
/** @param {ForwardArgs & { u: URL, upstreamIps: string[] }} args */
|
|
228
|
+
function forwardInner({ agent, method, url, headers, body, stream, cres, u, upstreamIps }) {
|
|
442
229
|
const sock = cres.socket;
|
|
443
230
|
if (!sock) return; // no transport left to answer on
|
|
444
231
|
const secure = u.protocol === 'https:';
|
|
@@ -447,21 +234,31 @@ export function createProxy(opts) {
|
|
|
447
234
|
for (const [k, v] of Object.entries(headers)) {
|
|
448
235
|
if (!HOP_REQ.has(k.toLowerCase())) fwdHeaders[k] = v;
|
|
449
236
|
}
|
|
450
|
-
const pinned =
|
|
237
|
+
const pinned = (upstreamIps ?? []).filter((ip) => net.isIP(ip));
|
|
451
238
|
const mod = secure ? https : http;
|
|
452
239
|
const up = mod.request({
|
|
453
240
|
host: u.hostname,
|
|
454
241
|
port: u.port ? parseInt(u.port, 10) : (secure ? 443 : 80),
|
|
455
|
-
// Pinned dial: answer from the checked
|
|
456
|
-
// with `{ all: true }
|
|
457
|
-
|
|
458
|
-
|
|
459
|
-
|
|
460
|
-
|
|
242
|
+
// Pinned dial: answer from the checked IPs, never DNS again. Node asks
|
|
243
|
+
// with `{ all: true }` and attempts every address (Happy Eyeballs: a
|
|
244
|
+
// refused address falls through to the next, each attempt short-timed);
|
|
245
|
+
// otherwise the first pinned address answers alone. A custom socket
|
|
246
|
+
// cannot serve here: the TLS stack will not handshake over one.
|
|
247
|
+
...(pinned.length ? { lookup: (h, o, cb) => {
|
|
248
|
+
const done = /** @type {(err: unknown, ...rest: unknown[]) => void} */ (typeof o === 'function' ? o : cb);
|
|
249
|
+
/** @param {string} ip */
|
|
250
|
+
const fam = (ip) => net.isIP(ip);
|
|
461
251
|
try {
|
|
462
|
-
|
|
463
|
-
|
|
464
|
-
|
|
252
|
+
const opts = typeof o === 'function' ? {} : (o ?? {});
|
|
253
|
+
if (opts && /** @type {{ all?: boolean }} */ (opts).all) {
|
|
254
|
+
done(null, pinned.map((address) => ({ address, family: fam(address) })));
|
|
255
|
+
} else {
|
|
256
|
+
const first = /** @type {string} */ (pinned[0]);
|
|
257
|
+
done(null, first, fam(first));
|
|
258
|
+
}
|
|
259
|
+
} catch (e) {
|
|
260
|
+
done(e);
|
|
261
|
+
}
|
|
465
262
|
} } : {}),
|
|
466
263
|
...(secure && !IP_RE.test(u.hostname) ? { servername: u.hostname } : {}),
|
|
467
264
|
...(secure && trust ? { ca: trust } : {}),
|
|
@@ -473,13 +270,7 @@ export function createProxy(opts) {
|
|
|
473
270
|
if (done) return;
|
|
474
271
|
done = true;
|
|
475
272
|
upstreams.delete(up);
|
|
476
|
-
|
|
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 {}
|
|
273
|
+
denyRes(cres, 502, note);
|
|
483
274
|
};
|
|
484
275
|
up.setTimeout(upstreamTimeoutMs, () => { up.destroy(new Error(`upstream timeout after ${upstreamTimeoutMs}ms`)); });
|
|
485
276
|
up.on('response', (ures) => {
|
|
@@ -511,17 +302,29 @@ export function createProxy(opts) {
|
|
|
511
302
|
else up.end();
|
|
512
303
|
}
|
|
513
304
|
|
|
514
|
-
|
|
515
|
-
|
|
516
|
-
|
|
517
|
-
|
|
518
|
-
|
|
519
|
-
|
|
520
|
-
|
|
521
|
-
|
|
522
|
-
|
|
523
|
-
|
|
524
|
-
|
|
305
|
+
// The rest of setup is infallible synchronously except this call, so a
|
|
306
|
+
// throw here releases the claim before it propagates (like upstreamCa
|
|
307
|
+
// above); async failures release through `ready` and `close()` below.
|
|
308
|
+
let holds = null;
|
|
309
|
+
try {
|
|
310
|
+
holds = hold ? createHolds({
|
|
311
|
+
log,
|
|
312
|
+
shouldHold: hold.shouldHold,
|
|
313
|
+
match: hold.match,
|
|
314
|
+
timeoutMs: hold.timeoutMs,
|
|
315
|
+
maxBody: holdMaxBody,
|
|
316
|
+
runtime,
|
|
317
|
+
onAsk: hold.onAsk,
|
|
318
|
+
pollMs: hold.pollMs,
|
|
319
|
+
onEvent: hold.onEvent,
|
|
320
|
+
onApprove: (h) => forward({ agent: h.agent, method: h.method, url: h.url,
|
|
321
|
+
headers: h.headers, body: h.body, cres: h.cres }),
|
|
322
|
+
onDeny: (h, reason) => denyRes(h.cres, 403, `denied: ${reason}`),
|
|
323
|
+
}) : null;
|
|
324
|
+
} catch (e) {
|
|
325
|
+
releaseClaim();
|
|
326
|
+
throw e;
|
|
327
|
+
}
|
|
525
328
|
|
|
526
329
|
const server = http.createServer((creq, cres) => {
|
|
527
330
|
// Async only for the wall's DNS lookup; no body listener is attached
|
|
@@ -596,9 +399,10 @@ export function createProxy(opts) {
|
|
|
596
399
|
creq.on('end', () => {
|
|
597
400
|
if (over) { denyRes(cres, 403, 'body too large to hold'); return; }
|
|
598
401
|
const body = finishLog();
|
|
599
|
-
// Parked: the tunnel stays open until
|
|
402
|
+
// Parked: the tunnel stays open until the ask channel decides. The
|
|
403
|
+
// hold reason travels as `note` so the ask file carries its `rule`.
|
|
600
404
|
queue.add({ agent, method, url: urlStr,
|
|
601
|
-
headers: { ...creq.headers }, body, sock, cres });
|
|
405
|
+
headers: { ...creq.headers }, body, sock, cres, note: reason });
|
|
602
406
|
});
|
|
603
407
|
}
|
|
604
408
|
// Idle tunnels die here; a request in flight is never idle by definition.
|
|
@@ -704,15 +508,16 @@ export function createProxy(opts) {
|
|
|
704
508
|
}
|
|
705
509
|
return { port: bound };
|
|
706
510
|
})();
|
|
707
|
-
// A rejected `ready` must never become an uncaught process crash
|
|
708
|
-
|
|
511
|
+
// A rejected `ready` must never become an uncaught process crash, and it
|
|
512
|
+
// releases the claim before the rejection reaches the caller (attached
|
|
513
|
+
// first, so this runs before any caller reaction).
|
|
514
|
+
ready.catch(() => { releaseClaim(); });
|
|
709
515
|
|
|
710
516
|
function addAgent(name) {
|
|
711
|
-
|
|
712
|
-
const sockPath = socketPathForAgent(runtime, name);
|
|
517
|
+
const sockPath = runtimePaths(runtime).socket(name);
|
|
713
518
|
if (agentServers.has(name)) return sockPath;
|
|
714
519
|
try { fs.unlinkSync(sockPath); } catch {}
|
|
715
|
-
fs.mkdirSync(path.
|
|
520
|
+
fs.mkdirSync(path.dirname(sockPath), { recursive: true });
|
|
716
521
|
const srv = net.createServer((sock) => {
|
|
717
522
|
if (closed) { sock.destroy(); return; }
|
|
718
523
|
admit(sock, name);
|
|
@@ -730,9 +535,7 @@ export function createProxy(opts) {
|
|
|
730
535
|
if (!srv) return;
|
|
731
536
|
agentServers.delete(name);
|
|
732
537
|
srv.close();
|
|
733
|
-
|
|
734
|
-
try { fs.unlinkSync(socketPathForAgent(runtime, name)); } catch {}
|
|
735
|
-
}
|
|
538
|
+
try { fs.unlinkSync(runtimePaths(runtime).socket(name)); } catch {}
|
|
736
539
|
}
|
|
737
540
|
|
|
738
541
|
async function close() {
|
|
@@ -741,7 +544,7 @@ export function createProxy(opts) {
|
|
|
741
544
|
for (const [, srv] of agentServers) srv.close();
|
|
742
545
|
agentServers.clear();
|
|
743
546
|
// Parked holds settle as denied (guarded writes), timers cleared,
|
|
744
|
-
//
|
|
547
|
+
// ask files removed, sweeper stopped — all inside holds.close().
|
|
745
548
|
holds?.close();
|
|
746
549
|
for (const up of upstreams) { try { up.destroy(); } catch {} }
|
|
747
550
|
upstreams.clear();
|
|
@@ -755,6 +558,7 @@ export function createProxy(opts) {
|
|
|
755
558
|
else logStream.once('finish', () => resolve());
|
|
756
559
|
});
|
|
757
560
|
await flushed;
|
|
561
|
+
releaseClaim();
|
|
758
562
|
}
|
|
759
563
|
|
|
760
564
|
return {
|