@johnhenry/wsh 0.46.0 → 0.47.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
@@ -337,11 +337,17 @@ malformed argument or a bad timestamp refuses the key (logged with the code `unk
337
337
  | `mcp:<tool>` | list and call that tool (`mcp:*`: every tool, and the `mcp` rpc channel) | `McpDiscover` lists only these, `McpCall` / the same |
338
338
  | `target:<name>` | name that target in `Open`, `FileOp`, `OpenEndpoint`; `ListTargets` shows only these | Node host only: the Rust server has no targets and refuses a request that names one |
339
339
  | `rpc:<protocol>` | open that rpc protocol (`wsh-host`, or an embedder's own) | `Open` kind `rpc` / the same |
340
+ | `objects:<root>` , `objects:<root>:<op>` | on that root of `wsh-objects` (`*`: every root), every operation, or just `get`, `call`, `set` or `on` (events) (#190) | JS host only: a `wsh-objects` handler of `exposeObjects` / `createPageHost({ expose })`. The Rust server has none, and it refuses a key line that holds an `objects:` capability (an unknown capability fails closed) |
340
341
  | `relay` | register, list and connect through the relay | `ReverseRegister` `ReverseList` `ReverseConnect` / the same |
341
342
 
342
343
  `<host>` is a name, an IP literal (IPv6 in brackets), `*`, or `*.suffix` (any subdomain, not the apex; the name is compared
343
344
  case-insensitively as the client sent it, so resolution is the gateway's `allow` policy's business). `<port>` is a number or `*`.
344
345
  `<path>` is absolute with no `.` or `..`, exact or ending in `/*` (anything below that directory). `<name>`/`<tool>` are exact or `*`.
346
+ `objects:<root>[:<op>]` follows the roots a host named in `exposeObjects`: a key that holds none keeps what `rpc:wsh-objects` gives (every root, every operation the host's
347
+ allow-lists let through); a key that holds any is **limited to the roots and operations they name** (`objects:window:get` reads `window` and nothing else; `objects:store` is every
348
+ operation on `store`; `objects:*:get` reads every root), may open the channel without `rpc:wsh-objects`, is not told of the roots it cannot use, and still meets the host's
349
+ allow-lists (a capability narrows them and never widens them). Walking to a path (reading the properties on the way) counts as part of any operation on that root. The key
350
+ is asked afresh for every operation, so an `expires` holds at call time.
345
351
  The `wsh-fs` rpc channel puts read and write methods on one channel, so it needs **both** `fs:read` and `fs:write`; a client without
346
352
  both falls back to `FileOp` and the file channels, which are checked per operation. A request with no target runs on the host's own
347
353
  backends and needs no `target:` capability (use `requireTarget` to confine keys to targets). Installing a key (`AuthorizedKeyAdd`) is never
@@ -641,17 +647,17 @@ optional ML-KEM backend, is left out of the measurement. What a page ships is wh
641
647
  <!-- bundle-size:start (generated by `npm run size -- --update`; do not edit) -->
642
648
  | browser bundle | minified | gzip |
643
649
  | --- | ---: | ---: |
644
- | `@johnhenry/wsh` (whole entry point) | 162.8 kB | 49.1 kB |
645
- | `@johnhenry/wsh/memory` (whole entry point) | 229.5 kB | 71.6 kB |
646
- | `@johnhenry/wsh/host` (whole entry point) | 124.8 kB | 41.0 kB |
647
- | `@johnhenry/wsh/reverse` (whole entry point) | 218.1 kB | 67.3 kB |
650
+ | `@johnhenry/wsh` (whole entry point) | 164.0 kB | 49.5 kB |
651
+ | `@johnhenry/wsh/memory` (whole entry point) | 231.5 kB | 72.3 kB |
652
+ | `@johnhenry/wsh/host` (whole entry point) | 126.1 kB | 41.5 kB |
653
+ | `@johnhenry/wsh/reverse` (whole entry point) | 220.0 kB | 68.0 kB |
648
654
  | `@johnhenry/wsh/pipe-relay` (whole entry point) | 7.0 kB | 3.0 kB |
649
655
  | `@johnhenry/wsh/testing` (whole entry point) | 7.9 kB | 2.6 kB |
650
- | `@johnhenry/wsh/page` (whole entry point) | 277.4 kB | 87.6 kB |
651
- | `@johnhenry/wsh/objects` (whole entry point) | 158.3 kB | 48.4 kB |
656
+ | `@johnhenry/wsh/page` (whole entry point) | 285.3 kB | 90.2 kB |
657
+ | `@johnhenry/wsh/objects` (whole entry point) | 165.7 kB | 50.8 kB |
652
658
  | `import { generateKeyPair } from '@johnhenry/wsh'` | 0.4 kB | 0.3 kB |
653
- | `import { WshClient } from '@johnhenry/wsh'` | 134.7 kB | 40.4 kB |
654
- | `import { createConnectionFactory } from '@johnhenry/wsh/host'` | 101.5 kB | 33.1 kB |
659
+ | `import { WshClient } from '@johnhenry/wsh'` | 135.9 kB | 40.8 kB |
660
+ | `import { createConnectionFactory } from '@johnhenry/wsh/host'` | 102.9 kB | 33.6 kB |
655
661
  <!-- bundle-size:end -->
656
662
 
657
663
  ### Signing with a page-held signer
@@ -774,7 +780,7 @@ earlier load will not match and trust-on-first-use gives no continuity. To keep
774
780
  ### Remote objects: `@johnhenry/wsh/objects` (#190)
775
781
 
776
782
  `wsh-objects` is an rpc protocol that reaches an object graph by path: a page's `window`, a worker's `self`, any object a host names as a **root**. It is `values` mode:
777
- only plain cloneable values ever cross (there are no handles, no events and no callbacks yet; `mode: 'handles'` is refused with a sentence saying it is not built).
783
+ only plain cloneable values ever cross (there are no handles and no callbacks yet; `mode: 'handles'` is refused with a sentence saying it is not built; events are delivered as copies, see below).
778
784
  Nothing is reachable but the named roots, and nothing in them is allowed until an allow-list says so.
779
785
 
780
786
  ```js
@@ -829,21 +835,36 @@ chain goes on the *result*, whose path is the callee with `()` (`window.app.getC
829
835
  **Bounds, each refused by name** (`limits`): `maxOps` 32 per request, `maxArgs` 16, `maxDepth` 8, `maxValueBytes` 262144 (and always under what the transport carries in one message), `maxKeys` 200
830
836
  for `describe`, `maxRequestsPerSecond` 50 per channel, `callTimeoutMs` 30000 for a call that returns a promise.
831
837
 
838
+ **Events.** `on(ref, 'type', listener)` subscribes to an EventTarget-style source (`addEventListener` / `removeEventListener`) or an emitter-style one (`on` / `off`, or `on` / `removeListener`),
839
+ but only one that an allow-list entry **of its own** names: `allow.on: ['window.app.bus@ready', 'window@hashchange']` (`path@type`: **the source and the type are named exactly**; a wildcard in either is refused when the host is created, so list the types one by one; in `createPageHost({ expose })` the path is relative to the
840
+ root and `'@hashchange'` is the root itself). `get` and `call` never imply it, and neither does a wildcard in another list; the refused names, the entries that need naming, `authorize(who, op)` (`op.type` is the
841
+ event type) and the key capability `objects:ROOT:on` all apply. What is delivered is plain data, never the event and never a node or a handle: an **Event** becomes `{ type, timeStamp, isTrusted }` plus the fields the **host**
842
+ lists for that type (`eventFields: { hashchange: ['newURL', 'oldURL'], '*': ['detail'] }`) that the subscriber asked for in `{ fields }` (a field not listed is refused; each is copied as plain data and a node is left out);
843
+ an **emitter's** arguments become `{ type, args }` (what cannot be cloned is `null`). The listener is `listener(data, { type, seq, dropped })`; `await on(...)` resolves to the function that unsubscribes (`off(fn)`
844
+ does the same). Bounds, by name: `maxSubscriptions` 16 per channel (refused), `maxEventsPerSecond` 20 per subscription, `maxEventBytes` 16384 and `maxQueuedEvents` 100 per channel: an event over any of the last three
845
+ is **dropped and counted** (the rate and the queue are checked before anything of the event is read or copied, so a dropped event costs a counter), and the next one delivered says how many were lost before it (`dropped`). Events leave as notifications whose write waits for the channel's credit, so a slow reader fills the bounded
846
+ queue and then loses events, counted, instead of growing the page's memory. Every listener is taken out of the page's sources when the channel ends: the operator leaves, Stop, a navigation, a revoke. An error in the far
847
+ side's listener goes to its `onError` and stays there; the host's listener only copies and queues and cannot throw into the page's dispatch. Callbacks as arguments of a call are **not offered** (a function cannot be
848
+ sent: it is refused where it is written); the design in #190 describes them as handles, which is the next step.
849
+
832
850
  **Threat model of `values` mode.** An allow-list of paths means what it says **only because nothing but cloneable values crosses**: a result can never be walked somewhere else, so what a session can
833
851
  reach is exactly the paths the lists name (and, below a `get`, the plain data inside that value). That holds up to what the named paths themselves do:
834
852
  - **Getters with side effects are still gets.** Reading an accessor property runs its getter, and setting one runs its setter; an entry that allows the path allows the effect. The copy of a value never runs a getter or a `toJSON`
835
853
  (an accessor member is left out).
836
854
  - **A `call` runs the application's function with the caller's arguments**, with the page's authority: whatever it does, it does. List the functions you would hand to the caller. A wide entry means what it says:
837
855
  `window.**` reaches `window.Object.assign`, `window.history.pushState` and every method of every object under it (it still excludes the refused names above).
856
+ - **An event source runs the page's own `addEventListener` or `on`**, and a field of an event is read by name (an accessor on an event is a getter, as for `get`). Naming a source in `allow.on` hands the caller what
857
+ that source emits, which for `window` or `document` can be every `keydown`, `input` or `message`: the host has to list the types (no wildcard is accepted), and should keep `eventFields` to what the caller should see (a `detail` or `data` field
858
+ carries whatever the page put there).
838
859
  - A Proxy used as a root runs its own traps for the paths that pass the allow-list, and for no others.
839
860
  - The list is judged by path text. Give a root its real name: a root called `doc` that *is* the `document` is not recognised as `document.cookie` by the entries that must name it.
840
861
  - It does not protect against the page's own code, against a function reachable by a listed path doing something unlisted, or against what a person at the keyboard can see. The remote caller sees results, which may hold text
841
862
  written by third parties.
842
863
  - 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.
843
864
 
844
- Types: `@johnhenry/wsh/objects` ships `.d.ts` (`client.openObjects<T>()` types the roots; references are untyped). Size: `@johnhenry/wsh/objects` is 48.4 kB gzipped (it contains the client), and
845
- the page entry point grows to 87.6 kB with it; no other entry point changed. Not built yet (later steps of #190): handles for what cannot be cloned, events and callbacks, a capability per root
846
- (`objects:ROOT`), typed remotes (`Remote<T>`), an MCP face for the allow-listed paths, and a dial-out form.
865
+ Types: `@johnhenry/wsh/objects` ships `.d.ts` (`client.openObjects<T>()` types the roots; references are untyped). Size: `@johnhenry/wsh/objects` is 50.8 kB gzipped (it contains the client), and
866
+ the page entry point is 90.2 kB with it; no other entry point changed. A capability per root and operation (`objects:ROOT[:OP]`) is described under [per-key capabilities](#authorized-key-options-122).
867
+ Not built yet (later steps of #190): handles for what cannot be cloned, callbacks as arguments, typed remotes (`Remote<T>`), an MCP face for the allow-listed paths, and a dial-out form.
847
868
 
848
869
  ### WebTransport listener
849
870
 
@@ -2015,7 +2036,7 @@ instead of dragging its own toolchain and CI job into an unrelated
2015
2036
  browser-app repo. It was previously deleted from clawser by accident
2016
2037
  (2026-03-14) and restored (2026-07-05) before this move.
2017
2038
 
2018
- Four crates, workspace-versioned (currently `0.17.0`):
2039
+ Four crates, workspace-versioned (currently `0.17.1`):
2019
2040
 
2020
2041
  | Crate | Kind | Description |
2021
2042
  |-------|------|--------------|
@@ -2185,7 +2206,7 @@ than left to be found.
2185
2206
  | Signals and resize for a one-off command | `session.signal()`, `session.resize()` | `wsh host command` forwards SIGINT/SIGTERM/SIGHUP (the same signal twice disconnects); `wsh --tty host command` also forwards terminal resizes | **Wire-unified** (`Signal`, `Resize`). The Rust `wsh-server` delivers `Signal` (#145) to a pty session's foreground process group (what ^C reaches) and to an exec-on-pipes command's own process group, for `HUP INT QUIT TERM KILL USR1 USR2 WINCH CONT STOP TSTP ALRM` (with or without `SIG`); another name is ignored, and only the control attachment of the connection that owns the channel can send one. Not delivered on Windows |
2186
2207
  | 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 |
2187
2208
  | 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) |
2188
- | 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 works where the Rust client speaks virtual-mode rpc: it does not yet, so `wsh mcp` cannot reach a page host | **JS-only** host (a page); the far side is unchanged wire (`mcp` rpc in virtual mode, #191) |
2209
+ | 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 client has no `wsh-objects` client, and no Rust host serves either | **JS-only** host (a page); the far side is unchanged wire (`mcp` rpc in virtual mode, #191) |
2189
2210
  | 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`) | none: the Rust client and `wsh-server` do not speak `wsh-objects`, and `wsh-server` has no handler for it | **JS-only**; 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 |
2190
2211
  | 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 |
2191
2212
  | 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) |
@@ -2263,7 +2284,7 @@ plus one `SHA256SUMS` file covering every archive in the release. These
2263
2284
  names are a stable contract other repos (clawser) pin and download by --
2264
2285
  do not change them without coordinating downstream.
2265
2286
 
2266
- `wsh --version` and `wsh-server --version` print the workspace version the binary was built from (`wsh 0.17.0`), which is the
2287
+ `wsh --version` and `wsh-server --version` print the workspace version the binary was built from (`wsh 0.17.1`), which is the
2267
2288
  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
2268
2289
  version cannot be read from the binary (look for a flag in `wsh --help` instead).
2269
2290
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@johnhenry/wsh",
3
- "version": "0.46.0",
3
+ "version": "0.47.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",
@@ -91,7 +91,7 @@
91
91
  "@modelcontextprotocol/sdk": "^1.17.0"
92
92
  },
93
93
  "scripts": {
94
- "test": "node --test test/*.test.mjs",
94
+ "test": "node scripts/run-tests.mjs",
95
95
  "test:rust": "node --test --test-timeout=180000 test/rust/*.test.mjs",
96
96
  "test:browser": "playwright test --config test/browser/playwright.config.mjs",
97
97
  "size": "node scripts/bundle-size.mjs",
package/src/client.mjs CHANGED
@@ -2815,7 +2815,9 @@ export class WshClient {
2815
2815
  */
2816
2816
  #attachTransportHandlers(transport) {
2817
2817
  transport.onControl = (msg) => this.#onTransportControl(msg);
2818
- transport.onClose = () => this.#handleTransportClose();
2818
+ // A sealed frame is opened asynchronously, so the close of the socket behind the last frame must wait for it: the frames
2819
+ // that arrived before the close are delivered first (the host's last words, the exit of a command), then the close is handled.
2820
+ transport.onClose = () => this.#afterOpens(() => this.#handleTransportClose());
2819
2821
  transport.onError = (err) => this.#handleTransportError(err);
2820
2822
  // A datagram is not a frame: on a sealed session a relay could inject one, so none is heard (UDP uses the reliable path).
2821
2823
  transport.onDatagram = (bytes) => { if (!this.#sessionSeal) this.#gateway?.handleDatagram(bytes); };
@@ -3046,16 +3048,35 @@ export class WshClient {
3046
3048
  this.#countDrop({ reason: 'plaintext-on-sealed-session', messageType: msg.type });
3047
3049
  return;
3048
3050
  }
3049
- seal.bridge.open(msg).then(
3051
+ this.#trackOpen(seal.bridge.open(msg).then(
3050
3052
  (inner) => { if (this.#sessionSeal === seal) this.#handleControl(inner); },
3051
3053
  (err) => this.#sealedFrameFailed(seal, err),
3052
- );
3054
+ ));
3053
3055
  return;
3054
3056
  }
3055
3057
  if (msg.type === MSG.KEY_EXCHANGE && msg.session_id === seal.sessionId) { this.#handleControl(msg); return; }
3056
3058
  this.#countDrop({ reason: 'plaintext-before-seal', messageType: msg.type });
3057
3059
  }
3058
3060
 
3061
+ /** Sealed frames being opened (each is one pending promise), and what is waiting for them to be delivered. */
3062
+ #opening = 0;
3063
+ #afterOpening = [];
3064
+
3065
+ /** @param {Promise<unknown>} p a frame being opened and delivered; never rejects */
3066
+ #trackOpen(p) {
3067
+ this.#opening++;
3068
+ const done = () => {
3069
+ if (--this.#opening > 0) return;
3070
+ for (const fn of this.#afterOpening.splice(0)) fn();
3071
+ };
3072
+ p.then(done, done);
3073
+ }
3074
+
3075
+ /** Run `fn` now, or once every sealed frame that has already arrived has been opened and delivered. */
3076
+ #afterOpens(fn) {
3077
+ if (this.#opening === 0) fn(); else this.#afterOpening.push(fn);
3078
+ }
3079
+
3059
3080
  #sealedFrameFailed(seal, err) {
3060
3081
  if (this.#sessionSeal !== seal || this.#state === STATE_CLOSED) return;
3061
3082
  this.#sessionSeal = { ...seal, failed: true };
@@ -3231,9 +3252,9 @@ export class WshClient {
3231
3252
  const sealState = this.#sealState;
3232
3253
  if (sealState) {
3233
3254
  if (sealState.bridge?.isFrame(inner)) {
3234
- sealState.bridge.open(inner)
3255
+ this.#trackOpen(sealState.bridge.open(inner)
3235
3256
  .then((opened) => this.#handleControl(opened, msg.from_fingerprint))
3236
- .catch((err) => this.#countDrop({ reason: 'unopenable-bridge-frame', detail: err.message }));
3257
+ .catch((err) => this.#countDrop({ reason: 'unopenable-bridge-frame', detail: err.message })));
3237
3258
  return;
3238
3259
  }
3239
3260
  const setup = !sealState.bridge && inner.type === MSG.KEY_EXCHANGE && inner.session_id === sealState.sessionId;
@@ -53,7 +53,10 @@ const fail = (code, reason) => ({ ok: false, code, reason });
53
53
  const NAME_CAP_RE = /^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/;
54
54
  const TOOL_CAP_RE = /^[A-Za-z0-9_][A-Za-z0-9_.:-]{0,127}$/;
55
55
  const DOMAIN_RE = /^[A-Za-z0-9]([A-Za-z0-9._-]*[A-Za-z0-9])?$/;
56
- const SIMPLE_CAPS = new Set(['exec', 'pty', 'relay', 'fs:read', 'fs:write']);
56
+ const OBJECT_ROOT_RE = /^[A-Za-z_$][A-Za-z0-9_$-]{0,63}$/;
57
+ /** The operations of `wsh-objects` a capability can name (`objects:ROOT:OP`). */
58
+ const OBJECT_OPS = ['get', 'call', 'set', 'on'];
59
+ const SIMPLE_CAPS =new Set(['exec', 'pty', 'relay', 'fs:read', 'fs:write']);
57
60
 
58
61
  const capFail = (code, reason) => ({ ok: false, code, reason });
59
62
 
@@ -132,6 +135,14 @@ function parseCapability(raw) {
132
135
  if (raw.startsWith('target:')) return named('target:', 'target', NAME_CAP_RE, true);
133
136
  if (raw.startsWith('mcp:')) return named('mcp:', 'mcp', TOOL_CAP_RE, true);
134
137
  if (raw.startsWith('rpc:')) return named('rpc:', 'rpc', NAME_CAP_RE, false);
138
+ if (raw.startsWith('objects:')) {
139
+ // objects:ROOT or objects:ROOT:OP (#190): a root of `wsh-objects` (or `*`), and optionally one operation on it. JS hosts only.
140
+ const parts = raw.slice('objects:'.length).split(':');
141
+ const [root, op, ...rest] = parts;
142
+ if (rest.length || !(root === '*' || OBJECT_ROOT_RE.test(root))) return bad('expected objects:<root>[:<get|call|set|on>]');
143
+ if (op !== undefined && !OBJECT_OPS.includes(op)) return bad(`the operation must be one of ${OBJECT_OPS.join(', ')}`);
144
+ return { ok: true, cap: { raw, kind: 'objects', name: root, op: op ?? null } };
145
+ }
135
146
  return capFail('unknown-capability', `unknown capability ${JSON.stringify(raw)}`);
136
147
  }
137
148
 
@@ -340,6 +351,8 @@ function capabilityRefusal(p, req) {
340
351
  // A handler that narrows by capability itself (`capabilityScoped`, req.scoped) may be opened by a key that names any
341
352
  // tool; every other `mcp` handler would show a `mcp:search` key all of its tools, so it still needs `mcp:*`.
342
353
  else if (proto === 'mcp') r = req.scoped ? need('mcp:<tool>', has('mcp')) : need('mcp:*', caps.some((c) => c.kind === 'mcp' && c.name === '*'));
354
+ // Same for `wsh-objects`: a key that names roots (`objects:window:get`) may open it without `rpc:wsh-objects`, and is limited to them.
355
+ else if (proto === 'wsh-objects' && req.scoped) r = need('rpc:wsh-objects', has('objects') || caps.some((c) => c.kind === 'rpc' && c.name === proto));
343
356
  else r = need(`rpc:${proto}`, caps.some((c) => c.kind === 'rpc' && c.name === proto));
344
357
  } else r = need(req.channel, false);
345
358
  return r ?? target();
@@ -350,6 +363,13 @@ function capabilityRefusal(p, req) {
350
363
  }
351
364
  case 'mcp': return need('mcp:*', has('mcp'));
352
365
  case 'mcp-call': case 'mcp-tool': return need(`mcp:${req.tool}`, caps.some((c) => c.kind === 'mcp' && nameMatches(c, req.tool)));
366
+ // An operation of `wsh-objects` on a root (`op`: get, call, set, or `walk`: reading on the way to something): a key that names no root
367
+ // with `objects:` is limited by `rpc:wsh-objects` alone (all roots, as before); one that names roots is limited to them.
368
+ case 'objects': {
369
+ const named = caps.filter((c) => c.kind === 'objects');
370
+ if (!named.length) return need('rpc:wsh-objects', caps.some((c) => c.kind === 'rpc' && c.name === 'wsh-objects'));
371
+ return need(`objects:${req.root}${req.op === 'walk' ? '' : `:${req.op}`}`, named.some((c) => nameMatches(c, req.root) && (req.op === 'walk' || c.op === null || c.op === req.op)));
372
+ }
353
373
  case 'relay': return need('relay', has('relay'));
354
374
  // Installing a key gives a key with no capability list, so a key with one never may.
355
375
  case 'key-admin': return { code: 'key-admin-not-permitted', reason: 'installing a key is not permitted for a restricted key' };
@@ -426,7 +446,7 @@ function optionsRefusal(p, req, activeSessions) {
426
446
  case 'mcp': case 'mcp-call': case 'mcp-tool': return p.mcp ? null : no('mcp-not-permitted', 'MCP not permitted for this key');
427
447
  case 'relay': return p.relay ? null : no('relay-not-permitted', 'relay not permitted for this key');
428
448
  // The gateway, endpoints and targets are not scoped by the options (only by capabilities).
429
- case 'tcp': case 'udp': case 'dns': case 'listen-tcp': case 'unix': case 'listen-unix': case 'endpoint': case 'target': return null;
449
+ case 'tcp': case 'udp': case 'dns': case 'listen-tcp': case 'unix': case 'listen-unix': case 'endpoint': case 'target': case 'objects': return null;
430
450
  // Installing another key (`AuthorizedKeyAdd`, which the Rust server serves): the new key has no options, so only a key that
431
451
  // is not restricted at all may add one -- a restricted key would otherwise mint an unrestricted one.
432
452
  case 'key-admin':
@@ -62,6 +62,14 @@ export const OBJECTS_DEFAULT_LIMITS = Object.freeze({
62
62
  maxKeys: 200,
63
63
  /** Requests accepted per second, per attached peer. */
64
64
  maxRequestsPerSecond: 50,
65
+ /** Event subscriptions per channel. */
66
+ maxSubscriptions: 16,
67
+ /** Events delivered per second, per subscription; the rest are dropped and counted. */
68
+ maxEventsPerSecond: 20,
69
+ /** Bytes of one delivered event; a bigger one is dropped and counted. */
70
+ maxEventBytes: 16 * 1024,
71
+ /** Events waiting for the transport (credit), per channel; more are dropped and counted. */
72
+ maxQueuedEvents: 100,
65
73
  /** How long a call that returns a promise is waited for. */
66
74
  callTimeoutMs: 30_000,
67
75
  });
@@ -83,6 +91,7 @@ export const NEEDS_LISTING = Object.freeze([
83
91
  ]);
84
92
 
85
93
  const KEY_MAX = 256;
94
+ const EVENT_TYPE_RE = /^[A-Za-z0-9_$:.-]{1,128}$/;
86
95
 
87
96
  function checkKey(key) {
88
97
  if (typeof key !== 'string' || key === '' || key.length > KEY_MAX) throw invalid(`a path segment must be a string of 1 to ${KEY_MAX} characters`);
@@ -336,12 +345,18 @@ function isPromiseLike(v) {
336
345
  * @param {() => number} [options.now]
337
346
  */
338
347
  export function createObjectsServer(options = {}) {
339
- const { roots, mode = 'values', allow = {}, authorize, limits: limitOptions = {}, guard, timers = null, now = () => Date.now() } = options;
340
- if (mode === 'handles') throw new TypeError("exposeObjects: mode 'handles' is not built: only 'values' exists (handles, events and callbacks are a later step of #190)");
348
+ const { roots, mode = 'values', allow = {}, authorize, limits: limitOptions = {}, guard, timers = null, eventFields = {}, now = () => Date.now() } = options;
349
+ if (mode === 'handles') throw new TypeError("exposeObjects: mode 'handles' is not built: only 'values' exists (handles and callbacks are a later step of #190)");
341
350
  if (mode !== 'values') throw new TypeError("exposeObjects: mode must be 'values'");
342
351
  if (typeof allow === 'string') throw new TypeError('exposeObjects: allow must be { get, call, set } (the wide-open form belongs to mode handles, which is not built)');
343
352
  if (!allow || typeof allow !== 'object' || Array.isArray(allow)) throw new TypeError('exposeObjects: allow must be { get, call, set }');
344
- for (const k of Object.keys(allow)) if (!['get', 'call', 'set'].includes(k)) throw new TypeError(`exposeObjects: allow.${k} is not an operation (get, call, set)`);
353
+ for (const k of Object.keys(allow)) if (!['get', 'call', 'set', 'on'].includes(k)) throw new TypeError(`exposeObjects: allow.${k} is not an operation (get, call, set, on)`);
354
+ // The extra fields of an event a subscriber may ask for, by event type (`'*'`: any type): names of properties read from the event, copied as plain data.
355
+ if (!eventFields || typeof eventFields !== 'object' || Array.isArray(eventFields)) throw new TypeError('exposeObjects: eventFields must be { [type]: [field names] }');
356
+ for (const [type, names] of Object.entries(eventFields)) {
357
+ if (!Array.isArray(names) || !names.every((n) => typeof n === 'string' && /^[A-Za-z_$][A-Za-z0-9_$]{0,63}$/.test(n))) throw new TypeError(`exposeObjects: eventFields[${JSON.stringify(type)}] must be an array of property names`);
358
+ for (const n of names) if (ALWAYS_REFUSED.has(n)) throw new TypeError(`exposeObjects: eventFields[${JSON.stringify(type)}] names "${n}", which is never reachable`);
359
+ }
345
360
  if (!roots || typeof roots !== 'object' || Array.isArray(roots)) throw new TypeError('exposeObjects: roots must be an object of { name: object }: the named roots are all that is reachable');
346
361
  const rootNames = Object.keys(roots);
347
362
  if (rootNames.length === 0) throw new TypeError('exposeObjects: at least one root is needed');
@@ -356,18 +371,37 @@ export function createObjectsServer(options = {}) {
356
371
  if (!Number.isSafeInteger(v) || v < 1) throw new TypeError(`exposeObjects: limits.${k} must be a positive integer`);
357
372
  limits[k] = v;
358
373
  }
359
- const lists = { get: compileList(allow.get, 'get'), call: compileList(allow.call, 'call'), set: compileList(allow.set, 'set') };
360
- const every = [...lists.get, ...lists.call, ...lists.set];
374
+ // `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.
375
+ const compileOn = (list) => {
376
+ if (list === undefined || list === null) return [];
377
+ if (!Array.isArray(list)) throw new TypeError('exposeObjects: allow.on must be an array of "path@type" entries');
378
+ return list.map((entry) => {
379
+ const at = typeof entry === 'string' ? entry.indexOf('@') : -1;
380
+ const type = at < 0 ? '' : entry.slice(at + 1);
381
+ if (at <= 0) throw new TypeError(`exposeObjects: allow.on entry ${JSON.stringify(entry)} must be "path@type"`);
382
+ if (/[*?]/.test(type)) throw new TypeError(`exposeObjects: allow.on entry ${JSON.stringify(entry)}: list the event types one by one; a wildcard type would hand over every event of the source`);
383
+ if (!EVENT_TYPE_RE.test(type)) throw new TypeError(`exposeObjects: allow.on entry ${JSON.stringify(entry)}: the event type must be a name of letters, digits and _ $ : . - (up to 128)`);
384
+ if (/\*/.test(entry.slice(0, at))) throw new TypeError(`exposeObjects: allow.on entry ${JSON.stringify(entry)}: an event source is named exactly, with no wildcard in the path`);
385
+ const segs = compileList([entry.slice(0, at)], 'on')[0];
386
+ return Object.assign(segs, { type });
387
+ });
388
+ };
389
+ const lists = { get: compileList(allow.get, 'get'), call: compileList(allow.call, 'call'), set: compileList(allow.set, 'set'), on: compileOn(allow.on) };
390
+ const every = [...lists.get, ...lists.call, ...lists.set, ...lists.on];
361
391
 
362
392
  /** The checks every operation passes, in order. `terminal` ones need the operation's own list; the rest need only to walk toward something allowed. */
363
- async function check(kind, root, segs, who, { terminal }) {
393
+ async function check(kind, root, segs, ctx, { terminal, type }) {
394
+ const who = ctx.who;
364
395
  const gone = guard?.();
365
396
  if (gone) throw refuse('gone', `refused: ${gone}`);
397
+ // 0. what the caller's key may do on this root, if the transport says (`ctx.permit(root, op)`, asked afresh: an expiry holds at call time)
398
+ permitted(ctx, root, kind === 'get' && !terminal ? 'walk' : kind === 'construct' ? 'call' : kind === 'describe' || kind === 'snapshot' ? 'get' : kind);
366
399
  const rel = segs.slice(1).map(bareName);
367
400
  const own = lists[kind === 'construct' ? 'call' : kind === 'describe' || kind === 'snapshot' ? 'get' : kind];
368
401
  // 1. the allow-list: the operation's own list for the operation itself, any list for walking toward something
369
402
  if (terminal) {
370
403
  if (!own.some((p) => matchPath(p, segs))) throw refuse('not-allowed', `refused: ${kind} of ${segs.join('.')} is not in the allow-list`, { path: segs.join('.'), op: kind });
404
+ if (kind === 'on' && !own.some((p) => matchPath(p, segs) && p.type === type)) throw refuse('not-allowed', `refused: the event type "${type}" of ${segs.join('.')} is not in the allow-list`, { path: segs.join('.'), op: kind, type });
371
405
  } else if (!every.some((p) => prefixPath(p, segs))) {
372
406
  throw refuse('not-allowed', `refused: ${segs.join('.')} is not on the way to anything the allow-list names`, { path: segs.join('.') });
373
407
  }
@@ -379,11 +413,16 @@ export function createObjectsServer(options = {}) {
379
413
  }
380
414
  if (terminal && authorize) {
381
415
  let ok = false;
382
- try { ok = (await authorize(who ?? {}, { kind, root, path: segs.slice(1), text: segs.join('.') })) === true; } catch { ok = false; }
416
+ try { ok = (await authorize(who ?? {}, { kind, root, path: segs.slice(1), text: segs.join('.'), ...(type !== undefined ? { type } : {}) })) === true; } catch { ok = false; }
383
417
  if (!ok) throw refuse('authorize', `refused: ${kind} of ${segs.join('.')} was not authorized`, { path: segs.join('.'), op: kind });
384
418
  }
385
419
  }
386
420
 
421
+ function permitted(ctx, root, op) {
422
+ if (typeof ctx.permit !== 'function' || ctx.permit(root, op) === true) return;
423
+ throw refuse('not-permitted', `refused: this key's capabilities do not allow ${op === 'walk' ? 'reading' : op} on ${root}`, { root, op });
424
+ }
425
+
387
426
  const readKey = (holder, key) => {
388
427
  if (holder === null || holder === undefined) throw new ObjectsError(OBJECTS_ERROR.FAILED, `cannot read "${key}" of ${holder === null ? 'null' : 'undefined'}`, { reason: 'bad-path' });
389
428
  return Reflect.get(Object(holder), key, holder);
@@ -431,14 +470,14 @@ export function createObjectsServer(options = {}) {
431
470
  const next = [...segs, key];
432
471
  if (kind === 'get') {
433
472
  if (typeof cur === 'function' && FUNCTION_REFLECTION.has(key)) throw refuse('always-refused', `refused: "${key}" of a function re-aims it and is never reachable`);
434
- await check('get', root, next, ctx.who, { terminal: last });
473
+ await check('get', root, next, ctx, { terminal: last });
435
474
  try { cur = readKey(cur, key); } catch (e) { throw wrapThrown(e, `reading ${next.join('.')}`); }
436
475
  segs = next;
437
476
  continue;
438
477
  }
439
478
  // call / construct
440
479
  if (kind === 'call' && typeof cur === 'function' && FUNCTION_REFLECTION.has(key)) throw refuse('always-refused', `refused: "${key}" of a function re-aims it and is never reachable`);
441
- await check(kind, root, next, ctx.who, { terminal: true });
480
+ await check(kind, root, next, ctx, { terminal: true });
442
481
  const args = op.args === undefined ? [] : op.args;
443
482
  if (!Array.isArray(args)) throw invalid('args must be an array');
444
483
  if (args.length > limits.maxArgs) throw limitError('maxArgs', limits.maxArgs, `${args.length} arguments`);
@@ -464,7 +503,7 @@ export function createObjectsServer(options = {}) {
464
503
  }
465
504
 
466
505
  /** Walk `path` (an array of keys) as traversal only; the holder and its path. */
467
- async function walk(root, path, who) {
506
+ async function walk(root, path, ctx) {
468
507
  if (!Array.isArray(path)) throw invalid('path must be an array');
469
508
  if (path.length > limits.maxOps) throw limitError('maxOps', limits.maxOps, `a path of ${path.length} segments`);
470
509
  let cur = roots[root];
@@ -473,7 +512,7 @@ export function createObjectsServer(options = {}) {
473
512
  const key = checkKey(raw);
474
513
  if (typeof cur === 'function' && FUNCTION_REFLECTION.has(key)) throw refuse('always-refused', `refused: "${key}" of a function re-aims it and is never reachable`);
475
514
  const next = [...segs, key];
476
- await check('get', root, next, who, { terminal: false });
515
+ await check('get', root, next, ctx, { terminal: false });
477
516
  try { cur = readKey(cur, key); } catch (e) { throw wrapThrown(e, `reading ${next.join('.')}`); }
478
517
  segs = next;
479
518
  }
@@ -484,10 +523,10 @@ export function createObjectsServer(options = {}) {
484
523
  const root = requireRoot(params);
485
524
  const path = params.path;
486
525
  if (!Array.isArray(path) || path.length === 0) throw invalid('set needs a path of at least one segment');
487
- const { cur: parent, segs } = await walk(root, path.slice(0, -1), ctx.who);
526
+ const { cur: parent, segs } = await walk(root, path.slice(0, -1), ctx);
488
527
  const key = checkKey(path[path.length - 1]);
489
528
  const target = [...segs, key];
490
- await check('set', root, target, ctx.who, { terminal: true });
529
+ await check('set', root, target, ctx, { terminal: true });
491
530
  if (parent === null || (typeof parent !== 'object' && typeof parent !== 'function')) throw new ObjectsError(OBJECTS_ERROR.FAILED, `cannot set "${key}" on ${segs.join('.')}: it is not an object`, { reason: 'bad-path' });
492
531
  const value = fromWire(params.value, limits);
493
532
  let ok;
@@ -504,8 +543,8 @@ export function createObjectsServer(options = {}) {
504
543
 
505
544
  async function describe(params, ctx) {
506
545
  const root = requireRoot(params);
507
- const { cur, segs } = await walk(root, params.path ?? [], ctx.who);
508
- await check('describe', root, segs, ctx.who, { terminal: false });
546
+ const { cur, segs } = await walk(root, params.path ?? [], ctx);
547
+ await check('describe', root, segs, ctx, { terminal: false });
509
548
  if (cur === null || (typeof cur !== 'object' && typeof cur !== 'function')) return { type: kindOf(cur), keys: [] };
510
549
  const keys = [];
511
550
  const seen = new Set();
@@ -531,17 +570,125 @@ export function createObjectsServer(options = {}) {
531
570
 
532
571
  async function snapshot(params, ctx) {
533
572
  const root = requireRoot(params);
534
- const { cur, segs } = await walk(root, params.path ?? [], ctx.who);
535
- await check('snapshot', root, segs, ctx.who, { terminal: true });
573
+ const { cur, segs } = await walk(root, params.path ?? [], ctx);
574
+ await check('snapshot', root, segs, ctx, { terminal: true });
536
575
  const depth = params.depth === undefined ? limits.maxDepth : Number.isSafeInteger(params.depth) && params.depth >= 0 ? Math.min(params.depth, limits.maxDepth) : (() => { throw invalid('depth must be a whole number'); })();
537
576
  const ceiling = ctx.maxBytes ?? limits.maxValueBytes;
538
577
  const wanted = params.maxBytes === undefined ? ceiling : Number.isSafeInteger(params.maxBytes) && params.maxBytes > 0 ? Math.min(params.maxBytes, ceiling) : (() => { throw invalid('maxBytes must be a positive whole number'); })();
539
578
  return toWire(cur, { maxDepth: depth, maxBytes: wanted, cut: true });
540
579
  }
541
580
 
581
+ // ── Events ──────────────────────────────────────────────────────────────────────────────────────────────────────────
582
+ // A subscription is a listener on an EventTarget-style source (`addEventListener`) or an emitter-style one (`on` / `off`), named by an `allow.on` entry
583
+ // (`path@type`) of its own. What is delivered is plain data: an Event becomes `{ type, timeStamp, isTrusted }` plus the fields the host lists for its type
584
+ // (`eventFields`) and the subscriber asked for, each copied as plain data (a node is left out); an emitter's arguments become `{ type, args }`. Never the event,
585
+ // never a handle. A listener runs in the page's dispatch: it only copies, bounds, queues, and cannot throw into it.
586
+
587
+ const sourceMethods = (source) => {
588
+ const fn = (name) => { try { const f = Reflect.get(Object(source), name, source); return typeof f === 'function' ? f : null; } catch { return null; } };
589
+ if (fn('addEventListener') && fn('removeEventListener')) return { kind: 'target', add: 'addEventListener', remove: 'removeEventListener' };
590
+ if (fn('on') && fn('off')) return { kind: 'emitter', add: 'on', remove: 'off' };
591
+ if (fn('on') && fn('removeListener')) return { kind: 'emitter', add: 'on', remove: 'removeListener' };
592
+ return null;
593
+ };
594
+
595
+ /** An Event as plain data. */
596
+ function describeEvent(event, fields) {
597
+ const read = (name) => { try { return Reflect.get(Object(event), name, event); } catch { return undefined; } };
598
+ const out = { type: String(read('type') ?? ''), timeStamp: Number.isFinite(read('timeStamp')) ? read('timeStamp') : 0, isTrusted: read('isTrusted') === true };
599
+ for (const name of fields) {
600
+ const w = toWire(read(name), { maxDepth: 3, maxBytes: limits.maxEventBytes });
601
+ if ('v' in w && w.v !== undefined) out[name] = w.v;
602
+ }
603
+ return out;
604
+ }
605
+
606
+ async function pump(session) {
607
+ if (session.pumping) return;
608
+ session.pumping = true;
609
+ try {
610
+ while (session.queue.length && !session.closed) {
611
+ const { sub, data, dropped } = session.queue.shift();
612
+ const message = { id: sub.id, seq: ++sub.seq, data, ...(dropped ? { dropped } : {}) };
613
+ // The write waits for the transport (credit): events behind it queue, to `maxQueuedEvents`, and beyond that are dropped and counted.
614
+ try { await session.peer.notify('event', message); } catch { /* the channel is going away */ }
615
+ }
616
+ } finally { session.pumping = false; }
617
+ }
618
+
619
+ function deliver(session, sub, args) {
620
+ if (session.closed) return;
621
+ try {
622
+ if (guard?.()) return;
623
+ const t = now();
624
+ while (sub.stamps.length && t - sub.stamps[0] >= 1000) sub.stamps.shift();
625
+ if (sub.stamps.length >= limits.maxEventsPerSecond) { sub.dropped++; return; }
626
+ // Room first, copy after: a dropped event costs a counter, not a read of the event or a copy of its fields.
627
+ if (session.queue.length >= limits.maxQueuedEvents) { sub.dropped++; return; }
628
+ let data;
629
+ if (sub.kind === 'target') data = describeEvent(args[0], sub.fields);
630
+ else {
631
+ // Emitter arguments: plain values; what cannot be cloned is null (the whole value keeps its position).
632
+ data = { type: sub.type, args: args.map((a) => { const w = toWire(a, { maxDepth: 4, maxBytes: limits.maxEventBytes }); return 'v' in w ? w.v : null; }) };
633
+ }
634
+ toWire(data, { maxDepth: 6, maxBytes: limits.maxEventBytes });
635
+ sub.stamps.push(t);
636
+ // The events dropped since the last accepted one are told with this one: "this many were lost before it".
637
+ session.queue.push({ sub, data, dropped: sub.dropped });
638
+ sub.dropped = 0;
639
+ void pump(session);
640
+ } catch { sub.dropped++; }
641
+ }
642
+
643
+ async function subscribe(params, ctx) {
644
+ const { session } = ctx;
645
+ const root = requireRoot(params);
646
+ const type = params.type;
647
+ if (typeof type !== 'string' || !EVENT_TYPE_RE.test(type)) throw invalid('an event type is a name of letters, digits and _ $ : . - (up to 128)');
648
+ const id = params.id;
649
+ if (!Number.isSafeInteger(id) || id < 1 || session.subs.has(id)) throw invalid('a subscription id is a whole number the channel has not used');
650
+ const asked = params.fields === undefined ? [] : params.fields;
651
+ if (!Array.isArray(asked) || asked.length > 16 || !asked.every((f) => typeof f === 'string')) throw invalid('fields must be an array of property names');
652
+ const offered = [...(eventFields[type] ?? []), ...(eventFields['*'] ?? [])];
653
+ for (const f of asked) if (!offered.includes(f)) throw refuse('not-allowed', `refused: the field "${f}" of ${type} events is not offered by this host`, { field: f, type });
654
+ if (session.subs.size >= limits.maxSubscriptions) throw limitError('maxSubscriptions', limits.maxSubscriptions, 'too many event subscriptions on this channel');
655
+ const { cur: source, segs } = await walk(root, params.path ?? [], ctx);
656
+ await check('on', root, segs, ctx, { terminal: true, type });
657
+ const kind = sourceMethods(source);
658
+ if (!kind) throw new ObjectsError(OBJECTS_ERROR.FAILED, `${segs.join('.')} is not an event source (it needs addEventListener, or on and off)`, { reason: 'not-an-event-source' });
659
+ const sub = { id, type, kind: kind.kind, fields: [...new Set(asked)], source, stamps: [], dropped: 0, seq: 0, remove: kind.remove, listener: null };
660
+ sub.listener = (...args) => deliver(session, sub, args);
661
+ try { Reflect.apply(Reflect.get(Object(source), kind.add, source), source, [type, sub.listener]); } catch (e) { throw wrapThrown(e, `${segs.join('.')}.${kind.add}`); }
662
+ session.subs.set(id, sub);
663
+ return { ok: true };
664
+ }
665
+
666
+ function removeSub(sub) {
667
+ try { Reflect.apply(Reflect.get(Object(sub.source), sub.remove, sub.source), sub.source, [sub.type, sub.listener]); } catch { /* the page's own source: nothing to tell */ }
668
+ }
669
+
670
+ async function unsubscribe(params, ctx) {
671
+ const sub = ctx.session.subs.get(params.id);
672
+ if (!sub) throw invalid('no such subscription');
673
+ ctx.session.subs.delete(params.id);
674
+ removeSub(sub);
675
+ ctx.session.queue = ctx.session.queue.filter((q) => q.sub !== sub);
676
+ return { ok: true, dropped: sub.dropped };
677
+ }
678
+
542
679
  /** Register the protocol's methods on a peer. `who` is the identity of every call unless the transport gives one per call. */
543
680
  function attach(peer, { who } = {}) {
544
681
  if (typeof peer?.onRequest !== 'function') throw new TypeError('attach: the peer needs onRequest(method, handler)');
682
+ const session = { peer, subs: new Map(), queue: [], pumping: false, closed: false };
683
+ // The end of the channel (the peer left, Stop, a navigation, a revoke) takes every listener out of the page's sources.
684
+ const prior = peer.onClose;
685
+ peer.onClose = (reason) => {
686
+ session.closed = true;
687
+ for (const sub of session.subs.values()) removeSub(sub);
688
+ session.subs.clear();
689
+ session.queue = [];
690
+ try { prior?.(reason); } catch { /* ignore */ }
691
+ };
545
692
  const stamps = [];
546
693
  const method = (name, fn) => peer.onRequest(name, async (params, ctx = {}) => {
547
694
  const t = now();
@@ -550,15 +697,18 @@ export function createObjectsServer(options = {}) {
550
697
  stamps.push(t);
551
698
  // A value is kept under what the transport carries in one message, with room for the envelope.
552
699
  const maxBytes = Math.min(limits.maxValueBytes, Math.max(1024, (peer.maxMessageBytes ?? Infinity) - 4096));
553
- const call = { ...ctx, signal: ctx.signal, who: ctx.who ?? who, maxBytes };
700
+ const call = { ...ctx, signal: ctx.signal, who: ctx.who ?? who, maxBytes, session };
554
701
  if (params === null || typeof params !== 'object' || Array.isArray(params)) throw invalid('params must be an object');
555
702
  try { return await fn(params, call); } catch (e) { if (e instanceof ObjectsError) throw e; throw wrapThrown(e, name); }
556
703
  });
557
- method('roots', async () => ({ roots: rootNames.slice() }));
704
+ // A key that may use only some roots is told of those only.
705
+ method('roots', async (_params, call) => ({ roots: rootNames.filter((name) => typeof call.permit !== 'function' || call.permit(name, 'walk') === true) }));
558
706
  method('resolve', resolve);
559
707
  method('set', setValue);
560
708
  method('describe', describe);
561
709
  method('snapshot', snapshot);
710
+ method('subscribe', subscribe);
711
+ method('unsubscribe', unsubscribe);
562
712
  return { limits };
563
713
  }
564
714
 
@@ -773,6 +923,33 @@ export async function snapshot(ref, { depth, maxBytes, signal } = {}) {
773
923
  } catch (e) { throw asObjectsError(e, state.session); }
774
924
  }
775
925
 
926
+ /**
927
+ * Listen for an event of a remote source named by the host's `allow.on`: `const stop = await on(win.app.bus, 'ready', (data, { seq, dropped }) => ...)`.
928
+ * `data` is plain (an Event as `{ type, timeStamp, isTrusted, ...the fields you asked for }`, an emitter's as `{ type, args }`); `dropped` counts the events the
929
+ * host dropped before this one (rate, size, or a slow channel). `fields` are extra event fields the host lists for the type. Resolves to the function that unsubscribes.
930
+ */
931
+ export async function on(ref, type, listener, { fields, onError } = {}) {
932
+ const { state, keys } = pathOf(ref, 'on');
933
+ if (typeof listener !== 'function') throw new TypeError('on needs a listener function: listener(data, { type, seq, dropped })');
934
+ const { session } = state;
935
+ const id = session.nextSub++;
936
+ // Registered before the request: an event can follow the answer at once.
937
+ session.subs.set(id, { listener, onError, type });
938
+ try {
939
+ await session.peer.request('subscribe', { id, root: state.root, path: keys, type, ...(fields ? { fields } : {}) });
940
+ } catch (e) { session.subs.delete(id); throw asObjectsError(e, session); }
941
+ return async function off() {
942
+ if (!session.subs.delete(id)) return;
943
+ try { await session.peer.request('unsubscribe', { id }); } catch { /* the channel is already gone: the host removed the listener with it */ }
944
+ };
945
+ }
946
+
947
+ /** Stop a subscription: `await off(await on(...))`, the same as calling the function `on` returned. */
948
+ export async function off(unsubscribe) {
949
+ if (typeof unsubscribe !== 'function') throw new TypeError('off needs what on() returned');
950
+ await unsubscribe();
951
+ }
952
+
776
953
  /** The shape of an object, for a REPL or completion: `{ type, keys: [{ key, type, own }] }`. Only names the allow-list could walk to are told. */
777
954
  export async function describe(ref, { signal } = {}) {
778
955
  const { state, keys } = pathOf(ref, 'describe');
@@ -786,7 +963,15 @@ export async function describe(ref, { signal } = {}) {
786
963
  */
787
964
  export async function createObjectsClient(peer, { timeoutMs } = {}) {
788
965
  if (typeof peer?.request !== 'function') throw new TypeError('createObjectsClient: the peer needs request(method, params)');
789
- const session = { peer, closing: null, timeoutMs };
966
+ const session = { peer, closing: null, timeoutMs, subs: new Map(), nextSub: 1 };
967
+ // 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.
968
+ peer.onNotification?.('event', (params) => {
969
+ const sub = session.subs.get(params?.id);
970
+ if (!sub) return;
971
+ try { sub.listener(params.data, { type: sub.type, seq: params.seq, dropped: Number.isSafeInteger(params.dropped) ? params.dropped : 0 }); } catch (e) {
972
+ try { sub.onError?.(e); } catch { /* the error handler's own */ }
973
+ }
974
+ });
790
975
  peer.onNotification?.('closing', (params) => { session.closing = typeof params?.reason === 'string' ? clip(params.reason, TEXT_MAX) : 'closing'; });
791
976
  let roots;
792
977
  try { roots = (await peer.request('roots', {}))?.roots; } catch (e) { throw asObjectsError(e, session); }
package/src/objects.d.ts CHANGED
@@ -44,6 +44,14 @@ export interface ObjectsLimits {
44
44
  maxRequestsPerSecond: number;
45
45
  /** How long a call that returns a promise is waited for. Default 30000. */
46
46
  callTimeoutMs: number;
47
+ /** Event subscriptions per channel. Default 16. */
48
+ maxSubscriptions: number;
49
+ /** Events delivered per second, per subscription; the rest are dropped and counted. Default 20. */
50
+ maxEventsPerSecond: number;
51
+ /** Bytes of one delivered event; a bigger one is dropped and counted. Default 16384. */
52
+ maxEventBytes: number;
53
+ /** Events waiting for the transport's credit, per channel; more are dropped and counted. Default 100. */
54
+ maxQueuedEvents: number;
47
55
  }
48
56
  export const OBJECTS_DEFAULT_LIMITS: Readonly<ObjectsLimits>;
49
57
 
@@ -55,11 +63,15 @@ export interface ObjectsAllow {
55
63
  get?: string[];
56
64
  call?: string[];
57
65
  set?: string[];
66
+ /** 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. */
67
+ on?: string[];
58
68
  }
59
69
 
60
70
  export interface ObjectsWho { username: string | null; fingerprint: string | null }
61
71
  export interface ObjectsOperation {
62
- kind: 'get' | 'call' | 'construct' | 'set' | 'describe' | 'snapshot';
72
+ kind: 'get' | 'call' | 'construct' | 'set' | 'on' | 'describe' | 'snapshot';
73
+ /** For `on`: the event type. */
74
+ type?: string;
63
75
  root: string;
64
76
  /** The path below the root. */
65
77
  path: string[];
@@ -76,6 +88,8 @@ export interface ObjectsServerOptions {
76
88
  /** Asked for every operation the allow-list let through; anything but `true` (a throw included) refuses. */
77
89
  authorize?: (who: ObjectsWho, op: ObjectsOperation) => boolean | Promise<boolean>;
78
90
  limits?: Partial<ObjectsLimits>;
91
+ /** Extra event fields a subscriber may ask for, by event type (`'*'`: any type): property names read from the event and copied as plain data (a node is left out). */
92
+ eventFields?: Record<string, string[]>;
79
93
  /** Why nothing may be served any more (the window left), else null. */
80
94
  guard?: () => string | null;
81
95
  /** For `callTimeoutMs`. */
@@ -140,6 +154,13 @@ export function call(ref: any, ...args: unknown[]): Promise<any>;
140
154
  export function construct(ref: any, ...args: unknown[]): Promise<any>;
141
155
  /** A bounded deep copy; subtrees deeper than `depth` are `null`. */
142
156
  export function snapshot(ref: any, options?: { depth?: number; maxBytes?: number; signal?: AbortSignal }): Promise<any>;
157
+ /**
158
+ * Listen for an event of a remote source named by the host's `allow.on`. `data` is plain: an Event as `{ type, timeStamp, isTrusted, ...fields }`, an emitter's as
159
+ * `{ type, args }`. `dropped` counts events the host dropped before this one. Resolves to the function that unsubscribes. Never an event object, never a handle.
160
+ */
161
+ export function on(ref: any, type: string, listener: (data: any, info: { type: string; seq: number; dropped: number }) => void, options?: { fields?: string[]; onError?: (error: unknown) => void }): Promise<() => Promise<void>>;
162
+ /** Stop a subscription: what `on` resolved to. */
163
+ export function off(unsubscribe: () => Promise<void>): Promise<void>;
143
164
  /** The shape of an object, for completion: the names and types the allow-list could walk to. */
144
165
  export function describe(ref: any, options?: { signal?: AbortSignal }): Promise<{ type: string; keys: Array<{ key: string; type: string; own: boolean }>; truncated?: boolean }>;
145
166
  /** End the connection behind what `openObjects()` returned. */
package/src/objects.mjs CHANGED
@@ -28,22 +28,28 @@ import {
28
28
  export {
29
29
  OBJECTS_PROTOCOL, OBJECTS_ERROR, OBJECTS_DEFAULT_LIMITS, NEEDS_LISTING, ObjectsError, NonValue,
30
30
  createObjectsServer, createObjectsClient, createDuplexPeer, matchPath, toWire, fromWire,
31
- get, set, call, construct, snapshot, describe, closeObjects,
31
+ get, set, call, construct, snapshot, describe, on, off, closeObjects,
32
32
  } from './objects-core.mjs';
33
33
 
34
34
  /** Timers for `callTimeoutMs` where the embedder gave none: this module is the Node-or-browser adapter, not the page entry point. */
35
35
  const defaultTimers = { setTimeout: (fn, ms) => setTimeout(fn, ms), clearTimeout: (id) => clearTimeout(id) };
36
36
 
37
37
  /** An `RpcChannel` as the core's `Peer`: refusals become `RpcError`s with their reason, so the far side hears the sentence and the rule. */
38
- function channelPeer(channel) {
38
+ function channelPeer(channel, host = {}) {
39
+ // What the key of this channel may do on a root: `objects:ROOT[:OP]` capabilities, through the host's `permits`, asked afresh for each operation.
40
+ const permit = typeof host.permits === 'function' ? (root, op) => host.permits({ kind: 'objects', root, op }) : undefined;
39
41
  return {
40
42
  onRequest: (method, handler) => channel.onRequest(method, async (params, ctx) => {
41
- try { return await handler(params, ctx); } catch (e) {
43
+ try { return await handler(params, permit ? { ...ctx, permit } : ctx); } catch (e) {
42
44
  if (e instanceof ObjectsError) throw new RpcError(e.code, e.message, e.data);
43
45
  throw e;
44
46
  }
45
47
  }),
46
48
  get maxMessageBytes() { return channel.maxMessageBytes; },
49
+ // Events go out as notifications, whose write waits for the channel's credit; the end of the channel takes the listeners out of the page.
50
+ notify: (method, params) => channel.notify(method, params),
51
+ get onClose() { return channel.onClose; },
52
+ set onClose(fn) { channel.onClose = fn; },
47
53
  };
48
54
  }
49
55
 
@@ -62,7 +68,7 @@ export function exposeObjects(options = {}) {
62
68
  const sessions = new Set();
63
69
  const handler = (channel, ctx = {}) => {
64
70
  const who = { username: ctx.user ?? null, fingerprint: ctx.fingerprint ?? null };
65
- server.attach(channelPeer(channel), { who });
71
+ server.attach(channelPeer(channel, ctx), { who });
66
72
  const session = { channel, who };
67
73
  sessions.add(session);
68
74
  const prior = channel.onClose;
@@ -77,6 +83,8 @@ export function exposeObjects(options = {}) {
77
83
  }));
78
84
  return targets.length;
79
85
  };
86
+ // This handler narrows by the key's capabilities itself (`objects:ROOT[:OP]`), so a key that names roots may open the channel without `rpc:wsh-objects`.
87
+ handler.capabilityScoped = true;
80
88
  handler.rootNames = server.rootNames;
81
89
  handler.limits = server.limits;
82
90
  return handler;
@@ -167,7 +167,7 @@ export interface WshPageHostOptions {
167
167
  * `'document.title'`, `'app.**'`; nothing allowed by default). A root named `window` is the window that was passed; another name needs `object`.
168
168
  * `mode: 'handles'` is refused: not built. See `@johnhenry/wsh/objects`.
169
169
  */
170
- expose?: Record<string, { mode?: 'values'; allow?: ObjectsAllow; authorize?: (who: ObjectsWho, op: ObjectsOperation) => boolean | Promise<boolean>; limits?: Partial<ObjectsLimits>; object?: object }>;
170
+ expose?: Record<string, { mode?: 'values'; allow?: ObjectsAllow; authorize?: (who: ObjectsWho, op: ObjectsOperation) => boolean | Promise<boolean>; limits?: Partial<ObjectsLimits>; object?: object; eventFields?: Record<string, string[]> }>;
171
171
  /** `true` (default): the badge in `window.document`. Callbacks: for a context with no document, or your own UI. `false` needs `unattended: true`. */
172
172
  indicator?: boolean | WshPageIndicatorCallbacks;
173
173
  /** Nobody is in front of this window. Allows `indicator: false` and a window with no document; what needs approval is then denied unless `mcp.prompt` answers. */
package/src/page-host.mjs CHANGED
@@ -69,31 +69,34 @@ function exposedRoots(window, expose) {
69
69
  const names = Object.keys(expose);
70
70
  if (names.length === 0) throw new TypeError('createPageHost: expose names no root');
71
71
  const roots = {};
72
- const allow = { get: [], call: [], set: [] };
72
+ const allow = { get: [], call: [], set: [], on: [] };
73
73
  const authorizers = new Map();
74
+ const eventFields = {};
74
75
  let limits;
75
76
  for (const name of names) {
76
77
  const cfg = expose[name];
77
78
  if (!isObj(cfg)) throw new TypeError(`createPageHost: expose.${name} must be { mode, allow }`);
78
- if (cfg.mode === 'handles') throw new TypeError("createPageHost: expose mode 'handles' is not built: only 'values' exists (handles, events and callbacks are a later step of #190)");
79
+ if (cfg.mode === 'handles') throw new TypeError("createPageHost: expose mode 'handles' is not built: only 'values' exists (handles and callbacks are a later step of #190)");
79
80
  if (cfg.mode !== undefined && cfg.mode !== 'values') throw new TypeError("createPageHost: expose mode must be 'values'");
80
81
  if (typeof cfg.allow === 'string') throw new TypeError('createPageHost: expose allow must be { get, call, set } (the wide-open form belongs to mode handles, which is not built)');
81
82
  const object = cfg.object ?? (name === 'window' ? window : undefined);
82
83
  if (object === undefined) throw new TypeError(`createPageHost: expose.${name}: only a root named "window" is the window; give { object } for another root`);
83
84
  roots[name] = object;
84
85
  for (const [op, list] of Object.entries(cfg.allow ?? {})) {
85
- if (!(op in allow)) throw new TypeError(`createPageHost: expose.${name}.allow.${op} is not an operation (get, call, set)`);
86
+ if (!(op in allow)) throw new TypeError(`createPageHost: expose.${name}.allow.${op} is not an operation (get, call, set, on)`);
86
87
  if (!Array.isArray(list)) throw new TypeError(`createPageHost: expose.${name}.allow.${op} must be an array of path patterns`);
87
88
  for (const entry of list) {
88
89
  if (typeof entry !== 'string' || entry === '') throw new TypeError(`createPageHost: expose.${name}.allow.${op} entries must be non-empty strings (paths relative to ${name})`);
89
- allow[op].push(`${name}.${entry}`);
90
+ // An event source is `path@type`; with no path (`'@hashchange'`) it is the root itself.
91
+ allow[op].push(op === 'on' && entry.startsWith('@') ? `${name}${entry}` : `${name}.${entry}`);
90
92
  }
91
93
  }
94
+ for (const [type, fields] of Object.entries(cfg.eventFields ?? {})) eventFields[type] = [...new Set([...(eventFields[type] ?? []), ...(Array.isArray(fields) ? fields : [])])];
92
95
  if (cfg.authorize !== undefined) { if (typeof cfg.authorize !== 'function') throw new TypeError(`createPageHost: expose.${name}.authorize must be a function`); authorizers.set(name, cfg.authorize); }
93
96
  if (cfg.limits !== undefined) limits = { ...limits, ...cfg.limits };
94
97
  }
95
98
  const authorize = authorizers.size ? (who, op) => (authorizers.has(op.root) ? authorizers.get(op.root)(who, { ...op, path: op.path }) : true) : undefined;
96
- return { roots, allow, authorize, limits };
99
+ return { roots, allow, authorize, limits, eventFields };
97
100
  }
98
101
 
99
102
  /** The indicator in the page: one row per connected key, with the key's fingerprint and a Stop control. */
@@ -250,7 +253,7 @@ export async function createPageHost(options = {}) {
250
253
  guard: () => gone() ?? mcp.guard?.() ?? null,
251
254
  }) : null;
252
255
  const objectsHandler = exposed ? exposeObjects({
253
- roots: exposed.roots, allow: exposed.allow, authorize: exposed.authorize, limits: exposed.limits, timers,
256
+ roots: exposed.roots, allow: exposed.allow, authorize: exposed.authorize, limits: exposed.limits, eventFields: exposed.eventFields, timers,
254
257
  guard: () => gone(),
255
258
  }) : null;
256
259
  /** What each handler tells and ends: the sessions of a key, or all of them. */
@@ -77,8 +77,16 @@ export function bindSocket(socket, ready, { remote = {}, dataStreams } = {}) {
77
77
  closeTransport: () => { try { socket.close(1000); } catch { /* already closed */ } },
78
78
  });
79
79
  });
80
- const drop = () => { if (closed) return; closed = true; chain = chain.then(() => conn?.close()).catch(() => {}); };
80
+ // The close joins the chain behind the messages that were received before it: each message is handled asynchronously, and
81
+ // marking the connection closed at once would drop the peer's last messages (its final write, the end of its input).
82
+ let closing = false;
83
+ const drop = () => {
84
+ if (closing) return;
85
+ closing = true;
86
+ chain = chain.then(() => { closed = true; return conn?.close(); }).catch(() => {});
87
+ };
81
88
  listen('message', (data) => {
89
+ if (closing) return;
82
90
  chain = chain.then(async () => {
83
91
  if (closed || !conn) return;
84
92
  const bytes = await toBytes(data);
@@ -62,7 +62,14 @@ class QMuxStreamAdapter {
62
62
  constructor(qs) {
63
63
  this.id = qs.id;
64
64
 
65
+ // `controller.error()` throws away what is queued, so a connection that ends right behind a stream's last bytes would
66
+ // take them with it. The failure is held until the reader has taken what had arrived (`pull` runs when the queue is
67
+ // empty), and delivered then.
68
+ let destroyedWith = null;
65
69
  this.readable = new ReadableStream({
70
+ pull: (controller) => {
71
+ if (destroyedWith) { try { controller.error(destroyedWith); } catch { /* already settled */ } }
72
+ },
66
73
  start: (controller) => {
67
74
  qs.onData = (data) => {
68
75
  try { controller.enqueue(data); } catch { /* controller already closed/errored */ }
@@ -74,7 +81,10 @@ class QMuxStreamAdapter {
74
81
  try { controller.error(new Error(`Stream ${qs.id} was reset by peer (error code ${errorCode})`)); } catch { /* already settled */ }
75
82
  };
76
83
  qs.onDestroy = (err) => {
77
- try { controller.error(err); } catch { /* already settled */ }
84
+ destroyedWith = err;
85
+ if (controller.desiredSize === null || controller.desiredSize > 0) {
86
+ try { controller.error(err); } catch { /* already settled */ }
87
+ }
78
88
  };
79
89
  },
80
90
  cancel: () => {
@@ -321,7 +331,11 @@ export class WebSocketTransport extends WshTransport {
321
331
  if (!this.#closedByUs) {
322
332
  this._emitError(err);
323
333
  }
324
- this._emitClose();
334
+ // What arrived before the close is delivered before it is reported: messages are dispatched one per turn, so the close
335
+ // (a separate event of the socket) could otherwise be handled while earlier ones are still waiting (a host's last words,
336
+ // the exit of a command).
337
+ if (this.#inbox.busy) this.#inbox.idle().then(() => this._emitClose(), () => this._emitClose());
338
+ else this._emitClose();
325
339
  }
326
340
 
327
341
  /**
package/src/transport.mjs CHANGED
@@ -73,10 +73,22 @@ export class SerialQueue {
73
73
  this.#handler = handler;
74
74
  }
75
75
 
76
+ #loop = Promise.resolve();
77
+
76
78
  /** @param {*} item */
77
79
  push(item) {
78
80
  this.#items.push(item);
79
- this.#drain();
81
+ if (!this.#draining) this.#loop = this.#drain();
82
+ }
83
+
84
+ /** Whether anything pushed is still waiting for, or being given to, the handler. */
85
+ get busy() {
86
+ return this.#draining || this.#items.length > 0;
87
+ }
88
+
89
+ /** Resolves once everything pushed so far has been dispatched (immediately when nothing is). */
90
+ idle() {
91
+ return this.#loop;
80
92
  }
81
93
 
82
94
  /** Discard any queued-but-not-yet-dispatched items (e.g. on reconnect). */
@@ -694,19 +706,23 @@ export class WebTransportTransport extends WshTransport {
694
706
  * @param {WebTransport} wt
695
707
  */
696
708
  #monitorClosed(wt) {
709
+ // What the control stream had delivered before the session ended is dispatched (one message per turn) before the close
710
+ // is reported: the end of the session is a separate event, and reporting it at once would overtake the last messages.
711
+ // The reader ends with the session, so this wait is bounded by it.
712
+ const afterControl = () => this.#controlReaderDone?.catch(() => {}) ?? Promise.resolve();
697
713
  wt.closed
698
- .then(() => {
714
+ .then(() => afterControl().then(() => {
699
715
  if (this.state !== 'closed') {
700
716
  this._setState('closed');
701
717
  this._emitClose();
702
718
  }
703
- })
704
- .catch((err) => {
719
+ }))
720
+ .catch((err) => afterControl().then(() => {
705
721
  if (this.state !== 'closed') {
706
722
  this._setState('closed');
707
723
  this._emitError(err);
708
724
  this._emitClose();
709
725
  }
710
- });
726
+ }));
711
727
  }
712
728
  }