@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.
- package/HOSTING-LIMITS.md +122 -0
- package/README.md +288 -1
- package/bin/carrier.mjs +104 -1
- package/bin/pillar-directory.mjs +34 -5
- package/bin/pillar-seed.mjs +129 -11
- package/bin/pillar.mjs +11 -4
- package/package.json +1 -1
- package/src/mailbox/mailbox.mjs +12 -0
- package/src/net/carrier-client.mjs +37 -9
- package/src/net/carrier-server.mjs +287 -25
- package/src/net/discovery.mjs +94 -0
- package/src/net/inbox-auth.mjs +100 -0
- package/src/net/refusals.mjs +24 -0
- package/src/net/seed-registry.mjs +374 -39
- package/src/net/seed-tier.mjs +35 -1
- package/src/net/tunnel-client.mjs +456 -0
- package/src/net/tunnel-relay.mjs +786 -0
- package/src/net/tunnel.mjs +292 -0
- package/src/notify-store.mjs +4 -1
- package/src/pillar.mjs +541 -9
- package/src/registry/directory-flags.mjs +7 -0
- package/src/registry/stats.mjs +1 -1
- package/src/vnext/continuity-cli.mjs +399 -0
- package/src/vnext/continuity.mjs +1801 -0
- package/src/vnext/init-cli.mjs +23 -7
- package/src/vnext/json-dir-mailbox.mjs +6 -0
- package/src/vnext/jsonl-mailbox.mjs +177 -23
- package/src/vnext/knock-cli.mjs +18 -0
- package/src/vnext/retired-import.mjs +556 -0
- package/src/vnext/verify-cli.mjs +1 -1
package/src/net/seed-tier.mjs
CHANGED
|
@@ -107,6 +107,33 @@ export const SEED_TIERS = [
|
|
|
107
107
|
|
|
108
108
|
export const SEED_TIER_NAMES = SEED_TIERS.map(t => t.name);
|
|
109
109
|
|
|
110
|
+
/**
|
|
111
|
+
* The highest rung each seed topology may hold (2.8.0; RedTeam c3ff4d, 085b71).
|
|
112
|
+
*
|
|
113
|
+
* A seed served through a relay shares the relay's availability, and the
|
|
114
|
+
* registry cannot observe it independently, so no relayed seed reaches
|
|
115
|
+
* `anchor`. `durable` (with its priority lane) needs a fresh attestation from
|
|
116
|
+
* a fleet relay this registry pins; when that lapses the seed holds `steady`.
|
|
117
|
+
* A seed on any other relay, or a migrated row that has not yet passed a
|
|
118
|
+
* challenge probe, stays at `probation`. A record with no topology is a direct
|
|
119
|
+
* seed (2.7.1 behaviour); an unknown topology fails low.
|
|
120
|
+
*/
|
|
121
|
+
export const TOPOLOGY_CAPS = Object.freeze({
|
|
122
|
+
direct: "anchor",
|
|
123
|
+
"relayed-vetted": "durable",
|
|
124
|
+
"relayed-lapsed": "steady",
|
|
125
|
+
"relayed-unvetted": "probation",
|
|
126
|
+
pending: "probation",
|
|
127
|
+
});
|
|
128
|
+
|
|
129
|
+
/** What a capped seed needs before it can climb past its cap. */
|
|
130
|
+
const CAP_NEEDS = Object.freeze({
|
|
131
|
+
"relayed-vetted": "a direct URL (a relayed seed stops at durable)",
|
|
132
|
+
"relayed-lapsed": "a fresh fleet-relay attestation",
|
|
133
|
+
"relayed-unvetted": "a fleet relay this registry pins",
|
|
134
|
+
pending: "a passing challenge probe through its relay",
|
|
135
|
+
});
|
|
136
|
+
|
|
110
137
|
/** Look a rung up by name. Unknown names resolve to `probation` (fail low). */
|
|
111
138
|
export function seedTier(name) {
|
|
112
139
|
return SEED_TIERS.find(t => t.name === name) ?? SEED_TIERS[0];
|
|
@@ -169,9 +196,16 @@ export function evaluateSeedTier(record, now = Date.now()) {
|
|
|
169
196
|
for (const t of SEED_TIERS) {
|
|
170
197
|
if (meets(t)) held = t; else break;
|
|
171
198
|
}
|
|
199
|
+
const topology = record?.topology ?? "direct";
|
|
200
|
+
let capIndex = SEED_TIERS.findIndex(t => t.name === TOPOLOGY_CAPS[topology]);
|
|
201
|
+
if (capIndex < 0) capIndex = 0; // @rule seed.topology-unknown-fails-low
|
|
202
|
+
const capped = SEED_TIERS.indexOf(held) >= capIndex && capIndex < SEED_TIERS.length - 1;
|
|
203
|
+
if (SEED_TIERS.indexOf(held) > capIndex) held = SEED_TIERS[capIndex]; // @rule seed.topology-cap
|
|
172
204
|
const nextRung = SEED_TIERS[SEED_TIERS.indexOf(held) + 1] ?? null;
|
|
173
205
|
|
|
174
206
|
const missing = [];
|
|
207
|
+
if (capped && CAP_NEEDS[topology]) missing.push(CAP_NEEDS[topology]);
|
|
208
|
+
if (capped && !CAP_NEEDS[topology]) missing.push("a known seed topology");
|
|
175
209
|
if (nextRung) {
|
|
176
210
|
if (ageMs < nextRung.minAgeMs) {
|
|
177
211
|
missing.push(`${Math.ceil((nextRung.minAgeMs - ageMs) / DAY)}d more enrolled`);
|
|
@@ -181,5 +215,5 @@ export function evaluateSeedTier(record, now = Date.now()) {
|
|
|
181
215
|
if (roundTrips < nextRung.minRoundTrips) missing.push(`${nextRung.minRoundTrips - roundTrips} more relay round-trips`);
|
|
182
216
|
}
|
|
183
217
|
|
|
184
|
-
return { tier: held.name, demoted: false, next: nextRung?.name ?? null, missing, ageMs, uptime, roundTrips };
|
|
218
|
+
return { tier: held.name, demoted: false, next: nextRung?.name ?? null, missing, ageMs, uptime, roundTrips, topology, capped };
|
|
185
219
|
}
|
|
@@ -0,0 +1,456 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Seed side of seed-over-egress (2.8.0): one outbound WebSocket from a seed
|
|
3
|
+
* to its relay, and a replay of each tunnelled request to the seed's own
|
|
4
|
+
* loopback carrier. The seed never listens on anything another machine can
|
|
5
|
+
* reach and never dials any host but its relay and its own loopback port.
|
|
6
|
+
*
|
|
7
|
+
* Protocol (./tunnel.mjs): the relay says hello {origin, nonce}; the seed
|
|
8
|
+
* checks the origin is the one it was configured with and answers with a
|
|
9
|
+
* signed auth bound to that origin, the one-use nonce and its full identity;
|
|
10
|
+
* the relay answers ready {url}, which must be `<origin>/e/<localId>`.
|
|
11
|
+
*
|
|
12
|
+
* Each request is checked again here: only the four carrier routes, and a
|
|
13
|
+
* client address that is a literal IP, sent on as the only X-Forwarded-For
|
|
14
|
+
* (the seed's carrier trusts loopback, so per-IP budgets charge the client).
|
|
15
|
+
* Logs carry state changes only, never a header, path, query or body; a
|
|
16
|
+
* reason from the relay is shown only when it is one the relay defines.
|
|
17
|
+
*
|
|
18
|
+
* Backoff (V1 2b5070): it resets only after a tunnel stayed up for
|
|
19
|
+
* `stableMs` (60 s), and a tunnel `replaced` by the relay backs off. A relay
|
|
20
|
+
* that refuses with `seed-already-connected` (another process holds this
|
|
21
|
+
* seed key there) is retried for `takeoverWaitMs` (45 s, about two ping
|
|
22
|
+
* intervals, enough for the relay to drop a dead process's tunnel); then
|
|
23
|
+
* the seed stops, whether or not it served before (V1 0a3350: after a relay
|
|
24
|
+
* restart the other process can win the reconnect, and a seed that kept
|
|
25
|
+
* retrying would split the mailbox for good). One that never served rejects
|
|
26
|
+
* start(); one that served calls `onGiveUp`. A reconnect of this same
|
|
27
|
+
* process (same instance) replaces its own tunnel and never sees that refusal.
|
|
28
|
+
*/
|
|
29
|
+
import { request as httpRequest } from "node:http";
|
|
30
|
+
import { isIP } from "node:net";
|
|
31
|
+
import { performance } from "node:perf_hooks";
|
|
32
|
+
import { WebSocket } from "ws";
|
|
33
|
+
import {
|
|
34
|
+
FRAME, FRAME_DATA_BYTES, MAX_FRAME_PAYLOAD, CHALLENGE_RE, allowedRoute, pickRequestHeaders,
|
|
35
|
+
encodeFrame, encodeJsonFrame, decodeFrame, signTunnelAuth, relayedUrlFor, newInstanceId, RELAY_REASONS,
|
|
36
|
+
} from "./tunnel.mjs";
|
|
37
|
+
|
|
38
|
+
/** Refusals that will not change by retrying: the seed binary exits 2 on these at start. */
|
|
39
|
+
export const DEFINITE_REFUSALS = Object.freeze(new Set([
|
|
40
|
+
"not-allowed", "bad-auth", "bad-public-key", "bad-sig-encoding", "bad-signature", "uuaid-key-mismatch",
|
|
41
|
+
"clock-skew", "no-tunnels", "upgrade-blocked", "origin-mismatch", "url-mismatch", "revoked",
|
|
42
|
+
]));
|
|
43
|
+
|
|
44
|
+
/** A tunnel must stay up this long before the reconnect backoff starts over (V1 2b5070). */
|
|
45
|
+
export const STABLE_TUNNEL_MS = 60_000;
|
|
46
|
+
/** How long a new seed waits for another process to release its key at the relay. */
|
|
47
|
+
export const TAKEOVER_WAIT_MS = 45_000;
|
|
48
|
+
/** After `replaced`, reconnect no sooner than this many doublings of the minimum (about 16 s). */
|
|
49
|
+
const REPLACED_MIN_ATTEMPT = 5;
|
|
50
|
+
/** While another process holds the key, retry at least this often so a takeover is quick. */
|
|
51
|
+
const CONFLICT_RETRY_MAX_MS = 10_000;
|
|
52
|
+
/** One stream's answer bytes waiting here past this pause its local answer. */
|
|
53
|
+
const STREAM_SEND_HIGH_WATER = 128 * 1024;
|
|
54
|
+
/** The most credit one relay message may grant (a sanity bound on peer input). */
|
|
55
|
+
const MAX_CREDIT_GRANT = 64 * 1024 * 1024;
|
|
56
|
+
|
|
57
|
+
/** A relay's reason as this seed may show it: a defined reason, or "refused". */
|
|
58
|
+
function relayReason(reason) {
|
|
59
|
+
let shown = reason;
|
|
60
|
+
if (!RELAY_REASONS.has(reason)) shown = "refused"; // @rule seed.known-reasons-only
|
|
61
|
+
return shown;
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
export class TunnelClient {
|
|
65
|
+
/**
|
|
66
|
+
* @param {object} o
|
|
67
|
+
* relayOrigin canonical relay origin (pillar-seed --relay)
|
|
68
|
+
* keychain the loaded seed keychain
|
|
69
|
+
* localPort the seed carrier's loopback port
|
|
70
|
+
* localHost 127.0.0.1 or ::1
|
|
71
|
+
*/
|
|
72
|
+
constructor({
|
|
73
|
+
relayOrigin, keychain, localPort, localHost = "127.0.0.1", log = () => {}, backoff = {}, maxStreams = 80,
|
|
74
|
+
maxRequestBytes = 2 * 1024 * 1024 + 8192, stableMs = STABLE_TUNNEL_MS, takeoverWaitMs = TAKEOVER_WAIT_MS,
|
|
75
|
+
mono = () => performance.now(), onGiveUp = null, responseBudget = null,
|
|
76
|
+
}) {
|
|
77
|
+
this.relayOrigin = relayOrigin;
|
|
78
|
+
this.keychain = keychain;
|
|
79
|
+
this.localPort = localPort;
|
|
80
|
+
this.localHost = localHost;
|
|
81
|
+
this.log = log;
|
|
82
|
+
this.minBackoffMs = backoff.minMs ?? 1000;
|
|
83
|
+
this.maxBackoffMs = backoff.maxMs ?? 60_000;
|
|
84
|
+
this.maxStreams = maxStreams;
|
|
85
|
+
this.maxRequestBytes = maxRequestBytes;
|
|
86
|
+
this.url = relayedUrlFor(relayOrigin, keychain._identity.publicKeyHex);
|
|
87
|
+
// This process, as the relay sees it (signed into every auth).
|
|
88
|
+
this.instance = newInstanceId();
|
|
89
|
+
this.stableMs = stableMs;
|
|
90
|
+
this.takeoverWaitMs = takeoverWaitMs;
|
|
91
|
+
this.mono = mono;
|
|
92
|
+
// Called once, with the error, when a seed that served gives up because
|
|
93
|
+
// another process holds its key (pillar-seed exits 2).
|
|
94
|
+
this.onGiveUp = onGiveUp;
|
|
95
|
+
// The carrier's ResponseBudget (./carrier-server.mjs), or null: each local
|
|
96
|
+
// request carries a ticket, and an inbox page it reserved is returned only
|
|
97
|
+
// when this stream's answer has gone to the relay or the stream is dropped.
|
|
98
|
+
this.responseBudget = responseBudget;
|
|
99
|
+
this.tickets = new Map();
|
|
100
|
+
this.readyAt = null;
|
|
101
|
+
this.conflictSince = null;
|
|
102
|
+
// Answer bytes the relay has paid for and this seed may send (granted by
|
|
103
|
+
// `{t:"credit"}` messages), and the answer frames waiting for credit, per
|
|
104
|
+
// stream in order, streams taking turns (RedTeam 87bb0b: the relay paces
|
|
105
|
+
// by credit, not by pausing).
|
|
106
|
+
this.credit = 0;
|
|
107
|
+
this.outQueue = new Map();
|
|
108
|
+
this.outQueued = 0;
|
|
109
|
+
// Streams the relay asked us to hold (their client is behind): their
|
|
110
|
+
// frames stay queued, in order, and their local answer is paused.
|
|
111
|
+
this.heldStreams = new Set();
|
|
112
|
+
// When each client address last sent a frame (a turn number), so that
|
|
113
|
+
// addresses take turns for credit, not streams (C7-2).
|
|
114
|
+
this.addrTurn = new Map();
|
|
115
|
+
this._turn = 0;
|
|
116
|
+
// One record per stream from its request until its END is sent or it is
|
|
117
|
+
// reset, whatever its local answer has done (C7-1).
|
|
118
|
+
this.streams = new Map();
|
|
119
|
+
this.state = "idle";
|
|
120
|
+
this.attempt = 0;
|
|
121
|
+
this.everReady = false;
|
|
122
|
+
this.stopped = false;
|
|
123
|
+
this.ws = null;
|
|
124
|
+
this._timer = null;
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
/** Connect; resolves at the first `ready`, rejects on a definite refusal before it. */
|
|
128
|
+
start() {
|
|
129
|
+
this.stopped = false;
|
|
130
|
+
return new Promise((resolve, reject) => {
|
|
131
|
+
this._firstReady = { resolve, reject };
|
|
132
|
+
this._connect();
|
|
133
|
+
});
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
stop() {
|
|
137
|
+
this.stopped = true;
|
|
138
|
+
clearTimeout(this._timer);
|
|
139
|
+
for (const s of this.streams.values()) s.lreq?.destroy();
|
|
140
|
+
this.streams.clear();
|
|
141
|
+
this._clearOut();
|
|
142
|
+
try { this.ws?.terminate(); } catch (_e) { /* gone */ }
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
_connect() {
|
|
146
|
+
if (this.stopped) return;
|
|
147
|
+
this.state = "connecting";
|
|
148
|
+
let refusal = null;
|
|
149
|
+
const wsUrl = `${this.relayOrigin.replace(/^http/, "ws")}/v1/tunnel`;
|
|
150
|
+
const ws = new WebSocket(wsUrl, { maxPayload: MAX_FRAME_PAYLOAD, perMessageDeflate: false, handshakeTimeout: 10_000, followRedirects: false });
|
|
151
|
+
this.ws = ws;
|
|
152
|
+
ws.on("unexpected-response", (req, res) => {
|
|
153
|
+
// A carrier that does not accept tunnels answers the upgrade like any
|
|
154
|
+
// unknown path; a full relay answers 503 and is retried. A relay that
|
|
155
|
+
// takes tunnels answers 426 when its proxy dropped the Upgrade headers.
|
|
156
|
+
if (res.statusCode === 404) refusal = "no-tunnels";
|
|
157
|
+
if (res.statusCode === 426) refusal = "upgrade-blocked"; // @rule seed.upgrade-blocked
|
|
158
|
+
req.destroy();
|
|
159
|
+
ws.terminate();
|
|
160
|
+
});
|
|
161
|
+
ws.on("message", (data, isBinary) => {
|
|
162
|
+
if (this.state === "ready") {
|
|
163
|
+
if (isBinary) this._onRelayFrame(data);
|
|
164
|
+
else this._onControl(data, (r) => { refusal = r; });
|
|
165
|
+
return;
|
|
166
|
+
}
|
|
167
|
+
if (isBinary) return ws.terminate();
|
|
168
|
+
let msg = null;
|
|
169
|
+
try { msg = JSON.parse(String(data)); } catch (_e) { return ws.terminate(); }
|
|
170
|
+
if (msg?.t === "hello" && this.state === "connecting") {
|
|
171
|
+
if (msg.origin !== this.relayOrigin) { refusal = "origin-mismatch"; return ws.terminate(); } // @rule seed.tunnel-origin-pinned
|
|
172
|
+
if (typeof msg.nonce !== "string" || !CHALLENGE_RE.test(msg.nonce)) return ws.terminate();
|
|
173
|
+
this.state = "auth-sent";
|
|
174
|
+
ws.send(JSON.stringify(signTunnelAuth(this.keychain, { origin: this.relayOrigin, nonce: msg.nonce, instance: this.instance })));
|
|
175
|
+
} else if (msg?.t === "ready" && this.state === "auth-sent") {
|
|
176
|
+
if (msg.url !== this.url) { refusal = "url-mismatch"; return ws.terminate(); } // @rule seed.tunnel-url-pinned
|
|
177
|
+
this.state = "ready";
|
|
178
|
+
this.readyAt = this.mono();
|
|
179
|
+
this.conflictSince = null;
|
|
180
|
+
this.everReady = true;
|
|
181
|
+
this.log(`tunnel: up, serving ${this.url}`);
|
|
182
|
+
this._firstReady?.resolve(this.url);
|
|
183
|
+
this._firstReady = null;
|
|
184
|
+
} else if (msg?.t === "error") {
|
|
185
|
+
refusal = relayReason(msg.reason);
|
|
186
|
+
}
|
|
187
|
+
});
|
|
188
|
+
ws.on("close", (code) => {
|
|
189
|
+
for (const s of this.streams.values()) s.lreq?.destroy();
|
|
190
|
+
this.streams.clear();
|
|
191
|
+
this._clearOut();
|
|
192
|
+
const wasReady = this.state === "ready";
|
|
193
|
+
this.state = "down";
|
|
194
|
+
if (this.stopped) return;
|
|
195
|
+
if (!this.everReady && refusal && DEFINITE_REFUSALS.has(refusal)) {
|
|
196
|
+
this._firstReady?.reject(Object.assign(new Error(refusal), { definite: true, reason: refusal }));
|
|
197
|
+
this._firstReady = null;
|
|
198
|
+
this.stopped = true;
|
|
199
|
+
return;
|
|
200
|
+
}
|
|
201
|
+
const now = this.mono();
|
|
202
|
+
// The backoff starts over only after a tunnel that stayed up (V1 2b5070).
|
|
203
|
+
if (wasReady && now - this.readyAt >= this.stableMs) this.attempt = 0; // @rule seed.backoff-reset-after-stable
|
|
204
|
+
if (refusal === "replaced") this.attempt = Math.max(this.attempt, REPLACED_MIN_ATTEMPT); // @rule seed.replaced-backs-off
|
|
205
|
+
let delay = this._nextDelay();
|
|
206
|
+
if (refusal === "seed-already-connected") {
|
|
207
|
+
if (this.conflictSince === null) {
|
|
208
|
+
this.conflictSince = now;
|
|
209
|
+
this.log(`tunnel: another process is serving this seed key through ${this.relayOrigin}; waiting up to ${Math.round(this.takeoverWaitMs / 1000)}s for it to stop`);
|
|
210
|
+
}
|
|
211
|
+
const waited = now - this.conflictSince;
|
|
212
|
+
let giveUp = false;
|
|
213
|
+
if (waited >= this.takeoverWaitMs) giveUp = true; // @rule seed.conflict-window-exit
|
|
214
|
+
if (giveUp) {
|
|
215
|
+
const err = Object.assign(new Error("seed-already-connected"), { definite: true, reason: "seed-already-connected", served: this.everReady });
|
|
216
|
+
this.stopped = true;
|
|
217
|
+
this.log(`tunnel: giving up: another process kept this seed key at ${this.relayOrigin} for ${Math.round(waited / 1000)}s`);
|
|
218
|
+
const pending = this._firstReady;
|
|
219
|
+
this._firstReady = null;
|
|
220
|
+
if (pending) pending.reject(err);
|
|
221
|
+
if (!pending) this.onGiveUp?.(err); // @rule seed.served-conflict-exits
|
|
222
|
+
return;
|
|
223
|
+
}
|
|
224
|
+
// Retry often enough to see the other process go, and to give up on time.
|
|
225
|
+
delay = Math.min(delay, CONFLICT_RETRY_MAX_MS, Math.max(0, this.takeoverWaitMs - waited));
|
|
226
|
+
this._timer = setTimeout(() => this._connect(), delay);
|
|
227
|
+
this._timer.unref?.();
|
|
228
|
+
return;
|
|
229
|
+
}
|
|
230
|
+
if (wasReady || this.attempt <= 1) this.log(`tunnel: down (${refusal ?? code}); reconnecting in ${Math.round(delay / 100) / 10}s`);
|
|
231
|
+
this._timer = setTimeout(() => this._connect(), delay);
|
|
232
|
+
this._timer.unref?.();
|
|
233
|
+
});
|
|
234
|
+
ws.on("error", () => { /* 'close' follows */ });
|
|
235
|
+
}
|
|
236
|
+
|
|
237
|
+
_onControl(data, setRefusal) {
|
|
238
|
+
let msg = null;
|
|
239
|
+
try { msg = JSON.parse(String(data)); } catch (_e) { return; }
|
|
240
|
+
if (msg?.t === "error") setRefusal(relayReason(msg.reason));
|
|
241
|
+
if (msg?.t === "credit" && Number.isSafeInteger(msg.bytes) && msg.bytes > 0 && msg.bytes <= MAX_CREDIT_GRANT) {
|
|
242
|
+
this.credit += msg.bytes;
|
|
243
|
+
this._drainOut();
|
|
244
|
+
}
|
|
245
|
+
// Only for a stream this seed still has, so a relay cannot grow the set.
|
|
246
|
+
if ((msg?.t === "hold" || msg?.t === "resume") && (this.streams.has(msg.id) || this.outQueue.has(msg.id))) {
|
|
247
|
+
const s = this.streams.get(msg.id);
|
|
248
|
+
if (msg.t === "hold") {
|
|
249
|
+
this.heldStreams.add(msg.id);
|
|
250
|
+
if (s && !s.held) { s.held = true; s.lres?.pause(); }
|
|
251
|
+
} else {
|
|
252
|
+
this.heldStreams.delete(msg.id);
|
|
253
|
+
this._drainOut();
|
|
254
|
+
}
|
|
255
|
+
}
|
|
256
|
+
}
|
|
257
|
+
|
|
258
|
+
/** Queue an answer frame for stream `id`: data bytes (`buf`) or its end. */
|
|
259
|
+
_queueOut(item) {
|
|
260
|
+
const q = this.outQueue.get(item.id);
|
|
261
|
+
if (q) q.push(item); else this.outQueue.set(item.id, [item]);
|
|
262
|
+
if (item.buf) { this.outQueued += item.buf.length; this._queuedFor(item.id, item.buf.length); }
|
|
263
|
+
this._drainOut();
|
|
264
|
+
}
|
|
265
|
+
|
|
266
|
+
/**
|
|
267
|
+
* Send queued answer frames, each stream's in order, data only within the
|
|
268
|
+
* credit the relay granted. Client addresses take turns, one frame each,
|
|
269
|
+
* the address that sent longest ago first, so one address with many
|
|
270
|
+
* streams gets the same share as one with a single stream (C7-2). Within
|
|
271
|
+
* an address its streams take turns: a stream that sent moves to the back.
|
|
272
|
+
* A held stream's frames are skipped (they wait in place), so a client that
|
|
273
|
+
* is behind never blocks the others.
|
|
274
|
+
*/
|
|
275
|
+
_drainOut() {
|
|
276
|
+
for (let sent = true; sent;) {
|
|
277
|
+
sent = false;
|
|
278
|
+
// Each address's first stream in line that is not held and can send:
|
|
279
|
+
// without credit only an END can go, and it needs none, so an END is
|
|
280
|
+
// never kept waiting behind a stream of its address that waits for
|
|
281
|
+
// credit (its page's ticket ends with it).
|
|
282
|
+
const next = new Map();
|
|
283
|
+
for (const id of this.outQueue.keys()) {
|
|
284
|
+
if (this.heldStreams.has(id)) continue; // @rule seed.hold-skips-stream
|
|
285
|
+
if (this.credit < 1 && !this.outQueue.get(id)[0].end) continue; // @rule seed.send-end-without-credit
|
|
286
|
+
const ip = this.streams.get(id)?.ip ?? "";
|
|
287
|
+
if (!next.has(ip)) next.set(ip, id);
|
|
288
|
+
}
|
|
289
|
+
const order = [...next.keys()].sort((a, b) => (this.addrTurn.get(a) ?? 0) - (this.addrTurn.get(b) ?? 0));
|
|
290
|
+
for (const ip of order) {
|
|
291
|
+
if (!this._sendNext(next.get(ip))) continue;
|
|
292
|
+
sent = true;
|
|
293
|
+
this.addrTurn.set(ip, ++this._turn); // @rule seed.send-fair-address
|
|
294
|
+
}
|
|
295
|
+
}
|
|
296
|
+
// Forget turns of addresses with no stream left (at most one per stream).
|
|
297
|
+
if (this.addrTurn.size > this.streams.size) {
|
|
298
|
+
const live = new Set([...this.streams.values()].map((x) => x.ip));
|
|
299
|
+
for (const ip of [...this.addrTurn.keys()]) if (!live.has(ip)) this.addrTurn.delete(ip);
|
|
300
|
+
}
|
|
301
|
+
// A stream whose own queue is short again, and that is not held, reads on.
|
|
302
|
+
for (const [id, s] of this.streams) {
|
|
303
|
+
if (s.held && !this.heldStreams.has(id) && (s.queued ?? 0) <= STREAM_SEND_HIGH_WATER) {
|
|
304
|
+
s.held = false; s.lres?.resume();
|
|
305
|
+
}
|
|
306
|
+
}
|
|
307
|
+
}
|
|
308
|
+
|
|
309
|
+
/** Send stream `id`'s next frame if it may go: its END always, data within credit. True when one went. */
|
|
310
|
+
_sendNext(id) {
|
|
311
|
+
const q = this.outQueue.get(id);
|
|
312
|
+
if (!q) return false;
|
|
313
|
+
const item = q[0];
|
|
314
|
+
if (item.end) {
|
|
315
|
+
this._send(encodeFrame(FRAME.RES_END, id));
|
|
316
|
+
this.outQueue.delete(id);
|
|
317
|
+
this._endTicket(id);
|
|
318
|
+
// Its END is sent: the stream is over at this end of the tunnel.
|
|
319
|
+
this.streams.delete(id); // @rule seed.tunnel-stream-until-end
|
|
320
|
+
return true;
|
|
321
|
+
}
|
|
322
|
+
let n = Math.min(item.buf.length, FRAME_DATA_BYTES);
|
|
323
|
+
n = Math.min(n, this.credit); // @rule seed.send-within-credit
|
|
324
|
+
if (n < 1) return false;
|
|
325
|
+
this._send(encodeFrame(FRAME.RES_DATA, id, item.buf.subarray(0, n)));
|
|
326
|
+
this.credit -= n;
|
|
327
|
+
this.outQueued -= n;
|
|
328
|
+
this._queuedFor(id, -n);
|
|
329
|
+
if (n < item.buf.length) item.buf = item.buf.subarray(n); else q.shift();
|
|
330
|
+
if (!q.length) { this.outQueue.delete(id); return true; }
|
|
331
|
+
// To the back of the line, so the next frame goes to the next stream.
|
|
332
|
+
this.outQueue.delete(id); // @rule seed.send-round-robin
|
|
333
|
+
this.outQueue.set(id, q);
|
|
334
|
+
return true;
|
|
335
|
+
}
|
|
336
|
+
|
|
337
|
+
/** Stream `id` is over: give back the inbox page its request reserved. */
|
|
338
|
+
_endTicket(id) {
|
|
339
|
+
const t = this.tickets.get(id);
|
|
340
|
+
if (t === undefined) return;
|
|
341
|
+
this.tickets.delete(id);
|
|
342
|
+
this.responseBudget?.end(t);
|
|
343
|
+
}
|
|
344
|
+
|
|
345
|
+
_queuedFor(id, n) {
|
|
346
|
+
const s = this.streams.get(id);
|
|
347
|
+
if (s) s.queued = (s.queued ?? 0) + n;
|
|
348
|
+
}
|
|
349
|
+
|
|
350
|
+
/** Forget queued answer frames for one stream (reset), or for all (tunnel gone). */
|
|
351
|
+
_purgeOut(id) {
|
|
352
|
+
this._endTicket(id);
|
|
353
|
+
this.heldStreams.delete(id);
|
|
354
|
+
for (const item of this.outQueue.get(id) ?? []) if (item.buf) this.outQueued -= item.buf.length;
|
|
355
|
+
this.outQueue.delete(id);
|
|
356
|
+
}
|
|
357
|
+
|
|
358
|
+
_clearOut() {
|
|
359
|
+
for (const id of [...this.tickets.keys()]) this._endTicket(id);
|
|
360
|
+
this.outQueue = new Map();
|
|
361
|
+
this.outQueued = 0;
|
|
362
|
+
this.credit = 0;
|
|
363
|
+
this.heldStreams.clear();
|
|
364
|
+
this.addrTurn.clear();
|
|
365
|
+
}
|
|
366
|
+
|
|
367
|
+
_nextDelay() {
|
|
368
|
+
this.attempt++;
|
|
369
|
+
const base = Math.min(this.maxBackoffMs, this.minBackoffMs * 2 ** Math.min(this.attempt - 1, 16));
|
|
370
|
+
return Math.round(base * (0.8 + Math.random() * 0.4));
|
|
371
|
+
}
|
|
372
|
+
|
|
373
|
+
_send(frame) {
|
|
374
|
+
try { this.ws?.send(frame); } catch (_e) { /* close follows */ }
|
|
375
|
+
}
|
|
376
|
+
|
|
377
|
+
_reset(id) {
|
|
378
|
+
const s = this.streams.get(id);
|
|
379
|
+
s?.lreq?.destroy();
|
|
380
|
+
this.streams.delete(id);
|
|
381
|
+
this._purgeOut(id);
|
|
382
|
+
this._send(encodeFrame(FRAME.RESET, id));
|
|
383
|
+
}
|
|
384
|
+
|
|
385
|
+
_onRelayFrame(data) {
|
|
386
|
+
const f = decodeFrame(Buffer.isBuffer(data) ? data : Buffer.from(data));
|
|
387
|
+
if (!f) return;
|
|
388
|
+
if (f.kind === FRAME.REQ) return this._open(f.id, f.payload);
|
|
389
|
+
const s = this.streams.get(f.id);
|
|
390
|
+
if (!s) return;
|
|
391
|
+
if (f.kind === FRAME.RESET) {
|
|
392
|
+
// Whatever its local answer has done (still running, or complete with
|
|
393
|
+
// frames queued for credit): its frames and its page go now (C7-1).
|
|
394
|
+
s.lreq.destroy();
|
|
395
|
+
this.streams.delete(f.id);
|
|
396
|
+
this._purgeOut(f.id); // @rule seed.tunnel-reset-purges
|
|
397
|
+
return;
|
|
398
|
+
}
|
|
399
|
+
// A complete local answer needs no more of its request.
|
|
400
|
+
if (s.localDone) return;
|
|
401
|
+
if (f.kind === FRAME.REQ_DATA) {
|
|
402
|
+
s.bytes += f.payload.length;
|
|
403
|
+
if (s.bytes > this.maxRequestBytes) return this._reset(f.id);
|
|
404
|
+
s.lreq.write(f.payload);
|
|
405
|
+
} else if (f.kind === FRAME.REQ_END) {
|
|
406
|
+
s.lreq.end();
|
|
407
|
+
}
|
|
408
|
+
}
|
|
409
|
+
|
|
410
|
+
_open(id, payload) {
|
|
411
|
+
let meta = null;
|
|
412
|
+
try { meta = JSON.parse(payload.toString("utf-8")); } catch (_e) { return this._reset(id); }
|
|
413
|
+
if (this.streams.has(id)) return this._reset(id);
|
|
414
|
+
if (!allowedRoute(meta?.method, meta?.path ?? "")) return this._reset(id); // @rule seed.tunnel-route-allow-list
|
|
415
|
+
if (typeof meta.path !== "string" || !meta.path.startsWith("/v1/")) return this._reset(id);
|
|
416
|
+
if (isIP(String(meta.ip ?? "")) === 0) return this._reset(id); // @rule seed.tunnel-client-ip
|
|
417
|
+
if (this.streams.size >= this.maxStreams) return this._reset(id);
|
|
418
|
+
const headers = { ...pickRequestHeaders(meta.headers ?? {}), "x-forwarded-for": meta.ip };
|
|
419
|
+
if (this.responseBudget) {
|
|
420
|
+
const t = this.responseBudget.ticket();
|
|
421
|
+
this.tickets.set(id, t);
|
|
422
|
+
headers["x-pillar-budget-ticket"] = t;
|
|
423
|
+
}
|
|
424
|
+
const lreq = httpRequest({ host: this.localHost, port: this.localPort, method: meta.method, path: meta.path, headers, agent: false });
|
|
425
|
+
const s = { lreq, bytes: 0, ip: meta.ip, localDone: false };
|
|
426
|
+
this.streams.set(id, s);
|
|
427
|
+
lreq.on("response", (lres) => {
|
|
428
|
+
this._send(encodeJsonFrame(FRAME.RES, id, { status: lres.statusCode, headers: { "content-type": "application/json" } }));
|
|
429
|
+
s.lres = lres;
|
|
430
|
+
lres.on("data", (chunk) => {
|
|
431
|
+
if (!this.streams.has(id)) return;
|
|
432
|
+
this._queueOut({ id, buf: chunk });
|
|
433
|
+
// Answer bytes wait here for credit (or while the relay holds this
|
|
434
|
+
// stream); past this stream's high-water mark the local answer
|
|
435
|
+
// pauses, so the rest stays in the carrier's reserved budget. Per
|
|
436
|
+
// stream only: a seed-wide mark would let held streams pause the
|
|
437
|
+
// healthy ones. Each stream holds at most this plus one read here,
|
|
438
|
+
// and a tunnel has at most maxStreams streams.
|
|
439
|
+
const over = (s.queued ?? 0) > STREAM_SEND_HIGH_WATER || this.heldStreams.has(id);
|
|
440
|
+
if (over && !s.held) { s.held = true; lres.pause(); }
|
|
441
|
+
});
|
|
442
|
+
lres.on("end", () => {
|
|
443
|
+
if (this.streams.get(id) !== s) return;
|
|
444
|
+
// The stream stays until its END is sent or it is reset.
|
|
445
|
+
s.localDone = true;
|
|
446
|
+
this._queueOut({ id, end: true });
|
|
447
|
+
});
|
|
448
|
+
// A local answer that stops before its end (the carrier went, a socket
|
|
449
|
+
// error) is reset, so the relay ends the stream now. Node emits close
|
|
450
|
+
// after error, and after end on a complete answer (Node 22).
|
|
451
|
+
lres.on("error", () => { /* close follows */ });
|
|
452
|
+
lres.on("close", () => { if (!s.localDone && this.streams.get(id) === s) this._reset(id); }); // @rule seed.tunnel-local-abort
|
|
453
|
+
});
|
|
454
|
+
lreq.on("error", () => { if (!s.localDone && this.streams.get(id) === s) this._reset(id); });
|
|
455
|
+
}
|
|
456
|
+
}
|