@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.
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,17 +85,28 @@ 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. */
67
92
  on?: string[];
68
93
  }
69
94
 
70
- export interface ObjectsWho { username: string | null; fingerprint: string | null }
95
+ /**
96
+ * Who a call is from, as `authorize(who, op)` and the allow-list's hooks see it: `fingerprint` is the hex SHA-256 of the caller's public key
97
+ * wherever the caller came from (over wsh: the key it logged in with). `podId` is there when the transport knows the caller by one (a mesh
98
+ * adapter that gave `{ podId }`: then `fingerprint` is derived from it); a wsh caller has no `podId`. `fingerprint` is `null` for a caller
99
+ * with no key (a password login).
100
+ */
101
+ export interface ObjectsWho { username: string | null; fingerprint: string | null; podId?: string }
102
+ /** What a transport that is not wsh may say of its caller; whichever of `fingerprint` (64 hex digits) and `podId` it gives, `ObjectsWho` has the hex `fingerprint`. */
103
+ export interface ObjectsIdentity { username?: string | null; fingerprint?: string | null; podId?: string | null }
71
104
  export interface ObjectsOperation {
72
105
  kind: 'get' | 'call' | 'construct' | 'set' | 'on' | 'describe' | 'snapshot';
73
106
  /** For `on`: the event type. */
74
107
  type?: string;
108
+ /** For a call that carries callbacks: how many. */
109
+ callbacks?: number;
75
110
  root: string;
76
111
  /** The path below the root. */
77
112
  path: string[];
@@ -82,8 +117,16 @@ export interface ObjectsOperation {
82
117
  export interface ObjectsServerOptions {
83
118
  /** The named roots: all that is reachable. */
84
119
  roots: Record<string, object>;
85
- /** `'values'` is the only mode: `'handles'` is refused (not built). */
120
+ /** `'values'` (the default). Handles are chosen per root with `handles`, not here. */
86
121
  mode?: 'values';
122
+ /**
123
+ * 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
124
+ * second opt-in, for DOM nodes, windows and documents (control of the page). Needs `random`.
125
+ */
126
+ handles?: Record<string, { nodes?: boolean; wideEntries?: boolean }>;
127
+ // `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).
128
+ /** The random source for handle ids: `(n) => bytes` from `crypto.getRandomValues`. `exposeObjects` defaults to the platform's, the page host to its window's. */
129
+ random?: (n: number) => Uint8Array;
87
130
  allow?: ObjectsAllow;
88
131
  /** Asked for every operation the allow-list let through; anything but `true` (a throw included) refuses. */
89
132
  authorize?: (who: ObjectsWho, op: ObjectsOperation) => boolean | Promise<boolean>;
@@ -99,7 +142,7 @@ export interface ObjectsServerOptions {
99
142
 
100
143
  /** What the core needs of a transport (an `RpcChannel` is one; `createDuplexPeer` makes one from `send` and `receive`). */
101
144
  export interface ObjectsPeer {
102
- onRequest(method: string, handler: (params: any, ctx: { signal?: AbortSignal; progress?: (chunk: unknown) => unknown; who?: ObjectsWho }) => unknown): unknown;
145
+ onRequest(method: string, handler: (params: any, ctx: { signal?: AbortSignal; progress?: (chunk: unknown) => unknown; who?: ObjectsIdentity; permit?: (root: string, op: string) => boolean }) => unknown): unknown;
103
146
  onNotification?(method: string, handler: (params: any) => void): unknown;
104
147
  request(method: string, params?: unknown, options?: { signal?: AbortSignal; onProgress?: (chunk: unknown) => void }): Promise<any>;
105
148
  notify(method: string, params?: unknown): unknown;
@@ -110,16 +153,27 @@ export interface ObjectsPeer {
110
153
 
111
154
  /** The transport-neutral server half: roots, allow-lists and limits, attachable to any peer. Knows nothing about wsh. */
112
155
  export function createObjectsServer(options: ObjectsServerOptions): {
113
- attach(peer: Pick<ObjectsPeer, 'onRequest' | 'maxMessageBytes'>, options?: { who?: ObjectsWho }): { limits: ObjectsLimits };
156
+ /** `who`: the identity of every call unless the peer gives one per call (`ctx.who`); one that names two keys, or is not an identity, throws a `TypeError` here. */
157
+ attach(peer: Pick<ObjectsPeer, 'onRequest' | 'maxMessageBytes'>, options?: { who?: ObjectsIdentity }): { limits: ObjectsLimits };
114
158
  readonly limits: Readonly<ObjectsLimits>;
115
159
  readonly rootNames: string[];
116
160
  };
117
161
 
118
- /** A peer over `send(message)` and `receive(message)`: the same protocol over any duplex that is not wsh. */
119
- export function createDuplexPeer(options: { send(message: object): void; maxMessageBytes?: number }): ObjectsPeer & { receive(message: unknown): void; close(reason?: string): void; readonly closed: boolean };
162
+ /**
163
+ * A peer over `send(message)` and `receive(message)`: the same protocol over any duplex that is not wsh. `who` is who is on the far side, as an
164
+ * identity object (a pod id goes in `podId`, not in a field named `fingerprint`); `permit(root, op)` is the transport's own capability check
165
+ * for each operation (`get`, `call`, `set`, `on`, or `walk` for reading on the way): `true` allows, anything else and a throw refuse.
166
+ */
167
+ export function createDuplexPeer(options: { send(message: object): void; maxMessageBytes?: number; who?: ObjectsIdentity; permit?: (root: string, op: 'get' | 'call' | 'set' | 'on' | 'walk') => boolean }): ObjectsPeer & { receive(message: unknown): void; close(reason?: string): void; readonly closed: boolean };
120
168
 
121
169
  /** 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?: { timeoutMs?: number }): Promise<T>;
170
+ export function createObjectsClient<T = Record<string, any>>(peer: Pick<ObjectsPeer, 'request'> & Partial<ObjectsPeer>, options?: {
171
+ timeoutMs?: number;
172
+ /** A callback of ours threw: it stays here, the page never hears of it. */
173
+ onCallbackError?: (error: unknown) => void;
174
+ /** The host dropped calls of a callback (rate, size, a slow channel) before the one that follows. */
175
+ onCallbackDropped?: (info: { dropped: number; fn: (...args: any[]) => unknown }) => void;
176
+ }): Promise<T>;
123
177
 
124
178
  /** `exposeObjects`: the rpc handler for `wsh-objects`. Usable as `rpc: { 'wsh-objects': exposeObjects({ roots, allow }) }` in any host. */
125
179
  export interface ObjectsHandler {
package/src/objects.mjs CHANGED
@@ -20,6 +20,7 @@
20
20
  */
21
21
 
22
22
  import { RpcError } from './rpc.mjs';
23
+ import { callerIdentity } from './key-names.mjs';
23
24
  import { WshClient } from './client.mjs';
24
25
  import {
25
26
  OBJECTS_PROTOCOL, ObjectsError, createObjectsServer, createObjectsClient,
@@ -28,12 +29,15 @@ import {
28
29
  export {
29
30
  OBJECTS_PROTOCOL, OBJECTS_ERROR, OBJECTS_DEFAULT_LIMITS, NEEDS_LISTING, ObjectsError, NonValue,
30
31
  createObjectsServer, createObjectsClient, createDuplexPeer, matchPath, toWire, fromWire,
31
- get, set, call, construct, snapshot, describe, on, off, closeObjects,
32
+ get, set, call, construct, snapshot, describe, on, off, use, release, RemoteHandle, closeObjects,
32
33
  } from './objects-core.mjs';
33
34
 
34
35
  /** Timers for `callTimeoutMs` where the embedder gave none: this module is the Node-or-browser adapter, not the page entry point. */
35
36
  const defaultTimers = { setTimeout: (fn, ms) => setTimeout(fn, ms), clearTimeout: (id) => clearTimeout(id) };
36
37
 
38
+ /** The platform's CSPRNG for handle ids, where the embedder gave none (the page host gives its window's). */
39
+ const defaultRandom = (n) => globalThis.crypto.getRandomValues(new Uint8Array(n));
40
+
37
41
  /** 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
42
  function channelPeer(channel, host = {}) {
39
43
  // 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,10 +68,12 @@ function channelPeer(channel, host = {}) {
64
68
  * @param {object} [options.limits] - `maxOps`, `maxArgs`, `maxDepth`, `maxValueBytes`, `maxKeys`, `maxRequestsPerSecond`, `callTimeoutMs`
65
69
  */
66
70
  export function exposeObjects(options = {}) {
67
- const server = createObjectsServer({ timers: defaultTimers, ...options });
71
+ const server = createObjectsServer({ timers: defaultTimers, random: defaultRandom, ...options });
68
72
  const sessions = new Set();
69
73
  const handler = (channel, ctx = {}) => {
70
- const who = { username: ctx.user ?? null, fingerprint: ctx.fingerprint ?? null };
74
+ // A wsh caller is its key, `{ username, fingerprint }`. A handler called by an adapter that is not wsh (a mesh channel) is given the
75
+ // caller as `ctx.who` (`{ username, fingerprint?, podId? }`), and it is that identity that `authorize` and `closeSessions` see.
76
+ const who = callerIdentity(ctx.who ?? { username: ctx.user ?? null, fingerprint: ctx.fingerprint ?? null });
71
77
  server.attach(channelPeer(channel, ctx), { who });
72
78
  const session = { channel, who };
73
79
  sessions.add(session);
@@ -93,7 +93,8 @@ export interface WebMcpCall {
93
93
  consequential: boolean;
94
94
  readOnly: boolean;
95
95
  }
96
- export interface WebMcpWho { username: string | null; fingerprint: string | null }
96
+ /** Who is calling: `{ username, fingerprint }` over wsh; a transport that is not wsh may add `podId`, and then `fingerprint` is the hex hash of the same key. */
97
+ export interface WebMcpWho { username: string | null; fingerprint: string | null; podId?: string }
97
98
  /** Answers `true` to allow the call; anything else denies. `signal` aborts when the call is cancelled or the session ends. */
98
99
  export type WebMcpPrompt = (call: WebMcpCall, who: WebMcpWho, extra: { signal: AbortSignal }) => boolean | Promise<boolean>;
99
100
 
@@ -132,7 +133,7 @@ export interface WebMcpToolsOptions {
132
133
  /** The `mcp` rpc handler for `createMemoryHost({ rpc: { mcp } })`, `createReverseHost` and so on. It declares itself `capabilityScoped`. */
133
134
  export interface WebMcpHandler {
134
135
  /** It needs from the host's rpc context only who is calling and `permits` (a host that gives no `permits` serves every allowed tool). */
135
- (channel: RpcChannel, ctx?: { user?: string | null; fingerprint?: string | null; permits?: (request: { kind: string; [field: string]: unknown }) => boolean }): void;
136
+ (channel: RpcChannel, ctx?: { user?: string | null; fingerprint?: string | null; who?: { username?: string | null; fingerprint?: string | null; podId?: string | null }; permits?: (request: { kind: string; [field: string]: unknown }) => boolean }): void;
136
137
  capabilityScoped: true;
137
138
  /** Tell every session (or those of one key) why, then end it. Resolves with how many were ended. */
138
139
  closeSessions(reason: string, fingerprint?: string): Promise<number>;
@@ -143,6 +144,49 @@ export interface WebMcpHandler {
143
144
  /** The page's WebMCP tools as MCP, an rpc handler for the `mcp` protocol. */
144
145
  export function webmcpTools(options: WebMcpToolsOptions): WebMcpHandler;
145
146
 
147
+ /**
148
+ * The page host's badge as its own function: a row per connected key with its fingerprint and a Stop button. BEST EFFORT: page code can
149
+ * remove or cover a DOM element; Stop, revoke and the key's capabilities are the controls that hold.
150
+ */
151
+ export function createPageIndicator(window: WshPageWindow, options: { name: string }): {
152
+ show(who: { fingerprint: string | null }, stop: () => unknown): void;
153
+ hide(who: { fingerprint: string | null }): void;
154
+ ensure(): void;
155
+ destroy(): void;
156
+ };
157
+
158
+ /** A JSON-RPC 2.0 message as an object: what the far side of `serveMcpOverDuplex` speaks (plain MCP). */
159
+ export type McpMessage = { jsonrpc: '2.0'; id?: string | number; method?: string; params?: object; result?: unknown; error?: { code: number; message: string; data?: unknown } };
160
+
161
+ export interface ServeMcpOverDuplexOptions {
162
+ /** Writes a message to the far side. A throw or rejection ends the session. */
163
+ send(message: McpMessage): void | Promise<void>;
164
+ /** Who is on the far side, as the transport knows it. `fingerprint` and `podId` agree (one is derived from the other). */
165
+ who?: { username?: string | null; fingerprint?: string | null; podId?: string | null };
166
+ /** The far side's grants, asked afresh for each tool (`{ kind: 'mcp-tool', tool }`); `@johnhenry/wsh/capabilities`' `permits` fits. */
167
+ permits?: (request: { kind: string; [field: string]: unknown }) => boolean;
168
+ /** Default 1048576. The largest message, JSON-encoded, in either direction. */
169
+ maxMessageBytes?: number;
170
+ /** Default 64. Requests of the far side being answered at once, of any kind. */
171
+ maxInflight?: number;
172
+ }
173
+
174
+ export interface McpDuplexSession {
175
+ /** Hand over one message from the far side. Never throws. */
176
+ receive(message: unknown): void;
177
+ /** End the session: running calls are aborted, the handler's watchers removed. */
178
+ close(reason?: string): void;
179
+ readonly closed: boolean;
180
+ readonly who: { username: string | null; fingerprint: string | null; podId?: string } | undefined;
181
+ }
182
+
183
+ /**
184
+ * Serve the handler of `webmcpTools` (or any rpc handler of the `mcp` protocol) over any duplex: `send` and `receive` of plain MCP
185
+ * JSON-RPC 2.0 messages. The handler's bounds, approval hook and untrusted labelling are unchanged; the seam adds the size of a message,
186
+ * the requests running at once and one answer per id.
187
+ */
188
+ export function serveMcpOverDuplex(handler: (channel: any, ctx?: any) => void, options: ServeMcpOverDuplexOptions): McpDuplexSession;
189
+
146
190
  /** The default `prompt`: an accessible modal dialog in `window.document` (a key's fingerprint, the tool, the input as text; Deny has focus; Escape and a timeout deny). */
147
191
  export function createDomPrompt(window: WshPageWindow, options?: { timeoutMs?: number; timers?: WshPageTimers }): WebMcpPrompt;
148
192
 
@@ -165,9 +209,9 @@ export interface WshPageHostOptions {
165
209
  /**
166
210
  * Object access (`wsh-objects`, `values` mode), off unless written: named roots, each with its allow-lists by operation (paths RELATIVE to the root:
167
211
  * `'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`.
212
+ * `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
213
  */
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[]> }>;
214
+ 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
215
  /** `true` (default): the badge in `window.document`. Callbacks: for a context with no document, or your own UI. `false` needs `unattended: true`. */
172
216
  indicator?: boolean | WshPageIndicatorCallbacks;
173
217
  /** 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
@@ -32,8 +32,10 @@ import { pipeUrl } from './pipe-relay.mjs';
32
32
  import { webmcpTools, captureWebMcp, createDomPrompt, timersOf, WEBMCP_DEFAULT_LIMITS } from './webmcp.mjs';
33
33
  import { exposeObjects } from './objects.mjs';
34
34
  import { OBJECTS_PROTOCOL } from './objects-core.mjs';
35
+ import { serveMcpOverDuplex } from './mcp-duplex.mjs';
35
36
 
36
- export { webmcpTools, captureWebMcp, createDomPrompt, WEBMCP_DEFAULT_LIMITS, exposeObjects };
37
+ export { webmcpTools, captureWebMcp, createDomPrompt, WEBMCP_DEFAULT_LIMITS, exposeObjects, serveMcpOverDuplex };
38
+ export { createDomIndicator as createPageIndicator };
37
39
 
38
40
  const RECONNECT_START_MS = 1000;
39
41
  const RECONNECT_MAX_MS = 30_000;
@@ -72,13 +74,17 @@ function exposedRoots(window, expose) {
72
74
  const allow = { get: [], call: [], set: [], on: [] };
73
75
  const authorizers = new Map();
74
76
  const eventFields = {};
77
+ const handles = {};
75
78
  let limits;
76
79
  for (const name of names) {
77
80
  const cfg = expose[name];
78
81
  if (!isObj(cfg)) throw new TypeError(`createPageHost: expose.${name} must be { mode, allow }`);
79
- if (cfg.mode === 'handles') throw new TypeError("createPageHost: expose mode 'handles' is not built: only 'values' exists (handles and callbacks are a later step of #190)");
80
- if (cfg.mode !== undefined && cfg.mode !== 'values') throw new TypeError("createPageHost: expose mode must be 'values'");
81
- if (typeof cfg.allow === 'string') throw new TypeError('createPageHost: expose allow must be { get, call, set } (the wide-open form belongs to mode handles, which is not built)');
82
+ if (cfg.mode !== undefined && cfg.mode !== 'values' && cfg.mode !== 'handles') throw new TypeError("createPageHost: expose mode must be 'values' (the default) or 'handles'");
83
+ 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');
84
+ // 'handles' is this root's own opt-in; `nodes: true` is a second one, for nodes, windows and documents: control of the page.
85
+ 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'`);
86
+ 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'`);
87
+ if (cfg.mode === 'handles') handles[name] = { nodes: cfg.nodes === true, wideEntries: cfg.wideEntries === true };
82
88
  const object = cfg.object ?? (name === 'window' ? window : undefined);
83
89
  if (object === undefined) throw new TypeError(`createPageHost: expose.${name}: only a root named "window" is the window; give { object } for another root`);
84
90
  roots[name] = object;
@@ -96,10 +102,16 @@ function exposedRoots(window, expose) {
96
102
  if (cfg.limits !== undefined) limits = { ...limits, ...cfg.limits };
97
103
  }
98
104
  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 };
105
+ return { roots, allow, authorize, limits, eventFields, handles };
100
106
  }
101
107
 
102
- /** The indicator in the page: one row per connected key, with the key's fingerprint and a Stop control. */
108
+ /**
109
+ * The indicator in the page: one row per connected key, with the key's fingerprint and a Stop control. Exported as `createPageIndicator(window,
110
+ * { name })` for an embedder that serves a session of its own (a mesh adapter) and wants the same badge: `show(who, stop)` adds a row for `who`
111
+ * (its fingerprint) with a Stop button that calls `stop()`, `hide(who)` removes it, `ensure()` puts the badge back if page code took it out,
112
+ * `destroy()` removes everything. BEST EFFORT: it is a DOM element of the page, which page code can remove or cover; Stop, a revoke and the
113
+ * key's capabilities are the controls that hold, not the badge.
114
+ */
103
115
  function createDomIndicator(window, { name }) {
104
116
  const doc = window.document;
105
117
  const make = (tag, props = {}, text) => {
@@ -152,7 +164,7 @@ function createDomIndicator(window, { name }) {
152
164
  * optionally the rendezvous id (default: a fresh random one, exposed as `host.rendezvousId`)
153
165
  * @param {Record<string, { mode?: 'values', allow?: { get?: string[], call?: string[], set?: string[] }, authorize?: Function, limits?: object, object?: object }>} [options.expose]
154
166
  * 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 refused: not built.
167
+ * 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
168
  * See `@johnhenry/wsh/objects` for what `values` mode promises.
157
169
  * @param {string} options.name - what this tab is called (shown in the indicator, the `serverInfo` of the MCP server)
158
170
  * @param {string | Uint8Array | Array<string | Uint8Array>} options.authorizedKeys - who may log in, as `authorized_keys` lines (with their
@@ -253,7 +265,9 @@ export async function createPageHost(options = {}) {
253
265
  guard: () => gone() ?? mcp.guard?.() ?? null,
254
266
  }) : null;
255
267
  const objectsHandler = exposed ? exposeObjects({
256
- roots: exposed.roots, allow: exposed.allow, authorize: exposed.authorize, limits: exposed.limits, eventFields: exposed.eventFields, timers,
268
+ roots: exposed.roots, allow: exposed.allow, authorize: exposed.authorize, limits: exposed.limits, eventFields: exposed.eventFields, handles: exposed.handles, timers,
269
+ // Handle ids come from the served window's own CSPRNG.
270
+ random: (n) => window.crypto.getRandomValues(new Uint8Array(n)),
257
271
  guard: () => gone(),
258
272
  }) : null;
259
273
  /** What each handler tells and ends: the sessions of a key, or all of them. */
@@ -592,7 +592,9 @@ export function createConnectionFactory(cfg) {
592
592
  state.channelBinding = boundKinds;
593
593
  let allowed = false;
594
594
  try {
595
- allowed = await cfg.authorize({ username: state.username, fingerprint: fp, publicKey: m.public_key });
595
+ // `sealRequired`: this host serves nothing until the session is sealed (after login), so a login here is not yet a session
596
+ // that can do anything; `cfg.onSealed` says when it is.
597
+ allowed = await cfg.authorize({ username: state.username, fingerprint: fp, publicKey: m.public_key, ...(sealRequired ? { sealRequired: true } : {}) });
596
598
  } catch (e) { log(`authorize threw: ${e.message}`); }
597
599
  if (!allowed) return refuse('key not authorized', 'unauthorized', claimed);
598
600
  // `authorize` may answer with a capability set (`{ permissions }` from `buildAuthorizer`): it narrows what the key's own options allow.
@@ -638,6 +640,7 @@ export function createConnectionFactory(cfg) {
638
640
  if (result.key) {
639
641
  sealed.bridge = new SealedBridge({ key: result.key, sessionId: state.sessionId, role: 'responder', scope: 'session' });
640
642
  log(`session sealed${result.hybrid ? ' (hybrid)' : ''}`);
643
+ try { cfg.onSealed?.({ username: state.username, fingerprint: state.fingerprint }); } catch (e) { log(`onSealed threw: ${e.message}`); }
641
644
  }
642
645
  } catch (e) { log(`sealed session refused: ${e.message}`); reportRefused('seal-failed', `key exchange failed: ${e.message}`); shutdown('sealed session key exchange failed'); }
643
646
  return undefined;
@@ -9,10 +9,10 @@
9
9
  import { MSG, gatewayOk, gatewayFail, gatewayClose, gatewayData, gatewayCredit, listenFail } from '../messages.gen.mjs';
10
10
  import { GatewayChannel, GATEWAY_CREDIT_FEATURE, GATEWAY_CREDIT_WINDOW } from '../gateway-channel.mjs';
11
11
 
12
- /** Numeric codes of GatewayFail (the same table `@johnhenry/browsermesh-netway` decodes). */
13
- export const GATEWAY_FAIL = Object.freeze({
14
- CONNECTION_REFUSED: 1, HOST_UNREACHABLE: 2, DNS_FAILED: 3, POLICY_DENIED: 4, TIMEOUT: 5, CLOSED: 6, QUEUE_FULL: 7,
15
- });
12
+ import { GATEWAY_FAIL } from '../gateway-errors.mjs';
13
+
14
+ /** Numeric codes of GatewayFail: the table of `gateway-errors.mjs` (what `@johnhenry/browsermesh-netway` decodes), under its old name here. */
15
+ export { GATEWAY_FAIL };
16
16
 
17
17
  export const DEFAULT_MAX_CONNECTIONS = 32;
18
18
  export const DEFAULT_MAX_BUFFERED = 4 * 1024 * 1024;
@@ -0,0 +1,115 @@
1
+ /**
2
+ * Test doubles for code that embeds wsh (part of `@johnhenry/wsh/testing`: NOT part of the stable API). Browser-safe: no port, no Node
3
+ * built-in, so a test in a page or a worker can use them too.
4
+ *
5
+ * - `createInProcessPipeRelay()`: the real pipe relay (`createPipeRelay`) living in this process, with a `WebSocket` constructor that
6
+ * dials it, a record of every message it copied, and a `tap` that may change, drop, repeat or add to what it writes (what a hostile
7
+ * relay could do). Two parties that dial it with the same rendezvous id are joined, and run the real handshake and sealed session.
8
+ * - `createMemoryPair()`: a memory host and a client already logged in to it, with a key the pair made and authorized.
9
+ */
10
+
11
+ import { createPipeRelay } from './pipe-relay.mjs';
12
+ import { createMemoryHost, createSocketPair } from './memory-host.mjs';
13
+ import { generateKeyPair, exportPublicKeyRaw } from './auth.mjs';
14
+
15
+ const toBytes = (data) => (data instanceof ArrayBuffer
16
+ ? new Uint8Array(data)
17
+ : new Uint8Array(data.buffer, data.byteOffset, data.byteLength));
18
+
19
+ /**
20
+ * A pipe relay in this process, for tests: no network, no ports.
21
+ *
22
+ * `new env.WebSocket(pipeUrl(anyBase, id, role))` dials it (the base is ignored; the path's last segment is the rendezvous id and
23
+ * `?role=host` the host side). A `WshClient` takes `env.WebSocket` as its WebSocket (`new WebSocketTransport({ WebSocket: env.WebSocket })`)
24
+ * and a host accepts the other half with `host.accept(new env.WebSocket(pipeUrl(base, id, 'host')))`.
25
+ *
26
+ * Every message the relay writes is recorded in `env.recorded` as `{ to: 'host' | 'operator', id, bytes }` (`to` is the role it was
27
+ * written to), BEFORE `tap` runs. `env.tap` (set at creation or later) is called for each such message and may return `undefined` to pass
28
+ * it through, `null` to drop it, or one `Uint8Array` or an array of them to write instead (change, repeat, add). `env.dropAll()` ends every
29
+ * pipe at once, as a relay restart would.
30
+ *
31
+ * @param {object} [options]
32
+ * @param {(info: { to: 'host' | 'operator', id: string, bytes: Uint8Array }) => (Uint8Array | Uint8Array[] | null | undefined)} [options.tap]
33
+ * @param {object} [options.relayOptions] options of `createPipeRelay()` (limits, `authorize`, ...)
34
+ * @returns {Promise<{ relay: object, recorded: Array<{ to: string, id: string, bytes: Uint8Array }>, tap: Function | null, WebSocket: Function, stats(): { waiting: number, pipes: number }, dropAll(): void, close(): Promise<void> }>}
35
+ */
36
+ export async function createInProcessPipeRelay({ tap = null, relayOptions } = {}) {
37
+ if (tap !== null && typeof tap !== 'function') throw new TypeError('createInProcessPipeRelay: tap must be a function');
38
+ const relay = createPipeRelay(relayOptions);
39
+ const sockets = new Set();
40
+ const env = {
41
+ relay,
42
+ recorded: [],
43
+ tap,
44
+ stats: () => relay.stats(),
45
+ /** End every pipe, as a relay restart would. */
46
+ dropAll() {
47
+ for (const s of [...sockets]) { try { s.close(1012, 'relay restarted'); } catch { /* already closed */ } }
48
+ },
49
+ async close() {
50
+ env.dropAll();
51
+ await relay.close();
52
+ },
53
+ WebSocket: null,
54
+ };
55
+ env.WebSocket = class InProcessWebSocket {
56
+ constructor(url) {
57
+ const u = new URL(url);
58
+ const id = u.pathname.split('/').pop();
59
+ const role = u.searchParams.get('role') === 'host' ? 'host' : 'operator';
60
+ const [client, server] = createSocketPair();
61
+ const send = server.send.bind(server);
62
+ server.send = (data) => {
63
+ // A text frame (the paired signal) is not wsh bytes: it is passed on as it is, and not recorded.
64
+ if (typeof data === 'string') { send(data); return; }
65
+ const bytes = toBytes(data);
66
+ env.recorded.push({ to: role, id, bytes: bytes.slice() });
67
+ let out = [bytes];
68
+ if (env.tap) {
69
+ const r = env.tap({ to: role, id, bytes });
70
+ if (r === null) out = [];
71
+ else if (r !== undefined) out = Array.isArray(r) ? r : [r];
72
+ }
73
+ for (const b of out) send(b);
74
+ };
75
+ sockets.add(server);
76
+ server.addEventListener('close', () => sockets.delete(server));
77
+ void relay.accept(server, { id, role, notifyPaired: role === 'host' && u.searchParams.get('paired') === '1' }).catch(() => {});
78
+ return client;
79
+ }
80
+ };
81
+ return env;
82
+ }
83
+
84
+ /**
85
+ * A memory host and a client already logged in to it.
86
+ *
87
+ * With no `host.auth` it makes (or uses) an Ed25519 key and authorizes exactly that key. With `host.auth` it uses the host exactly as given,
88
+ * and the client logs in with what you say (`keyPair`, or `credentials` such as `{ password }`).
89
+ *
90
+ * @param {object} [options]
91
+ * @param {object} [options.host] options of `createMemoryHost()` (`exec`, `rpc`, `hostKey`, `sealSession`, ...)
92
+ * @param {string} [options.username='alice']
93
+ * @param {CryptoKeyPair} [options.keyPair] a key to log in with (made if not given); it is authorized unless `host.auth` is given
94
+ * @param {object} [options.credentials] extra options of `host.connect()` (`password`, `timeout`, ...), merged over the key login
95
+ * @returns {Promise<{ host: object, client: object, username: string, keyPair: CryptoKeyPair | null, close(): Promise<void> }>}
96
+ */
97
+ export async function createMemoryPair({ host: hostOptions = {}, username = 'alice', keyPair, credentials = {} } = {}) {
98
+ if (hostOptions === null || typeof hostOptions !== 'object') throw new TypeError('createMemoryPair: host must be the options of createMemoryHost()');
99
+ const own = hostOptions.auth !== undefined;
100
+ if (own && keyPair === undefined && credentials.password === undefined && credentials.signer === undefined && credentials.keyPair === undefined) {
101
+ throw new TypeError('createMemoryPair: host.auth is given, so say how to log in: a keyPair it authorizes, or credentials ({ password } or { signer })');
102
+ }
103
+ const key = keyPair ?? (own ? null : await generateKeyPair(true));
104
+ const host = createMemoryHost(own ? hostOptions : { ...hostOptions, auth: { authorizedKeys: [await exportPublicKeyRaw(key.publicKey)] } });
105
+ let client;
106
+ try {
107
+ client = await host.connect({ username, ...(key ? { keyPair: key } : {}), ...credentials });
108
+ } catch (e) { await host.close(); throw e; }
109
+ return {
110
+ host, client, username, keyPair: key,
111
+ async close() {
112
+ try { await client.disconnect(); } finally { await host.close(); }
113
+ },
114
+ };
115
+ }
package/src/testing.d.ts CHANGED
@@ -46,5 +46,49 @@ export class QMuxProtocolError extends Error {
46
46
  readonly errorCode: number;
47
47
  }
48
48
 
49
+ import type { WshClient } from './index.js';
50
+ import type { WshMemoryHost, WshMemoryHostOptions, WshMemoryConnectOptions } from './memory-host.js';
51
+ import type { PipeRelay, PipeRelayOptions } from './pipe-relay.js';
52
+
53
+ /** One message the in-process relay wrote. */
54
+ export interface RelayTapInfo { to: 'host' | 'operator'; id: string; bytes: Uint8Array }
55
+
56
+ /** A pipe relay that lives in this process (see `createInProcessPipeRelay`). */
57
+ export interface InProcessPipeRelay {
58
+ /** The real relay (`createPipeRelay()`); `accept` is wired to the sockets `WebSocket` hands out. */
59
+ relay: PipeRelay;
60
+ /** Every message the relay wrote, before `tap` ran: `to` is the role it was written to. */
61
+ recorded: Array<{ to: 'host' | 'operator'; id: string; bytes: Uint8Array }>;
62
+ /** Called for each message the relay writes: `undefined` passes it, `null` drops it, bytes (or an array of them) are written instead. May be set at any time. */
63
+ tap: ((info: RelayTapInfo) => Uint8Array | Uint8Array[] | null | undefined) | null;
64
+ /** A `WebSocket` constructor that dials this relay: `new env.WebSocket(pipeUrl(anyBase, id, role))`. */
65
+ WebSocket: new (url: string) => any;
66
+ stats(): { waiting: number; pipes: number };
67
+ /** End every pipe at once, as a relay restart would. */
68
+ dropAll(): void;
69
+ close(): Promise<void>;
70
+ }
71
+
72
+ /** The real pipe relay running in this process, with a record and a tap for a hostile one. No port, no Node built-in. */
73
+ export function createInProcessPipeRelay(options?: { tap?: InProcessPipeRelay['tap']; relayOptions?: PipeRelayOptions }): Promise<InProcessPipeRelay>;
74
+
75
+ export interface MemoryPair {
76
+ host: WshMemoryHost;
77
+ client: WshClient;
78
+ username: string;
79
+ /** The key the client logged in with (`null` when `host.auth` was given and the client logs in some other way). */
80
+ keyPair: CryptoKeyPair | null;
81
+ /** Disconnects the client, then closes the host. */
82
+ close(): Promise<void>;
83
+ }
84
+
85
+ /** A memory host and a client already logged in to it. Without `host.auth`, it makes (or uses) a key and authorizes exactly that key. */
86
+ export function createMemoryPair(options?: {
87
+ host?: WshMemoryHostOptions;
88
+ username?: string;
89
+ keyPair?: CryptoKeyPair;
90
+ credentials?: Partial<WshMemoryConnectOptions>;
91
+ }): Promise<MemoryPair>;
92
+
49
93
  /** Machine-readable form of the notice: `stable` is `false`. */
50
94
  export const QMUX_TESTING_API: Readonly<{ stable: false; notice: string }>;
package/src/testing.mjs CHANGED
@@ -20,6 +20,9 @@ export {
20
20
  QMuxProtocolError,
21
21
  } from './qmux.mjs';
22
22
 
23
+ // Test doubles: a pipe relay that lives in this process (with a tap for a hostile relay), and a memory host with a client logged in.
24
+ export { createInProcessPipeRelay, createMemoryPair } from './testing-doubles.mjs';
25
+
23
26
  /** Machine-readable form of the notice above, so a test (or a reader) can check what it imported. */
24
27
  export const QMUX_TESTING_API = Object.freeze({
25
28
  stable: false,
package/src/transport.mjs CHANGED
@@ -384,7 +384,7 @@ function decodeHashString(str) {
384
384
  // Strip the separators OpenSSL and friends emit, plus any surrounding
385
385
  // whitespace: "SHA256 Fingerprint=" style output is colon-separated,
386
386
  // and hand-copied values often carry spaces or dashes.
387
- const compact = str.trim().replace(/^[^=]*fingerprint[^=]*=\s*/i, '');
387
+ const compact = str.trim().replace(/^[^=]{0,64}fingerprint[^=]{0,64}=\s*/i, '');
388
388
  const hexish = compact.replace(/[\s:-]/g, '');
389
389
 
390
390
  if (/^[0-9a-fA-F]+$/.test(hexish) && hexish.length % 2 === 0) {
package/src/webmcp.mjs CHANGED
@@ -21,6 +21,7 @@
21
21
  */
22
22
 
23
23
  import { RpcError, RPC_ERROR } from './rpc.mjs';
24
+ import { callerIdentity } from './key-names.mjs';
24
25
 
25
26
  const TOOL_NAME_RE = /^[A-Za-z0-9_.-]{1,128}$/;
26
27
  const APPROVE_MODES = new Set(['never', 'consequential', 'always']);
@@ -441,11 +442,13 @@ export function webmcpTools(options = {}) {
441
442
  }
442
443
 
443
444
  /** What one session may see: allowed, listable, within `maxTools`, and permitted by its key. */
444
- async function visible(permits) {
445
+ async function visible(permits, kind = 'mcp-tool') {
445
446
  const out = [];
446
447
  for (const tool of (await gather()).values()) {
447
448
  if (!allowed.has(tool.name)) continue;
448
- if (permits && !permits({ kind: 'mcp-tool', tool: tool.name })) continue;
449
+ // The hook is told which it is: `mcp-tool` is listing a tool, `mcp-call` is running one (`op` says the same as `'list'` / `'call'`),
450
+ // so an adapter may scope them apart. The notation's `mcp:TOOL` covers both.
451
+ if (permits && !permits({ kind, op: kind === 'mcp-call' ? 'call' : 'list', tool: tool.name })) continue;
449
452
  const bad = unlistable(tool, limits);
450
453
  if (bad) { emit({ outcome: 'unlisted', name: tool.name, limit: bad.limit, detail: bad.detail }); continue; }
451
454
  if (out.length >= limits.maxTools) { emit({ outcome: 'unlisted', name: tool.name, limit: 'maxTools', detail: `more than ${limits.maxTools} tools` }); continue; }
@@ -464,7 +467,8 @@ export function webmcpTools(options = {}) {
464
467
  };
465
468
 
466
469
  function handler(channel, ctx = {}) {
467
- const who = { username: ctx.user ?? null, fingerprint: ctx.fingerprint ?? null };
470
+ // A wsh caller is its key, `{ username, fingerprint }`; a transport that is not wsh (`serveMcpOverDuplex`) gives `ctx.who`, which may carry a `podId`.
471
+ const who = callerIdentity(ctx.who ?? { username: ctx.user ?? null, fingerprint: ctx.fingerprint ?? null });
468
472
  const permits = typeof ctx.permits === 'function' ? ctx.permits : null;
469
473
  const session = { channel, who, inflight: new Map(), starts: [], approvals: Promise.resolve(), unsubscribe: null, listed: null, closed: false };
470
474
  sessions.add(session);
@@ -507,7 +511,7 @@ export function webmcpTools(options = {}) {
507
511
  if (session.starts.length >= limits.maxCallsPerMinute) throw fail('maxCallsPerMinute', `more than ${limits.maxCallsPerMinute} calls in a minute`, { name });
508
512
  session.starts.push(t);
509
513
 
510
- const tool = (await visible(permits)).find((x) => x.name === name);
514
+ const tool = (await visible(permits, 'mcp-call')).find((x) => x.name === name);
511
515
  // A tool that is not allowed, not permitted to this key or not there looks the same.
512
516
  if (!tool) { emit({ outcome: 'unknown', name, who }); throw new RpcError(RPC_ERROR.INVALID_PARAMS, `unknown tool: ${name}`); }
513
517
  const text = jsonOrNull(args) ?? '';