@johnhenry/wsh 0.36.0 → 0.38.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +468 -11
- package/package.json +5 -1
- package/src/bridge-seal.mjs +77 -0
- package/src/channel-binding.mjs +124 -0
- package/src/client.mjs +374 -40
- package/src/e2e-exchange.mjs +51 -1
- package/src/forward-node.mjs +118 -0
- package/src/gateway-channel.mjs +250 -0
- package/src/gateway-client.mjs +307 -0
- package/src/gateway-datagram.mjs +191 -0
- package/src/host.d.ts +3 -3
- package/src/index.d.ts +142 -0
- package/src/index.mjs +14 -0
- package/src/memory-host.d.ts +17 -3
- package/src/memory-host.mjs +31 -7
- package/src/messages.gen.mjs +59 -7
- package/src/operator-proof.mjs +135 -0
- package/src/pipe-relay.d.ts +49 -0
- package/src/pipe-relay.mjs +274 -0
- package/src/reverse-host.d.ts +2 -2
- package/src/reverse-host.mjs +126 -15
- package/src/server/address-guard.mjs +164 -0
- package/src/server/client-env.mjs +60 -0
- package/src/server/connection.mjs +70 -12
- package/src/server/gateway-core.mjs +189 -0
- package/src/server/gateway.mjs +596 -81
- package/src/server/index.d.ts +132 -5
- package/src/server/index.mjs +29 -3
- package/src/server/pty.mjs +1 -0
- package/src/server/relay.mjs +45 -2
- package/src/server/reverse-policy.mjs +98 -0
- package/src/server/udp-policy.mjs +59 -0
- package/src/server/unix-policy.mjs +120 -0
- package/src/server/webtransport.mjs +31 -0
- package/src/transport-ws.mjs +16 -0
- package/src/transport.mjs +71 -0
package/src/e2e-exchange.mjs
CHANGED
|
@@ -89,6 +89,34 @@ export function keyExchangeTranscript({ sessionId, algorithm, initiatorKey, resp
|
|
|
89
89
|
return out;
|
|
90
90
|
}
|
|
91
91
|
|
|
92
|
+
const INIT_LABEL = new TextEncoder().encode('wsh-e2e-keyexchange-init-v1\0');
|
|
93
|
+
|
|
94
|
+
/**
|
|
95
|
+
* The bytes an INITIATOR signs in its round-1 `KeyExchange` (wsh #117), so that both halves are authenticated: the
|
|
96
|
+
* label (different from the responder's, so neither signature can pass for the other), the session id, the algorithm,
|
|
97
|
+
* its own ephemeral key and the identity key of the responder it means to reach. The responder's signed reply then
|
|
98
|
+
* covers both ephemeral keys.
|
|
99
|
+
* @param {{ sessionId: string, algorithm: string, initiatorKey: Uint8Array, responderIdentity: Uint8Array }} t
|
|
100
|
+
*/
|
|
101
|
+
export function initiatorTranscript({ sessionId, algorithm, initiatorKey, responderIdentity }) {
|
|
102
|
+
const parts = [INIT_LABEL, lp(enc.encode(sessionId)), lp(enc.encode(algorithm)), lp(initiatorKey), lp(responderIdentity)];
|
|
103
|
+
const out = new Uint8Array(parts.reduce((n, p) => n + p.length, 0));
|
|
104
|
+
let off = 0;
|
|
105
|
+
for (const p of parts) { out.set(p, off); off += p.length; }
|
|
106
|
+
return out;
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
/** Verify an initiator's `KeyExchange.signature` against its identity key. */
|
|
110
|
+
export async function verifyInitiatorSignature(initiatorIdentity, signature, transcript) {
|
|
111
|
+
if (!(signature instanceof Uint8Array) || signature.length !== 64) return false;
|
|
112
|
+
try {
|
|
113
|
+
const key = initiatorIdentity instanceof Uint8Array ? await importPublicKeyRaw(initiatorIdentity) : initiatorIdentity;
|
|
114
|
+
return await verifyBytes(key, signature, initiatorTranscript(transcript));
|
|
115
|
+
} catch {
|
|
116
|
+
return false;
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
|
|
92
120
|
/**
|
|
93
121
|
* Verify a responder's `KeyExchange.signature`.
|
|
94
122
|
* @param {Uint8Array | CryptoKey} peerIdentity - the host's raw 32-byte Ed25519 public key (or an imported one)
|
|
@@ -125,12 +153,21 @@ export class E2EResponder {
|
|
|
125
153
|
* @param {object} [opts]
|
|
126
154
|
* @param {CryptoKey | null} [opts.signKey] - long-term Ed25519 private key; given, the reply is signed
|
|
127
155
|
* @param {boolean} [opts.hybrid=true] - offer X25519+ML-KEM-768 when the initiator asks for it
|
|
156
|
+
* @param {Uint8Array | null} [opts.identity] - this responder's raw 32-byte identity key (what an initiator signs as `responderIdentity`)
|
|
157
|
+
* @param {{ publicKey: Uint8Array, require?: boolean } | null} [opts.initiator] - the operator's identity key, already
|
|
158
|
+
* proven (a `ReverseProof`): a round-1 `signature` is verified against it and a bad one refuses the exchange;
|
|
159
|
+
* with `require`, a missing one does too (#117)
|
|
128
160
|
*/
|
|
129
|
-
constructor({ signKey = null, hybrid = true } = {}) {
|
|
161
|
+
constructor({ signKey = null, hybrid = true, identity = null, initiator = null } = {}) {
|
|
130
162
|
this.#sign = signKey;
|
|
131
163
|
this.#hybrid = hybrid;
|
|
164
|
+
this.#identity = identity;
|
|
165
|
+
this.#initiator = initiator;
|
|
132
166
|
}
|
|
133
167
|
|
|
168
|
+
#identity;
|
|
169
|
+
#initiator;
|
|
170
|
+
|
|
134
171
|
get signs() { return !!this.#sign; }
|
|
135
172
|
|
|
136
173
|
/** Forget unfinished exchanges (the connection ended). */
|
|
@@ -166,6 +203,19 @@ export class E2EResponder {
|
|
|
166
203
|
const wantHybrid = algorithm === E2E_ALGORITHM_HYBRID && this.#hybrid
|
|
167
204
|
&& peerKem instanceof Uint8Array && peerKem.length === MLKEM768_PUBLIC_KEY_LENGTH;
|
|
168
205
|
|
|
206
|
+
// The initiator's half (wsh #117): signed by the operator key this connection already proved.
|
|
207
|
+
let initiatorAuthenticated = false;
|
|
208
|
+
if (this.#initiator) {
|
|
209
|
+
if (msg.signature !== undefined) {
|
|
210
|
+
initiatorAuthenticated = !!this.#identity && await verifyInitiatorSignature(this.#initiator.publicKey, msg.signature, {
|
|
211
|
+
sessionId, algorithm, initiatorKey: peerPub, responderIdentity: this.#identity,
|
|
212
|
+
});
|
|
213
|
+
if (!initiatorAuthenticated) throw Object.assign(new Error('KeyExchange initiator signature does not verify'), { code: 'E2E_INITIATOR_UNAUTHENTICATED' });
|
|
214
|
+
} else if (this.#initiator.require) {
|
|
215
|
+
throw Object.assign(new Error('KeyExchange without the initiator signature this host requires'), { code: 'E2E_INITIATOR_UNAUTHENTICATED' });
|
|
216
|
+
}
|
|
217
|
+
}
|
|
218
|
+
|
|
169
219
|
// A fresh exchange for this session replaces an unfinished one.
|
|
170
220
|
this.#drop(sessionId);
|
|
171
221
|
|
|
@@ -0,0 +1,118 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `client.forwardUnix({ local, remote })` for Node: the `ssh -L` / `ssh -R` shapes with unix sockets and TCP ports
|
|
3
|
+
* mixed. Loaded on demand by `WshClient#forwardUnix` so the browser build never sees `node:*`.
|
|
4
|
+
*/
|
|
5
|
+
|
|
6
|
+
import net from 'node:net';
|
|
7
|
+
import fsp from 'node:fs/promises';
|
|
8
|
+
import { once } from 'node:events';
|
|
9
|
+
|
|
10
|
+
/** `/path`, `./path`, `@abstract` are sockets; anything else is `host:port` (also `[::1]:80`, or a bare port = 127.0.0.1). */
|
|
11
|
+
export function parseEndpoint(spec) {
|
|
12
|
+
if (typeof spec !== 'string' || !spec) throw new TypeError('forwardUnix: an endpoint must be a non-empty string');
|
|
13
|
+
if (spec.startsWith('/') || spec.startsWith('./') || spec.startsWith('../') || spec.startsWith('@')) return { kind: 'unix', path: spec };
|
|
14
|
+
if (/^\d{1,5}$/.test(spec)) return { kind: 'tcp', host: '127.0.0.1', port: Number(spec) };
|
|
15
|
+
const m = /^(?:\[([^\]]+)\]|([^:]+)):(\d{1,5})$/.exec(spec);
|
|
16
|
+
if (!m) throw new TypeError(`forwardUnix: ${JSON.stringify(spec)} is neither a socket path nor host:port`);
|
|
17
|
+
const port = Number(m[3]);
|
|
18
|
+
if (port > 65535) throw new TypeError(`forwardUnix: bad port in ${JSON.stringify(spec)}`);
|
|
19
|
+
return { kind: 'tcp', host: m[1] ?? m[2], port };
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
/** Pipe a net.Socket and a gateway duplex both ways with backpressure on each leg. */
|
|
23
|
+
function pipe(sock, duplex) {
|
|
24
|
+
const writer = duplex.writable.getWriter();
|
|
25
|
+
const reader = duplex.readable.getReader();
|
|
26
|
+
sock.on('data', (d) => {
|
|
27
|
+
sock.pause();
|
|
28
|
+
writer.write(new Uint8Array(d.buffer, d.byteOffset, d.length)).then(() => { if (!sock.destroyed) sock.resume(); }, () => sock.destroy());
|
|
29
|
+
});
|
|
30
|
+
sock.on('end', () => { void writer.close().catch(() => {}); });
|
|
31
|
+
sock.on('error', () => {});
|
|
32
|
+
sock.on('close', () => { duplex.destroy(); });
|
|
33
|
+
(async () => {
|
|
34
|
+
try {
|
|
35
|
+
for (;;) {
|
|
36
|
+
const { value, done } = await reader.read();
|
|
37
|
+
if (done) break;
|
|
38
|
+
if (!sock.write(value)) await once(sock, 'drain');
|
|
39
|
+
}
|
|
40
|
+
sock.end();
|
|
41
|
+
} catch { sock.destroy(); }
|
|
42
|
+
})();
|
|
43
|
+
duplex.closed.then(() => { if (!sock.destroyed) sock.end(); });
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
async function listenLocal(spec, { replace }) {
|
|
47
|
+
const server = net.createServer({ pauseOnConnect: true });
|
|
48
|
+
if (spec.kind === 'tcp') {
|
|
49
|
+
await new Promise((resolve, reject) => { server.once('error', reject); server.listen({ host: spec.host, port: spec.port }, () => { server.off('error', reject); resolve(); }); });
|
|
50
|
+
return { server, cleanup: async () => {} };
|
|
51
|
+
}
|
|
52
|
+
if (spec.path.startsWith('@')) throw new TypeError('forwardUnix: a local abstract socket is not supported; use a path');
|
|
53
|
+
let existing = null;
|
|
54
|
+
try { existing = await fsp.lstat(spec.path); } catch (e) { if (e.code !== 'ENOENT') throw e; }
|
|
55
|
+
if (existing) {
|
|
56
|
+
if (!existing.isSocket()) throw new Error(`${spec.path} exists and is not a socket`);
|
|
57
|
+
if (!replace) throw new Error(`${spec.path} already exists (pass replace: true to replace a stale socket)`);
|
|
58
|
+
const live = await new Promise((resolve) => {
|
|
59
|
+
const p = net.connect({ path: spec.path });
|
|
60
|
+
p.once('connect', () => { p.destroy(); resolve(true); });
|
|
61
|
+
p.once('error', (e) => resolve(e.code !== 'ECONNREFUSED' && e.code !== 'ENOENT'));
|
|
62
|
+
});
|
|
63
|
+
if (live) throw new Error(`${spec.path} is in use`);
|
|
64
|
+
await fsp.unlink(spec.path);
|
|
65
|
+
}
|
|
66
|
+
const old = (() => { try { return process.umask(0o177); } catch { return null; } })();
|
|
67
|
+
try {
|
|
68
|
+
await new Promise((resolve, reject) => { server.once('error', reject); server.listen({ path: spec.path }, () => { server.off('error', reject); resolve(); }); });
|
|
69
|
+
} finally { if (old !== null) process.umask(old); }
|
|
70
|
+
await fsp.chmod(spec.path, 0o600);
|
|
71
|
+
const st = await fsp.lstat(spec.path);
|
|
72
|
+
return {
|
|
73
|
+
server,
|
|
74
|
+
cleanup: async () => { try { const now = await fsp.lstat(spec.path); if (now.isSocket() && now.ino === st.ino) await fsp.unlink(spec.path); } catch { /* gone */ } },
|
|
75
|
+
};
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
/**
|
|
79
|
+
* @param {import('./client.mjs').WshClient} client
|
|
80
|
+
* @param {{ local: string, remote: string, reverse?: boolean, replace?: boolean, onError?: (err: Error) => void }} opts
|
|
81
|
+
*/
|
|
82
|
+
export async function forward(client, { local, remote, reverse = false, replace = false, onError = () => {} } = {}) {
|
|
83
|
+
const l = parseEndpoint(local);
|
|
84
|
+
const r = parseEndpoint(remote);
|
|
85
|
+
|
|
86
|
+
if (reverse) {
|
|
87
|
+
if (r.kind !== 'unix') throw new TypeError('forwardUnix: with reverse: true the remote end must be a socket path (the host listens on it)');
|
|
88
|
+
const handle = await client.listenUnix(r.path, {
|
|
89
|
+
replace,
|
|
90
|
+
onConnection: (duplex) => {
|
|
91
|
+
const sock = l.kind === 'unix' ? net.connect({ path: l.path }) : net.connect({ host: l.host, port: l.port });
|
|
92
|
+
sock.pause();
|
|
93
|
+
sock.once('connect', () => { pipe(sock, duplex); sock.resume(); });
|
|
94
|
+
sock.once('error', (e) => { duplex.destroy(); onError(e); });
|
|
95
|
+
},
|
|
96
|
+
});
|
|
97
|
+
return { local, remote, close: () => handle.close() };
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
const { server, cleanup } = await listenLocal(l, { replace });
|
|
101
|
+
const open = r.kind === 'unix' ? () => client.openUnix(r.path) : () => client.openTcp(r.host, r.port);
|
|
102
|
+
server.on('connection', async (sock) => {
|
|
103
|
+
sock.on('error', () => {});
|
|
104
|
+
let duplex;
|
|
105
|
+
try { duplex = await open(); } catch (e) { sock.destroy(); onError(e); return; }
|
|
106
|
+
if (sock.destroyed) { duplex.destroy(); return; }
|
|
107
|
+
pipe(sock, duplex);
|
|
108
|
+
sock.resume();
|
|
109
|
+
});
|
|
110
|
+
server.on('error', onError);
|
|
111
|
+
return {
|
|
112
|
+
local, remote, address: server.address(),
|
|
113
|
+
async close() {
|
|
114
|
+
await new Promise((res) => { server.close(() => res()); server.closeAllConnections?.(); });
|
|
115
|
+
await cleanup();
|
|
116
|
+
},
|
|
117
|
+
};
|
|
118
|
+
}
|
|
@@ -0,0 +1,250 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* One gateway connection's data path with flow control, shared by both ends: the Node host (a TCP or unix socket is
|
|
3
|
+
* attached to it), the host's named endpoints (the embedder gets its streams), and the client (`openUnix()` and
|
|
4
|
+
* friends hand the application its streams). Browser-safe: no `node:*` import.
|
|
5
|
+
*
|
|
6
|
+
* Wire behaviour (spec: `GatewayCredit`, feature "gateway-credit"):
|
|
7
|
+
* - With `credit` on, each direction starts with `window` bytes of credit. `write()` sends only while it holds credit
|
|
8
|
+
* and waits for a `GatewayCredit` otherwise; the receiving side returns credit (`sendCredit`) as its application
|
|
9
|
+
* consumes data, so a slow reader stops the sender instead of growing a buffer. A peer that sends beyond the
|
|
10
|
+
* credit it was given has broken the protocol and the connection is closed.
|
|
11
|
+
* - With `credit` off (a peer that predates the feature), nothing is metered on the wire: `write()` still waits for
|
|
12
|
+
* the transport to accept each frame (the QMux window), and what the peer sends is bounded by `maxQueued` (this
|
|
13
|
+
* connection) and `budget` (all of this client's connections): exceeding either closes the connection.
|
|
14
|
+
*
|
|
15
|
+
* GatewayClose is a half-close, as it always was for the host: the side that sends it sends no more data, and goes on
|
|
16
|
+
* receiving until the peer's own GatewayClose arrives. The connection is over when both have been sent (or on `destroy()`).
|
|
17
|
+
*
|
|
18
|
+
* Wire side: `receive(bytes)` for a GatewayData, `grant(n)` for a GatewayCredit, `remoteClosed(reason)` for a
|
|
19
|
+
* GatewayClose. Application side: `write(bytes)`, `consumed(n)`, `end(reason)`, `destroy()`, or `streams()` for web streams.
|
|
20
|
+
*/
|
|
21
|
+
|
|
22
|
+
/** Credit each direction of a connection starts with when "gateway-credit" is negotiated (a protocol constant). */
|
|
23
|
+
export const GATEWAY_CREDIT_WINDOW = 262144;
|
|
24
|
+
/** Feature string: the client lists it in `Hello.features`, the host in `ServerHello.features`; both = credit is on. */
|
|
25
|
+
export const GATEWAY_CREDIT_FEATURE = 'gateway-credit';
|
|
26
|
+
/** Largest GatewayData payload this implementation sends. */
|
|
27
|
+
export const GATEWAY_MAX_FRAME = 65536;
|
|
28
|
+
|
|
29
|
+
/**
|
|
30
|
+
* @typedef {object} GatewayChannelOptions
|
|
31
|
+
* @property {number} id gateway_id
|
|
32
|
+
* @property {boolean} [credit=false] metered by GatewayCredit
|
|
33
|
+
* @property {number} [window=GATEWAY_CREDIT_WINDOW]
|
|
34
|
+
* @property {number} [maxQueued=4194304] bytes received and not yet consumed before the connection is closed
|
|
35
|
+
* @property {{ used: number, max: number }} [budget] shared by all of a client's connections (`used` is kept by the channel)
|
|
36
|
+
* @property {boolean} [writeAfterRemoteClose=false] keep accepting `write()` after the peer's GatewayClose (the host's origin may still answer)
|
|
37
|
+
* @property {number} [graceMs=0] after the peer's GatewayClose, end our side too once this long has passed (0 = never)
|
|
38
|
+
* @property {(bytes: Uint8Array) => Promise<unknown> | unknown} sendData
|
|
39
|
+
* @property {(n: number) => unknown} sendCredit
|
|
40
|
+
* @property {(reason?: string) => unknown} sendClose
|
|
41
|
+
* @property {(bytes: Uint8Array) => void} [onData] sink mode: receive() calls this instead of queueing for `streams().readable`
|
|
42
|
+
* @property {(reason?: string) => void} [onRemoteClose] the peer sent GatewayClose (it will send no more data)
|
|
43
|
+
* @property {(reason?: string) => void} [onClose] called once, when the connection is over
|
|
44
|
+
*/
|
|
45
|
+
|
|
46
|
+
export class GatewayChannel {
|
|
47
|
+
#o;
|
|
48
|
+
#sendCredit;
|
|
49
|
+
#peerWindow;
|
|
50
|
+
#unacked = 0;
|
|
51
|
+
#queue = [];
|
|
52
|
+
#queued = 0;
|
|
53
|
+
#waiter = null;
|
|
54
|
+
#creditWaiters = [];
|
|
55
|
+
#sentClose = false;
|
|
56
|
+
#gotClose = false;
|
|
57
|
+
#finished = false;
|
|
58
|
+
#graceTimer = null;
|
|
59
|
+
#streams = null;
|
|
60
|
+
#closedPromise;
|
|
61
|
+
#resolveClosed;
|
|
62
|
+
|
|
63
|
+
/** @param {GatewayChannelOptions} o */
|
|
64
|
+
constructor(o) {
|
|
65
|
+
this.#o = { window: GATEWAY_CREDIT_WINDOW, maxQueued: 4 * 1024 * 1024, credit: false, writeAfterRemoteClose: false, graceMs: 0, ...o };
|
|
66
|
+
this.#sendCredit = this.#o.credit ? this.#o.window : Infinity;
|
|
67
|
+
this.#peerWindow = this.#o.credit ? this.#o.window : Infinity;
|
|
68
|
+
this.#closedPromise = new Promise((r) => { this.#resolveClosed = r; });
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
get id() { return this.#o.id; }
|
|
72
|
+
/** True once the connection is over. */
|
|
73
|
+
get closed() { return this.#finished; }
|
|
74
|
+
/** True once the peer's GatewayClose arrived. */
|
|
75
|
+
get remoteEnded() { return this.#gotClose; }
|
|
76
|
+
/** Resolves (with the close reason, if any) once the connection is over. */
|
|
77
|
+
get closedPromise() { return this.#closedPromise; }
|
|
78
|
+
/** Bytes received and not yet consumed. */
|
|
79
|
+
get queuedBytes() { return this.#queued; }
|
|
80
|
+
|
|
81
|
+
// ── wire side ──────────────────────────────────────────────────────
|
|
82
|
+
|
|
83
|
+
/** A GatewayData arrived. */
|
|
84
|
+
receive(bytes) {
|
|
85
|
+
if (this.#finished || this.#gotClose) return;
|
|
86
|
+
const n = bytes.byteLength;
|
|
87
|
+
if (n === 0) return;
|
|
88
|
+
if (this.#o.credit) {
|
|
89
|
+
this.#peerWindow -= n;
|
|
90
|
+
if (this.#peerWindow < 0) return this.#violate('peer exceeded its credit');
|
|
91
|
+
}
|
|
92
|
+
const budget = this.#o.budget;
|
|
93
|
+
if (this.#queued + n > this.#o.maxQueued || (budget && budget.used + n > budget.max)) return this.#violate('buffer limit exceeded');
|
|
94
|
+
this.#queued += n;
|
|
95
|
+
if (budget) budget.used += n;
|
|
96
|
+
if (this.#o.onData) { this.#o.onData(bytes); return; }
|
|
97
|
+
this.#queue.push(bytes);
|
|
98
|
+
this.#waiter?.();
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
/** A GatewayCredit arrived. */
|
|
102
|
+
grant(n) {
|
|
103
|
+
if (!this.#o.credit || this.#finished || !Number.isFinite(n) || n <= 0) return;
|
|
104
|
+
this.#sendCredit = Math.min(this.#sendCredit + n, Number.MAX_SAFE_INTEGER);
|
|
105
|
+
this.#wakeWriters();
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
/** A GatewayClose arrived: no more data comes (queued data can still be read). */
|
|
109
|
+
remoteClosed(reason) {
|
|
110
|
+
if (this.#finished || this.#gotClose) return;
|
|
111
|
+
this.#gotClose = true;
|
|
112
|
+
this.#waiter?.();
|
|
113
|
+
try { this.#o.onRemoteClose?.(reason); } catch { /* the application's problem */ }
|
|
114
|
+
if (!this.#o.writeAfterRemoteClose) this.#wakeWriters();
|
|
115
|
+
if (this.#sentClose) { if (this.#queue.length === 0) this.#finish(reason); return; }
|
|
116
|
+
if (this.#o.graceMs > 0) {
|
|
117
|
+
clearTimeout(this.#graceTimer);
|
|
118
|
+
this.#graceTimer = setTimeout(() => this.end('grace period over'), this.#o.graceMs);
|
|
119
|
+
this.#graceTimer.unref?.();
|
|
120
|
+
}
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
// ── application side ───────────────────────────────────────────────
|
|
124
|
+
|
|
125
|
+
/**
|
|
126
|
+
* Send `bytes` to the peer: waits for credit (when metered) and for the transport to accept each frame. Resolves
|
|
127
|
+
* when all of it has been handed over; rejects if the connection can no longer carry it.
|
|
128
|
+
*/
|
|
129
|
+
async write(bytes) {
|
|
130
|
+
let off = 0;
|
|
131
|
+
while (off < bytes.byteLength) {
|
|
132
|
+
this.#assertWritable();
|
|
133
|
+
let n = Math.min(bytes.byteLength - off, GATEWAY_MAX_FRAME);
|
|
134
|
+
if (this.#o.credit) {
|
|
135
|
+
while (this.#sendCredit <= 0) {
|
|
136
|
+
this.#assertWritable();
|
|
137
|
+
await new Promise((resolve) => this.#creditWaiters.push(resolve));
|
|
138
|
+
}
|
|
139
|
+
this.#assertWritable();
|
|
140
|
+
n = Math.min(n, this.#sendCredit);
|
|
141
|
+
this.#sendCredit -= n;
|
|
142
|
+
}
|
|
143
|
+
await this.#o.sendData(bytes.subarray(off, off + n));
|
|
144
|
+
off += n;
|
|
145
|
+
}
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
#assertWritable() {
|
|
149
|
+
if (this.#finished || this.#sentClose || (this.#gotClose && !this.#o.writeAfterRemoteClose)) throw new Error('gateway connection closed');
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
/** The application has taken `n` received bytes: returns credit to the peer, and frees queue and budget. */
|
|
153
|
+
consumed(n) {
|
|
154
|
+
if (n <= 0) return;
|
|
155
|
+
const taken = Math.min(n, this.#queued);
|
|
156
|
+
this.#queued -= taken;
|
|
157
|
+
if (this.#o.budget) this.#o.budget.used -= taken;
|
|
158
|
+
if (this.#o.credit && !this.#finished && !this.#gotClose) {
|
|
159
|
+
this.#unacked += taken;
|
|
160
|
+
if (this.#unacked >= this.#o.window / 2) {
|
|
161
|
+
const give = this.#unacked;
|
|
162
|
+
this.#unacked = 0;
|
|
163
|
+
this.#peerWindow += give;
|
|
164
|
+
try { void this.#o.sendCredit(give); } catch { /* transport gone */ }
|
|
165
|
+
}
|
|
166
|
+
}
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
/** We are done sending: GatewayClose goes out once. The connection is over when the peer's arrives too. */
|
|
170
|
+
end(reason) {
|
|
171
|
+
if (this.#finished || this.#sentClose) return;
|
|
172
|
+
this.#sentClose = true;
|
|
173
|
+
try { void this.#o.sendClose(reason); } catch { /* transport gone */ }
|
|
174
|
+
this.#wakeWriters();
|
|
175
|
+
if (this.#gotClose && this.#queue.length === 0) this.#finish(reason);
|
|
176
|
+
else if (!this.#gotClose && this.#o.graceMs > 0) {
|
|
177
|
+
// The peer owes us its own GatewayClose; a peer that never sends it must not hold the slot forever.
|
|
178
|
+
this.#graceTimer = setTimeout(() => this.destroy('grace period over'), this.#o.graceMs);
|
|
179
|
+
this.#graceTimer.unref?.();
|
|
180
|
+
}
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
/** Tear down at once; sends GatewayClose first if we had not. */
|
|
184
|
+
destroy(reason) {
|
|
185
|
+
if (this.#finished) return;
|
|
186
|
+
if (!this.#sentClose) { this.#sentClose = true; try { void this.#o.sendClose(reason); } catch { /* gone */ } }
|
|
187
|
+
this.#finish(reason);
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
/** The transport went away: finish without sending anything. */
|
|
191
|
+
abandon(reason) {
|
|
192
|
+
if (this.#finished) return;
|
|
193
|
+
this.#sentClose = true;
|
|
194
|
+
this.#finish(reason);
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
/**
|
|
198
|
+
* Web streams over the connection: `readable` yields what the peer sends (credit is returned as it is read, so a
|
|
199
|
+
* slow reader stops the peer), `writable` sends (its writes wait for credit). Closing `writable` half-closes;
|
|
200
|
+
* cancelling `readable` or aborting `writable` destroys the connection.
|
|
201
|
+
* @returns {{ readable: ReadableStream<Uint8Array>, writable: WritableStream<Uint8Array> }}
|
|
202
|
+
*/
|
|
203
|
+
streams() {
|
|
204
|
+
if (this.#streams) return this.#streams;
|
|
205
|
+
const self = this;
|
|
206
|
+
const readable = new ReadableStream({
|
|
207
|
+
async pull(controller) {
|
|
208
|
+
while (self.#queue.length === 0 && !self.#gotClose && !self.#finished) await new Promise((r) => { self.#waiter = r; });
|
|
209
|
+
self.#waiter = null;
|
|
210
|
+
if (self.#queue.length) {
|
|
211
|
+
const chunk = self.#queue.shift();
|
|
212
|
+
controller.enqueue(chunk);
|
|
213
|
+
self.consumed(chunk.byteLength);
|
|
214
|
+
return;
|
|
215
|
+
}
|
|
216
|
+
controller.close();
|
|
217
|
+
if (self.#sentClose) self.#finish();
|
|
218
|
+
},
|
|
219
|
+
cancel(reason) { self.destroy(typeof reason === 'string' ? reason : undefined); },
|
|
220
|
+
}, { highWaterMark: 0 });
|
|
221
|
+
const writable = new WritableStream({
|
|
222
|
+
write(chunk) { return self.write(chunk instanceof Uint8Array ? chunk : new Uint8Array(chunk)); },
|
|
223
|
+
close() { self.end(); },
|
|
224
|
+
abort(reason) { self.destroy(typeof reason === 'string' ? reason : undefined); },
|
|
225
|
+
});
|
|
226
|
+
this.#streams = { readable, writable };
|
|
227
|
+
return this.#streams;
|
|
228
|
+
}
|
|
229
|
+
|
|
230
|
+
// ── internals ──────────────────────────────────────────────────────
|
|
231
|
+
|
|
232
|
+
#violate(reason) { this.destroy(reason); }
|
|
233
|
+
|
|
234
|
+
#wakeWriters() {
|
|
235
|
+
for (const w of this.#creditWaiters.splice(0)) w(); // write() re-checks and throws or continues
|
|
236
|
+
}
|
|
237
|
+
|
|
238
|
+
#finish(reason) {
|
|
239
|
+
if (this.#finished) return;
|
|
240
|
+
this.#finished = true;
|
|
241
|
+
clearTimeout(this.#graceTimer);
|
|
242
|
+
if (this.#o.budget) this.#o.budget.used -= this.#queued;
|
|
243
|
+
this.#queued = 0;
|
|
244
|
+
this.#queue = [];
|
|
245
|
+
this.#waiter?.();
|
|
246
|
+
this.#wakeWriters();
|
|
247
|
+
try { this.#o.onClose?.(reason); } catch { /* the application's problem */ }
|
|
248
|
+
this.#resolveClosed(reason);
|
|
249
|
+
}
|
|
250
|
+
}
|