@johnhenry/wsh 0.48.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.
@@ -0,0 +1,184 @@
1
+ /**
2
+ * MCP over any duplex (#220). The handler of `webmcpTools` (and any rpc handler of the `mcp` protocol written as `(channel, ctx) => void`)
3
+ * serves MCP on a channel; over wsh that channel is an `RpcChannel` of the `mcp` rpc protocol. `serveMcpOverDuplex` gives the same handler
4
+ * a channel made of nothing but two functions you already have: `send(message)` for what goes to the far side, and `receive(message)` for
5
+ * what comes from it, so a transport that is not wsh at all (a mesh channel, a `MessagePort`, a data channel, a test) can carry it.
6
+ *
7
+ * ```js
8
+ * import { webmcpTools, serveMcpOverDuplex } from '@johnhenry/wsh/page';
9
+ * const handler = webmcpTools({ window, allow: ['search'], approve: 'consequential' });
10
+ * const session = serveMcpOverDuplex(handler, { send: (message) => meshChannel.send(message), who: { podId } });
11
+ * meshChannel.onmessage = (message) => session.receive(message);
12
+ * meshChannel.onclose = () => session.close('the peer left');
13
+ * ```
14
+ *
15
+ * WHAT THE FAR SIDE SPEAKS: plain MCP, that is JSON-RPC 2.0 messages as JavaScript objects (`{ jsonrpc: '2.0', id, method, params }`,
16
+ * `{ jsonrpc: '2.0', id, result }` or `{ jsonrpc: '2.0', id, error: { code, message, data? } }`, and notifications with no `id`): an MCP SDK
17
+ * `Client` can be connected to it through any `Transport` that moves those objects. Encoding them (JSON text, CBOR, structured clone) is the
18
+ * transport's business; this file sees objects. No batches (MCP no longer has them), no ids but strings and integers, one answer per id.
19
+ *
20
+ * WHAT IS THE HANDLER'S, UNCHANGED: the allow-list of tools, the bounds on tools, schemas, arguments and results, the approval of the
21
+ * person at the page (`approve`, `prompt`), the `onCall` events and the labelling of every result as untrusted page content. WHAT THIS
22
+ * ADDS: the bounds of the seam itself (the size of a message in either direction, the requests running at once, one id one request), and
23
+ * the refusal of anything that is not a JSON-RPC 2.0 message from the far side.
24
+ *
25
+ * It does NOT authenticate the far side or seal anything: whoever the transport says is on the other end is `who`, and `permits` is
26
+ * whatever that transport's grants allow. Those are the adapter's to establish and say; they are not in the messages.
27
+ */
28
+
29
+ import { RpcError, RPC_ERROR } from './rpc.mjs';
30
+ import { callerIdentity } from './key-names.mjs';
31
+
32
+ const DEFAULT_MAX_MESSAGE_BYTES = 1024 * 1024;
33
+ const DEFAULT_MAX_INFLIGHT = 64;
34
+ const MAX_ID_CHARS = 256;
35
+
36
+ const isObject = (v) => v !== null && typeof v === 'object' && !Array.isArray(v);
37
+
38
+ /** UTF-8 length of the JSON of `value` (the size of the message on a JSON transport), or -1 when it has none. */
39
+ function jsonBytes(value) {
40
+ let s;
41
+ try { s = JSON.stringify(value); } catch { return -1; }
42
+ if (typeof s !== 'string') return -1;
43
+ let n = 0;
44
+ for (let i = 0; i < s.length; i++) {
45
+ const c = s.charCodeAt(i);
46
+ if (c < 0x80) n += 1;
47
+ else if (c < 0x800) n += 2;
48
+ else if (c >= 0xd800 && c <= 0xdbff) { n += 4; i++; } else n += 3;
49
+ }
50
+ return n;
51
+ }
52
+
53
+ const validId = (id) => (typeof id === 'string' && id.length >= 1 && id.length <= MAX_ID_CHARS) || (Number.isSafeInteger(id));
54
+
55
+ /**
56
+ * Serve an MCP handler over a duplex.
57
+ *
58
+ * @param {(channel: object, ctx?: object) => void} handler what `webmcpTools(...)` returns, or any handler written for an rpc channel of the `mcp` protocol
59
+ * @param {object} options
60
+ * @param {(message: object) => void | Promise<void>} options.send writes a JSON-RPC 2.0 message to the far side; a throw (or a rejection) ends the session
61
+ * @param {{ username?: string | null, fingerprint?: string | null, podId?: string | null }} [options.who] who is on the far side, as the transport knows
62
+ * it: the handler's prompt, `onCall` events and `closeSessions(reason, fingerprint)` see it (`fingerprint` and `podId` agree, see `callerIdentity`)
63
+ * @param {(request: { kind: string, [field: string]: unknown }) => boolean} [options.permits] the far side's grants, asked afresh for each tool
64
+ * (`{ kind: 'mcp-tool', tool }`); with none, nothing narrows the handler's own allow-list. `@johnhenry/wsh/capabilities`'s `permits` fits: `(req) => permits(caps, req)`
65
+ * @param {number} [options.maxMessageBytes=1048576] the largest message, JSON-encoded, in either direction
66
+ * @param {number} [options.maxInflight=64] requests of the far side being answered at once, of any kind
67
+ * @returns {{ receive(message: unknown): void, close(reason?: string): void, readonly closed: boolean, readonly who: object | undefined }}
68
+ */
69
+ export function serveMcpOverDuplex(handler, options = {}) {
70
+ if (typeof handler !== 'function') throw new TypeError('serveMcpOverDuplex: the handler must be a function (channel, ctx), what webmcpTools() returns');
71
+ const { send, who, permits, maxMessageBytes = DEFAULT_MAX_MESSAGE_BYTES, maxInflight = DEFAULT_MAX_INFLIGHT } = options;
72
+ if (typeof send !== 'function') throw new TypeError('serveMcpOverDuplex: send(message) is required');
73
+ if (permits !== undefined && typeof permits !== 'function') throw new TypeError('serveMcpOverDuplex: permits must be a function');
74
+ if (!Number.isSafeInteger(maxMessageBytes) || maxMessageBytes < 256) throw new TypeError('serveMcpOverDuplex: maxMessageBytes must be a whole number of at least 256');
75
+ if (!Number.isSafeInteger(maxInflight) || maxInflight < 1) throw new TypeError('serveMcpOverDuplex: maxInflight must be a positive whole number');
76
+ const identity = callerIdentity(who);
77
+
78
+ let closed = false;
79
+ const requestHandlers = new Map();
80
+ const notificationHandlers = new Map();
81
+ /** id -> its AbortController, for what is being answered. */
82
+ const inflight = new Map();
83
+
84
+ const fail = (reason) => { try { session.close(reason); } catch { /* already closing */ } };
85
+ /** Write one message; a throw or rejection of the transport ends the session. Resolves when written. */
86
+ async function write(message) {
87
+ if (closed) return;
88
+ const size = jsonBytes(message);
89
+ if (size < 0) throw new TypeError('the message cannot be serialised as JSON');
90
+ if (size > maxMessageBytes) throw new RpcError(RPC_ERROR.INTERNAL, `refused: a message of ${size} bytes is larger than maxMessageBytes (${maxMessageBytes})`, { reason: 'message-too-large' });
91
+ try { await send(message); } catch (e) { fail('the transport failed to send'); throw e; }
92
+ }
93
+ const respond = (id, body) => write({ jsonrpc: '2.0', id, ...body }).catch(() => {});
94
+ const refuse = (id, code, message, data) => respond(id, { error: { code, message, ...(data !== undefined ? { data } : {}) } });
95
+
96
+ /** The channel the handler is given: the part of an `RpcChannel` that an MCP handler uses. */
97
+ const channel = {
98
+ maxMessageBytes,
99
+ onRequest(method, fn) { requestHandlers.set(method, fn); },
100
+ onNotification(method, fn) { notificationHandlers.set(method, fn); },
101
+ notify: (method, params) => write({ jsonrpc: '2.0', method, ...(params !== undefined ? { params } : {}) }),
102
+ request: () => Promise.reject(new RpcError(RPC_ERROR.METHOD_NOT_FOUND, 'this side serves MCP and asks the far side nothing')),
103
+ close: async (reason) => { session.close(reason); },
104
+ onClose: null,
105
+ get closed() { return closed; },
106
+ };
107
+
108
+ async function dispatch(id, method, params) {
109
+ const fn = requestHandlers.get(method);
110
+ if (!fn) { await refuse(id, RPC_ERROR.METHOD_NOT_FOUND, `method not found: ${method}`); return; }
111
+ const ctl = new AbortController();
112
+ inflight.set(id, ctl);
113
+ try {
114
+ const result = await fn(params, { id, signal: ctl.signal });
115
+ // A cancelled request is not answered: the far side said it no longer wants the answer.
116
+ if (!closed && !ctl.signal.aborted) {
117
+ const body = { jsonrpc: '2.0', id, result: result === undefined ? {} : result };
118
+ const size = jsonBytes(body);
119
+ if (size < 0) await refuse(id, RPC_ERROR.INTERNAL, 'the answer cannot be serialised as JSON');
120
+ else if (size > maxMessageBytes) await refuse(id, RPC_ERROR.INTERNAL, `refused: the answer is ${size} bytes, larger than maxMessageBytes (${maxMessageBytes})`, { reason: 'message-too-large' });
121
+ else await write(body).catch(() => {});
122
+ }
123
+ } catch (e) {
124
+ if (!closed && !ctl.signal.aborted) {
125
+ if (e instanceof RpcError) await refuse(id, e.code, e.message, e.toJSON().data);
126
+ else await refuse(id, RPC_ERROR.INTERNAL, String(e?.message ?? e));
127
+ }
128
+ } finally {
129
+ inflight.delete(id);
130
+ }
131
+ }
132
+
133
+ const session = {
134
+ /** Hand over one message from the far side. Never throws: what cannot be answered is refused or dropped. */
135
+ receive(message) {
136
+ if (closed) return;
137
+ if (!isObject(message) || message.jsonrpc !== '2.0') {
138
+ // An id we can read is answered; anything else is dropped (there is no one to tell).
139
+ if (isObject(message) && validId(message.id)) void refuse(message.id, RPC_ERROR.INVALID_REQUEST, 'not a JSON-RPC 2.0 message (batches are not supported)');
140
+ else if (Array.isArray(message) || message === null || typeof message !== 'object') void refuse(null, RPC_ERROR.INVALID_REQUEST, 'not a JSON-RPC 2.0 message (batches are not supported)');
141
+ return;
142
+ }
143
+ const size = jsonBytes(message);
144
+ if (size < 0 || size > maxMessageBytes) {
145
+ void refuse(validId(message.id) ? message.id : null, RPC_ERROR.INVALID_REQUEST, `refused: a message larger than maxMessageBytes (${maxMessageBytes})`, { reason: 'message-too-large' });
146
+ return;
147
+ }
148
+ const hasId = Object.hasOwn(message, 'id');
149
+ if (typeof message.method !== 'string') {
150
+ // A response (or error) of the far side: nothing here asked it anything.
151
+ if (hasId && !('result' in message) && !('error' in message)) void refuse(validId(message.id) ? message.id : null, RPC_ERROR.INVALID_REQUEST, 'a request needs a method');
152
+ return;
153
+ }
154
+ if (message.params !== undefined && !isObject(message.params)) {
155
+ if (hasId) void refuse(validId(message.id) ? message.id : null, RPC_ERROR.INVALID_REQUEST, 'params must be an object');
156
+ return;
157
+ }
158
+ if (!hasId) {
159
+ // A notification. Cancellation is the one the seam knows: it aborts the request the far side names.
160
+ if (message.method === 'notifications/cancelled') inflight.get(message.params?.requestId)?.abort(new Error('cancelled by the caller'));
161
+ try { notificationHandlers.get(message.method)?.(message.params); } catch { /* a notification has no one to tell */ }
162
+ return;
163
+ }
164
+ if (!validId(message.id)) { void refuse(null, RPC_ERROR.INVALID_REQUEST, 'a request id is a string or a whole number'); return; }
165
+ if (inflight.has(message.id)) { void refuse(message.id, RPC_ERROR.INVALID_REQUEST, `request id ${JSON.stringify(message.id)} is still in flight`); return; }
166
+ if (inflight.size >= maxInflight) { void refuse(message.id, RPC_ERROR.STREAM_LIMIT, `refused: maxInflight: more than ${maxInflight} requests at once`, { limit: 'maxInflight' }); return; }
167
+ void dispatch(message.id, message.method, message.params);
168
+ },
169
+
170
+ /** End the session: running calls are aborted, the handler's watchers are removed, nothing more is answered. */
171
+ close(reason = 'closed') {
172
+ if (closed) return;
173
+ closed = true;
174
+ for (const ctl of inflight.values()) ctl.abort(new Error(`the session ended (${reason})`));
175
+ try { channel.onClose?.(reason); } catch { /* the handler's own */ }
176
+ },
177
+
178
+ get closed() { return closed; },
179
+ get who() { return identity; },
180
+ };
181
+
182
+ handler(channel, { ...(identity ? { who: identity, user: identity.username, fingerprint: identity.fingerprint } : {}), ...(permits ? { permits } : {}) });
183
+ return session;
184
+ }
@@ -90,6 +90,11 @@ export interface WshMemoryHostOptions {
90
90
  sealSession?: false | 'offer' | 'require';
91
91
  /** #163: told once per connection this host turned away (a key it does not allow, a plain client on a host that requires a sealed session, ...), with a stable reason code. */
92
92
  onRefused?: WshOnRefused;
93
+ /**
94
+ * Called once per connection when its session has been sealed (after login). With `sealSession: 'require'` a login is not yet a session
95
+ * that can do anything: `auth.authorize(who)` is told `who.sealRequired: true`, and audit or an indicator belongs here instead.
96
+ */
97
+ onSealed?: (who: { username: string | null; fingerprint: string | null }) => void;
93
98
  /**
94
99
  * #121: execution targets, each with its own `exec`, `pty`, `fs` and `endpoints` and an `authorize(who, { target, kind })`.
95
100
  * A client names one in `Open`, `FileOp` or `OpenEndpoint` and lists what it may use with `listTargets()`. Off unless given:
@@ -180,7 +180,8 @@ function createRegistry(sessions, log) {
180
180
  * @param {(line: string) => void} [options.onLog]
181
181
  */
182
182
  export function createMemoryHost({ auth, exec, pty, fs, hostKey, mcp, extensions, rpc, rpcMaxMessageBytes = RPC_DEFAULT_MAX_MESSAGE, rpcMaxInflight = 64, sessions, endpoints, dataStreams = true, bindTimeoutMs = 3000, connectionTtlMs = 0, requireChannelBinding = false, sealSession = false, onLog = () => {},
183
- onShare, onRefused, targets, requireTarget, usernamePattern } = {}) {
183
+ onShare, onRefused, onSealed, targets, requireTarget, usernamePattern } = {}) {
184
+ if (onSealed !== undefined && typeof onSealed !== 'function') throw new TypeError('createMemoryHost: onSealed must be a function');
184
185
  resolveUsernamePattern(usernamePattern, 'createMemoryHost');
185
186
  validateOnShare(onShare, 'createMemoryHost');
186
187
  validateOnRefused(onRefused, 'createMemoryHost');
@@ -217,7 +218,7 @@ export function createMemoryHost({ auth, exec, pty, fs, hostKey, mcp, extensions
217
218
 
218
219
  const ready = Promise.all([buildAuthorizer(auth, { log: onLog }), hostKeyReady]).then(([authorize, hostKeyResolved]) => createConnectionFactory({
219
220
  authorize, execRunner, execOptions, pty: ptyBackend, files, bindTimeoutMs, connectionTtlMs, requireChannelBinding, sealSession, log: onLog,
220
- methods, hostKey: hostKeyResolved, rateLimit, extensions, mcp: mcpHost, rpc: rpcHost, onShare, onRefused,
221
+ methods, hostKey: hostKeyResolved, rateLimit, extensions, mcp: mcpHost, rpc: rpcHost, onShare, onRefused, onSealed,
221
222
  targets: targetTable, requireTarget: mustHaveTarget, usernamePattern,
222
223
  gateway: gatewayCfg, createGatewaySession: gatewayCfg ? createEndpointGatewaySession : undefined, sessions: registry, relay: null,
223
224
  }));
@@ -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). */
@@ -460,8 +462,14 @@ export function createObjectsServer(options = {}) {
460
462
  }
461
463
  }
462
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
+
463
471
  function permitted(ctx, root, op) {
464
- if (typeof ctx.permit !== 'function' || ctx.permit(root, op) === true) return;
472
+ if (keyMay(ctx, root, op)) return;
465
473
  throw refuse('not-permitted', `refused: this key's capabilities do not allow ${op === 'walk' ? 'reading' : op} on ${root}`, { root, op });
466
474
  }
467
475
 
@@ -592,7 +600,7 @@ export function createObjectsServer(options = {}) {
592
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. */
593
601
  function previewOf(value, root, segs, ctx) {
594
602
  if (!lists.get.some((p) => matchPath(p, segs))) return {};
595
- if (typeof ctx.permit === 'function' && ctx.permit(root, 'get') !== true) return {};
603
+ if (!keyMay(ctx, root, 'get')) return {};
596
604
  const rel = segs.slice(1).map(bareName);
597
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 {};
598
606
  try {
@@ -852,9 +860,14 @@ export function createObjectsServer(options = {}) {
852
860
  return { ok: true, dropped: sub.dropped };
853
861
  }
854
862
 
855
- /** 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
+ */
856
868
  function attach(peer, { who } = {}) {
857
869
  if (typeof peer?.onRequest !== 'function') throw new TypeError('attach: the peer needs onRequest(method, handler)');
870
+ const defaultWho = callerIdentity(who);
858
871
  const session = { peer, subs: new Map(), queue: [], pumping: false, closed: false, handles: new Map(), callbacks: new Map(), deadCalls: 0 };
859
872
  // The end of the channel (the peer left, Stop, a navigation, a revoke) takes every listener out of the page's sources.
860
873
  const prior = peer.onClose;
@@ -876,14 +889,14 @@ export function createObjectsServer(options = {}) {
876
889
  stamps.push(t);
877
890
  // A value is kept under what the transport carries in one message, with room for the envelope.
878
891
  const maxBytes = Math.min(limits.maxValueBytes, Math.max(1024, (peer.maxMessageBytes ?? Infinity) - 4096));
879
- 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 };
880
893
  if (params === null || typeof params !== 'object' || Array.isArray(params)) throw invalid('params must be an object');
881
894
  try { return await fn(params, call); } catch (e) { if (e instanceof ObjectsError) throw e; throw wrapThrown(e, name); }
882
895
  });
883
896
  // A key that may use only some roots is told of those only.
884
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.
885
898
  method('roots', async (_params, call) => ({
886
- roots: rootNames.filter((name) => typeof call.permit !== 'function' || call.permit(name, 'walk') === true),
899
+ roots: rootNames.filter((name) => keyMay(call, name, 'walk')),
887
900
  features: ['events', 'callbacks', ...(handleRoots.size ? ['handles'] : [])],
888
901
  }));
889
902
  method('resolve', resolve);
@@ -905,10 +918,20 @@ export function createObjectsServer(options = {}) {
905
918
  /**
906
919
  * A `Peer` over `send(message)` and `receive(message)` (JSON-RPC-shaped plain objects: requests `{ id, method, params }`, responses
907
920
  * `{ id, result }` / `{ id, error }`, notifications `{ method, params }`, and `$/cancel` and `$/progress`). For a transport that is not wsh.
908
- * @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
909
930
  */
910
- export function createDuplexPeer({ send, maxMessageBytes = 1024 * 1024 } = {}) {
931
+ export function createDuplexPeer({ send, maxMessageBytes = 1024 * 1024, who, permit } = {}) {
911
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);
912
935
  let nextId = 1;
913
936
  let closed = false;
914
937
  const pending = new Map();
@@ -948,7 +971,7 @@ export function createDuplexPeer({ send, maxMessageBytes = 1024 * 1024 } = {}) {
948
971
  if (!handler) { send({ id, error: { code: -32601, message: `method not found: ${message.method}` } }); return; }
949
972
  const ctl = new AbortController();
950
973
  inflight.set(id, ctl);
951
- 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 } : {}) };
952
975
  Promise.resolve().then(() => handler(message.params, ctx)).then(
953
976
  (result) => { if (ctl.signal.aborted) return; send({ id, result: result === undefined ? null : result }); },
954
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 } : {}) } }); },
package/src/objects.d.ts CHANGED
@@ -92,7 +92,15 @@ export interface ObjectsAllow {
92
92
  on?: string[];
93
93
  }
94
94
 
95
- 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 }
96
104
  export interface ObjectsOperation {
97
105
  kind: 'get' | 'call' | 'construct' | 'set' | 'on' | 'describe' | 'snapshot';
98
106
  /** For `on`: the event type. */
@@ -134,7 +142,7 @@ export interface ObjectsServerOptions {
134
142
 
135
143
  /** What the core needs of a transport (an `RpcChannel` is one; `createDuplexPeer` makes one from `send` and `receive`). */
136
144
  export interface ObjectsPeer {
137
- 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;
138
146
  onNotification?(method: string, handler: (params: any) => void): unknown;
139
147
  request(method: string, params?: unknown, options?: { signal?: AbortSignal; onProgress?: (chunk: unknown) => void }): Promise<any>;
140
148
  notify(method: string, params?: unknown): unknown;
@@ -145,13 +153,18 @@ export interface ObjectsPeer {
145
153
 
146
154
  /** The transport-neutral server half: roots, allow-lists and limits, attachable to any peer. Knows nothing about wsh. */
147
155
  export function createObjectsServer(options: ObjectsServerOptions): {
148
- 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 };
149
158
  readonly limits: Readonly<ObjectsLimits>;
150
159
  readonly rootNames: string[];
151
160
  };
152
161
 
153
- /** A peer over `send(message)` and `receive(message)`: the same protocol over any duplex that is not wsh. */
154
- 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 };
155
168
 
156
169
  /** The client half over any peer: the roots, as lazy references. */
157
170
  export function createObjectsClient<T = Record<string, any>>(peer: Pick<ObjectsPeer, 'request'> & Partial<ObjectsPeer>, options?: {
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,
@@ -70,7 +71,9 @@ export function exposeObjects(options = {}) {
70
71
  const server = createObjectsServer({ timers: defaultTimers, random: defaultRandom, ...options });
71
72
  const sessions = new Set();
72
73
  const handler = (channel, ctx = {}) => {
73
- 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 });
74
77
  server.attach(channelPeer(channel, ctx), { who });
75
78
  const session = { channel, who };
76
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
 
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;
@@ -103,7 +105,13 @@ function exposedRoots(window, expose) {
103
105
  return { roots, allow, authorize, limits, eventFields, handles };
104
106
  }
105
107
 
106
- /** 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
+ */
107
115
  function createDomIndicator(window, { name }) {
108
116
  const doc = window.document;
109
117
  const make = (tag, props = {}, text) => {
@@ -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
+ }