@johnhenry/wsh 0.47.0 → 0.49.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.
@@ -24,6 +24,8 @@
24
24
  * chain continues on the RESULT, whose path is the callee with `()`: `window.app.getCart().items`. Nothing is allowed by default.
25
25
  */
26
26
 
27
+ import { callerIdentity } from './key-names.mjs';
28
+
27
29
  export const OBJECTS_PROTOCOL = 'wsh-objects';
28
30
 
29
31
  /** Error codes, JSON-RPC's where one fits (`reason` in `data` says which rule). */
@@ -62,6 +64,14 @@ export const OBJECTS_DEFAULT_LIMITS = Object.freeze({
62
64
  maxKeys: 200,
63
65
  /** Requests accepted per second, per attached peer. */
64
66
  maxRequestsPerSecond: 50,
67
+ /** Handles per channel (on roots that opted in): more are refused, nothing is evicted. */
68
+ maxHandles: 64,
69
+ /** Callbacks (stubs of far-side functions) per channel: more are refused. */
70
+ maxCallbacks: 16,
71
+ /** Calls of one callback per second; the rest are dropped and counted. */
72
+ maxCallbacksPerSecond: 20,
73
+ /** Bytes of the arguments of one callback call; a bigger one is dropped and counted. */
74
+ maxCallbackBytes: 16 * 1024,
65
75
  /** Event subscriptions per channel. */
66
76
  maxSubscriptions: 16,
67
77
  /** Events delivered per second, per subscription; the rest are dropped and counted. */
@@ -91,6 +101,10 @@ export const NEEDS_LISTING = Object.freeze([
91
101
  ]);
92
102
 
93
103
  const KEY_MAX = 256;
104
+ const CALLBACK_SUFFIX = '(callback)';
105
+ const B64URL = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_';
106
+ /** 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. */
107
+ const GRAPH_MEMBERS = Object.freeze(['ownerDocument', 'defaultView', 'parentNode', 'parentElement', 'getRootNode', 'contentWindow', 'contentDocument', 'self', 'window', 'top', 'parent', 'frames', 'opener', 'globalThis']);
94
108
  const EVENT_TYPE_RE = /^[A-Za-z0-9_$:.-]{1,128}$/;
95
109
 
96
110
  function checkKey(key) {
@@ -106,9 +120,18 @@ function checkKey(key) {
106
120
  function compileList(list, kind) {
107
121
  if (list === undefined || list === null) return [];
108
122
  if (!Array.isArray(list)) throw new TypeError(`exposeObjects: allow.${kind} must be an array of path patterns`);
109
- return list.map((entry) => {
110
- if (typeof entry !== 'string' || entry === '') throw new TypeError(`exposeObjects: allow.${kind} entries must be non-empty strings`);
111
- const segs = entry.split('.');
123
+ return list.map((original) => {
124
+ if (typeof original !== 'string' || original === '') throw new TypeError(`exposeObjects: allow.${kind} entries must be non-empty strings`);
125
+ // A call entry that ends in `(callback)` says the call accepts functions as arguments (they arrive as stubs the page can call, one-way).
126
+ let entry = original;
127
+ let callbacks = false;
128
+ if (entry.endsWith(CALLBACK_SUFFIX)) {
129
+ if (kind !== 'call') throw new TypeError(`exposeObjects: allow.${kind} entry ${JSON.stringify(original)}: only a call entry can accept callbacks`);
130
+ entry = entry.slice(0, -CALLBACK_SUFFIX.length);
131
+ callbacks = true;
132
+ }
133
+ if (entry.includes(CALLBACK_SUFFIX)) throw new TypeError(`exposeObjects: allow.${kind} entry ${JSON.stringify(original)}: "(callback)" ends an entry`);
134
+ const segs = Object.assign(entry.split('.'), { callbacks });
112
135
  for (const s of segs) {
113
136
  if (s === '') throw new TypeError(`exposeObjects: allow.${kind} entry ${JSON.stringify(entry)} has an empty segment`);
114
137
  if (ALWAYS_REFUSED.has(s)) throw new TypeError(`exposeObjects: allow.${kind} entry ${JSON.stringify(entry)} names "${s}", which is never reachable`);
@@ -345,10 +368,10 @@ function isPromiseLike(v) {
345
368
  * @param {() => number} [options.now]
346
369
  */
347
370
  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: mode 'handles' is not built: only 'values' exists (handles and callbacks are a later step of #190)");
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 } (the wide-open form belongs to mode handles, which is not built)');
371
+ const { roots, mode = 'values', allow = {}, authorize, limits: limitOptions = {}, guard, timers = null, eventFields = {}, handles = {}, random = null, now = () => Date.now() } = options;
372
+ 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)");
373
+ if (mode !== 'values') throw new TypeError("exposeObjects: mode must be 'values' (handles are chosen per root with handles: { ROOT: {} })");
374
+ 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
375
  if (!allow || typeof allow !== 'object' || Array.isArray(allow)) throw new TypeError('exposeObjects: allow must be { get, call, set }');
353
376
  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
377
  // 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 +388,17 @@ export function createObjectsServer(options = {}) {
365
388
  if (roots[name] === null || (typeof roots[name] !== 'object' && typeof roots[name] !== 'function')) throw new TypeError(`exposeObjects: root "${name}" must be an object`);
366
389
  }
367
390
  if (authorize !== undefined && typeof authorize !== 'function') throw new TypeError('exposeObjects: authorize must be a function (who, op) => boolean');
391
+ // 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.
392
+ if (!handles || typeof handles !== 'object' || Array.isArray(handles)) throw new TypeError('exposeObjects: handles must be { ROOT: { nodes? } }');
393
+ const handleRoots = new Map();
394
+ for (const [name, cfg] of Object.entries(handles)) {
395
+ if (!rootNames.includes(name)) throw new TypeError(`exposeObjects: handles names ${JSON.stringify(name)}, which is no such root`);
396
+ if (cfg === null || typeof cfg !== 'object' || Array.isArray(cfg)) throw new TypeError(`exposeObjects: handles.${name} must be an object ({ nodes?: boolean })`);
397
+ if (cfg.nodes !== undefined && typeof cfg.nodes !== 'boolean') throw new TypeError(`exposeObjects: handles.${name}.nodes must be true or false`);
398
+ if (cfg.wideEntries !== undefined && typeof cfg.wideEntries !== 'boolean') throw new TypeError(`exposeObjects: handles.${name}.wideEntries must be true or false`);
399
+ handleRoots.set(name, { nodes: cfg.nodes === true, wideEntries: cfg.wideEntries === true });
400
+ }
401
+ 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
402
  const limits = { ...OBJECTS_DEFAULT_LIMITS };
369
403
  for (const [k, v] of Object.entries(limitOptions)) {
370
404
  if (!(k in OBJECTS_DEFAULT_LIMITS)) throw new TypeError(`exposeObjects: unknown limit ${JSON.stringify(k)} (${Object.keys(OBJECTS_DEFAULT_LIMITS).join(', ')})`);
@@ -388,9 +422,17 @@ export function createObjectsServer(options = {}) {
388
422
  };
389
423
  const lists = { get: compileList(allow.get, 'get'), call: compileList(allow.call, 'call'), set: compileList(allow.set, 'set'), on: compileOn(allow.on) };
390
424
  const every = [...lists.get, ...lists.call, ...lists.set, ...lists.on];
425
+ // 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.
426
+ for (const [name, mode] of handleRoots) {
427
+ if (mode.wideEntries) continue;
428
+ for (const kind of ['call', 'set']) {
429
+ const wide = lists[kind].find((p) => (p[0] === name || p[0] === '*' || p[0] === '**') && p.some((s) => s === '*' || s === '**'));
430
+ 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 } }`);
431
+ }
432
+ }
391
433
 
392
434
  /** 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 }) {
435
+ async function check(kind, root, segs, ctx, { terminal, type, callbacks = 0 }) {
394
436
  const who = ctx.who;
395
437
  const gone = guard?.();
396
438
  if (gone) throw refuse('gone', `refused: ${gone}`);
@@ -401,25 +443,33 @@ export function createObjectsServer(options = {}) {
401
443
  // 1. the allow-list: the operation's own list for the operation itself, any list for walking toward something
402
444
  if (terminal) {
403
445
  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 });
446
+ 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
447
  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
448
  } else if (!every.some((p) => prefixPath(p, segs))) {
406
449
  throw refuse('not-allowed', `refused: ${segs.join('.')} is not on the way to anything the allow-list names`, { path: segs.join('.') });
407
450
  }
408
451
  // 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
- for (const seq of NEEDS_LISTING) {
452
+ // On a root with handles, the members that lead back up to the document or window graph need naming as well.
453
+ for (const seq of handleRoots.has(root) ? [...NEEDS_LISTING, ...GRAPH_MEMBERS.map((n) => [n])] : NEEDS_LISTING) {
410
454
  if (!containsSequence(rel, seq)) continue;
411
455
  const listed = terminal ? own.some((p) => matchPath(p, segs) && patternNames(p, seq)) : every.some((p) => prefixPath(p, segs) && patternNames(p, seq));
412
456
  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
457
  }
414
458
  if (terminal && authorize) {
415
459
  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; }
460
+ try { ok = (await authorize(who ?? {}, { kind, root, path: segs.slice(1), text: segs.join('.'), ...(type !== undefined ? { type } : {}), ...(callbacks ? { callbacks } : {}) })) === true; } catch { ok = false; }
417
461
  if (!ok) throw refuse('authorize', `refused: ${kind} of ${segs.join('.')} was not authorized`, { path: segs.join('.'), op: kind });
418
462
  }
419
463
  }
420
464
 
465
+ /** What the transport says the caller's key may do (`ctx.permit(root, op)`): anything but `true`, and a throw, is no. No `permit`: the transport does not limit. */
466
+ const keyMay = (ctx, root, op) => {
467
+ if (typeof ctx.permit !== 'function') return true;
468
+ try { return ctx.permit(root, op) === true; } catch { return false; }
469
+ };
470
+
421
471
  function permitted(ctx, root, op) {
422
- if (typeof ctx.permit !== 'function' || ctx.permit(root, op) === true) return;
472
+ if (keyMay(ctx, root, op)) return;
423
473
  throw refuse('not-permitted', `refused: this key's capabilities do not allow ${op === 'walk' ? 'reading' : op} on ${root}`, { root, op });
424
474
  }
425
475
 
@@ -453,12 +503,13 @@ export function createObjectsServer(options = {}) {
453
503
  }
454
504
 
455
505
  async function resolve(params, ctx) {
456
- const root = requireRoot(params);
506
+ const start = startOf(params, ctx);
507
+ const { root } = start;
457
508
  const ops = params.ops;
458
509
  if (!Array.isArray(ops)) throw invalid('ops must be an array');
459
510
  if (ops.length > limits.maxOps) throw limitError('maxOps', limits.maxOps, `${ops.length} operations in one request`);
460
- let cur = roots[root];
461
- let segs = [root];
511
+ let cur = start.cur;
512
+ let segs = start.segs;
462
513
  for (let i = 0; i < ops.length; i++) {
463
514
  const op = ops[i];
464
515
  const last = i === ops.length - 1;
@@ -477,22 +528,92 @@ export function createObjectsServer(options = {}) {
477
528
  }
478
529
  // call / construct
479
530
  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
- await check(kind, root, next, ctx, { terminal: true });
531
+ // Functions of the far side, passed as arguments: `callbacks: [[index, id], ...]`, with null in `args` at those places.
532
+ const spec = op.callbacks === undefined ? [] : op.callbacks;
533
+ 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], ...]');
534
+ await check(kind, root, next, ctx, { terminal: true, callbacks: spec.length });
481
535
  const args = op.args === undefined ? [] : op.args;
482
536
  if (!Array.isArray(args)) throw invalid('args must be an array');
483
537
  if (args.length > limits.maxArgs) throw limitError('maxArgs', limits.maxArgs, `${args.length} arguments`);
538
+ 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
539
  const clean = fromWire(args, limits);
540
+ const made = [];
541
+ try {
542
+ 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; }
543
+ } catch (e) { for (const id of made) killCallback(ctx.session, id); throw e; }
485
544
  if (kind === 'call' && isTimerCallee(key) && typeof clean[0] === 'string') throw refuse('always-refused', `refused: ${key} with a string would evaluate it`);
486
545
  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' });
546
+ try { fn = readKey(cur, key); } catch (e) { for (const id of made) killCallback(ctx.session, id); throw wrapThrown(e, `reading ${next.join('.')}`); }
547
+ 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
548
  try {
490
549
  const out = kind === 'call' ? Reflect.apply(fn, cur, clean) : Reflect.construct(fn, clean);
491
550
  cur = kind === 'call' ? await settle(out, ctx) : out;
492
- } catch (e) { throw wrapThrown(e, next.join('.')); }
551
+ } catch (e) { for (const id of made) killCallback(ctx.session, id); throw wrapThrown(e, next.join('.')); }
493
552
  segs = [...segs, `${key}()`];
494
553
  }
495
- return toWire(cur, { maxDepth: limits.maxDepth, maxBytes: ctx.maxBytes ?? limits.maxValueBytes });
554
+ return finishValue(cur, root, segs, ctx);
555
+ }
556
+
557
+ // ── Handles ───────────────────────────────────────────────────────────────────────────────────────────────────────
558
+ // 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
559
+ // 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
560
+ // allow-lists for that path extended by the member: it never widens what the path grants. The table is per channel, bounded, never evicts.
561
+
562
+ /** Prototype-chain names of what reaches the document or window graph. */
563
+ const GRAPH_CLASSES = new Set(['Node', 'Window', 'WorkerGlobalScope', 'Document']);
564
+ function reachesGraph(value) {
565
+ try {
566
+ let proto = Object.getPrototypeOf(value);
567
+ for (let hops = 0; proto && hops < 16; hops++, proto = Object.getPrototypeOf(proto)) {
568
+ const d = Object.getOwnPropertyDescriptor(proto, 'constructor');
569
+ const name = d && 'value' in d && typeof d.value === 'function' ? Object.getOwnPropertyDescriptor(d.value, 'name')?.value : undefined;
570
+ if (GRAPH_CLASSES.has(name)) return true;
571
+ }
572
+ const tag = Object.prototype.toString.call(value);
573
+ return tag === '[object Window]' || tag === '[object global]' || tag === '[object Document]' || tag === '[object HTMLDocument]';
574
+ } catch { return true; }
575
+ }
576
+
577
+ function finishValue(cur, root, segs, ctx) {
578
+ const wire = toWire(cur, { maxDepth: limits.maxDepth, maxBytes: ctx.maxBytes ?? limits.maxValueBytes });
579
+ const mode = handleRoots.get(root);
580
+ if (!mode || !('u' in wire) || (wire.u !== 'function' && wire.u !== 'object') || !ctx.session) return wire;
581
+ 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
582
+ if (wire.u === 'function' && reachesGraph(cur) && !mode.nodes) return wire;
583
+ const { session } = ctx;
584
+ if (session.handles.size >= limits.maxHandles) throw limitError('maxHandles', limits.maxHandles, 'too many handles on this channel: release some (nothing is evicted)');
585
+ const id = newHandleId();
586
+ session.handles.set(id, { root, segs: segs.slice(), value: cur });
587
+ return { h: id, kind: wire.u, ...(wire.type ? { type: wire.type } : {}), ...previewOf(cur, root, segs, ctx) };
588
+ }
589
+
590
+ function newHandleId() {
591
+ const bytes = random(16);
592
+ let out = '';
593
+ let acc = 0;
594
+ let bits = 0;
595
+ for (const b of bytes) { acc = (acc << 8) | b; bits += 8; while (bits >= 6) { bits -= 6; out += B64URL[(acc >> bits) & 63]; } }
596
+ if (bits > 0) out += B64URL[(acc << (6 - bits)) & 63];
597
+ return out;
598
+ }
599
+
600
+ /** 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. */
601
+ function previewOf(value, root, segs, ctx) {
602
+ if (!lists.get.some((p) => matchPath(p, segs))) return {};
603
+ if (!keyMay(ctx, root, 'get')) return {};
604
+ const rel = segs.slice(1).map(bareName);
605
+ 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 {};
606
+ try {
607
+ // Exactly the names describe() would list: the ones the allow-lists could walk to from here.
608
+ 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);
609
+ return { preview: { keys } };
610
+ } catch { return {}; }
611
+ }
612
+
613
+ async function releaseHandle(params, ctx) {
614
+ const { session } = ctx;
615
+ 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)');
616
+ return { ok: true };
496
617
  }
497
618
 
498
619
  function requireRoot(params) {
@@ -502,12 +623,26 @@ export function createObjectsServer(options = {}) {
502
623
  return root;
503
624
  }
504
625
 
505
- /** Walk `path` (an array of keys) as traversal only; the holder and its path. */
506
- async function walk(root, path, ctx) {
626
+ /**
627
+ * 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
628
+ * up in THIS channel's table by its id: another channel, another key, or a made-up id finds nothing.
629
+ */
630
+ function startOf(params, ctx) {
631
+ if (params === null || typeof params !== 'object') throw invalid('params must be an object');
632
+ if (params.handle === undefined) { const root = requireRoot(params); return { root, cur: roots[root], segs: [root] }; }
633
+ const rec = typeof params.handle === 'string' ? ctx.session?.handles.get(params.handle) : undefined;
634
+ if (!rec) throw invalid('no such handle (it was released, belongs to another session, or never existed)');
635
+ // The root's mode is checked again, and the key's permission for that root is asked afresh by `check` on every step.
636
+ return { root: rec.root, cur: rec.value, segs: rec.segs.slice() };
637
+ }
638
+
639
+ /** Walk `path` (an array of keys) as traversal only, from where the request starts; the holder and its path. */
640
+ async function walk(start, path, ctx) {
641
+ const root = start.root;
507
642
  if (!Array.isArray(path)) throw invalid('path must be an array');
508
643
  if (path.length > limits.maxOps) throw limitError('maxOps', limits.maxOps, `a path of ${path.length} segments`);
509
- let cur = roots[root];
510
- let segs = [root];
644
+ let cur = start.cur;
645
+ let segs = start.segs;
511
646
  for (const raw of path) {
512
647
  const key = checkKey(raw);
513
648
  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 +655,11 @@ export function createObjectsServer(options = {}) {
520
655
  }
521
656
 
522
657
  async function setValue(params, ctx) {
523
- const root = requireRoot(params);
658
+ const start = startOf(params, ctx);
659
+ const { root } = start;
524
660
  const path = params.path;
525
661
  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(root, path.slice(0, -1), ctx);
662
+ const { cur: parent, segs } = await walk(start, path.slice(0, -1), ctx);
527
663
  const key = checkKey(path[path.length - 1]);
528
664
  const target = [...segs, key];
529
665
  await check('set', root, target, ctx, { terminal: true });
@@ -542,8 +678,9 @@ export function createObjectsServer(options = {}) {
542
678
  }
543
679
 
544
680
  async function describe(params, ctx) {
545
- const root = requireRoot(params);
546
- const { cur, segs } = await walk(root, params.path ?? [], ctx);
681
+ const start = startOf(params, ctx);
682
+ const { root } = start;
683
+ const { cur, segs } = await walk(start, params.path ?? [], ctx);
547
684
  await check('describe', root, segs, ctx, { terminal: false });
548
685
  if (cur === null || (typeof cur !== 'object' && typeof cur !== 'function')) return { type: kindOf(cur), keys: [] };
549
686
  const keys = [];
@@ -569,8 +706,9 @@ export function createObjectsServer(options = {}) {
569
706
  }
570
707
 
571
708
  async function snapshot(params, ctx) {
572
- const root = requireRoot(params);
573
- const { cur, segs } = await walk(root, params.path ?? [], ctx);
709
+ const start = startOf(params, ctx);
710
+ const { root } = start;
711
+ const { cur, segs } = await walk(start, params.path ?? [], ctx);
574
712
  await check('snapshot', root, segs, ctx, { terminal: true });
575
713
  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
714
  const ceiling = ctx.maxBytes ?? limits.maxValueBytes;
@@ -608,14 +746,60 @@ export function createObjectsServer(options = {}) {
608
746
  session.pumping = true;
609
747
  try {
610
748
  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 */ }
749
+ const { sub, cb, data, dropped } = session.queue.shift();
750
+ const message = cb ? { id: cb.id, seq: ++cb.seq, args: data, ...(dropped ? { dropped } : {}) } : { id: sub.id, seq: ++sub.seq, data, ...(dropped ? { dropped } : {}) };
751
+ // The write waits for the transport (credit): events and callback calls behind it queue, to `maxQueuedEvents`, and beyond that are dropped and counted.
752
+ try { await session.peer.notify(cb ? 'callback' : 'event', message); } catch { /* the channel is going away */ }
615
753
  }
616
754
  } finally { session.pumping = false; }
617
755
  }
618
756
 
757
+ // ── Callbacks ─────────────────────────────────────────────────────────────────────────────────────────────────────────
758
+ // 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
759
+ // 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
760
+ // 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.
761
+
762
+ function makeCallback(session, id) {
763
+ // The same function sent again (an id the channel already has) is the same stub.
764
+ const existing = session.callbacks.get(id);
765
+ if (existing) return existing.stub;
766
+ if (session.callbacks.size >= limits.maxCallbacks) throw limitError('maxCallbacks', limits.maxCallbacks, 'too many callbacks on this channel: release some');
767
+ const cb = { id, seq: 0, stamps: [], dropped: 0, dead: false, stub: null };
768
+ cb.stub = function callback(...args) {
769
+ try { deliverCallback(session, cb, args); } catch { cb.dropped++; }
770
+ };
771
+ session.callbacks.set(id, cb);
772
+ return cb.stub;
773
+ }
774
+
775
+ function killCallback(session, id) {
776
+ const cb = session.callbacks.get(id);
777
+ if (cb) { cb.dead = true; session.callbacks.delete(id); }
778
+ return !!cb;
779
+ }
780
+
781
+ function deliverCallback(session, cb, args) {
782
+ if (session.closed || cb.dead || guard?.()) { session.deadCalls++; return; }
783
+ const t = now();
784
+ while (cb.stamps.length && t - cb.stamps[0] >= 1000) cb.stamps.shift();
785
+ // Rate and room first, copy after: a dropped call costs a counter.
786
+ if (cb.stamps.length >= limits.maxCallbacksPerSecond || session.queue.length >= limits.maxQueuedEvents) { cb.dropped++; return; }
787
+ let copy;
788
+ try {
789
+ copy = args.slice(0, limits.maxArgs).map((a) => { const w = toWire(a, { maxDepth: 4, maxBytes: limits.maxCallbackBytes }); return 'v' in w ? w.v : null; });
790
+ toWire(copy, { maxDepth: 6, maxBytes: limits.maxCallbackBytes });
791
+ } catch { cb.dropped++; return; }
792
+ cb.stamps.push(t);
793
+ session.queue.push({ cb, data: copy, dropped: cb.dropped });
794
+ cb.dropped = 0;
795
+ void pump(session);
796
+ }
797
+
798
+ async function releaseCallback(params, ctx) {
799
+ if (!killCallback(ctx.session, params.id)) throw invalid('no such callback');
800
+ return { ok: true };
801
+ }
802
+
619
803
  function deliver(session, sub, args) {
620
804
  if (session.closed) return;
621
805
  try {
@@ -652,7 +836,7 @@ export function createObjectsServer(options = {}) {
652
836
  const offered = [...(eventFields[type] ?? []), ...(eventFields['*'] ?? [])];
653
837
  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
838
  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);
839
+ const { cur: source, segs } = await walk({ root, cur: roots[root], segs: [root] }, params.path ?? [], ctx);
656
840
  await check('on', root, segs, ctx, { terminal: true, type });
657
841
  const kind = sourceMethods(source);
658
842
  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' });
@@ -676,10 +860,15 @@ export function createObjectsServer(options = {}) {
676
860
  return { ok: true, dropped: sub.dropped };
677
861
  }
678
862
 
679
- /** Register the protocol's methods on a peer. `who` is the identity of every call unless the transport gives one per call. */
863
+ /**
864
+ * Register the protocol's methods on a peer. `who` is the identity of every call unless the transport gives one per call: an object
865
+ * `{ username, fingerprint, podId? }` (see `callerIdentity`): a caller that has only a `podId` gets the hex `fingerprint` as well, and one
866
+ * that names two different keys is refused here, not when its first call arrives.
867
+ */
680
868
  function attach(peer, { who } = {}) {
681
869
  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 };
870
+ const defaultWho = callerIdentity(who);
871
+ const session = { peer, subs: new Map(), queue: [], pumping: false, closed: false, handles: new Map(), callbacks: new Map(), deadCalls: 0 };
683
872
  // The end of the channel (the peer left, Stop, a navigation, a revoke) takes every listener out of the page's sources.
684
873
  const prior = peer.onClose;
685
874
  peer.onClose = (reason) => {
@@ -687,6 +876,9 @@ export function createObjectsServer(options = {}) {
687
876
  for (const sub of session.subs.values()) removeSub(sub);
688
877
  session.subs.clear();
689
878
  session.queue = [];
879
+ session.handles.clear(); // the end of the channel (leaving, Stop, navigation, revoke) releases every handle
880
+ for (const cb of session.callbacks.values()) cb.dead = true; // and kills every callback stub
881
+ session.callbacks.clear();
690
882
  try { prior?.(reason); } catch { /* ignore */ }
691
883
  };
692
884
  const stamps = [];
@@ -697,19 +889,25 @@ export function createObjectsServer(options = {}) {
697
889
  stamps.push(t);
698
890
  // A value is kept under what the transport carries in one message, with room for the envelope.
699
891
  const maxBytes = Math.min(limits.maxValueBytes, Math.max(1024, (peer.maxMessageBytes ?? Infinity) - 4096));
700
- const call = { ...ctx, signal: ctx.signal, who: ctx.who ?? who, maxBytes, session };
892
+ const call = { ...ctx, signal: ctx.signal, who: ctx.who === undefined || ctx.who === null ? defaultWho : callerIdentity(ctx.who), maxBytes, session };
701
893
  if (params === null || typeof params !== 'object' || Array.isArray(params)) throw invalid('params must be an object');
702
894
  try { return await fn(params, call); } catch (e) { if (e instanceof ObjectsError) throw e; throw wrapThrown(e, name); }
703
895
  });
704
896
  // 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) }));
897
+ // 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.
898
+ method('roots', async (_params, call) => ({
899
+ roots: rootNames.filter((name) => keyMay(call, name, 'walk')),
900
+ features: ['events', 'callbacks', ...(handleRoots.size ? ['handles'] : [])],
901
+ }));
706
902
  method('resolve', resolve);
707
903
  method('set', setValue);
708
904
  method('describe', describe);
709
905
  method('snapshot', snapshot);
710
906
  method('subscribe', subscribe);
711
907
  method('unsubscribe', unsubscribe);
712
- return { limits };
908
+ method('release', releaseHandle);
909
+ method('releaseCallback', releaseCallback);
910
+ return { limits, handleCount: () => session.handles.size, callbackCount: () => session.callbacks.size, deadCallbackCalls: () => session.deadCalls };
713
911
  }
714
912
 
715
913
  return { attach, limits: Object.freeze({ ...limits }), rootNames: rootNames.slice() };
@@ -720,10 +918,20 @@ export function createObjectsServer(options = {}) {
720
918
  /**
721
919
  * A `Peer` over `send(message)` and `receive(message)` (JSON-RPC-shaped plain objects: requests `{ id, method, params }`, responses
722
920
  * `{ id, result }` / `{ id, error }`, notifications `{ method, params }`, and `$/cancel` and `$/progress`). For a transport that is not wsh.
723
- * @param {{ send(message: object): void, maxMessageBytes?: number }} options
921
+ *
922
+ * `who` is who is on the far side, for a transport that knows (a mesh channel knows the pod it is with): an identity object
923
+ * `{ username?, fingerprint?, podId? }`, so an adapter does not put a pod id in a field named `fingerprint`. Whichever of `fingerprint`
924
+ * (64 hex digits) and `podId` it gives, `authorize(who, op)` sees the hex `fingerprint`, and the `podId` when it was given; an identity that
925
+ * names two keys, or is not an object, is refused here. `permit(root, op)` is the transport's own capability check, asked for every
926
+ * operation (`get`, `call`, `set`, `on`, or `walk` for reading on the way to something): `true` allows, anything else, and a throw,
927
+ * refuses; with no `permit` the transport limits nothing.
928
+ *
929
+ * @param {{ send(message: object): void, maxMessageBytes?: number, who?: { username?: string | null, fingerprint?: string | null, podId?: string | null }, permit?: (root: string, op: string) => boolean }} options
724
930
  */
725
- export function createDuplexPeer({ send, maxMessageBytes = 1024 * 1024 } = {}) {
931
+ export function createDuplexPeer({ send, maxMessageBytes = 1024 * 1024, who, permit } = {}) {
726
932
  if (typeof send !== 'function') throw new TypeError('createDuplexPeer: send(message) is required');
933
+ if (permit !== undefined && typeof permit !== 'function') throw new TypeError('createDuplexPeer: permit must be a function (root, op) => boolean');
934
+ const identity = callerIdentity(who);
727
935
  let nextId = 1;
728
936
  let closed = false;
729
937
  const pending = new Map();
@@ -763,7 +971,7 @@ export function createDuplexPeer({ send, maxMessageBytes = 1024 * 1024 } = {}) {
763
971
  if (!handler) { send({ id, error: { code: -32601, message: `method not found: ${message.method}` } }); return; }
764
972
  const ctl = new AbortController();
765
973
  inflight.set(id, ctl);
766
- const ctx = { signal: ctl.signal, progress: (chunk) => send({ method: '$/progress', params: { id, chunk } }) };
974
+ const ctx = { signal: ctl.signal, progress: (chunk) => send({ method: '$/progress', params: { id, chunk } }), ...(identity ? { who: identity } : {}), ...(permit ? { permit } : {}) };
767
975
  Promise.resolve().then(() => handler(message.params, ctx)).then(
768
976
  (result) => { if (ctl.signal.aborted) return; send({ id, result: result === undefined ? null : result }); },
769
977
  (e) => { if (ctl.signal.aborted) return; send({ id, error: { code: e?.code ?? OBJECTS_ERROR.FAILED, message: String(e?.message ?? e), ...(e?.data ? { data: e.data } : {}) } }); },
@@ -805,11 +1013,33 @@ export class NonValue {
805
1013
  toString() { return `[remote ${this.kind}${this.type ? ` ${this.type}` : ''}${this.text ? `: ${this.text}` : ''}]`; }
806
1014
  }
807
1015
 
808
- const decodeResult = (res) => {
1016
+ const decodeResult = (res, session) => {
1017
+ if (res && typeof res === 'object' && typeof res.h === 'string' && session) {
1018
+ 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' });
1019
+ return new RemoteHandle(session, res);
1020
+ }
809
1021
  if (res && typeof res === 'object' && 'u' in res) return res.u === 'undefined' ? undefined : new NonValue(res);
810
1022
  return res?.v;
811
1023
  };
812
1024
 
1025
+ const HANDLE_ID = new WeakMap();
1026
+
1027
+ /**
1028
+ * 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
1029
+ * 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.
1030
+ */
1031
+ export class RemoteHandle {
1032
+ constructor(session, wire) {
1033
+ HANDLE_ID.set(this, { session, id: wire.h });
1034
+ Object.defineProperty(this, 'kind', { value: wire.kind, enumerable: false });
1035
+ Object.defineProperty(this, 'type', { value: wire.type, enumerable: false });
1036
+ Object.defineProperty(this, 'preview', { value: wire.preview, enumerable: false });
1037
+ Object.freeze(this);
1038
+ }
1039
+
1040
+ toString() { return `[remote handle${this.type ? ` ${this.type}` : ''}]`; }
1041
+ }
1042
+
813
1043
  function asObjectsError(e, session) {
814
1044
  if (e instanceof ObjectsError) return e;
815
1045
  const closing = session?.closing ? ` (${session.closing})` : '';
@@ -828,6 +1058,7 @@ function plainArgs(args) {
828
1058
  let visits = 0;
829
1059
  const walk = (v, depth) => {
830
1060
  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)');
1061
+ 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
1062
  if (v === null || typeof v !== 'object' || depth > 8 || ++visits > 2000) return;
832
1063
  if (ArrayBuffer.isView(v)) return;
833
1064
  for (const k of Object.keys(v)) walk(v[k], depth + 1);
@@ -836,8 +1067,11 @@ function plainArgs(args) {
836
1067
  return args;
837
1068
  }
838
1069
 
839
- function makeRef(session, root, ops) {
840
- const state = { session, root, ops };
1070
+ /** What a request names as its start: the handle this reference stands on, or its root. */
1071
+ const target = (state) => (state.handle !== undefined ? { handle: state.handle } : { root: state.root });
1072
+
1073
+ function makeRef(session, root, ops, handle) {
1074
+ const state = { session, root, ops, handle };
841
1075
  const readOnly = (what) => () => { throw new TypeError(what); };
842
1076
  const handler = {
843
1077
  get(_target, key) {
@@ -847,7 +1081,7 @@ function makeRef(session, root, ops) {
847
1081
  // `await ref` sends the whole chain in ONE request. A remote property really named "then" is reached with get(ref, 'then').
848
1082
  return (onFulfilled, onRejected) => send(state).then(onFulfilled, onRejected);
849
1083
  }
850
- return makeRef(session, root, [...ops, { get: key }]);
1084
+ return makeRef(session, root, [...ops, { get: key }], handle);
851
1085
  },
852
1086
  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
1087
  defineProperty: readOnly('a remote reference cannot be defined on: use set(ref, key, value)'),
@@ -856,22 +1090,52 @@ function makeRef(session, root, ops) {
856
1090
  apply(_t, _this, args) {
857
1091
  const last = ops[ops.length - 1];
858
1092
  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, args: plainArgs(args) }]);
1093
+ return makeRef(session, root, [...ops.slice(0, -1), { call: last.get, ...callArgs(args) }], handle);
860
1094
  },
861
1095
  construct(_t, args) {
862
1096
  const last = ops[ops.length - 1];
863
1097
  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, args: plainArgs(args) }]);
1098
+ return makeRef(session, root, [...ops.slice(0, -1), { construct: last.get, ...callArgs(args) }], handle);
865
1099
  },
866
1100
  };
867
1101
  // A function as the target so the proxy can be called and constructed.
868
1102
  return new Proxy(function remote() {}, handler);
869
1103
  }
870
1104
 
1105
+ /**
1106
+ * 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`
1107
+ * (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.
1108
+ */
1109
+ function callArgs(args) {
1110
+ const fns = [];
1111
+ const copy = args.map((a, i) => {
1112
+ if (typeof a === 'function' && !a[BRAND]) { fns.push([i, a]); return null; }
1113
+ return a;
1114
+ });
1115
+ plainArgs(copy);
1116
+ return fns.length ? { args: copy, fns } : { args: copy };
1117
+ }
1118
+
1119
+ const CALLBACK_OF = new WeakMap();
1120
+
1121
+ /** 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. */
1122
+ function wireOp(session, op) {
1123
+ if (!op.fns) return op;
1124
+ const { fns, ...rest } = op;
1125
+ return { ...rest, callbacks: fns.map(([i, fn]) => {
1126
+ let rec = CALLBACK_OF.get(fn);
1127
+ 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); }
1128
+ return [i, rec.id];
1129
+ }) };
1130
+ }
1131
+
871
1132
  async function send(state, { signal } = {}) {
872
- const { session, root, ops } = state;
1133
+ const { session } = state;
873
1134
  try {
874
- return decodeResult(await session.peer.request('resolve', { root, ops }, { signal, ...(session.timeoutMs ? { timeoutMs: session.timeoutMs } : {}) }));
1135
+ // 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.
1136
+ 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' });
1137
+ const ops = state.ops.map((op) => wireOp(session, op));
1138
+ return decodeResult(await session.peer.request('resolve', { ...target(state), ops }, { signal, ...(session.timeoutMs ? { timeoutMs: session.timeoutMs } : {}) }), session);
875
1139
  } catch (e) { throw asObjectsError(e, session); }
876
1140
  }
877
1141
 
@@ -896,7 +1160,7 @@ export function get(ref, ...keys) {
896
1160
  export async function set(ref, key, value) {
897
1161
  const { state, keys } = pathOf(ref, 'set');
898
1162
  plainArgs([value]);
899
- try { await state.session.peer.request('set', { root: state.root, path: [...keys, String(key)], value }); } catch (e) { throw asObjectsError(e, state.session); }
1163
+ try { await state.session.peer.request('set', { ...target(state), path: [...keys, String(key)], value }); } catch (e) { throw asObjectsError(e, state.session); }
900
1164
  }
901
1165
 
902
1166
  /** 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 +1168,7 @@ export function call(ref, ...args) {
904
1168
  const state = stateOf(ref);
905
1169
  const last = state.ops[state.ops.length - 1];
906
1170
  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, args: plainArgs(args) }] });
1171
+ return send({ ...state, ops: [...state.ops.slice(0, -1), { call: last.get, ...callArgs(args) }] });
908
1172
  }
909
1173
 
910
1174
  /** `new` a constructor reached by name: `await construct(win.app.Cart, 'A')`. */
@@ -912,14 +1176,14 @@ export function construct(ref, ...args) {
912
1176
  const state = stateOf(ref);
913
1177
  const last = state.ops[state.ops.length - 1];
914
1178
  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, args: plainArgs(args) }] });
1179
+ return send({ ...state, ops: [...state.ops.slice(0, -1), { construct: last.get, ...callArgs(args) }] });
916
1180
  }
917
1181
 
918
1182
  /** A bounded deep copy: `await snapshot(win.app.state, { depth: 3, maxBytes: 256_000 })`. Subtrees deeper than `depth` are `null`. */
919
1183
  export async function snapshot(ref, { depth, maxBytes, signal } = {}) {
920
1184
  const { state, keys } = pathOf(ref, 'snapshot');
921
1185
  try {
922
- return decodeResult(await state.session.peer.request('snapshot', { root: state.root, path: keys, ...(depth !== undefined ? { depth } : {}), ...(maxBytes !== undefined ? { maxBytes } : {}) }, { signal }));
1186
+ return decodeResult(await state.session.peer.request('snapshot', { ...target(state), path: keys, ...(depth !== undefined ? { depth } : {}), ...(maxBytes !== undefined ? { maxBytes } : {}) }, { signal }));
923
1187
  } catch (e) { throw asObjectsError(e, state.session); }
924
1188
  }
925
1189
 
@@ -932,6 +1196,8 @@ export async function on(ref, type, listener, { fields, onError } = {}) {
932
1196
  const { state, keys } = pathOf(ref, 'on');
933
1197
  if (typeof listener !== 'function') throw new TypeError('on needs a listener function: listener(data, { type, seq, dropped })');
934
1198
  const { session } = state;
1199
+ if (state.handle !== undefined) throw new TypeError('events are not offered through a handle: name the source by its path');
1200
+ 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
1201
  const id = session.nextSub++;
936
1202
  // Registered before the request: an event can follow the answer at once.
937
1203
  session.subs.set(id, { listener, onError, type });
@@ -953,7 +1219,7 @@ export async function off(unsubscribe) {
953
1219
  /** 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
1220
  export async function describe(ref, { signal } = {}) {
955
1221
  const { state, keys } = pathOf(ref, 'describe');
956
- try { return await state.session.peer.request('describe', { root: state.root, path: keys }, { signal }); } catch (e) { throw asObjectsError(e, state.session); }
1222
+ try { return await state.session.peer.request('describe', { ...target(state), path: keys }, { signal }); } catch (e) { throw asObjectsError(e, state.session); }
957
1223
  }
958
1224
 
959
1225
  /**
@@ -961,9 +1227,17 @@ export async function describe(ref, { signal } = {}) {
961
1227
  * @param {object} peer
962
1228
  * @param {{ timeoutMs?: number }} [options]
963
1229
  */
964
- export async function createObjectsClient(peer, { timeoutMs } = {}) {
1230
+ export async function createObjectsClient(peer, { timeoutMs, onCallbackError, onCallbackDropped } = {}) {
965
1231
  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 };
1232
+ const session = { peer, closing: null, timeoutMs, subs: new Map(), nextSub: 1, callbacks: new Map(), nextCb: 1 };
1233
+ // 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 })`
1234
+ // is told, before the call that follows them, how many calls the host dropped (rate, size, a slow channel).
1235
+ peer.onNotification?.('callback', (params) => {
1236
+ const fn = session.callbacks.get(params?.id);
1237
+ if (!fn || !Array.isArray(params.args)) return;
1238
+ if (Number.isSafeInteger(params.dropped) && params.dropped > 0) { try { onCallbackDropped?.({ dropped: params.dropped, fn }); } catch { /* ours */ } }
1239
+ try { fn(...params.args); } catch (e) { try { onCallbackError?.(e); } catch { /* ours */ } }
1240
+ });
967
1241
  // 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
1242
  peer.onNotification?.('event', (params) => {
969
1243
  const sub = session.subs.get(params?.id);
@@ -974,7 +1248,12 @@ export async function createObjectsClient(peer, { timeoutMs } = {}) {
974
1248
  });
975
1249
  peer.onNotification?.('closing', (params) => { session.closing = typeof params?.reason === 'string' ? clip(params.reason, TEXT_MAX) : 'closing'; });
976
1250
  let roots;
977
- try { roots = (await peer.request('roots', {}))?.roots; } catch (e) { throw asObjectsError(e, session); }
1251
+ try {
1252
+ const answer = await peer.request('roots', {});
1253
+ roots = answer?.roots;
1254
+ // What the host says it supports; a host that says nothing (before 0.48.0) supports none of the three.
1255
+ session.features = Array.isArray(answer?.features) ? answer.features.filter((f) => typeof f === 'string') : [];
1256
+ } catch (e) { throw asObjectsError(e, session); }
978
1257
  if (!Array.isArray(roots)) throw new ObjectsError(OBJECTS_ERROR.FAILED, 'the host did not list its roots', { reason: 'bad-reply' });
979
1258
  const page = {};
980
1259
  for (const name of roots) if (typeof name === 'string' && !ALWAYS_REFUSED.has(name)) page[name] = makeRef(session, name, []);
@@ -983,6 +1262,31 @@ export async function createObjectsClient(peer, { timeoutMs } = {}) {
983
1262
  }
984
1263
 
985
1264
  /** End the connection behind what `openObjects()` returned. */
1265
+ /** 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. */
1266
+ export function use(handle) {
1267
+ const rec = handle instanceof RemoteHandle ? HANDLE_ID.get(handle) : undefined;
1268
+ if (!rec) throw new TypeError('use needs a handle (what awaiting a reference returns on a root that opted in to handles)');
1269
+ return makeRef(rec.session, null, [], rec.id);
1270
+ }
1271
+
1272
+ /** Give a handle's place back. Releasing a released handle does nothing. Everything is released when the channel ends. */
1273
+ export async function release(handle) {
1274
+ // A function that was passed as a callback: its stub in the page dies, and a call of it is a counted no-op.
1275
+ if (typeof handle === 'function' && CALLBACK_OF.has(handle)) {
1276
+ const cb = CALLBACK_OF.get(handle);
1277
+ if (cb.released) return;
1278
+ cb.released = true;
1279
+ cb.session.callbacks.delete(cb.id);
1280
+ try { await cb.session.peer.request('releaseCallback', { id: cb.id }); } catch (e) { throw asObjectsError(e, cb.session); }
1281
+ return;
1282
+ }
1283
+ const rec = handle instanceof RemoteHandle ? HANDLE_ID.get(handle) : undefined;
1284
+ if (!rec) throw new TypeError('release needs a handle, or a function that was passed as a callback');
1285
+ if (rec.released) return;
1286
+ rec.released = true;
1287
+ try { await rec.session.peer.request('release', { handle: rec.id }); } catch (e) { throw asObjectsError(e, rec.session); }
1288
+ }
1289
+
986
1290
  export async function closeObjects(page) {
987
1291
  const session = page?.[SESSION];
988
1292
  if (!session) throw new TypeError('closeObjects: expected what openObjects() returned');