@uuaid/pillar 2.7.3 → 2.8.1

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