@johnhenry/wsh 0.46.1 → 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/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;
@@ -44,6 +60,22 @@ export interface ObjectsLimits {
44
60
  maxRequestsPerSecond: number;
45
61
  /** How long a call that returns a promise is waited for. Default 30000. */
46
62
  callTimeoutMs: number;
63
+ /** Event subscriptions per channel. Default 16. */
64
+ maxSubscriptions: number;
65
+ /** Events delivered per second, per subscription; the rest are dropped and counted. Default 20. */
66
+ maxEventsPerSecond: number;
67
+ /** Bytes of one delivered event; a bigger one is dropped and counted. Default 16384. */
68
+ maxEventBytes: number;
69
+ /** Events waiting for the transport's credit, per channel; more are dropped and counted. Default 100. */
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;
47
79
  }
48
80
  export const OBJECTS_DEFAULT_LIMITS: Readonly<ObjectsLimits>;
49
81
 
@@ -53,13 +85,20 @@ export const NEEDS_LISTING: ReadonlyArray<readonly string[]>;
53
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. */
54
86
  export interface ObjectsAllow {
55
87
  get?: string[];
88
+ // (`call` entries may end in `(callback)`: the call accepts functions as arguments, which reach the page as one-way stubs.)
56
89
  call?: string[];
57
90
  set?: string[];
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. */
92
+ on?: string[];
58
93
  }
59
94
 
60
95
  export interface ObjectsWho { username: string | null; fingerprint: string | null }
61
96
  export interface ObjectsOperation {
62
- kind: 'get' | 'call' | 'construct' | 'set' | 'describe' | 'snapshot';
97
+ kind: 'get' | 'call' | 'construct' | 'set' | 'on' | 'describe' | 'snapshot';
98
+ /** For `on`: the event type. */
99
+ type?: string;
100
+ /** For a call that carries callbacks: how many. */
101
+ callbacks?: number;
63
102
  root: string;
64
103
  /** The path below the root. */
65
104
  path: string[];
@@ -70,12 +109,22 @@ export interface ObjectsOperation {
70
109
  export interface ObjectsServerOptions {
71
110
  /** The named roots: all that is reachable. */
72
111
  roots: Record<string, object>;
73
- /** `'values'` is the only mode: `'handles'` is refused (not built). */
112
+ /** `'values'` (the default). Handles are chosen per root with `handles`, not here. */
74
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;
75
122
  allow?: ObjectsAllow;
76
123
  /** Asked for every operation the allow-list let through; anything but `true` (a throw included) refuses. */
77
124
  authorize?: (who: ObjectsWho, op: ObjectsOperation) => boolean | Promise<boolean>;
78
125
  limits?: Partial<ObjectsLimits>;
126
+ /** Extra event fields a subscriber may ask for, by event type (`'*'`: any type): property names read from the event and copied as plain data (a node is left out). */
127
+ eventFields?: Record<string, string[]>;
79
128
  /** Why nothing may be served any more (the window left), else null. */
80
129
  guard?: () => string | null;
81
130
  /** For `callTimeoutMs`. */
@@ -105,7 +154,13 @@ export function createObjectsServer(options: ObjectsServerOptions): {
105
154
  export function createDuplexPeer(options: { send(message: object): void; maxMessageBytes?: number }): ObjectsPeer & { receive(message: unknown): void; close(reason?: string): void; readonly closed: boolean };
106
155
 
107
156
  /** The client half over any peer: the roots, as lazy references. */
108
- export function createObjectsClient<T = Record<string, any>>(peer: Pick<ObjectsPeer, 'request'> & Partial<ObjectsPeer>, options?: { timeoutMs?: number }): Promise<T>;
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>;
109
164
 
110
165
  /** `exposeObjects`: the rpc handler for `wsh-objects`. Usable as `rpc: { 'wsh-objects': exposeObjects({ roots, allow }) }` in any host. */
111
166
  export interface ObjectsHandler {
@@ -140,6 +195,13 @@ export function call(ref: any, ...args: unknown[]): Promise<any>;
140
195
  export function construct(ref: any, ...args: unknown[]): Promise<any>;
141
196
  /** A bounded deep copy; subtrees deeper than `depth` are `null`. */
142
197
  export function snapshot(ref: any, options?: { depth?: number; maxBytes?: number; signal?: AbortSignal }): Promise<any>;
198
+ /**
199
+ * Listen for an event of a remote source named by the host's `allow.on`. `data` is plain: an Event as `{ type, timeStamp, isTrusted, ...fields }`, an emitter's as
200
+ * `{ type, args }`. `dropped` counts events the host dropped before this one. Resolves to the function that unsubscribes. Never an event object, never a handle.
201
+ */
202
+ export function on(ref: any, type: string, listener: (data: any, info: { type: string; seq: number; dropped: number }) => void, options?: { fields?: string[]; onError?: (error: unknown) => void }): Promise<() => Promise<void>>;
203
+ /** Stop a subscription: what `on` resolved to. */
204
+ export function off(unsubscribe: () => Promise<void>): Promise<void>;
143
205
  /** The shape of an object, for completion: the names and types the allow-list could walk to. */
144
206
  export function describe(ref: any, options?: { signal?: AbortSignal }): Promise<{ type: string; keys: Array<{ key: string; type: string; own: boolean }>; truncated?: boolean }>;
145
207
  /** End the connection behind what `openObjects()` returned. */
package/src/objects.mjs CHANGED
@@ -28,22 +28,31 @@ import {
28
28
  export {
29
29
  OBJECTS_PROTOCOL, OBJECTS_ERROR, OBJECTS_DEFAULT_LIMITS, NEEDS_LISTING, ObjectsError, NonValue,
30
30
  createObjectsServer, createObjectsClient, createDuplexPeer, matchPath, toWire, fromWire,
31
- get, set, call, construct, snapshot, describe, closeObjects,
31
+ get, set, call, construct, snapshot, describe, on, off, 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
- function channelPeer(channel) {
41
+ function channelPeer(channel, host = {}) {
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.
43
+ const permit = typeof host.permits === 'function' ? (root, op) => host.permits({ kind: 'objects', root, op }) : undefined;
39
44
  return {
40
45
  onRequest: (method, handler) => channel.onRequest(method, async (params, ctx) => {
41
- try { return await handler(params, ctx); } catch (e) {
46
+ try { return await handler(params, permit ? { ...ctx, permit } : ctx); } catch (e) {
42
47
  if (e instanceof ObjectsError) throw new RpcError(e.code, e.message, e.data);
43
48
  throw e;
44
49
  }
45
50
  }),
46
51
  get maxMessageBytes() { return channel.maxMessageBytes; },
52
+ // Events go out as notifications, whose write waits for the channel's credit; the end of the channel takes the listeners out of the page.
53
+ notify: (method, params) => channel.notify(method, params),
54
+ get onClose() { return channel.onClose; },
55
+ set onClose(fn) { channel.onClose = fn; },
47
56
  };
48
57
  }
49
58
 
@@ -58,11 +67,11 @@ function channelPeer(channel) {
58
67
  * @param {object} [options.limits] - `maxOps`, `maxArgs`, `maxDepth`, `maxValueBytes`, `maxKeys`, `maxRequestsPerSecond`, `callTimeoutMs`
59
68
  */
60
69
  export function exposeObjects(options = {}) {
61
- const server = createObjectsServer({ timers: defaultTimers, ...options });
70
+ const server = createObjectsServer({ timers: defaultTimers, random: defaultRandom, ...options });
62
71
  const sessions = new Set();
63
72
  const handler = (channel, ctx = {}) => {
64
73
  const who = { username: ctx.user ?? null, fingerprint: ctx.fingerprint ?? null };
65
- server.attach(channelPeer(channel), { who });
74
+ server.attach(channelPeer(channel, ctx), { who });
66
75
  const session = { channel, who };
67
76
  sessions.add(session);
68
77
  const prior = channel.onClose;
@@ -77,6 +86,8 @@ export function exposeObjects(options = {}) {
77
86
  }));
78
87
  return targets.length;
79
88
  };
89
+ // This handler narrows by the key's capabilities itself (`objects:ROOT[:OP]`), so a key that names roots may open the channel without `rpc:wsh-objects`.
90
+ handler.capabilityScoped = true;
80
91
  handler.rootNames = server.rootNames;
81
92
  handler.limits = server.limits;
82
93
  return handler;
@@ -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 refused: not built. See `@johnhenry/wsh/objects`.
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 }>;
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
@@ -69,31 +69,38 @@ function exposedRoots(window, expose) {
69
69
  const names = Object.keys(expose);
70
70
  if (names.length === 0) throw new TypeError('createPageHost: expose names no root');
71
71
  const roots = {};
72
- const allow = { get: [], call: [], set: [] };
72
+ const allow = { get: [], call: [], set: [], on: [] };
73
73
  const authorizers = new Map();
74
+ const eventFields = {};
75
+ const handles = {};
74
76
  let limits;
75
77
  for (const name of names) {
76
78
  const cfg = expose[name];
77
79
  if (!isObj(cfg)) throw new TypeError(`createPageHost: expose.${name} must be { mode, allow }`);
78
- if (cfg.mode === 'handles') throw new TypeError("createPageHost: expose mode 'handles' is not built: only 'values' exists (handles, events and callbacks are a later step of #190)");
79
- if (cfg.mode !== undefined && cfg.mode !== 'values') throw new TypeError("createPageHost: expose mode must be 'values'");
80
- if (typeof cfg.allow === 'string') throw new TypeError('createPageHost: expose allow must be { get, call, set } (the wide-open form belongs to mode handles, which is not built)');
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 };
81
86
  const object = cfg.object ?? (name === 'window' ? window : undefined);
82
87
  if (object === undefined) throw new TypeError(`createPageHost: expose.${name}: only a root named "window" is the window; give { object } for another root`);
83
88
  roots[name] = object;
84
89
  for (const [op, list] of Object.entries(cfg.allow ?? {})) {
85
- if (!(op in allow)) throw new TypeError(`createPageHost: expose.${name}.allow.${op} is not an operation (get, call, set)`);
90
+ if (!(op in allow)) throw new TypeError(`createPageHost: expose.${name}.allow.${op} is not an operation (get, call, set, on)`);
86
91
  if (!Array.isArray(list)) throw new TypeError(`createPageHost: expose.${name}.allow.${op} must be an array of path patterns`);
87
92
  for (const entry of list) {
88
93
  if (typeof entry !== 'string' || entry === '') throw new TypeError(`createPageHost: expose.${name}.allow.${op} entries must be non-empty strings (paths relative to ${name})`);
89
- allow[op].push(`${name}.${entry}`);
94
+ // An event source is `path@type`; with no path (`'@hashchange'`) it is the root itself.
95
+ allow[op].push(op === 'on' && entry.startsWith('@') ? `${name}${entry}` : `${name}.${entry}`);
90
96
  }
91
97
  }
98
+ for (const [type, fields] of Object.entries(cfg.eventFields ?? {})) eventFields[type] = [...new Set([...(eventFields[type] ?? []), ...(Array.isArray(fields) ? fields : [])])];
92
99
  if (cfg.authorize !== undefined) { if (typeof cfg.authorize !== 'function') throw new TypeError(`createPageHost: expose.${name}.authorize must be a function`); authorizers.set(name, cfg.authorize); }
93
100
  if (cfg.limits !== undefined) limits = { ...limits, ...cfg.limits };
94
101
  }
95
102
  const authorize = authorizers.size ? (who, op) => (authorizers.has(op.root) ? authorizers.get(op.root)(who, { ...op, path: op.path }) : true) : undefined;
96
- return { roots, allow, authorize, limits };
103
+ return { roots, allow, authorize, limits, eventFields, handles };
97
104
  }
98
105
 
99
106
  /** The indicator in the page: one row per connected key, with the key's fingerprint and a Stop control. */
@@ -149,7 +156,7 @@ function createDomIndicator(window, { name }) {
149
156
  * optionally the rendezvous id (default: a fresh random one, exposed as `host.rendezvousId`)
150
157
  * @param {Record<string, { mode?: 'values', allow?: { get?: string[], call?: string[], set?: string[] }, authorize?: Function, limits?: object, object?: object }>} [options.expose]
151
158
  * object access, off unless written: named roots (`window` is the window passed; another name needs `object`), each with its allow-lists by
152
- * operation (paths relative to the root: `'document.title'`, `'app.**'`; nothing allowed by default). `mode: 'handles'` is refused: not built.
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).
153
160
  * See `@johnhenry/wsh/objects` for what `values` mode promises.
154
161
  * @param {string} options.name - what this tab is called (shown in the indicator, the `serverInfo` of the MCP server)
155
162
  * @param {string | Uint8Array | Array<string | Uint8Array>} options.authorizedKeys - who may log in, as `authorized_keys` lines (with their
@@ -250,7 +257,9 @@ export async function createPageHost(options = {}) {
250
257
  guard: () => gone() ?? mcp.guard?.() ?? null,
251
258
  }) : null;
252
259
  const objectsHandler = exposed ? exposeObjects({
253
- roots: exposed.roots, allow: exposed.allow, authorize: exposed.authorize, limits: exposed.limits, 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)),
254
263
  guard: () => gone(),
255
264
  }) : null;
256
265
  /** What each handler tells and ends: the sessions of a key, or all of them. */