@johnhenry/wsh 0.48.0 → 0.50.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +156 -30
- package/package.json +21 -3
- package/spec/capabilities.md +175 -0
- package/spec/capabilities.vectors.json +200 -0
- package/spec/duplex-binding.md +86 -0
- package/spec/key-options.vectors.json +248 -0
- package/spec/message-matrix.md +259 -0
- package/spec/wsh-v1.md +1607 -0
- package/spec/wsh-v1.yaml +2783 -0
- package/src/auth.mjs +3 -34
- package/src/capabilities.d.ts +53 -0
- package/src/capabilities.mjs +69 -0
- package/src/duplex.d.ts +69 -0
- package/src/duplex.mjs +208 -0
- package/src/gateway-errors.mjs +45 -0
- package/src/identity.d.ts +61 -0
- package/src/identity.mjs +194 -0
- package/src/index.d.ts +11 -0
- package/src/index.mjs +1 -0
- package/src/key-names.mjs +115 -0
- package/src/key-options.mjs +5 -0
- package/src/mcp-duplex.mjs +184 -0
- package/src/memory-host.d.ts +5 -0
- package/src/memory-host.mjs +3 -2
- package/src/objects-core.mjs +31 -8
- package/src/objects.d.ts +18 -5
- package/src/objects.mjs +4 -1
- package/src/page-host.d.ts +46 -2
- package/src/page-host.mjs +10 -2
- package/src/server/connection.mjs +15 -7
- package/src/server/gateway-core.mjs +4 -4
- package/src/server/socket.mjs +5 -2
- package/src/testing-doubles.mjs +115 -0
- package/src/testing.d.ts +44 -0
- package/src/testing.mjs +3 -0
- package/src/transport.mjs +1 -1
- package/src/webmcp.mjs +8 -4
package/src/objects-core.mjs
CHANGED
|
@@ -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 (
|
|
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 (
|
|
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
|
-
/**
|
|
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
|
|
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) =>
|
|
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
|
-
*
|
|
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
|
-
|
|
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?:
|
|
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
|
-
|
|
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
|
-
/**
|
|
154
|
-
|
|
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
|
-
|
|
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);
|
package/src/page-host.d.ts
CHANGED
|
@@ -93,7 +93,8 @@ export interface WebMcpCall {
|
|
|
93
93
|
consequential: boolean;
|
|
94
94
|
readOnly: boolean;
|
|
95
95
|
}
|
|
96
|
-
|
|
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
|
-
/**
|
|
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) => {
|
|
@@ -164,7 +164,7 @@ export function createConnectionFactory(cfg) {
|
|
|
164
164
|
* `dataStreams: false` means there are no client-opened streams to bind, so exec output rides SessionData.
|
|
165
165
|
* `e2e` overrides `cfg.e2e` for this connection.
|
|
166
166
|
*/
|
|
167
|
-
return function attach({ send: sendBytes, sendMessage = null, remote = {}, authenticated = null, dataStreams = true, closeTransport = null, e2e: e2eOverride, channelBinding = null, datagrams = null }) {
|
|
167
|
+
return function attach({ send: sendBytes, sendMessage = null, remote = {}, authenticated = null, dataStreams = true, closeTransport = null, e2e: e2eOverride, channelBinding = null, datagrams = null, sealSession: sealOverride }) {
|
|
168
168
|
const cid = ++counter;
|
|
169
169
|
const log = (m) => cfg.log(`[conn ${cid}] ${m}`);
|
|
170
170
|
const state = {
|
|
@@ -260,8 +260,13 @@ export function createConnectionFactory(cfg) {
|
|
|
260
260
|
|
|
261
261
|
// A sealed session (#155): after login, a signed KeyExchange for this connection's session id seals everything
|
|
262
262
|
// that follows (control messages, gateway and endpoint data included) as EncryptedFrames on channel 0.
|
|
263
|
-
|
|
264
|
-
|
|
263
|
+
// `sealSession: 'require'` in the options of this connection may only STRENGTHEN the host's setting (a transport that cannot vouch for itself,
|
|
264
|
+
// a duplex someone else carries, asks for it); a host that cannot seal (no host key, or client-opened data streams) then cannot serve it at all.
|
|
265
|
+
if (sealOverride !== undefined && sealOverride !== 'require') throw new TypeError("attach: sealSession can only be 'require' for one connection");
|
|
266
|
+
if (sealOverride === 'require' && (!cfg.hostKey || dataStreams)) throw new Error('this connection must be sealed, and this host cannot seal it (it needs a host key and dataStreams: false)');
|
|
267
|
+
const sealMode = sealOverride === 'require' ? 'require' : cfg.sealSession;
|
|
268
|
+
const sealOn = !!sealMode && !!cfg.hostKey && !dataStreams;
|
|
269
|
+
const sealRequired = sealOn && sealMode === 'require';
|
|
265
270
|
/** @type {{ bridge: SealedBridge | null, responder: E2EResponder | null }} */
|
|
266
271
|
const sealed = { bridge: null, responder: null };
|
|
267
272
|
|
|
@@ -520,11 +525,11 @@ export function createConnectionFactory(cfg) {
|
|
|
520
525
|
} else {
|
|
521
526
|
return refuse(`unsupported auth method ${JSON.stringify(method)}`, 'bad-request', { username: user });
|
|
522
527
|
}
|
|
523
|
-
if (
|
|
528
|
+
if (sealRequired && method !== 'pubkey') return refuse('this host requires a sealed session, which needs a key login', 'not-sealed', { username: user });
|
|
524
529
|
state.username = user;
|
|
525
530
|
state.method = method;
|
|
526
531
|
gateway?.setPeerFeatures(m.features);
|
|
527
|
-
const features = hostFeatures(cfg, { dataStreams });
|
|
532
|
+
const features = hostFeatures(sealMode === cfg.sealSession ? cfg : { ...cfg, sealSession: sealMode }, { dataStreams });
|
|
528
533
|
// UDP over datagrams only where this transport has them and the gateway serves (and allows) UDP.
|
|
529
534
|
if (datagrams && cfg.gateway?.tcp && cfg.gateway.udp?.datagrams) features.push(GATEWAY_DATAGRAM_FEATURE);
|
|
530
535
|
let hostFingerprint;
|
|
@@ -592,7 +597,9 @@ export function createConnectionFactory(cfg) {
|
|
|
592
597
|
state.channelBinding = boundKinds;
|
|
593
598
|
let allowed = false;
|
|
594
599
|
try {
|
|
595
|
-
|
|
600
|
+
// `sealRequired`: this host serves nothing until the session is sealed (after login), so a login here is not yet a session
|
|
601
|
+
// that can do anything; `cfg.onSealed` says when it is.
|
|
602
|
+
allowed = await cfg.authorize({ username: state.username, fingerprint: fp, publicKey: m.public_key, ...(sealRequired ? { sealRequired: true } : {}) });
|
|
596
603
|
} catch (e) { log(`authorize threw: ${e.message}`); }
|
|
597
604
|
if (!allowed) return refuse('key not authorized', 'unauthorized', claimed);
|
|
598
605
|
// `authorize` may answer with a capability set (`{ permissions }` from `buildAuthorizer`): it narrows what the key's own options allow.
|
|
@@ -638,6 +645,7 @@ export function createConnectionFactory(cfg) {
|
|
|
638
645
|
if (result.key) {
|
|
639
646
|
sealed.bridge = new SealedBridge({ key: result.key, sessionId: state.sessionId, role: 'responder', scope: 'session' });
|
|
640
647
|
log(`session sealed${result.hybrid ? ' (hybrid)' : ''}`);
|
|
648
|
+
try { cfg.onSealed?.({ username: state.username, fingerprint: state.fingerprint }); } catch (e) { log(`onSealed threw: ${e.message}`); }
|
|
641
649
|
}
|
|
642
650
|
} catch (e) { log(`sealed session refused: ${e.message}`); reportRefused('seal-failed', `key exchange failed: ${e.message}`); shutdown('sealed session key exchange failed'); }
|
|
643
651
|
return undefined;
|
|
@@ -861,7 +869,7 @@ export function createConnectionFactory(cfg) {
|
|
|
861
869
|
if (requireTarget) return send(openFail({ reason: 'a target is required' }));
|
|
862
870
|
{
|
|
863
871
|
const protocol = typeof m.command === 'string' ? m.command : '';
|
|
864
|
-
const refusal = keyRefusal({ kind: 'open', channel: 'rpc', protocol, scoped: cfg.rpc?.protocols.get(protocol)?.capabilityScoped === true });
|
|
872
|
+
const refusal = keyRefusal({ kind: 'open', channel: 'rpc', protocol, scoped: cfg.rpc?.protocols.get(protocol)?.capabilityScoped === true, authorizesItself: cfg.rpc?.protocols.get(protocol)?.authorizesItself === true });
|
|
865
873
|
if (refusal) return send(openFail({ reason: refusal.reason }));
|
|
866
874
|
}
|
|
867
875
|
return openRpc(m);
|
|
@@ -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
|
-
|
|
13
|
-
|
|
14
|
-
|
|
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;
|
package/src/server/socket.mjs
CHANGED
|
@@ -35,10 +35,12 @@ async function toBytes(data) {
|
|
|
35
35
|
* @param {{ remote?: { address?: string, headers?: object }, dataStreams?: boolean }} [options] - what the host knows about the peer
|
|
36
36
|
* (`address` keys the password-failure throttle; the default key is shared by every socket without one).
|
|
37
37
|
* `dataStreams: false` serves this connection without client-opened data streams (exec output rides SessionData), for a
|
|
38
|
-
* client that cannot open them (the Rust client over WebSocket, #132).
|
|
38
|
+
* client that cannot open them (the Rust client over WebSocket, #132). `sealSession: 'require'` makes THIS connection serve nothing
|
|
39
|
+
* until it is sealed, whatever the host's own setting (it can only strengthen it; a host with no host key, or with data streams, refuses to
|
|
40
|
+
* attach it: `ready` rejects). It is what `@johnhenry/wsh/duplex` asks of a transport it cannot vouch for.
|
|
39
41
|
* @returns {Promise<{ close(): void }>} resolves once the connection is attached; `close()` drops it
|
|
40
42
|
*/
|
|
41
|
-
export function bindSocket(socket, ready, { remote = {}, dataStreams } = {}) {
|
|
43
|
+
export function bindSocket(socket, ready, { remote = {}, dataStreams, sealSession } = {}) {
|
|
42
44
|
if (!socket || typeof socket.send !== 'function' || typeof socket.close !== 'function') {
|
|
43
45
|
throw new TypeError('accept: socket must be a WebSocket-like duplex with send() and close()');
|
|
44
46
|
}
|
|
@@ -74,6 +76,7 @@ export function bindSocket(socket, ready, { remote = {}, dataStreams } = {}) {
|
|
|
74
76
|
send: write,
|
|
75
77
|
remote: { address: remote.address, headers: remote.headers ?? {} },
|
|
76
78
|
dataStreams,
|
|
79
|
+
...(sealSession !== undefined ? { sealSession } : {}),
|
|
77
80
|
closeTransport: () => { try { socket.close(1000); } catch { /* already closed */ } },
|
|
78
81
|
});
|
|
79
82
|
});
|
|
@@ -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(/^[^=]
|
|
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
|
-
|
|
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
|
-
|
|
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) ?? '';
|