@uuaid/pillar 2.7.3 → 2.8.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.
@@ -0,0 +1,776 @@
1
+ /**
2
+ * Relay side of seed-over-egress (2.8.0): serves tunnelled seeds at
3
+ * `<origin>/e/<localId>/v1/...` for a carrier started with --accept-tunnels.
4
+ *
5
+ * Off unless a CarrierServer is given a TunnelRelay; then /v1/tunnel takes
6
+ * WebSocket upgrades and /e/* is forwarded. A seed is admitted only when its
7
+ * full uuaid is on the allow-file (exact match, re-read when the file
8
+ * changes; a removed uuaid's tunnel is closed at once), or in `open` mode,
9
+ * which the carrier binary allows only on a loopback listener (tests).
10
+ *
11
+ * Trust (DESIGN-egress-seed.md §2, RedTeam 085b71 C1): a relay sees inbox
12
+ * auth headers, which a carrier accepts again for 5 minutes. It is trusted
13
+ * with them, so it never logs or keeps them: logs carry the seed's localId,
14
+ * method, route template, status, byte counts and time only; state is keyed
15
+ * by client IP, localId and stream id; every /e/* answer is `no-store`.
16
+ *
17
+ * With an attestation key (allow-file mode only), a seed-info answer to a
18
+ * registry's challenge carries `x-pillar-relay-attest`: the relay's signed
19
+ * statement that it came through this exact active tunnel of a seed on the
20
+ * current allow-file (pillar-relay-attest/1, ./tunnel.mjs).
21
+ */
22
+ import { createHash, randomBytes } from "node:crypto";
23
+ import { performance } from "node:perf_hooks";
24
+ import { readFileSync, statSync } from "node:fs";
25
+ import { WebSocketServer } from "ws";
26
+ import { clientIpOf, DEFAULT_TRUSTED_PROXIES } from "./client-ip.mjs";
27
+ import { withCarrierFix } from "./refusals.mjs"; // the same one-line `fix` a carrier adds
28
+ import {
29
+ FRAME, FRAME_DATA_BYTES, MAX_FRAME_PAYLOAD, CHALLENGE_RE, allowedRoute, parseRelayPath,
30
+ pickRequestHeaders, encodeFrame, encodeJsonFrame, decodeFrame, verifyTunnelAuth,
31
+ makeRelayAttest, encodeAttestHeader,
32
+ } from "./tunnel.mjs";
33
+
34
+ /** Defaults; each can be lowered or raised per relay (tests lower them). */
35
+ export const TUNNEL_LIMITS = Object.freeze({
36
+ maxTunnels: 32,
37
+ tunnelsPerIp: 2,
38
+ pendingUpgrades: 16,
39
+ pendingPerIp: 4,
40
+ authTimeoutMs: 10_000,
41
+ streamsPerTunnel: 80,
42
+ streamsTotal: 512,
43
+ streamsPerClientIp: 32,
44
+ requestsPerClientIpPerMin: 600,
45
+ maxRequestBytes: 2 * 1024 * 1024 + 8192,
46
+ maxResponseBytes: 32 * 1024 * 1024,
47
+ streamDeadlineMs: 40_000,
48
+ tunnelBytesPerSec: 256 * 1024,
49
+ tunnelBurstBytes: 4 * 1024 * 1024,
50
+ totalBytesPerSec: 8 * 1024 * 1024,
51
+ totalBurstBytes: 32 * 1024 * 1024,
52
+ wsBufferedHighWater: 1024 * 1024,
53
+ totalBufferedBytes: 64 * 1024 * 1024,
54
+ pingIntervalMs: 20_000,
55
+ // Distinct client IPs held in the per-IP request window. When every entry
56
+ // is still inside its minute, a new IP is refused (tunnel-busy) rather than
57
+ // admitted or allowed to evict another client's history (RedTeam 995f4c).
58
+ clientRateTableMax: 10_000,
59
+ // Answer bytes a seed may have granted but not yet sent (credit window, per
60
+ // tunnel). Credit is paid from the tunnel's and the relay's outbound budgets
61
+ // when granted, so the relay never pauses the tunnel's socket to pace it.
62
+ creditWindowBytes: 128 * 1024,
63
+ // A stream whose client took no bytes for this long, while bytes waited for
64
+ // it at the relay, is dropped (client-slow), wherever the rest of its
65
+ // answer is held, so it stops holding the seed's response budget before
66
+ // the stream deadline (V1 da76d8). The relay sees a client take bytes only
67
+ // when its socket buffers do, in steps of about 300 KB on macOS loopback
68
+ // (9.9 s apart at 32 KiB/s, round 6 addendum): 10 s keeps every client
69
+ // fast enough to read a whole page before the deadline (51 KiB/s).
70
+ slowClientMs: 10_000,
71
+ // Unread answer bytes one client may hold at the relay before the relay
72
+ // tells the seed to hold that stream (per-stream flow control, round 6):
73
+ // a client that does not read stops only its own stream, never the tunnel.
74
+ streamHeldBytes: 256 * 1024,
75
+ });
76
+
77
+ /** Answer headers on every /e/* response: JSON only, never sniffed, framed or cached. */
78
+ const SAFE_HEADERS = Object.freeze({
79
+ "content-type": "application/json",
80
+ "x-content-type-options": "nosniff",
81
+ "content-security-policy": "default-src 'none'",
82
+ "cache-control": "no-store",
83
+ });
84
+
85
+ const UUAID_LINE = /^uuaid:[a-z0-9-]+:[a-z0-9-]+:[^\s:]+$/;
86
+
87
+ /**
88
+ * Parse an allow-file: one full uuaid per line; blank lines and `#` comments
89
+ * skipped. Throws naming the first bad line.
90
+ */
91
+ export function parseAllowFile(text) {
92
+ const set = new Set();
93
+ String(text).split(/\r?\n/).forEach((raw, i) => {
94
+ const line = raw.trim();
95
+ if (!line || line.startsWith("#")) return;
96
+ if (!UUAID_LINE.test(line)) throw new Error(`allow-file line ${i + 1} is not a full uuaid`);
97
+ set.add(line);
98
+ });
99
+ return set;
100
+ }
101
+
102
+ function allowSha(set) {
103
+ return createHash("sha256").update([...set].sort().join("\n"), "utf-8").digest("hex");
104
+ }
105
+
106
+ /**
107
+ * A token bucket in bytes. Bytes are reserved (taken) before they move, and
108
+ * only as many as `available` allows, so the balance never goes negative:
109
+ * every open stream together stays within burst + rate x time (RedTeam
110
+ * 995f4c, 87bb0b). Admission needs at least one whole byte of budget.
111
+ */
112
+ class Bucket {
113
+ constructor(perSec, burst, now) { this.perSec = perSec; this.burst = burst; this.tokens = burst; this.at = now; }
114
+ refill(now) { this.tokens = Math.min(this.burst, this.tokens + ((now - this.at) * this.perSec) / 1000); this.at = now; }
115
+ ok(now) { this.refill(now); return this.tokens >= 1; }
116
+ available(now) { this.refill(now); return Math.max(0, Math.floor(this.tokens)); }
117
+ take(n, now) { this.refill(now); this.tokens -= n; }
118
+ }
119
+
120
+ /** Smallest credit grant worth a message, unless the window or a budget is smaller. */
121
+ const MIN_GRANT = 4096;
122
+
123
+ /** How long a tunnel may go unheard (no pong, no frame) and still count as live: 1.5 ping intervals. */
124
+ const LIVE_WINDOW_PINGS = 1.5;
125
+
126
+ export class TunnelRelay {
127
+ /**
128
+ * @param {object} o
129
+ * origin canonical public origin of this relay
130
+ * admission { mode: "allow-file", path } or { mode: "open" }
131
+ * keychain attestation key (allow-file mode only; optional)
132
+ * trustedProxies whose X-Forwarded-For counts (the carrier's list)
133
+ * limits overrides of TUNNEL_LIMITS
134
+ * log (line) => void; never given a header value
135
+ * now wall clock (ms): attestation `at`, tunnel `since`
136
+ * mono monotonic clock (ms): rate windows, byte buckets and
137
+ * deadlines, so a wall-clock step (NTP) never starves or
138
+ * floods the relay
139
+ */
140
+ constructor({ origin, admission, keychain = null, trustedProxies = DEFAULT_TRUSTED_PROXIES, limits = {}, log = () => {}, now = () => Date.now(), mono = () => performance.now() }) {
141
+ if (!origin) throw new Error("TunnelRelay needs its origin");
142
+ if (admission?.mode !== "open" && admission?.mode !== "allow-file") throw new Error("TunnelRelay admission is allow-file or open");
143
+ this.origin = origin;
144
+ this.mode = admission.mode;
145
+ this.allowPath = admission.mode === "allow-file" ? admission.path : null;
146
+ this.keychain = admission.mode === "allow-file" ? keychain : null;
147
+ this.trustedProxies = trustedProxies;
148
+ this.limits = { ...TUNNEL_LIMITS, ...limits };
149
+ this.log = log;
150
+ this.now = now;
151
+ this.mono = mono;
152
+ this.tunnels = new Map(); // localId -> tunnel
153
+ this.tunnelsByIp = new Map(); // seed ip -> count
154
+ this.pendingByIp = new Map(); // ip -> unauthenticated upgrades
155
+ this.pendingTotal = 0;
156
+ this.clientRate = new Map(); // client ip -> request times (last minute)
157
+ this.clientStreams = new Map(); // client ip -> open streams
158
+ this.streamsTotal = 0;
159
+ this._nextStream = 1;
160
+ // Streams whose seed has sent the whole answer (RES_END) while bytes still
161
+ // wait here for the client (C7-1): out of their tunnel, but counted per
162
+ // client address, in total and toward the total buffer cap, under the
163
+ // progress rule, and dropped at the stream deadline (Lead review C-P3-1).
164
+ this.draining = new Set();
165
+ const t = this.mono();
166
+ this.totalIn = new Bucket(this.limits.totalBytesPerSec, this.limits.totalBurstBytes, t);
167
+ this.totalOut = new Bucket(this.limits.totalBytesPerSec, this.limits.totalBurstBytes, t);
168
+ this.allow = { set: new Set(), sha: allowSha(new Set()), stamp: null, checkedAt: -Infinity };
169
+ if (this.allowPath) this._reloadAllow(true);
170
+ this.wss = new WebSocketServer({ noServer: true, maxPayload: MAX_FRAME_PAYLOAD, perMessageDeflate: false, clientTracking: false });
171
+ this._pingTimer = setInterval(() => this._ping(), this.limits.pingIntervalMs);
172
+ this._pingTimer.unref?.();
173
+ this._allowTimer = this.allowPath ? setInterval(() => this._recheckAllow(), 1000) : null;
174
+ this._allowTimer?.unref?.();
175
+ }
176
+
177
+ // ------------------------------------------------------------ admission
178
+
179
+ /** Re-read the allow-file if it changed. `strict` (start-up) throws on a bad file. */
180
+ _reloadAllow(strict = false) {
181
+ this.allow.checkedAt = this.mono();
182
+ let st;
183
+ try { st = statSync(this.allowPath); } catch (e) {
184
+ if (strict) throw new Error(`allow-file ${this.allowPath} cannot be read (${e.code ?? e.message})`);
185
+ this._setAllow(new Set(), "missing");
186
+ return;
187
+ }
188
+ const stamp = `${st.mtimeMs}:${st.size}:${st.ino}`;
189
+ if (stamp === this.allow.stamp) return;
190
+ try {
191
+ this._setAllow(parseAllowFile(readFileSync(this.allowPath, "utf-8")), stamp);
192
+ } catch (e) {
193
+ if (strict) throw e;
194
+ this._setAllow(new Set(), stamp); // fail closed on a damaged file
195
+ this.log(`relay: allow-file unreadable (${e.message}); admitting no seed until it is fixed`);
196
+ }
197
+ }
198
+
199
+ _setAllow(set, stamp) {
200
+ this.allow.set = set;
201
+ this.allow.sha = allowSha(set);
202
+ this.allow.stamp = stamp;
203
+ }
204
+
205
+ _allowNow() {
206
+ if (this.allowPath && this.mono() - this.allow.checkedAt >= 1000) this._reloadAllow();
207
+ return this.allow;
208
+ }
209
+
210
+ _admitted(uuaid) {
211
+ if (this.mode === "open") return true;
212
+ return this._allowNow().set.has(uuaid);
213
+ }
214
+
215
+ /** Close every tunnel whose uuaid left the allow-file (revocation). */
216
+ _recheckAllow() {
217
+ const allow = this._allowNow();
218
+ for (const t of [...this.tunnels.values()]) {
219
+ if (!allow.set.has(t.uuaid)) this._closeTunnel(t, 4003, "revoked"); // @rule relay.revoke-closes-tunnel
220
+ }
221
+ }
222
+
223
+ // ------------------------------------------------------------ tunnels
224
+
225
+ /** http.Server 'upgrade' handler. */
226
+ handleUpgrade(req, socket, head) {
227
+ let pathname = "";
228
+ try { pathname = new URL(req.url, "http://relay").pathname; } catch (_e) { /* refused below */ }
229
+ if (pathname !== "/v1/tunnel") return this._rejectUpgrade(socket, 404, "Not Found");
230
+ const ip = clientIpOf(req, this.trustedProxies);
231
+ if (this.pendingTotal >= this.limits.pendingUpgrades) return this._rejectUpgrade(socket, 503, "Service Unavailable"); // @rule relay.pending-total-cap
232
+ if ((this.pendingByIp.get(ip) ?? 0) >= this.limits.pendingPerIp) return this._rejectUpgrade(socket, 503, "Service Unavailable");
233
+ const conn = { ip, pending: true };
234
+ this._addPending(conn);
235
+ socket.once("close", () => this._releasePending(conn));
236
+ this.wss.handleUpgrade(req, socket, head, (ws) => this._onConnection(ws, conn));
237
+ }
238
+
239
+ _rejectUpgrade(socket, code, text) {
240
+ socket.end(`HTTP/1.1 ${code} ${text}\r\nconnection: close\r\ncontent-length: 0\r\n\r\n`);
241
+ socket.destroy();
242
+ }
243
+
244
+ _addPending(conn) {
245
+ this.pendingTotal++;
246
+ this.pendingByIp.set(conn.ip, (this.pendingByIp.get(conn.ip) ?? 0) + 1);
247
+ }
248
+
249
+ _releasePending(conn) {
250
+ if (!conn.pending) return;
251
+ conn.pending = false;
252
+ this.pendingTotal--;
253
+ const n = (this.pendingByIp.get(conn.ip) ?? 1) - 1;
254
+ if (n > 0) this.pendingByIp.set(conn.ip, n); else this.pendingByIp.delete(conn.ip);
255
+ }
256
+
257
+ _refuse(ws, conn, reason, code = 4001) {
258
+ this._releasePending(conn);
259
+ try { ws.send(JSON.stringify({ t: "error", v: 1, reason })); } catch (_e) { /* closing anyway */ }
260
+ ws.close(code, reason);
261
+ }
262
+
263
+ _onConnection(ws, conn) {
264
+ // A fresh nonce per connection, consumed by its first auth message: an
265
+ // auth signed for one connection is useless on any other.
266
+ let nonce = randomBytes(32).toString("hex");
267
+ let tunnel = null;
268
+ const authTimer = setTimeout(() => this._refuse(ws, conn, "auth-timeout", 4008), this.limits.authTimeoutMs);
269
+ authTimer.unref?.();
270
+ ws.send(JSON.stringify({ t: "hello", v: 1, origin: this.origin, nonce }));
271
+ ws.on("message", (data, isBinary) => {
272
+ if (tunnel) {
273
+ // After `ready` a seed sends only binary frames; a second auth (or any
274
+ // text) on a live tunnel closes it (design §4, Lead review C-P3-3).
275
+ if (!isBinary) return this._closeTunnel(tunnel, 4002, "unexpected-message"); // @rule relay.second-auth-closes
276
+ tunnel.lastSeen = this.mono();
277
+ this._onSeedFrame(tunnel, data);
278
+ return;
279
+ }
280
+ // The first message is the auth, whatever its type: a binary frame (or
281
+ // any message that does not verify) consumes the nonce and is refused.
282
+ if (nonce === null) return;
283
+ const offered = nonce;
284
+ nonce = null;
285
+ clearTimeout(authTimer);
286
+ let msg = null;
287
+ try { msg = JSON.parse(String(data)); } catch (_e) { msg = null; }
288
+ const now = this.now();
289
+ const m = this.mono();
290
+ const v = verifyTunnelAuth(msg, { origin: this.origin, nonce: offered, now });
291
+ if (!v.ok) return this._refuse(ws, conn, v.reason);
292
+ if (!this._admitted(v.uuaid)) return this._refuse(ws, conn, "not-allowed"); // @rule relay.allow-file-admission
293
+ const replacing = this.tunnels.get(v.localId);
294
+ if (replacing) {
295
+ // Two processes with one seed key would replace each other forever,
296
+ // and mail accepted by one is never read from the other (V1 2b5070).
297
+ // A live tunnel is kept; only a reconnect of the same process, or a
298
+ // tunnel not heard from in 1.5 ping intervals (its process is gone),
299
+ // is replaced.
300
+ let live = m - replacing.lastSeen < this.limits.pingIntervalMs * LIVE_WINDOW_PINGS;
301
+ if (replacing.instance === v.instance) live = false; // @rule relay.same-instance-replaces
302
+ if (live) return this._refuse(ws, conn, "seed-already-connected", 4009); // @rule relay.keep-live-tunnel
303
+ }
304
+ if (!replacing && this.tunnels.size >= this.limits.maxTunnels) return this._refuse(ws, conn, "relay-full", 4013); // @rule relay.tunnel-total-cap
305
+ const fromIp = (this.tunnelsByIp.get(conn.ip) ?? 0) - (replacing?.ip === conn.ip ? 1 : 0);
306
+ if (fromIp >= this.limits.tunnelsPerIp) return this._refuse(ws, conn, "relay-full", 4013); // @rule relay.tunnel-per-ip-cap
307
+ if (replacing) this._closeTunnel(replacing, 4000, "replaced");
308
+ this._releasePending(conn);
309
+ tunnel = {
310
+ id: randomBytes(16).toString("hex"),
311
+ uuaid: v.uuaid, publicKey: v.publicKey, localId: v.localId, ip: conn.ip, since: now, ws,
312
+ instance: v.instance, lastSeen: m, credit: 0, inTurn: 0,
313
+ streams: new Map(), missedPongs: 0, closed: false,
314
+ inB: new Bucket(this.limits.tunnelBytesPerSec, this.limits.tunnelBurstBytes, m),
315
+ outB: new Bucket(this.limits.tunnelBytesPerSec, this.limits.tunnelBurstBytes, m),
316
+ };
317
+ this.tunnels.set(v.localId, tunnel);
318
+ this.tunnelsByIp.set(conn.ip, (this.tunnelsByIp.get(conn.ip) ?? 0) + 1);
319
+ ws.on("pong", () => { tunnel.missedPongs = 0; tunnel.lastSeen = this.mono(); });
320
+ ws.send(JSON.stringify({
321
+ t: "ready", v: 1, url: `${this.origin}/e/${v.localId}`,
322
+ limits: { maxRequestBytes: this.limits.maxRequestBytes, maxResponseBytes: this.limits.maxResponseBytes, streamsPerTunnel: this.limits.streamsPerTunnel },
323
+ }));
324
+ this.log(`relay: tunnel up ${v.localId}`);
325
+ });
326
+ ws.on("close", () => {
327
+ clearTimeout(authTimer);
328
+ this._releasePending(conn);
329
+ if (tunnel) this._dropTunnel(tunnel);
330
+ });
331
+ ws.on("error", () => { /* 'close' follows */ });
332
+ }
333
+
334
+ _closeTunnel(tunnel, code, reason) {
335
+ try { tunnel.ws.send(JSON.stringify({ t: "error", v: 1, reason })); } catch (_e) { /* closing anyway */ }
336
+ try { tunnel.ws.close(code, reason); } catch (_e) { /* already closing */ }
337
+ this._dropTunnel(tunnel);
338
+ }
339
+
340
+ _dropTunnel(tunnel) {
341
+ if (tunnel.closed) return;
342
+ tunnel.closed = true;
343
+ if (this.tunnels.get(tunnel.localId) === tunnel) this.tunnels.delete(tunnel.localId);
344
+ const n = (this.tunnelsByIp.get(tunnel.ip) ?? 1) - 1;
345
+ if (n > 0) this.tunnelsByIp.set(tunnel.ip, n); else this.tunnelsByIp.delete(tunnel.ip);
346
+ for (const s of [...tunnel.streams.values()]) this._fail(s, 502, "seed-offline", false);
347
+ this.log(`relay: tunnel down ${tunnel.localId}`);
348
+ }
349
+
350
+ _ping() {
351
+ for (const t of [...this.tunnels.values()]) {
352
+ if (t.missedPongs >= 2) { t.ws.terminate(); this._dropTunnel(t); continue; }
353
+ t.missedPongs++;
354
+ try { t.ws.ping(); } catch (_e) { /* close follows */ }
355
+ }
356
+ }
357
+
358
+ // ------------------------------------------------------------ requests
359
+
360
+ _send(res, code, obj) {
361
+ if (res.headersSent || res.destroyed) return;
362
+ const body = JSON.stringify(withCarrierFix(code, obj));
363
+ res.writeHead(code, { ...SAFE_HEADERS, "content-length": Buffer.byteLength(body) });
364
+ res.end(body);
365
+ }
366
+
367
+ _clientRateOk(ip, now) {
368
+ let times = this.clientRate.get(ip);
369
+ if (!times) {
370
+ if (this.clientRate.size >= this.limits.clientRateTableMax) this._pruneRates(now);
371
+ if (this.clientRate.size >= this.limits.clientRateTableMax) return false; // @rule relay.rate-table-bound
372
+ times = [];
373
+ this.clientRate.set(ip, times);
374
+ }
375
+ while (times.length && times[0] <= now - 60_000) times.shift();
376
+ if (times.length >= this.limits.requestsPerClientIpPerMin) return false;
377
+ times.push(now);
378
+ return true;
379
+ }
380
+
381
+ _pruneRates(now) {
382
+ for (const [ip, times] of this.clientRate) {
383
+ while (times.length && times[0] <= now - 60_000) times.shift();
384
+ if (!times.length) this.clientRate.delete(ip);
385
+ }
386
+ }
387
+
388
+ _buffered() {
389
+ let n = 0;
390
+ for (const t of this.tunnels.values()) {
391
+ n += t.ws.bufferedAmount;
392
+ for (const s of t.streams.values()) n += this._waiting(s) + (s.inQueuedBytes ?? 0);
393
+ }
394
+ for (const s of this.draining) n += this._waiting(s); // @rule relay.draining-counted
395
+ return n;
396
+ }
397
+
398
+ /** The CarrierServer hands every /e/* request here. */
399
+ async handleRequest(req, res, url) {
400
+ const now = this.mono();
401
+ const p = parseRelayPath(url.pathname);
402
+ if (!p) return this._send(res, 404, { error: "not-found" });
403
+ const route = allowedRoute(req.method, p.rest);
404
+ if (!route) return this._send(res, 404, { error: "not-found" }); // @rule relay.route-allow-list
405
+ const tunnel = this.tunnels.get(p.localId);
406
+ if (!tunnel) return this._send(res, 503, { error: "seed-offline" });
407
+ const ip = clientIpOf(req, this.trustedProxies);
408
+ const L = this.limits;
409
+ const busy = () => this._send(res, 503, { error: "tunnel-busy" });
410
+ if (!this._clientRateOk(ip, now)) return busy(); // @rule relay.client-rate
411
+ if ((this.clientStreams.get(ip) ?? 0) >= L.streamsPerClientIp) return busy(); // @rule relay.client-streams
412
+ if (tunnel.streams.size >= L.streamsPerTunnel) return busy(); // @rule relay.tunnel-streams
413
+ if (this.streamsTotal >= L.streamsTotal) return busy(); // @rule relay.total-streams
414
+ if (!tunnel.inB.ok(now) || !tunnel.outB.ok(now)) return busy(); // @rule relay.tunnel-bandwidth
415
+ if (!this.totalIn.ok(now) || !this.totalOut.ok(now)) return busy(); // @rule relay.total-bandwidth
416
+ if (tunnel.ws.bufferedAmount > L.wsBufferedHighWater) return busy();
417
+ if (this._buffered() > L.totalBufferedBytes) return busy(); // @rule relay.total-buffered
418
+ const declared = Number(req.headers["content-length"] ?? 0);
419
+ if (declared > L.maxRequestBytes) return this._send(res, 413, { error: "body-too-large" }); // @rule relay.request-size
420
+
421
+ const id = this._nextStream++;
422
+ if (this._nextStream > 0xffffffff) this._nextStream = 1;
423
+ const challenge = route === "/v1/seed-info" ? url.searchParams.get("challenge") : null;
424
+ const stream = {
425
+ id, tunnel, req, res, ip, route, method: req.method, localId: p.localId, startedAt: now,
426
+ bytesIn: 0, bytesOut: 0, status: 0, headersSent: false, done: false, challenge,
427
+ // The answer, written to the client one frame at a time (_writeOut), and
428
+ // when its socket last took one (_checkSlowClients).
429
+ outQ: [], outQBytes: 0, writing: false, progressAt: now, seedDone: false,
430
+ inQueue: [], inQueuedBytes: 0, inEnded: false, inEndSent: false,
431
+ };
432
+ tunnel.streams.set(id, stream);
433
+ this.streamsTotal++;
434
+ this.clientStreams.set(ip, (this.clientStreams.get(ip) ?? 0) + 1);
435
+ stream.timer = setTimeout(() => this._fail(stream, 504, "seed-timeout"), L.streamDeadlineMs);
436
+ stream.timer.unref?.();
437
+ res.on("close", () => { if (!stream.done) this._fail(stream, 0, "client-gone"); });
438
+
439
+ // The client address is taken once, here, at this relay's ingress; any
440
+ // X-Forwarded-For the client sent is not forwarded (pickRequestHeaders).
441
+ this._toSeed(tunnel, encodeJsonFrame(FRAME.REQ, id, { method: req.method, path: p.rest + url.search, headers: pickRequestHeaders(req.headers), ip }));
442
+ // Credit for the answer, paid from the outbound budgets now, so the seed
443
+ // can answer without waiting a round trip.
444
+ this._grantCredit(tunnel);
445
+ // The upload is forwarded only as far as the inbound budgets allow (see
446
+ // _pumpInbound); the rest waits here, one chunk per stream at most, with
447
+ // the request paused, and counts toward the total buffer cap.
448
+ req.on("data", (chunk) => {
449
+ if (stream.done) return;
450
+ stream.bytesIn += chunk.length;
451
+ if (stream.bytesIn > L.maxRequestBytes) return this._fail(stream, 413, "body-too-large");
452
+ if (this._buffered() + chunk.length > L.totalBufferedBytes) return this._fail(stream, 503, "tunnel-busy"); // @rule relay.inbound-queue-cap
453
+ stream.inQueue.push(chunk);
454
+ stream.inQueuedBytes += chunk.length;
455
+ req.pause();
456
+ this._pumpInbound(tunnel);
457
+ this._schedulePump();
458
+ });
459
+ req.on("end", () => {
460
+ if (stream.done) return;
461
+ stream.inEnded = true;
462
+ this._pumpInbound(tunnel);
463
+ this._schedulePump();
464
+ });
465
+ this._schedulePump();
466
+ }
467
+
468
+ // ------------------------------------------------------------ pacing
469
+
470
+ _schedulePump() {
471
+ if (this._pumpTimer || this._stopped) return;
472
+ this._pumpTimer = setTimeout(() => { this._pumpTimer = null; this._pump(); }, 20);
473
+ this._pumpTimer.unref?.();
474
+ }
475
+
476
+ /**
477
+ * Every 20 ms while streams are open or draining: forward waiting uploads,
478
+ * grant answer credit as the budgets allow, and drop clients that stopped
479
+ * taking bytes.
480
+ */
481
+ _pump() {
482
+ const tunnels = [...this.tunnels.values()].filter((t) => !t.closed && t.streams.size);
483
+ if (tunnels.length) {
484
+ const start = (this._pumpTurn = ((this._pumpTurn ?? 0) + 1) % tunnels.length);
485
+ for (let i = 0; i < tunnels.length; i++) {
486
+ const t = tunnels[(start + i) % tunnels.length];
487
+ this._pumpInbound(t);
488
+ this._checkSlowClients(t);
489
+ this._grantCredit(t);
490
+ }
491
+ }
492
+ this._checkSlow(this.draining); // @rule relay.drain-progress
493
+ if (tunnels.length || this.draining.size) this._schedulePump();
494
+ }
495
+
496
+ /**
497
+ * Forward waiting upload bytes to the seed, reserving each piece against the
498
+ * tunnel's and the relay's inbound budgets before it is sent (RedTeam
499
+ * 87bb0b): never more than both allow, whatever other streams are open.
500
+ */
501
+ _pumpInbound(t) {
502
+ const list = [...t.streams.values()];
503
+ if (!list.length) return;
504
+ const first = t.inTurn++ % list.length;
505
+ for (let i = 0; i < list.length; i++) {
506
+ const s = list[(first + i) % list.length];
507
+ if (s.done) continue;
508
+ while (s.inQueue.length) {
509
+ if (t.ws.bufferedAmount > this.limits.wsBufferedHighWater) return;
510
+ const now = this.mono();
511
+ const head = s.inQueue[0];
512
+ const n = Math.min(head.length, FRAME_DATA_BYTES, t.inB.available(now), this.totalIn.available(now));
513
+ if (n < 1) return;
514
+ t.inB.take(n, now); // @rule relay.inbound-reserve-tunnel
515
+ this.totalIn.take(n, now); // @rule relay.inbound-reserve-total
516
+ this._toSeed(t, encodeFrame(FRAME.REQ_DATA, s.id, head.subarray(0, n)));
517
+ s.inQueuedBytes -= n;
518
+ if (n === head.length) s.inQueue.shift(); else s.inQueue[0] = head.subarray(n);
519
+ }
520
+ if (s.inEnded && !s.inEndSent) {
521
+ s.inEndSent = true;
522
+ this._toSeed(t, encodeFrame(FRAME.REQ_END, s.id));
523
+ } else if (!s.inEnded && s.req.isPaused()) {
524
+ s.req.resume();
525
+ }
526
+ }
527
+ }
528
+
529
+ /**
530
+ * Grant a tunnel's seed credit to send answer bytes, paid now from the
531
+ * tunnel's and the relay's outbound budgets (RedTeam 87bb0b). The relay
532
+ * never pauses the tunnel's socket, so pongs keep flowing while a transfer
533
+ * is paced. No credit while the tunnel's clients have not read what they
534
+ * already got.
535
+ */
536
+ _grantCredit(t) {
537
+ if (t.closed || !t.streams.size) return;
538
+ const room = this.limits.creditWindowBytes - t.credit;
539
+ if (room < 1) return;
540
+ const now = this.mono();
541
+ const n = Math.min(room, t.outB.available(now), this.totalOut.available(now));
542
+ if (n < Math.min(MIN_GRANT, room, t.outB.burst, this.totalOut.burst)) return;
543
+ t.outB.take(n, now); // @rule relay.credit-reserve-tunnel
544
+ this.totalOut.take(n, now); // @rule relay.credit-reserve-total
545
+ t.credit += n;
546
+ try { t.ws.send(JSON.stringify({ t: "credit", v: 1, bytes: n })); } catch (_e) { /* close follows */ }
547
+ }
548
+
549
+ /**
550
+ * A client that stops taking bytes is dropped (client-slow) once bytes have
551
+ * waited for it at the relay, none taken, for slowClientMs (V1 da76d8):
552
+ * whatever the tunnel's other streams hold, and wherever the rest of its
553
+ * answer is (on hold at the seed, waiting there for credit, here, or all of
554
+ * it here once the seed is done: _pump checks draining streams the same
555
+ * way, C7-1). The seed then drops the stream and returns its page to the
556
+ * response budget.
557
+ * A client that keeps taking bytes, however slowly, is not dropped here:
558
+ * one frame at a time is written to it (_writeOut), so each frame its
559
+ * socket takes counts. Until the client's socket buffers are full the
560
+ * relay cannot tell a client that does not read from one that does; the
561
+ * seed's budget bounds what such a stream holds meanwhile, and the stream
562
+ * deadline its time.
563
+ */
564
+ _checkSlowClients(t) {
565
+ this._checkSlow(t.streams.values());
566
+ }
567
+
568
+ _checkSlow(streams) {
569
+ const now = this.mono();
570
+ for (const s of [...streams]) {
571
+ if (this._waiting(s) === 0) { s.progressAt = now; continue; }
572
+ if (now - s.progressAt >= this.limits.slowClientMs) this._fail(s, 0, "client-slow"); // @rule relay.slow-client-dropped
573
+ }
574
+ }
575
+
576
+ /** Answer bytes in this process for one live stream's client. */
577
+ _waiting(s) {
578
+ return s.outQBytes + (s.res.writableLength ?? 0);
579
+ }
580
+
581
+ /**
582
+ * Write a live stream's answer to its client one frame at a time: the next
583
+ * only once its socket has taken the last, so the rest waits in outQ and a
584
+ * slow client's progress shows frame by frame, not only when a whole
585
+ * backlog has gone. When the backlog is gone, a held stream resumes, and a
586
+ * stream whose seed is done ends its answer.
587
+ */
588
+ _writeOut(s) {
589
+ if (s.done || s.writing || !s.outQ.length) return;
590
+ const b = s.outQ.shift();
591
+ s.outQBytes -= b.length;
592
+ s.writing = true;
593
+ s.res.write(b, (err) => {
594
+ s.writing = false;
595
+ if (err || s.done) return;
596
+ s.progressAt = this.mono(); // @rule relay.client-progress
597
+ this._writeOut(s);
598
+ if (s.seedDone) return this._endIfDrained(s);
599
+ if (s.held && !s.outQ.length) {
600
+ s.held = false;
601
+ this._controlToSeed(s.tunnel, { t: "resume", v: 1, id: s.id });
602
+ this._grantCredit(s.tunnel);
603
+ }
604
+ });
605
+ }
606
+
607
+ /**
608
+ * Per-stream flow control (round 6): when more than streamHeldBytes wait
609
+ * here for one client, tell the seed to hold that stream; once its backlog
610
+ * here is gone, resume it (_writeOut). The seed then keeps that answer in
611
+ * its own reserved budget, and the tunnel keeps serving every other stream.
612
+ */
613
+ _holdIfBehind(t, stream) {
614
+ if (stream.held || stream.done) return;
615
+ if (this._waiting(stream) <= this.limits.streamHeldBytes) return;
616
+ stream.held = true;
617
+ this._controlToSeed(t, { t: "hold", v: 1, id: stream.id }); // @rule relay.stream-hold
618
+ }
619
+
620
+ _controlToSeed(t, msg) {
621
+ if (t.closed) return;
622
+ try { t.ws.send(JSON.stringify(msg)); } catch (_e) { /* close follows */ }
623
+ }
624
+
625
+ _toSeed(tunnel, frame) {
626
+ if (tunnel.closed) return;
627
+ try { tunnel.ws.send(frame); } catch (_e) { /* close follows */ }
628
+ }
629
+
630
+ /** A frame from the seed: the answer to one of its streams. */
631
+ _onSeedFrame(tunnel, data) {
632
+ const f = decodeFrame(Buffer.isBuffer(data) ? data : Buffer.from(data));
633
+ if (!f) return;
634
+ // Every answer byte is paid for by credit, whatever happens to it next
635
+ // (RedTeam 82902d): data for a stream that has ended, is unknown, or has
636
+ // no headers yet is charged before it is dropped, as the seed charged it
637
+ // when it sent it. A seed that sends past its credit is cut off.
638
+ if (f.kind === FRAME.RES_DATA) {
639
+ tunnel.credit -= f.payload.length;
640
+ if (tunnel.credit < 0) return this._closeTunnel(tunnel, 4002, "flow-violation"); // @rule relay.credit-enforced
641
+ this._schedulePump();
642
+ }
643
+ const stream = tunnel.streams.get(f.id);
644
+ if (!stream || stream.done) return;
645
+ if (f.kind === FRAME.RES) {
646
+ // A seed answers each stream once; headers twice break the protocol.
647
+ if (stream.headersSent) return this._closeTunnel(tunnel, 4002, "flow-violation"); // @rule relay.headers-once
648
+ let meta = null;
649
+ try { meta = JSON.parse(f.payload.toString("utf-8")); } catch (_e) { meta = null; }
650
+ const status = Number(meta?.status);
651
+ if (!Number.isInteger(status) || status < 200 || status > 599) return this._fail(stream, 502, "seed-bad-answer");
652
+ // Nothing the seed sends as a header reaches the client.
653
+ const headers = { ...SAFE_HEADERS };
654
+ const attest = status === 200 ? this._attest(stream, this.now()) : null;
655
+ if (attest) headers["x-pillar-relay-attest"] = attest;
656
+ stream.status = status;
657
+ stream.headersSent = true;
658
+ stream.res.writeHead(status, headers);
659
+ } else if (f.kind === FRAME.RES_DATA) {
660
+ if (!stream.headersSent) return this._fail(stream, 502, "seed-bad-answer");
661
+ stream.bytesOut += f.payload.length;
662
+ if (stream.bytesOut > this.limits.maxResponseBytes) return this._fail(stream, 502, "seed-answer-too-large"); // @rule relay.response-size
663
+ // A client that does not read backs its answer up in this process. The
664
+ // total cap is a hard bound, not only an admission check (C-P3-1): once
665
+ // the backlog passes it, a stream whose answer is queued is dropped.
666
+ stream.outQ.push(f.payload);
667
+ stream.outQBytes += f.payload.length;
668
+ this._writeOut(stream);
669
+ if (stream.outQBytes > 0 && this._buffered() > this.limits.totalBufferedBytes) return this._fail(stream, 0, "client-slow"); // @rule relay.total-buffered-enforced
670
+ this._holdIfBehind(tunnel, stream);
671
+ // Top the credit up as soon as half the window is used, so the transfer
672
+ // is limited by the budgets, not by the pump's 20 ms tick.
673
+ if (tunnel.credit <= this.limits.creditWindowBytes / 2) this._grantCredit(tunnel);
674
+ } else if (f.kind === FRAME.RES_END) {
675
+ if (!stream.headersSent) return this._fail(stream, 502, "seed-bad-answer");
676
+ this._seedDone(stream);
677
+ } else if (f.kind === FRAME.RESET) {
678
+ this._fail(stream, 502, "seed-reset", false);
679
+ }
680
+ }
681
+
682
+ /**
683
+ * The attestation for a seed-info answer to a registry's challenge: only in
684
+ * allow-file mode with a key, only while the seed is on the allow-file as
685
+ * it is now, and only for the tunnel that is active for that seed now.
686
+ */
687
+ _attest(stream, now) {
688
+ if (!this.keychain || this.mode !== "allow-file") return null;
689
+ if (stream.route !== "/v1/seed-info" || !CHALLENGE_RE.test(stream.challenge ?? "")) return null;
690
+ const allow = this._allowNow();
691
+ if (!allow.set.has(stream.tunnel.uuaid)) return null; // @rule relay.attest-current-allow-file
692
+ if (this.tunnels.get(stream.localId) !== stream.tunnel) return null; // @rule relay.attest-active-tunnel
693
+ const t = stream.tunnel;
694
+ return encodeAttestHeader(makeRelayAttest(this.keychain, {
695
+ origin: this.origin, path: `/e/${t.localId}/v1/seed-info`, uuaid: t.uuaid, publicKey: t.publicKey,
696
+ challenge: stream.challenge, tunnelId: t.id, tunnelSince: t.since, admission: "allow-file",
697
+ allowSha256: allow.sha, at: now,
698
+ }));
699
+ }
700
+
701
+ /**
702
+ * The seed has sent the whole answer (RES_END). The stream leaves its tunnel
703
+ * (no more credit, holds or seed-offline for it), but it is not over: what
704
+ * waits here still goes to the client one frame at a time, under the same
705
+ * progress rule, counted in _buffered, per client address and in total,
706
+ * until its last byte is in the client's socket (C7-1, C7-2). The stream
707
+ * deadline, from the stream's start, still bounds it.
708
+ */
709
+ _seedDone(s) {
710
+ s.seedDone = true;
711
+ s.held = false;
712
+ s.tunnel.streams.delete(s.id);
713
+ clearTimeout(s.timer);
714
+ s.timer = setTimeout(() => this._fail(s, 0, "drain-deadline"), Math.max(0, s.startedAt + this.limits.streamDeadlineMs - this.mono())); // @rule relay.drain-deadline
715
+ s.timer?.unref?.();
716
+ this.draining.add(s); // @rule relay.drain-observed
717
+ this._endIfDrained(s);
718
+ this._schedulePump();
719
+ }
720
+
721
+ /** A stream whose seed is done and whose queue here is empty: end its answer; it is over once that has flushed. */
722
+ _endIfDrained(s) {
723
+ if (s.done || !s.seedDone || s.writing || s.outQ.length || s.ending) return;
724
+ s.ending = true;
725
+ s.res.once("finish", () => this._finish(s));
726
+ s.res.end();
727
+ }
728
+
729
+ /** End a stream with an error (or, once headers went out, by destroying it). */
730
+ _fail(stream, code, error, tellSeed = true) {
731
+ if (stream.done) return;
732
+ // A seed that is done with a stream no longer knows it.
733
+ if (tellSeed && !stream.seedDone) this._toSeed(stream.tunnel, encodeFrame(FRAME.RESET, stream.id));
734
+ if (code && !stream.headersSent) { stream.status = code; this._send(stream.res, code, { error }); }
735
+ else if (!stream.res.writableFinished) stream.res.destroy();
736
+ this._finish(stream);
737
+ }
738
+
739
+ /** The stream is over: nothing of its answer waits here any more. */
740
+ _finish(stream) {
741
+ if (stream.done) return;
742
+ stream.done = true;
743
+ stream.inQueue = [];
744
+ stream.inQueuedBytes = 0;
745
+ stream.outQ = [];
746
+ stream.outQBytes = 0;
747
+ clearTimeout(stream.timer);
748
+ stream.tunnel.streams.delete(stream.id);
749
+ this.draining.delete(stream);
750
+ this.streamsTotal--;
751
+ const n = (this.clientStreams.get(stream.ip) ?? 1) - 1;
752
+ if (n > 0) this.clientStreams.set(stream.ip, n); else this.clientStreams.delete(stream.ip);
753
+ // Route template, never the path, query or any header value.
754
+ this.log(`relay: ${stream.localId} ${stream.method} ${stream.route} ${stream.status || "-"} ${stream.bytesIn}/${stream.bytesOut}B ${Math.round(this.mono() - stream.startedAt)}ms`);
755
+ }
756
+
757
+ /** Everything this relay keeps between requests (tests check it holds no header value). */
758
+ stateSnapshot() {
759
+ return {
760
+ tunnels: [...this.tunnels.values()].map(t => ({ id: t.id, uuaid: t.uuaid, publicKey: t.publicKey, localId: t.localId, ip: t.ip, since: t.since, instance: t.instance, credit: t.credit, streams: [...t.streams.keys()] })),
761
+ tunnelsByIp: [...this.tunnelsByIp], pendingByIp: [...this.pendingByIp], pendingTotal: this.pendingTotal,
762
+ clientRate: [...this.clientRate.keys()], clientStreams: [...this.clientStreams], streamsTotal: this.streamsTotal, draining: this.draining.size,
763
+ allow: { set: [...this.allow.set], sha: this.allow.sha },
764
+ };
765
+ }
766
+
767
+ close() {
768
+ this._stopped = true;
769
+ clearTimeout(this._pumpTimer);
770
+ clearInterval(this._pingTimer);
771
+ if (this._allowTimer) clearInterval(this._allowTimer);
772
+ for (const t of [...this.tunnels.values()]) { try { t.ws.terminate(); } catch (_e) { /* gone */ } this._dropTunnel(t); }
773
+ for (const s of [...this.draining]) this._fail(s, 0, "relay-closed");
774
+ this.wss.close();
775
+ }
776
+ }