@johnhenry/wsh 0.49.0 → 0.51.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 +139 -20
- package/bin/wsh-objects-types.mjs +98 -0
- package/package.json +11 -2
- package/spec/capabilities.md +1 -0
- package/spec/duplex-binding.md +86 -0
- package/spec/objects.md +176 -0
- package/spec/wsh-v1.yaml +9 -1
- package/src/duplex.d.ts +69 -0
- package/src/duplex.mjs +208 -0
- package/src/key-options.mjs +3 -0
- package/src/objects-core.mjs +112 -14
- package/src/objects-mcp.mjs +130 -0
- package/src/objects-schema.mjs +143 -0
- package/src/objects-type-text.mjs +95 -0
- package/src/objects-types.d.ts +38 -0
- package/src/objects-types.mjs +290 -0
- package/src/objects.d.ts +113 -5
- package/src/objects.mjs +4 -1
- package/src/page-host.d.ts +2 -2
- package/src/page-host.mjs +29 -9
- package/src/server/connection.mjs +11 -6
- package/src/server/socket.mjs +5 -2
- package/src/webmcp.mjs +17 -4
package/src/objects-core.mjs
CHANGED
|
@@ -25,6 +25,8 @@
|
|
|
25
25
|
*/
|
|
26
26
|
|
|
27
27
|
import { callerIdentity } from './key-names.mjs';
|
|
28
|
+
import { describeRootTypes, narrowTypes } from './objects-types.mjs';
|
|
29
|
+
import { buildMcpTools } from './objects-mcp.mjs';
|
|
28
30
|
|
|
29
31
|
export const OBJECTS_PROTOCOL = 'wsh-objects';
|
|
30
32
|
|
|
@@ -368,7 +370,7 @@ function isPromiseLike(v) {
|
|
|
368
370
|
* @param {() => number} [options.now]
|
|
369
371
|
*/
|
|
370
372
|
export function createObjectsServer(options = {}) {
|
|
371
|
-
const { roots, mode = 'values', allow = {}, authorize, limits: limitOptions = {}, guard, timers = null, eventFields = {}, handles = {}, random = null, now = () => Date.now() } = options;
|
|
373
|
+
const { roots, mode = 'values', allow = {}, authorize, limits: limitOptions = {}, guard, timers = null, eventFields = {}, handles = {}, random = null, types = {}, mcp, now = () => Date.now() } = options;
|
|
372
374
|
if (mode === 'handles') throw new TypeError("exposeObjects: handles are chosen per root, not for the host: use handles: { window: {} } (and nodes: true on a root that may hand out nodes)");
|
|
373
375
|
if (mode !== 'values') throw new TypeError("exposeObjects: mode must be 'values' (handles are chosen per root with handles: { ROOT: {} })");
|
|
374
376
|
if (typeof allow === 'string') throw new TypeError('exposeObjects: allow must be { get, call, set, on }: a wide-open string is not accepted, and the allow-lists apply to handles too');
|
|
@@ -431,6 +433,21 @@ export function createObjectsServer(options = {}) {
|
|
|
431
433
|
}
|
|
432
434
|
}
|
|
433
435
|
|
|
436
|
+
// Types for the far side's `.d.ts` (`types: { 'window.app.cart.add': { args: '[item: { sku: string }]', result: 'number' } }`): host-authored text that is sent to the far side.
|
|
437
|
+
// It is checked when the host is created (a conservative type syntax, bounded, and only for a path that an allow-list entry names), so a bad text is a TypeError here, not something the far side finds.
|
|
438
|
+
if (!types || typeof types !== 'object' || Array.isArray(types)) throw new TypeError('exposeObjects: types must be { [path]: { value?, args?, result?, data? } }');
|
|
439
|
+
const typesByRoot = new Map();
|
|
440
|
+
for (const [key, spec] of Object.entries(types)) {
|
|
441
|
+
const root = key.split(/[.@]/, 1)[0];
|
|
442
|
+
if (!rootNames.includes(root)) throw new TypeError(`exposeObjects: types names ${JSON.stringify(key.slice(0, 60))}, which is not under a root`);
|
|
443
|
+
if (!typesByRoot.has(root)) typesByRoot.set(root, {});
|
|
444
|
+
typesByRoot.get(root)[key] = spec;
|
|
445
|
+
}
|
|
446
|
+
const allowStrings = { get: allow.get ?? [], call: allow.call ?? [], set: allow.set ?? [], on: allow.on ?? [] };
|
|
447
|
+
for (const [root, map] of typesByRoot) {
|
|
448
|
+
try { describeRootTypes({ root, allow: allowStrings, eventFields, types: map }); } catch (e) { throw new TypeError(String(e?.message ?? e).replace(/^describeRootTypes:/, 'exposeObjects:')); }
|
|
449
|
+
}
|
|
450
|
+
|
|
434
451
|
/** The checks every operation passes, in order. `terminal` ones need the operation's own list; the rest need only to walk toward something allowed. */
|
|
435
452
|
async function check(kind, root, segs, ctx, { terminal, type, callbacks = 0 }) {
|
|
436
453
|
const who = ctx.who;
|
|
@@ -438,6 +455,19 @@ export function createObjectsServer(options = {}) {
|
|
|
438
455
|
if (gone) throw refuse('gone', `refused: ${gone}`);
|
|
439
456
|
// 0. what the caller's key may do on this root, if the transport says (`ctx.permit(root, op)`, asked afresh: an expiry holds at call time)
|
|
440
457
|
permitted(ctx, root, kind === 'get' && !terminal ? 'walk' : kind === 'construct' ? 'call' : kind === 'describe' || kind === 'snapshot' ? 'get' : kind);
|
|
458
|
+
staticCheck(kind, root, segs, { terminal, type, callbacks });
|
|
459
|
+
if (terminal && authorize) {
|
|
460
|
+
let ok = false;
|
|
461
|
+
try { ok = (await authorize(who ?? {}, { kind, root, path: segs.slice(1), text: segs.join('.'), ...(type !== undefined ? { type } : {}), ...(callbacks ? { callbacks } : {}) })) === true; } catch { ok = false; }
|
|
462
|
+
if (!ok) throw refuse('authorize', `refused: ${kind} of ${segs.join('.')} was not authorized`, { path: segs.join('.'), op: kind });
|
|
463
|
+
}
|
|
464
|
+
}
|
|
465
|
+
|
|
466
|
+
/**
|
|
467
|
+
* The part of `check` that needs nothing of the caller: the allow-lists and the names that need listing. It is what makes an MCP tool for a path possible when the host is
|
|
468
|
+
* configured (the path must pass it for its operation), and it is the same code every call passes.
|
|
469
|
+
*/
|
|
470
|
+
function staticCheck(kind, root, segs, { terminal, type, callbacks = 0 }) {
|
|
441
471
|
const rel = segs.slice(1).map(bareName);
|
|
442
472
|
const own = lists[kind === 'construct' ? 'call' : kind === 'describe' || kind === 'snapshot' ? 'get' : kind];
|
|
443
473
|
// 1. the allow-list: the operation's own list for the operation itself, any list for walking toward something
|
|
@@ -455,11 +485,6 @@ export function createObjectsServer(options = {}) {
|
|
|
455
485
|
const listed = terminal ? own.some((p) => matchPath(p, segs) && patternNames(p, seq)) : every.some((p) => prefixPath(p, segs) && patternNames(p, seq));
|
|
456
486
|
if (!listed) throw refuse('needs-listing', `refused: "${rel.join('.')}" is refused until an allow-list entry names ${seq.join('.')} (a wildcard does not)`, { path: segs.join('.') });
|
|
457
487
|
}
|
|
458
|
-
if (terminal && authorize) {
|
|
459
|
-
let ok = false;
|
|
460
|
-
try { ok = (await authorize(who ?? {}, { kind, root, path: segs.slice(1), text: segs.join('.'), ...(type !== undefined ? { type } : {}), ...(callbacks ? { callbacks } : {}) })) === true; } catch { ok = false; }
|
|
461
|
-
if (!ok) throw refuse('authorize', `refused: ${kind} of ${segs.join('.')} was not authorized`, { path: segs.join('.'), op: kind });
|
|
462
|
-
}
|
|
463
488
|
}
|
|
464
489
|
|
|
465
490
|
/** 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. */
|
|
@@ -613,6 +638,13 @@ export function createObjectsServer(options = {}) {
|
|
|
613
638
|
async function releaseHandle(params, ctx) {
|
|
614
639
|
const { session } = ctx;
|
|
615
640
|
if (typeof params.handle !== 'string' || !session.handles.delete(params.handle)) throw invalid('no such handle (it was released, belongs to another session, or never existed)');
|
|
641
|
+
// The event subscriptions made through the handle end with it: the listeners leave the page's sources, and what they had queued is dropped.
|
|
642
|
+
for (const [id, sub] of [...session.subs]) {
|
|
643
|
+
if (sub.handle !== params.handle) continue;
|
|
644
|
+
session.subs.delete(id);
|
|
645
|
+
removeSub(sub);
|
|
646
|
+
session.queue = session.queue.filter((q) => q.sub !== sub);
|
|
647
|
+
}
|
|
616
648
|
return { ok: true };
|
|
617
649
|
}
|
|
618
650
|
|
|
@@ -826,7 +858,12 @@ export function createObjectsServer(options = {}) {
|
|
|
826
858
|
|
|
827
859
|
async function subscribe(params, ctx) {
|
|
828
860
|
const { session } = ctx;
|
|
829
|
-
|
|
861
|
+
// Where the source is looked for starts at a root, or at a handle of THIS channel: a handle stands at the path that produced it, and what is subscribed to is that
|
|
862
|
+
// path extended by `params.path`, judged exactly as a path subscription for it (its own `allow.on` entry naming the type, the key's `on`, `authorize`).
|
|
863
|
+
const start = startOf(params, ctx);
|
|
864
|
+
const { root } = start;
|
|
865
|
+
const handleId = params.handle;
|
|
866
|
+
const handleRec = handleId === undefined ? null : session.handles.get(handleId);
|
|
830
867
|
const type = params.type;
|
|
831
868
|
if (typeof type !== 'string' || !EVENT_TYPE_RE.test(type)) throw invalid('an event type is a name of letters, digits and _ $ : . - (up to 128)');
|
|
832
869
|
const id = params.id;
|
|
@@ -836,11 +873,16 @@ export function createObjectsServer(options = {}) {
|
|
|
836
873
|
const offered = [...(eventFields[type] ?? []), ...(eventFields['*'] ?? [])];
|
|
837
874
|
for (const f of asked) if (!offered.includes(f)) throw refuse('not-allowed', `refused: the field "${f}" of ${type} events is not offered by this host`, { field: f, type });
|
|
838
875
|
if (session.subs.size >= limits.maxSubscriptions) throw limitError('maxSubscriptions', limits.maxSubscriptions, 'too many event subscriptions on this channel');
|
|
839
|
-
const { cur: source, segs } = await walk(
|
|
876
|
+
const { cur: source, segs } = await walk(start, params.path ?? [], ctx);
|
|
840
877
|
await check('on', root, segs, ctx, { terminal: true, type });
|
|
878
|
+
// The checks above may have waited (`authorize`): the handle may have been released, the channel may have ended, another subscribe may have taken the last place.
|
|
879
|
+
if (session.closed) throw refuse('gone', 'refused: the channel ended');
|
|
880
|
+
if (handleRec &&session.handles.get(handleId) !== handleRec) throw invalid('no such handle (it was released, belongs to another session, or never existed)');
|
|
881
|
+
if (session.subs.has(id)) throw invalid('a subscription id is a whole number the channel has not used');
|
|
882
|
+
if (session.subs.size >= limits.maxSubscriptions) throw limitError('maxSubscriptions', limits.maxSubscriptions, 'too many event subscriptions on this channel');
|
|
841
883
|
const kind = sourceMethods(source);
|
|
842
884
|
if (!kind) throw new ObjectsError(OBJECTS_ERROR.FAILED, `${segs.join('.')} is not an event source (it needs addEventListener, or on and off)`, { reason: 'not-an-event-source' });
|
|
843
|
-
const sub = { id, type, kind: kind.kind, fields: [...new Set(asked)], source, stamps: [], dropped: 0, seq: 0, remove: kind.remove, listener: null };
|
|
885
|
+
const sub = { id, type, kind: kind.kind, fields: [...new Set(asked)], source, stamps: [], dropped: 0, seq: 0, remove: kind.remove, listener: null, handle: handleRec ? handleId : undefined };
|
|
844
886
|
sub.listener = (...args) => deliver(session, sub, args);
|
|
845
887
|
try { Reflect.apply(Reflect.get(Object(source), kind.add, source), source, [type, sub.listener]); } catch (e) { throw wrapThrown(e, `${segs.join('.')}.${kind.add}`); }
|
|
846
888
|
session.subs.set(id, sub);
|
|
@@ -897,8 +939,24 @@ export function createObjectsServer(options = {}) {
|
|
|
897
939
|
// The host also says what it supports (additive: an older client ignores it), so a client does not send a function to a host that would drop it, nor misread a handle.
|
|
898
940
|
method('roots', async (_params, call) => ({
|
|
899
941
|
roots: rootNames.filter((name) => keyMay(call, name, 'walk')),
|
|
900
|
-
features: ['events', 'callbacks', ...(handleRoots.size ? ['handles'] : [])],
|
|
942
|
+
features: ['events', 'callbacks', 'types', ...(handleRoots.size ? ['handles', 'handle-events'] : [])],
|
|
901
943
|
}));
|
|
944
|
+
// What this key may do on one root, as data a far side turns into a `.d.ts` (`describeRootTypes`): the allow-list entries of that root for the operations the key's
|
|
945
|
+
// capabilities grant, the host's type map for them, the event fields of the types it may subscribe to. Nothing of another root, and nothing that is not allowed.
|
|
946
|
+
method('types', async (params, call) => {
|
|
947
|
+
const root = requireRoot(params);
|
|
948
|
+
permitted(call, root, 'walk');
|
|
949
|
+
const ops = ['get', 'call', 'set', 'on'].filter((op) => keyMay(call, root, op));
|
|
950
|
+
const mine = (list) => (Array.isArray(list) ? list : []).filter((entry) => { const first = String(entry).split(/[.@]/, 1)[0]; return first === root || first === '*' || first === '**'; });
|
|
951
|
+
const lists = Object.fromEntries(['get', 'call', 'set', 'on'].map((op) => [op, ops.includes(op) ? mine(allowStrings[op]) : []]));
|
|
952
|
+
const typeMap = narrowTypes({ root, ops, allow: allowStrings, types: typesByRoot.get(root) ?? {} });
|
|
953
|
+
const offered = new Set(lists.on.map((entry) => entry.slice(entry.indexOf('@') + 1)));
|
|
954
|
+
const fields = Object.fromEntries(Object.entries(eventFields).filter(([type]) => type === '*' ? offered.size > 0 : offered.has(type)));
|
|
955
|
+
const answer = { version: 1, root, ops, allow: lists, eventFields: fields, types: typeMap, handles: handleRoots.has(root) };
|
|
956
|
+
const size = toWire(answer, { maxDepth: 6, maxBytes: call.maxBytes ?? limits.maxValueBytes });
|
|
957
|
+
if (!('v' in size)) throw new ObjectsError(OBJECTS_ERROR.FAILED, 'the description could not be written', { reason: 'bad-reply' });
|
|
958
|
+
return size.v;
|
|
959
|
+
});
|
|
902
960
|
method('resolve', resolve);
|
|
903
961
|
method('set', setValue);
|
|
904
962
|
method('describe', describe);
|
|
@@ -910,7 +968,32 @@ export function createObjectsServer(options = {}) {
|
|
|
910
968
|
return { limits, handleCount: () => session.handles.size, callbackCount: () => session.callbacks.size, deadCallbackCalls: () => session.deadCalls };
|
|
911
969
|
}
|
|
912
970
|
|
|
913
|
-
|
|
971
|
+
/**
|
|
972
|
+
* One `get` or `call` of a named path (`path` starts with the root: `['window', 'app', 'cart', 'add']`), through the same checks as an objects call: the key's grants
|
|
973
|
+
* (`permit(root, op)`), the allow-lists, the names that need listing, `authorize` and the window guard. No session: nothing here makes a handle or takes a callback, and the
|
|
974
|
+
* answer is the wire value (`{ v }`, or a named non-value `{ u }`). `args` are plain data, copied and bounded like the arguments of a call. This is what an MCP tool runs.
|
|
975
|
+
* @param {{ kind: 'get' | 'call', path: string[], args?: unknown[] }} request
|
|
976
|
+
* @param {{ who?: object, permit?: (root: string, op: string) => boolean, signal?: AbortSignal }} [ctx]
|
|
977
|
+
*/
|
|
978
|
+
async function invoke({ kind, path, args = [] } = {}, { who, permit, signal } = {}) {
|
|
979
|
+
if (kind !== 'get' && kind !== 'call') throw invalid('invoke: kind must be get or call');
|
|
980
|
+
if (!Array.isArray(path) || path.length < 2 || !path.every((s) => typeof s === 'string')) throw invalid('invoke: path must be a root and at least one member');
|
|
981
|
+
if (!Array.isArray(args)) throw invalid('invoke: args must be an array');
|
|
982
|
+
const root = requireRoot({ root: path[0] });
|
|
983
|
+
const last = path.length - 2;
|
|
984
|
+
const ops = path.slice(1).map((key, i) => (kind === 'call' && i === last ? { call: key, args } : { get: key }));
|
|
985
|
+
return resolve({ root, ops }, { who: callerIdentity(who) ?? undefined, permit, signal, maxBytes: limits.maxValueBytes });
|
|
986
|
+
}
|
|
987
|
+
|
|
988
|
+
// The MCP face (#219): tools for named allow-listed paths, built from the host's `mcp: { tools }`. Empty unless the host wrote it.
|
|
989
|
+
const mcpTools = buildMcpTools({
|
|
990
|
+
mcp,
|
|
991
|
+
rootNames,
|
|
992
|
+
allows: (kind, root, segs) => staticCheck(kind, root, segs, { terminal: true }),
|
|
993
|
+
invoke,
|
|
994
|
+
});
|
|
995
|
+
|
|
996
|
+
return { attach, invoke, limits: Object.freeze({ ...limits }), rootNames: rootNames.slice(), mcpTools, mcpToolNames: mcpTools.map((t) => t.name) };
|
|
914
997
|
}
|
|
915
998
|
|
|
916
999
|
// ── A bare duplex as a peer ─────────────────────────────────────────────────────────────────────────────────────────
|
|
@@ -1196,13 +1279,14 @@ export async function on(ref, type, listener, { fields, onError } = {}) {
|
|
|
1196
1279
|
const { state, keys } = pathOf(ref, 'on');
|
|
1197
1280
|
if (typeof listener !== 'function') throw new TypeError('on needs a listener function: listener(data, { type, seq, dropped })');
|
|
1198
1281
|
const { session } = state;
|
|
1199
|
-
if (state.handle !== undefined) throw new TypeError('events are not offered through a handle: name the source by its path');
|
|
1200
1282
|
if (!session.features?.includes('events')) throw new ObjectsError(OBJECTS_ERROR.FAILED, 'this host does not support events (it did not say so)', { reason: 'unsupported' });
|
|
1283
|
+
// Through a handle: a host before 0.51.0 would not know the request, so it is not sent unless the host said it supports it.
|
|
1284
|
+
if (state.handle !== undefined && !session.features.includes('handle-events')) throw new ObjectsError(OBJECTS_ERROR.FAILED, 'this host does not support events through a handle (it did not say so): name the source by its path instead', { reason: 'unsupported' });
|
|
1201
1285
|
const id = session.nextSub++;
|
|
1202
1286
|
// Registered before the request: an event can follow the answer at once.
|
|
1203
|
-
session.subs.set(id, { listener, onError, type });
|
|
1287
|
+
session.subs.set(id, { listener, onError, type, handle: state.handle });
|
|
1204
1288
|
try {
|
|
1205
|
-
await session.peer.request('subscribe', { id,
|
|
1289
|
+
await session.peer.request('subscribe', { id, ...target(state), path: keys, type, ...(fields ? { fields } : {}) });
|
|
1206
1290
|
} catch (e) { session.subs.delete(id); throw asObjectsError(e, session); }
|
|
1207
1291
|
return async function off() {
|
|
1208
1292
|
if (!session.subs.delete(id)) return;
|
|
@@ -1216,6 +1300,18 @@ export async function off(unsubscribe) {
|
|
|
1216
1300
|
await unsubscribe();
|
|
1217
1301
|
}
|
|
1218
1302
|
|
|
1303
|
+
/**
|
|
1304
|
+
* What this key may do on a root, as data: `{ version, root, ops, allow, eventFields, types, handles }` (the host's allow-list entries for the root, narrowed by the key's
|
|
1305
|
+
* capabilities, and the host's type map for them). Give it to `describeRootTypes` from `@johnhenry/wsh/objects-types` for the text of a `.d.ts`; nothing is written or evaluated here.
|
|
1306
|
+
* Takes a root as `openObjects()` returns it (`page.window`), not a path or a handle.
|
|
1307
|
+
*/
|
|
1308
|
+
export async function rootDescription(ref, { signal } = {}) {
|
|
1309
|
+
const state = stateOf(ref);
|
|
1310
|
+
if (state.ops.length > 0 || state.handle !== undefined) throw new TypeError('rootDescription takes a root (page.window), not a path or a handle');
|
|
1311
|
+
if (!state.session.features?.includes('types')) throw new ObjectsError(OBJECTS_ERROR.FAILED, 'this host does not support types (it did not say so): it is older than 0.51.0', { reason: 'unsupported' });
|
|
1312
|
+
try { return await state.session.peer.request('types', { root: state.root }, { signal }); } catch (e) { throw asObjectsError(e, state.session); }
|
|
1313
|
+
}
|
|
1314
|
+
|
|
1219
1315
|
/** The shape of an object, for a REPL or completion: `{ type, keys: [{ key, type, own }] }`. Only names the allow-list could walk to are told. */
|
|
1220
1316
|
export async function describe(ref, { signal } = {}) {
|
|
1221
1317
|
const { state, keys } = pathOf(ref, 'describe');
|
|
@@ -1284,6 +1380,8 @@ export async function release(handle) {
|
|
|
1284
1380
|
if (!rec) throw new TypeError('release needs a handle, or a function that was passed as a callback');
|
|
1285
1381
|
if (rec.released) return;
|
|
1286
1382
|
rec.released = true;
|
|
1383
|
+
// The host ends the subscriptions made through the handle with it: forget them here too.
|
|
1384
|
+
for (const [id, sub] of [...rec.session.subs]) if (sub.handle === rec.id) rec.session.subs.delete(id);
|
|
1287
1385
|
try { await rec.session.peer.request('release', { handle: rec.id }); } catch (e) { throw asObjectsError(e, rec.session); }
|
|
1288
1386
|
}
|
|
1289
1387
|
|
|
@@ -0,0 +1,130 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* An MCP face for allow-listed object paths (#219): the host names, in `mcp: { tools: [...] }`, which paths of which roots become MCP tools; each gets a host-authored name,
|
|
3
|
+
* description and JSON Schema for its arguments. This module builds the tool definitions; `webmcpTools({ tools })` serves them on the `mcp` channel with the WebMCP bridge's own
|
|
4
|
+
* approval, bounds and untrusted label (so a tool that is not marked read-only asks the person at the page, exactly as a WebMCP tool does).
|
|
5
|
+
*
|
|
6
|
+
* What a tool is: a CALL of one named method (`call: 'window.app.cart.add'`), or a read-only GET of one named value (`get: 'window.document.title'`). Nothing is a tool by being
|
|
7
|
+
* allowed: a path is a tool only if it is written here, and only if the host's allow-list (the same one the objects client is held to) names it for that operation (checked when
|
|
8
|
+
* the host is created; and again on every call, because a call goes through the same checks as an objects call: the allow-list, the names that need listing, the key's
|
|
9
|
+
* `objects:ROOT:OP` capability and `authorize`). No handles, events or callbacks: an argument is plain data validated against the schema, a result is plain data or an error.
|
|
10
|
+
*/
|
|
11
|
+
|
|
12
|
+
import { compileSchema } from './objects-schema.mjs';
|
|
13
|
+
|
|
14
|
+
/** The key of the host-only part of a tool definition (see `INTERNAL_TOOL` in `webmcp.mjs`; the same registered symbol, so this file need not import it). */
|
|
15
|
+
const INTERNAL_TOOL = Symbol.for('wsh.webmcp.internal');
|
|
16
|
+
|
|
17
|
+
const TOOL_NAME_RE = /^[A-Za-z0-9_.-]{1,128}$/;
|
|
18
|
+
const TOOL_FIELDS = new Set(['name', 'title', 'description', 'call', 'get', 'inputSchema', 'args', 'readOnly']);
|
|
19
|
+
const NEVER = new Set(['__proto__', 'prototype', 'constructor', '__defineGetter__', '__defineSetter__', '__lookupGetter__', '__lookupSetter__', 'eval', 'Function', 'import', 'execScript']);
|
|
20
|
+
|
|
21
|
+
export const MCP_TOOL_LIMITS = Object.freeze({
|
|
22
|
+
/** Tools one host may name. */
|
|
23
|
+
maxTools: 64,
|
|
24
|
+
/** Characters of a description. */
|
|
25
|
+
maxDescriptionChars: 2000,
|
|
26
|
+
/** Arguments of a call tool (positional). */
|
|
27
|
+
maxArgs: 16,
|
|
28
|
+
});
|
|
29
|
+
|
|
30
|
+
const isObj = (v) => v !== null && typeof v === 'object' && !Array.isArray(v);
|
|
31
|
+
|
|
32
|
+
/**
|
|
33
|
+
* @param {object} options
|
|
34
|
+
* @param {unknown} options.mcp - the host's `mcp` option
|
|
35
|
+
* @param {string[]} options.rootNames
|
|
36
|
+
* @param {(kind: 'get' | 'call', root: string, segs: string[]) => void} options.allows - throws (an `ObjectsError`) unless the allow-list names the path for the operation
|
|
37
|
+
* @param {(request: { kind: 'get' | 'call', path: string[], args?: unknown[] }, ctx: object) => Promise<object>} options.invoke - one call through the server's checks
|
|
38
|
+
* @returns {object[]} tool definitions for `webmcpTools({ tools })`
|
|
39
|
+
*/
|
|
40
|
+
export function buildMcpTools({ mcp, rootNames, allows, invoke }) {
|
|
41
|
+
if (mcp === undefined) return [];
|
|
42
|
+
if (!isObj(mcp)) throw new TypeError('exposeObjects: mcp must be { tools: [...] }');
|
|
43
|
+
for (const k of Object.keys(mcp)) if (k !== 'tools') throw new TypeError(`exposeObjects: mcp.${k} is not an option (mcp is { tools: [...] }: name each path that becomes a tool; nothing is a tool by being allowed)`);
|
|
44
|
+
if (!Array.isArray(mcp.tools)) throw new TypeError('exposeObjects: mcp.tools must be an array of { name, description, call | get, inputSchema, ... }');
|
|
45
|
+
if (mcp.tools.length > MCP_TOOL_LIMITS.maxTools) throw new TypeError(`exposeObjects: mcp.tools lists at most ${MCP_TOOL_LIMITS.maxTools} tools`);
|
|
46
|
+
const seen = new Set();
|
|
47
|
+
return mcp.tools.map((spec, index) => {
|
|
48
|
+
const label = isObj(spec) && typeof spec.name === 'string' ? `mcp tool "${spec.name.slice(0, 60)}"` : `mcp.tools[${index}]`;
|
|
49
|
+
const fail = (message) => new TypeError(`exposeObjects: ${label}: ${message}`);
|
|
50
|
+
if (!isObj(spec)) throw fail('must be an object');
|
|
51
|
+
for (const k of Object.keys(spec)) if (!TOOL_FIELDS.has(k)) throw fail(`"${k}" is not a field of a tool (${[...TOOL_FIELDS].join(', ')}); events, handles and callbacks have no MCP tool`);
|
|
52
|
+
if (typeof spec.name !== 'string' || !TOOL_NAME_RE.test(spec.name)) throw fail('name must be 1 to 128 characters of letters, digits, "_", "-" and "."');
|
|
53
|
+
if (seen.has(spec.name)) throw fail('is listed twice');
|
|
54
|
+
seen.add(spec.name);
|
|
55
|
+
if (typeof spec.description !== 'string' || spec.description.trim() === '' || spec.description.length > MCP_TOOL_LIMITS.maxDescriptionChars) throw fail(`needs a description of 1 to ${MCP_TOOL_LIMITS.maxDescriptionChars} characters (the far side reads it to decide when to call the tool)`);
|
|
56
|
+
if (spec.title !== undefined && (typeof spec.title !== 'string' || spec.title.length > 200)) throw fail('title must be a string of at most 200 characters');
|
|
57
|
+
const named = [['call', spec.call], ['get', spec.get]].filter(([, v]) => v !== undefined);
|
|
58
|
+
if (named.length !== 1) throw fail('names exactly one of call, get: the path it runs (a path is a tool only if it is written here)');
|
|
59
|
+
const [kind, text] = named[0];
|
|
60
|
+
if (typeof text !== 'string') throw fail(`${kind} must be the path as text`);
|
|
61
|
+
const segs = text.split('.');
|
|
62
|
+
for (const s of segs) {
|
|
63
|
+
if (s === '') throw fail(`${kind} ${JSON.stringify(text.slice(0, 80))} has an empty segment`);
|
|
64
|
+
if (/\*/.test(s)) throw fail(`${kind} must be a literal path, with no wildcard (${JSON.stringify(text.slice(0, 80))})`);
|
|
65
|
+
if (s.includes('(') || s.includes(')')) throw fail(`${kind} must be a literal member path, not one through a call result (${JSON.stringify(text.slice(0, 80))})`);
|
|
66
|
+
if (NEVER.has(s)) throw fail(`${kind} names "${s}", which is never reachable`);
|
|
67
|
+
}
|
|
68
|
+
if (!rootNames.includes(segs[0])) throw fail(`${kind} ${JSON.stringify(text.slice(0, 80))} starts at ${JSON.stringify(segs[0].slice(0, 40))}, which is not a root of this host`);
|
|
69
|
+
if (segs.length < 2) throw fail(`${kind} must name a member of a root, not the root itself`);
|
|
70
|
+
try { allows(kind, segs[0], segs); } catch (e) { throw fail(`${String(e?.message ?? e)} (a tool never widens the allow-list: list the path there, then name it here)`); }
|
|
71
|
+
|
|
72
|
+
if (spec.readOnly !== undefined && typeof spec.readOnly !== 'boolean') throw fail('readOnly must be true or false');
|
|
73
|
+
// Read-only only when the host says so, for a get as for a call: a getter can have effects, and the mark skips the person's approval.
|
|
74
|
+
const readOnly = spec.readOnly === true;
|
|
75
|
+
const schema = spec.inputSchema ?? { type: 'object', properties: {}, additionalProperties: false };
|
|
76
|
+
if (!isObj(schema) || (schema.type !== undefined && schema.type !== 'object')) throw fail('inputSchema must describe an object');
|
|
77
|
+
let compiled;
|
|
78
|
+
try { compiled = compileSchema({ type: 'object', ...schema }, { what: `${label} inputSchema` }); } catch (e) { throw new TypeError(`exposeObjects: ${e.message}`); }
|
|
79
|
+
const properties = isObj(schema.properties) ? Object.keys(schema.properties) : [];
|
|
80
|
+
|
|
81
|
+
let mapping;
|
|
82
|
+
if (kind === 'get') {
|
|
83
|
+
if (spec.args !== undefined) throw fail('args is for a call: a get takes no arguments');
|
|
84
|
+
mapping = null;
|
|
85
|
+
} else if (spec.args === undefined) mapping = properties.length ? 'object' : [];
|
|
86
|
+
else if (spec.args === 'object') mapping = 'object';
|
|
87
|
+
else if (Array.isArray(spec.args) && spec.args.length <= MCP_TOOL_LIMITS.maxArgs && new Set(spec.args).size === spec.args.length && spec.args.every((a) => typeof a === 'string')) {
|
|
88
|
+
for (const a of spec.args) if (!properties.includes(a)) throw fail(`args names "${a.slice(0, 40)}", which is not a property of inputSchema`);
|
|
89
|
+
mapping = spec.args.slice();
|
|
90
|
+
} else throw fail(`args must be 'object' (the input is the one argument) or a list of up to ${MCP_TOOL_LIMITS.maxArgs} property names (the arguments, in order)`);
|
|
91
|
+
|
|
92
|
+
const root = segs[0];
|
|
93
|
+
const op = kind;
|
|
94
|
+
const argsOf = (input) => {
|
|
95
|
+
if (mapping === 'object') return [input];
|
|
96
|
+
const list = mapping.map((name) => (Object.hasOwn(input, name) ? input[name] : undefined));
|
|
97
|
+
while (list.length && list[list.length - 1] === undefined) list.pop();
|
|
98
|
+
return list.map((v) => (v === undefined ? null : v));
|
|
99
|
+
};
|
|
100
|
+
const definition = {
|
|
101
|
+
name: spec.name,
|
|
102
|
+
...(spec.title ? { title: spec.title } : {}),
|
|
103
|
+
description: spec.description,
|
|
104
|
+
inputSchema: JSON.parse(JSON.stringify({ type: 'object', ...schema })),
|
|
105
|
+
annotations: { readOnlyHint: readOnly },
|
|
106
|
+
[INTERNAL_TOOL]: {
|
|
107
|
+
caller: true,
|
|
108
|
+
// Before the person is asked and before the page runs anything.
|
|
109
|
+
validate: (input) => compiled.validate(input),
|
|
110
|
+
// Listed only to a key that may do this on this root: `mcp:TOOL` and `objects:ROOT:OP` are both needed.
|
|
111
|
+
available: ({ permits } = {}) => !permits || permits({ kind: 'objects', root, op }) === true,
|
|
112
|
+
},
|
|
113
|
+
async execute(input, { signal, who, permits } = {}) {
|
|
114
|
+
const problem = compiled.validate(input);
|
|
115
|
+
if (problem) throw new Error(`invalid arguments: ${problem}`);
|
|
116
|
+
const permit = permits ? (r, o) => permits({ kind: 'objects', root: r, op: o }) === true : undefined;
|
|
117
|
+
const out = await invoke({ kind, path: segs, args: kind === 'call' ? argsOf(input) : [] }, { who, permit, signal });
|
|
118
|
+
if (out && 'u' in out) {
|
|
119
|
+
if (out.u === 'undefined') return { content: [] };
|
|
120
|
+
throw new Error(`the ${kind} of ${text} returned something that is not plain data (${out.u}${out.type ? ` ${out.type}` : ''}): only plain values are carried`);
|
|
121
|
+
}
|
|
122
|
+
const value = out?.v;
|
|
123
|
+
const isPlainObject = value !== null && typeof value === 'object' && !Array.isArray(value) && !(value instanceof Uint8Array);
|
|
124
|
+
const rendered = typeof value === 'string' ? value : value instanceof Uint8Array ? `[${value.byteLength} bytes]` : JSON.stringify(value);
|
|
125
|
+
return { content: [{ type: 'text', text: rendered ?? '' }], ...(isPlainObject ? { structuredContent: value } : {}) };
|
|
126
|
+
},
|
|
127
|
+
};
|
|
128
|
+
return definition;
|
|
129
|
+
});
|
|
130
|
+
}
|
|
@@ -0,0 +1,143 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* A small, bounded subset of JSON Schema, for the arguments of an MCP tool made from an object path (#219). The host writes the schema; the far side's arguments are
|
|
3
|
+
* checked against it BEFORE anything runs (before the person at the page is asked, and before the page's function is called). The rule that keeps what is advertised
|
|
4
|
+
* equal to what is enforced: a schema that uses a keyword this validator does not enforce is refused when the host is configured (`compileSchema` throws), so a schema
|
|
5
|
+
* can never promise a check that is not made.
|
|
6
|
+
*
|
|
7
|
+
* Enforced: `type` (one name or a list), `enum`, `const`, `properties`, `required`, `additionalProperties` (a boolean or a schema), `items` (one schema), `minItems`,
|
|
8
|
+
* `maxItems`, `minLength`, `maxLength`, `minimum`, `maximum` and `anyOf`. Annotations that assert nothing are accepted and ignored: `description`, `title`, `default`,
|
|
9
|
+
* `examples`, `format`, `$comment`, `$schema`. Everything else (`$ref`, `pattern`, `oneOf`, `allOf`, `not`, `patternProperties`, `if`, ...) is refused: a regular
|
|
10
|
+
* expression of the host's would run against the far side's text, and a reference needs a resolver.
|
|
11
|
+
*
|
|
12
|
+
* What it checks of a VALUE, whatever the schema says: it is plain data (a JSON-shaped value: no function, no class instance), it nests no deeper than `maxDepth` and has
|
|
13
|
+
* no more than `maxNodes` nodes, and no object has a key that climbs to a prototype (`__proto__`, `constructor`, `prototype`, ...).
|
|
14
|
+
*/
|
|
15
|
+
|
|
16
|
+
export const SCHEMA_LIMITS = Object.freeze({
|
|
17
|
+
/** Nesting of a schema, and of a value checked against one. */
|
|
18
|
+
maxDepth: 8,
|
|
19
|
+
/** Nodes of a schema, and nodes visited when a value is checked. */
|
|
20
|
+
maxNodes: 2000,
|
|
21
|
+
/** Properties one object schema lists. */
|
|
22
|
+
maxProperties: 64,
|
|
23
|
+
/** Members of an `enum`, entries of `required` and of `anyOf`. */
|
|
24
|
+
maxList: 64,
|
|
25
|
+
});
|
|
26
|
+
|
|
27
|
+
const TYPES = new Set(['string', 'number', 'integer', 'boolean', 'null', 'object', 'array']);
|
|
28
|
+
const ANNOTATIONS = new Set(['description', 'title', 'default', 'examples', 'format', '$comment', '$schema']);
|
|
29
|
+
const ENFORCED = new Set(['type', 'enum', 'const', 'properties', 'required', 'additionalProperties', 'items', 'minItems', 'maxItems', 'minLength', 'maxLength', 'minimum', 'maximum', 'anyOf']);
|
|
30
|
+
const NEVER_KEYS = new Set(['__proto__', 'prototype', 'constructor', '__defineGetter__', '__defineSetter__', '__lookupGetter__', '__lookupSetter__']);
|
|
31
|
+
|
|
32
|
+
const isObj = (v) => v !== null && typeof v === 'object' && !Array.isArray(v);
|
|
33
|
+
const bad = (what, message) => new TypeError(`${what}: ${message}`);
|
|
34
|
+
|
|
35
|
+
const same = (a, b) => {
|
|
36
|
+
if (a === b) return true;
|
|
37
|
+
if (typeof a !== 'object' || typeof b !== 'object' || a === null || b === null) return false;
|
|
38
|
+
try { return JSON.stringify(a) === JSON.stringify(b); } catch { return false; }
|
|
39
|
+
};
|
|
40
|
+
|
|
41
|
+
/**
|
|
42
|
+
* Check a schema and return `{ validate(value) }`, which returns `null` when the value fits and a sentence when it does not (the first problem).
|
|
43
|
+
* @param {object} schema
|
|
44
|
+
* @param {{ what?: string }} [options] - what the schema is for, for the messages
|
|
45
|
+
*/
|
|
46
|
+
export function compileSchema(schema, { what = 'inputSchema' } = {}) {
|
|
47
|
+
let nodes = 0;
|
|
48
|
+
const check = (s, depth, at) => {
|
|
49
|
+
if (!isObj(s)) throw bad(what, `${at} must be a schema object`);
|
|
50
|
+
if (depth > SCHEMA_LIMITS.maxDepth) throw bad(what, `${at} nests deeper than ${SCHEMA_LIMITS.maxDepth}`);
|
|
51
|
+
if (++nodes > SCHEMA_LIMITS.maxNodes) throw bad(what, `has more than ${SCHEMA_LIMITS.maxNodes} nodes`);
|
|
52
|
+
for (const k of Object.keys(s)) {
|
|
53
|
+
if (ENFORCED.has(k) || ANNOTATIONS.has(k)) continue;
|
|
54
|
+
throw bad(what, `${at}: the keyword "${k}" is not supported (it could not be enforced, so it would promise a check that is not made)`);
|
|
55
|
+
}
|
|
56
|
+
if (s.type !== undefined) {
|
|
57
|
+
const list = Array.isArray(s.type) ? s.type : [s.type];
|
|
58
|
+
if (list.length === 0 || list.length > TYPES.size || !list.every((t) => TYPES.has(t))) throw bad(what, `${at}.type must be one of ${[...TYPES].join(', ')} (or a list of them)`);
|
|
59
|
+
}
|
|
60
|
+
if (s.enum !== undefined && (!Array.isArray(s.enum) || s.enum.length === 0 || s.enum.length > SCHEMA_LIMITS.maxList)) throw bad(what, `${at}.enum must be a list of 1 to ${SCHEMA_LIMITS.maxList} values`);
|
|
61
|
+
if (s.required !== undefined && (!Array.isArray(s.required) || s.required.length > SCHEMA_LIMITS.maxList || !s.required.every((r) => typeof r === 'string' && !NEVER_KEYS.has(r)))) throw bad(what, `${at}.required must be a list of at most ${SCHEMA_LIMITS.maxList} property names`);
|
|
62
|
+
for (const k of ['minItems', 'maxItems', 'minLength', 'maxLength']) if (s[k] !== undefined && (!Number.isSafeInteger(s[k]) || s[k] < 0)) throw bad(what, `${at}.${k} must be a whole number of at least 0`);
|
|
63
|
+
for (const k of ['minimum', 'maximum']) if (s[k] !== undefined && (typeof s[k] !== 'number' || !Number.isFinite(s[k]))) throw bad(what, `${at}.${k} must be a number`);
|
|
64
|
+
if (s.properties !== undefined) {
|
|
65
|
+
if (!isObj(s.properties)) throw bad(what, `${at}.properties must be an object of schemas`);
|
|
66
|
+
const keys = Object.keys(s.properties);
|
|
67
|
+
if (keys.length > SCHEMA_LIMITS.maxProperties) throw bad(what, `${at}.properties lists more than ${SCHEMA_LIMITS.maxProperties} properties`);
|
|
68
|
+
for (const k of keys) {
|
|
69
|
+
if (NEVER_KEYS.has(k)) throw bad(what, `${at}.properties names "${k}", which is never accepted`);
|
|
70
|
+
check(s.properties[k], depth + 1, `${at}.properties.${k}`);
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
if (s.additionalProperties !== undefined && typeof s.additionalProperties !== 'boolean') check(s.additionalProperties, depth + 1, `${at}.additionalProperties`);
|
|
74
|
+
if (s.items !== undefined) check(s.items, depth + 1, `${at}.items`);
|
|
75
|
+
if (s.anyOf !== undefined) {
|
|
76
|
+
if (!Array.isArray(s.anyOf) || s.anyOf.length === 0 || s.anyOf.length > SCHEMA_LIMITS.maxList) throw bad(what, `${at}.anyOf must be a list of 1 to ${SCHEMA_LIMITS.maxList} schemas`);
|
|
77
|
+
s.anyOf.forEach((sub, i) => check(sub, depth + 1, `${at}.anyOf[${i}]`));
|
|
78
|
+
}
|
|
79
|
+
};
|
|
80
|
+
check(schema, 0, '');
|
|
81
|
+
|
|
82
|
+
const typeOk = (t, v) => {
|
|
83
|
+
switch (t) {
|
|
84
|
+
case 'string': return typeof v === 'string';
|
|
85
|
+
case 'number': return typeof v === 'number' && Number.isFinite(v);
|
|
86
|
+
case 'integer': return typeof v === 'number' && Number.isInteger(v);
|
|
87
|
+
case 'boolean': return typeof v === 'boolean';
|
|
88
|
+
case 'null': return v === null;
|
|
89
|
+
case 'object': return isObj(v);
|
|
90
|
+
case 'array': return Array.isArray(v);
|
|
91
|
+
default: return false;
|
|
92
|
+
}
|
|
93
|
+
};
|
|
94
|
+
const label = (at) => (at === '' ? 'the arguments' : `"${at}"`);
|
|
95
|
+
|
|
96
|
+
/** The first problem of `value` against `s`, or null. `budget.nodes` counts what is visited. */
|
|
97
|
+
const walk = (s, value, depth, at, budget) => {
|
|
98
|
+
if (++budget.nodes > SCHEMA_LIMITS.maxNodes) return `${label(at)}: the arguments are too large to check (more than ${SCHEMA_LIMITS.maxNodes} values)`;
|
|
99
|
+
if (depth > SCHEMA_LIMITS.maxDepth) return `${label(at)}: nested deeper than ${SCHEMA_LIMITS.maxDepth}`;
|
|
100
|
+
if (value === undefined || typeof value === 'function' || typeof value === 'symbol' || typeof value === 'bigint') return `${label(at)} is not plain data`;
|
|
101
|
+
if (s.type !== undefined) {
|
|
102
|
+
const list = Array.isArray(s.type) ? s.type : [s.type];
|
|
103
|
+
if (!list.some((t) => typeOk(t, value))) return `${label(at)} must be ${list.join(' or ')}`;
|
|
104
|
+
}
|
|
105
|
+
if (s.enum !== undefined && !s.enum.some((e) => same(e, value))) return `${label(at)} must be one of ${JSON.stringify(s.enum).slice(0, 120)}`;
|
|
106
|
+
if (s.const !== undefined && !same(s.const, value)) return `${label(at)} must be ${JSON.stringify(s.const).slice(0, 80)}`;
|
|
107
|
+
if (typeof value === 'string') {
|
|
108
|
+
if (s.minLength !== undefined && [...value].length < s.minLength) return `${label(at)} must be at least ${s.minLength} characters`;
|
|
109
|
+
if (s.maxLength !== undefined && [...value].length > s.maxLength) return `${label(at)} must be at most ${s.maxLength} characters`;
|
|
110
|
+
}
|
|
111
|
+
if (typeof value === 'number') {
|
|
112
|
+
if (s.minimum !== undefined && value < s.minimum) return `${label(at)} must be at least ${s.minimum}`;
|
|
113
|
+
if (s.maximum !== undefined && value > s.maximum) return `${label(at)} must be at most ${s.maximum}`;
|
|
114
|
+
}
|
|
115
|
+
if (Array.isArray(value)) {
|
|
116
|
+
if (s.minItems !== undefined && value.length < s.minItems) return `${label(at)} must have at least ${s.minItems} items`;
|
|
117
|
+
if (s.maxItems !== undefined && value.length > s.maxItems) return `${label(at)} must have at most ${s.maxItems} items`;
|
|
118
|
+
for (let i = 0; i < value.length; i++) {
|
|
119
|
+
const p = s.items === undefined ? (value[i] !== null && typeof value[i] === 'object' ? walk({}, value[i], depth + 1, `${at}[${i}]`, budget) : null) : walk(s.items, value[i], depth + 1, `${at}[${i}]`, budget);
|
|
120
|
+
if (p) return p;
|
|
121
|
+
}
|
|
122
|
+
} else if (isObj(value)) {
|
|
123
|
+
const keys = Object.keys(value);
|
|
124
|
+
for (const k of keys) if (NEVER_KEYS.has(k)) return `${label(at)} has the key "${k}", which is never accepted`;
|
|
125
|
+
for (const r of s.required ?? []) if (!Object.hasOwn(value, r)) return `missing required argument "${at === '' ? r : `${at}.${r}`}"`;
|
|
126
|
+
for (const k of keys) {
|
|
127
|
+
const child = at === '' ? k : `${at}.${k}`;
|
|
128
|
+
const known = s.properties !== undefined && Object.hasOwn(s.properties, k);
|
|
129
|
+
if (known) { const p = walk(s.properties[k], value[k], depth + 1, child, budget); if (p) return p; continue; }
|
|
130
|
+
if (s.additionalProperties === false) return `${label(at)} has an argument that is not allowed: "${k}"`;
|
|
131
|
+
const p = walk(isObj(s.additionalProperties) ? s.additionalProperties : {}, value[k], depth + 1, child, budget);
|
|
132
|
+
if (p) return p;
|
|
133
|
+
}
|
|
134
|
+
}
|
|
135
|
+
if (s.anyOf !== undefined) {
|
|
136
|
+
// Every branch sees the same budget, so a hostile value cannot be walked once per branch past the bound.
|
|
137
|
+
if (!s.anyOf.some((sub) => walk(sub, value, depth, at, budget) === null)) return `${label(at)} matches none of the allowed forms`;
|
|
138
|
+
}
|
|
139
|
+
return null;
|
|
140
|
+
};
|
|
141
|
+
|
|
142
|
+
return { schema, validate: (value) => walk(schema, value, 0, '', { nodes: 0 }) };
|
|
143
|
+
}
|
|
@@ -0,0 +1,95 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The text of a TypeScript type that a host supplies for a path (`exposeObjects({ types })`) and a client writes into a `.d.ts` file. It is HOST-AUTHORED text
|
|
3
|
+
* that travels to the far side, so the far side treats it as untrusted: it is never evaluated, only checked here and, if it passes, written out by an explicit
|
|
4
|
+
* call. The check is a small tokenizer, not a parser: it accepts a conservative subset of type syntax (identifiers, string and number literals, and the
|
|
5
|
+
* punctuation of object, tuple, function, union, intersection, generic, conditional and indexed types) and refuses everything that could change what the
|
|
6
|
+
* surrounding declaration means or reach outside it.
|
|
7
|
+
*
|
|
8
|
+
* What it refuses, and why:
|
|
9
|
+
* - any character outside printable ASCII on one line (no newline, so nothing can start a new declaration or a `///` directive);
|
|
10
|
+
* - `/`, `\`, a backtick, `@`, `#`, `%`, `^`, `~`, `!` and `*`: no comment, no escape sequence, no template literal, no decorator;
|
|
11
|
+
* - the words `import`, `export`, `require`, `declare`, `module`, `namespace`, `global`, `typeof`, `class`, `function`, `enum`, `interface`, `eval`: nothing
|
|
12
|
+
* that reads a file, a value or the global scope by name, or declares anything;
|
|
13
|
+
* - unbalanced or mismatched brackets, a `;` outside braces and a `,` outside any bracket: a text cannot close the declaration it sits in or add a member to it;
|
|
14
|
+
* - a text, a string literal, a nesting depth or a total that is over its bound.
|
|
15
|
+
*
|
|
16
|
+
* It does not make the text TRUE: a host can name a type that is wrong, and a type that is too wide or too narrow is a tooling problem, not a hole (a type
|
|
17
|
+
* is erased before anything runs). It makes the text safe to write into a declaration file.
|
|
18
|
+
*/
|
|
19
|
+
|
|
20
|
+
export const TYPE_TEXT_LIMITS = Object.freeze({
|
|
21
|
+
/** Characters of one type text. */
|
|
22
|
+
maxTextChars: 1024,
|
|
23
|
+
/** Characters of one string literal inside a type text. */
|
|
24
|
+
maxStringChars: 200,
|
|
25
|
+
/** Nesting of brackets in one type text. */
|
|
26
|
+
maxNesting: 16,
|
|
27
|
+
/** Entries of a type map. */
|
|
28
|
+
maxEntries: 256,
|
|
29
|
+
/** Characters of all the type texts of one root together. */
|
|
30
|
+
maxTotalChars: 32 * 1024,
|
|
31
|
+
});
|
|
32
|
+
|
|
33
|
+
const FORBIDDEN_WORDS = new Set(['import', 'export', 'require', 'declare', 'module', 'namespace', 'global', 'typeof', 'class', 'function', 'enum', 'interface', 'eval']);
|
|
34
|
+
const PUNCTUATION = new Set(['{', '}', '[', ']', '(', ')', '<', '>', '|', '&', ':', ';', ',', '?', '=', '.', '-', '+']);
|
|
35
|
+
const OPEN = { '{': '}', '[': ']', '(': ')', '<': '>' };
|
|
36
|
+
const CLOSE = new Set(Object.values(OPEN));
|
|
37
|
+
|
|
38
|
+
/**
|
|
39
|
+
* Check one type text; returns it unchanged, or throws a `TypeError` that names the rule.
|
|
40
|
+
* @param {unknown} text
|
|
41
|
+
* @param {string} [what] - what the text is for, for the message
|
|
42
|
+
* @returns {string}
|
|
43
|
+
*/
|
|
44
|
+
export function checkTypeText(text, what = 'a type text') {
|
|
45
|
+
const fail = (why) => new TypeError(`${what}: ${why}`);
|
|
46
|
+
if (typeof text !== 'string' || text.trim() === '') throw fail('must be a non-empty string');
|
|
47
|
+
if (text.length > TYPE_TEXT_LIMITS.maxTextChars) throw fail(`is over ${TYPE_TEXT_LIMITS.maxTextChars} characters`);
|
|
48
|
+
const stack = [];
|
|
49
|
+
let i = 0;
|
|
50
|
+
while (i < text.length) {
|
|
51
|
+
const c = text[i];
|
|
52
|
+
const code = text.charCodeAt(i);
|
|
53
|
+
if (code < 0x20 || code > 0x7e) throw fail('may hold printable ASCII on one line only');
|
|
54
|
+
if (c === ' ') { i++; continue; }
|
|
55
|
+
if (c === '"' || c === "'") {
|
|
56
|
+
const end = text.indexOf(c, i + 1);
|
|
57
|
+
if (end < 0) throw fail('has a string literal that does not end');
|
|
58
|
+
const body = text.slice(i + 1, end);
|
|
59
|
+
if (body.includes('\\')) throw fail('has a string literal with an escape sequence');
|
|
60
|
+
if (body.length > TYPE_TEXT_LIMITS.maxStringChars) throw fail(`has a string literal over ${TYPE_TEXT_LIMITS.maxStringChars} characters`);
|
|
61
|
+
i = end + 1;
|
|
62
|
+
continue;
|
|
63
|
+
}
|
|
64
|
+
if (/[A-Za-z_$]/.test(c)) {
|
|
65
|
+
let j = i + 1;
|
|
66
|
+
while (j < text.length && /[A-Za-z0-9_$]/.test(text[j])) j++;
|
|
67
|
+
const word = text.slice(i, j);
|
|
68
|
+
if (FORBIDDEN_WORDS.has(word)) throw fail(`may not use the word "${word}"`);
|
|
69
|
+
i = j;
|
|
70
|
+
continue;
|
|
71
|
+
}
|
|
72
|
+
if (/[0-9]/.test(c)) {
|
|
73
|
+
let j = i + 1;
|
|
74
|
+
while (j < text.length && /[0-9._]/.test(text[j])) j++;
|
|
75
|
+
i = j;
|
|
76
|
+
continue;
|
|
77
|
+
}
|
|
78
|
+
if (!PUNCTUATION.has(c)) throw fail(`may not contain "${c}"`);
|
|
79
|
+
// `=>` is an arrow, not a closing angle bracket.
|
|
80
|
+
if (c === '=' && text[i + 1] === '>') { i += 2; continue; }
|
|
81
|
+
if (c in OPEN) {
|
|
82
|
+
stack.push(OPEN[c]);
|
|
83
|
+
if (stack.length > TYPE_TEXT_LIMITS.maxNesting) throw fail(`nests deeper than ${TYPE_TEXT_LIMITS.maxNesting}`);
|
|
84
|
+
} else if (CLOSE.has(c)) {
|
|
85
|
+
if (stack.pop() !== c) throw fail(`has a "${c}" that closes nothing`);
|
|
86
|
+
} else if (c === ';') {
|
|
87
|
+
if (stack[stack.length - 1] !== '}') throw fail('has a ";" outside braces');
|
|
88
|
+
} else if (c === ',') {
|
|
89
|
+
if (stack.length === 0) throw fail('has a "," outside any bracket');
|
|
90
|
+
}
|
|
91
|
+
i++;
|
|
92
|
+
}
|
|
93
|
+
if (stack.length) throw fail('has a bracket that is not closed');
|
|
94
|
+
return text;
|
|
95
|
+
}
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
/** The operations of `wsh-objects` a key may hold on a root. */
|
|
2
|
+
export type ObjectsOp = 'get' | 'call' | 'set' | 'on';
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* What a host says one key may do on one root: its `types` answer (`rootDescription(page.window)` fetches it), or the allow-lists a host holds (paths qualified with the
|
|
6
|
+
* root, as in `allow`). `ops` is what the key's capabilities grant on this root (default: all four).
|
|
7
|
+
*/
|
|
8
|
+
export interface RootDescription {
|
|
9
|
+
root: string;
|
|
10
|
+
ops?: ObjectsOp[];
|
|
11
|
+
allow: { get?: string[]; call?: string[]; set?: string[]; on?: string[] };
|
|
12
|
+
/** Extra event fields a subscriber may ask for, by event type (`'*'`: any type). */
|
|
13
|
+
eventFields?: Record<string, string[]>;
|
|
14
|
+
/**
|
|
15
|
+
* Host-authored TypeScript type texts, by literal path (`'window.app.cart.add'`; an event as `'window.app.bus@ready'`): `value` (the awaited value of a get),
|
|
16
|
+
* `args` (a tuple type) and `result` (the awaited value) of a call, `data` (what a listener receives) of an event. Checked by `checkTypeText`, bounded, and only
|
|
17
|
+
* for a path an entry allows. Untrusted text: copied into the file, never evaluated.
|
|
18
|
+
*/
|
|
19
|
+
types?: Record<string, { value?: string; args?: string; result?: string; data?: string }>;
|
|
20
|
+
version?: number;
|
|
21
|
+
handles?: boolean;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
/**
|
|
25
|
+
* The text of a `.d.ts` file for one root: only what the key may do, values `unknown` unless the host supplied a type, calls `(...args: unknown[]) => PromiseLike<unknown>`,
|
|
26
|
+
* wildcards untyped, events as typed `on` overloads. Pure: reads nothing, writes nothing, evaluates nothing; throws a `TypeError` on a description or type text it does not accept.
|
|
27
|
+
* @param options.name - the exported type's name (default: the root's name, capitalised, plus `Remote`: `WindowRemote`)
|
|
28
|
+
*/
|
|
29
|
+
export function describeRootTypes(description: RootDescription, options?: { name?: string }): string;
|
|
30
|
+
|
|
31
|
+
/** Check the text of one type: returns it, or throws a `TypeError` naming the rule. A conservative subset of type syntax; see the README. */
|
|
32
|
+
export function checkTypeText(text: unknown, what?: string): string;
|
|
33
|
+
|
|
34
|
+
export const TYPE_TEXT_LIMITS: Readonly<{ maxTextChars: number; maxStringChars: number; maxNesting: number; maxEntries: number; maxTotalChars: number }>;
|
|
35
|
+
export const OBJECTS_TYPES_LIMITS: Readonly<{ maxEntries: number; maxEntryChars: number; maxNodes: number; maxEvents: number }>;
|
|
36
|
+
|
|
37
|
+
/** The part of a host's type map that a key holding `ops` may be told. */
|
|
38
|
+
export function narrowTypes(options: { root: string; ops: ObjectsOp[]; allow: RootDescription['allow']; types?: RootDescription['types'] }): NonNullable<RootDescription['types']>;
|