barebox 0.3.0 → 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.
- package/CHANGELOG.md +80 -0
- package/README.md +21 -22
- package/barebox.context.md +136 -16
- package/package.json +6 -1
- package/primitives.json +1 -1
- package/src/cardscan.js +96 -0
- package/src/certs.js +22 -2
- package/src/cli.js +31 -6
- package/src/config.js +96 -0
- package/src/holds.js +237 -50
- package/src/labels.js +88 -0
- package/src/launcher.js +11 -2
- package/src/overlay.js +54 -2
- package/src/policy.js +138 -0
- package/src/proxy.js +596 -132
- package/src/run.js +40 -73
- package/src/runtime.js +40 -3
- package/src/wall.js +104 -37
- package/types/cardscan.d.ts +17 -0
- package/types/cli.d.ts +1 -1
- package/types/config.d.ts +41 -0
- package/types/holds.d.ts +37 -48
- package/types/labels.d.ts +21 -0
- package/types/launcher.d.ts +3 -1
- package/types/overlay.d.ts +8 -0
- package/types/policy.d.ts +64 -0
- package/types/proxy.d.ts +83 -34
- package/types/run.d.ts +32 -10
- package/types/runtime.d.ts +22 -1
- package/types/wall.d.ts +4 -2
package/src/proxy.js
CHANGED
|
@@ -1,13 +1,16 @@
|
|
|
1
1
|
// Proxy: the front door. Terminates agent TLS with per-host certificates
|
|
2
2
|
// minted on demand, sees every request through a private stdlib http.Server
|
|
3
3
|
// (so HEAD, 204/304, chunked, keep-alive and slow upstreams just work),
|
|
4
|
-
// forwards with https/http.request, and
|
|
5
|
-
//
|
|
6
|
-
//
|
|
4
|
+
// forwards with https/http.request, and asks a gate about every request
|
|
5
|
+
// (bareguard, one gate per agent; see `gateFor`). When the gate asks, the
|
|
6
|
+
// hold queue is its human channel: the request parks for a human decision.
|
|
7
|
+
// Identity = socket: each agent has its own unix listener, and every log
|
|
8
|
+
// line and hold names the agent, never `c<n>`.
|
|
7
9
|
//
|
|
8
10
|
// Timeout shape: the client idle clock is the server's keep-alive timeout —
|
|
9
11
|
// by construction it only ticks when no request is in flight. The upstream
|
|
10
12
|
// response gets its own much longer clock.
|
|
13
|
+
import crypto from 'node:crypto';
|
|
11
14
|
import net from 'node:net';
|
|
12
15
|
import tls from 'node:tls';
|
|
13
16
|
import http from 'node:http';
|
|
@@ -15,55 +18,40 @@ import https from 'node:https';
|
|
|
15
18
|
import fs from 'node:fs';
|
|
16
19
|
import path from 'node:path';
|
|
17
20
|
import { ensureCA, certFor, HOST_RE } from './certs.js';
|
|
18
|
-
import {
|
|
19
|
-
import {
|
|
21
|
+
import { createCardScanner } from './cardscan.js';
|
|
22
|
+
import { ASK_BODY_LIMIT, DEFAULT_HOLD_MAX_BODY, bodyPreview, createHolds } from './holds.js';
|
|
23
|
+
import { claimRuntime, ensurePrivateDir, runtimePaths } from './runtime.js';
|
|
24
|
+
import { paymentPath, toolFor, buildTools, emptyMatcher } from './policy.js';
|
|
20
25
|
import { checkUpstream } from './wall.js';
|
|
26
|
+
import { Gate } from 'bareguard';
|
|
21
27
|
|
|
22
28
|
const AGENT = Symbol('agent');
|
|
23
29
|
const SECURE = Symbol('secure');
|
|
24
30
|
const IP_RE = /^\d+\.\d+\.\d+\.\d+$/;
|
|
25
31
|
// Hop-by-hop headers must not be forwarded: node's HTTP stack re-frames.
|
|
26
32
|
const HOP_REQ = new Set(['proxy-connection', 'proxy-authorization']);
|
|
33
|
+
// Bodies up to this size are read whole (under the agent's working slot) so
|
|
34
|
+
// the card floor can scan them; a bigger body streams on, unchecked.
|
|
35
|
+
const WORK_BODY_LIMIT = 65536;
|
|
36
|
+
// Small teams: one proxy serves at most this many agents (the TCP door's
|
|
37
|
+
// 'tcp' agent is not counted); more agents means another proxy.
|
|
38
|
+
const MAX_AGENTS = 40;
|
|
39
|
+
const EMPTY = Buffer.alloc(0);
|
|
27
40
|
const HOP_RESP = new Set(['connection', 'keep-alive', 'proxy-authenticate',
|
|
28
41
|
'proxy-authorization', 'te', 'trailer', 'transfer-encoding', 'upgrade']);
|
|
29
42
|
|
|
30
|
-
// Secrets never land in the audit log verbatim: Authorization-style header
|
|
31
|
-
// values are replaced with a fixed marker before an entry is written. The
|
|
32
|
-
// user's `redact` hook runs after this scrubbing, so it sees (and further
|
|
33
|
-
// shapes) an already-safe entry. Bodies stay logged as-is.
|
|
34
|
-
const REDACTED = '[redacted]';
|
|
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']);
|
|
38
|
-
|
|
39
|
-
/**
|
|
40
|
-
* Copy a log entry with sensitive header values replaced by `[redacted]`.
|
|
41
|
-
* The caller's headers object is never mutated.
|
|
42
|
-
*
|
|
43
|
-
* @param {Record<string, unknown>} entry log entry about to be written
|
|
44
|
-
* @returns {Record<string, unknown>} entry with secrets scrubbed
|
|
45
|
-
*/
|
|
46
|
-
function scrubSecrets(entry) {
|
|
47
|
-
const h = entry['headers'];
|
|
48
|
-
if (!h || typeof h !== 'object') return entry;
|
|
49
|
-
const src = /** @type {Record<string, unknown>} */ (h);
|
|
50
|
-
if (!Object.keys(src).some((k) => SENSITIVE_HEADERS.has(k.toLowerCase()))) return entry;
|
|
51
|
-
const headers = { ...src };
|
|
52
|
-
for (const k of Object.keys(headers)) {
|
|
53
|
-
if (SENSITIVE_HEADERS.has(k.toLowerCase())) headers[k] = REDACTED;
|
|
54
|
-
}
|
|
55
|
-
return { ...entry, headers };
|
|
56
|
-
}
|
|
57
|
-
|
|
58
43
|
/**
|
|
59
44
|
* Options for {@link createProxy}.
|
|
60
45
|
*
|
|
61
46
|
* @typedef {object} ProxyOptions
|
|
62
|
-
* @property {string} logFile JSON-lines
|
|
47
|
+
* @property {string} logFile the runtime's one audit file (`runtimePaths(runtime).audit`), in bareguard's JSON-lines shape: every agent's gate and the runtime's own `sbx` gate append to it. barebox's own facts are `annotate` lines (`verdict` = `resp`, `deny`, `hold`, `decide`, `hold-abandoned`, ...); a response status is a `record` line joined to its request's `check` by `aid`.
|
|
63
48
|
* @property {string} runtime runtime dir; required. Holds the CA + minted host certs (`certs/`, see `runtime.js`), the agent sockets, and the hold queue files.
|
|
64
49
|
* @property {number} [port] opt-in TCP listener for tests, bound to 127.0.0.1 only (default: none)
|
|
65
50
|
* @property {string} [upstreamCa] extra PEM the proxy trusts for upstream TLS, on top of system roots
|
|
66
|
-
* @property {
|
|
51
|
+
* @property {(agent: string, ctx: { humanChannel: (event: any) => Promise<{ decision: 'allow' | 'deny', reason?: string }>, tools: Record<string, any> }) => GateLike | Promise<GateLike>} [gateFor] builds the gate that decides one agent's requests (called once per agent, and once for the TCP door's `tcp` agent); `ctx.humanChannel` is the hold queue and `ctx.tools` the runtime's one tools table, both to hand to a bareguard `Gate`. Omit it to forward everything.
|
|
52
|
+
* @property {{ matcher: { match: (method: string, url: string) => { key: string, source: string } }, tools: Record<string, any> }} [labels] the loaded label files (see `loadLabels`); omitted means no labels, only the built-in model endpoints
|
|
53
|
+
* @property {string[]} [allowLocal] exact `host:port` pairs (the `localLlm` setting) that may pass the wall's private/loopback check; any other local destination is still denied
|
|
54
|
+
* @property {HoldOptions} [hold] hold queue config (deadline, caps, ask seam)
|
|
67
55
|
* @property {number} [upstreamTimeoutMs] give up on an upstream response after this (default 120000)
|
|
68
56
|
* @property {object} [unsafeTestOnly] TEST-ONLY escape hatch: everything under
|
|
69
57
|
* it weakens the sandbox wall, so production omits it and tests name it loudly.
|
|
@@ -73,18 +61,22 @@ function scrubSecrets(entry) {
|
|
|
73
61
|
* @property {(host: string) => Promise<string[] | string | null>} [unsafeTestOnly.resolveUpstream]
|
|
74
62
|
* DNS stub: replaces the wall's resolver so rebinding is testable. Production omits it.
|
|
75
63
|
* @property {number} [clientIdleMs] kill a client tunnel idle this long; never fires mid-request (default 60000)
|
|
76
|
-
* @property {
|
|
77
|
-
|
|
64
|
+
* @property {(entry: Record<string, unknown>) => Record<string, unknown>} [redact] log redaction hook, applied after built-in secret scrubbing; its result becomes the `meta` of an `annotate` line (default: identity)
|
|
65
|
+
*/
|
|
66
|
+
|
|
67
|
+
/**
|
|
68
|
+
* Anything with bareguard's `check`: a `Gate`, or a plain object for tests. An
|
|
69
|
+
* `askHuman` outcome from a plain object goes to the same human channel.
|
|
70
|
+
*
|
|
71
|
+
* @typedef {{ check: (action: Record<string, unknown>) => Promise<{ outcome: string, rule?: string, reason?: string | null, aid?: string }>, record?: (action: Record<string, unknown>, result: Record<string, unknown>, opts?: { aid?: string }) => Promise<void>, annotate?: (fact: Record<string, unknown>) => Promise<void>, drainAnnotations?: () => unknown[] }} GateLike
|
|
78
72
|
*/
|
|
79
73
|
|
|
80
74
|
/**
|
|
81
|
-
* Hold queue options (the
|
|
75
|
+
* Hold queue options (the queue lives in holds.js).
|
|
82
76
|
*
|
|
83
77
|
* @typedef {object} HoldOptions
|
|
84
|
-
* @property {string} [match] path substring that parks a request (default decision)
|
|
85
|
-
* @property {import('./holds.js').ShouldHold} [shouldHold] decision function; overrides `match`
|
|
86
78
|
* @property {number|string} [timeoutMs] hold deadline in ms, or `'never'` (default 120000)
|
|
87
|
-
* @property {number} [maxBody] bodies over this are denied at the door, never queued (default
|
|
79
|
+
* @property {number} [maxBody] bodies over this are denied at the door, never queued; held bodies spool to `<runtime>/held` (default 52428800)
|
|
88
80
|
* @property {import('./holds.js').OnAsk|null} [onAsk] ask seam (bareguard `humanChannel` shape).
|
|
89
81
|
* When present no files are involved; omit it for the default file checkpoint
|
|
90
82
|
* (`<runtime>/asks` + `<runtime>/answers`, `sbx pending/approve/deny`).
|
|
@@ -100,9 +92,11 @@ function scrubSecrets(entry) {
|
|
|
100
92
|
* @property {string} method HTTP method
|
|
101
93
|
* @property {string} url full URL
|
|
102
94
|
* @property {Record<string, string | string[] | undefined>} headers
|
|
103
|
-
* @property {Buffer} [body] buffered body
|
|
104
|
-
* @property {
|
|
95
|
+
* @property {Buffer} [body] buffered body
|
|
96
|
+
* @property {Buffer} [prefix] bytes already read from `stream`, written upstream before it
|
|
97
|
+
* @property {import('node:stream').Readable} [stream] live body: the request itself, or a held body's file
|
|
105
98
|
* @property {import('node:http').ServerResponse} cres parked or live client response
|
|
99
|
+
* @property {{ gate: GateLike, action: Record<string, unknown>, aid: string }} [rec] the deciding gate, the request's action and the decision's aid: the response status is recorded there (absent: it is logged as a `resp` fact)
|
|
106
100
|
*/
|
|
107
101
|
|
|
108
102
|
/**
|
|
@@ -112,14 +106,13 @@ function scrubSecrets(entry) {
|
|
|
112
106
|
*/
|
|
113
107
|
|
|
114
108
|
/**
|
|
115
|
-
* Start the front-door proxy. Every request is
|
|
116
|
-
* headers and body; bytes go upstream untouched. Requests the hold rule
|
|
109
|
+
* Start the front-door proxy. Every request is audited with its method and URL, and a request with a body also with its byte count and SHA-256 (never headers or body text); bytes go upstream untouched. Requests the hold rule
|
|
117
110
|
* flags park for a human decision instead of forwarding.
|
|
118
111
|
*
|
|
119
112
|
* @param {ProxyOptions} opts
|
|
120
113
|
* @returns live proxy: `ready` resolves when listeners + CA are up; the shape is inferred, see `Proxy`
|
|
121
114
|
* @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.
|
|
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.
|
|
115
|
+
* @fails Throws synchronously on a missing or unopenable `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.
|
|
123
116
|
* @example
|
|
124
117
|
* import { createProxy } from "barebox";
|
|
125
118
|
* const proxy = createProxy({ port: 0, runtime: "./sbx-runtime", logFile: "./mitm.log" });
|
|
@@ -128,12 +121,20 @@ function scrubSecrets(entry) {
|
|
|
128
121
|
*/
|
|
129
122
|
export function createProxy(opts) {
|
|
130
123
|
const { logFile, runtime, port = null,
|
|
131
|
-
upstreamCa = null, hold = null,
|
|
124
|
+
upstreamCa = null, hold = null, gateFor = null, allowLocal = [], labels = null,
|
|
132
125
|
upstreamTimeoutMs = 120000, clientIdleMs = 60000,
|
|
133
126
|
unsafeTestOnly = null,
|
|
134
|
-
|
|
127
|
+
redact = (e) => e } = opts ?? {};
|
|
135
128
|
const { allowLoopback = false, resolveUpstream = null } = unsafeTestOnly ?? {};
|
|
136
|
-
const gate = {
|
|
129
|
+
const gate = {
|
|
130
|
+
allowLoopback, resolveUpstream: resolveUpstream ?? undefined,
|
|
131
|
+
allowLocal: new Set(allowLocal.map((e) => String(e).toLowerCase())),
|
|
132
|
+
};
|
|
133
|
+
/** @param {URL} u @returns {number} */
|
|
134
|
+
const portOf = (u) => (u.port ? parseInt(u.port, 10) : (u.protocol === 'https:' ? 443 : 80));
|
|
135
|
+
// One tools table and one matcher per runtime, shared by every gate.
|
|
136
|
+
const matcher = labels?.matcher ?? emptyMatcher;
|
|
137
|
+
const tools = buildTools(labels?.tools, [...allowLocal]);
|
|
137
138
|
if (!logFile) throw new Error('createProxy: logFile is required');
|
|
138
139
|
if (typeof runtime !== 'string' || !runtime) throw new Error('createProxy: runtime is required');
|
|
139
140
|
// One live proxy per runtime, enforced here: claimed before the hold
|
|
@@ -143,14 +144,95 @@ export function createProxy(opts) {
|
|
|
143
144
|
// Always `<runtime>/certs`: one layout, owned by runtime.js, so there is
|
|
144
145
|
// nothing to contain and no check to fail.
|
|
145
146
|
const certDir = runtimePaths(runtime).certsDir;
|
|
146
|
-
const holdMaxBody = hold?.maxBody ??
|
|
147
|
+
const holdMaxBody = hold?.maxBody ?? DEFAULT_HOLD_MAX_BODY;
|
|
148
|
+
const heldFile = runtimePaths(runtime).heldFile;
|
|
147
149
|
|
|
148
|
-
|
|
149
|
-
//
|
|
150
|
-
//
|
|
151
|
-
|
|
150
|
+
// Open the audit file synchronously: a bad `logFile` (a directory, a
|
|
151
|
+
// missing parent, no permission) throws here, where the claim can still
|
|
152
|
+
// be released — not later as an uncaught error. bareguard appends to it.
|
|
153
|
+
try {
|
|
154
|
+
fs.closeSync(fs.openSync(logFile, 'a', 0o600));
|
|
155
|
+
} catch (e) {
|
|
156
|
+
const msg = e instanceof Error ? e.message : String(e);
|
|
157
|
+
releaseClaim();
|
|
158
|
+
throw new Error(`createProxy: cannot open logFile ${logFile}: ${msg}`);
|
|
159
|
+
}
|
|
160
|
+
// `openSync`'s mode is masked by the umask and doesn't apply to an
|
|
161
|
+
// existing file: a 0644 log from an older run would stay world-readable
|
|
162
|
+
// while new lines append, so fix it up on every start.
|
|
152
163
|
try { fs.chmodSync(logFile, 0o600); } catch {}
|
|
153
|
-
|
|
164
|
+
|
|
165
|
+
// The audit file has one shape: bareguard's. A response status is a
|
|
166
|
+
// `gate.record` joined to its request's `check` by aid; every other fact is
|
|
167
|
+
// an `annotate({ surface: false })` on the agent's gate when it is built, else
|
|
168
|
+
// on the runtime's own `sbx` gate (which never runs `check()`).
|
|
169
|
+
/** @type {GateLike} */
|
|
170
|
+
let sbxGate;
|
|
171
|
+
try {
|
|
172
|
+
sbxGate = /** @type {GateLike} */ (/** @type {unknown} */ (new Gate({ audit: { path: logFile } })));
|
|
173
|
+
} catch (e) {
|
|
174
|
+
releaseClaim();
|
|
175
|
+
throw e;
|
|
176
|
+
}
|
|
177
|
+
const sbxInit = /** @type {{ init: () => Promise<void> }} */ (/** @type {unknown} */ (sbxGate)).init();
|
|
178
|
+
sbxInit.catch(() => {}); // reported by the first line that awaits it
|
|
179
|
+
/** Gates by agent: the only place a gate is kept (see `gateOf`). @type {Map<string, { p: Promise<GateLike>, gate: GateLike|null }>} */
|
|
180
|
+
const gates = new Map();
|
|
181
|
+
/** @type {Set<Promise<void>>} */
|
|
182
|
+
const pendingLog = new Set();
|
|
183
|
+
let logClosing = false;
|
|
184
|
+
let logFailed = false;
|
|
185
|
+
/** @param {unknown} e */
|
|
186
|
+
const logFail = (e) => {
|
|
187
|
+
if (logFailed) return;
|
|
188
|
+
logFailed = true;
|
|
189
|
+
console.error(`sbx: audit log ${logFile} write failed: ${e instanceof Error ? e.message : String(e)}`);
|
|
190
|
+
};
|
|
191
|
+
/** Track one audit write; a failure is reported once, never thrown. @param {() => Promise<unknown>} fn */
|
|
192
|
+
const track = (fn) => {
|
|
193
|
+
// After close() ends the flush a late line (a socket torn down by close)
|
|
194
|
+
// is dropped on purpose: a write nobody waits for would wedge close().
|
|
195
|
+
if (logClosing) return;
|
|
196
|
+
const p = fn().then(() => {}, logFail).then(() => { pendingLog.delete(p); });
|
|
197
|
+
pendingLog.add(p);
|
|
198
|
+
};
|
|
199
|
+
/** Cut a string field. @param {unknown} v @param {number} n */
|
|
200
|
+
const cut = (v, n) => (typeof v === 'string' ? v.slice(0, n) : v);
|
|
201
|
+
/**
|
|
202
|
+
* barebox's fact as the `meta` of an annotate. The per-field cuts keep audit
|
|
203
|
+
* lines short; bareguard 0.30.0 drops whole keys over its own cap.
|
|
204
|
+
* @param {Record<string, unknown>} o
|
|
205
|
+
* @returns {Record<string, unknown>}
|
|
206
|
+
*/
|
|
207
|
+
const metaOf = (o) => {
|
|
208
|
+
const { ev: _ev, ...meta } = redact(o);
|
|
209
|
+
meta['url'] = cut(meta['url'], 400);
|
|
210
|
+
meta['note'] = cut(meta['note'], 200);
|
|
211
|
+
meta['reason'] = cut(meta['reason'], 200);
|
|
212
|
+
return meta;
|
|
213
|
+
};
|
|
214
|
+
/** @param {Record<string, unknown>} o */
|
|
215
|
+
async function writeLog(o) {
|
|
216
|
+
const agent = typeof o['agent'] === 'string' ? o['agent'] : null;
|
|
217
|
+
// Never build a gate from here: a built one, else the sbx gate.
|
|
218
|
+
const entry = agent ? gates.get(agent) : undefined;
|
|
219
|
+
const cand = entry?.gate ?? null;
|
|
220
|
+
const g = cand && typeof cand.annotate === 'function' ? cand : sbxGate;
|
|
221
|
+
if (g === sbxGate) await sbxInit;
|
|
222
|
+
const where = [o['id'], o['agent'], o['code'], o['method'], o['url'] ?? o['note']]
|
|
223
|
+
.filter((x) => x !== undefined && x !== null).join(' ');
|
|
224
|
+
try {
|
|
225
|
+
await /** @type {NonNullable<GateLike['annotate']>} */ (g.annotate)({
|
|
226
|
+
surface: false, verdict: String(o['ev']), where, meta: metaOf(o) });
|
|
227
|
+
} finally {
|
|
228
|
+
// Normal use of bareguard's API for a process with no turns: it keeps memory at zero facts
|
|
229
|
+
// (0.30.0 caps the buffer at 256, which could reach about 350 KB per gate). No upstream ask is pending.
|
|
230
|
+
g.drainAnnotations?.();
|
|
231
|
+
}
|
|
232
|
+
}
|
|
233
|
+
// Synchronous for callers (holds.js shares it); the write is tracked.
|
|
234
|
+
/** @param {Record<string, unknown>} o */
|
|
235
|
+
const log = (o) => { track(() => writeLog(o)); };
|
|
154
236
|
let trust = null;
|
|
155
237
|
if (upstreamCa) {
|
|
156
238
|
let extra;
|
|
@@ -196,18 +278,29 @@ export function createProxy(opts) {
|
|
|
196
278
|
// Enforcement sits here (every forward, incl. the approve path) AND at
|
|
197
279
|
// the door (request handler + CONNECT): a parked hold is re-checked on
|
|
198
280
|
// approve, so a DNS change while parked cannot slip through.
|
|
281
|
+
// A body stream nobody will pipe: a held file is closed (its owner then
|
|
282
|
+
// deletes it); a live request is drained so its response can go out.
|
|
283
|
+
/** @param {import('node:stream').Readable|undefined} stream */
|
|
284
|
+
function discard(stream) {
|
|
285
|
+
try {
|
|
286
|
+
if (stream instanceof fs.ReadStream) stream.destroy();
|
|
287
|
+
else stream?.resume();
|
|
288
|
+
} catch {}
|
|
289
|
+
}
|
|
290
|
+
|
|
199
291
|
/** @param {ForwardArgs} args */
|
|
200
|
-
async function forward({ agent, method, url, headers, body, stream, cres }) {
|
|
292
|
+
async function forward({ agent, method, url, headers, body, prefix, stream, cres, rec }) {
|
|
201
293
|
let u;
|
|
202
294
|
try {
|
|
203
295
|
u = new URL(url);
|
|
204
296
|
} catch {
|
|
297
|
+
discard(stream);
|
|
205
298
|
denyRes(cres, 400, 'bad request target');
|
|
206
299
|
return;
|
|
207
300
|
}
|
|
208
|
-
const verdict = await checkUpstream(u.hostname, gate);
|
|
301
|
+
const verdict = await checkUpstream(u.hostname, gate, portOf(u));
|
|
209
302
|
if (!verdict.ok) {
|
|
210
|
-
|
|
303
|
+
discard(stream);
|
|
211
304
|
denyRes(cres, 403, verdict.reason);
|
|
212
305
|
return;
|
|
213
306
|
}
|
|
@@ -215,19 +308,19 @@ export function createProxy(opts) {
|
|
|
215
308
|
// throw before it can answer must still be loud, never a floating reject.
|
|
216
309
|
// The dial is pinned to the checked IPs: no second DNS resolution.
|
|
217
310
|
try {
|
|
218
|
-
forwardInner({ agent, method, url, headers, body, stream, cres, u, upstreamIps: verdict.ips });
|
|
311
|
+
forwardInner({ agent, method, url, headers, body, prefix, stream, cres, rec, u, upstreamIps: verdict.ips });
|
|
219
312
|
} catch (e) {
|
|
220
313
|
// The live stream arrives paused (see handleRequest): unpause so no
|
|
221
314
|
// paused stream leaks on this path.
|
|
222
|
-
|
|
315
|
+
discard(stream);
|
|
223
316
|
denyRes(cres, 502, `upstream failed: ${e.message}`);
|
|
224
317
|
}
|
|
225
318
|
}
|
|
226
319
|
|
|
227
320
|
/** @param {ForwardArgs & { u: URL, upstreamIps: string[] }} args */
|
|
228
|
-
function forwardInner({ agent, method, url, headers, body, stream, cres, u, upstreamIps }) {
|
|
321
|
+
function forwardInner({ agent, method, url, headers, body, prefix, stream, cres, rec, u, upstreamIps }) {
|
|
229
322
|
const sock = cres.socket;
|
|
230
|
-
if (!sock) return; // no transport left to answer on
|
|
323
|
+
if (!sock) { discard(stream); return; } // no transport left to answer on
|
|
231
324
|
const secure = u.protocol === 'https:';
|
|
232
325
|
/** @type {Record<string, string | string[] | undefined>} */
|
|
233
326
|
const fwdHeaders = {};
|
|
@@ -280,7 +373,11 @@ export function createProxy(opts) {
|
|
|
280
373
|
if (!HOP_RESP.has(k.toLowerCase()) && v !== undefined) respHeaders[k] = v;
|
|
281
374
|
}
|
|
282
375
|
if (ures.statusCode === undefined) { fail('upstream sent no status'); up.destroy(); return; }
|
|
283
|
-
|
|
376
|
+
const status = ures.statusCode;
|
|
377
|
+
if (rec && typeof rec.gate.record === 'function') {
|
|
378
|
+
const { gate: g, action, aid } = rec;
|
|
379
|
+
track(() => /** @type {NonNullable<GateLike['record']>} */ (g.record)(action, { status }, { aid }));
|
|
380
|
+
} else log({ ev: 'resp', agent, url, status });
|
|
284
381
|
try {
|
|
285
382
|
cres.writeHead(ures.statusCode, respHeaders);
|
|
286
383
|
} catch (e) { fail(`cannot frame upstream response: ${e.message}`); up.destroy(); return; }
|
|
@@ -298,28 +395,36 @@ export function createProxy(opts) {
|
|
|
298
395
|
if (!done && !cres.writableEnded) { done = true; upstreams.delete(up); up.destroy(); }
|
|
299
396
|
});
|
|
300
397
|
if (body) up.end(body);
|
|
301
|
-
else if (stream)
|
|
302
|
-
|
|
398
|
+
else if (stream) {
|
|
399
|
+
// A held body's file: closed when the request is done with it, and a
|
|
400
|
+
// read failure (the file vanished) fails the request, never crashes.
|
|
401
|
+
if (stream instanceof fs.ReadStream) {
|
|
402
|
+
up.once('close', () => stream.destroy());
|
|
403
|
+
stream.once('error', (e) => up.destroy(e));
|
|
404
|
+
}
|
|
405
|
+
if (prefix?.length) up.write(prefix);
|
|
406
|
+
stream.pipe(up);
|
|
407
|
+
} else up.end();
|
|
303
408
|
}
|
|
304
409
|
|
|
305
410
|
// The rest of setup is infallible synchronously except this call, so a
|
|
306
411
|
// throw here releases the claim before it propagates (like upstreamCa
|
|
307
412
|
// above); async failures release through `ready` and `close()` below.
|
|
413
|
+
// The queue is the gate's human channel, so a gate means a queue.
|
|
308
414
|
let holds = null;
|
|
309
415
|
try {
|
|
310
|
-
holds = hold ? createHolds({
|
|
416
|
+
holds = (hold || gateFor) ? createHolds({
|
|
311
417
|
log,
|
|
312
|
-
|
|
313
|
-
match: hold.match,
|
|
314
|
-
timeoutMs: hold.timeoutMs,
|
|
418
|
+
timeoutMs: hold?.timeoutMs,
|
|
315
419
|
maxBody: holdMaxBody,
|
|
316
420
|
runtime,
|
|
317
|
-
onAsk: hold
|
|
318
|
-
pollMs: hold
|
|
319
|
-
onEvent: hold
|
|
320
|
-
|
|
321
|
-
|
|
322
|
-
|
|
421
|
+
onAsk: hold?.onAsk,
|
|
422
|
+
pollMs: hold?.pollMs,
|
|
423
|
+
onEvent: hold?.onEvent,
|
|
424
|
+
// A parked request's pending ask ends here: handleRequest, awaiting
|
|
425
|
+
// its gate, then forwards or refuses.
|
|
426
|
+
onApprove: (h) => h.finish({ decision: 'allow' }),
|
|
427
|
+
onDeny: (h, reason) => h.finish({ decision: 'deny', reason }),
|
|
323
428
|
}) : null;
|
|
324
429
|
} catch (e) {
|
|
325
430
|
releaseClaim();
|
|
@@ -329,9 +434,208 @@ export function createProxy(opts) {
|
|
|
329
434
|
const server = http.createServer((creq, cres) => {
|
|
330
435
|
// Async only for the wall's DNS lookup; no body listener is attached
|
|
331
436
|
// before the check, so nothing is lost while it resolves.
|
|
332
|
-
|
|
437
|
+
reqDone.set(creq, handleRequest(creq, cres)
|
|
438
|
+
.catch((e) => denyRes(cres, 500, `proxy failed: ${e.message}`)));
|
|
333
439
|
});
|
|
334
440
|
|
|
441
|
+
/** Each request's handler promise, so `close()` can wait for those inside a gate check. @type {WeakMap<object, Promise<void>>} */
|
|
442
|
+
const reqDone = new WeakMap();
|
|
443
|
+
|
|
444
|
+
/**
|
|
445
|
+
* Gates by agent, built lazily (and at `addAgent`): one per agent, so the
|
|
446
|
+
* grant is the agent's own. `gates` (declared with the log) is the only
|
|
447
|
+
* place a gate is kept; `entry.gate` is set once the build settled.
|
|
448
|
+
*
|
|
449
|
+
* @param {string} agent
|
|
450
|
+
* @returns {Promise<GateLike>}
|
|
451
|
+
*/
|
|
452
|
+
function gateOf(agent) {
|
|
453
|
+
let e = gates.get(agent);
|
|
454
|
+
if (!e) {
|
|
455
|
+
if (!gateFor) throw new Error('createProxy: no gateFor');
|
|
456
|
+
const p = Promise.resolve().then(() => gateFor(agent, { humanChannel: askHuman, tools }));
|
|
457
|
+
const entry = { p, gate: /** @type {GateLike|null} */ (null) };
|
|
458
|
+
e = entry;
|
|
459
|
+
gates.set(agent, entry);
|
|
460
|
+
p.then((g) => { entry.gate = g; },
|
|
461
|
+
// A failed build must not stick: the next request tries again, loudly.
|
|
462
|
+
() => { if (gates.get(agent) === entry) gates.delete(agent); });
|
|
463
|
+
}
|
|
464
|
+
return e.p;
|
|
465
|
+
}
|
|
466
|
+
|
|
467
|
+
/**
|
|
468
|
+
* Requests inside `gate.check()`, by `rid`: how the human channel finds
|
|
469
|
+
* the request an ask is about. handleRequest sets and deletes each entry
|
|
470
|
+
* (the one writer); the channel only reads it and sets the fields it owns
|
|
471
|
+
* (`asked`, `status`, `heldId`, `endAsk`).
|
|
472
|
+
*
|
|
473
|
+
* @type {Map<string, RequestCtx>}
|
|
474
|
+
*/
|
|
475
|
+
const inflightCtx = new Map();
|
|
476
|
+
let ridN = 0;
|
|
477
|
+
|
|
478
|
+
/**
|
|
479
|
+
* @typedef {object} RequestCtx
|
|
480
|
+
* @property {string} agent agent name
|
|
481
|
+
* @property {string} method HTTP method
|
|
482
|
+
* @property {string} url full URL
|
|
483
|
+
* @property {Record<string, string | string[] | undefined>} headers request headers
|
|
484
|
+
* @property {import('node:http').IncomingMessage} creq the request (paused)
|
|
485
|
+
* @property {import('node:http').ServerResponse} cres the response
|
|
486
|
+
* @property {ReturnType<typeof makeTee>} tee the body tee (masked preview, byte count)
|
|
487
|
+
* @property {boolean} hasBody the request carries a body
|
|
488
|
+
* @property {Buffer[]} chunks the body bytes read so far (up to ~64 KB)
|
|
489
|
+
* @property {boolean} over more body follows `chunks`, unread in `creq`
|
|
490
|
+
* @property {() => void} freeWork release the agent's working slot (idempotent)
|
|
491
|
+
* @property {boolean} asked the human channel took this request
|
|
492
|
+
* @property {number|null} status HTTP status the channel wants for a denial (null: 403)
|
|
493
|
+
* @property {string|null} heldId id of the held body file, once spooled
|
|
494
|
+
* @property {((reason: string) => void)|null} endAsk end a not-yet-parked ask as a denial
|
|
495
|
+
*/
|
|
496
|
+
|
|
497
|
+
/**
|
|
498
|
+
* The human channel (bareguard `humanChannel` shape): every gate's asks
|
|
499
|
+
* come here. Finds the request by `event.action.rid`, then holds it.
|
|
500
|
+
*
|
|
501
|
+
* @param {{ action?: { rid?: unknown }, rule?: string, rwxLetter?: string }} event
|
|
502
|
+
* @returns {Promise<{ decision: 'allow' | 'deny', reason?: string }>}
|
|
503
|
+
*/
|
|
504
|
+
async function askHuman(event) {
|
|
505
|
+
const ctx = inflightCtx.get(String(event?.action?.rid));
|
|
506
|
+
if (!ctx) return { decision: 'deny', reason: 'request gone' };
|
|
507
|
+
ctx.asked = true;
|
|
508
|
+
return holdRequest(ctx, event);
|
|
509
|
+
}
|
|
510
|
+
|
|
511
|
+
/**
|
|
512
|
+
* Hold one request for the human: reserve the agent's hold slot, spool the
|
|
513
|
+
* body to `<runtime>/held/<id>` (the bytes already read plus the rest of
|
|
514
|
+
* the stream, capped at `holdMaxBody`), free the working slot, park, and
|
|
515
|
+
* wait. The promise settles once: on the queue's decision, on expiry, or
|
|
516
|
+
* when the client or the proxy goes away first.
|
|
517
|
+
*
|
|
518
|
+
* @param {RequestCtx} ctx the request
|
|
519
|
+
* @param {{ rule?: string, rwxLetter?: string }} event the gate's ask
|
|
520
|
+
* @returns {Promise<{ decision: 'allow' | 'deny', reason?: string }>}
|
|
521
|
+
*/
|
|
522
|
+
function holdRequest(ctx, event) {
|
|
523
|
+
return new Promise((resolve) => {
|
|
524
|
+
const queue = /** @type {NonNullable<typeof holds>} */ (holds);
|
|
525
|
+
const { agent, cres, creq } = ctx;
|
|
526
|
+
const sock = cres.socket;
|
|
527
|
+
let settled = false;
|
|
528
|
+
let parked = false;
|
|
529
|
+
let dead = false;
|
|
530
|
+
/** @type {import('node:fs').WriteStream|null} */
|
|
531
|
+
let ws = null;
|
|
532
|
+
/** @param {{ decision: 'allow' | 'deny', reason?: string }} d */
|
|
533
|
+
const finish = (d) => {
|
|
534
|
+
if (settled) return;
|
|
535
|
+
settled = true;
|
|
536
|
+
ctx.endAsk = null;
|
|
537
|
+
resolve(d);
|
|
538
|
+
};
|
|
539
|
+
/** @param {string} reason @param {number} [status] */
|
|
540
|
+
const refuse = (reason, status) => {
|
|
541
|
+
if (status) ctx.status = status;
|
|
542
|
+
finish({ decision: 'deny', reason });
|
|
543
|
+
};
|
|
544
|
+
const abort = () => {
|
|
545
|
+
if (dead) return;
|
|
546
|
+
dead = true;
|
|
547
|
+
ws?.destroy();
|
|
548
|
+
queue.dropBody(slot.id);
|
|
549
|
+
};
|
|
550
|
+
/** @param {string} why @param {number} [status] */
|
|
551
|
+
const fail = (why, status) => {
|
|
552
|
+
if (parked) return; // parked: the queue owns the end
|
|
553
|
+
abort();
|
|
554
|
+
slot.cancel();
|
|
555
|
+
refuse(why, status);
|
|
556
|
+
};
|
|
557
|
+
if (closed) { refuse('proxy closing'); return; }
|
|
558
|
+
if (!sock || sock.destroyed) { refuse('client gone'); return; }
|
|
559
|
+
const slot = queue.reserve(agent, {
|
|
560
|
+
onReady: () => stream(),
|
|
561
|
+
onExpire: (why) => { abort(); refuse(why); },
|
|
562
|
+
});
|
|
563
|
+
if (slot.state === 'full') { ctx.freeWork(); refuse('hold queue full', 429); return; }
|
|
564
|
+
ctx.endAsk = (why) => fail(why);
|
|
565
|
+
cres.on('close', () => ctx.endAsk?.('client gone'));
|
|
566
|
+
let size = 0;
|
|
567
|
+
if (ctx.hasBody) {
|
|
568
|
+
// The bytes already read go to the body file at once, so a request
|
|
569
|
+
// waiting in line holds no body in memory.
|
|
570
|
+
try {
|
|
571
|
+
// Open synchronously: a later unlink can then never race the create.
|
|
572
|
+
ws = fs.createWriteStream('', { fd: fs.openSync(heldFile(slot.id), 'wx', 0o600) });
|
|
573
|
+
} catch (e) {
|
|
574
|
+
fail(`cannot hold body: ${e instanceof Error ? e.message : String(e)}`, 500);
|
|
575
|
+
ctx.freeWork();
|
|
576
|
+
return;
|
|
577
|
+
}
|
|
578
|
+
ws.on('error', (e) => fail(`cannot hold body: ${e.message}`, 500));
|
|
579
|
+
for (const c of ctx.chunks) {
|
|
580
|
+
size += c.length;
|
|
581
|
+
ws.write(c);
|
|
582
|
+
}
|
|
583
|
+
ctx.chunks = [];
|
|
584
|
+
ctx.heldId = slot.id;
|
|
585
|
+
if (size > holdMaxBody) fail('body too large to hold');
|
|
586
|
+
}
|
|
587
|
+
// The working slot is released: a queued hold must not stop the
|
|
588
|
+
// agent's next body from being read.
|
|
589
|
+
ctx.freeWork();
|
|
590
|
+
if (slot.state === 'now') stream();
|
|
591
|
+
|
|
592
|
+
// At the front of the line: take the rest of the body, then park.
|
|
593
|
+
function stream() {
|
|
594
|
+
if (settled || dead) return;
|
|
595
|
+
const parkIt = () => {
|
|
596
|
+
if (dead || settled) return;
|
|
597
|
+
// Parked: the tunnel stays open until the ask channel decides.
|
|
598
|
+
// null: the reservation already expired and onExpire refused.
|
|
599
|
+
parked = queue.add({ agent, method: ctx.method, url: ctx.url,
|
|
600
|
+
preview: bodyPreview(ctx.tee.head), bodyBytes: ctx.tee.bytes,
|
|
601
|
+
sock, note: event.rule ?? 'ask', letter: event.rwxLetter, finish,
|
|
602
|
+
slot, arrivedAt: slot.arrivedAt }) !== null;
|
|
603
|
+
};
|
|
604
|
+
const done = () => { if (ws) { ws.once('finish', parkIt); ws.end(); } else parkIt(); };
|
|
605
|
+
if (!ctx.over) { done(); return; }
|
|
606
|
+
creq.on('data', (c) => {
|
|
607
|
+
if (dead) return;
|
|
608
|
+
size += c.length;
|
|
609
|
+
if (size > holdMaxBody) { fail('body too large to hold'); return; }
|
|
610
|
+
if (ws && !ws.write(c)) {
|
|
611
|
+
creq.pause();
|
|
612
|
+
ws.once('drain', () => creq.resume());
|
|
613
|
+
}
|
|
614
|
+
});
|
|
615
|
+
creq.on('error', () => { fail('client body failed', 502); });
|
|
616
|
+
creq.on('end', () => { if (!dead) done(); });
|
|
617
|
+
creq.resume();
|
|
618
|
+
}
|
|
619
|
+
});
|
|
620
|
+
}
|
|
621
|
+
|
|
622
|
+
/**
|
|
623
|
+
* The one decision for a request: the gate's `check`, and, for a plain
|
|
624
|
+
* check object that answers `askHuman`, the same human channel.
|
|
625
|
+
*
|
|
626
|
+
* @param {GateLike} g the agent's gate
|
|
627
|
+
* @param {Record<string, unknown>} action the request as an action
|
|
628
|
+
* @returns {Promise<{ outcome: string, rule?: string, reason?: string | null, aid?: string }>} terminal allow or deny
|
|
629
|
+
*/
|
|
630
|
+
async function decideAction(g, action) {
|
|
631
|
+
const d = await g.check(action);
|
|
632
|
+
if (d.outcome !== 'askHuman') return d;
|
|
633
|
+
const h = await askHuman({ action, rule: d.rule });
|
|
634
|
+
return h.decision === 'allow'
|
|
635
|
+
? { outcome: 'allow', rule: 'humanChannel.allow', aid: d.aid }
|
|
636
|
+
: { outcome: 'deny', rule: d.rule, reason: h.reason ?? 'denied', aid: d.aid };
|
|
637
|
+
}
|
|
638
|
+
|
|
335
639
|
async function handleRequest(creq, cres) {
|
|
336
640
|
const sock = creq.socket;
|
|
337
641
|
const agent = agentOf(sock);
|
|
@@ -349,60 +653,186 @@ export function createProxy(opts) {
|
|
|
349
653
|
const method = creq.method;
|
|
350
654
|
if (!method) { denyRes(cres, 400, 'bad request method'); return; }
|
|
351
655
|
const urlStr = url.toString();
|
|
352
|
-
const verdict = await checkUpstream(url.hostname, gate);
|
|
656
|
+
const verdict = await checkUpstream(url.hostname, gate, portOf(url));
|
|
353
657
|
if (!verdict.ok) {
|
|
354
658
|
try { creq.resume(); } catch {}
|
|
355
659
|
denyRes(cres, 403, verdict.reason);
|
|
356
660
|
return;
|
|
357
661
|
}
|
|
358
|
-
const
|
|
359
|
-
const
|
|
360
|
-
|
|
361
|
-
//
|
|
362
|
-
//
|
|
363
|
-
//
|
|
364
|
-
|
|
365
|
-
|
|
366
|
-
|
|
367
|
-
|
|
368
|
-
|
|
369
|
-
|
|
370
|
-
|
|
371
|
-
|
|
372
|
-
|
|
373
|
-
|
|
374
|
-
|
|
375
|
-
|
|
376
|
-
|
|
377
|
-
|
|
378
|
-
|
|
379
|
-
|
|
380
|
-
// so both the tee and upstream see the whole body.
|
|
381
|
-
creq.pause();
|
|
382
|
-
creq.on('data', (c) => {
|
|
383
|
-
size += c.length;
|
|
384
|
-
if (size > maxLogBody || over) { over = true; return; }
|
|
385
|
-
chunks.push(c);
|
|
386
|
-
});
|
|
387
|
-
creq.on('end', finishLog);
|
|
388
|
-
creq.on('error', () => {});
|
|
389
|
-
forward({ agent, method, url: urlStr,
|
|
390
|
-
headers: { ...creq.headers }, stream: creq, cres });
|
|
662
|
+
const cl = Number(creq.headers['content-length'] ?? 0);
|
|
663
|
+
const hasBody = creq.headers['transfer-encoding'] !== undefined || cl > 0;
|
|
664
|
+
|
|
665
|
+
// Pause before any body listener: a listener would put the stream in
|
|
666
|
+
// flowing mode and starve whoever reads it next. The tee sees every body
|
|
667
|
+
// byte once, whatever path reads it, and feeds the ask (a masked
|
|
668
|
+
// 4 KB preview) and the audit's `body` fact (byte count and SHA-256).
|
|
669
|
+
creq.pause();
|
|
670
|
+
const tee = makeTee();
|
|
671
|
+
creq.on('data', (c) => tee.push(c));
|
|
672
|
+
// `end` fires once the whole body was read, whichever path read it (also
|
|
673
|
+
// a streamed body past 64 KB), so the values cover all of it. A client
|
|
674
|
+
// that aborts mid-body never reaches `end`: no line, as before.
|
|
675
|
+
const rid = `r${++ridN}`;
|
|
676
|
+
if (hasBody) {
|
|
677
|
+
creq.on('end', () => log({ ev: 'body', agent, rid, bodyBytes: tee.bytes, bodySha256: tee.digest() }));
|
|
678
|
+
}
|
|
679
|
+
creq.on('error', () => {});
|
|
680
|
+
|
|
681
|
+
// No gate: straight through. pipe() resumes the flow.
|
|
682
|
+
if (!gateFor) {
|
|
683
|
+
forward({ agent, method, url: urlStr, headers: { ...creq.headers }, stream: creq, cres });
|
|
391
684
|
return;
|
|
392
685
|
}
|
|
393
|
-
|
|
394
|
-
|
|
395
|
-
|
|
396
|
-
|
|
397
|
-
|
|
398
|
-
|
|
399
|
-
|
|
400
|
-
|
|
401
|
-
|
|
402
|
-
|
|
403
|
-
|
|
404
|
-
|
|
405
|
-
|
|
686
|
+
|
|
687
|
+
// One decision path. A body is read first (one body at a time per agent,
|
|
688
|
+
// up to 64 KB, so the card floor can scan it); then the agent's gate
|
|
689
|
+
// decides; a gate that asks runs the human channel inside `check()`.
|
|
690
|
+
let freed = false;
|
|
691
|
+
/** @type {() => void} */
|
|
692
|
+
let free = () => {};
|
|
693
|
+
const freeWork = () => { if (!freed) { freed = true; free(); } };
|
|
694
|
+
try {
|
|
695
|
+
if (hasBody) {
|
|
696
|
+
free = await takeWorkSlot(agent, cres);
|
|
697
|
+
} else creq.resume();
|
|
698
|
+
if (sock.destroyed) return;
|
|
699
|
+
/** @type {RequestCtx} */
|
|
700
|
+
const ctx = { agent, method, url: urlStr, headers: { ...creq.headers }, creq, cres, tee,
|
|
701
|
+
hasBody, chunks: [], over: false, freeWork, asked: false, status: null, heldId: null,
|
|
702
|
+
endAsk: null };
|
|
703
|
+
let cardLike = false;
|
|
704
|
+
if (hasBody) {
|
|
705
|
+
if (await readWorkBody(ctx)) return;
|
|
706
|
+
// Past 64 KB the body streams on unscanned (known gap).
|
|
707
|
+
if (!ctx.over) cardLike = createCardScanner().push(Buffer.concat(ctx.chunks));
|
|
708
|
+
}
|
|
709
|
+
// The body never goes in the action: bareguard writes the action to its audit file.
|
|
710
|
+
const action = { type: 'net', tool: toolFor(matcher, tools, method, urlStr), url: urlStr, method, agent,
|
|
711
|
+
cardLike, paymentPath: paymentPath(urlStr), rid };
|
|
712
|
+
inflightCtx.set(rid, ctx);
|
|
713
|
+
const g = await gateOf(agent);
|
|
714
|
+
const d = await decideAction(g, action);
|
|
715
|
+
if (d.outcome === 'allow') {
|
|
716
|
+
const common = { agent, method, url: urlStr, headers: ctx.headers, cres,
|
|
717
|
+
...(d.aid ? { rec: { gate: g, action, aid: d.aid } } : {}) };
|
|
718
|
+
if (ctx.heldId) {
|
|
719
|
+
// The file is the exact body; the client's own framing (length or
|
|
720
|
+
// chunked) still describes it. It is deleted once the upstream is done.
|
|
721
|
+
const id = ctx.heldId;
|
|
722
|
+
const rs = fs.createReadStream(heldFile(id));
|
|
723
|
+
rs.on('close', () => holds?.dropBody(id));
|
|
724
|
+
await forward({ ...common, stream: rs });
|
|
725
|
+
} else if (!hasBody) {
|
|
726
|
+
await forward({ ...common, body: EMPTY });
|
|
727
|
+
} else if (ctx.over) {
|
|
728
|
+
// Past 64 KB: send what was read, pipe the rest.
|
|
729
|
+
await forward({ ...common, prefix: Buffer.concat(ctx.chunks), stream: creq });
|
|
730
|
+
} else {
|
|
731
|
+
await forward({ ...common, body: Buffer.concat(ctx.chunks) });
|
|
732
|
+
}
|
|
733
|
+
} else {
|
|
734
|
+
discard(creq);
|
|
735
|
+
const why = ctx.asked
|
|
736
|
+
? `denied: ${d.reason ?? 'denied'}`
|
|
737
|
+
: `denied: ${d.rule ?? 'gate'}${d.reason ? `: ${d.reason}` : ''}`;
|
|
738
|
+
denyRes(cres, ctx.status ?? 403, why);
|
|
739
|
+
}
|
|
740
|
+
} finally {
|
|
741
|
+
inflightCtx.delete(rid);
|
|
742
|
+
freeWork();
|
|
743
|
+
}
|
|
744
|
+
}
|
|
745
|
+
|
|
746
|
+
/**
|
|
747
|
+
* Constant-memory tee of a request body: the first ASK_BODY_LIMIT bytes,
|
|
748
|
+
* the byte count and a running SHA-256.
|
|
749
|
+
*/
|
|
750
|
+
function makeTee() {
|
|
751
|
+
const hash = crypto.createHash('sha256');
|
|
752
|
+
let head = EMPTY;
|
|
753
|
+
let bytes = 0;
|
|
754
|
+
return {
|
|
755
|
+
push(/** @type {Buffer} */ c) {
|
|
756
|
+
hash.update(c);
|
|
757
|
+
bytes += c.length;
|
|
758
|
+
if (head.length < ASK_BODY_LIMIT) head = Buffer.concat([head, c.subarray(0, ASK_BODY_LIMIT - head.length)]);
|
|
759
|
+
},
|
|
760
|
+
get head() { return head; },
|
|
761
|
+
get bytes() { return bytes; },
|
|
762
|
+
digest: () => hash.copy().digest('hex'),
|
|
763
|
+
};
|
|
764
|
+
}
|
|
765
|
+
|
|
766
|
+
// One working slot per agent: a FIFO of body reads. A slot frees when its
|
|
767
|
+
// holder calls the returned function, or when its response closes (a dead
|
|
768
|
+
// client never wedges the line). Waiters stay paused and unread.
|
|
769
|
+
/** @type {Map<string, Promise<void>>} */
|
|
770
|
+
const workTail = new Map();
|
|
771
|
+
/**
|
|
772
|
+
* @param {string} agent agent name
|
|
773
|
+
* @param {import('node:http').ServerResponse} cres the request's response
|
|
774
|
+
* @returns {Promise<() => void>} resolves with `free` once the slot is ours
|
|
775
|
+
*/
|
|
776
|
+
function takeWorkSlot(agent, cres) {
|
|
777
|
+
const prev = workTail.get(agent) ?? Promise.resolve();
|
|
778
|
+
/** @type {() => void} */
|
|
779
|
+
let free = () => {};
|
|
780
|
+
const mine = new Promise((resolve) => { free = () => resolve(undefined); });
|
|
781
|
+
const tail = prev.then(() => mine);
|
|
782
|
+
workTail.set(agent, tail);
|
|
783
|
+
void tail.then(() => { if (workTail.get(agent) === tail) workTail.delete(agent); });
|
|
784
|
+
cres.once('close', free);
|
|
785
|
+
return prev.then(() => free);
|
|
786
|
+
}
|
|
787
|
+
|
|
788
|
+
/**
|
|
789
|
+
* Read the working slice of the body into `ctx.chunks` and `ctx.over`. Its
|
|
790
|
+
* own frame, so no reference to the chunks outlives a later spool to disk.
|
|
791
|
+
*
|
|
792
|
+
* @param {RequestCtx} ctx request context
|
|
793
|
+
* @returns {Promise<boolean>} true when the client went away
|
|
794
|
+
*/
|
|
795
|
+
async function readWorkBody(ctx) {
|
|
796
|
+
const r = await readBounded(ctx.creq, WORK_BODY_LIMIT);
|
|
797
|
+
if (r.aborted) return true;
|
|
798
|
+
ctx.chunks = r.chunks;
|
|
799
|
+
ctx.over = r.over;
|
|
800
|
+
return false;
|
|
801
|
+
}
|
|
802
|
+
|
|
803
|
+
/**
|
|
804
|
+
* Read a paused request's body until it ends or passes `limit` bytes
|
|
805
|
+
* (then pause again, keeping everything read so far in `chunks`).
|
|
806
|
+
*
|
|
807
|
+
* @param {import('node:http').IncomingMessage} creq paused request
|
|
808
|
+
* @param {number} limit byte limit
|
|
809
|
+
* @returns {Promise<{ chunks: Buffer[], over: boolean, aborted: boolean }>}
|
|
810
|
+
*/
|
|
811
|
+
function readBounded(creq, limit) {
|
|
812
|
+
return new Promise((resolve) => {
|
|
813
|
+
/** @type {Buffer[]} */
|
|
814
|
+
const chunks = [];
|
|
815
|
+
let size = 0;
|
|
816
|
+
/** @param {boolean} over @param {boolean} aborted */
|
|
817
|
+
const done = (over, aborted) => {
|
|
818
|
+
creq.off('data', onData);
|
|
819
|
+
creq.off('end', onEnd);
|
|
820
|
+
creq.off('close', onGone);
|
|
821
|
+
creq.off('error', onGone);
|
|
822
|
+
resolve({ chunks, over, aborted });
|
|
823
|
+
};
|
|
824
|
+
const onData = (/** @type {Buffer} */ c) => {
|
|
825
|
+
chunks.push(c);
|
|
826
|
+
size += c.length;
|
|
827
|
+
if (size > limit) { creq.pause(); done(true, false); }
|
|
828
|
+
};
|
|
829
|
+
const onEnd = () => done(false, false);
|
|
830
|
+
const onGone = () => done(false, true);
|
|
831
|
+
creq.on('data', onData);
|
|
832
|
+
creq.on('end', onEnd);
|
|
833
|
+
creq.on('close', onGone);
|
|
834
|
+
creq.on('error', onGone);
|
|
835
|
+
creq.resume();
|
|
406
836
|
});
|
|
407
837
|
}
|
|
408
838
|
// Idle tunnels die here; a request in flight is never idle by definition.
|
|
@@ -458,7 +888,7 @@ export function createProxy(opts) {
|
|
|
458
888
|
}
|
|
459
889
|
// Deny the tunnel itself: no cert is minted for a walled destination,
|
|
460
890
|
// and the inner request is checked again on arrival anyway.
|
|
461
|
-
const verdict = await checkUpstream(host, gate);
|
|
891
|
+
const verdict = await checkUpstream(host, gate, portNum);
|
|
462
892
|
if (!verdict.ok) {
|
|
463
893
|
denyRaw(sock, 403, verdict.reason);
|
|
464
894
|
return;
|
|
@@ -505,6 +935,7 @@ export function createProxy(opts) {
|
|
|
505
935
|
});
|
|
506
936
|
});
|
|
507
937
|
bound = await boundP;
|
|
938
|
+
if (gateFor) void gateOf('tcp').catch(() => {});
|
|
508
939
|
}
|
|
509
940
|
return { port: bound };
|
|
510
941
|
})();
|
|
@@ -516,8 +947,11 @@ export function createProxy(opts) {
|
|
|
516
947
|
function addAgent(name) {
|
|
517
948
|
const sockPath = runtimePaths(runtime).socket(name);
|
|
518
949
|
if (agentServers.has(name)) return sockPath;
|
|
950
|
+
if (agentServers.size >= MAX_AGENTS) {
|
|
951
|
+
throw new Error(`createProxy: agent limit reached (${MAX_AGENTS} agents per proxy); run another proxy for more`);
|
|
952
|
+
}
|
|
519
953
|
try { fs.unlinkSync(sockPath); } catch {}
|
|
520
|
-
|
|
954
|
+
ensurePrivateDir(path.dirname(sockPath));
|
|
521
955
|
const srv = net.createServer((sock) => {
|
|
522
956
|
if (closed) { sock.destroy(); return; }
|
|
523
957
|
admit(sock, name);
|
|
@@ -527,14 +961,26 @@ export function createProxy(opts) {
|
|
|
527
961
|
try { fs.chmodSync(sockPath, 0o600); } catch {}
|
|
528
962
|
});
|
|
529
963
|
agentServers.set(name, srv);
|
|
964
|
+
if (gateFor) void gateOf(name).catch(() => {});
|
|
530
965
|
return sockPath;
|
|
531
966
|
}
|
|
532
967
|
|
|
968
|
+
// Ends the agent's door AND its open connections: its parked holds end
|
|
969
|
+
// synchronously as deny / client gone (no waiting on the socket's async
|
|
970
|
+
// 'close'), then each socket is destroyed.
|
|
533
971
|
function removeAgent(name) {
|
|
534
972
|
const srv = agentServers.get(name);
|
|
535
973
|
if (!srv) return;
|
|
536
974
|
agentServers.delete(name);
|
|
975
|
+
gates.delete(name);
|
|
537
976
|
srv.close();
|
|
977
|
+
for (const s of [...clients]) {
|
|
978
|
+
if (s[AGENT] !== name) continue;
|
|
979
|
+
holds?.abandonSocket(s);
|
|
980
|
+
s.destroy();
|
|
981
|
+
}
|
|
982
|
+
// Asks still waiting in line (not parked) end now, as client gone, too.
|
|
983
|
+
for (const c of inflightCtx.values()) if (c.agent === name) c.endAsk?.('client gone');
|
|
538
984
|
try { fs.unlinkSync(runtimePaths(runtime).socket(name)); } catch {}
|
|
539
985
|
}
|
|
540
986
|
|
|
@@ -546,18 +992,36 @@ export function createProxy(opts) {
|
|
|
546
992
|
// Parked holds settle as denied (guarded writes), timers cleared,
|
|
547
993
|
// ask files removed, sweeper stopped — all inside holds.close().
|
|
548
994
|
holds?.close();
|
|
995
|
+
// Requests inside a gate check now end on their own (holds.close() refused
|
|
996
|
+
// their asks, parked or waiting): wait for their 403 and last log lines BEFORE the
|
|
997
|
+
// sockets go, but never forever (a wedged gate must not wedge close).
|
|
998
|
+
const checking = [...inflightCtx.values()].map((c) => reqDone.get(c.creq)).filter(Boolean);
|
|
999
|
+
if (checking.length) {
|
|
1000
|
+
/** @type {ReturnType<typeof setTimeout>|undefined} */
|
|
1001
|
+
let cap;
|
|
1002
|
+
await Promise.race([
|
|
1003
|
+
Promise.allSettled(checking),
|
|
1004
|
+
new Promise((resolve) => { cap = setTimeout(resolve, 3000); }),
|
|
1005
|
+
]);
|
|
1006
|
+
clearTimeout(cap);
|
|
1007
|
+
}
|
|
549
1008
|
for (const up of upstreams) { try { up.destroy(); } catch {} }
|
|
550
1009
|
upstreams.clear();
|
|
551
1010
|
for (const s of clients) { try { s.destroy(); } catch {} }
|
|
552
1011
|
clients.clear();
|
|
553
1012
|
server.close();
|
|
554
|
-
|
|
555
|
-
|
|
556
|
-
|
|
557
|
-
|
|
558
|
-
|
|
559
|
-
|
|
560
|
-
|
|
1013
|
+
// Lines logged from here on are dropped; the ones in flight are awaited,
|
|
1014
|
+
// but never forever (a wedged disk must not wedge close).
|
|
1015
|
+
logClosing = true;
|
|
1016
|
+
if (pendingLog.size) {
|
|
1017
|
+
/** @type {ReturnType<typeof setTimeout>|undefined} */
|
|
1018
|
+
let cap;
|
|
1019
|
+
await Promise.race([
|
|
1020
|
+
Promise.allSettled([...pendingLog]),
|
|
1021
|
+
new Promise((resolve) => { cap = setTimeout(resolve, 3000); }),
|
|
1022
|
+
]);
|
|
1023
|
+
clearTimeout(cap);
|
|
1024
|
+
}
|
|
561
1025
|
releaseClaim();
|
|
562
1026
|
}
|
|
563
1027
|
|