@johnhenry/wsh 0.49.0 → 0.51.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,176 @@
1
+ # The `wsh-objects` protocol (remote objects)
2
+
3
+ Status: describes what `@johnhenry/wsh/objects` (`src/objects-core.mjs`, `src/objects.mjs`) serves and speaks as of 0.50.0, and what the Rust client
4
+ (`wsh_client::objects`, `wsh objects`) speaks. It adds nothing to the wire: this file only writes down what the code does. The JavaScript
5
+ implementation is the reference; where this text and `src/objects-core.mjs` differ, the code is right and this file is a bug.
6
+
7
+ A host names some **roots** (objects: a page's `window`, a worker's `self`, a Node object). A peer reaches into them **by path** and only
8
+ **cloneable values** cross: plain data, or a name for what is not plain data. There is no distributed object graph. What may be read, called,
9
+ set or listened to is decided by the host's allow-lists (paths with `*` and `**`), by `authorize`, and by the key's capabilities
10
+ (`objects:ROOT[:OP]`, `spec/capabilities.md`); the protocol only carries the request and the refusal.
11
+
12
+ ## 1. The channel
13
+
14
+ An rpc channel of protocol `wsh-objects` (`rpc-protocol:wsh-objects` in `ServerHello.features`), opened as any rpc channel is: `Open { kind: rpc,
15
+ command: "wsh-objects" }`. On a sealed session or behind a relay the host states `rpc-virtual` and the channel rides `SessionData` (inside the
16
+ seal) with `GatewayCredit` backpressure; otherwise it is a data stream. Messages are a CBOR sequence (RFC 8742) of JSON-RPC 2.0 messages
17
+ (`{ jsonrpc: "2.0", id, method, params }`, `{ jsonrpc, id, result }`, `{ jsonrpc, id, error: { code, message, data? } }`, notifications without
18
+ `id`), bounded by `rpc-max-message:<n>` (default 1 MiB). `$/cancel { id }` cancels a request; `$/progress` is not used by this protocol.
19
+
20
+ A path is an array of segments in requests (`["app","cart","items"]`), and text with dots for people (`window.app.cart.items`). The first segment of
21
+ the text form is the root.
22
+
23
+ ## 2. Requests (peer to host)
24
+
25
+ Every `params` is an object. A request names where it starts: `root: "window"` (a root the host listed) or `handle: "<id>"` (section 5), never both.
26
+
27
+ | method | params | result |
28
+ |---|---|---|
29
+ | `roots` | `{}` | `{ roots: [name…], features: [string…] }` |
30
+ | `resolve` | `{ root \| handle, ops: [op…] }` | a **wire value** (section 3) |
31
+ | `set` | `{ root \| handle, path: [seg…], value }` | `{ ok: true }` |
32
+ | `describe` | `{ root \| handle, path?: [seg…] }` | `{ type, keys: [{ key, type, own }…], truncated? }` |
33
+ | `snapshot` | `{ root \| handle, path?: [seg…], depth?, maxBytes? }` | a wire value; `truncated: true` when a subtree deeper than `depth` was cut to `null` |
34
+ | `subscribe` | `{ id, root, path?: [seg…], type, fields?: [name…] }` | `{ ok: true }` |
35
+ | `unsubscribe` | `{ id }` | `{ ok: true, dropped }` |
36
+ | `release` | `{ handle }` | `{ ok: true }` |
37
+ | `releaseCallback` | `{ id }` | `{ ok: true }` |
38
+
39
+ `roots` lists only the roots the key may use (`objects:ROOT[:OP]`). `features` is what the host supports: `events`, `callbacks` and (when a root opted
40
+ in) `handles`. A host that says nothing (before 0.48.0) supports none of them; a peer must not use a feature the host did not state.
41
+
42
+ **`resolve`** walks a whole chain in one request. `ops` is up to 32 operations, each an object with exactly one of:
43
+
44
+ - `{ get: key }` read a member;
45
+ - `{ call: key, args?: [value…], callbacks?: [[index, id]…] }` call the method `key` of the current value (`this` is the current value);
46
+ - `{ construct: key, args?, callbacks? }` `new` the constructor `key`.
47
+
48
+ The chain continues on the result of each step, so `window.app.getCart().items` is `get app, call getCart, get items`. The path an operation is
49
+ judged by is the keys so far, with `()` after a called one (`window.app.getCart().items`): that is what an allow-list entry names. The last operation
50
+ is the one the allow-list must allow (`get`, or `call`/`construct` from the `call` list); the ones before it need only be on the way to something
51
+ the host allows. At most 16 arguments (`maxArgs`). `callbacks` are section 6.
52
+
53
+ `set` assigns the last segment of `path` on the object the rest of it reaches. `describe` lists the names the allow-lists could walk to from the path
54
+ (`type` is `null`, `boolean`, `number`, `string`, `array`, `object`, `function`, `accessor`…). `snapshot` is a bounded deep copy: `depth` (whole
55
+ number, at most the host's `maxDepth`, 8) and `maxBytes` bound it.
56
+
57
+ **`subscribe`** listens to an event source named by an `allow.on` entry `path@type`: the object at `path` must have `addEventListener` /
58
+ `removeEventListener` or `on` / `off`. `id` is a whole number chosen by the peer, at least 1, not yet used on the channel. `type` is a name of
59
+ letters, digits and `_ $ : . -` (up to 128). `fields` (at most 16) are extra event properties the host lists for the type (`eventFields`); a field it
60
+ does not offer is `not-allowed`. A subscription cannot be made through a handle (0.50.0): `subscribe` takes a `root` only.
61
+
62
+ ## 3. Wire values
63
+
64
+ The result of `resolve`, `snapshot` is one of:
65
+
66
+ | shape | meaning |
67
+ |---|---|
68
+ | `{ v: <plain> }` | plain data, plus `truncated: true` on a `snapshot` that cut something |
69
+ | `{ u: <kind>, type?, text? }` | a **named non-value**: something that cannot be cloned |
70
+ | `{ h: <id>, kind, type?, preview?: { keys: [name…] } }` | an opaque **handle** (section 5), only on a root that opted in and only if `features` has `handles` |
71
+
72
+ **Plain data** is `null`, booleans, numbers (integers as CBOR integers, others as floats), text, **bytes** (a CBOR byte string: an `ArrayBuffer`,
73
+ a typed array or a `DataView` on the host), arrays and plain objects with text keys. Inside an object or array the rule is JSON's: a member that
74
+ cannot be cloned (a function, a node, a class instance, a symbol, an accessor property, `undefined`, a cycle) is left out of an object and is `null`
75
+ in an array; the keys `__proto__`, `constructor` and `prototype` are never copied. An integer of 2^63 or more is not plain data (a non-value
76
+ `number`). A value is at most `maxDepth` (8) deep and `maxValueBytes` (256 KiB, and under the channel's message bound less 4096) long, else the
77
+ request is refused with `limit`.
78
+
79
+ **Named non-values**, `u` is one of:
80
+
81
+ | `u` | what it names | `type` / `text` |
82
+ |---|---|---|
83
+ | `undefined` | `undefined` | |
84
+ | `function` | a function | `type`: its name, when printable |
85
+ | `symbol` | a symbol | |
86
+ | `bigint` | a bigint | `text`: its digits |
87
+ | `number` | an integer too large for the wire | `text`: its rendering |
88
+ | `Date` | a date | `text`: ISO 8601 (or `Invalid Date`) |
89
+ | `RegExp` | a regular expression | `text`: its source and flags |
90
+ | `Error` | an error or `DOMException` | `type`: class name, `text`: its message (up to 200 characters) |
91
+ | `object` | any other object: a class instance, a node, a Map | `type`: its class name |
92
+
93
+ `type` is up to 64 printable ASCII characters. **Everything in `type`, `text`, names, previews and strings is the page's own text: untrusted.** A
94
+ peer prints it escaped and never interprets it.
95
+
96
+ **Values sent to the host** (`args`, `set`'s `value`) are plain data only: `null`, booleans, numbers, text, bytes, arrays, plain objects. The host
97
+ refuses any other kind (`bad-request`), a key `__proto__`, `constructor` or `prototype` (`always-refused`), values deeper than 8 or longer than
98
+ `maxValueBytes`.
99
+
100
+ ## 4. Always-refused names and the rules that hold for every allow-list
101
+
102
+ Whatever an allow-list says, these are refused (reason `always-refused`): the path segments `__proto__`, `prototype`, `constructor`,
103
+ `__defineGetter__`, `__defineSetter__`, `__lookupGetter__`, `__lookupSetter__`, `eval`, `Function`, `import`, `execScript`; `call`, `apply` and
104
+ `bind` of a function; `setTimeout`, `setInterval` and `setImmediate` called with a string. A segment is a string of 1 to 256 characters with no
105
+ `.`. The names in `NEEDS_LISTING` (`document.cookie`, `localStorage`, `sessionStorage`, `indexedDB`, `navigator.credentials`, `fetch`,
106
+ `XMLHttpRequest`, `postMessage`, `open`; and on a root with handles the members that climb back to the window or document) are refused (reason
107
+ `needs-listing`) until an allow-list entry **names** them: a wildcard does not.
108
+
109
+ ## 5. Handles
110
+
111
+ On a root that the host says opts in (`features` has `handles`), a function or an object that is not plain data comes back as a handle
112
+ `{ h, kind: "function" | "object", type?, preview? }` instead of a named non-value. A handle is **path-bound**: it stands at the path that produced
113
+ it, and every operation through it (`resolve`, `set`, `describe`, `snapshot` with `handle` in place of `root`) is judged by the allow-lists for that
114
+ path extended by the member named; a handle never widens what the path grants. `preview.keys` (up to 8 names) is told only where a `get` of the
115
+ path would be allowed. The id is 22 characters of base64url from the host's CSPRNG, valid on this channel only (another channel or key finds
116
+ nothing: `bad-request` "no such handle"). The table holds 64 handles per channel (`maxHandles`); more is `limit` and **nothing is evicted**. A
117
+ handle is given back by `release` and all of them when the channel ends. A handle is not an argument: it means something only on its own channel.
118
+
119
+ ## 6. Callbacks
120
+
121
+ A function of the peer may be passed to a `call` or `construct` whose allow-list entry ends in `(callback)`: its place in `args` is `null` and
122
+ `callbacks` lists `[argumentIndex, id]` (`id` a whole number from 1, the same function the same id). The host's stub is **one-way**: calling it
123
+ copies its arguments as plain data, queues a `callback` notification and returns `undefined` at once. The host sends
124
+ `callback { id, seq, args: [value…], dropped? }`; calls beyond `maxCallbacksPerSecond` (20), larger than `maxCallbackBytes` (16 KiB), or when the
125
+ queue is full are dropped and counted (`dropped`, told with the next delivered call). There are at most 16 callbacks per channel
126
+ (`maxCallbacks`). `releaseCallback` kills a stub. `features` has `callbacks`.
127
+
128
+ ## 7. Notifications (host to peer)
129
+
130
+ - `event { id, seq, data, dropped? }`: `id` is the subscription's, `seq` counts the delivered events of that subscription from 1. `data` is plain: for
131
+ an EventTarget source `{ type, timeStamp, isTrusted, ...fields }`, for an emitter `{ type, args: [value…] }`. `dropped` (when present) is the
132
+ number of events the host dropped (rate `maxEventsPerSecond` 20 per subscription, size `maxEventBytes` 16 KiB, queue `maxQueuedEvents` 100 per
133
+ channel, a slow reader) since the last one it delivered for that subscription. At most 16 subscriptions per channel.
134
+ - `callback { id, seq, args, dropped? }`: section 6.
135
+ - `closing { reason }`: the host is about to end the channel (the page left, Stop was pressed, a key was revoked).
136
+
137
+ A peer treats a notification for an id it does not know as noise.
138
+
139
+ ## 8. Errors and limits
140
+
141
+ An error response is `{ code, message, data: { reason, ... } }`. `message` is a sentence for a person and may carry page-controlled text.
142
+
143
+ | `code` | meaning | `reason` (in `data`) |
144
+ |---|---|---|
145
+ | `-32003` | refused | `always-refused`, `not-allowed` (allow-list, or an event type or field the host does not offer), `needs-listing`, `authorize` (the host's `authorize` said no), `not-permitted` (the key's `objects:` capability does not allow the operation on the root), `gone` (the page left) |
146
+ | `-32002` | a bound | `limit`, with `limit` (the name: `maxOps`, `maxArgs`, `maxDepth`, `maxValueBytes`, `maxRequestsPerSecond`, `maxHandles`, `maxCallbacks`, `maxSubscriptions`, `callTimeoutMs`) and `max` |
147
+ | `-32602` | invalid | `bad-request`, `no-such-root` |
148
+ | `-32000` | failed | `bad-path` (reading a member of `null` or `undefined`), `not-a-function`, `threw` (the called code threw), `refused-by-object` (a read-only or frozen assignment), `not-an-event-source`, `cancelled`, `closed` |
149
+ | `-32601`, `-32600`, `-32603`, `-32001` | the rpc layer's own: method not found, invalid request, internal error, cancelled | |
150
+
151
+ `-32002` is also the rpc layer's `stream-limit` (more than 64 requests in flight). The bounds, per attached channel: 32 operations per `resolve`,
152
+ 16 arguments, depth 8, 256 KiB per value, 200 keys per `describe`, 50 requests per second, 30 s for a call that returns a promise, and the counts
153
+ of sections 5 to 7.
154
+
155
+ ## 9. Keys and the host's switches
156
+
157
+ The caller's key may carry `capabilities="objects:ROOT[:OP]"` (`spec/capabilities.md`): a key that names any `objects:` entry is limited to what they
158
+ name (the operation is `get`, `call` (also `construct`), `set` or `on`; `get` also covers `describe`, `snapshot` and walking), may open the
159
+ channel without `rpc:wsh-objects`, and is told only of the roots it can use. A key with no `objects:` entry is limited by `rpc:wsh-objects` alone.
160
+ The key's capability is asked again for every operation (an expiry holds at call time).
161
+
162
+ ## 10. What a peer must do
163
+
164
+ - Open the channel only if the host states `rpc-protocol:wsh-objects`; on a sealed session also `rpc-virtual`.
165
+ - Ask `roots` first, and use only `features` the host stated; refuse locally, with a name, what it did not state, rather than send what a host
166
+ that does not know it would drop (a function it does not know is `null`).
167
+ - Treat every byte of text from the host as untrusted data; never interpret it, never let it reach a terminal unescaped.
168
+ - Bound what it accepts: the channel's message bound applies in both directions, and a subscriber that cannot keep up must drop and count, not stop
169
+ reading (stopping reading stops the host's credit, which is the host's backstop, but also every answer behind it).
170
+
171
+ ## 11. What the released peers do
172
+
173
+ - JavaScript (`@johnhenry/wsh` 0.46.0 to 0.50.0): the reference described above. 0.46.0 and 0.47.0 hosts have no `features` in `roots`, no events, handles or
174
+ callbacks; a peer sees an empty `features`.
175
+ - Rust `wsh-server`: serves no `wsh-objects` channel and no page host, and refuses a key line with an `objects:` capability (an unknown capability
176
+ fails closed). Rust released before the `wsh_client::objects` client (`rust-v0.17.1` and earlier) has no objects client at all.
package/spec/wsh-v1.yaml CHANGED
@@ -1273,7 +1273,15 @@ messages:
1273
1273
  description: >
1274
1274
  Machine-readable failure reason. Known values:
1275
1275
  1=CONNECTION_REFUSED, 2=HOST_UNREACHABLE, 3=DNS_FAILED,
1276
- 4=POLICY_DENIED, 5=GATEWAY_DISABLED.
1276
+ 4=POLICY_DENIED, 5=GATEWAY_DISABLED, 6=CLOSED, 7=QUEUE_FULL.
1277
+ KNOWN INCONSISTENCY (documentation only, behaviour unchanged):
1278
+ the Rust wsh-server sends 5 for a disabled gateway, while the
1279
+ Node gateway (@johnhenry/wsh/server, the page and memory hosts)
1280
+ sends 5 for a timeout (TIMEOUT), and @johnhenry/browsermesh-netway
1281
+ names 5 TIMEOUT. A client that reads 5 should treat it as "timed
1282
+ out or disabled". 6 and 7 are sent by the Node gateway (the Rust
1283
+ server sends 7 for a full queue). The table is exported as data
1284
+ from @johnhenry/wsh (GATEWAY_FAIL_TABLE).
1277
1285
  message:
1278
1286
  type: string
1279
1287
  required: true
@@ -0,0 +1,69 @@
1
+ /**
2
+ * `@johnhenry/wsh/duplex`: a full wsh session over a duplex of messages that another library provides (a mesh channel, a `MessagePort`).
3
+ * Browser-safe. See `spec/duplex-binding.md` for what the duplex must guarantee and what a hop can and cannot do.
4
+ */
5
+ import type { WshClient } from './index.js';
6
+
7
+ export const DUPLEX_DEFAULT_MAX_MESSAGE_BYTES: 65536;
8
+ export const DUPLEX_DEFAULT_MAX_BUFFERED_BYTES: 4194304;
9
+
10
+ export interface WshDuplexOptions {
11
+ /** Writes ONE message to the far side (reliable, in order). May be asynchronous: the next message waits for it. A throw or rejection ends the link. */
12
+ send(bytes: Uint8Array): void | Promise<void>;
13
+ /** Ends the underlying duplex (called when the session ends; not called after `end()`). */
14
+ close?(reason?: string): void;
15
+ /** Default 65536. A bigger write is cut into messages of at most this size; a bigger incoming message ends the link. */
16
+ maxMessageBytes?: number;
17
+ /** Default 4194304. Bytes waiting for `send` (or for a listener) before the link is ended. */
18
+ maxBufferedBytes?: number;
19
+ }
20
+
21
+ /** What `createDuplexSocket` makes: a WebSocket-shaped object the transport and `host.accept` take, and the two calls that feed it. */
22
+ export function createDuplexSocket(options: WshDuplexOptions): {
23
+ socket: object;
24
+ /** One message from the far side. */
25
+ receive(data: Uint8Array | ArrayBuffer): void;
26
+ /** The duplex ended on its own. */
27
+ end(reason?: string): void;
28
+ readonly closed: boolean;
29
+ };
30
+
31
+ /**
32
+ * Serve a host's session over a duplex, SEALED (the host serves nothing until the session is sealed, whatever its own `sealSession`). The host needs a
33
+ * host key; with none `ready` rejects. `allowUnsealed: true` lifts it.
34
+ */
35
+ export function serveWshOverDuplex(
36
+ host: { accept(socket: object, options?: object): Promise<{ close(): void }> },
37
+ options: WshDuplexOptions & { allowUnsealed?: boolean; remote?: { address?: string } },
38
+ ): {
39
+ receive(data: Uint8Array | ArrayBuffer): void;
40
+ end(reason?: string): void;
41
+ ready: Promise<{ close(): void }>;
42
+ close(): void;
43
+ };
44
+
45
+ /**
46
+ * Connect a client over a duplex: key login, sealed, bound to the host key, and the host key must be named (`expectHostKey`, `knownHosts`, or
47
+ * `trustOnFirstUse: true`). `allowUnsealed: true` lifts the seal and the binding; a password login needs it.
48
+ */
49
+ export function connectWshOverDuplex(
50
+ duplex: WshDuplexOptions,
51
+ credentials: {
52
+ username: string;
53
+ keyPair?: CryptoKeyPair;
54
+ signer?: { publicKey: Uint8Array | CryptoKey; sign(data: Uint8Array): Promise<Uint8Array> | Uint8Array };
55
+ password?: string;
56
+ expectHostKey?: string;
57
+ knownHosts?: object;
58
+ trustOnFirstUse?: boolean;
59
+ allowUnsealed?: boolean;
60
+ timeout?: number;
61
+ [option: string]: unknown;
62
+ },
63
+ ): {
64
+ receive(data: Uint8Array | ArrayBuffer): void;
65
+ end(reason?: string): void;
66
+ client: WshClient;
67
+ connected: Promise<WshClient>;
68
+ close(): Promise<void>;
69
+ };
package/src/duplex.mjs ADDED
@@ -0,0 +1,208 @@
1
+ /**
2
+ * `@johnhenry/wsh/duplex` -- a full wsh session over a duplex that someone else provides (#220): a mesh channel, a `MessagePort`, a data
3
+ * channel, anything that can carry bytes in order. Browser-safe. The specification, with what the duplex must guarantee and what a hop on it can
4
+ * and cannot do, is `spec/duplex-binding.md`; this file is the binding.
5
+ *
6
+ * ```js
7
+ * // the host side (a page, a pod): a memory host with a host key, served over the link
8
+ * const host = createMemoryHost({ auth: { authorizedKeys }, hostKey: true, dataStreams: false, exec });
9
+ * const served = serveWshOverDuplex(host, { send: (bytes) => channel.send(bytes) });
10
+ * channel.onmessage = (bytes) => served.receive(bytes);
11
+ *
12
+ * // the client side: pinned to the host key it expects (a mesh knows the peer's key), sealed
13
+ * const link = connectWshOverDuplex({ send: (bytes) => channel.send(bytes) }, { username: 'alice', keyPair, expectHostKey });
14
+ * channel.onmessage = (bytes) => link.receive(bytes);
15
+ * const client = await link.connected;
16
+ * ```
17
+ *
18
+ * Nothing new is on the wire: the duplex carries what a WebSocket would (QMux records), and `createDuplexSocket` is the WebSocket-shaped
19
+ * object the existing transport and `host.accept` already take. A session over it is SEALED unless you say `allowUnsealed: true` out loud.
20
+ */
21
+
22
+ import { WshClient } from './client.mjs';
23
+ import { WebSocketTransport } from './transport-ws.mjs';
24
+
25
+ const CONNECTING = 0;
26
+ const OPEN = 1;
27
+ const CLOSING = 2;
28
+ const CLOSED = 3;
29
+
30
+ /** Largest message handed to `send` unless the duplex says otherwise: what the pipe relay carries by default is 4 MiB; a mesh channel is far smaller. */
31
+ export const DUPLEX_DEFAULT_MAX_MESSAGE_BYTES = 64 * 1024;
32
+ /** Bytes held for a duplex whose `send` has not finished before the link is dropped (a peer that does not read). */
33
+ export const DUPLEX_DEFAULT_MAX_BUFFERED_BYTES = 4 * 1024 * 1024;
34
+
35
+ const toBytes = (data) => {
36
+ if (data instanceof Uint8Array) return data;
37
+ if (data instanceof ArrayBuffer) return new Uint8Array(data);
38
+ if (ArrayBuffer.isView(data)) return new Uint8Array(data.buffer, data.byteOffset, data.byteLength);
39
+ return null;
40
+ };
41
+
42
+ class DuplexEvent extends Event {
43
+ constructor(type, init = {}) { super(type); Object.assign(this, init); }
44
+ }
45
+
46
+ /**
47
+ * The WebSocket-shaped object over a duplex of messages.
48
+ *
49
+ * @param {object} options
50
+ * @param {(bytes: Uint8Array) => void | Promise<void>} options.send writes ONE message to the far side. Messages must arrive reliably and in order. It may be
51
+ * asynchronous (it is waited for before the next is written, which is the backpressure) and a rejection or throw ends the link.
52
+ * @param {(reason?: string) => void} [options.close] ends the underlying duplex
53
+ * @param {number} [options.maxMessageBytes=65536] the largest message `send` is given (a bigger write is cut into messages of at most this size: the
54
+ * transport above reads a byte stream, so where the cuts fall does not matter) and the largest message `receive` accepts (a bigger one ends the link)
55
+ * @param {number} [options.maxBufferedBytes=4194304] bytes waiting for `send`; over it the link is ended (a peer that does not read is not buffered for without bound)
56
+ * @returns {{ socket: object, receive(data: Uint8Array | ArrayBuffer): void, end(reason?: string): void, readonly closed: boolean }}
57
+ */
58
+ export function createDuplexSocket({ send, close, maxMessageBytes = DUPLEX_DEFAULT_MAX_MESSAGE_BYTES, maxBufferedBytes = DUPLEX_DEFAULT_MAX_BUFFERED_BYTES } = {}) {
59
+ if (typeof send !== 'function') throw new TypeError('createDuplexSocket: send(bytes) is required');
60
+ if (close !== undefined && typeof close !== 'function') throw new TypeError('createDuplexSocket: close must be a function');
61
+ if (!Number.isSafeInteger(maxMessageBytes) || maxMessageBytes < 256) throw new TypeError('createDuplexSocket: maxMessageBytes must be a whole number of at least 256');
62
+ if (!Number.isSafeInteger(maxBufferedBytes) || maxBufferedBytes < maxMessageBytes) throw new TypeError('createDuplexSocket: maxBufferedBytes must be a whole number of at least maxMessageBytes');
63
+
64
+ const events = new EventTarget();
65
+ let buffered = 0;
66
+ let pending = Promise.resolve();
67
+ let finished = false;
68
+
69
+ const finish = (code, reason, { callClose = true } = {}) => {
70
+ if (finished) return;
71
+ finished = true;
72
+ socket.readyState = CLOSED;
73
+ if (callClose) { try { close?.(reason); } catch { /* the duplex is already gone */ } }
74
+ events.dispatchEvent(new DuplexEvent('close', { code, reason, wasClean: code === 1000 }));
75
+ };
76
+
77
+ // A duplex is already up when the socket is made, but whoever uses the socket attaches its listeners a moment later (a client builds its
78
+ // transport after some asynchronous steps). So `open` is told to a listener that arrives after it, and messages wait, in order, for the
79
+ // first listener of `message`: nothing the far side said first (the host speaks first) is lost.
80
+ let opened = false;
81
+ let messageListeners = 0;
82
+ const incoming = [];
83
+ const flush = () => {
84
+ if (!opened || messageListeners === 0) return;
85
+ while (incoming.length && !finished) events.dispatchEvent(new DuplexEvent('message', { data: incoming.shift() }));
86
+ };
87
+
88
+ const socket = {
89
+ CONNECTING, OPEN, CLOSING, CLOSED,
90
+ readyState: CONNECTING,
91
+ binaryType: 'arraybuffer',
92
+ get bufferedAmount() { return buffered; },
93
+ addEventListener: (type, fn, options) => {
94
+ events.addEventListener(type, fn, options);
95
+ if (type === 'open' && opened && !finished) queueMicrotask(() => { if (!finished) fn(new DuplexEvent('open')); });
96
+ if (type === 'message') { messageListeners++; queueMicrotask(flush); }
97
+ },
98
+ removeEventListener: (type, fn) => events.removeEventListener(type, fn),
99
+ send(data) {
100
+ if (socket.readyState !== OPEN) throw new Error('WebSocket is not open');
101
+ const bytes = toBytes(data);
102
+ if (!bytes) return; // wsh frames are binary
103
+ for (let at = 0; at < bytes.byteLength; at += maxMessageBytes) {
104
+ const part = bytes.slice(at, at + maxMessageBytes);
105
+ if (buffered + part.byteLength > maxBufferedBytes) { finish(1013, 'the duplex does not take what is written to it'); return; }
106
+ buffered += part.byteLength;
107
+ pending = pending.then(async () => {
108
+ if (finished) return;
109
+ try { await send(part); } catch { finish(1011, 'the duplex failed to send'); } finally { buffered -= part.byteLength; }
110
+ });
111
+ }
112
+ },
113
+ close(code = 1000, reason = '') { finish(code, reason); },
114
+ };
115
+
116
+ queueMicrotask(() => { if (finished) return; socket.readyState = OPEN; opened = true; events.dispatchEvent(new DuplexEvent('open')); flush(); });
117
+
118
+ return {
119
+ socket,
120
+ /** One message from the far side. A message that is not bytes, or is larger than `maxMessageBytes`, ends the link. */
121
+ receive(data) {
122
+ if (finished) return;
123
+ const bytes = toBytes(data);
124
+ if (!bytes) { finish(1003, 'a message that is not bytes'); return; }
125
+ if (bytes.byteLength > maxMessageBytes) { finish(1009, 'a message larger than maxMessageBytes'); return; }
126
+ if (incoming.reduce((n, b) => n + b.byteLength, 0) + bytes.byteLength > maxBufferedBytes) { finish(1013, 'more arrived than the receiver takes'); return; }
127
+ incoming.push(bytes.slice().buffer);
128
+ queueMicrotask(flush); // in order, after `open`, once something listens
129
+ },
130
+ /** The duplex ended on its own (the peer left, the channel closed): the socket closes, `close` is not called back. */
131
+ end(reason = 'the duplex ended') { finish(1006, reason, { callClose: false }); },
132
+ get closed() { return finished; },
133
+ };
134
+ }
135
+
136
+ /**
137
+ * Serve a host's wsh session over a duplex: `host.accept(socket)` with `dataStreams: false` and the session SEALED, whatever the host's own
138
+ * `sealSession` says (it can only be strengthened). The host needs a host key (`hostKey: ...`): with none it cannot seal, so it cannot serve a
139
+ * duplex, and `ready` rejects. `host` is anything with `accept(socket, options)`: `createMemoryHost()`, `createWshServer()`.
140
+ *
141
+ * @param {{ accept(socket: object, options?: object): Promise<{ close(): void }> }} host
142
+ * @param {object} options as `createDuplexSocket` (`send`, `close`, `maxMessageBytes`, `maxBufferedBytes`), and
143
+ * @param {boolean} [options.allowUnsealed=false] serve a client that does not seal: nothing a hop does is then caught. Refused by default.
144
+ * @param {object} [options.remote] what the host knows of the far side (`{ address }`, for its rate limiting of password failures)
145
+ * @returns {{ receive(data: Uint8Array | ArrayBuffer): void, end(reason?: string): void, ready: Promise<{ close(): void }>, close(): void }}
146
+ */
147
+ export function serveWshOverDuplex(host, { allowUnsealed = false, remote, ...duplexOptions } = {}) {
148
+ if (typeof host?.accept !== 'function') throw new TypeError('serveWshOverDuplex: host must have accept(socket, options) (createMemoryHost(), createWshServer())');
149
+ if (typeof allowUnsealed !== 'boolean') throw new TypeError('serveWshOverDuplex: allowUnsealed must be true or false');
150
+ const link = createDuplexSocket(duplexOptions);
151
+ const ready = Promise.resolve().then(() => host.accept(link.socket, {
152
+ dataStreams: false,
153
+ ...(allowUnsealed ? {} : { sealSession: 'require' }),
154
+ ...(remote ? { remote } : {}),
155
+ })).catch((e) => { link.socket.close(1011, 'this host cannot serve this duplex'); throw e; });
156
+ ready.catch(() => {});
157
+ return {
158
+ receive: link.receive,
159
+ end: link.end,
160
+ ready,
161
+ close() { link.socket.close(1000, 'closed'); },
162
+ };
163
+ }
164
+
165
+ /**
166
+ * Connect a wsh client over a duplex: the login is a key login, the session is SEALED, the login is bound to the host's key, and the host's key
167
+ * must be named: a hop on the duplex that answers as a host of its own would otherwise be trusted on first use. Name it with `expectHostKey` (the
168
+ * hex fingerprint; over a mesh it is the peer's pod id, `podIdToFingerprint(peer)`), or `knownHosts`, or say `trustOnFirstUse: true`.
169
+ *
170
+ * @param {object} duplex as `createDuplexSocket` (`send`, `close`, `maxMessageBytes`, `maxBufferedBytes`)
171
+ * @param {object} credentials `{ username, keyPair | signer, expectHostKey | knownHosts | trustOnFirstUse, timeout, allowUnsealed }` and the other options of
172
+ * `WshClient.connect`; `allowUnsealed: true` (and `sealSession`, `requireChannelBinding`) set the guarantees down, out loud
173
+ * @returns {{ receive(data: Uint8Array | ArrayBuffer): void, end(reason?: string): void, client: WshClient, connected: Promise<WshClient>, close(): Promise<void> }}
174
+ */
175
+ export function connectWshOverDuplex(duplex, { allowUnsealed = false, ...credentials } = {}) {
176
+ if (typeof allowUnsealed !== 'boolean') throw new TypeError('connectWshOverDuplex: allowUnsealed must be true or false');
177
+ if (credentials.password !== undefined && !allowUnsealed) throw new TypeError('connectWshOverDuplex: a password login cannot be sealed (a hop would read it): use a key, or say allowUnsealed: true');
178
+ if (credentials.expectHostKey === undefined && credentials.knownHosts === undefined && credentials.trustOnFirstUse !== true && credentials.onHostKey === undefined) {
179
+ throw new TypeError('connectWshOverDuplex: name the host key you expect (expectHostKey: its hex fingerprint, over a mesh the peer\'s pod id converted with podIdToFingerprint), or knownHosts, or say trustOnFirstUse: true (a hop on the duplex could answer as the host)');
180
+ }
181
+ const link = createDuplexSocket(duplex);
182
+ let used = false;
183
+ // One duplex serves one connection: the constructor the transport calls hands back the socket made for it, once.
184
+ function LinkSocket() {
185
+ if (used) throw new Error('this duplex carries one connection and it is in use');
186
+ used = true;
187
+ return link.socket;
188
+ }
189
+ const client = new WshClient({
190
+ transportFactories: {
191
+ ws: () => new WebSocketTransport({ WebSocket: LinkSocket }),
192
+ wt: () => { throw new Error('connectWshOverDuplex: a duplex is not WebTransport'); },
193
+ },
194
+ });
195
+ const connected = client.connect('ws://duplex.invalid/', {
196
+ transport: 'ws',
197
+ ...(allowUnsealed ? {} : { sealSession: true, requireChannelBinding: ['host'] }),
198
+ ...credentials,
199
+ }).then(() => client);
200
+ connected.catch(() => {});
201
+ return {
202
+ receive: link.receive,
203
+ end: link.end,
204
+ client,
205
+ connected,
206
+ close: () => client.disconnect(),
207
+ };
208
+ }
@@ -347,6 +347,9 @@ function capabilityRefusal(p, req) {
347
347
  else if (req.channel === 'file') { const need_ = req.direction === 'download' ? 'fs:read' : 'fs:write'; r = need(need_, has(need_)); }
348
348
  else if (req.channel === 'rpc') {
349
349
  const proto = req.protocol;
350
+ // A handler that says it authorizes for itself (`authorizesItself`: it asks the host's own `permits` for every call) is opened by any key the
351
+ // options let in: the list does not have to name its protocol. The options and the expiry were checked before this; only the `rpc:`/`mcp:` entry is deferred.
352
+ if (req.authorizesItself === true) return req.target === undefined || req.target === null ? null : target();
350
353
  // The file rpc has read and write methods on one channel: a key without both is refused it (a client falls back to
351
354
  // FileOp and the file channels, which are checked per operation).
352
355
  if (proto === 'wsh-fs') r = need('fs:read', has('fs:read')) ?? need('fs:write', has('fs:write'));