@johnhenry/wsh 0.51.0 → 0.52.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 CHANGED
@@ -386,8 +386,11 @@ The notation above is written down once, as a specification, with vectors that a
386
386
  capabilities the notation knows, a timestamp it can read, no control character or line break in the comment, a plain Ed25519
387
387
  key, and it reads its own line back through a host's parser before returning it.
388
388
  - **The gateway error table** is data too: `GATEWAY_FAIL`, `GATEWAY_FAIL_TABLE` and `gatewayFailName(code)` are exported from the
389
- package root (`@johnhenry/browsermesh-netway` decodes the same numbers). The table notes that the Rust server sends `5` for a
390
- disabled gateway where the Node gateway sends it for a timeout.
389
+ package root (`@johnhenry/browsermesh-netway` decodes the same numbers; the vectors are `spec/gateway-fail.vectors.json`). `5` is
390
+ `GATEWAY_DISABLED` (the spec and the Rust server) and `TIMEOUT` is `8` (#223). A Node gateway of 0.51.0 or earlier sent `5` for a timeout,
391
+ so a reader keeps treating a `5` as "the gateway is disabled, or a timeout from an older Node gateway": `GATEWAY_FAIL_TABLE` and the
392
+ message of a `GatewayError` that carries `5` say both. A new Node gateway sends `8` for a timeout, so a client written for the
393
+ old number (`code === 5` meaning a timeout) must also accept `8`.
391
394
  - **For the object and MCP layers**: the identity handed to `authorize(who, op)` is `{ username, fingerprint, podId? }`.
392
395
  `fingerprint` is always the hex hash of the caller's key; `podId` is there when the transport knows the caller by one. A
393
396
  transport that is not wsh gives an identity object (`createDuplexPeer({ send, who: { podId } })`, or `attach(peer, { who })`)
@@ -754,6 +757,34 @@ On the far side nothing new is needed: `wsh-mcp --sealed --host-key <host.finger
754
757
  server any MCP client can launch, and in code `client.connect(host.operatorUrl, { keyPair, sealSession: true })` then
755
758
  `client.openRpc('mcp')`. The host serves one operator at a time and dials the relay again when a session ends.
756
759
 
760
+ **The dial-out form (`connect`, #219), off unless written.** For an operator that *listens* (a process of yours that accepts connections), the page can dial it itself
761
+ instead of waiting behind a relay: `createPageHost({ window, connect: 'wss://operator.example/pages/shop', name, authorizedKeys, mcp, expose })` (not together with `relay`;
762
+ there is no `operatorUrl` and no rendezvous id, both are `null`). The URL is dialled **exactly as written** (no role or rendezvous id is added), must be `ws://` or `wss://` with
763
+ no user name, password or fragment in it, and is **never logged** (its query may hold a secret). Everything after the socket opens is what it is behind a relay: key login only
764
+ (`authorizedKeys`), a sealed session, `onSession`, the person's approval for consequential tools, the visible indicator and **Stop** (which also refuses that key), the
765
+ `mcp` and `wsh-objects` channels, closing when the window leaves its origin, and dialling again after a session or a failed attempt (`reconnect`, with the same backoff). The operator
766
+ is the wsh *client* on what it accepts, for example in Node:
767
+
768
+ ```js
769
+ import { WebSocketServer } from 'ws';
770
+ import { connectWshOverDuplex } from '@johnhenry/wsh/duplex';
771
+
772
+ new WebSocketServer({ port: 9000 }).on('connection', (ws) => {
773
+ const link = connectWshOverDuplex({ send: (bytes) => ws.send(bytes), close: () => ws.close(1000) },
774
+ { username: 'alice', keyPair, expectHostKey: pageHostFingerprint }); // the page shows host.fingerprint; the login is sealed and bound to it
775
+ ws.on('message', (data) => link.receive(data));
776
+ ws.on('close', () => link.end('the page left'));
777
+ link.connected.then((client) => client.openRpc('mcp'));
778
+ });
779
+ ```
780
+
781
+ What the form changes: **nothing sits between the page and the operator**, so there is no relay to see ciphertext (the sealed session still hides the traffic from a hop you did not
782
+ choose, such as a proxy), and **the page chooses whom to dial**: whoever answers at that URL learns the page's host key and what its handshake states before any key logs in, and can
783
+ only try to log in (a key that is not in `authorizedKeys`, or whose `capabilities` do not allow it, gets nothing). What it does **not** protect against: a URL that points at the wrong
784
+ listener is not noticed by the page (the operator must pin the page's host key, and the page does not pin the operator: it authenticates keys, not endpoints); a page that
785
+ is told to dial by code you did not write dials; the page redials the URL for as long as the host is open, so a listener that wants a quiet period must say no at login, or the host be
786
+ closed. Browser pages can dial `wss://` endpoints their content security policy allows (`connect-src`), and not `ws://` from an `https:` page.
787
+
757
788
  **`window` is explicit.** `createPageHost`, `webmcpTools` and `captureWebMcp` read nothing but the object they are given: where tools are
758
789
  registered (`window.document.modelContext`, the older `window.navigator.modelContext`), where the indicator is drawn
759
790
  (`window.document`), which `WebSocket` dials the relay, and whose origin is reported. A test greps the entry point's source for
@@ -943,7 +974,7 @@ await release(cart); // gives its place back; everything
943
974
  and drops what it had queued; it also ends with the channel, Stop, a navigation and a revoke, as a path subscription does. A handle released while its subscription was being authorized leaves no listener. `maxSubscriptions`, the rate, size and queue bounds and the drop counting are the same ones, shared with path subscriptions.
944
975
  The delivery is the same too: plain copies, never the event, never a handle.
945
976
 
946
- A host says what it supports with its roots (`features`: `events`, `callbacks`, and `handles` and `handle-events` when a root opted in). A client does not send a function to a host that has not said it supports callbacks, nor use events on one that has not said so, nor subscribe through
977
+ A host says what it supports with its roots (`features`: `events`, `callbacks`, `callback-returns` when an entry lets a callback return a value, `types`, and `handles` and `handle-events` when a root opted in). A client does not send a function to a host that has not said it supports callbacks, nor use events on one that has not said so, nor subscribe through
947
978
  a handle on one that has not said `handle-events` (0.50.0 and before; a named `unsupported` error, nothing is sent);
948
979
  a handle-shaped answer from a host that never said it supports handles is the same error. A 0.47.0 host says nothing, so it counts as supporting none of them. A 0.50.0 client never sends a handle subscription (it refuses to write one), so it is unaffected by a 0.51.0 host.
949
980
 
@@ -957,7 +988,14 @@ await win.app.subscribe((event) => console.log(event.n)); // the page's subscr
957
988
  await release(fn); // kills the stub (also: the channel ending)
958
989
  ```
959
990
 
960
- - **One-way.** The stub copies its arguments, queues a notification and **returns `undefined` at once**: the page cannot be made to wait for the far side, and the far side's return value is not delivered back (a notation to ask for it is not built).
991
+ - **One-way.** The stub copies its arguments, queues a notification and **returns `undefined` at once**: the page cannot be made to wait for the far side, and the far side's return value is not delivered back. That is the rule for every entry that says only `(callback)`. The next bullet is the one way to get a value back, and only where the host wrote it.
992
+ - **Callback return values (#219), off unless the host opts in per entry.** An entry that ends in `(callback:returns)` (every function the call takes may answer) or `(callback:returns=0,2)` (only the functions at those argument positions; the others stay one-way) makes that stub return a **promise** of what the far side's function returned: `const ok = await stub(question)`. The page is never blocked and never waits unboundedly:
993
+ - **The wait is bounded by the host**, from the call (queueing included): `limits.callbackReturnTimeoutMs`, 2000 by default and **at most 30000** (a larger value is a `TypeError` when the host is created). The host needs `timers` (`exposeObjects` and `createPageHost` supply them; `createObjectsServer` without `timers` and a returning entry is a `TypeError`).
994
+ - **Every case that is not an answer is `undefined`**, and the promise **never rejects**: the timeout, an error thrown by the far side's function (its text stays on the far side, where `onCallbackError` gets it), a result that is not plain data (a function, a handle) or larger than `maxCallbackResultBytes` (16384), a call over the rate or size bound, a table that is full (`maxPendingCallbackReturns`, 8 calls waiting per channel, at most 64: the call is dropped, counted and **not sent**), a released callback, the end of the channel (Stop, a navigation, a revoke settle every waiting call with `undefined` at once and take the timers away), and a far side that did not say it can answer. So treat `undefined` as "no answer": a function that returns `undefined` is indistinguishable from a timeout, and code that asks "may I?" must treat anything but an explicit `true` as no.
995
+ - **The value is plain data**, copied under the same rules as an argument (`maxDepth` 4, bytes, bytes arrays, no function, no handle, never an object with a prototype), and the page is handed the copy. A late answer after the timeout is ignored. An answer is for a request id the host gave on this channel, once; an answer for an id nobody waits for is counted against the request rate and changes nothing else.
996
+ - **A far side that is slow or hostile can make the page wait at most `callbackReturnTimeoutMs` per call and at most `maxPendingCallbackReturns` calls at a time**; it cannot make the page wait for anything else. `host.callbackReturnStats()` (on what `attach` returns) says how many calls are `pending` and how many were `answered`, `timedOut`, `failed`, `refused` or `dropped`.
997
+ - **Negotiation.** A host states `callback-returns` in the `features` of its `roots` answer only when an entry says it; a client says it answers by listing `callback-returns` in the `features` of its `roots` request. A host that has not been told never asks (the stub resolves `undefined` at once and the callback is delivered one-way), so a 0.51.0 client against a new host neither waits nor breaks, and a new client against a 0.51.0 host sends one extra optional field that it ignores. The `types` a host sends tell an entry as `(callback)` so a 0.51.0 client reads them; the generated types do not describe a returned value.
998
+ - **What it does not do.** It does not make the answer true or safe: whatever the far side returns is data from the person or program on the other end, and the page's code that acts on it (`if (await ask())`) is what to write defensively. It adds no other direction: the far side still cannot call into the page except through the entries the host listed.
961
999
  - **Plain values only.** The arguments are copied under the same rules as a result: plain data and bytes; what cannot be cloned (a function, a node, a class instance, a date) is `null`; never a handle.
962
1000
  - **Bounds.** `maxCallbacks` (16 per channel, refused by name), `maxCallbacksPerSecond` (20 per callback), `maxCallbackBytes` (16384 per call); a call over the rate, the size or the shared queue (`maxQueuedEvents`) is dropped and counted, and the next delivered call is preceded by
963
1001
  `onCallbackDropped({ dropped })` on the client. The notifications go through the channel's credit like events. The same function sent again is the same callback.
@@ -1012,7 +1050,7 @@ reach is exactly the paths the lists name (and, below a `get`, the plain data in
1012
1050
  - A sealed session, a key login and a visible indicator (the page host) are what keep a relay and an unknown caller out; `authorize` is where an embedder asks the person.
1013
1051
 
1014
1052
  Size: see the size table (`npm run size`) for `@johnhenry/wsh/objects` (it contains the client and the checks the host runs on a type map), `@johnhenry/wsh/objects-types` and the page entry point. A capability per root and operation (`objects:ROOT[:OP]`) is described under [per-key capabilities](#authorized-key-options-122).
1015
- Not built yet: a dial-out form.
1053
+ A dial-out form of the page host (`createPageHost({ connect })`, an operator that listens) is described under [A page as a host](#a-page-as-a-host-johnhenrywshpage-190).
1016
1054
 
1017
1055
  #### Typed remotes (#219)
1018
1056
 
@@ -1039,7 +1077,7 @@ a hand-written `T` is what you believe); `authorize` is dynamic and is not refle
1039
1077
  another key gets another file, and a key that changes or expires changes the answer. The `types` answer tells a key the allow-list entries it may use, which is what `describe` would reveal path by path and nothing about a member the key may not reach.
1040
1078
 
1041
1079
  **The CLI.** `wsh-objects-types [--root NAME] [--name TYPE] [--out FILE [--force]] [--sealed] [--host-key KEY] [--identity FILE] [user@]<url>` (the package's second bin; JavaScript only) connects like `wsh-mcp` does, asks for the description of one root and prints the declarations, or writes them with `--out`.
1042
- The Rust `wsh` has no `wsh-objects` client and no equivalent. A host before 0.51.0 does not state the `types` feature in the `features` of its `roots` answer, and `rootDescription` then refuses with a named `unsupported` error without sending anything.
1080
+ The Rust `wsh --sealed [--via RELAY] objects user@host types ROOT` (`rust-v0.19.0`) asks the same question and prints the description as JSON (`wsh_client::objects::ObjectsClient::root_description`); it has no generator for `.d.ts` text. A host before 0.51.0 does not state the `types` feature in the `features` of its `roots` answer, and `rootDescription` then refuses with a named `unsupported` error without sending anything.
1043
1081
 
1044
1082
  ### WebTransport listener
1045
1083
 
@@ -1720,15 +1758,18 @@ wsh --sealed [--via RELAY] objects user@host set window.app.n 5
1720
1758
  wsh --sealed [--via RELAY] objects user@host snapshot window.app.state --depth 3
1721
1759
  wsh --sealed [--via RELAY] objects user@host describe window.app
1722
1760
  wsh --sealed [--via RELAY] objects user@host watch window.app.bus@ready --field detail --count 3
1723
- wsh --sealed [--via RELAY] objects user@host session # JSON requests on stdin, one answer line each: one connection, so a handle can be held across calls
1761
+ wsh --sealed [--via RELAY] objects user@host types window # what this key may do on the root, as the host describes it (needs the host to state `types`)
1762
+ wsh --sealed [--via RELAY] objects user@host session # JSON requests on stdin, one answer line each: one connection, so a handle, a subscription or a callback can be held across calls
1724
1763
  ```
1725
1764
 
1726
1765
  JSON on stdout. Plain data is printed as the JSON it is; bytes as `{"$bytes":"<base64>"}`, what the host could not clone as `{"$nonValue":{"kind":"function","type":"fn"}}`, a handle as `{"$handle":{...}}` (a page can build plain data that looks like these: this is an inspection format; use the library where that matters).
1727
1766
  **Text from the page is never interpreted**: names, strings, previews and error messages are printed as JSON strings in which every control character, C1 control, line or paragraph separator and bidirectional-text control is a `\uXXXX` escape. `watch` prints one line per event, `{"seq":N,"dropped":N,"dropped_here":N,"data":...}`: `dropped` is what the host dropped before it (its bounds: rate, size, queue), `dropped_here` what this side dropped when its bounded queue was full.
1728
- Exit status: 0 done; 1 other failure; 2 usage, or not `--sealed`; 3 the host refused (its allow-lists, a key's `objects:` capability, a bound); 4 not found; 5 unsupported (the host does not state the channel, or `events` / `handles`, which are refused locally before anything is sent). `wsh --help objects` lists the rest.
1767
+ Exit status: 0 done; 1 other failure; 2 usage, or not `--sealed`; 3 the host refused (its allow-lists, a key's `objects:` capability, a bound); 4 not found; 5 unsupported (the host does not state the channel, or `events` / `handles` / `handle-events` / `callbacks` / `types`, which are refused locally before anything is sent). `wsh --help objects` lists the rest.
1768
+
1769
+ In a `session`, one line per request and one answer line each, in order. Events and callbacks live there because they need one connection: `{"op":"watch","path":"window.app.bus","event":"ready"}` answers `{"ok":true,"result":{"subscription":"s1"}}` (through a handle: `{"op":"watch","handle":"h1","path":"","event":"ready"}`; the host must state `handle-events`, and releasing the handle ends the subscription); `{"op":"next","subscription":"s1"}` waits (`timeoutMs`, default 10000) for the next event; `{"op":"callback"}` answers `{"callback":"c1"}`, which a call passes with `{"op":"call","path":"window.app.listen","args":[null],"callbacks":[[0,"c1"]]}` (the host must state `callbacks`, and the allow-list entry must end in `(callback)`); `{"op":"next","callback":"c1"}` waits for the host's next call of it; `unwatch` and `{"op":"release","callback":"c1"}` end them.
1729
1770
 
1730
- In Rust code, `wsh_client::objects::ObjectsClient::open(&client)` gives `roots()`, `root(name)` and a `Target` with `get` / `call` / `construct` / `set` / `snapshot` / `describe` / `resolve(Chain)` (a whole chain such as `app.getCart().items` is one request) and `subscribe` (a bounded `Subscription`), with typed `ObjectsError`s (`Refused`, `Limit`, `NotFound`, `Unsupported`, ...) carrying the host's `reason`, values as a serde-friendly `Value` (bytes native), and `Handle`s (released with `release()`, when dropped, and when the session ends).
1731
- **What it cannot do:** callbacks (passing a function to the host), events through a handle (the host offers none), and serving objects (`wsh-server` has no page host and no `wsh-objects` handler); WebTransport and Windows are not exercised. It protects nothing the host's allow-lists do not: it only speaks to a host that chose to expose objects.
1771
+ In Rust code, `wsh_client::objects::ObjectsClient::open(&client)` gives `roots()`, `root(name)`, `root_description(root)` (the `types` answer, as plain data), `callback(capacity)` and a `Target` with `get` / `call` / `call_with` (callbacks among the arguments) / `construct` / `set` / `snapshot` / `describe` / `resolve(Chain)` (a whole chain such as `app.getCart().items` is one request) and `subscribe` (a bounded `Subscription`, from a root or from a handle's `target()`), with typed `ObjectsError`s (`Refused`, `Limit`, `NotFound`, `Unsupported`, ...) carrying the host's `reason`, values as a serde-friendly `Value` (bytes native), `Handle`s (released with `release()`, when dropped, and when the session ends) and `Callback`s (a bounded queue of the host's calls; one-way: the host gets no return value).
1772
+ **What it cannot do:** serve objects (`wsh-server` has no page host and no `wsh-objects` handler, and will not: see [why](spec/objects.md#11-what-the-released-peers-do)); WebTransport and Windows are not exercised. It protects nothing the host's allow-lists do not: it only speaks to a host that chose to expose objects. A callback hands the host's code a way to push plain values at this process: they are bounded (this side's queue, the host's rate and size limits) and untrusted like every other byte from the host, and a `session`'s `next` prints them as escaped JSON.
1732
1773
 
1733
1774
  ### Host key (fingerprint / TOFU)
1734
1775
 
@@ -2233,7 +2274,7 @@ instead of dragging its own toolchain and CI job into an unrelated
2233
2274
  browser-app repo. It was previously deleted from clawser by accident
2234
2275
  (2026-03-14) and restored (2026-07-05) before this move.
2235
2276
 
2236
- Four crates, workspace-versioned (currently `0.18.0`):
2277
+ Four crates, workspace-versioned (currently `0.19.0`):
2237
2278
 
2238
2279
  | Crate | Kind | Description |
2239
2280
  |-------|------|--------------|
@@ -2404,9 +2445,10 @@ than left to be found.
2404
2445
  | Dial target | a URL | `wsh [user@]host` (dials `https://` then `wss://` on `--port`), or a full URL: `wsh wss://host:8443/rendezvous/ab12 command`, `ws://127.0.0.1:PORT/` | **CLI-only convenience**: a URL is dialled exactly as given (no transport fallback; `--port` and `--transport` do not apply). Plain `ws://` is accepted only to a loopback host |
2405
2446
  | Host that runs in a browser page (`createMemoryHost`, `@johnhenry/wsh/reverse`) | yes, with injected `pty` / `fs` / `hostKey` | no (a Rust host is a process) | **JS-only**. A Rust *client* can operate such a host only with `dataStreams: false` (#132): the released Rust client over WebSocket cannot open QMux data streams, and says nothing in `Hello` that a host could use to decide. `wsh scp` works against such a host with the Rust client of the next `rust-v` release (it speaks `FileChunk`, #140); a released `rust-v0.11.0` or older `wsh scp` hangs against it (`wsh ls` and exec work) |
2406
2447
  | A page's WebMCP tools served as MCP, behind a pipe relay (#190) | `createPageHost`, `webmcpTools`, `captureWebMcp` from `@johnhenry/wsh/page`; the far side is `wsh-mcp --sealed` or `openRpc('mcp')` | the far side only: `wsh --sealed --via <relay>/r/<id> mcp user@host` (the Rust CLI, `rust-v0.17.1`+) lists and calls a page host's tools (`test/rust/wsh-mcp-page-host.test.mjs`); the Rust `wsh objects` is a `wsh-objects` client (next row), and no Rust host serves either | **JS-only** host (a page); the far side is unchanged wire (`mcp` rpc in virtual mode, #191) |
2407
- | Remote objects by path, `values` mode (#190): `wsh-objects`, `client.openObjects()` | `exposeObjects` / `createObjectsServer` / `createPageHost({ expose })` host side; `get`, `set`, `call`, `construct`, `snapshot`, `describe` far side (`@johnhenry/wsh/objects`) | **Client only** (`rust-v0.18.0`, #219): `wsh_client::objects` (`ObjectsClient`, values mode, events with a bounded `Subscription`, handles) and `wsh --sealed [--via RELAY] objects user@host roots\|get\|call\|set\|snapshot\|describe\|watch\|session` (sealed sessions only; JSON on stdout; exit 3 refused, 4 not found, 5 unsupported); a feature the host does not state is refused locally. Not built: callbacks, events through a handle. `wsh-server` serves no `wsh-objects` and refuses an `objects:` key capability. The wire is `spec/objects.md`; tested against a real page host through a recording relay (`test/rust/wsh-objects.test.mjs`) | **JS host, Rust or JS far side**; an rpc protocol on the existing `rpc` channel (no new message or feature string), so a released peer simply does not offer or open it. The Rust codec gained a CBOR-value read path so byte strings survive (the existing `rpc` channels still reject them) |
2408
- | Events through a handle (#219): `on(use(handle).path, type, listener)` | `@johnhenry/wsh/objects` (`exposeObjects({ handles })`); the host states `handle-events` in the `features` of its `roots` answer | none: no Rust `wsh-objects` client or host | **JS-only**; a new `subscribe` parameter (`handle`) on the existing `wsh-objects` rpc channel, offered only to a client that saw `handle-events`. A 0.50.0 host does not say it, and a new client then refuses to subscribe through a handle with a named `unsupported` error without sending anything; a 0.50.0 client cannot write such a request |
2409
- | Typed remotes (#219): `describeRootTypes`, `rootDescription`, `Remote<T>`, `wsh-objects-types` | `@johnhenry/wsh/objects` (the `types` method, the `types` option, `Remote<T>`, `RemoteRoots<T>`), `@johnhenry/wsh/objects-types` (the pure generator), the `wsh-objects-types` bin | none: no Rust `wsh-objects` client or host, and the Rust CLI has no equivalent of the bin | **JS-only**; a new `types` method on the existing `wsh-objects` rpc channel and a `types` string in the `features` of its `roots` answer (no new message type or `ServerHello` feature). A 0.50.0 host does not state it, and a new client then refuses with a named `unsupported` error and sends nothing; a 0.50.0 client never calls it |
2448
+ | A page host that dials an operator that listens, instead of a relay (#219): `createPageHost({ connect })` | `@johnhenry/wsh/page`; the operator is any process that accepts the socket and logs in as the client (`connectWshOverDuplex` from `@johnhenry/wsh/duplex`) | none: the Rust CLI has no listening operator mode (`wsh --via` dials a relay's operator side), so a Rust far side cannot be the listener | **JS-only**, no wire change: the same handshake and sealed session over a socket the page opened, URL as written |
2449
+ | Remote objects by path, `values` mode (#190): `wsh-objects`, `client.openObjects()` | `exposeObjects` / `createObjectsServer` / `createPageHost({ expose })` host side; `get`, `set`, `call`, `construct`, `snapshot`, `describe` far side (`@johnhenry/wsh/objects`) | **Client only** (`rust-v0.18.0`, #219): `wsh_client::objects` (`ObjectsClient`, values mode, events with a bounded `Subscription`, handles; from `rust-v0.19.0`: events through a handle, callbacks, `root_description`) and `wsh --sealed [--via RELAY] objects user@host roots\|get\|call\|set\|snapshot\|describe\|watch\|types\|session` (sealed sessions only; JSON on stdout; exit 3 refused, 4 not found, 5 unsupported); a feature the host does not state is refused locally. Callback return values (`(callback:returns)`, a JS host notation) are not asked of it: it never lists `callback-returns`, so a callback it passes stays one-way. Not planned: a host in `wsh-server` (it has no object graph to expose, see `spec/objects.md` section 11); it serves no `wsh-objects` and refuses an `objects:` key capability. The wire is `spec/objects.md`; tested against a real page host through a recording relay (`test/rust/wsh-objects.test.mjs`) | **JS host, Rust or JS far side**; an rpc protocol on the existing `rpc` channel (no new message or feature string), so a released peer simply does not offer or open it. The Rust codec gained a CBOR-value read path so byte strings survive (the existing `rpc` channels still reject them) |
2450
+ | Events through a handle (#219): `on(use(handle).path, type, listener)` | `@johnhenry/wsh/objects` (`exposeObjects({ handles })`); the host states `handle-events` in the `features` of its `roots` answer | **Client only** (`rust-v0.19.0`): `Target::subscribe` on a handle's `target()` and, in `wsh objects session`, `{"op":"watch","handle":...}`; refused locally unless the host states `handle-events`; releasing the handle ends the subscription. No Rust host | **JS host**; a new `subscribe` parameter (`handle`) on the existing `wsh-objects` rpc channel, offered only to a client that saw `handle-events`. A 0.50.0 host does not say it, and a new client then refuses to subscribe through a handle with a named `unsupported` error without sending anything; a 0.50.0 client cannot write such a request |
2451
+ | Typed remotes (#219): `describeRootTypes`, `rootDescription`, `Remote<T>`, `wsh-objects-types` | `@johnhenry/wsh/objects` (the `types` method, the `types` option, `Remote<T>`, `RemoteRoots<T>`), `@johnhenry/wsh/objects-types` (the pure generator), the `wsh-objects-types` bin | **Client only, the data not the generator** (`rust-v0.19.0`): `ObjectsClient::root_description` and `wsh objects types ROOT` print the host's `types` answer as JSON; refused locally unless the host states `types`. No `.d.ts` generator and no `Remote<T>` in Rust; no Rust host | **JS host**; a new `types` method on the existing `wsh-objects` rpc channel and a `types` string in the `features` of its `roots` answer (no new message type or `ServerHello` feature). A 0.50.0 host does not state it, and a new client then refuses with a named `unsupported` error and sends nothing; a 0.50.0 client never calls it |
2410
2452
  | An MCP face for named object paths (#219): `exposeObjects({ mcp: { tools } })`, `createPageHost({ expose: { ROOT: { mcp: { tools } } } })` | `@johnhenry/wsh/objects` (`handler.mcpTools`, `server.invoke`) served by `webmcpTools` / `serveMcpOverDuplex` on the `mcp` channel; the far side is any MCP client (`wsh-mcp --sealed`, `client.openRpc('mcp')`) | the far side only: `wsh --sealed --via <relay>/r/<id> mcp user@host` lists and calls these tools like any `mcp` tool; no Rust `wsh-objects` host | **JS-only host**; **wire: nothing new** (the existing `mcp` rpc channel and its methods, no feature string), so any released MCP-speaking peer reaches it |
2411
2453
  | Interactive shell UI | none -- this SDK is a protocol client, not a terminal emulator; pair with xterm.js/ghostty-web | `wsh connect`, `wsh sftp` (line-oriented REPL) | **Deliberately not unified** -- a browser embeds a terminal widget the host page owns; a CLI process owns its own TTY |
2412
2454
  | Attach / resume | `attachSession()`, `resumeSession()`, `WshSession.seq` | `attach_session()`, `resume_session()` | **Wire-unified** (`Attach`/`Resume`/`Presence`); `seq` = cumulative output bytes. `@johnhenry/wsh/server` honours `last_seq` (bounded ring, gap errors) and answers Presence with `channel_id`/`seq`; the Rust `wsh-server` does the same (`rust-v0.2.0`+; fixed 256 KiB ring) |
@@ -2429,7 +2471,7 @@ than left to be found.
2429
2471
  | `authorized_keys` options (#122): `restrict`, `permit-*`, `no-pty`, `command=`, `max-sessions=` | `auth.authorizedKeys` lines with options on `createWshServer` / `createMemoryHost`; `parseAuthorizedKeyEntries()` | `wsh-server` reads `~/.wsh/authorized_keys` (then `~/.ssh/authorized_keys`) | **Same rules and the same vectors on both hosts** (`spec/key-options.vectors.json`, run by the JS suite and a Rust test); an option that is not understood keeps the key out, on both. See [Authorized-key options](#authorized-key-options-122) for the per-host column |
2430
2472
  | Per-key capabilities and expiry (#122): `capabilities="..."`, `expires="..."`; `authorize()` may return a set | every entry the host has: `Open` kinds, `FileOp` read vs write, gateway TCP/UDP/unix/endpoint open and listen, MCP discovery and calls, targets, rpc channels, relay; refusals through `onRefused` (`not-permitted`, `key-expired`) | the same, except **no endpoints and no targets** (`endpoint:` / `target:` parse and grant nothing; such requests are refused); refusals are logged, there is no callback; no `authorize` | **Same grammar, same vectors, same refusal codes on both hosts**; default-deny only for a key whose line has `capabilities`. Neither covers sessions already open, see [Security model](#security-model). The notation is written in `spec/capabilities.md` and its vectors (`spec/capabilities.vectors.json`, `version` 1) ship in the npm package and are run by both; the Rust server's subset is stated by refusal: a key line with an `objects:` capability is refused at load (`unknown-capability`) |
2431
2473
  | A session over a caller-supplied duplex (#220): `serveWshOverDuplex`, `connectWshOverDuplex` from `@johnhenry/wsh/duplex` | exported, browser-safe; sealed by default | none: the Rust server and client dial a WebSocket, TLS or a pipe relay (a pipe relay carries the same bytes) | **Unified on the wire** (nothing new); the binding is the JS implementation's |
2432
- | `permits(capabilities, request)`, `@johnhenry/wsh/identity` (fingerprint, pod id, OpenSSH line, `authorized_keys` line builder), the `GATEWAY_FAIL` table, `serveMcpOverDuplex`, `createDuplexPeer({ who, permit })` (#220) | exported pure functions and seams of the JS package, browser-safe | none: the Rust server and CLI export no library function of these; the Rust server sends the same `GatewayFail` numbers, with `5` meaning "gateway disabled" where the Node gateway sends it for a timeout | **Notation unified by vectors**; the functions are the JS implementation's and are not a wire feature |
2474
+ | `permits(capabilities, request)`, `@johnhenry/wsh/identity` (fingerprint, pod id, OpenSSH line, `authorized_keys` line builder), the `GATEWAY_FAIL` table, `serveMcpOverDuplex`, `createDuplexPeer({ who, permit })` (#220) | exported pure functions and seams of the JS package, browser-safe | none: the Rust server and CLI export no library function of these; the Rust server sends the same `GatewayFail` numbers, with `5` meaning "gateway disabled"; the Node gateway sends `8` for a timeout (older Node gateways sent `5`, so a reader still takes a `5` as "disabled, or a timeout from an older Node gateway") | **Notation unified by vectors**; the functions are the JS implementation's and are not a wire feature |
2433
2475
  | Session recording/replay | `SessionRecorder`/`SessionPlayer` (asciicast-v2-shaped JSON) | none | **JS-only** -- no current Rust consumer needs playback; the vocabulary is asciicast v2's, so a Rust port could share it |
2434
2476
  | Self-signed cert pinning | `serverCertificateHashes` (WebTransport option) | `--cert-hash <sha256>` (repeatable) and `ConnectConfig.cert_hash`/`cert_hashes`, with the same rules (SHA-256, ECDSA P-256, at most 14 days); `wsh-server` prints its certificate hash at start-up. Without a pin the certificate is validated against the system trust store; `--insecure-skip-cert-verification` is the development-only opt-out | **Not a wire concept**; a default changed in the Rust client, see the CHANGELOG |
2435
2477
 
@@ -2486,7 +2528,7 @@ plus one `SHA256SUMS` file covering every archive in the release. These
2486
2528
  names are a stable contract other repos (clawser) pin and download by --
2487
2529
  do not change them without coordinating downstream.
2488
2530
 
2489
- `wsh --version` and `wsh-server --version` print the workspace version the binary was built from (`wsh 0.18.0`), which is the
2531
+ `wsh --version` and `wsh-server --version` print the workspace version the binary was built from (`wsh 0.19.0`), which is the
2490
2532
  number in the `rust-vX.Y.Z` tag. Binaries of `rust-v0.9.0` to `rust-v0.10.0` printed a fixed `0.1.0`, so against one of those the
2491
2533
  version cannot be read from the binary (look for a flag in `wsh --help` instead).
2492
2534
 
@@ -2601,7 +2643,9 @@ out explicitly below rather than left to be discovered.
2601
2643
  bounds, a visible Stop) and what it cannot make safe (a tool does whatever its `execute` does with the user's session; results may carry
2602
2644
  third-party text and are untrusted to the MCP client; the dialog and the indicator belong to the page and are not a defence against code
2603
2645
  already in it; a fresh host key per page load means no pin outlives it unless `hostKeyStore` is given) are stated in
2604
- [A page as a host](#a-page-as-a-host-johnhenrywshpage-190).
2646
+ [A page as a host](#a-page-as-a-host-johnhenrywshpage-190). The **dial-out form** (`connect`, off unless written) makes the page dial an endpoint of the embedder's choosing:
2647
+ the page does not authenticate that endpoint (the operator pins the page's host key, the page checks keys), the endpoint learns the host key and the stated features before
2648
+ any login, and the page redials it while the host is open; the URL is not logged. The key login, sealing, approval, indicator and Stop are unchanged.
2605
2649
  - **Objects and MCP over a transport that is not wsh (`createDuplexPeer`, `serveMcpOverDuplex`, #220) are only as authenticated as that transport.** The
2606
2650
  identity they hand to `authorize(who, op)`, a prompt and `onCall` is whatever the adapter gave (`who`, `permit`, `permits`): `fingerprint` and `podId`
2607
2651
  are checked to agree, nothing else is verified, and the messages carry no proof of either. They bound what they receive (message size, requests in
@@ -2611,7 +2655,7 @@ out explicitly below rather than left to be discovered.
2611
2655
  - **`wsh-objects` (`@johnhenry/wsh/objects`, #190) lets a key read, call and set the paths an allow-list names on the roots a host names, and nothing else.** An allow-list of paths means what it says
2612
2656
  only because nothing but cloneable values crosses (no handles in `values` mode; on a root that opted in to [handles](#handles), a handle is judged by the path that produced it and never widens it, and nodes need their own opt-in; an event subscription through a handle needs the producing path's own `allow.on` entry and ends with the handle); what it cannot make safe is stated in
2613
2657
  [Remote objects](#remote-objects-johnhenrywshobjects-190): a getter or a setter on an allowed path runs, a called function does whatever it does with the page's authority, a wide pattern means its width, and a
2614
- few paths (`document.cookie`, storage, `fetch`, ...) need an entry that names them. The generated types (#219) are advisory text: the host's type map is host-authored text that is checked, bounded and never evaluated (see [Typed remotes](#typed-remotes-219)), and the file says only what the fetching key may do. The MCP face for named paths (#219) is the allow-list **plus** a list of the paths that are tools, **plus** the WebMCP bridge's approval for any tool not marked read-only: a tool needs the key's `mcp:TOOL` and `objects:ROOT:OP`, its arguments are validated before the person is asked, its results are labelled untrusted, and it makes no handle, event or callback; a called function still does whatever it does with the page's authority. Object access is off on every host unless `exposeObjects` or `createPageHost({ expose })` is written, and `rpc:wsh-objects` is the key capability that gates it.
2658
+ few paths (`document.cookie`, storage, `fetch`, ...) need an entry that names them. A callback that returns a value (`(callback:returns)`) is not a way for the far side to call into the page more widely, but it is a way for the far side to make the page wait: that wait is bounded by the host (`callbackReturnTimeoutMs`, at most 30 s, and `maxPendingCallbackReturns` waiting calls per channel), and nothing the far side answers is more than plain data; it does not protect a page whose own code trusts the answer. The generated types (#219) are advisory text: the host's type map is host-authored text that is checked, bounded and never evaluated (see [Typed remotes](#typed-remotes-219)), and the file says only what the fetching key may do. The MCP face for named paths (#219) is the allow-list **plus** a list of the paths that are tools, **plus** the WebMCP bridge's approval for any tool not marked read-only: a tool needs the key's `mcp:TOOL` and `objects:ROOT:OP`, its arguments are validated before the person is asked, its results are labelled untrusted, and it makes no handle, event or callback; a called function still does whatever it does with the page's authority. Object access is off on every host unless `exposeObjects` or `createPageHost({ expose })` is written, and `rpc:wsh-objects` is the key capability that gates it. The Rust client (`wsh objects`, `wsh_client::objects`) is only as safe as the host it speaks to: a callback it passes lets the host's code push plain values at the process (bounded by its own queue and the host's rate and size limits; they are text from the host and are escaped in `wsh objects session` output, never interpreted), a subscription through a handle lives only as long as the handle, and `types` prints text the host wrote. None of it widens what the host's allow-lists and the key's capabilities allow.
2615
2659
  - **`wsh-mcp` runs as a client with your key (#127).** It reads a private key file you point it at (no passphrase support: protect the
2616
2660
  file, `0600`), logs in as you and hands the MCP client everything the host's `mcp` channel serves; whatever the MCP client (or the
2617
2661
  model behind it) asks of those tools is done as you. It does not pin the host unless you pass `--host-key` (it warns once on stderr),
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@johnhenry/wsh",
3
- "version": "0.51.0",
3
+ "version": "0.52.0",
4
4
  "description": "Web Shell \u2014 browser-native remote command execution over WebTransport and WebSocket with Ed25519 authentication",
5
5
  "type": "module",
6
6
  "main": "./src/index.mjs",
@@ -0,0 +1,14 @@
1
+ {
2
+ "version": 1,
3
+ "description": "The codes of GatewayFail (#223): the number, its name, and who sends it. Code 5 is GATEWAY_DISABLED (what spec/wsh-v1.yaml says and what the Rust wsh-server sends). A Node gateway older than the release that introduced 8 sent 5 for a timeout, so a reader treats a 5 as 'disabled, or a timeout from an older Node gateway'. TIMEOUT is 8. A code is never reused and a reader that gets a number it does not know says so rather than guessing.",
4
+ "codes": [
5
+ { "code": 1, "name": "CONNECTION_REFUSED", "sentBy": ["node", "rust"] },
6
+ { "code": 2, "name": "HOST_UNREACHABLE", "sentBy": ["node", "rust"] },
7
+ { "code": 3, "name": "DNS_FAILED", "sentBy": ["node"] },
8
+ { "code": 4, "name": "POLICY_DENIED", "sentBy": ["node", "rust"] },
9
+ { "code": 5, "name": "GATEWAY_DISABLED", "alsoSentAs": ["TIMEOUT"], "sentBy": ["rust", "node-before-timeout-8"] },
10
+ { "code": 6, "name": "CLOSED", "sentBy": ["node"] },
11
+ { "code": 7, "name": "QUEUE_FULL", "sentBy": ["node", "rust"] },
12
+ { "code": 8, "name": "TIMEOUT", "sentBy": ["node"] }
13
+ ]
14
+ }
package/spec/objects.md CHANGED
@@ -1,6 +1,6 @@
1
1
  # The `wsh-objects` protocol (remote objects)
2
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
3
+ Status: describes what `@johnhenry/wsh/objects` (`src/objects-core.mjs`, `src/objects.mjs`) serves and speaks as of 0.51.0, and what the Rust client
4
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
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
6
 
@@ -26,18 +26,28 @@ Every `params` is an object. A request names where it starts: `root: "window"` (
26
26
 
27
27
  | method | params | result |
28
28
  |---|---|---|
29
- | `roots` | `{}` | `{ roots: [name…], features: [string…] }` |
29
+ | `roots` | `{ features?: [string…] }` | `{ roots: [name…], features: [string…] }` |
30
30
  | `resolve` | `{ root \| handle, ops: [op…] }` | a **wire value** (section 3) |
31
31
  | `set` | `{ root \| handle, path: [seg…], value }` | `{ ok: true }` |
32
32
  | `describe` | `{ root \| handle, path?: [seg…] }` | `{ type, keys: [{ key, type, own }…], truncated? }` |
33
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 }` |
34
+ | `subscribe` | `{ id, root \| handle, path?: [seg…], type, fields?: [name…] }` | `{ ok: true }` |
35
35
  | `unsubscribe` | `{ id }` | `{ ok: true, dropped }` |
36
36
  | `release` | `{ handle }` | `{ ok: true }` |
37
37
  | `releaseCallback` | `{ id }` | `{ ok: true }` |
38
+ | `callbackResult` | `{ rid, value? \| error?: true }` | `{ ok }` (peer to host, section 6) |
39
+ | `types` | `{ root }` | `{ version, root, ops, allow, eventFields, types, handles }`: plain data |
38
40
 
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
+ `roots` lists only the roots the key may use (`objects:ROOT[:OP]`). `features` is what the host supports: `events`, `callbacks`, `callback-returns` (only when an
42
+ allow-list entry lets a callback return a value), `types` and (when a root opted in) `handles` and `handle-events`. A host that says nothing (before 0.48.0) supports
43
+ none of them; a host before 0.51.0 does not say `types` or `handle-events`; a peer must not use a feature the host did not state. A peer says what it can do in the
44
+ optional `features` of its `roots` request: `callback-returns` means it answers a callback that asks for a return value (section 6). A host that predates the field
45
+ ignores it.
46
+
47
+ **`types`** answers what this key may do on one root: `ops` (the operations among `get`, `call`, `set`, `on` the key holds on it), `allow` (the host's allow-list
48
+ entries for the root, by operation, only for those operations; entries are written with the root first, `window.app.cart.add`), `eventFields` (the extra event
49
+ fields of the types the key may listen to), `types` (the host's type map, `{ path: { value?, args?, result?, data? } }`: host-authored type text, never to be
50
+ evaluated), `handles` (whether the root opted in). Every string in it is the host's text: untrusted.
41
51
 
42
52
  **`resolve`** walks a whole chain in one request. `ops` is up to 32 operations, each an object with exactly one of:
43
53
 
@@ -57,7 +67,9 @@ number, at most the host's `maxDepth`, 8) and `maxBytes` bound it.
57
67
  **`subscribe`** listens to an event source named by an `allow.on` entry `path@type`: the object at `path` must have `addEventListener` /
58
68
  `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
69
  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.
70
+ does not offer is `not-allowed`. A subscription through a handle (`handle` in place of `root`, only if `features` has `handle-events`) is judged as a path subscription
71
+ for the path that produced the handle extended by `path` (its own `allow.on` entry naming the type, the key's `objects:ROOT:on`, `authorize`) and ends with the
72
+ handle: `release`, the session ending and a revoke end it. A host before 0.51.0 takes a `root` only.
61
73
 
62
74
  ## 3. Wire values
63
75
 
@@ -125,6 +137,18 @@ copies its arguments as plain data, queues a `callback` notification and returns
125
137
  queue is full are dropped and counted (`dropped`, told with the next delivered call). There are at most 16 callbacks per channel
126
138
  (`maxCallbacks`). `releaseCallback` kills a stub. `features` has `callbacks`.
127
139
 
140
+ **Return values (optional, off unless the host says so).** The allow-list entry is `(callback)` for a one-way stub, `(callback:returns)` when every function it takes
141
+ may return a value, `(callback:returns=I,J)` for the functions at those argument positions only (0 to 99). Such a stub returns a promise to the page's code, never
142
+ blocks, and the host settles it at the latest `callbackReturnTimeoutMs` (default 2000, at most 30000) after the call: with the value, or with `undefined` in every
143
+ other case (timeout, an error in the peer's function, a value that is not plain data or is over `maxCallbackResultBytes` (16384), a call dropped by the rate or size
144
+ bound, a full table of waiting calls (`maxPendingCallbackReturns`, default 8, at most 64: such a call is not sent), a released callback, the end of the channel).
145
+ A host asks only a peer that listed `callback-returns` in its `roots` request, and says it supports this in `features` (`callback-returns`). The `callback`
146
+ notification then has one more field, `rid` (a whole number from 1, per channel): `callback { id, seq, args, dropped?, rid? }`. The peer answers once with the request
147
+ `callbackResult { rid, value }` (`value` plain data, left out for `undefined`) or `callbackResult { rid, error: true }` (an error, a function, a handle, anything that
148
+ is not plain data: the text of an error is never sent), result `{ ok: true }`, or `{ ok: false }` for a `rid` nobody waits for (late, unknown or already answered);
149
+ the host counts such an answer against `maxRequestsPerSecond` and ignores it. A peer that does not answer costs the page the timeout, once per call; a host never has
150
+ more than `maxPendingCallbackReturns` calls waiting. In the `types` answer the entry is told as `(callback)`.
151
+
128
152
  ## 7. Notifications (host to peer)
129
153
 
130
154
  - `event { id, seq, data, dropped? }`: `id` is the subscription's, `seq` counts the delivered events of that subscription from 1. `data` is plain: for
@@ -170,7 +194,19 @@ The key's capability is asked again for every operation (an expiry holds at call
170
194
 
171
195
  ## 11. What the released peers do
172
196
 
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`.
197
+ - JavaScript (`@johnhenry/wsh` 0.46.0 to 0.51.0): the reference described above. 0.46.0 and 0.47.0 hosts have no `features` in `roots`, no events, handles or
198
+ callbacks; a peer sees an empty `features`. 0.50.0 and earlier hosts do not state `types` or `handle-events`.
199
+ - Rust client (`wsh_client::objects`, `wsh objects`): `rust-v0.18.0` speaks values, events by path and handles. `rust-v0.19.0` also speaks callbacks, events
200
+ through a handle and `types`, each only to a host that states it (`callbacks`, `handle-events`, `types`); against an older host they are refused locally, by name, and
201
+ nothing is sent. Rust released before the client (`rust-v0.17.1` and earlier) has no objects client at all.
202
+ - `callback-returns` (callback return values, JS hosts only): a 0.51.0 client, and the Rust client, never list `callback-returns` in their `roots` request, so a host that
203
+ states it never asks them for an answer: the page gets `undefined` at once and the callback is delivered one-way. A 0.51.0 host ignores the `features` of a `roots` request.
175
204
  - 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.
205
+ fails closed). **This is a decision, not a gap to close.** `wsh-objects` exists to reach a *live object graph* by path (a page's `window`, a worker's `self`, a
206
+ Node object), under allow-lists written over that graph's names; a Rust server has no such graph to expose, and anything it could name (its configuration, its
207
+ sessions, its counters) would be a fixed set of paths written in Rust, which is what a typed rpc channel is for. The Rust server already offers one
208
+ (`wsh-host`, `wsh mcp --channel wsh-host`), with its methods, bounds and `rpc:` capability checked in Rust rather than reconstructed as path rules over a
209
+ dynamic graph. A second, path-addressed way to read the same few fields would add a surface (allow-list syntax, `needs-listing` names, handles, callbacks that
210
+ call back into the server's own tasks) with nothing to protect it that the typed channel does not already have. So the server does not serve `wsh-objects`, and
211
+ a key line that asks for `objects:` capabilities stays refused rather than accepted and ignored. What would change this: a Rust host that embeds a scripting
212
+ runtime or another real object graph (none is planned).
package/spec/wsh-v1.yaml CHANGED
@@ -1273,15 +1273,18 @@ 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, 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).
1276
+ 4=POLICY_DENIED, 5=GATEWAY_DISABLED, 6=CLOSED, 7=QUEUE_FULL,
1277
+ 8=TIMEOUT. A code is never reused for something else.
1278
+ COMPATIBILITY: Node gateways older than the release that
1279
+ introduced 8 (the @johnhenry/wsh/server gateway and the page and
1280
+ memory hosts) sent 5 for a timeout, and a released peer still
1281
+ does. A reader therefore treats 5 as "the gateway is disabled,
1282
+ or a timeout from an older Node gateway" and says so; it never
1283
+ assumes a 5 is only one of the two. Senders: the Rust wsh-server
1284
+ sends 5 for a disabled gateway and 7 for a full queue; the Node
1285
+ gateway sends 6, 7 and 8. The table is exported as data from
1286
+ @johnhenry/wsh (GATEWAY_FAIL_TABLE) and as vectors in
1287
+ spec/gateway-fail.vectors.json.
1285
1288
  message:
1286
1289
  type: string
1287
1290
  required: true
package/src/duplex.mjs CHANGED
@@ -124,7 +124,8 @@ export function createDuplexSocket({ send, close, maxMessageBytes = DUPLEX_DEFAU
124
124
  if (!bytes) { finish(1003, 'a message that is not bytes'); return; }
125
125
  if (bytes.byteLength > maxMessageBytes) { finish(1009, 'a message larger than maxMessageBytes'); return; }
126
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);
127
+ // A copy that owns its memory: `Buffer.prototype.slice` (what the `ws` package hands over) returns a view of the same pool, whose `.buffer` is not these bytes.
128
+ incoming.push(new Uint8Array(bytes).buffer);
128
129
  queueMicrotask(flush); // in order, after `open`, once something listens
129
130
  },
130
131
  /** The duplex ended on its own (the peer left, the channel closed): the socket closes, `close` is not called back. */
@@ -15,16 +15,20 @@ import {
15
15
  } from './messages.mjs';
16
16
  import { GatewayChannel, GATEWAY_CREDIT_FEATURE } from './gateway-channel.mjs';
17
17
  import { UdpFlow, decodeDatagram } from './gateway-datagram.mjs';
18
+ import { GATEWAY_FAIL_FIVE_NOTE } from './gateway-errors.mjs';
18
19
 
19
20
  const ID_BASE = 0x40000000;
20
21
  const ID_LIMIT = 0xffffffff;
21
22
  const DEFAULT_TIMEOUT_MS = 30_000;
22
23
  const CLIENT_GRACE_MS = 5_000;
23
24
 
24
- /** An Error from a GatewayFail / ListenFail: `.code` is the GatewayFail code (4 = refused by policy), `.reason` the host's text. */
25
+ /**
26
+ * An Error from a GatewayFail / ListenFail: `.code` is the GatewayFail code (4 = refused by policy, 8 = timed out). A `5` is "the gateway is
27
+ * disabled, or a timeout from an older Node gateway" and the message says both (the host's own words come first).
28
+ */
25
29
  export class GatewayError extends Error {
26
30
  constructor(message, code) {
27
- super(message);
31
+ super(code === 5 ? `${message} (${GATEWAY_FAIL_FIVE_NOTE})` : message);
28
32
  this.name = 'GatewayError';
29
33
  this.code = code;
30
34
  }
@@ -5,26 +5,33 @@
5
5
  * decodes them (it keeps a copy by hand: it can import this one instead, the names and numbers are the same).
6
6
  *
7
7
  * The table is a contract: a code is never reused for something else and a number is never renumbered. A new code is added at the end.
8
+ * One exception was made, once (#223): the Node gateway used to send `5` for a timeout while the spec and the Rust `wsh-server` use `5` for
9
+ * "gateway disabled". `5` is now `GATEWAY_DISABLED` everywhere and `TIMEOUT` is `8`. A reader keeps accepting a `5` as "disabled, or a
10
+ * timeout from an older Node gateway", because a released Node peer still sends it.
8
11
  */
9
12
 
10
13
  /** Wire codes of `GatewayFail`, by name. */
11
14
  export const GATEWAY_FAIL = Object.freeze({
12
- CONNECTION_REFUSED: 1, HOST_UNREACHABLE: 2, DNS_FAILED: 3, POLICY_DENIED: 4, TIMEOUT: 5, CLOSED: 6, QUEUE_FULL: 7,
15
+ CONNECTION_REFUSED: 1, HOST_UNREACHABLE: 2, DNS_FAILED: 3, POLICY_DENIED: 4, GATEWAY_DISABLED: 5, CLOSED: 6, QUEUE_FULL: 7, TIMEOUT: 8,
13
16
  });
14
17
 
18
+ /** What a reader says about a `5`: it is what the Rust server sends when its gateway is off, and what a Node gateway older than the one that sends `TIMEOUT` (8) sent for a timeout. */
19
+ export const GATEWAY_FAIL_FIVE_NOTE = 'code 5: the gateway is disabled, or a timeout from an older Node gateway';
20
+
15
21
  /**
16
- * The same codes with their meaning. `alsoSentAs` lists a second name a different implementation gives the same number: the Rust
17
- * `wsh-server` sends `5` for "gateway disabled" (and `spec/wsh-v1.yaml` lists `5=GATEWAY_DISABLED`), where the Node gateway sends it for a
18
- * timeout. A client that reads `5` therefore should say "timed out or disabled" rather than only one of the two.
22
+ * The same codes with their meaning. `alsoSentAs` lists a second name a different (or older) implementation gives the same number: a Node
23
+ * gateway older than the release that introduced `TIMEOUT` = 8 sent `5` for a timeout. A client that reads `5` therefore says "disabled,
24
+ * or a timeout from an older Node gateway" rather than only one of the two.
19
25
  */
20
26
  export const GATEWAY_FAIL_TABLE = Object.freeze([
21
27
  Object.freeze({ name: 'CONNECTION_REFUSED', code: 1, meaning: 'The destination actively refused the connection (nothing listens there).' }),
22
28
  Object.freeze({ name: 'HOST_UNREACHABLE', code: 2, meaning: 'The destination could not be reached on the network (no route, connect failed, socket error).' }),
23
29
  Object.freeze({ name: 'DNS_FAILED', code: 3, meaning: 'The name did not resolve, or is not a valid name.' }),
24
30
  Object.freeze({ name: 'POLICY_DENIED', code: 4, meaning: 'The host refused by policy: the key lacks the capability, the address is not allowed, the endpoint or target does not exist or is not for this caller, or the request was malformed or reused an id.' }),
25
- Object.freeze({ name: 'TIMEOUT', code: 5, alsoSentAs: Object.freeze(['GATEWAY_DISABLED']), meaning: 'The host did not finish in time. The Rust wsh-server sends this number when its gateway is disabled.' }),
31
+ Object.freeze({ name: 'GATEWAY_DISABLED', code: 5, alsoSentAs: Object.freeze(['TIMEOUT']), meaning: 'The host has its gateway disabled (the Rust wsh-server sends this). A Node gateway older than the one that sends TIMEOUT (8) sent a 5 for a timeout, so a 5 can also be a timeout from an older Node gateway.' }),
26
32
  Object.freeze({ name: 'CLOSED', code: 6, meaning: 'The gateway connection was closed before the operation finished.' }),
27
33
  Object.freeze({ name: 'QUEUE_FULL', code: 7, meaning: 'The host holds too many gateway connections or too much unsent data, and takes no more for now.' }),
34
+ Object.freeze({ name: 'TIMEOUT', code: 8, meaning: 'The host did not finish in time (a connect or a name lookup timed out).' }),
28
35
  ]);
29
36
 
30
37
  /**
package/src/index.d.ts CHANGED
@@ -2248,14 +2248,21 @@ export interface WshUdpFlow extends WshGatewayDuplex {
2248
2248
  /** Feature string for UDP over WebTransport datagrams. */
2249
2249
  export const GATEWAY_DATAGRAM_FEATURE: 'gateway-datagram';
2250
2250
 
2251
- /** A GatewayFail / ListenFail as an Error: `code` 4 = refused by the host's policy, 7 = too many connections, 1 = refused by the target. */
2251
+ /**
2252
+ * A GatewayFail / ListenFail as an Error: `code` 4 = refused by the host's policy, 7 = too many connections, 1 = refused by the target,
2253
+ * 8 = timed out. A `5` is "the gateway is disabled, or a timeout from an older Node gateway", and the message says so.
2254
+ */
2252
2255
  export class GatewayError extends Error { code: number }
2253
2256
 
2254
- /** The codes of `GatewayFail` by name (the one table the Node gateway, the page host and netway share). Frozen; a number is never reused. */
2257
+ /**
2258
+ * The codes of `GatewayFail` by name (the one table the Node gateway, the page host and netway share). Frozen. `5` is `GATEWAY_DISABLED` (the
2259
+ * spec, the Rust server); `TIMEOUT` is `8`. A Node gateway older than the one that sends `8` sent `5` for a timeout, so keep reading a `5` as
2260
+ * "disabled, or a timeout from an older Node gateway".
2261
+ */
2255
2262
  export const GATEWAY_FAIL: Readonly<{
2256
- CONNECTION_REFUSED: 1; HOST_UNREACHABLE: 2; DNS_FAILED: 3; POLICY_DENIED: 4; TIMEOUT: 5; CLOSED: 6; QUEUE_FULL: 7;
2263
+ CONNECTION_REFUSED: 1; HOST_UNREACHABLE: 2; DNS_FAILED: 3; POLICY_DENIED: 4; GATEWAY_DISABLED: 5; CLOSED: 6; QUEUE_FULL: 7; TIMEOUT: 8;
2257
2264
  }>;
2258
- /** The same codes with their meaning; `alsoSentAs` is a second name another implementation gives the number (the Rust server sends `5` for a disabled gateway). */
2265
+ /** The same codes with their meaning; `alsoSentAs` is a second name another (or an older) implementation gives the number (`5` is also what an older Node gateway sent for a timeout). */
2259
2266
  export const GATEWAY_FAIL_TABLE: ReadonlyArray<Readonly<{ name: keyof typeof GATEWAY_FAIL; code: number; meaning: string; alsoSentAs?: readonly string[] }>>;
2260
2267
  /** Codes a client gives its own `GatewayError` when it never asked the host (not on the wire): `UNSUPPORTED` is `0`, a feature the host did not advertise. */
2261
2268
  export const GATEWAY_FAIL_LOCAL: Readonly<{ UNSUPPORTED: 0 }>;
@@ -74,6 +74,15 @@ export const OBJECTS_DEFAULT_LIMITS = Object.freeze({
74
74
  maxCallbacksPerSecond: 20,
75
75
  /** Bytes of the arguments of one callback call; a bigger one is dropped and counted. */
76
76
  maxCallbackBytes: 16 * 1024,
77
+ /**
78
+ * Callbacks whose entry says `(callback:returns)`: the longest the page's stub waits for the far side's answer, from the call (queueing included). After it the
79
+ * promise the stub returned is settled with `undefined`. At most 30000.
80
+ */
81
+ callbackReturnTimeoutMs: 2000,
82
+ /** Calls of returning callbacks waiting for an answer, per channel; a call beyond it is dropped and counted, never sent. At most 64. */
83
+ maxPendingCallbackReturns: 8,
84
+ /** Bytes of the value a far-side callback answers with; a bigger one (or one that is not plain data) becomes `undefined` for the page and is counted. */
85
+ maxCallbackResultBytes: 16 * 1024,
77
86
  /** Event subscriptions per channel. */
78
87
  maxSubscriptions: 16,
79
88
  /** Events delivered per second, per subscription; the rest are dropped and counted. */
@@ -104,6 +113,10 @@ export const NEEDS_LISTING = Object.freeze([
104
113
 
105
114
  const KEY_MAX = 256;
106
115
  const CALLBACK_SUFFIX = '(callback)';
116
+ /** The ceilings of the bounds a host may set for callbacks that return a value: the page's wait is bounded whatever the host asks for. */
117
+ const RETURN_CEILINGS = Object.freeze({ callbackReturnTimeoutMs: 30_000, maxPendingCallbackReturns: 64 });
118
+ /** The end of a call entry that accepts callbacks: `(callback)` one-way, `(callback:returns)` every function may answer, `(callback:returns=0,2)` the functions at those argument positions may. */
119
+ const CALLBACK_NOTATION = /\(callback(?::returns(?:=(\d{1,2}(?:,\d{1,2})*))?)?\)$/;
107
120
  const B64URL = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_';
108
121
  /** On a root with handles: members that lead from a node back up to the document or window graph. Refused until an allow-list entry names them, nodes opt-in or not. */
109
122
  const GRAPH_MEMBERS = Object.freeze(['ownerDocument', 'defaultView', 'parentNode', 'parentElement', 'getRootNode', 'contentWindow', 'contentDocument', 'self', 'window', 'top', 'parent', 'frames', 'opener', 'globalThis']);
@@ -125,15 +138,19 @@ function compileList(list, kind) {
125
138
  return list.map((original) => {
126
139
  if (typeof original !== 'string' || original === '') throw new TypeError(`exposeObjects: allow.${kind} entries must be non-empty strings`);
127
140
  // A call entry that ends in `(callback)` says the call accepts functions as arguments (they arrive as stubs the page can call, one-way).
141
+ // `(callback:returns)` (every function it takes may answer) and `(callback:returns=0,2)` (the functions at those argument positions) also let the stub return the far side's value.
128
142
  let entry = original;
129
143
  let callbacks = false;
130
- if (entry.endsWith(CALLBACK_SUFFIX)) {
144
+ let returns = null;
145
+ const notation = CALLBACK_NOTATION.exec(entry);
146
+ if (notation) {
131
147
  if (kind !== 'call') throw new TypeError(`exposeObjects: allow.${kind} entry ${JSON.stringify(original)}: only a call entry can accept callbacks`);
132
- entry = entry.slice(0, -CALLBACK_SUFFIX.length);
148
+ entry = entry.slice(0, notation.index);
133
149
  callbacks = true;
150
+ if (notation[0] !== CALLBACK_SUFFIX) returns = notation[1] === undefined ? true : new Set(notation[1].split(',').map(Number));
134
151
  }
135
- if (entry.includes(CALLBACK_SUFFIX)) throw new TypeError(`exposeObjects: allow.${kind} entry ${JSON.stringify(original)}: "(callback)" ends an entry`);
136
- const segs = Object.assign(entry.split('.'), { callbacks });
152
+ if (entry.includes('(callback')) throw new TypeError(`exposeObjects: allow.${kind} entry ${JSON.stringify(original)}: "(callback)", "(callback:returns)" or "(callback:returns=N,M)" ends an entry`);
153
+ const segs = Object.assign(entry.split('.'), { callbacks, returns });
137
154
  for (const s of segs) {
138
155
  if (s === '') throw new TypeError(`exposeObjects: allow.${kind} entry ${JSON.stringify(entry)} has an empty segment`);
139
156
  if (ALWAYS_REFUSED.has(s)) throw new TypeError(`exposeObjects: allow.${kind} entry ${JSON.stringify(entry)} names "${s}", which is never reachable`);
@@ -405,6 +422,7 @@ export function createObjectsServer(options = {}) {
405
422
  for (const [k, v] of Object.entries(limitOptions)) {
406
423
  if (!(k in OBJECTS_DEFAULT_LIMITS)) throw new TypeError(`exposeObjects: unknown limit ${JSON.stringify(k)} (${Object.keys(OBJECTS_DEFAULT_LIMITS).join(', ')})`);
407
424
  if (!Number.isSafeInteger(v) || v < 1) throw new TypeError(`exposeObjects: limits.${k} must be a positive integer`);
425
+ if (k in RETURN_CEILINGS && v > RETURN_CEILINGS[k]) throw new TypeError(`exposeObjects: limits.${k} is at most ${RETURN_CEILINGS[k]}: the page's wait for a callback's answer is bounded whatever the host asks for`);
408
426
  limits[k] = v;
409
427
  }
410
428
  // `on` entries are `path@type` (`'window.app.bus@ready'`): the source and the event type, both named exactly (no wildcard in either); each is compiled as a path with its type attached.
@@ -424,6 +442,9 @@ export function createObjectsServer(options = {}) {
424
442
  };
425
443
  const lists = { get: compileList(allow.get, 'get'), call: compileList(allow.call, 'call'), set: compileList(allow.set, 'set'), on: compileOn(allow.on) };
426
444
  const every = [...lists.get, ...lists.call, ...lists.set, ...lists.on];
445
+ // A callback that returns a value makes the page wait for the far side, so it needs a clock to cut the wait: this module reaches for no global.
446
+ const anyReturns = lists.call.some((p) => p.returns);
447
+ if (anyReturns && !timers) throw new TypeError('exposeObjects: an entry that says (callback:returns) needs timers ({ setTimeout, clearTimeout }): the page\'s wait for the far side\'s answer is bounded by a timer');
427
448
  // With handles, a wildcard in `call` or `set` lets a caller hold and reuse every object under it: the root says so (`wideEntries: true`) or lists the paths.
428
449
  for (const [name, mode] of handleRoots) {
429
450
  if (mode.wideEntries) continue;
@@ -564,7 +585,7 @@ export function createObjectsServer(options = {}) {
564
585
  const clean = fromWire(args, limits);
565
586
  const made = [];
566
587
  try {
567
- for (const [index, id] of spec) { const had = ctx.session.callbacks.has(id); const stub = makeCallback(ctx.session, id); if (!had) made.push(id); clean[index] = stub; }
588
+ for (const [index, id] of spec) { const had = ctx.session.callbacks.has(id); const stub = makeCallback(ctx.session, id, returnsAt(next, index)); if (!had) made.push(id); clean[index] = stub; }
568
589
  } catch (e) { for (const id of made) killCallback(ctx.session, id); throw e; }
569
590
  if (kind === 'call' && isTimerCallee(key) && typeof clean[0] === 'string') throw refuse('always-refused', `refused: ${key} with a string would evaluate it`);
570
591
  let fn;
@@ -778,10 +799,10 @@ export function createObjectsServer(options = {}) {
778
799
  session.pumping = true;
779
800
  try {
780
801
  while (session.queue.length && !session.closed) {
781
- const { sub, cb, data, dropped } = session.queue.shift();
782
- const message = cb ? { id: cb.id, seq: ++cb.seq, args: data, ...(dropped ? { dropped } : {}) } : { id: sub.id, seq: ++sub.seq, data, ...(dropped ? { dropped } : {}) };
802
+ const { sub, cb, data, dropped, rid } = session.queue.shift();
803
+ const message = cb ? { id: cb.id, seq: ++cb.seq, args: data, ...(dropped ? { dropped } : {}), ...(rid ? { rid } : {}) } : { id: sub.id, seq: ++sub.seq, data, ...(dropped ? { dropped } : {}) };
783
804
  // The write waits for the transport (credit): events and callback calls behind it queue, to `maxQueuedEvents`, and beyond that are dropped and counted.
784
- try { await session.peer.notify(cb ? 'callback' : 'event', message); } catch { /* the channel is going away */ }
805
+ try { await session.peer.notify(cb ? 'callback' : 'event', message); } catch { if (rid) finishReturn(session, rid, undefined, 'failed'); /* the channel is going away */ }
785
806
  }
786
807
  } finally { session.pumping = false; }
787
808
  }
@@ -791,14 +812,35 @@ export function createObjectsServer(options = {}) {
791
812
  // values (what cannot be cloned is null; never a handle), bounds them, queues a notification through the channel's credit, and returns undefined at once, so
792
813
  // the page cannot be made to wait for the far side and learns nothing of it. After the channel ends, or after a release, a call is a no-op that is counted.
793
814
 
794
- function makeCallback(session, id) {
795
- // The same function sent again (an id the channel already has) is the same stub.
815
+ //
816
+ // `(callback:returns)` (or `=N,M`, per argument position) is the one exception, and only where the host wrote it: the stub then returns a PROMISE, never a block. It is
817
+ // settled with the far side's return value if that arrives within `callbackReturnTimeoutMs` (counted from the call; 2 s, at most 30 s), as plain data within
818
+ // `maxCallbackResultBytes`, and with `undefined` in every other case: a timeout, an error on the far side (its text stays there), a result that is too big or is not plain
819
+ // data, a full table (`maxPendingCallbackReturns`), a call dropped by the rate or size bound, a dead channel, a released callback, and a far side that did not say it can
820
+ // answer (an older client): the page never waits on a peer that cannot answer. The answer comes as a `callbackResult` request for a request id the host gave, once.
821
+
822
+ /** Does an entry that matches `segs` let the function at argument `index` answer? (Any matching entry that says so: the allow-list is a union, as everywhere.) */
823
+ function returnsAt(segs, index) {
824
+ return lists.call.some((p) => p.callbacks && p.returns && matchPath(p, segs) && (p.returns === true || p.returns.has(index)));
825
+ }
826
+
827
+ function makeCallback(session, id, returns = false) {
828
+ // The same function sent again (an id the channel already has) is the same stub. A returning stub that is also sent to an entry that says only (callback) stops returning.
796
829
  const existing = session.callbacks.get(id);
797
- if (existing) return existing.stub;
830
+ if (existing) { if (!returns) existing.returns = false; return existing.stub; }
798
831
  if (session.callbacks.size >= limits.maxCallbacks) throw limitError('maxCallbacks', limits.maxCallbacks, 'too many callbacks on this channel: release some');
799
- const cb = { id, seq: 0, stamps: [], dropped: 0, dead: false, stub: null };
832
+ const cb = { id, seq: 0, stamps: [], dropped: 0, dead: false, stub: null, returns };
800
833
  cb.stub = function callback(...args) {
801
- try { deliverCallback(session, cb, args); } catch { cb.dropped++; }
834
+ if (!cb.returns) {
835
+ try { deliverCallback(session, cb, args, null); } catch { cb.dropped++; }
836
+ return undefined;
837
+ }
838
+ // Always a promise, settled at the latest `callbackReturnTimeoutMs` after this call, whatever the far side does.
839
+ return new Promise((resolve) => {
840
+ let waiting = false;
841
+ try { waiting = deliverCallback(session, cb, args, resolve); } catch { cb.dropped++; session.returnStats.dropped++; }
842
+ if (!waiting) resolve(undefined);
843
+ });
802
844
  };
803
845
  session.callbacks.set(id, cb);
804
846
  return cb.stub;
@@ -806,25 +848,57 @@ export function createObjectsServer(options = {}) {
806
848
 
807
849
  function killCallback(session, id) {
808
850
  const cb = session.callbacks.get(id);
809
- if (cb) { cb.dead = true; session.callbacks.delete(id); }
851
+ if (cb) {
852
+ cb.dead = true;
853
+ session.callbacks.delete(id);
854
+ for (const [rid, p] of [...session.pendingReturns]) if (p.cb === cb) finishReturn(session, rid, undefined, 'failed');
855
+ }
810
856
  return !!cb;
811
857
  }
812
858
 
813
- function deliverCallback(session, cb, args) {
814
- if (session.closed || cb.dead || guard?.()) { session.deadCalls++; return; }
859
+ /** Settle one waiting call (once) with `value`, and take its timer away. `outcome` is the counter it adds to. Returns whether anything was waiting. */
860
+ function finishReturn(session, rid, value, outcome) {
861
+ const p = session.pendingReturns.get(rid);
862
+ if (!p) return false;
863
+ session.pendingReturns.delete(rid);
864
+ if (p.timer !== null) timers?.clearTimeout(p.timer);
865
+ session.returnStats[outcome]++;
866
+ p.resolve(value);
867
+ return true;
868
+ }
869
+
870
+ /** The channel ended: nobody can answer any more. */
871
+ function finishAllReturns(session) {
872
+ for (const rid of [...session.pendingReturns.keys()]) finishReturn(session, rid, undefined, 'failed');
873
+ }
874
+
875
+ /** Returns whether a call is now waiting for an answer (then `resolve` is called later, by `finishReturn`); else the caller resolves `undefined` at once. */
876
+ function deliverCallback(session, cb, args, resolve) {
877
+ if (session.closed || cb.dead || guard?.()) { session.deadCalls++; return false; }
815
878
  const t = now();
816
879
  while (cb.stamps.length && t - cb.stamps[0] >= 1000) cb.stamps.shift();
880
+ const dropOne = () => { cb.dropped++; if (resolve) session.returnStats.dropped++; return false; };
817
881
  // Rate and room first, copy after: a dropped call costs a counter.
818
- if (cb.stamps.length >= limits.maxCallbacksPerSecond || session.queue.length >= limits.maxQueuedEvents) { cb.dropped++; return; }
882
+ if (cb.stamps.length >= limits.maxCallbacksPerSecond || session.queue.length >= limits.maxQueuedEvents) return dropOne();
883
+ // A call that would have to wait but has no room to: dropped, not sent (a far side cannot make the table grow).
884
+ const answerable = resolve !== null && session.clientReturns;
885
+ if (answerable && session.pendingReturns.size >= limits.maxPendingCallbackReturns) return dropOne();
819
886
  let copy;
820
887
  try {
821
888
  copy = args.slice(0, limits.maxArgs).map((a) => { const w = toWire(a, { maxDepth: 4, maxBytes: limits.maxCallbackBytes }); return 'v' in w ? w.v : null; });
822
889
  toWire(copy, { maxDepth: 6, maxBytes: limits.maxCallbackBytes });
823
- } catch { cb.dropped++; return; }
890
+ } catch { return dropOne(); }
824
891
  cb.stamps.push(t);
825
- session.queue.push({ cb, data: copy, dropped: cb.dropped });
892
+ let rid;
893
+ if (answerable) {
894
+ rid = session.nextRid++;
895
+ const timer = timers.setTimeout(() => { finishReturn(session, rid, undefined, 'timedOut'); }, limits.callbackReturnTimeoutMs);
896
+ session.pendingReturns.set(rid, { cb, resolve, timer });
897
+ }
898
+ session.queue.push({ cb, data: copy, dropped: cb.dropped, ...(rid ? { rid } : {}) });
826
899
  cb.dropped = 0;
827
900
  void pump(session);
901
+ return rid !== undefined;
828
902
  }
829
903
 
830
904
  async function releaseCallback(params, ctx) {
@@ -910,7 +984,11 @@ export function createObjectsServer(options = {}) {
910
984
  function attach(peer, { who } = {}) {
911
985
  if (typeof peer?.onRequest !== 'function') throw new TypeError('attach: the peer needs onRequest(method, handler)');
912
986
  const defaultWho = callerIdentity(who);
913
- const session = { peer, subs: new Map(), queue: [], pumping: false, closed: false, handles: new Map(), callbacks: new Map(), deadCalls: 0 };
987
+ const session = {
988
+ peer, subs: new Map(), queue: [], pumping: false, closed: false, handles: new Map(), callbacks: new Map(), deadCalls: 0,
989
+ // Callbacks that return a value: the calls waiting for an answer by request id, whether the far side said it answers, and what became of the calls.
990
+ pendingReturns: new Map(), nextRid: 1, clientReturns: false, returnStats: { answered: 0, timedOut: 0, failed: 0, refused: 0, dropped: 0 },
991
+ };
914
992
  // The end of the channel (the peer left, Stop, a navigation, a revoke) takes every listener out of the page's sources.
915
993
  const prior = peer.onClose;
916
994
  peer.onClose = (reason) => {
@@ -921,14 +999,29 @@ export function createObjectsServer(options = {}) {
921
999
  session.handles.clear(); // the end of the channel (leaving, Stop, navigation, revoke) releases every handle
922
1000
  for (const cb of session.callbacks.values()) cb.dead = true; // and kills every callback stub
923
1001
  session.callbacks.clear();
1002
+ finishAllReturns(session); // a page that is waiting for a far side that has gone is told `undefined` now, and its timers go
924
1003
  try { prior?.(reason); } catch { /* ignore */ }
925
1004
  };
926
1005
  const stamps = [];
927
- const method = (name, fn) => peer.onRequest(name, async (params, ctx = {}) => {
1006
+ const spendRequest = () => {
928
1007
  const t = now();
929
1008
  while (stamps.length && t - stamps[0] >= 1000) stamps.shift();
930
1009
  if (stamps.length >= limits.maxRequestsPerSecond) throw limitError('maxRequestsPerSecond', limits.maxRequestsPerSecond, 'too many requests in a second');
931
1010
  stamps.push(t);
1011
+ };
1012
+ // The far side's answer to a callback that returns a value. It completes a call the host is already waiting on (by a request id this channel gave, once), so it
1013
+ // takes nothing from the request rate; an answer nobody waits for does, and is the only way to spend it with no effect.
1014
+ peer.onRequest('callbackResult', async (params) => {
1015
+ if (params === null || typeof params !== 'object' || Array.isArray(params) || !Number.isSafeInteger(params.rid) || params.rid < 1) throw invalid('callbackResult needs { rid }');
1016
+ if (!session.pendingReturns.has(params.rid)) { spendRequest(); return { ok: false }; }
1017
+ if (params.error === true) { finishReturn(session, params.rid, undefined, 'failed'); return { ok: true }; }
1018
+ let value;
1019
+ try { value = params.value === undefined ? undefined : fromWire(params.value, { maxDepth: 4, maxBytes: limits.maxCallbackResultBytes }); } catch { finishReturn(session, params.rid, undefined, 'refused'); return { ok: true }; }
1020
+ finishReturn(session, params.rid, value, 'answered');
1021
+ return { ok: true };
1022
+ });
1023
+ const method = (name, fn) => peer.onRequest(name, async (params, ctx = {}) => {
1024
+ spendRequest();
932
1025
  // A value is kept under what the transport carries in one message, with room for the envelope.
933
1026
  const maxBytes = Math.min(limits.maxValueBytes, Math.max(1024, (peer.maxMessageBytes ?? Infinity) - 4096));
934
1027
  const call = { ...ctx, signal: ctx.signal, who: ctx.who === undefined || ctx.who === null ? defaultWho : callerIdentity(ctx.who), maxBytes, session };
@@ -937,10 +1030,14 @@ export function createObjectsServer(options = {}) {
937
1030
  });
938
1031
  // A key that may use only some roots is told of those only.
939
1032
  // The host also says what it supports (additive: an older client ignores it), so a client does not send a function to a host that would drop it, nor misread a handle.
940
- method('roots', async (_params, call) => ({
941
- roots: rootNames.filter((name) => keyMay(call, name, 'walk')),
942
- features: ['events', 'callbacks', 'types', ...(handleRoots.size ? ['handles', 'handle-events'] : [])],
943
- }));
1033
+ // A client that answers a callback says so here (`features: ['callback-returns']`): an older one does not, and a returning stub then never waits for it.
1034
+ method('roots', async (params, call) => {
1035
+ session.clientReturns = anyReturns && Array.isArray(params.features) && params.features.includes('callback-returns');
1036
+ return {
1037
+ roots: rootNames.filter((name) => keyMay(call, name, 'walk')),
1038
+ features: ['events', 'callbacks', ...(anyReturns ? ['callback-returns'] : []), 'types', ...(handleRoots.size ? ['handles', 'handle-events'] : [])],
1039
+ };
1040
+ });
944
1041
  // What this key may do on one root, as data a far side turns into a `.d.ts` (`describeRootTypes`): the allow-list entries of that root for the operations the key's
945
1042
  // capabilities grant, the host's type map for them, the event fields of the types it may subscribe to. Nothing of another root, and nothing that is not allowed.
946
1043
  method('types', async (params, call) => {
@@ -948,7 +1045,9 @@ export function createObjectsServer(options = {}) {
948
1045
  permitted(call, root, 'walk');
949
1046
  const ops = ['get', 'call', 'set', 'on'].filter((op) => keyMay(call, root, op));
950
1047
  const mine = (list) => (Array.isArray(list) ? list : []).filter((entry) => { const first = String(entry).split(/[.@]/, 1)[0]; return first === root || first === '*' || first === '**'; });
951
- const lists = Object.fromEntries(['get', 'call', 'set', 'on'].map((op) => [op, ops.includes(op) ? mine(allowStrings[op]) : []]));
1048
+ // An entry that lets a callback return is told as `(callback)`: a client that predates the notation parses only that, and the types do not describe a return.
1049
+ const told = (op, entry) => (op === 'call' ? String(entry).replace(CALLBACK_NOTATION, '(callback)') : entry);
1050
+ const lists = Object.fromEntries(['get', 'call', 'set', 'on'].map((op) => [op, ops.includes(op) ? mine(allowStrings[op]).map((e) => told(op, e)) : []]));
952
1051
  const typeMap = narrowTypes({ root, ops, allow: allowStrings, types: typesByRoot.get(root) ?? {} });
953
1052
  const offered = new Set(lists.on.map((entry) => entry.slice(entry.indexOf('@') + 1)));
954
1053
  const fields = Object.fromEntries(Object.entries(eventFields).filter(([type]) => type === '*' ? offered.size > 0 : offered.has(type)));
@@ -965,7 +1064,11 @@ export function createObjectsServer(options = {}) {
965
1064
  method('unsubscribe', unsubscribe);
966
1065
  method('release', releaseHandle);
967
1066
  method('releaseCallback', releaseCallback);
968
- return { limits, handleCount: () => session.handles.size, callbackCount: () => session.callbacks.size, deadCallbackCalls: () => session.deadCalls };
1067
+ return {
1068
+ limits, handleCount: () => session.handles.size, callbackCount: () => session.callbacks.size, deadCallbackCalls: () => session.deadCalls,
1069
+ /** What became of the calls of callbacks that return a value: `pending` now, and since the channel began `answered`, `timedOut`, `failed` (the far side's error, a write that failed, the channel ending, a release), `refused` (too big or not plain data) and `dropped` (the rate, the size, a full table). */
1070
+ callbackReturnStats: () => ({ pending: session.pendingReturns.size, ...session.returnStats }),
1071
+ };
969
1072
  }
970
1073
 
971
1074
  /**
@@ -1318,6 +1421,30 @@ export async function describe(ref, { signal } = {}) {
1318
1421
  try { return await state.session.peer.request('describe', { ...target(state), path: keys }, { signal }); } catch (e) { throw asObjectsError(e, state.session); }
1319
1422
  }
1320
1423
 
1424
+ /**
1425
+ * Answer a host that asked for a callback's return value: plain data within the bound, or an error mark (the text of an error never travels). Never throws: the host bounds
1426
+ * its own wait, so an answer that cannot be sent costs the page `undefined`, nothing more.
1427
+ */
1428
+ async function answerCallback(session, rid, threw, out, onCallbackError) {
1429
+ let body;
1430
+ try {
1431
+ if (threw) body = { rid, error: true };
1432
+ else {
1433
+ const value = await out;
1434
+ if (value === undefined) body = { rid };
1435
+ else if (typeof value === 'function' || value instanceof RemoteHandle) body = { rid, error: true };
1436
+ else {
1437
+ const w = toWire(value, { maxDepth: 4, maxBytes: OBJECTS_DEFAULT_LIMITS.maxValueBytes });
1438
+ body = 'v' in w ? { rid, value: w.v } : { rid, error: true };
1439
+ }
1440
+ }
1441
+ } catch (e) {
1442
+ try { onCallbackError?.(e); } catch { /* ours */ }
1443
+ body = { rid, error: true };
1444
+ }
1445
+ try { await session.peer.request('callbackResult', body); } catch { /* the channel is going away, or the host gave up */ }
1446
+ }
1447
+
1321
1448
  /**
1322
1449
  * The client half over any peer: asks for the roots and returns them as lazy references, `{ window }`.
1323
1450
  * @param {object} peer
@@ -1332,7 +1459,10 @@ export async function createObjectsClient(peer, { timeoutMs, onCallbackError, on
1332
1459
  const fn = session.callbacks.get(params?.id);
1333
1460
  if (!fn || !Array.isArray(params.args)) return;
1334
1461
  if (Number.isSafeInteger(params.dropped) && params.dropped > 0) { try { onCallbackDropped?.({ dropped: params.dropped, fn }); } catch { /* ours */ } }
1335
- try { fn(...params.args); } catch (e) { try { onCallbackError?.(e); } catch { /* ours */ } }
1462
+ let out; let threw = false;
1463
+ try { out = fn(...params.args); } catch (e) { threw = true; try { onCallbackError?.(e); } catch { /* ours */ } }
1464
+ // The host asked for the return value (`rid`: only a host whose entry says (callback:returns), and only because the roots request below said this side answers).
1465
+ if (Number.isSafeInteger(params.rid) && params.rid >= 1) void answerCallback(session, params.rid, threw, out, onCallbackError);
1336
1466
  });
1337
1467
  // An event the host delivers: to the listener that asked, in this process. A listener that throws is this side's business and goes to its `onError`: it never travels back.
1338
1468
  peer.onNotification?.('event', (params) => {
@@ -1345,7 +1475,8 @@ export async function createObjectsClient(peer, { timeoutMs, onCallbackError, on
1345
1475
  peer.onNotification?.('closing', (params) => { session.closing = typeof params?.reason === 'string' ? clip(params.reason, TEXT_MAX) : 'closing'; });
1346
1476
  let roots;
1347
1477
  try {
1348
- const answer = await peer.request('roots', {});
1478
+ // This side answers a callback's return value when a host asks for it: a host that predates the notation ignores the field, and one that has no such entry never asks.
1479
+ const answer = await peer.request('roots', { features: ['callback-returns'] });
1349
1480
  roots = answer?.roots;
1350
1481
  // What the host says it supports; a host that says nothing (before 0.48.0) supports none of the three.
1351
1482
  session.features = Array.isArray(answer?.features) ? answer.features.filter((f) => typeof f === 'string') : [];
@@ -79,7 +79,9 @@ function parseEntry(raw, op) {
79
79
  text = text.slice(0, at);
80
80
  if (!EVENT_TYPE.test(type)) throw bad(`allow.on entry ${JSON.stringify(raw.slice(0, 80))}: the event type is not a name`);
81
81
  }
82
- if (op === 'call' && text.endsWith('(callback)')) { callbacks = true; text = text.slice(0, -'(callback)'.length); }
82
+ // `(callback)`, and the notations that also let the far side's function return a value (`(callback:returns)`, `(callback:returns=0,2)`): the types do not describe a return.
83
+ const callbackEnd = op === 'call' ? /\(callback(?::returns(?:=\d{1,2}(?:,\d{1,2})*)?)?\)$/.exec(text) : null;
84
+ if (callbackEnd) { callbacks = true; text = text.slice(0, callbackEnd.index); }
83
85
  const segs = splitPath(text, `allow.${op} entry`);
84
86
  if (op === 'on' && segs.some((s) => s.includes('*'))) throw bad(`allow.on entry ${JSON.stringify(raw.slice(0, 80))}: an event source is named exactly`);
85
87
  return { segs, callbacks, type, text };
package/src/objects.d.ts CHANGED
@@ -124,6 +124,12 @@ export interface ObjectsLimits {
124
124
  maxCallbacksPerSecond: number;
125
125
  /** Bytes of the arguments of one callback call; a bigger one is dropped and counted. Default 16384. */
126
126
  maxCallbackBytes: number;
127
+ /** The longest the page's stub waits for a far-side function that returns (`(callback:returns)`), from the call; then its promise is settled with `undefined`. Default 2000, at most 30000. */
128
+ callbackReturnTimeoutMs: number;
129
+ /** Calls of returning callbacks waiting for an answer per channel; a call beyond it is dropped and counted, never sent. Default 8, at most 64. */
130
+ maxPendingCallbackReturns: number;
131
+ /** Bytes of the value a far-side callback answers with; a bigger one, or one that is not plain data, is `undefined` for the page. Default 16384. */
132
+ maxCallbackResultBytes: number;
127
133
  }
128
134
  export const OBJECTS_DEFAULT_LIMITS: Readonly<ObjectsLimits>;
129
135
 
@@ -133,7 +139,9 @@ export const NEEDS_LISTING: ReadonlyArray<readonly string[]>;
133
139
  /** Allow-lists by operation: path patterns from a root (`'window.document.title'`, `'window.app.**'`; `*` is one segment, `**` any number). `call` covers `construct`. Nothing is allowed by default. */
134
140
  export interface ObjectsAllow {
135
141
  get?: string[];
136
- // (`call` entries may end in `(callback)`: the call accepts functions as arguments, which reach the page as one-way stubs.)
142
+ // (`call` entries may end in `(callback)`: the call accepts functions as arguments, which reach the page as one-way stubs. `(callback:returns)` also lets the stub return a
143
+ // promise of the far side's return value, `(callback:returns=0,2)` only for the functions at those argument positions; the wait is bounded by `callbackReturnTimeoutMs`
144
+ // and every other outcome is `undefined`. It needs `timers` (`exposeObjects` and `createPageHost` supply them).)
137
145
  call?: string[];
138
146
  set?: string[];
139
147
  /** Event sources, as `path@type` (`'window.app.bus@ready'`; the source and the type are named exactly, a wildcard in either is refused). Never implied by the other lists. */
@@ -210,7 +218,11 @@ export interface ObjectsPeer {
210
218
  /** The transport-neutral server half: roots, allow-lists and limits, attachable to any peer. Knows nothing about wsh. */
211
219
  export function createObjectsServer(options: ObjectsServerOptions): {
212
220
  /** `who`: the identity of every call unless the peer gives one per call (`ctx.who`); one that names two keys, or is not an identity, throws a `TypeError` here. */
213
- attach(peer: Pick<ObjectsPeer, 'onRequest' | 'maxMessageBytes'>, options?: { who?: ObjectsIdentity }): { limits: ObjectsLimits };
221
+ attach(peer: Pick<ObjectsPeer, 'onRequest' | 'maxMessageBytes'>, options?: { who?: ObjectsIdentity }): {
222
+ limits: ObjectsLimits;
223
+ /** What became of the calls of callbacks that return: `pending` now, and in total `answered`, `timedOut`, `failed`, `refused` and `dropped`. */
224
+ callbackReturnStats(): { pending: number; answered: number; timedOut: number; failed: number; refused: number; dropped: number };
225
+ };
214
226
  /**
215
227
  * One `get` or `call` of a named path (`path` starts with the root), through the same checks as an objects call (the key's grants as `permit(root, op)`, the allow-lists,
216
228
  * the names that need listing, `authorize`, the window guard). No session, so no handle and no callback; resolves with the wire value (`{ v }`, or a named non-value `{ u }`).
@@ -195,11 +195,10 @@ export interface WshPageIndicatorCallbacks {
195
195
  disconnected(who: { username: string; fingerprint: string }): void;
196
196
  }
197
197
 
198
- export interface WshPageHostOptions {
198
+ /** The options every form of the page host takes (where it dials is `relay` or `connect`, see `WshPageHostOptions` and `WshPageDialOutOptions`). */
199
+ export interface WshPageHostBaseOptions {
199
200
  /** The realm to serve: required, and the only thing read. Passing it exposes nothing by itself. */
200
201
  window: WshPageWindow;
201
- /** A pipe relay (`@johnhenry/wsh/pipe-relay`): its `ws://` / `wss://` URL, or `{ url, id }` with a rendezvous id of your own. */
202
- relay: string | { url: string; id?: string };
203
202
  /** What this tab is called: shown in the indicator, the `serverInfo.name` of the MCP server. */
204
203
  name: string;
205
204
  /** Who may log in: `authorized_keys` lines (options such as `capabilities="mcp:search"` apply) or raw 32-byte keys. Required. */
@@ -232,6 +231,23 @@ export interface WshPageHostOptions {
232
231
  onLog?: (line: string) => void;
233
232
  }
234
233
 
234
+ /** The default form: the page dials a pipe relay and the operator dials the same relay. */
235
+ export interface WshPageHostOptions extends WshPageHostBaseOptions {
236
+ /** A pipe relay (`@johnhenry/wsh/pipe-relay`): its `ws://` / `wss://` URL, or `{ url, id }` with a rendezvous id of your own. */
237
+ relay: string | { url: string; id?: string };
238
+ connect?: never;
239
+ }
240
+
241
+ /**
242
+ * The dial-out form, off unless written: the page dials an operator that WAITS (a process that listens and logs in as the client over what it accepts, for example
243
+ * with `connectWshOverDuplex`) instead of a relay. Not together with `relay`. The URL is dialled exactly as written (no role or rendezvous id is added), must be
244
+ * `ws://` or `wss://` with no user name, password or fragment, and is never logged. The login, the sealed session, the approval, the indicator and Stop are the same.
245
+ */
246
+ export interface WshPageDialOutOptions extends WshPageHostBaseOptions {
247
+ connect: string | { url: string };
248
+ relay?: never;
249
+ }
250
+
235
251
  export interface WshPageHost {
236
252
  /** The URL an operator dials. Its rendezvous id is the secret that pairs the operator with this page. */
237
253
  readonly operatorUrl: string;
@@ -251,7 +267,12 @@ export interface WshPageHost {
251
267
  close(): Promise<void>;
252
268
  }
253
269
 
270
+ /** What `createPageHost` gives for the dial-out form: nobody dials this page, so there is no `operatorUrl` and no rendezvous id. */
271
+ export type WshPageDialOutHost = Omit<WshPageHost, 'operatorUrl' | 'rendezvousId'> & { readonly operatorUrl: null; readonly rendezvousId: null };
272
+
254
273
  /** A page (or any window-shaped realm) as a host behind a pipe relay it chose: key login only, sealed sessions only, the window's WebMCP tools as MCP. */
255
274
  export function createPageHost(options: WshPageHostOptions): Promise<WshPageHost>;
275
+ /** The dial-out form: the page dials an operator that listens (`connect`). */
276
+ export function createPageHost(options: WshPageDialOutOptions): Promise<WshPageDialOutHost>;
256
277
 
257
278
  export type { RpcChannel, WshRpcContext };
package/src/page-host.mjs CHANGED
@@ -177,6 +177,9 @@ function createDomIndicator(window, { name }) {
177
177
  * and whose origin is reported. Passing it exposes nothing by itself.
178
178
  * @param {string | { url: string, id?: string }} options.relay - a pipe relay (`@johnhenry/wsh/pipe-relay`): its `ws://` / `wss://` URL, and
179
179
  * optionally the rendezvous id (default: a fresh random one, exposed as `host.rendezvousId`)
180
+ * @param {string | { url: string }} [options.connect] - the dial-out form, OFF unless written and not together with `relay`: the `ws://` / `wss://` URL of an operator that
181
+ * WAITS (it listens, and logs in as the client over what it accepts). Dialled exactly as written (no role or rendezvous id is added), never logged, no user name,
182
+ * password or fragment in it. The login, sealing, approval, indicator and Stop are the same as behind a relay; there is no `operatorUrl` (it is `null`).
180
183
  * @param {Record<string, { mode?: 'values', allow?: { get?: string[], call?: string[], set?: string[] }, authorize?: Function, limits?: object, object?: object }>} [options.expose]
181
184
  * object access, off unless written: named roots (`window` is the window passed; another name needs `object`), each with its allow-lists by
182
185
  * operation (paths relative to the root: `'document.title'`, `'app.**'`; nothing allowed by default). `mode: 'handles'` is this root's own opt-in to handles (`nodes: true` a second one, for nodes and the window graph).
@@ -208,7 +211,7 @@ function createDomIndicator(window, { name }) {
208
211
  * @param {(line: string) => void} [options.onLog]
209
212
  */
210
213
  export async function createPageHost(options = {}) {
211
- const { window, relay, name, authorizedKeys, mcp, expose, indicator = true, unattended = false, hostKey, hostKeyStore, onSession, onSessionEnd, onRefused, onClose, reconnect = true, onLog = () => {} } = options;
214
+ const { window, relay, connect, name, authorizedKeys, mcp, expose, indicator = true, unattended = false, hostKey, hostKeyStore, onSession, onSessionEnd, onRefused, onClose, reconnect = true, onLog = () => {} } = options;
212
215
  if (!window || (typeof window !== 'object' && typeof window !== 'function')) {
213
216
  throw new TypeError('createPageHost: window is required: it is the realm served and the only thing this reads (pass `window`, an iframe\'s contentWindow, or a worker\'s self)');
214
217
  }
@@ -237,11 +240,25 @@ export async function createPageHost(options = {}) {
237
240
  for (const [k, fn] of Object.entries({ onSession, onSessionEnd, onRefused, onClose })) if (fn !== undefined && typeof fn !== 'function') throw new TypeError(`createPageHost: ${k} must be a function`);
238
241
  if (hostKeyStore !== undefined && (typeof hostKeyStore?.load !== 'function' || typeof hostKeyStore?.save !== 'function')) throw new TypeError('createPageHost: hostKeyStore needs load() and save(keyPair)');
239
242
 
240
- const relayOptions = typeof relay === 'string' ? { url: relay } : relay;
241
- if (!isObj(relayOptions) || typeof relayOptions.url !== 'string') throw new TypeError('createPageHost: relay is required: the ws:// or wss:// URL of a pipe relay (or { url, id })');
242
- const rendezvousId = relayOptions.id ?? randomRendezvousId(window.crypto);
243
- const hostUrl = pipeUrl(relayOptions.url, rendezvousId, 'host');
244
- const operatorUrl = pipeUrl(relayOptions.url, rendezvousId, 'operator');
243
+ // Where the page dials: a pipe relay (the default form: the operator dials the same relay and the rendezvous id pairs them), or, only when `connect` is written, an
244
+ // endpoint of an operator that WAITS. Exactly one; neither is dialled until createPageHost is called with it.
245
+ if (relay !== undefined && connect !== undefined) throw new TypeError('createPageHost: give relay or connect, not both: relay is a pipe relay the operator also dials, connect is an operator that listens');
246
+ let hostUrl; let operatorUrl = null; let rendezvousId = null;
247
+ if (connect !== undefined) {
248
+ const connectUrl = typeof connect === 'string' ? connect : isObj(connect) && Object.keys(connect).every((k) => k === 'url') ? connect.url : undefined;
249
+ let parsed = null;
250
+ try { parsed = typeof connectUrl === 'string' ? new URL(connectUrl) : null; } catch { parsed = null; }
251
+ if (!parsed || (parsed.protocol !== 'ws:' && parsed.protocol !== 'wss:') || parsed.username !== '' || parsed.password !== '' || parsed.hash !== '' || connectUrl.includes('#')) {
252
+ throw new TypeError('createPageHost: connect must be the ws:// or wss:// URL of an operator that listens (or { url }), with no user name, password or fragment in it');
253
+ }
254
+ hostUrl = connectUrl; // dialled as written: no role or rendezvous id is added, and the URL is never logged (its query may be a secret)
255
+ } else {
256
+ const relayOptions = typeof relay === 'string' ? { url: relay } : relay;
257
+ if (!isObj(relayOptions) || typeof relayOptions.url !== 'string') throw new TypeError('createPageHost: relay is required: the ws:// or wss:// URL of a pipe relay (or { url, id }), or connect: the URL of an operator that listens');
258
+ rendezvousId = relayOptions.id ?? randomRendezvousId(window.crypto);
259
+ hostUrl = pipeUrl(relayOptions.url, rendezvousId, 'host');
260
+ operatorUrl = pipeUrl(relayOptions.url, rendezvousId, 'operator');
261
+ }
245
262
 
246
263
  const timers = timersOf(window, options.timers);
247
264
  const origin = readOrigin(window);
@@ -342,7 +359,7 @@ export async function createPageHost(options = {}) {
342
359
  let socket;
343
360
  try { socket = new window.WebSocket(hostUrl); } catch (e) { onLog(`dialing the relay failed: ${e?.message ?? e}`); schedule(false); return; }
344
361
  halfSocket = socket;
345
- onLog('dialed the relay, waiting for an operator');
362
+ onLog(operatorUrl === null ? 'dialed the operator endpoint, waiting for it to log in' : 'dialed the relay, waiting for an operator');
346
363
  let served = false;
347
364
  void memory.accept(socket, { remote: { address: 'relay' } }).catch((e) => onLog(`accept failed: ${e?.message ?? e}`));
348
365
  const onEnd = () => {