@johnhenry/wsh 0.44.1 → 0.46.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.
@@ -11,10 +11,13 @@
11
11
  * What a pipe relay can still do is in the README's Security model: it sees metadata and ciphertext-free traffic
12
12
  * volume, can drop or delay bytes, and can offer a host or operator to whoever holds the rendezvous id.
13
13
  *
14
- * THIS MODULE IMPORTS NOTHING STATICALLY, and its only dynamic imports are `ws`, `node:http` and `node:https` (in
15
- * `listen()`, for embedders that do not already run an HTTP server). test/pipe-relay.test.mjs asserts that the
16
- * module graph reaches nothing that can execute code or read files. That is the point of shipping it as its own
17
- * entry point (`@johnhenry/wsh/pipe-relay`) rather than a mode of the server.
14
+ * THIS MODULE IMPORTS NOTHING, statically or by name: it is browser-safe (a page can bundle it for `pipeUrl`,
15
+ * `newRendezvousId`, `watchPairing`, or to run `accept()` over sockets it holds). The one Node-only piece, `listen()`
16
+ * (an HTTP server with `ws`, for embedders that do not already run one), lives in `./pipe-relay-node.mjs` and is
17
+ * loaded only when `listen()` is called, through a specifier a bundler does not follow. test/pipe-relay.test.mjs
18
+ * asserts that this module's graph is this one file and that the Node module reaches nothing that can execute code
19
+ * or read files; test/browser-bundle.test.mjs bundles this entry for the browser. That is the point of shipping it
20
+ * as its own entry point (`@johnhenry/wsh/pipe-relay`) rather than a mode of the server.
18
21
  *
19
22
  * Bounds (every one has a default; 0 turns a limit off only where noted):
20
23
  * maxWaiting halves waiting for a partner, over all ids (default 1024); more are refused
@@ -32,6 +35,8 @@
32
35
  */
33
36
 
34
37
  const OPEN = 1;
38
+ /** The Node-only half (`listen()`): a variable, not a literal, so a bundler does not follow it. */
39
+ const NODE_LISTENER = './pipe-relay-node.mjs';
35
40
  const ID_RE = /^[A-Za-z0-9_-]{22,128}$/;
36
41
  const ROLES = new Set(['host', 'operator']);
37
42
  const MIN_ID_LENGTH = 22; // 16 random bytes, base64url
@@ -44,21 +49,95 @@ export function newRendezvousId() {
44
49
  return btoa(s).replaceAll('+', '-').replaceAll('/', '_').replaceAll('=', '');
45
50
  }
46
51
 
52
+ /**
53
+ * The one text frame a relay sends a host that asked for it, when its partner arrives (before anything the partner said).
54
+ * Everything else on a pipe is binary, so a text frame can never be wsh bytes.
55
+ */
56
+ export const PAIRED_FRAME = 'wsh-pipe/1 paired';
57
+
47
58
  /**
48
59
  * The URL one side dials: `<relay>/r/<id>`, with `?role=host` for the host (the operator is the default).
49
60
  * @param {string} relayUrl - `ws://` / `wss://` (or `http(s)://`) base of the relay
50
61
  * @param {string} id
51
62
  * @param {'host' | 'operator'} [role='operator']
63
+ * @param {{ notifyPaired?: boolean }} [options] - `notifyPaired` (a host only) adds `&paired=1`: ask the relay to send
64
+ * `PAIRED_FRAME` when the operator arrives. A relay that predates it ignores the parameter and never sends it.
52
65
  */
53
- export function pipeUrl(relayUrl, id, role = 'operator') {
66
+ export function pipeUrl(relayUrl, id, role = 'operator', { notifyPaired = false } = {}) {
54
67
  if (!ID_RE.test(id)) throw new TypeError(`pipeUrl: the rendezvous id must be ${MIN_ID_LENGTH}-128 base64url characters (use newRendezvousId())`);
55
68
  if (!ROLES.has(role)) throw new TypeError("pipeUrl: role must be 'host' or 'operator'");
69
+ if (notifyPaired && role !== 'host') throw new TypeError('pipeUrl: notifyPaired is for the host side');
56
70
  const u = new URL(relayUrl);
57
71
  u.pathname = `${u.pathname.replace(/\/+$/, '')}/r/${id}`;
58
- u.search = role === 'host' ? '?role=host' : '';
72
+ u.search = role === 'host' ? (notifyPaired ? '?role=host&paired=1' : '?role=host') : '';
59
73
  return u.toString();
60
74
  }
61
75
 
76
+ const textOf = (data) => {
77
+ if (typeof data === 'string') return data;
78
+ try {
79
+ if (data instanceof ArrayBuffer) return new TextDecoder().decode(data);
80
+ if (ArrayBuffer.isView(data)) return new TextDecoder().decode(data);
81
+ if (Array.isArray(data)) return null;
82
+ return typeof data?.toString === 'function' ? String(data) : null;
83
+ } catch { return null; }
84
+ };
85
+
86
+ /**
87
+ * Host side of the paired signal. Wrap the socket a host dialled with `notifyPaired` BEFORE anything is attached to it, hand
88
+ * the returned `socket` to `server.accept()` / `host.accept()` (it is the same socket, with the one `PAIRED_FRAME` text frame
89
+ * kept out of what the wsh host reads), and await `paired`: it resolves when the operator arrives, and rejects if the socket
90
+ * closes first. Against a relay that does not know the flag it never resolves (the connection works as it always did): a
91
+ * host that must know should also bound its wait with its own timer.
92
+ * @param {object} socket a WebSocket-like (`ws` or a browser's)
93
+ * @returns {{ socket: object, paired: Promise<void> }}
94
+ */
95
+ export function watchPairing(socket) {
96
+ let resolve; let reject; let settled = false;
97
+ const paired = new Promise((res, rej) => { resolve = res; reject = rej; });
98
+ paired.catch(() => {}); // a host that ignores the promise must not crash on an unhandled rejection
99
+ const isSignal = (data, isBinary) => isBinary !== true && textOf(data) === PAIRED_FRAME;
100
+ const onSignal = (data, isBinary) => { if (!settled && isSignal(data, isBinary)) { settled = true; resolve(); } };
101
+ const onClose = () => { if (!settled) { settled = true; reject(new Error('the pipe closed before a partner arrived')); } };
102
+ if (typeof socket.addEventListener === 'function') {
103
+ socket.addEventListener('message', (ev) => onSignal(ev?.data));
104
+ socket.addEventListener('close', onClose);
105
+ } else if (typeof socket.on === 'function') {
106
+ socket.on('message', (data, isBinary) => onSignal(data, isBinary));
107
+ socket.on('close', onClose);
108
+ } else {
109
+ throw new TypeError('watchPairing: socket must support on() or addEventListener()');
110
+ }
111
+
112
+ // The same socket for everything else, minus the signal frame for whoever listens for messages through it.
113
+ const wrapped = new Map();
114
+ const wrapFor = (style, fn) => {
115
+ let w = wrapped.get(fn);
116
+ if (!w) {
117
+ w = style === 'event'
118
+ ? (ev) => { if (!isSignal(ev?.data)) fn(ev); }
119
+ : (data, isBinary) => { if (!isSignal(data, isBinary)) fn(data, isBinary); };
120
+ wrapped.set(fn, w);
121
+ }
122
+ return w;
123
+ };
124
+ const proxy = new Proxy(socket, {
125
+ get(target, prop) {
126
+ if ((prop === 'addEventListener' || prop === 'on' || prop === 'addListener' || prop === 'once') && typeof target[prop] === 'function') {
127
+ const style = prop === 'addEventListener' ? 'event' : 'node';
128
+ return (type, fn, ...rest) => (type === 'message' && typeof fn === 'function' ? target[prop](type, wrapFor(style, fn), ...rest) : target[prop](type, fn, ...rest));
129
+ }
130
+ if ((prop === 'removeEventListener' || prop === 'off' || prop === 'removeListener') && typeof target[prop] === 'function') {
131
+ return (type, fn, ...rest) => target[prop](type, (type === 'message' && wrapped.get(fn)) || fn, ...rest);
132
+ }
133
+ const v = Reflect.get(target, prop, target);
134
+ return typeof v === 'function' ? v.bind(target) : v;
135
+ },
136
+ set(target, prop, value) { target[prop] = value; return true; },
137
+ });
138
+ return { socket: proxy, paired };
139
+ }
140
+
62
141
  const sane = (code) => (Number.isInteger(code) && code >= 1000 && code <= 4999 && ![1004, 1005, 1006, 1015].includes(code) ? code : 1000);
63
142
 
64
143
  /** Adapt a `ws`-style (`on`) or browser-style (`addEventListener`) socket to message/close callbacks. */
@@ -110,7 +189,9 @@ export function createPipeRelay({
110
189
  /** Live pipes. */
111
190
  const pipes = new Set();
112
191
  let closed = false;
113
- let server = null;
192
+ let listening = false;
193
+ /** What to run when the relay closes (the HTTP server of `listen()`). */
194
+ const closers = [];
114
195
 
115
196
  const closeSocket = (socket, code = 1000, reason = '') => { try { socket.close(code, reason); } catch { /* gone */ } };
116
197
 
@@ -125,6 +206,10 @@ export function createPipeRelay({
125
206
  waiting.delete(first.id);
126
207
  const pipe = { halves: [first, second], bytes: 0, last: Date.now(), timers: [], done: false };
127
208
  pipes.add(pipe);
209
+ // A host that asked is told its partner is here, ahead of anything the partner said (not counted as pipe traffic).
210
+ for (const h of pipe.halves) {
211
+ if (h.notifyPaired && h.socket.readyState === OPEN) { try { h.socket.send(PAIRED_FRAME); } catch { /* it is gone; the pipe ends when its close arrives */ } }
212
+ }
128
213
  const end = (code, reason, from) => {
129
214
  if (pipe.done) return;
130
215
  pipe.done = true;
@@ -175,18 +260,20 @@ export function createPipeRelay({
175
260
  /**
176
261
  * Hand the relay one accepted connection.
177
262
  * @param {object} socket - a WebSocket-like duplex (`send`, `close`, `readyState`, `on` or `addEventListener`)
178
- * @param {{ id: string, role?: 'host' | 'operator', remote?: object }} who
263
+ * @param {{ id: string, role?: 'host' | 'operator', remote?: object, notifyPaired?: boolean }} who `notifyPaired` (a host
264
+ * that asked, `?paired=1`): send it `PAIRED_FRAME` once when the operator arrives. Only a host may ask.
179
265
  * @returns {Promise<boolean>} whether the connection is now waiting or paired (false: it was refused and closed)
180
266
  */
181
- async function accept(socket, { id, role = 'operator', remote } = {}) {
267
+ async function accept(socket, { id, role = 'operator', remote, notifyPaired = false } = {}) {
182
268
  if (!socket || typeof socket.send !== 'function' || typeof socket.close !== 'function') throw new TypeError('createPipeRelay.accept: socket must be a WebSocket-like duplex');
269
+ if (notifyPaired && role !== 'host') throw new TypeError('createPipeRelay.accept: notifyPaired is for the host side');
183
270
  const refuse = (code, reason) => { closeSocket(socket, code, reason); return false; };
184
271
  if (closed) return refuse(1001, 'relay is shutting down');
185
272
  if (typeof id !== 'string' || !ID_RE.test(id)) return refuse(1008, 'bad rendezvous id');
186
273
  if (!ROLES.has(role)) return refuse(1008, 'bad role');
187
274
 
188
275
  // Listeners first, so nothing the peer says while we decide is lost; it is held (bounded) until it can be passed on.
189
- const half = { id, role, socket, early: [], earlyBytes: 0, timer: null, forward: null, paused: false, resume: null };
276
+ const half = { id, role, socket, early: [], earlyBytes: 0, timer: null, forward: null, paused: false, resume: null, notifyPaired: notifyPaired === true };
190
277
  let pipeRef = null;
191
278
  listenOn(socket, (data, isBinary) => {
192
279
  if (half.forward) return half.forward(data, isBinary);
@@ -227,42 +314,24 @@ export function createPipeRelay({
227
314
  * Convenience for embedders without an HTTP server; needs the `ws` package. `tls` is the options of `https.createServer`.
228
315
  * @returns {Promise<{ port: number, address: string, close(): Promise<void> }>}
229
316
  */
230
- async function listen({ host = '127.0.0.1', port = 0, path = '/r', tls } = {}) {
231
- if (server) throw new Error('createPipeRelay: already listening');
232
- const { WebSocketServer } = await import('ws');
233
- const http = tls ? await import('node:https') : await import('node:http');
234
- const wss = new WebSocketServer({ noServer: true, maxPayload: maxMessageBytes });
235
- const srv = tls ? http.createServer(tls) : http.createServer();
236
- srv.on('request', (_req, res) => { res.statusCode = 426; res.end('WebSocket only'); });
237
- srv.on('upgrade', (req, sock, head) => {
238
- let url;
239
- try { url = new URL(req.url, 'http://x'); } catch { sock.destroy(); return; }
240
- const m = url.pathname.startsWith(`${path}/`) ? url.pathname.slice(path.length + 1) : null;
241
- const role = url.searchParams.get('role') ?? 'operator';
242
- if (!m || !ID_RE.test(m) || !ROLES.has(role)) { sock.write('HTTP/1.1 404 Not Found\r\nConnection: close\r\n\r\n'); sock.destroy(); return; }
243
- wss.handleUpgrade(req, sock, head, (ws) => { accept(ws, { id: m, role, remote: { address: req.socket.remoteAddress, headers: req.headers } }).catch(() => closeSocket(ws, 1011, 'error')); });
244
- });
245
- await new Promise((resolve, reject) => { srv.once('error', reject); srv.listen(port, host, () => { srv.off('error', reject); resolve(); }); });
246
- server = { srv, wss };
247
- const addr = srv.address();
248
- return {
249
- port: addr.port, address: addr.address,
250
- close: () => close(),
251
- };
317
+ async function listen(options = {}) {
318
+ if (listening) throw new Error('createPipeRelay: already listening');
319
+ listening = true;
320
+ try {
321
+ // The Node half lives in its own module and is named through a variable, so a bundler building this file for a
322
+ // browser neither follows it nor needs `ws` or `node:http`.
323
+ const { listenPipeRelay } = await import(NODE_LISTENER);
324
+ return await listenPipeRelay({ accept, maxMessageBytes, onClose: (fn) => closers.push(fn), close: () => close() }, options);
325
+ } catch (e) { listening = false; throw e; }
252
326
  }
253
327
 
254
328
  async function close() {
255
329
  closed = true;
330
+ listening = false;
256
331
  for (const h of waiting.values()) { clearTimeout(h.timer); closeSocket(h.socket, 1001, 'relay is shutting down'); }
257
332
  waiting.clear();
258
333
  for (const p of [...pipes]) p.end(1001, 'relay is shutting down', null);
259
- if (server) {
260
- const { srv, wss } = server;
261
- server = null;
262
- for (const c of wss.clients) c.terminate();
263
- await new Promise((r) => wss.close(r));
264
- await new Promise((r) => { srv.close(() => r()); srv.closeAllConnections?.(); });
265
- }
334
+ for (const fn of closers.splice(0)) await fn();
266
335
  }
267
336
 
268
337
  return {
@@ -15,6 +15,10 @@ export interface WshBrowserReverseHostOptions extends Omit<WshReverseHostOptions
15
15
  /** An object of file operations, not a root path. */
16
16
  fs?: WshFileBackend;
17
17
  mcp?: WshServerMcpOptions;
18
+ /** Typed rpc channels (#191): one handler per protocol, served to the bridged operator in virtual data mode and stated as `rpc-virtual` in `ReverseAccept.features` (so it needs `reportFeatures`). Handler functions only. */
19
+ rpc?: Record<string, ((channel: import('./index.js').RpcChannel, ctx: import('./server/index.js').WshRpcContext) => void | Promise<void>) | false | null | undefined>;
20
+ rpcMaxMessageBytes?: number;
21
+ rpcMaxInflight?: number;
18
22
  }
19
23
 
20
24
  /**
@@ -21,7 +21,8 @@ import { MULTI_OPERATOR_FEATURE } from './server/relay.mjs';
21
21
  import { E2E_SIGN_FEATURE, E2EResponder } from './e2e-exchange.mjs';
22
22
  import { OPERATOR_PROOF_FEATURE, E2E_SEALED_FEATURE, createReverseChallenge, verifyOperatorProof } from './operator-proof.mjs';
23
23
  import { SealedBridge, BRIDGE_CHANNEL_ID } from './bridge-seal.mjs';
24
- import { resolveBackends } from './host-backends.mjs';
24
+ import { resolveBackends, createRpcTable } from './host-backends.mjs';
25
+ import { RPC_DEFAULT_MAX_MESSAGE } from './rpc.mjs';
25
26
  import { createConnectionFactory, hostFeatures } from './server/connection.mjs';
26
27
  import { validateOnShare } from './shares.mjs';
27
28
  import { refusalNotifier, validateOnRefused } from './refusal.mjs';
@@ -40,6 +41,12 @@ const BACKOFF_MAX_MS = 30_000;
40
41
  * @param {object} [options.pty]
41
42
  * @param {object} [options.fs]
42
43
  * @param {object} [options.mcp]
44
+ * @param {Record<string, Function | false | null>} [options.rpc] - Typed rpc channels (wsh #85, #191): `{ [protocol]: (channel, ctx) => void }`,
45
+ * served to the bridged operator in virtual data mode (the CBOR sequence rides `SessionData`, inside `EncryptedFrame` when the
46
+ * bridge is sealed), advertised as `rpc-virtual`, `rpc-protocol:<name>` and `rpc-max-message:<n>` in `ReverseAccept.features`
47
+ * (so it needs `reportFeatures`, the default). `@johnhenry/wsh/server`'s also takes the `wsh-host` and `wsh-fs` built-ins.
48
+ * @param {number} [options.rpcMaxMessageBytes=1048576]
49
+ * @param {number} [options.rpcMaxInflight=64]
43
50
  * @param {boolean} [options.reconnect=true] - Dial again (with backoff) after the relay connection ends. A relay ends it when a bridge does.
44
51
  * @param {object} [options.connect] - Extra options for the relay connection (`expectHostKey`, `knownHosts`, ...).
45
52
  * @param {string} [options.peerType='host']
@@ -78,7 +85,9 @@ const BACKOFF_MAX_MS = 30_000;
78
85
  * @param {(line: string) => void} [options.onLog]
79
86
  */
80
87
  export function createReverseHost(options = {}) {
81
- return createReverseHostWith(options, resolveBackends(options));
88
+ const rpc = options.rpc === undefined || options.rpc === null ? null
89
+ : createRpcTable(options.rpc, options.rpcMaxMessageBytes ?? RPC_DEFAULT_MAX_MESSAGE, options.rpcMaxInflight ?? 64, 'createReverseHost');
90
+ return createReverseHostWith(options, { ...resolveBackends(options), rpc });
82
91
  }
83
92
 
84
93
  /**
@@ -98,6 +107,7 @@ export function createReverseHostWith({
98
107
  if (requireOperatorProof && e2e === false) throw new TypeError('createReverseHost: requireOperatorProof seals the bridge, which needs e2e (do not set e2e: false)');
99
108
  if (requireOperatorProof && !reportFeatures) throw new TypeError('createReverseHost: requireOperatorProof needs reportFeatures (the operator learns "e2e-sealed" from ReverseAccept.features)');
100
109
  if (backends.targets) throw new TypeError('createReverseHost: targets are not supported by a reverse host (a bridged operator reaches the one machine behind it); use createWshServer or createMemoryHost');
110
+ if (backends.rpc?.protocols.size && !reportFeatures) throw new TypeError('createReverseHost: rpc needs reportFeatures (the operator learns "rpc-virtual" and the protocols from ReverseAccept.features)');
101
111
  if (!url) throw new TypeError('createReverseHost: url is required');
102
112
  if (!username) throw new TypeError('createReverseHost: username is required');
103
113
  if (!keyPair) throw new TypeError('createReverseHost: keyPair is required (the relay keys peers by fingerprint)');
@@ -121,12 +131,12 @@ export function createReverseHostWith({
121
131
  });
122
132
  /** Features for `ReverseAccept` on this relay connection. */
123
133
  const bridgeFeatures = (c, e2eConfig, manyOperators) => [
124
- ...hostFeatures({ mcp: backends.mcp, files: backends.files, e2e: e2eConfig, onShare }, { dataStreams: false }),
134
+ ...hostFeatures({ mcp: backends.mcp, files: backends.files, e2e: e2eConfig, onShare, rpc: backends.rpc ?? null }, { dataStreams: false }),
125
135
  ...(manyOperators ? [MULTI_OPERATOR_FEATURE] : []),
126
136
  ];
127
137
  const factory = createConnectionFactory({
128
138
  authorize: async () => false, methods: { pubkey: false, password: null }, hostKey: null, rateLimit: null,
129
- execRunner: backends.execRunner, execOptions: backends.execOptions, pty: backends.pty, files: backends.files, mcp: backends.mcp,
139
+ execRunner: backends.execRunner, execOptions: backends.execOptions, pty: backends.pty, files: backends.files, mcp: backends.mcp, rpc: backends.rpc ?? null,
130
140
  sessions: null, relay: null, e2e: null, bindTimeoutMs: 3000, log: (l) => onLog(`[reverse] ${l}`), onShare,
131
141
  });
132
142
 
@@ -0,0 +1,127 @@
1
+ /**
2
+ * rpc channels in virtual data mode (wsh #191): the CBOR sequence of an `rpc` channel (see `rpc.mjs`) carried as
3
+ * `SessionData` on the control plane -- and so inside `EncryptedFrame` on a sealed session -- instead of on a
4
+ * client-opened data stream. Transport-free and browser-safe: the host (`server/connection.mjs`) and the client
5
+ * (`client.mjs`) each bind an `RpcCreditLink` to their end of the channel.
6
+ *
7
+ * A stream has the transport's own flow control; the control plane has none, so the link meters the bytes itself:
8
+ * - each direction starts with `RPC_CREDIT_WINDOW` bytes of credit; `write()` sends only while it holds credit and waits
9
+ * for a `GatewayCredit` otherwise, so a reader that does not read bounds the sender;
10
+ * - the receiver returns credit (`GatewayCredit`) as `RpcChannel` takes the bytes in, in bytes and not in messages, so a
11
+ * message larger than the window still arrives (credit is returned for the bytes of a partly received message);
12
+ * - a peer that sends more than the credit it was given has broken the protocol, and the channel is closed.
13
+ *
14
+ * `GatewayCredit` is reused rather than a new message, because it is already forwarded by every relay and ignored for an
15
+ * id it does not know. Its `gateway_id` is a number space of its own beside the gateway's: an rpc channel's credit is
16
+ * `RPC_CREDIT_FLAG | channel_id`, a flag no gateway id ever has (the gateway's ids count up from 1).
17
+ */
18
+
19
+ /** Credit each direction of a virtual-mode rpc channel starts with, in bytes (a protocol constant). */
20
+ export const RPC_CREDIT_WINDOW = 262144;
21
+ /** `GatewayCredit.gateway_id` bit that marks credit for an rpc channel; the rest is the channel id. */
22
+ export const RPC_CREDIT_FLAG = 0x80000000;
23
+ /** Largest `SessionData` payload this layer sends. */
24
+ export const RPC_VIRTUAL_CHUNK_BYTES = 32 * 1024;
25
+
26
+ /** The `GatewayCredit.gateway_id` that grants credit on rpc channel `channelId`. @param {number} channelId */
27
+ export const rpcCreditId = (channelId) => (RPC_CREDIT_FLAG | channelId) >>> 0;
28
+ /** The rpc channel a `GatewayCredit.gateway_id` is for, or `undefined` if it is not rpc credit. @param {number} gatewayId */
29
+ export const rpcChannelOfCredit = (gatewayId) => (Number.isInteger(gatewayId) && gatewayId >= RPC_CREDIT_FLAG ? gatewayId - RPC_CREDIT_FLAG : undefined);
30
+
31
+ /**
32
+ * One end of the byte pipe under a virtual-mode `RpcChannel`.
33
+ *
34
+ * const link = new RpcCreditLink({ sendData, sendCredit, onViolation });
35
+ * const chan = new RpcChannel({ write: (b) => link.write(b), onConsumed: (n) => link.consumed(n), ... });
36
+ * // SessionData arrives: if (link.receive(bytes.length)) chan.feed(bytes)
37
+ * // GatewayCredit arrives: link.grant(n)
38
+ */
39
+ export class RpcCreditLink {
40
+ #sendData; #sendCredit; #onViolation; #window; #chunk;
41
+ /** Credit this end may still spend. */
42
+ #credit;
43
+ /** Credit this end has granted the peer and not yet seen spent. */
44
+ #peerCredit;
45
+ /** Bytes taken in and not yet returned as credit. */
46
+ #owed = 0;
47
+ #waiters = [];
48
+ #closed = false;
49
+
50
+ /**
51
+ * @param {object} o
52
+ * @param {(bytes: Uint8Array) => Promise<void> | void} o.sendData - one `SessionData` payload
53
+ * @param {(bytes: number) => Promise<void> | void} o.sendCredit - one `GatewayCredit`
54
+ * @param {(why: string) => void} [o.onViolation] - the peer overran its credit
55
+ * @param {number} [o.window]
56
+ * @param {number} [o.chunkBytes]
57
+ */
58
+ constructor({ sendData, sendCredit, onViolation = () => {}, window = RPC_CREDIT_WINDOW, chunkBytes = RPC_VIRTUAL_CHUNK_BYTES }) {
59
+ this.#sendData = sendData;
60
+ this.#sendCredit = sendCredit;
61
+ this.#onViolation = onViolation;
62
+ this.#window = window;
63
+ this.#chunk = chunkBytes;
64
+ this.#credit = window;
65
+ this.#peerCredit = window;
66
+ }
67
+
68
+ /** Credit this end holds to send with. */
69
+ get credit() { return this.#credit; }
70
+
71
+ /** Send `bytes`: in chunks, each waiting for credit. Rejects if the link closes first. @param {Uint8Array} bytes */
72
+ async write(bytes) {
73
+ let off = 0;
74
+ while (off < bytes.length) {
75
+ while (this.#credit <= 0) {
76
+ if (this.#closed) throw new Error('rpc channel closed');
77
+ await new Promise((resolve) => this.#waiters.push(resolve));
78
+ }
79
+ if (this.#closed) throw new Error('rpc channel closed');
80
+ const n = Math.min(bytes.length - off, this.#credit, this.#chunk);
81
+ this.#credit -= n;
82
+ const piece = bytes.subarray(off, off + n);
83
+ off += n;
84
+ await this.#sendData(piece);
85
+ }
86
+ }
87
+
88
+ /** The peer granted `n` more bytes (a `GatewayCredit`). @param {number} n */
89
+ grant(n) {
90
+ if (this.#closed || !Number.isSafeInteger(n) || n <= 0) return;
91
+ this.#credit = Math.min(this.#credit + n, Number.MAX_SAFE_INTEGER);
92
+ for (const w of this.#waiters.splice(0)) w();
93
+ }
94
+
95
+ /**
96
+ * Account for `n` bytes the peer sent (a `SessionData`). Returns false, and reports a violation, if that is more than the
97
+ * credit this end granted: the caller must then not deliver them.
98
+ * @param {number} n
99
+ */
100
+ receive(n) {
101
+ if (this.#closed) return false;
102
+ this.#peerCredit -= n;
103
+ if (this.#peerCredit < 0) {
104
+ this.#onViolation('the peer sent more rpc data than the credit it was given');
105
+ return false;
106
+ }
107
+ return true;
108
+ }
109
+
110
+ /** The application took `n` received bytes in: hand the peer credit back, in batches of half a window. @param {number} n */
111
+ consumed(n) {
112
+ if (this.#closed) return;
113
+ this.#owed += n;
114
+ if (this.#owed >= this.#window / 2) {
115
+ const give = this.#owed;
116
+ this.#owed = 0;
117
+ this.#peerCredit += give;
118
+ try { void Promise.resolve(this.#sendCredit(give)).catch(() => {}); } catch { /* transport gone */ }
119
+ }
120
+ }
121
+
122
+ /** The channel is over: writers waiting for credit are released with an error. */
123
+ close() {
124
+ this.#closed = true;
125
+ for (const w of this.#waiters.splice(0)) w();
126
+ }
127
+ }
package/src/rpc.mjs CHANGED
@@ -23,6 +23,13 @@ import { cborEncode, cborDecode } from './cbor.mjs';
23
23
 
24
24
  /** ServerHello feature: the host serves `rpc` sessions. */
25
25
  export const RPC_FEATURE = 'rpc';
26
+ /**
27
+ * ServerHello (or `ReverseAccept`) feature: the host serves `rpc` channels in virtual data mode -- the CBOR sequence rides
28
+ * `SessionData` (inside `EncryptedFrame` on a sealed session), metered by credit (`src/rpc-virtual.mjs`). A host states
29
+ * this INSTEAD of `rpc` on a connection that has no client-opened data streams, so a peer that only knows stream-mode rpc
30
+ * (it looks for `rpc`) never opens one it cannot carry.
31
+ */
32
+ export const RPC_VIRTUAL_FEATURE = 'rpc-virtual';
26
33
  /** ServerHello feature prefix: one `rpc-protocol:<name>` per supported protocol. */
27
34
  export const RPC_PROTOCOL_PREFIX = 'rpc-protocol:';
28
35
  /** ServerHello feature prefix: `rpc-max-message:<bytes>`, the largest single message the host accepts. */
@@ -53,6 +60,7 @@ export const RPC_ERROR = Object.freeze({
53
60
  * Read the rpc advertisement out of `ServerHello.features`.
54
61
  * @param {string[]} [features]
55
62
  * @returns {{ enabled: boolean, protocols: string[], maxMessageBytes: number }}
63
+ * `enabled`: stream-mode rpc (`rpc`). Virtual-mode rpc (`rpc-virtual`) is not counted here: ask `rpcVirtualOffered`.
56
64
  */
57
65
  export function parseRpcFeatures(features = []) {
58
66
  const protocols = [];
@@ -70,6 +78,9 @@ export function parseRpcFeatures(features = []) {
70
78
  return { enabled, protocols, maxMessageBytes };
71
79
  }
72
80
 
81
+ /** Does this feature list offer rpc in virtual data mode (`rpc-virtual`)? @param {string[]} [features] */
82
+ export const rpcVirtualOffered = (features = []) => features.includes(RPC_VIRTUAL_FEATURE);
83
+
73
84
  // ── Errors ────────────────────────────────────────────────────────────
74
85
 
75
86
  /** A JSON-RPC error: thrown by `request()` for an error response, and by handlers to answer with one. */
@@ -245,7 +256,12 @@ function prune(v) {
245
256
  if (Array.isArray(v)) return v.map((x) => (x === undefined ? null : prune(x)));
246
257
  if (v && typeof v === 'object' && !ArrayBuffer.isView(v) && !(v instanceof ArrayBuffer)) {
247
258
  const o = {};
248
- for (const k of Object.keys(v)) if (v[k] !== undefined) o[k] = prune(v[k]);
259
+ for (const k of Object.keys(v)) {
260
+ if (v[k] === undefined) continue;
261
+ // An own `__proto__` member is data (it can arrive in a decoded message): copy it as data, never through the setter.
262
+ if (k === '__proto__') Object.defineProperty(o, k, { value: prune(v[k]), writable: true, enumerable: true, configurable: true });
263
+ else o[k] = prune(v[k]);
264
+ }
249
265
  return o;
250
266
  }
251
267
  return v;
@@ -278,6 +294,8 @@ export class RpcChannel {
278
294
  #closing = null;
279
295
  #held = false;
280
296
  #heldItems = [];
297
+ #heldBytes = 0;
298
+ #onConsumed;
281
299
 
282
300
  /** Called once when the channel ends, with the reason. */
283
301
  onClose = null;
@@ -289,9 +307,13 @@ export class RpcChannel {
289
307
  * @param {number} [opts.maxMessageBytes=1048576]
290
308
  * @param {number} [opts.timeoutMs] - default per-request timeout (none when omitted)
291
309
  * @param {number} [opts.maxInflight=64] - concurrent inbound requests before `-32002`
310
+ * @param {(bytes: number) => void} [opts.onConsumed] - for a metered transport (virtual-mode rpc): called with the number of
311
+ * received bytes this channel has taken in and dispatched, so the transport can hand the sender credit for them. Bytes
312
+ * of messages queued behind `hold()` are not reported until `release()`.
292
313
  */
293
- constructor({ write, close, maxMessageBytes = RPC_DEFAULT_MAX_MESSAGE, timeoutMs, maxInflight = 64 } = {}) {
314
+ constructor({ write, close, maxMessageBytes = RPC_DEFAULT_MAX_MESSAGE, timeoutMs, maxInflight = 64, onConsumed } = {}) {
294
315
  if (typeof write !== 'function') throw new TypeError('RpcChannel: write(bytes) is required');
316
+ this.#onConsumed = typeof onConsumed === 'function' ? onConsumed : null;
295
317
  this.#write = write;
296
318
  this.#closeFn = close ?? (() => {});
297
319
  this.#max = maxMessageBytes;
@@ -359,6 +381,14 @@ export class RpcChannel {
359
381
  if (this.#closed) return;
360
382
  this.#dispatch(item);
361
383
  }
384
+ this.#consumed(this.#heldBytes);
385
+ this.#heldBytes = 0;
386
+ }
387
+
388
+ #consumed(n) {
389
+ if (n > 0 && this.#onConsumed) {
390
+ try { this.#onConsumed(n); } catch { /* the transport's problem */ }
391
+ }
362
392
  }
363
393
 
364
394
  // ── Outbound ────────────────────────────────────────────────────────
@@ -495,6 +525,8 @@ export class RpcChannel {
495
525
  if (this.#held) this.#heldItems.push(item);
496
526
  else this.#dispatch(item);
497
527
  }
528
+ if (this.#held) this.#heldBytes += bytes.length;
529
+ else this.#consumed(bytes.length);
498
530
  }
499
531
 
500
532
  #dispatch(m) {