@johnhenry/wsh 0.47.0 → 0.48.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 +62 -9
- package/package.json +1 -1
- package/src/objects-core.mjs +333 -52
- package/src/objects.d.ts +43 -2
- package/src/objects.mjs +5 -2
- package/src/page-host.d.ts +2 -2
- package/src/page-host.mjs +12 -6
package/README.md
CHANGED
|
@@ -653,8 +653,8 @@ optional ML-KEM backend, is left out of the measurement. What a page ships is wh
|
|
|
653
653
|
| `@johnhenry/wsh/reverse` (whole entry point) | 220.0 kB | 68.0 kB |
|
|
654
654
|
| `@johnhenry/wsh/pipe-relay` (whole entry point) | 7.0 kB | 3.0 kB |
|
|
655
655
|
| `@johnhenry/wsh/testing` (whole entry point) | 7.9 kB | 2.6 kB |
|
|
656
|
-
| `@johnhenry/wsh/page` (whole entry point) |
|
|
657
|
-
| `@johnhenry/wsh/objects` (whole entry point) |
|
|
656
|
+
| `@johnhenry/wsh/page` (whole entry point) | 293.7 kB | 93.1 kB |
|
|
657
|
+
| `@johnhenry/wsh/objects` (whole entry point) | 174.4 kB | 53.4 kB |
|
|
658
658
|
| `import { generateKeyPair } from '@johnhenry/wsh'` | 0.4 kB | 0.3 kB |
|
|
659
659
|
| `import { WshClient } from '@johnhenry/wsh'` | 135.9 kB | 40.8 kB |
|
|
660
660
|
| `import { createConnectionFactory } from '@johnhenry/wsh/host'` | 102.9 kB | 33.6 kB |
|
|
@@ -780,7 +780,7 @@ earlier load will not match and trust-on-first-use gives no continuity. To keep
|
|
|
780
780
|
### Remote objects: `@johnhenry/wsh/objects` (#190)
|
|
781
781
|
|
|
782
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:
|
|
783
|
-
only plain cloneable values ever cross (
|
|
783
|
+
only plain cloneable values ever cross (on a root that has not opted in to [handles](#handles) there are no handles and no callbacks; events are delivered as copies, see below).
|
|
784
784
|
Nothing is reachable but the named roots, and nothing in them is allowed until an allow-list says so.
|
|
785
785
|
|
|
786
786
|
```js
|
|
@@ -844,8 +844,61 @@ an **emitter's** arguments become `{ type, args }` (what cannot be cloned is `nu
|
|
|
844
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
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
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
|
|
848
|
-
|
|
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 a separate facility (see [Callbacks](#callbacks)).
|
|
848
|
+
|
|
849
|
+
#### Handles
|
|
850
|
+
|
|
851
|
+
A root can opt in to **handles**: `exposeObjects({ roots, handles: { window: {} }, ... })`, or `createPageHost({ expose: { window: { mode: 'handles', allow } } })`. Values stays the default, and the opt-in is per root.
|
|
852
|
+
On such a root a function or an object that is not plain data (a class instance with state, a `Map`) comes back as an opaque `RemoteHandle` instead of a named non-value, and `use(handle)` makes a reference that stands on it:
|
|
853
|
+
|
|
854
|
+
```js
|
|
855
|
+
const cart = await win.app.cart; // a RemoteHandle { type: 'Cart' } (what a plain value or a named non-value would have been)
|
|
856
|
+
await use(cart).add({ sku: 'A1' }); // the same object across calls; one request per chain, as ever
|
|
857
|
+
await use(cart).items.length;
|
|
858
|
+
await release(cart); // gives its place back; everything is released when the channel ends
|
|
859
|
+
```
|
|
860
|
+
|
|
861
|
+
- **The path-bound model.** A handle stands at the **path that produced it**: one got by `get window.app.cart` behaves as `window.app.cart`; one returned by calling `window.app.makeCounter` behaves as `window.app.makeCounter()`
|
|
862
|
+
(the notation values mode uses for results), and its members as `window.app.makeCounter().inc`. Every operation through it is judged by the allow-lists for that path extended by the member, exactly as if the path were written out.
|
|
863
|
+
**A handle never widens what a path grants**: if only `window.app.cart.add` may be called, `use(cart).items` is refused. Allow-list entries can name such paths (`call: ['window.app.makeCounter', 'window.app.makeCounter().inc']`).
|
|
864
|
+
The always-refused names stay refused through a handle, and so do the entries that must name their path (`fetch`, cookies, storage, ...).
|
|
865
|
+
- **A handle is opaque and local.** Its id is 128 random bits (from `crypto.getRandomValues`; the page host uses the served window's). It is meaningful only on the channel that produced it, for the key that holds that channel: another
|
|
866
|
+
channel, another key, a reconnect, or a guess finds nothing (`no such handle`). Nothing of it is enumerable on the far side; it is not thenable, and it cannot be sent as an argument.
|
|
867
|
+
- **Nodes and the window graph.** A DOM node, a window or a document is **not** handed out as a handle (it stays a named non-value) unless the root sets its own opt-in, `nodes: true`, which is control of the page. Even then the members that
|
|
868
|
+
lead back up to the graph (`ownerDocument`, `defaultView`, `parentNode`, `parentElement`, `getRootNode`, `contentWindow`, `contentDocument`, `self`, `window`, `top`, `parent`, `frames`, `opener`, `globalThis`) stay refused
|
|
869
|
+
until an allow-list entry names them; a wildcard does not.
|
|
870
|
+
- **A bounded table.** `maxHandles` (64) per channel, **refused by name on overflow, never evicted**; `release(handle)` is explicit; all of them go when the channel ends (the operator leaving, Stop, a navigation, a revoke). A far side's
|
|
871
|
+
garbage-collection hints would be advisory only; none is used.
|
|
872
|
+
- **Previews.** `handle.preview` (a bounded list of up to 8 member names) is present only if a `get` entry names the handle's path, and lists only the names `describe(use(handle))` would list: those the allow-lists could walk to from there. Otherwise a handle says its type and nothing more.
|
|
873
|
+
- **Wide entries need an acknowledgement.** A wildcard (`*` or `**`) in `allow.call` or `allow.set` on a handles root lets a caller hold and reuse every object under it, so the host refuses to start with one unless the root says
|
|
874
|
+
so, `handles: { window: { wideEntries: true } }` (in `createPageHost`, `wideEntries: true` beside `mode: 'handles'`), or lists the paths. A wildcard in `get` alone needs no acknowledgement. A values root is not affected.
|
|
875
|
+
- **Capabilities.** `objects:ROOT[:OP]` apply unchanged: an operation through a handle is the same `get`, `call`, `set` of the producing path (a key with `objects:window:get` can read through a handle and cannot call through it).
|
|
876
|
+
- **What a handle is not.** The host's real object stays in the page: calling a method runs the page's code with the caller's plain-data arguments, as for any `call`; a handle to an object with a powerful method is as powerful as that method's entry in `call`. A handle is
|
|
877
|
+
a reference to something already reachable by a path, so it cannot reach more than the path's own entries; but a wide entry (`window.app.**`) covers every member of every object under it. Events are not offered through a handle, and callbacks are not built.
|
|
878
|
+
|
|
879
|
+
A host says what it supports with its roots (`features`: `events`, `callbacks`, and `handles` 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 (a named `unsupported` error);
|
|
880
|
+
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.
|
|
881
|
+
|
|
882
|
+
#### Callbacks
|
|
883
|
+
|
|
884
|
+
A far-side **function passed as an argument** of a call is a callback, but only where the call's allow-list entry says so by ending in `(callback)`: `allow.call: ['window.app.subscribe(callback)']`. A call entry without it refuses a function
|
|
885
|
+
argument (`does not accept callbacks`), and a function nested inside an argument, a remote reference and a handle are refused where they are written. The page then receives a **stub**, a plain function it may keep and call:
|
|
886
|
+
|
|
887
|
+
```js
|
|
888
|
+
await win.app.subscribe((event) => console.log(event.n)); // the page's subscribe(fn) gets a stub; fn runs here, on the far side
|
|
889
|
+
await release(fn); // kills the stub (also: the channel ending)
|
|
890
|
+
```
|
|
891
|
+
|
|
892
|
+
- **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).
|
|
893
|
+
- **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.
|
|
894
|
+
- **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
|
|
895
|
+
`onCallbackDropped({ dropped })` on the client. The notifications go through the channel's credit like events. The same function sent again is the same callback.
|
|
896
|
+
- **Dead after the session.** A stub is dead after the channel ends (the operator leaving, Stop, a navigation, a revoke) and after `release(fn)`: calling it does nothing and is counted. A listener that throws on the far side goes to `onCallbackError` and never reaches the page.
|
|
897
|
+
- The call with callbacks is a `call` for `authorize` (`op.callbacks` is how many) and for the key's `objects:ROOT:call` capability. A callback is a channel for the page's own code to push plain values to the caller: it can send whatever the page's code puts in it, within the bounds, so list `(callback)` only on calls whose
|
|
898
|
+
stub the page will use for what the caller should see.
|
|
899
|
+
|
|
900
|
+
**The indicator is best effort.** The page host shows a visible element while a session is connected, puts it back if the page removes it, and has a Stop button. Page code can always remove or cover a DOM element, and a tool or a
|
|
901
|
+
function the caller may call runs with the page's authority. What holds is **Stop and revoke** (they close the channel from the page's own code, whatever is on screen) and **the key's capabilities and the host's allow-lists**.
|
|
849
902
|
|
|
850
903
|
**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
|
|
851
904
|
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:
|
|
@@ -862,9 +915,9 @@ reach is exactly the paths the lists name (and, below a `get`, the plain data in
|
|
|
862
915
|
written by third parties.
|
|
863
916
|
- 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.
|
|
864
917
|
|
|
865
|
-
Types: `@johnhenry/wsh/objects` ships `.d.ts` (`client.openObjects<T>()` types the roots; references are untyped). Size: `@johnhenry/wsh/objects` is
|
|
866
|
-
the page entry point is
|
|
867
|
-
Not built yet (later steps of #190):
|
|
918
|
+
Types: `@johnhenry/wsh/objects` ships `.d.ts` (`client.openObjects<T>()` types the roots; references are untyped). Size: `@johnhenry/wsh/objects` is 53.4 kB gzipped (it contains the client), and
|
|
919
|
+
the page entry point is 93.1 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).
|
|
920
|
+
Not built yet (later steps of #190): typed remotes (`Remote<T>`), an MCP face for the allow-listed paths, and a dial-out form.
|
|
868
921
|
|
|
869
922
|
### WebTransport listener
|
|
870
923
|
|
|
@@ -2401,7 +2454,7 @@ out explicitly below rather than left to be discovered.
|
|
|
2401
2454
|
already in it; a fresh host key per page load means no pin outlives it unless `hostKeyStore` is given) are stated in
|
|
2402
2455
|
[A page as a host](#a-page-as-a-host-johnhenrywshpage-190).
|
|
2403
2456
|
- **`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
|
|
2404
|
-
only because nothing but cloneable values crosses (no handles in `values` mode); what it cannot make safe is stated in
|
|
2457
|
+
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); what it cannot make safe is stated in
|
|
2405
2458
|
[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
|
|
2406
2459
|
few paths (`document.cookie`, storage, `fetch`, ...) need an entry that names them. 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.
|
|
2407
2460
|
- **`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
|
package/package.json
CHANGED
package/src/objects-core.mjs
CHANGED
|
@@ -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
|
+
/** Handles per channel (on roots that opted in): more are refused, nothing is evicted. */
|
|
66
|
+
maxHandles: 64,
|
|
67
|
+
/** Callbacks (stubs of far-side functions) per channel: more are refused. */
|
|
68
|
+
maxCallbacks: 16,
|
|
69
|
+
/** Calls of one callback per second; the rest are dropped and counted. */
|
|
70
|
+
maxCallbacksPerSecond: 20,
|
|
71
|
+
/** Bytes of the arguments of one callback call; a bigger one is dropped and counted. */
|
|
72
|
+
maxCallbackBytes: 16 * 1024,
|
|
65
73
|
/** Event subscriptions per channel. */
|
|
66
74
|
maxSubscriptions: 16,
|
|
67
75
|
/** Events delivered per second, per subscription; the rest are dropped and counted. */
|
|
@@ -91,6 +99,10 @@ export const NEEDS_LISTING = Object.freeze([
|
|
|
91
99
|
]);
|
|
92
100
|
|
|
93
101
|
const KEY_MAX = 256;
|
|
102
|
+
const CALLBACK_SUFFIX = '(callback)';
|
|
103
|
+
const B64URL = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_';
|
|
104
|
+
/** 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. */
|
|
105
|
+
const GRAPH_MEMBERS = Object.freeze(['ownerDocument', 'defaultView', 'parentNode', 'parentElement', 'getRootNode', 'contentWindow', 'contentDocument', 'self', 'window', 'top', 'parent', 'frames', 'opener', 'globalThis']);
|
|
94
106
|
const EVENT_TYPE_RE = /^[A-Za-z0-9_$:.-]{1,128}$/;
|
|
95
107
|
|
|
96
108
|
function checkKey(key) {
|
|
@@ -106,9 +118,18 @@ function checkKey(key) {
|
|
|
106
118
|
function compileList(list, kind) {
|
|
107
119
|
if (list === undefined || list === null) return [];
|
|
108
120
|
if (!Array.isArray(list)) throw new TypeError(`exposeObjects: allow.${kind} must be an array of path patterns`);
|
|
109
|
-
return list.map((
|
|
110
|
-
if (typeof
|
|
111
|
-
|
|
121
|
+
return list.map((original) => {
|
|
122
|
+
if (typeof original !== 'string' || original === '') throw new TypeError(`exposeObjects: allow.${kind} entries must be non-empty strings`);
|
|
123
|
+
// A call entry that ends in `(callback)` says the call accepts functions as arguments (they arrive as stubs the page can call, one-way).
|
|
124
|
+
let entry = original;
|
|
125
|
+
let callbacks = false;
|
|
126
|
+
if (entry.endsWith(CALLBACK_SUFFIX)) {
|
|
127
|
+
if (kind !== 'call') throw new TypeError(`exposeObjects: allow.${kind} entry ${JSON.stringify(original)}: only a call entry can accept callbacks`);
|
|
128
|
+
entry = entry.slice(0, -CALLBACK_SUFFIX.length);
|
|
129
|
+
callbacks = true;
|
|
130
|
+
}
|
|
131
|
+
if (entry.includes(CALLBACK_SUFFIX)) throw new TypeError(`exposeObjects: allow.${kind} entry ${JSON.stringify(original)}: "(callback)" ends an entry`);
|
|
132
|
+
const segs = Object.assign(entry.split('.'), { callbacks });
|
|
112
133
|
for (const s of segs) {
|
|
113
134
|
if (s === '') throw new TypeError(`exposeObjects: allow.${kind} entry ${JSON.stringify(entry)} has an empty segment`);
|
|
114
135
|
if (ALWAYS_REFUSED.has(s)) throw new TypeError(`exposeObjects: allow.${kind} entry ${JSON.stringify(entry)} names "${s}", which is never reachable`);
|
|
@@ -345,10 +366,10 @@ function isPromiseLike(v) {
|
|
|
345
366
|
* @param {() => number} [options.now]
|
|
346
367
|
*/
|
|
347
368
|
export function createObjectsServer(options = {}) {
|
|
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:
|
|
350
|
-
if (mode !== 'values') throw new TypeError("exposeObjects: mode must be 'values'");
|
|
351
|
-
if (typeof allow === 'string') throw new TypeError('exposeObjects: allow must be { get, call, set }
|
|
369
|
+
const { roots, mode = 'values', allow = {}, authorize, limits: limitOptions = {}, guard, timers = null, eventFields = {}, handles = {}, random = null, now = () => Date.now() } = options;
|
|
370
|
+
if (mode === 'handles') throw new TypeError("exposeObjects: handles are chosen per root, not for the host: use handles: { window: {} } (and nodes: true on a root that may hand out nodes)");
|
|
371
|
+
if (mode !== 'values') throw new TypeError("exposeObjects: mode must be 'values' (handles are chosen per root with handles: { ROOT: {} })");
|
|
372
|
+
if (typeof allow === 'string') throw new TypeError('exposeObjects: allow must be { get, call, set, on }: a wide-open string is not accepted, and the allow-lists apply to handles too');
|
|
352
373
|
if (!allow || typeof allow !== 'object' || Array.isArray(allow)) throw new TypeError('exposeObjects: allow must be { get, call, set }');
|
|
353
374
|
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
375
|
// 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.
|
|
@@ -365,6 +386,17 @@ export function createObjectsServer(options = {}) {
|
|
|
365
386
|
if (roots[name] === null || (typeof roots[name] !== 'object' && typeof roots[name] !== 'function')) throw new TypeError(`exposeObjects: root "${name}" must be an object`);
|
|
366
387
|
}
|
|
367
388
|
if (authorize !== undefined && typeof authorize !== 'function') throw new TypeError('exposeObjects: authorize must be a function (who, op) => boolean');
|
|
389
|
+
// Handles: per root, explicit. `nodes: true` is the root's own opt-in to hand out DOM nodes, windows and documents: control of the page.
|
|
390
|
+
if (!handles || typeof handles !== 'object' || Array.isArray(handles)) throw new TypeError('exposeObjects: handles must be { ROOT: { nodes? } }');
|
|
391
|
+
const handleRoots = new Map();
|
|
392
|
+
for (const [name, cfg] of Object.entries(handles)) {
|
|
393
|
+
if (!rootNames.includes(name)) throw new TypeError(`exposeObjects: handles names ${JSON.stringify(name)}, which is no such root`);
|
|
394
|
+
if (cfg === null || typeof cfg !== 'object' || Array.isArray(cfg)) throw new TypeError(`exposeObjects: handles.${name} must be an object ({ nodes?: boolean })`);
|
|
395
|
+
if (cfg.nodes !== undefined && typeof cfg.nodes !== 'boolean') throw new TypeError(`exposeObjects: handles.${name}.nodes must be true or false`);
|
|
396
|
+
if (cfg.wideEntries !== undefined && typeof cfg.wideEntries !== 'boolean') throw new TypeError(`exposeObjects: handles.${name}.wideEntries must be true or false`);
|
|
397
|
+
handleRoots.set(name, { nodes: cfg.nodes === true, wideEntries: cfg.wideEntries === true });
|
|
398
|
+
}
|
|
399
|
+
if (handleRoots.size && typeof random !== 'function') throw new TypeError('exposeObjects: handles need a random source (random: (n) => Uint8Array of n random bytes, from crypto.getRandomValues)');
|
|
368
400
|
const limits = { ...OBJECTS_DEFAULT_LIMITS };
|
|
369
401
|
for (const [k, v] of Object.entries(limitOptions)) {
|
|
370
402
|
if (!(k in OBJECTS_DEFAULT_LIMITS)) throw new TypeError(`exposeObjects: unknown limit ${JSON.stringify(k)} (${Object.keys(OBJECTS_DEFAULT_LIMITS).join(', ')})`);
|
|
@@ -388,9 +420,17 @@ export function createObjectsServer(options = {}) {
|
|
|
388
420
|
};
|
|
389
421
|
const lists = { get: compileList(allow.get, 'get'), call: compileList(allow.call, 'call'), set: compileList(allow.set, 'set'), on: compileOn(allow.on) };
|
|
390
422
|
const every = [...lists.get, ...lists.call, ...lists.set, ...lists.on];
|
|
423
|
+
// 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.
|
|
424
|
+
for (const [name, mode] of handleRoots) {
|
|
425
|
+
if (mode.wideEntries) continue;
|
|
426
|
+
for (const kind of ['call', 'set']) {
|
|
427
|
+
const wide = lists[kind].find((p) => (p[0] === name || p[0] === '*' || p[0] === '**') && p.some((s) => s === '*' || s === '**'));
|
|
428
|
+
if (wide) throw new TypeError(`exposeObjects: allow.${kind} entry ${JSON.stringify(wide.join('.'))} is wide on the handles root "${name}": list the paths, or acknowledge it with handles: { ${name}: { wideEntries: true } }`);
|
|
429
|
+
}
|
|
430
|
+
}
|
|
391
431
|
|
|
392
432
|
/** The checks every operation passes, in order. `terminal` ones need the operation's own list; the rest need only to walk toward something allowed. */
|
|
393
|
-
async function check(kind, root, segs, ctx, { terminal, type }) {
|
|
433
|
+
async function check(kind, root, segs, ctx, { terminal, type, callbacks = 0 }) {
|
|
394
434
|
const who = ctx.who;
|
|
395
435
|
const gone = guard?.();
|
|
396
436
|
if (gone) throw refuse('gone', `refused: ${gone}`);
|
|
@@ -401,19 +441,21 @@ export function createObjectsServer(options = {}) {
|
|
|
401
441
|
// 1. the allow-list: the operation's own list for the operation itself, any list for walking toward something
|
|
402
442
|
if (terminal) {
|
|
403
443
|
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 });
|
|
444
|
+
if (callbacks > 0 && !own.some((p) => matchPath(p, segs) && p.callbacks)) throw refuse('not-allowed', `refused: ${segs.join('.')} does not accept callbacks (its allow-list entry would end in "${CALLBACK_SUFFIX}")`, { path: segs.join('.'), op: kind });
|
|
404
445
|
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 });
|
|
405
446
|
} else if (!every.some((p) => prefixPath(p, segs))) {
|
|
406
447
|
throw refuse('not-allowed', `refused: ${segs.join('.')} is not on the way to anything the allow-list names`, { path: segs.join('.') });
|
|
407
448
|
}
|
|
408
449
|
// 2. what a wildcard does not cover: the operation itself needs an entry that names it; walking toward one needs only that some entry that names it goes that way
|
|
409
|
-
|
|
450
|
+
// On a root with handles, the members that lead back up to the document or window graph need naming as well.
|
|
451
|
+
for (const seq of handleRoots.has(root) ? [...NEEDS_LISTING, ...GRAPH_MEMBERS.map((n) => [n])] : NEEDS_LISTING) {
|
|
410
452
|
if (!containsSequence(rel, seq)) continue;
|
|
411
453
|
const listed = terminal ? own.some((p) => matchPath(p, segs) && patternNames(p, seq)) : every.some((p) => prefixPath(p, segs) && patternNames(p, seq));
|
|
412
454
|
if (!listed) throw refuse('needs-listing', `refused: "${rel.join('.')}" is refused until an allow-list entry names ${seq.join('.')} (a wildcard does not)`, { path: segs.join('.') });
|
|
413
455
|
}
|
|
414
456
|
if (terminal && authorize) {
|
|
415
457
|
let ok = false;
|
|
416
|
-
try { ok = (await authorize(who ?? {}, { kind, root, path: segs.slice(1), text: segs.join('.'), ...(type !== undefined ? { type } : {}) })) === true; } catch { ok = false; }
|
|
458
|
+
try { ok = (await authorize(who ?? {}, { kind, root, path: segs.slice(1), text: segs.join('.'), ...(type !== undefined ? { type } : {}), ...(callbacks ? { callbacks } : {}) })) === true; } catch { ok = false; }
|
|
417
459
|
if (!ok) throw refuse('authorize', `refused: ${kind} of ${segs.join('.')} was not authorized`, { path: segs.join('.'), op: kind });
|
|
418
460
|
}
|
|
419
461
|
}
|
|
@@ -453,12 +495,13 @@ export function createObjectsServer(options = {}) {
|
|
|
453
495
|
}
|
|
454
496
|
|
|
455
497
|
async function resolve(params, ctx) {
|
|
456
|
-
const
|
|
498
|
+
const start = startOf(params, ctx);
|
|
499
|
+
const { root } = start;
|
|
457
500
|
const ops = params.ops;
|
|
458
501
|
if (!Array.isArray(ops)) throw invalid('ops must be an array');
|
|
459
502
|
if (ops.length > limits.maxOps) throw limitError('maxOps', limits.maxOps, `${ops.length} operations in one request`);
|
|
460
|
-
let cur =
|
|
461
|
-
let segs =
|
|
503
|
+
let cur = start.cur;
|
|
504
|
+
let segs = start.segs;
|
|
462
505
|
for (let i = 0; i < ops.length; i++) {
|
|
463
506
|
const op = ops[i];
|
|
464
507
|
const last = i === ops.length - 1;
|
|
@@ -477,22 +520,92 @@ export function createObjectsServer(options = {}) {
|
|
|
477
520
|
}
|
|
478
521
|
// call / construct
|
|
479
522
|
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`);
|
|
480
|
-
|
|
523
|
+
// Functions of the far side, passed as arguments: `callbacks: [[index, id], ...]`, with null in `args` at those places.
|
|
524
|
+
const spec = op.callbacks === undefined ? [] : op.callbacks;
|
|
525
|
+
if (!Array.isArray(spec) || spec.length > limits.maxArgs || !spec.every((c) => Array.isArray(c) && c.length === 2 && Number.isSafeInteger(c[0]) && c[0] >= 0 && Number.isSafeInteger(c[1]) && c[1] >= 1)) throw invalid('callbacks must be [[argument index, id], ...]');
|
|
526
|
+
await check(kind, root, next, ctx, { terminal: true, callbacks: spec.length });
|
|
481
527
|
const args = op.args === undefined ? [] : op.args;
|
|
482
528
|
if (!Array.isArray(args)) throw invalid('args must be an array');
|
|
483
529
|
if (args.length > limits.maxArgs) throw limitError('maxArgs', limits.maxArgs, `${args.length} arguments`);
|
|
530
|
+
if (spec.some(([i]) => i >= args.length || args[i] !== null) || new Set(spec.map(([i]) => i)).size !== spec.length) throw invalid('a callback takes the place of an argument, once');
|
|
484
531
|
const clean = fromWire(args, limits);
|
|
532
|
+
const made = [];
|
|
533
|
+
try {
|
|
534
|
+
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; }
|
|
535
|
+
} catch (e) { for (const id of made) killCallback(ctx.session, id); throw e; }
|
|
485
536
|
if (kind === 'call' && isTimerCallee(key) && typeof clean[0] === 'string') throw refuse('always-refused', `refused: ${key} with a string would evaluate it`);
|
|
486
537
|
let fn;
|
|
487
|
-
try { fn = readKey(cur, key); } catch (e) { throw wrapThrown(e, `reading ${next.join('.')}`); }
|
|
488
|
-
if (typeof fn !== 'function') throw new ObjectsError(OBJECTS_ERROR.FAILED, `${next.join('.')} is not a function`, { reason: 'not-a-function' });
|
|
538
|
+
try { fn = readKey(cur, key); } catch (e) { for (const id of made) killCallback(ctx.session, id); throw wrapThrown(e, `reading ${next.join('.')}`); }
|
|
539
|
+
if (typeof fn !== 'function') { for (const id of made) killCallback(ctx.session, id); throw new ObjectsError(OBJECTS_ERROR.FAILED, `${next.join('.')} is not a function`, { reason: 'not-a-function' }); }
|
|
489
540
|
try {
|
|
490
541
|
const out = kind === 'call' ? Reflect.apply(fn, cur, clean) : Reflect.construct(fn, clean);
|
|
491
542
|
cur = kind === 'call' ? await settle(out, ctx) : out;
|
|
492
|
-
} catch (e) { throw wrapThrown(e, next.join('.')); }
|
|
543
|
+
} catch (e) { for (const id of made) killCallback(ctx.session, id); throw wrapThrown(e, next.join('.')); }
|
|
493
544
|
segs = [...segs, `${key}()`];
|
|
494
545
|
}
|
|
495
|
-
return
|
|
546
|
+
return finishValue(cur, root, segs, ctx);
|
|
547
|
+
}
|
|
548
|
+
|
|
549
|
+
// ── Handles ───────────────────────────────────────────────────────────────────────────────────────────────────────
|
|
550
|
+
// On a root that opted in (`handles: { ROOT: { nodes? } }`), a function or an object that is not plain data comes back as an opaque handle instead of a
|
|
551
|
+
// named non-value. A handle stands at the PATH that produced it (`a.b` for a get, `a.f()` for a call), and every operation through it is judged by the
|
|
552
|
+
// allow-lists for that path extended by the member: it never widens what the path grants. The table is per channel, bounded, never evicts.
|
|
553
|
+
|
|
554
|
+
/** Prototype-chain names of what reaches the document or window graph. */
|
|
555
|
+
const GRAPH_CLASSES = new Set(['Node', 'Window', 'WorkerGlobalScope', 'Document']);
|
|
556
|
+
function reachesGraph(value) {
|
|
557
|
+
try {
|
|
558
|
+
let proto = Object.getPrototypeOf(value);
|
|
559
|
+
for (let hops = 0; proto && hops < 16; hops++, proto = Object.getPrototypeOf(proto)) {
|
|
560
|
+
const d = Object.getOwnPropertyDescriptor(proto, 'constructor');
|
|
561
|
+
const name = d && 'value' in d && typeof d.value === 'function' ? Object.getOwnPropertyDescriptor(d.value, 'name')?.value : undefined;
|
|
562
|
+
if (GRAPH_CLASSES.has(name)) return true;
|
|
563
|
+
}
|
|
564
|
+
const tag = Object.prototype.toString.call(value);
|
|
565
|
+
return tag === '[object Window]' || tag === '[object global]' || tag === '[object Document]' || tag === '[object HTMLDocument]';
|
|
566
|
+
} catch { return true; }
|
|
567
|
+
}
|
|
568
|
+
|
|
569
|
+
function finishValue(cur, root, segs, ctx) {
|
|
570
|
+
const wire = toWire(cur, { maxDepth: limits.maxDepth, maxBytes: ctx.maxBytes ?? limits.maxValueBytes });
|
|
571
|
+
const mode = handleRoots.get(root);
|
|
572
|
+
if (!mode || !('u' in wire) || (wire.u !== 'function' && wire.u !== 'object') || !ctx.session) return wire;
|
|
573
|
+
if (wire.u === 'object' && reachesGraph(cur) && !mode.nodes) return wire; // a node, a window, a document: named, not a handle, without the root's own opt-in
|
|
574
|
+
if (wire.u === 'function' && reachesGraph(cur) && !mode.nodes) return wire;
|
|
575
|
+
const { session } = ctx;
|
|
576
|
+
if (session.handles.size >= limits.maxHandles) throw limitError('maxHandles', limits.maxHandles, 'too many handles on this channel: release some (nothing is evicted)');
|
|
577
|
+
const id = newHandleId();
|
|
578
|
+
session.handles.set(id, { root, segs: segs.slice(), value: cur });
|
|
579
|
+
return { h: id, kind: wire.u, ...(wire.type ? { type: wire.type } : {}), ...previewOf(cur, root, segs, ctx) };
|
|
580
|
+
}
|
|
581
|
+
|
|
582
|
+
function newHandleId() {
|
|
583
|
+
const bytes = random(16);
|
|
584
|
+
let out = '';
|
|
585
|
+
let acc = 0;
|
|
586
|
+
let bits = 0;
|
|
587
|
+
for (const b of bytes) { acc = (acc << 8) | b; bits += 8; while (bits >= 6) { bits -= 6; out += B64URL[(acc >> bits) & 63]; } }
|
|
588
|
+
if (bits > 0) out += B64URL[(acc << (6 - bits)) & 63];
|
|
589
|
+
return out;
|
|
590
|
+
}
|
|
591
|
+
|
|
592
|
+
/** A preview is what a `get` on the same path could reveal: the names of a few own members, and only where the get-list names the path. */
|
|
593
|
+
function previewOf(value, root, segs, ctx) {
|
|
594
|
+
if (!lists.get.some((p) => matchPath(p, segs))) return {};
|
|
595
|
+
if (typeof ctx.permit === 'function' && ctx.permit(root, 'get') !== true) return {};
|
|
596
|
+
const rel = segs.slice(1).map(bareName);
|
|
597
|
+
for (const seq of [...NEEDS_LISTING, ...GRAPH_MEMBERS.map((n) => [n])]) if (containsSequence(rel, seq) && !lists.get.some((p) => matchPath(p, segs) && patternNames(p, seq))) return {};
|
|
598
|
+
try {
|
|
599
|
+
// Exactly the names describe() would list: the ones the allow-lists could walk to from here.
|
|
600
|
+
const keys = Object.keys(value).filter((k) => !ALWAYS_REFUSED.has(k) && !k.includes('.') && k.length <= 64 && every.some((p) => prefixPath(p, [...segs, k]))).slice(0, 8);
|
|
601
|
+
return { preview: { keys } };
|
|
602
|
+
} catch { return {}; }
|
|
603
|
+
}
|
|
604
|
+
|
|
605
|
+
async function releaseHandle(params, ctx) {
|
|
606
|
+
const { session } = ctx;
|
|
607
|
+
if (typeof params.handle !== 'string' || !session.handles.delete(params.handle)) throw invalid('no such handle (it was released, belongs to another session, or never existed)');
|
|
608
|
+
return { ok: true };
|
|
496
609
|
}
|
|
497
610
|
|
|
498
611
|
function requireRoot(params) {
|
|
@@ -502,12 +615,26 @@ export function createObjectsServer(options = {}) {
|
|
|
502
615
|
return root;
|
|
503
616
|
}
|
|
504
617
|
|
|
505
|
-
/**
|
|
506
|
-
|
|
618
|
+
/**
|
|
619
|
+
* Where a request starts: a root, or a handle of this channel (`params.handle`), which stands at the path that produced it. A handle is looked
|
|
620
|
+
* up in THIS channel's table by its id: another channel, another key, or a made-up id finds nothing.
|
|
621
|
+
*/
|
|
622
|
+
function startOf(params, ctx) {
|
|
623
|
+
if (params === null || typeof params !== 'object') throw invalid('params must be an object');
|
|
624
|
+
if (params.handle === undefined) { const root = requireRoot(params); return { root, cur: roots[root], segs: [root] }; }
|
|
625
|
+
const rec = typeof params.handle === 'string' ? ctx.session?.handles.get(params.handle) : undefined;
|
|
626
|
+
if (!rec) throw invalid('no such handle (it was released, belongs to another session, or never existed)');
|
|
627
|
+
// The root's mode is checked again, and the key's permission for that root is asked afresh by `check` on every step.
|
|
628
|
+
return { root: rec.root, cur: rec.value, segs: rec.segs.slice() };
|
|
629
|
+
}
|
|
630
|
+
|
|
631
|
+
/** Walk `path` (an array of keys) as traversal only, from where the request starts; the holder and its path. */
|
|
632
|
+
async function walk(start, path, ctx) {
|
|
633
|
+
const root = start.root;
|
|
507
634
|
if (!Array.isArray(path)) throw invalid('path must be an array');
|
|
508
635
|
if (path.length > limits.maxOps) throw limitError('maxOps', limits.maxOps, `a path of ${path.length} segments`);
|
|
509
|
-
let cur =
|
|
510
|
-
let segs =
|
|
636
|
+
let cur = start.cur;
|
|
637
|
+
let segs = start.segs;
|
|
511
638
|
for (const raw of path) {
|
|
512
639
|
const key = checkKey(raw);
|
|
513
640
|
if (typeof cur === 'function' && FUNCTION_REFLECTION.has(key)) throw refuse('always-refused', `refused: "${key}" of a function re-aims it and is never reachable`);
|
|
@@ -520,10 +647,11 @@ export function createObjectsServer(options = {}) {
|
|
|
520
647
|
}
|
|
521
648
|
|
|
522
649
|
async function setValue(params, ctx) {
|
|
523
|
-
const
|
|
650
|
+
const start = startOf(params, ctx);
|
|
651
|
+
const { root } = start;
|
|
524
652
|
const path = params.path;
|
|
525
653
|
if (!Array.isArray(path) || path.length === 0) throw invalid('set needs a path of at least one segment');
|
|
526
|
-
const { cur: parent, segs } = await walk(
|
|
654
|
+
const { cur: parent, segs } = await walk(start, path.slice(0, -1), ctx);
|
|
527
655
|
const key = checkKey(path[path.length - 1]);
|
|
528
656
|
const target = [...segs, key];
|
|
529
657
|
await check('set', root, target, ctx, { terminal: true });
|
|
@@ -542,8 +670,9 @@ export function createObjectsServer(options = {}) {
|
|
|
542
670
|
}
|
|
543
671
|
|
|
544
672
|
async function describe(params, ctx) {
|
|
545
|
-
const
|
|
546
|
-
const {
|
|
673
|
+
const start = startOf(params, ctx);
|
|
674
|
+
const { root } = start;
|
|
675
|
+
const { cur, segs } = await walk(start, params.path ?? [], ctx);
|
|
547
676
|
await check('describe', root, segs, ctx, { terminal: false });
|
|
548
677
|
if (cur === null || (typeof cur !== 'object' && typeof cur !== 'function')) return { type: kindOf(cur), keys: [] };
|
|
549
678
|
const keys = [];
|
|
@@ -569,8 +698,9 @@ export function createObjectsServer(options = {}) {
|
|
|
569
698
|
}
|
|
570
699
|
|
|
571
700
|
async function snapshot(params, ctx) {
|
|
572
|
-
const
|
|
573
|
-
const {
|
|
701
|
+
const start = startOf(params, ctx);
|
|
702
|
+
const { root } = start;
|
|
703
|
+
const { cur, segs } = await walk(start, params.path ?? [], ctx);
|
|
574
704
|
await check('snapshot', root, segs, ctx, { terminal: true });
|
|
575
705
|
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'); })();
|
|
576
706
|
const ceiling = ctx.maxBytes ?? limits.maxValueBytes;
|
|
@@ -608,14 +738,60 @@ export function createObjectsServer(options = {}) {
|
|
|
608
738
|
session.pumping = true;
|
|
609
739
|
try {
|
|
610
740
|
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 */ }
|
|
741
|
+
const { sub, cb, data, dropped } = session.queue.shift();
|
|
742
|
+
const message = cb ? { id: cb.id, seq: ++cb.seq, args: data, ...(dropped ? { dropped } : {}) } : { id: sub.id, seq: ++sub.seq, data, ...(dropped ? { dropped } : {}) };
|
|
743
|
+
// The write waits for the transport (credit): events and callback calls behind it queue, to `maxQueuedEvents`, and beyond that are dropped and counted.
|
|
744
|
+
try { await session.peer.notify(cb ? 'callback' : 'event', message); } catch { /* the channel is going away */ }
|
|
615
745
|
}
|
|
616
746
|
} finally { session.pumping = false; }
|
|
617
747
|
}
|
|
618
748
|
|
|
749
|
+
// ── Callbacks ─────────────────────────────────────────────────────────────────────────────────────────────────────────
|
|
750
|
+
// A far-side function passed to a call whose entry ends in `(callback)` becomes a stub in the page. The stub is one-way: calling it copies its arguments as plain
|
|
751
|
+
// 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
|
|
752
|
+
// 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.
|
|
753
|
+
|
|
754
|
+
function makeCallback(session, id) {
|
|
755
|
+
// The same function sent again (an id the channel already has) is the same stub.
|
|
756
|
+
const existing = session.callbacks.get(id);
|
|
757
|
+
if (existing) return existing.stub;
|
|
758
|
+
if (session.callbacks.size >= limits.maxCallbacks) throw limitError('maxCallbacks', limits.maxCallbacks, 'too many callbacks on this channel: release some');
|
|
759
|
+
const cb = { id, seq: 0, stamps: [], dropped: 0, dead: false, stub: null };
|
|
760
|
+
cb.stub = function callback(...args) {
|
|
761
|
+
try { deliverCallback(session, cb, args); } catch { cb.dropped++; }
|
|
762
|
+
};
|
|
763
|
+
session.callbacks.set(id, cb);
|
|
764
|
+
return cb.stub;
|
|
765
|
+
}
|
|
766
|
+
|
|
767
|
+
function killCallback(session, id) {
|
|
768
|
+
const cb = session.callbacks.get(id);
|
|
769
|
+
if (cb) { cb.dead = true; session.callbacks.delete(id); }
|
|
770
|
+
return !!cb;
|
|
771
|
+
}
|
|
772
|
+
|
|
773
|
+
function deliverCallback(session, cb, args) {
|
|
774
|
+
if (session.closed || cb.dead || guard?.()) { session.deadCalls++; return; }
|
|
775
|
+
const t = now();
|
|
776
|
+
while (cb.stamps.length && t - cb.stamps[0] >= 1000) cb.stamps.shift();
|
|
777
|
+
// Rate and room first, copy after: a dropped call costs a counter.
|
|
778
|
+
if (cb.stamps.length >= limits.maxCallbacksPerSecond || session.queue.length >= limits.maxQueuedEvents) { cb.dropped++; return; }
|
|
779
|
+
let copy;
|
|
780
|
+
try {
|
|
781
|
+
copy = args.slice(0, limits.maxArgs).map((a) => { const w = toWire(a, { maxDepth: 4, maxBytes: limits.maxCallbackBytes }); return 'v' in w ? w.v : null; });
|
|
782
|
+
toWire(copy, { maxDepth: 6, maxBytes: limits.maxCallbackBytes });
|
|
783
|
+
} catch { cb.dropped++; return; }
|
|
784
|
+
cb.stamps.push(t);
|
|
785
|
+
session.queue.push({ cb, data: copy, dropped: cb.dropped });
|
|
786
|
+
cb.dropped = 0;
|
|
787
|
+
void pump(session);
|
|
788
|
+
}
|
|
789
|
+
|
|
790
|
+
async function releaseCallback(params, ctx) {
|
|
791
|
+
if (!killCallback(ctx.session, params.id)) throw invalid('no such callback');
|
|
792
|
+
return { ok: true };
|
|
793
|
+
}
|
|
794
|
+
|
|
619
795
|
function deliver(session, sub, args) {
|
|
620
796
|
if (session.closed) return;
|
|
621
797
|
try {
|
|
@@ -652,7 +828,7 @@ export function createObjectsServer(options = {}) {
|
|
|
652
828
|
const offered = [...(eventFields[type] ?? []), ...(eventFields['*'] ?? [])];
|
|
653
829
|
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
830
|
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);
|
|
831
|
+
const { cur: source, segs } = await walk({ root, cur: roots[root], segs: [root] }, params.path ?? [], ctx);
|
|
656
832
|
await check('on', root, segs, ctx, { terminal: true, type });
|
|
657
833
|
const kind = sourceMethods(source);
|
|
658
834
|
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' });
|
|
@@ -679,7 +855,7 @@ export function createObjectsServer(options = {}) {
|
|
|
679
855
|
/** Register the protocol's methods on a peer. `who` is the identity of every call unless the transport gives one per call. */
|
|
680
856
|
function attach(peer, { who } = {}) {
|
|
681
857
|
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 };
|
|
858
|
+
const session = { peer, subs: new Map(), queue: [], pumping: false, closed: false, handles: new Map(), callbacks: new Map(), deadCalls: 0 };
|
|
683
859
|
// The end of the channel (the peer left, Stop, a navigation, a revoke) takes every listener out of the page's sources.
|
|
684
860
|
const prior = peer.onClose;
|
|
685
861
|
peer.onClose = (reason) => {
|
|
@@ -687,6 +863,9 @@ export function createObjectsServer(options = {}) {
|
|
|
687
863
|
for (const sub of session.subs.values()) removeSub(sub);
|
|
688
864
|
session.subs.clear();
|
|
689
865
|
session.queue = [];
|
|
866
|
+
session.handles.clear(); // the end of the channel (leaving, Stop, navigation, revoke) releases every handle
|
|
867
|
+
for (const cb of session.callbacks.values()) cb.dead = true; // and kills every callback stub
|
|
868
|
+
session.callbacks.clear();
|
|
690
869
|
try { prior?.(reason); } catch { /* ignore */ }
|
|
691
870
|
};
|
|
692
871
|
const stamps = [];
|
|
@@ -702,14 +881,20 @@ export function createObjectsServer(options = {}) {
|
|
|
702
881
|
try { return await fn(params, call); } catch (e) { if (e instanceof ObjectsError) throw e; throw wrapThrown(e, name); }
|
|
703
882
|
});
|
|
704
883
|
// A key that may use only some roots is told of those only.
|
|
705
|
-
|
|
884
|
+
// 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.
|
|
885
|
+
method('roots', async (_params, call) => ({
|
|
886
|
+
roots: rootNames.filter((name) => typeof call.permit !== 'function' || call.permit(name, 'walk') === true),
|
|
887
|
+
features: ['events', 'callbacks', ...(handleRoots.size ? ['handles'] : [])],
|
|
888
|
+
}));
|
|
706
889
|
method('resolve', resolve);
|
|
707
890
|
method('set', setValue);
|
|
708
891
|
method('describe', describe);
|
|
709
892
|
method('snapshot', snapshot);
|
|
710
893
|
method('subscribe', subscribe);
|
|
711
894
|
method('unsubscribe', unsubscribe);
|
|
712
|
-
|
|
895
|
+
method('release', releaseHandle);
|
|
896
|
+
method('releaseCallback', releaseCallback);
|
|
897
|
+
return { limits, handleCount: () => session.handles.size, callbackCount: () => session.callbacks.size, deadCallbackCalls: () => session.deadCalls };
|
|
713
898
|
}
|
|
714
899
|
|
|
715
900
|
return { attach, limits: Object.freeze({ ...limits }), rootNames: rootNames.slice() };
|
|
@@ -805,11 +990,33 @@ export class NonValue {
|
|
|
805
990
|
toString() { return `[remote ${this.kind}${this.type ? ` ${this.type}` : ''}${this.text ? `: ${this.text}` : ''}]`; }
|
|
806
991
|
}
|
|
807
992
|
|
|
808
|
-
const decodeResult = (res) => {
|
|
993
|
+
const decodeResult = (res, session) => {
|
|
994
|
+
if (res && typeof res === 'object' && typeof res.h === 'string' && session) {
|
|
995
|
+
if (!session.features?.includes('handles')) throw new ObjectsError(OBJECTS_ERROR.FAILED, 'the host returned a handle but did not say it supports handles: it is not a host this client understands', { reason: 'unsupported' });
|
|
996
|
+
return new RemoteHandle(session, res);
|
|
997
|
+
}
|
|
809
998
|
if (res && typeof res === 'object' && 'u' in res) return res.u === 'undefined' ? undefined : new NonValue(res);
|
|
810
999
|
return res?.v;
|
|
811
1000
|
};
|
|
812
1001
|
|
|
1002
|
+
const HANDLE_ID = new WeakMap();
|
|
1003
|
+
|
|
1004
|
+
/**
|
|
1005
|
+
* What a value that cannot be cloned arrives as on a root that opted in to handles: an opaque token. Nothing of it is enumerable (the id is not
|
|
1006
|
+
* there to copy), it is not thenable, and it is not an argument. `use(handle)` makes a reference that stands on it; `release(handle)` gives its place back.
|
|
1007
|
+
*/
|
|
1008
|
+
export class RemoteHandle {
|
|
1009
|
+
constructor(session, wire) {
|
|
1010
|
+
HANDLE_ID.set(this, { session, id: wire.h });
|
|
1011
|
+
Object.defineProperty(this, 'kind', { value: wire.kind, enumerable: false });
|
|
1012
|
+
Object.defineProperty(this, 'type', { value: wire.type, enumerable: false });
|
|
1013
|
+
Object.defineProperty(this, 'preview', { value: wire.preview, enumerable: false });
|
|
1014
|
+
Object.freeze(this);
|
|
1015
|
+
}
|
|
1016
|
+
|
|
1017
|
+
toString() { return `[remote handle${this.type ? ` ${this.type}` : ''}]`; }
|
|
1018
|
+
}
|
|
1019
|
+
|
|
813
1020
|
function asObjectsError(e, session) {
|
|
814
1021
|
if (e instanceof ObjectsError) return e;
|
|
815
1022
|
const closing = session?.closing ? ` (${session.closing})` : '';
|
|
@@ -828,6 +1035,7 @@ function plainArgs(args) {
|
|
|
828
1035
|
let visits = 0;
|
|
829
1036
|
const walk = (v, depth) => {
|
|
830
1037
|
if (typeof v === 'function') throw new TypeError('a function or a remote reference cannot be sent as an argument: only plain data crosses (a reference is a path: await it to get its value first)');
|
|
1038
|
+
if (v instanceof RemoteHandle) throw new TypeError('a handle cannot be sent as an argument: it means something only on its own session, and only plain data crosses');
|
|
831
1039
|
if (v === null || typeof v !== 'object' || depth > 8 || ++visits > 2000) return;
|
|
832
1040
|
if (ArrayBuffer.isView(v)) return;
|
|
833
1041
|
for (const k of Object.keys(v)) walk(v[k], depth + 1);
|
|
@@ -836,8 +1044,11 @@ function plainArgs(args) {
|
|
|
836
1044
|
return args;
|
|
837
1045
|
}
|
|
838
1046
|
|
|
839
|
-
|
|
840
|
-
|
|
1047
|
+
/** What a request names as its start: the handle this reference stands on, or its root. */
|
|
1048
|
+
const target = (state) => (state.handle !== undefined ? { handle: state.handle } : { root: state.root });
|
|
1049
|
+
|
|
1050
|
+
function makeRef(session, root, ops, handle) {
|
|
1051
|
+
const state = { session, root, ops, handle };
|
|
841
1052
|
const readOnly = (what) => () => { throw new TypeError(what); };
|
|
842
1053
|
const handler = {
|
|
843
1054
|
get(_target, key) {
|
|
@@ -847,7 +1058,7 @@ function makeRef(session, root, ops) {
|
|
|
847
1058
|
// `await ref` sends the whole chain in ONE request. A remote property really named "then" is reached with get(ref, 'then').
|
|
848
1059
|
return (onFulfilled, onRejected) => send(state).then(onFulfilled, onRejected);
|
|
849
1060
|
}
|
|
850
|
-
return makeRef(session, root, [...ops, { get: key }]);
|
|
1061
|
+
return makeRef(session, root, [...ops, { get: key }], handle);
|
|
851
1062
|
},
|
|
852
1063
|
set(_t, key) { throw new TypeError(`cannot assign to ${String(key)} of a remote reference with "=": assignment cannot be awaited or report a refusal. Use await set(ref, ${JSON.stringify(String(key))}, value)`); },
|
|
853
1064
|
defineProperty: readOnly('a remote reference cannot be defined on: use set(ref, key, value)'),
|
|
@@ -856,22 +1067,52 @@ function makeRef(session, root, ops) {
|
|
|
856
1067
|
apply(_t, _this, args) {
|
|
857
1068
|
const last = ops[ops.length - 1];
|
|
858
1069
|
if (!last || !('get' in last)) throw new TypeError('only a method reached by name can be called (win.app.cart.add(x)); call a path, not a result');
|
|
859
|
-
return makeRef(session, root, [...ops.slice(0, -1), { call: last.get,
|
|
1070
|
+
return makeRef(session, root, [...ops.slice(0, -1), { call: last.get, ...callArgs(args) }], handle);
|
|
860
1071
|
},
|
|
861
1072
|
construct(_t, args) {
|
|
862
1073
|
const last = ops[ops.length - 1];
|
|
863
1074
|
if (!last || !('get' in last)) throw new TypeError('only a constructor reached by name can be constructed (new win.app.Cart())');
|
|
864
|
-
return makeRef(session, root, [...ops.slice(0, -1), { construct: last.get,
|
|
1075
|
+
return makeRef(session, root, [...ops.slice(0, -1), { construct: last.get, ...callArgs(args) }], handle);
|
|
865
1076
|
},
|
|
866
1077
|
};
|
|
867
1078
|
// A function as the target so the proxy can be called and constructed.
|
|
868
1079
|
return new Proxy(function remote() {}, handler);
|
|
869
1080
|
}
|
|
870
1081
|
|
|
1082
|
+
/**
|
|
1083
|
+
* The arguments of a call: a function at the top level of the list (not a reference, not a handle) is a CALLBACK: its place is null on the wire, listed in `fns`
|
|
1084
|
+
* (until it is sent, when `send` gives it an id). A function deeper in an argument, a reference and a handle are refused where they are written.
|
|
1085
|
+
*/
|
|
1086
|
+
function callArgs(args) {
|
|
1087
|
+
const fns = [];
|
|
1088
|
+
const copy = args.map((a, i) => {
|
|
1089
|
+
if (typeof a === 'function' && !a[BRAND]) { fns.push([i, a]); return null; }
|
|
1090
|
+
return a;
|
|
1091
|
+
});
|
|
1092
|
+
plainArgs(copy);
|
|
1093
|
+
return fns.length ? { args: copy, fns } : { args: copy };
|
|
1094
|
+
}
|
|
1095
|
+
|
|
1096
|
+
const CALLBACK_OF = new WeakMap();
|
|
1097
|
+
|
|
1098
|
+
/** The wire form of an op: its callbacks get ids (one per function per channel, the same id each time it is sent) and `fns` goes. */
|
|
1099
|
+
function wireOp(session, op) {
|
|
1100
|
+
if (!op.fns) return op;
|
|
1101
|
+
const { fns, ...rest } = op;
|
|
1102
|
+
return { ...rest, callbacks: fns.map(([i, fn]) => {
|
|
1103
|
+
let rec = CALLBACK_OF.get(fn);
|
|
1104
|
+
if (!rec || rec.session !== session || rec.released) { rec = { session, id: session.nextCb++, released: false }; CALLBACK_OF.set(fn, rec); session.callbacks.set(rec.id, fn); }
|
|
1105
|
+
return [i, rec.id];
|
|
1106
|
+
}) };
|
|
1107
|
+
}
|
|
1108
|
+
|
|
871
1109
|
async function send(state, { signal } = {}) {
|
|
872
|
-
const { session
|
|
1110
|
+
const { session } = state;
|
|
873
1111
|
try {
|
|
874
|
-
|
|
1112
|
+
// A function would reach a host that does not know callbacks as null: refuse to send it (a named error), unless the host said it supports them.
|
|
1113
|
+
if (state.ops.some((op) => op.fns) && !session.features?.includes('callbacks')) throw new ObjectsError(OBJECTS_ERROR.FAILED, 'this host does not support callbacks (it did not say so): a function cannot be passed to it', { reason: 'unsupported' });
|
|
1114
|
+
const ops = state.ops.map((op) => wireOp(session, op));
|
|
1115
|
+
return decodeResult(await session.peer.request('resolve', { ...target(state), ops }, { signal, ...(session.timeoutMs ? { timeoutMs: session.timeoutMs } : {}) }), session);
|
|
875
1116
|
} catch (e) { throw asObjectsError(e, session); }
|
|
876
1117
|
}
|
|
877
1118
|
|
|
@@ -896,7 +1137,7 @@ export function get(ref, ...keys) {
|
|
|
896
1137
|
export async function set(ref, key, value) {
|
|
897
1138
|
const { state, keys } = pathOf(ref, 'set');
|
|
898
1139
|
plainArgs([value]);
|
|
899
|
-
try { await state.session.peer.request('set', {
|
|
1140
|
+
try { await state.session.peer.request('set', { ...target(state), path: [...keys, String(key)], value }); } catch (e) { throw asObjectsError(e, state.session); }
|
|
900
1141
|
}
|
|
901
1142
|
|
|
902
1143
|
/** Call a method reached by name with these (plain-data) arguments: `await call(win.app.cart.add, { sku: 'A1' })`; for a method named `then`, `call(ref, ...)`. */
|
|
@@ -904,7 +1145,7 @@ export function call(ref, ...args) {
|
|
|
904
1145
|
const state = stateOf(ref);
|
|
905
1146
|
const last = state.ops[state.ops.length - 1];
|
|
906
1147
|
if (!last || !('get' in last)) throw new TypeError('call needs a method reached by name');
|
|
907
|
-
return send({ ...state, ops: [...state.ops.slice(0, -1), { call: last.get,
|
|
1148
|
+
return send({ ...state, ops: [...state.ops.slice(0, -1), { call: last.get, ...callArgs(args) }] });
|
|
908
1149
|
}
|
|
909
1150
|
|
|
910
1151
|
/** `new` a constructor reached by name: `await construct(win.app.Cart, 'A')`. */
|
|
@@ -912,14 +1153,14 @@ export function construct(ref, ...args) {
|
|
|
912
1153
|
const state = stateOf(ref);
|
|
913
1154
|
const last = state.ops[state.ops.length - 1];
|
|
914
1155
|
if (!last || !('get' in last)) throw new TypeError('construct needs a constructor reached by name');
|
|
915
|
-
return send({ ...state, ops: [...state.ops.slice(0, -1), { construct: last.get,
|
|
1156
|
+
return send({ ...state, ops: [...state.ops.slice(0, -1), { construct: last.get, ...callArgs(args) }] });
|
|
916
1157
|
}
|
|
917
1158
|
|
|
918
1159
|
/** A bounded deep copy: `await snapshot(win.app.state, { depth: 3, maxBytes: 256_000 })`. Subtrees deeper than `depth` are `null`. */
|
|
919
1160
|
export async function snapshot(ref, { depth, maxBytes, signal } = {}) {
|
|
920
1161
|
const { state, keys } = pathOf(ref, 'snapshot');
|
|
921
1162
|
try {
|
|
922
|
-
return decodeResult(await state.session.peer.request('snapshot', {
|
|
1163
|
+
return decodeResult(await state.session.peer.request('snapshot', { ...target(state), path: keys, ...(depth !== undefined ? { depth } : {}), ...(maxBytes !== undefined ? { maxBytes } : {}) }, { signal }));
|
|
923
1164
|
} catch (e) { throw asObjectsError(e, state.session); }
|
|
924
1165
|
}
|
|
925
1166
|
|
|
@@ -932,6 +1173,8 @@ export async function on(ref, type, listener, { fields, onError } = {}) {
|
|
|
932
1173
|
const { state, keys } = pathOf(ref, 'on');
|
|
933
1174
|
if (typeof listener !== 'function') throw new TypeError('on needs a listener function: listener(data, { type, seq, dropped })');
|
|
934
1175
|
const { session } = state;
|
|
1176
|
+
if (state.handle !== undefined) throw new TypeError('events are not offered through a handle: name the source by its path');
|
|
1177
|
+
if (!session.features?.includes('events')) throw new ObjectsError(OBJECTS_ERROR.FAILED, 'this host does not support events (it did not say so)', { reason: 'unsupported' });
|
|
935
1178
|
const id = session.nextSub++;
|
|
936
1179
|
// Registered before the request: an event can follow the answer at once.
|
|
937
1180
|
session.subs.set(id, { listener, onError, type });
|
|
@@ -953,7 +1196,7 @@ export async function off(unsubscribe) {
|
|
|
953
1196
|
/** 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. */
|
|
954
1197
|
export async function describe(ref, { signal } = {}) {
|
|
955
1198
|
const { state, keys } = pathOf(ref, 'describe');
|
|
956
|
-
try { return await state.session.peer.request('describe', {
|
|
1199
|
+
try { return await state.session.peer.request('describe', { ...target(state), path: keys }, { signal }); } catch (e) { throw asObjectsError(e, state.session); }
|
|
957
1200
|
}
|
|
958
1201
|
|
|
959
1202
|
/**
|
|
@@ -961,9 +1204,17 @@ export async function describe(ref, { signal } = {}) {
|
|
|
961
1204
|
* @param {object} peer
|
|
962
1205
|
* @param {{ timeoutMs?: number }} [options]
|
|
963
1206
|
*/
|
|
964
|
-
export async function createObjectsClient(peer, { timeoutMs } = {}) {
|
|
1207
|
+
export async function createObjectsClient(peer, { timeoutMs, onCallbackError, onCallbackDropped } = {}) {
|
|
965
1208
|
if (typeof peer?.request !== 'function') throw new TypeError('createObjectsClient: the peer needs request(method, params)');
|
|
966
|
-
const session = { peer, closing: null, timeoutMs, subs: new Map(), nextSub: 1 };
|
|
1209
|
+
const session = { peer, closing: null, timeoutMs, subs: new Map(), nextSub: 1, callbacks: new Map(), nextCb: 1 };
|
|
1210
|
+
// The page called a stub of one of our functions: run it here. Its errors and its return value stay here (the stub is one-way); `onCallbackDropped({ dropped })`
|
|
1211
|
+
// is told, before the call that follows them, how many calls the host dropped (rate, size, a slow channel).
|
|
1212
|
+
peer.onNotification?.('callback', (params) => {
|
|
1213
|
+
const fn = session.callbacks.get(params?.id);
|
|
1214
|
+
if (!fn || !Array.isArray(params.args)) return;
|
|
1215
|
+
if (Number.isSafeInteger(params.dropped) && params.dropped > 0) { try { onCallbackDropped?.({ dropped: params.dropped, fn }); } catch { /* ours */ } }
|
|
1216
|
+
try { fn(...params.args); } catch (e) { try { onCallbackError?.(e); } catch { /* ours */ } }
|
|
1217
|
+
});
|
|
967
1218
|
// 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
1219
|
peer.onNotification?.('event', (params) => {
|
|
969
1220
|
const sub = session.subs.get(params?.id);
|
|
@@ -974,7 +1225,12 @@ export async function createObjectsClient(peer, { timeoutMs } = {}) {
|
|
|
974
1225
|
});
|
|
975
1226
|
peer.onNotification?.('closing', (params) => { session.closing = typeof params?.reason === 'string' ? clip(params.reason, TEXT_MAX) : 'closing'; });
|
|
976
1227
|
let roots;
|
|
977
|
-
try {
|
|
1228
|
+
try {
|
|
1229
|
+
const answer = await peer.request('roots', {});
|
|
1230
|
+
roots = answer?.roots;
|
|
1231
|
+
// What the host says it supports; a host that says nothing (before 0.48.0) supports none of the three.
|
|
1232
|
+
session.features = Array.isArray(answer?.features) ? answer.features.filter((f) => typeof f === 'string') : [];
|
|
1233
|
+
} catch (e) { throw asObjectsError(e, session); }
|
|
978
1234
|
if (!Array.isArray(roots)) throw new ObjectsError(OBJECTS_ERROR.FAILED, 'the host did not list its roots', { reason: 'bad-reply' });
|
|
979
1235
|
const page = {};
|
|
980
1236
|
for (const name of roots) if (typeof name === 'string' && !ALWAYS_REFUSED.has(name)) page[name] = makeRef(session, name, []);
|
|
@@ -983,6 +1239,31 @@ export async function createObjectsClient(peer, { timeoutMs } = {}) {
|
|
|
983
1239
|
}
|
|
984
1240
|
|
|
985
1241
|
/** End the connection behind what `openObjects()` returned. */
|
|
1242
|
+
/** A reference that stands on a handle: `await use(handle).items.length`. Its path is the one that produced the handle, extended by what you name. */
|
|
1243
|
+
export function use(handle) {
|
|
1244
|
+
const rec = handle instanceof RemoteHandle ? HANDLE_ID.get(handle) : undefined;
|
|
1245
|
+
if (!rec) throw new TypeError('use needs a handle (what awaiting a reference returns on a root that opted in to handles)');
|
|
1246
|
+
return makeRef(rec.session, null, [], rec.id);
|
|
1247
|
+
}
|
|
1248
|
+
|
|
1249
|
+
/** Give a handle's place back. Releasing a released handle does nothing. Everything is released when the channel ends. */
|
|
1250
|
+
export async function release(handle) {
|
|
1251
|
+
// A function that was passed as a callback: its stub in the page dies, and a call of it is a counted no-op.
|
|
1252
|
+
if (typeof handle === 'function' && CALLBACK_OF.has(handle)) {
|
|
1253
|
+
const cb = CALLBACK_OF.get(handle);
|
|
1254
|
+
if (cb.released) return;
|
|
1255
|
+
cb.released = true;
|
|
1256
|
+
cb.session.callbacks.delete(cb.id);
|
|
1257
|
+
try { await cb.session.peer.request('releaseCallback', { id: cb.id }); } catch (e) { throw asObjectsError(e, cb.session); }
|
|
1258
|
+
return;
|
|
1259
|
+
}
|
|
1260
|
+
const rec = handle instanceof RemoteHandle ? HANDLE_ID.get(handle) : undefined;
|
|
1261
|
+
if (!rec) throw new TypeError('release needs a handle, or a function that was passed as a callback');
|
|
1262
|
+
if (rec.released) return;
|
|
1263
|
+
rec.released = true;
|
|
1264
|
+
try { await rec.session.peer.request('release', { handle: rec.id }); } catch (e) { throw asObjectsError(e, rec.session); }
|
|
1265
|
+
}
|
|
1266
|
+
|
|
986
1267
|
export async function closeObjects(page) {
|
|
987
1268
|
const session = page?.[SESSION];
|
|
988
1269
|
if (!session) throw new TypeError('closeObjects: expected what openObjects() returned');
|
package/src/objects.d.ts
CHANGED
|
@@ -18,6 +18,22 @@ export class ObjectsError extends Error {
|
|
|
18
18
|
}
|
|
19
19
|
|
|
20
20
|
/** What a remote value that cannot be cloned arrives as: named, never a handle. `kind`: `function`, `symbol`, `bigint`, `number` (too large for the wire), `Date`, `RegExp`, `Error`, `object`. */
|
|
21
|
+
/**
|
|
22
|
+
* What a value that cannot be cloned arrives as on a root that opted in to handles: an opaque token, nothing of it enumerable, not thenable, not an argument.
|
|
23
|
+
* It stands at the path that produced it: `use(handle)` makes a reference that continues that path; `release(handle)` gives its place back.
|
|
24
|
+
*/
|
|
25
|
+
export class RemoteHandle {
|
|
26
|
+
readonly kind: 'function' | 'object';
|
|
27
|
+
/** The class name, or a function's name. */
|
|
28
|
+
readonly type?: string;
|
|
29
|
+
/** Up to 8 member names, only if a `get` entry names the handle's path. */
|
|
30
|
+
readonly preview?: { keys: string[] };
|
|
31
|
+
}
|
|
32
|
+
/** A reference that stands on a handle: `await use(handle).items.length`. Judged by the producing path extended by what you name. */
|
|
33
|
+
export function use(handle: RemoteHandle): any;
|
|
34
|
+
/** Give a handle's place back (releasing a released handle does nothing); or kill the stub of a function that was passed as a callback. */
|
|
35
|
+
export function release(handleOrCallback: RemoteHandle | ((...args: any[]) => unknown)): Promise<void>;
|
|
36
|
+
|
|
21
37
|
export class NonValue {
|
|
22
38
|
constructor(wire: { u: string; type?: string; text?: string });
|
|
23
39
|
readonly kind: string;
|
|
@@ -52,6 +68,14 @@ export interface ObjectsLimits {
|
|
|
52
68
|
maxEventBytes: number;
|
|
53
69
|
/** Events waiting for the transport's credit, per channel; more are dropped and counted. Default 100. */
|
|
54
70
|
maxQueuedEvents: number;
|
|
71
|
+
/** Handles per channel on roots that opted in; more are refused by name, nothing is evicted. Default 64. */
|
|
72
|
+
maxHandles: number;
|
|
73
|
+
/** Callbacks (stubs of far-side functions) per channel; more are refused. Default 16. */
|
|
74
|
+
maxCallbacks: number;
|
|
75
|
+
/** Calls of one callback per second; the rest are dropped and counted. Default 20. */
|
|
76
|
+
maxCallbacksPerSecond: number;
|
|
77
|
+
/** Bytes of the arguments of one callback call; a bigger one is dropped and counted. Default 16384. */
|
|
78
|
+
maxCallbackBytes: number;
|
|
55
79
|
}
|
|
56
80
|
export const OBJECTS_DEFAULT_LIMITS: Readonly<ObjectsLimits>;
|
|
57
81
|
|
|
@@ -61,6 +85,7 @@ export const NEEDS_LISTING: ReadonlyArray<readonly string[]>;
|
|
|
61
85
|
/** 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. */
|
|
62
86
|
export interface ObjectsAllow {
|
|
63
87
|
get?: string[];
|
|
88
|
+
// (`call` entries may end in `(callback)`: the call accepts functions as arguments, which reach the page as one-way stubs.)
|
|
64
89
|
call?: string[];
|
|
65
90
|
set?: string[];
|
|
66
91
|
/** 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. */
|
|
@@ -72,6 +97,8 @@ export interface ObjectsOperation {
|
|
|
72
97
|
kind: 'get' | 'call' | 'construct' | 'set' | 'on' | 'describe' | 'snapshot';
|
|
73
98
|
/** For `on`: the event type. */
|
|
74
99
|
type?: string;
|
|
100
|
+
/** For a call that carries callbacks: how many. */
|
|
101
|
+
callbacks?: number;
|
|
75
102
|
root: string;
|
|
76
103
|
/** The path below the root. */
|
|
77
104
|
path: string[];
|
|
@@ -82,8 +109,16 @@ export interface ObjectsOperation {
|
|
|
82
109
|
export interface ObjectsServerOptions {
|
|
83
110
|
/** The named roots: all that is reachable. */
|
|
84
111
|
roots: Record<string, object>;
|
|
85
|
-
/** `'values'`
|
|
112
|
+
/** `'values'` (the default). Handles are chosen per root with `handles`, not here. */
|
|
86
113
|
mode?: 'values';
|
|
114
|
+
/**
|
|
115
|
+
* Roots that opt in to handles: a value that cannot be cloned comes back as an opaque `RemoteHandle`, judged by the path that produced it. `nodes: true` is a
|
|
116
|
+
* second opt-in, for DOM nodes, windows and documents (control of the page). Needs `random`.
|
|
117
|
+
*/
|
|
118
|
+
handles?: Record<string, { nodes?: boolean; wideEntries?: boolean }>;
|
|
119
|
+
// `wideEntries: true` acknowledges a wildcard in `allow.call` or `allow.set` on that root (without it the host refuses to start: list the paths, or say so).
|
|
120
|
+
/** The random source for handle ids: `(n) => bytes` from `crypto.getRandomValues`. `exposeObjects` defaults to the platform's, the page host to its window's. */
|
|
121
|
+
random?: (n: number) => Uint8Array;
|
|
87
122
|
allow?: ObjectsAllow;
|
|
88
123
|
/** Asked for every operation the allow-list let through; anything but `true` (a throw included) refuses. */
|
|
89
124
|
authorize?: (who: ObjectsWho, op: ObjectsOperation) => boolean | Promise<boolean>;
|
|
@@ -119,7 +154,13 @@ export function createObjectsServer(options: ObjectsServerOptions): {
|
|
|
119
154
|
export function createDuplexPeer(options: { send(message: object): void; maxMessageBytes?: number }): ObjectsPeer & { receive(message: unknown): void; close(reason?: string): void; readonly closed: boolean };
|
|
120
155
|
|
|
121
156
|
/** The client half over any peer: the roots, as lazy references. */
|
|
122
|
-
export function createObjectsClient<T = Record<string, any>>(peer: Pick<ObjectsPeer, 'request'> & Partial<ObjectsPeer>, options?: {
|
|
157
|
+
export function createObjectsClient<T = Record<string, any>>(peer: Pick<ObjectsPeer, 'request'> & Partial<ObjectsPeer>, options?: {
|
|
158
|
+
timeoutMs?: number;
|
|
159
|
+
/** A callback of ours threw: it stays here, the page never hears of it. */
|
|
160
|
+
onCallbackError?: (error: unknown) => void;
|
|
161
|
+
/** The host dropped calls of a callback (rate, size, a slow channel) before the one that follows. */
|
|
162
|
+
onCallbackDropped?: (info: { dropped: number; fn: (...args: any[]) => unknown }) => void;
|
|
163
|
+
}): Promise<T>;
|
|
123
164
|
|
|
124
165
|
/** `exposeObjects`: the rpc handler for `wsh-objects`. Usable as `rpc: { 'wsh-objects': exposeObjects({ roots, allow }) }` in any host. */
|
|
125
166
|
export interface ObjectsHandler {
|
package/src/objects.mjs
CHANGED
|
@@ -28,12 +28,15 @@ 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, on, off, closeObjects,
|
|
31
|
+
get, set, call, construct, snapshot, describe, on, off, use, release, RemoteHandle, 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
|
+
/** The platform's CSPRNG for handle ids, where the embedder gave none (the page host gives its window's). */
|
|
38
|
+
const defaultRandom = (n) => globalThis.crypto.getRandomValues(new Uint8Array(n));
|
|
39
|
+
|
|
37
40
|
/** 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
41
|
function channelPeer(channel, host = {}) {
|
|
39
42
|
// 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.
|
|
@@ -64,7 +67,7 @@ function channelPeer(channel, host = {}) {
|
|
|
64
67
|
* @param {object} [options.limits] - `maxOps`, `maxArgs`, `maxDepth`, `maxValueBytes`, `maxKeys`, `maxRequestsPerSecond`, `callTimeoutMs`
|
|
65
68
|
*/
|
|
66
69
|
export function exposeObjects(options = {}) {
|
|
67
|
-
const server = createObjectsServer({ timers: defaultTimers, ...options });
|
|
70
|
+
const server = createObjectsServer({ timers: defaultTimers, random: defaultRandom, ...options });
|
|
68
71
|
const sessions = new Set();
|
|
69
72
|
const handler = (channel, ctx = {}) => {
|
|
70
73
|
const who = { username: ctx.user ?? null, fingerprint: ctx.fingerprint ?? null };
|
package/src/page-host.d.ts
CHANGED
|
@@ -165,9 +165,9 @@ export interface WshPageHostOptions {
|
|
|
165
165
|
/**
|
|
166
166
|
* Object access (`wsh-objects`, `values` mode), off unless written: named roots, each with its allow-lists by operation (paths RELATIVE to the root:
|
|
167
167
|
* `'document.title'`, `'app.**'`; nothing allowed by default). A root named `window` is the window that was passed; another name needs `object`.
|
|
168
|
-
* `mode: 'handles'` is
|
|
168
|
+
* `mode: 'handles'` is this root's own opt-in to handles (`nodes: true` a second, for nodes and the window graph). 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; eventFields?: Record<string, string[]> }>;
|
|
170
|
+
expose?: Record<string, { mode?: 'values' | 'handles'; nodes?: boolean; wideEntries?: boolean; 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
|
@@ -72,13 +72,17 @@ function exposedRoots(window, expose) {
|
|
|
72
72
|
const allow = { get: [], call: [], set: [], on: [] };
|
|
73
73
|
const authorizers = new Map();
|
|
74
74
|
const eventFields = {};
|
|
75
|
+
const handles = {};
|
|
75
76
|
let limits;
|
|
76
77
|
for (const name of names) {
|
|
77
78
|
const cfg = expose[name];
|
|
78
79
|
if (!isObj(cfg)) throw new TypeError(`createPageHost: expose.${name} must be { mode, allow }`);
|
|
79
|
-
if (cfg.mode
|
|
80
|
-
if (
|
|
81
|
-
|
|
80
|
+
if (cfg.mode !== undefined && cfg.mode !== 'values' && cfg.mode !== 'handles') throw new TypeError("createPageHost: expose mode must be 'values' (the default) or 'handles'");
|
|
81
|
+
if (typeof cfg.allow === 'string') throw new TypeError('createPageHost: expose allow must be { get, call, set, on }: a wide-open string is not accepted, and the allow-lists apply to handles too');
|
|
82
|
+
// 'handles' is this root's own opt-in; `nodes: true` is a second one, for nodes, windows and documents: control of the page.
|
|
83
|
+
if (cfg.nodes !== undefined && (cfg.mode !== 'handles' || typeof cfg.nodes !== 'boolean')) throw new TypeError(`createPageHost: expose.${name}.nodes is a boolean, and only for mode: 'handles'`);
|
|
84
|
+
if (cfg.wideEntries !== undefined && (cfg.mode !== 'handles' || typeof cfg.wideEntries !== 'boolean')) throw new TypeError(`createPageHost: expose.${name}.wideEntries is a boolean, and only for mode: 'handles'`);
|
|
85
|
+
if (cfg.mode === 'handles') handles[name] = { nodes: cfg.nodes === true, wideEntries: cfg.wideEntries === true };
|
|
82
86
|
const object = cfg.object ?? (name === 'window' ? window : undefined);
|
|
83
87
|
if (object === undefined) throw new TypeError(`createPageHost: expose.${name}: only a root named "window" is the window; give { object } for another root`);
|
|
84
88
|
roots[name] = object;
|
|
@@ -96,7 +100,7 @@ function exposedRoots(window, expose) {
|
|
|
96
100
|
if (cfg.limits !== undefined) limits = { ...limits, ...cfg.limits };
|
|
97
101
|
}
|
|
98
102
|
const authorize = authorizers.size ? (who, op) => (authorizers.has(op.root) ? authorizers.get(op.root)(who, { ...op, path: op.path }) : true) : undefined;
|
|
99
|
-
return { roots, allow, authorize, limits, eventFields };
|
|
103
|
+
return { roots, allow, authorize, limits, eventFields, handles };
|
|
100
104
|
}
|
|
101
105
|
|
|
102
106
|
/** The indicator in the page: one row per connected key, with the key's fingerprint and a Stop control. */
|
|
@@ -152,7 +156,7 @@ function createDomIndicator(window, { name }) {
|
|
|
152
156
|
* optionally the rendezvous id (default: a fresh random one, exposed as `host.rendezvousId`)
|
|
153
157
|
* @param {Record<string, { mode?: 'values', allow?: { get?: string[], call?: string[], set?: string[] }, authorize?: Function, limits?: object, object?: object }>} [options.expose]
|
|
154
158
|
* object access, off unless written: named roots (`window` is the window passed; another name needs `object`), each with its allow-lists by
|
|
155
|
-
* operation (paths relative to the root: `'document.title'`, `'app.**'`; nothing allowed by default). `mode: 'handles'` is
|
|
159
|
+
* 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).
|
|
156
160
|
* See `@johnhenry/wsh/objects` for what `values` mode promises.
|
|
157
161
|
* @param {string} options.name - what this tab is called (shown in the indicator, the `serverInfo` of the MCP server)
|
|
158
162
|
* @param {string | Uint8Array | Array<string | Uint8Array>} options.authorizedKeys - who may log in, as `authorized_keys` lines (with their
|
|
@@ -253,7 +257,9 @@ export async function createPageHost(options = {}) {
|
|
|
253
257
|
guard: () => gone() ?? mcp.guard?.() ?? null,
|
|
254
258
|
}) : null;
|
|
255
259
|
const objectsHandler = exposed ? exposeObjects({
|
|
256
|
-
roots: exposed.roots, allow: exposed.allow, authorize: exposed.authorize, limits: exposed.limits, eventFields: exposed.eventFields, timers,
|
|
260
|
+
roots: exposed.roots, allow: exposed.allow, authorize: exposed.authorize, limits: exposed.limits, eventFields: exposed.eventFields, handles: exposed.handles, timers,
|
|
261
|
+
// Handle ids come from the served window's own CSPRNG.
|
|
262
|
+
random: (n) => window.crypto.getRandomValues(new Uint8Array(n)),
|
|
257
263
|
guard: () => gone(),
|
|
258
264
|
}) : null;
|
|
259
265
|
/** What each handler tells and ends: the sessions of a key, or all of them. */
|