@tik-choco/mistlib-mcp 0.0.0-stage → 0.1.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/LICENSE +373 -0
- package/README.md +128 -2
- package/dist/index.d.ts +3 -0
- package/dist/index.js +3 -0
- package/dist/mcp/index.d.ts +3 -0
- package/dist/mcp/index.js +1 -0
- package/dist/mcp/schema.d.ts +6 -0
- package/dist/mcp/schema.js +29 -0
- package/dist/mcp/server.d.ts +100 -0
- package/dist/mcp/server.js +303 -0
- package/dist/provider/identity.d.ts +4 -0
- package/dist/provider/identity.js +57 -0
- package/dist/provider/index.d.ts +4 -0
- package/dist/provider/index.js +3 -0
- package/dist/provider/mistseed.d.ts +16 -0
- package/dist/provider/mistseed.js +91 -0
- package/dist/provider/protocol.d.ts +49 -0
- package/dist/provider/protocol.js +139 -0
- package/dist/provider/provider.d.ts +3 -0
- package/dist/provider/provider.js +430 -0
- package/dist/provider/shared-node.d.ts +23 -0
- package/dist/provider/shared-node.js +78 -0
- package/dist/provider/types.d.ts +31 -0
- package/dist/provider/types.js +1 -0
- package/dist/wire/credentials.d.ts +47 -0
- package/dist/wire/credentials.js +79 -0
- package/dist/wire/encoding.d.ts +7 -0
- package/dist/wire/encoding.js +23 -0
- package/dist/wire/errors.d.ts +27 -0
- package/dist/wire/errors.js +19 -0
- package/dist/wire/framing.d.ts +40 -0
- package/dist/wire/framing.js +166 -0
- package/dist/wire/index.d.ts +8 -0
- package/dist/wire/index.js +8 -0
- package/dist/wire/json.d.ts +13 -0
- package/dist/wire/json.js +73 -0
- package/dist/wire/messages.d.ts +68 -0
- package/dist/wire/messages.js +89 -0
- package/dist/wire/names.d.ts +4 -0
- package/dist/wire/names.js +14 -0
- package/dist/wire/noise-session.d.ts +135 -0
- package/dist/wire/noise-session.js +432 -0
- package/noise-wasm/README.md +59 -0
- package/noise-wasm/pkg/noise_wasm.d.ts +101 -0
- package/noise-wasm/pkg/noise_wasm.js +699 -0
- package/noise-wasm/pkg/noise_wasm_bg.wasm +0 -0
- package/noise-wasm/pkg/noise_wasm_bg.wasm.d.ts +30 -0
- package/package.json +70 -4
- package/spec/provider-runtime-v1.md +100 -0
- package/spec/secure-channel-v1.md +213 -0
- package/spec/wire-v1.md +355 -0
- package/vectors/wire-v1.json +117 -0
|
@@ -0,0 +1,430 @@
|
|
|
1
|
+
import { McpServer, prepareTool } from "../mcp/server.js";
|
|
2
|
+
import { randomId, base64url, unbase64url, exactKeys, isToken } from "../wire/encoding.js";
|
|
3
|
+
import { isObject, canonicalJson, canonicalBytes, parseJson } from "../wire/json.js";
|
|
4
|
+
import { isNamespace } from "../wire/names.js";
|
|
5
|
+
import { isOrigin, isProviderTicket } from "../wire/credentials.js";
|
|
6
|
+
import { MCP_VERSION, MAX_TOOLS, encodeWire } from "../wire/messages.js";
|
|
7
|
+
import { splitFrames, FrameReassembler } from "../wire/framing.js";
|
|
8
|
+
import { pairInitiator, reconnectInitiator, bindSession, generateStaticKeypair, normalizePairingCode, ed25519PublicKeyFromDidKey } from "../wire/noise-session.js";
|
|
9
|
+
import { createOriginSigner } from "./identity.js";
|
|
10
|
+
import { Inbox, pairingRoom, isPermanentRoom, sha256, PAIRING_KEY, SESSION_TIMEOUT, PAIR_TIMEOUT, LIVENESS_TIMEOUT, validateTicket, sealControl, openControl, check, abortable, delay } from "./protocol.js";
|
|
11
|
+
const localListeners = new Set();
|
|
12
|
+
const broadcastChange = () => { for (const listener of [...localListeners])
|
|
13
|
+
listener(); };
|
|
14
|
+
const key32 = (value) => {
|
|
15
|
+
try {
|
|
16
|
+
return typeof value === "string" && unbase64url(value).length === 32;
|
|
17
|
+
}
|
|
18
|
+
catch {
|
|
19
|
+
return false;
|
|
20
|
+
}
|
|
21
|
+
};
|
|
22
|
+
function readPairing(raw) {
|
|
23
|
+
const p = parseJson(new TextEncoder().encode(raw));
|
|
24
|
+
if (!isObject(p) || !exactKeys(p, ["v", "gatewayDid", "remoteStatic", "localPrivate", "localPublic", "instance", "room", "ticket"]) ||
|
|
25
|
+
p.v !== 1 || !ed25519PublicKeyFromDidKey(p.gatewayDid) || !key32(p.remoteStatic) || !key32(p.localPrivate) || !key32(p.localPublic) ||
|
|
26
|
+
!isToken(p.instance) || !isPermanentRoom(p.room) || !isProviderTicket(p.ticket))
|
|
27
|
+
throw new Error("Invalid saved pairing");
|
|
28
|
+
return p;
|
|
29
|
+
}
|
|
30
|
+
function localStatic(p) { return { privateKey: unbase64url(p.localPrivate), publicKey: unbase64url(p.localPublic) }; }
|
|
31
|
+
function childController(parent) {
|
|
32
|
+
const controller = new AbortController();
|
|
33
|
+
const abort = () => controller.abort();
|
|
34
|
+
if (parent.aborted)
|
|
35
|
+
abort();
|
|
36
|
+
else
|
|
37
|
+
parent.addEventListener("abort", abort, { once: true });
|
|
38
|
+
return { controller, detach: () => parent.removeEventListener("abort", abort) };
|
|
39
|
+
}
|
|
40
|
+
const helloCompatible = (h) => h.mcpVersions.includes(MCP_VERSION);
|
|
41
|
+
class Runtime {
|
|
42
|
+
options;
|
|
43
|
+
origin;
|
|
44
|
+
storage;
|
|
45
|
+
tools = new Map();
|
|
46
|
+
statusListeners = new Set();
|
|
47
|
+
currentStatus = { state: "unpaired" };
|
|
48
|
+
raw;
|
|
49
|
+
runController;
|
|
50
|
+
run = Promise.resolve();
|
|
51
|
+
pairController;
|
|
52
|
+
pairing;
|
|
53
|
+
signerPromise;
|
|
54
|
+
server;
|
|
55
|
+
guardHandler;
|
|
56
|
+
disposed = false;
|
|
57
|
+
constructor(options) {
|
|
58
|
+
this.options = options;
|
|
59
|
+
if (!isNamespace(options.namespace) || typeof options.title !== "string" || !options.title.trim() || options.title.length > 256 ||
|
|
60
|
+
!options.transport.selfNodeId)
|
|
61
|
+
throw new TypeError("Invalid provider options");
|
|
62
|
+
const origin = globalThis.location?.origin;
|
|
63
|
+
if (!isOrigin(origin))
|
|
64
|
+
throw new TypeError("An HTTP(S) origin is required");
|
|
65
|
+
this.origin = origin;
|
|
66
|
+
this.storage = options.storage ?? globalThis.localStorage;
|
|
67
|
+
localListeners.add(this.refresh);
|
|
68
|
+
globalThis.addEventListener?.("storage", this.storageChanged);
|
|
69
|
+
this.refresh();
|
|
70
|
+
}
|
|
71
|
+
get status() { return { ...this.currentStatus }; }
|
|
72
|
+
onStatus(cb) {
|
|
73
|
+
this.statusListeners.add(cb);
|
|
74
|
+
return () => { this.statusListeners.delete(cb); };
|
|
75
|
+
}
|
|
76
|
+
update(state, fingerprint) {
|
|
77
|
+
if (this.disposed || (this.currentStatus.state === state && this.currentStatus.fingerprint === fingerprint))
|
|
78
|
+
return;
|
|
79
|
+
this.currentStatus = { state, ...(fingerprint === undefined ? {} : { fingerprint }) };
|
|
80
|
+
for (const cb of [...this.statusListeners]) {
|
|
81
|
+
try {
|
|
82
|
+
cb(this.status);
|
|
83
|
+
}
|
|
84
|
+
catch { /* observer isolation */ }
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
getSigner() {
|
|
88
|
+
if (this.options.signer)
|
|
89
|
+
return Promise.resolve(this.options.signer);
|
|
90
|
+
return this.signerPromise ??= createOriginSigner().catch(error => { this.signerPromise = undefined; throw error; });
|
|
91
|
+
}
|
|
92
|
+
storageChanged = (event) => { if (event.key === PAIRING_KEY || event.key === null)
|
|
93
|
+
this.refresh(); };
|
|
94
|
+
refresh = () => {
|
|
95
|
+
if (this.disposed)
|
|
96
|
+
return;
|
|
97
|
+
let raw;
|
|
98
|
+
try {
|
|
99
|
+
raw = this.storage.getItem(PAIRING_KEY);
|
|
100
|
+
}
|
|
101
|
+
catch {
|
|
102
|
+
this.runController?.abort();
|
|
103
|
+
this.raw = undefined;
|
|
104
|
+
this.update("error");
|
|
105
|
+
return;
|
|
106
|
+
}
|
|
107
|
+
if (raw === this.raw)
|
|
108
|
+
return;
|
|
109
|
+
this.raw = raw;
|
|
110
|
+
this.runController?.abort();
|
|
111
|
+
if (raw === null) {
|
|
112
|
+
this.update("unpaired");
|
|
113
|
+
return;
|
|
114
|
+
}
|
|
115
|
+
let record;
|
|
116
|
+
try {
|
|
117
|
+
record = readPairing(raw);
|
|
118
|
+
}
|
|
119
|
+
catch {
|
|
120
|
+
this.update("error");
|
|
121
|
+
return;
|
|
122
|
+
}
|
|
123
|
+
const controller = this.runController = new AbortController();
|
|
124
|
+
this.update("connecting");
|
|
125
|
+
this.run = this.run.catch(() => { }).then(async () => {
|
|
126
|
+
if (controller.signal.aborted)
|
|
127
|
+
return;
|
|
128
|
+
const fingerprint = await sha256(ed25519PublicKeyFromDidKey(record.gatewayDid));
|
|
129
|
+
check(controller.signal);
|
|
130
|
+
this.update("connecting", fingerprint);
|
|
131
|
+
await this.lock(`mist-mcp:v1:${this.origin}:${this.options.namespace}`, controller.signal, () => this.lead(record, fingerprint, controller.signal));
|
|
132
|
+
}).catch(() => { if (!controller.signal.aborted)
|
|
133
|
+
this.update("error"); });
|
|
134
|
+
};
|
|
135
|
+
async lock(name, signal, fn) {
|
|
136
|
+
const locks = globalThis.navigator?.locks;
|
|
137
|
+
if (!locks) {
|
|
138
|
+
check(signal);
|
|
139
|
+
await fn();
|
|
140
|
+
return;
|
|
141
|
+
}
|
|
142
|
+
await locks.request(name, { mode: "exclusive", signal }, async () => { check(signal); await fn(); });
|
|
143
|
+
}
|
|
144
|
+
registerTool(name, definition, handler) {
|
|
145
|
+
if (this.disposed || this.tools.has(name) || this.tools.size >= MAX_TOOLS)
|
|
146
|
+
throw new TypeError("Invalid or duplicate tool");
|
|
147
|
+
const prepared = prepareTool(name, definition, handler);
|
|
148
|
+
const tool = { definition: prepared.definition, handler };
|
|
149
|
+
if (this.server)
|
|
150
|
+
tool.remove = this.server.registerTool(name, tool.definition, this.guardHandler(handler));
|
|
151
|
+
this.tools.set(name, tool);
|
|
152
|
+
return () => {
|
|
153
|
+
if (this.tools.get(name) !== tool)
|
|
154
|
+
return;
|
|
155
|
+
this.tools.delete(name);
|
|
156
|
+
tool.remove?.();
|
|
157
|
+
};
|
|
158
|
+
}
|
|
159
|
+
pair(code) {
|
|
160
|
+
if (this.disposed || this.pairing)
|
|
161
|
+
return Promise.reject(new Error("Pairing unavailable"));
|
|
162
|
+
let normalized;
|
|
163
|
+
try {
|
|
164
|
+
normalized = normalizePairingCode(code);
|
|
165
|
+
}
|
|
166
|
+
catch (error) {
|
|
167
|
+
return Promise.reject(error);
|
|
168
|
+
}
|
|
169
|
+
const controller = this.pairController = new AbortController();
|
|
170
|
+
const deadline = setTimeout(() => { this.update("error"); controller.abort(); }, PAIR_TIMEOUT);
|
|
171
|
+
const promise = this.lock(`mist-mcp:v1:${this.origin}:pair`, controller.signal, async () => {
|
|
172
|
+
if (this.storage.getItem(PAIRING_KEY) !== null)
|
|
173
|
+
throw new Error("Unpair before pairing another gateway");
|
|
174
|
+
this.update("connecting");
|
|
175
|
+
const record = await this.performPair(normalized, controller.signal);
|
|
176
|
+
check(controller.signal);
|
|
177
|
+
if (this.storage.getItem(PAIRING_KEY) !== null)
|
|
178
|
+
throw new Error("Pairing changed");
|
|
179
|
+
this.storage.setItem(PAIRING_KEY, canonicalJson(record));
|
|
180
|
+
broadcastChange();
|
|
181
|
+
}).catch(error => { if (!this.disposed && !controller.signal.aborted && this.raw === null)
|
|
182
|
+
this.update("error"); throw error; })
|
|
183
|
+
.finally(() => { clearTimeout(deadline); this.pairController = undefined; this.pairing = undefined; });
|
|
184
|
+
this.pairing = promise;
|
|
185
|
+
return promise;
|
|
186
|
+
}
|
|
187
|
+
async performPair(code, parent) {
|
|
188
|
+
const { controller, detach } = childController(parent);
|
|
189
|
+
const signal = controller.signal;
|
|
190
|
+
const transport = this.options.transport;
|
|
191
|
+
let room, inbox, handshake, cipher;
|
|
192
|
+
let deadline;
|
|
193
|
+
try {
|
|
194
|
+
const signer = await abortable(this.getSigner(), signal);
|
|
195
|
+
const keys = await abortable(generateStaticKeypair(), signal);
|
|
196
|
+
room = await pairingRoom(code);
|
|
197
|
+
check(signal);
|
|
198
|
+
inbox = new Inbox(transport, room, controller);
|
|
199
|
+
await abortable(transport.join(room), signal);
|
|
200
|
+
const { from, hello } = await inbox.hello(h => helloCompatible(h) && !!ed25519PublicKeyFromDidKey(h.gatewayDid));
|
|
201
|
+
const sid = randomId();
|
|
202
|
+
inbox.select(from, sid);
|
|
203
|
+
deadline = setTimeout(() => controller.abort(), SESSION_TIMEOUT);
|
|
204
|
+
handshake = await pairInitiator({ code, localStatic: keys, prologue: { roomId: room, initiatorNodeId: transport.selfNodeId, responderNodeId: from } });
|
|
205
|
+
check(signal);
|
|
206
|
+
await inbox.sendData("mcp.pair.challenge", handshake.writeMessage());
|
|
207
|
+
handshake.readMessage(await inbox.receiveData("mcp.pair.proof"));
|
|
208
|
+
await inbox.sendData("mcp.pair.proof", handshake.writeMessage());
|
|
209
|
+
const result = handshake.finish();
|
|
210
|
+
cipher = result.cipher;
|
|
211
|
+
const binding = await bindSession(result, { signer, expectedRemoteDid: hello.gatewayDid });
|
|
212
|
+
await inbox.sendData("mcp.pair.proof", binding.localBinding);
|
|
213
|
+
const session = await binding.accept(await inbox.receiveData("mcp.pair.proof"));
|
|
214
|
+
check(signal);
|
|
215
|
+
const fingerprint = await sha256(ed25519PublicKeyFromDidKey(session.remoteDid));
|
|
216
|
+
this.update("connecting", fingerprint);
|
|
217
|
+
await inbox.sendData("mcp.pair.grant", sealControl(cipher, "mcp.pair.grant", sid, { origin: this.origin }));
|
|
218
|
+
const body = openControl(cipher, "mcp.pair.grant", sid, await inbox.receiveData("mcp.pair.grant"));
|
|
219
|
+
if (!exactKeys(body, ["room", "ticket"]) || !isPermanentRoom(body.room))
|
|
220
|
+
throw new Error("Invalid pairing grant");
|
|
221
|
+
const ticket = await validateTicket(body.ticket, session.remoteDid, signer.did, this.origin, hello.instance);
|
|
222
|
+
check(signal);
|
|
223
|
+
return { v: 1, gatewayDid: session.remoteDid, remoteStatic: base64url(session.remoteStatic), localPrivate: base64url(keys.privateKey),
|
|
224
|
+
localPublic: base64url(keys.publicKey), instance: ticket.instance, room: body.room, ticket };
|
|
225
|
+
}
|
|
226
|
+
finally {
|
|
227
|
+
clearTimeout(deadline);
|
|
228
|
+
handshake?.close();
|
|
229
|
+
cipher?.close();
|
|
230
|
+
inbox?.close();
|
|
231
|
+
detach();
|
|
232
|
+
if (room)
|
|
233
|
+
await transport.leave(room);
|
|
234
|
+
}
|
|
235
|
+
}
|
|
236
|
+
async lead(record, fingerprint, signal) {
|
|
237
|
+
let backoff = 2000;
|
|
238
|
+
while (!signal.aborted) {
|
|
239
|
+
if (this.storage.getItem(PAIRING_KEY) !== this.raw) {
|
|
240
|
+
this.refresh();
|
|
241
|
+
break;
|
|
242
|
+
}
|
|
243
|
+
this.update("connecting", fingerprint);
|
|
244
|
+
try {
|
|
245
|
+
await this.connect(record, fingerprint, signal, () => { backoff = 2000; });
|
|
246
|
+
}
|
|
247
|
+
catch { /* session is already discarded */ }
|
|
248
|
+
if (signal.aborted)
|
|
249
|
+
break;
|
|
250
|
+
this.update("error", fingerprint);
|
|
251
|
+
// Capped exponential backoff, with jitter to avoid reconnect storms.
|
|
252
|
+
await delay(Math.min(60_000, backoff * (0.8 + Math.random() * 0.4)), signal);
|
|
253
|
+
backoff = Math.min(60_000, backoff * 2);
|
|
254
|
+
}
|
|
255
|
+
}
|
|
256
|
+
async connect(record, fingerprint, parent, established) {
|
|
257
|
+
const { controller, detach } = childController(parent);
|
|
258
|
+
const signal = controller.signal;
|
|
259
|
+
const transport = this.options.transport, room = record.room;
|
|
260
|
+
const expectedRaw = this.raw;
|
|
261
|
+
const pairingUnchanged = () => this.storage.getItem(PAIRING_KEY) === expectedRaw;
|
|
262
|
+
let inbox, handshake, cipher;
|
|
263
|
+
let server, reassembler, sweep;
|
|
264
|
+
let session, from, sid, sending = false, sendFailed = false, joined = false, authenticated = false;
|
|
265
|
+
const deadline = setTimeout(() => controller.abort(), SESSION_TIMEOUT);
|
|
266
|
+
try {
|
|
267
|
+
const signer = await abortable(this.getSigner(), signal);
|
|
268
|
+
await validateTicket(record.ticket, record.gatewayDid, signer.did, this.origin, record.instance);
|
|
269
|
+
check(signal);
|
|
270
|
+
inbox = new Inbox(transport, room, controller);
|
|
271
|
+
joined = true;
|
|
272
|
+
await abortable(transport.join(room), signal);
|
|
273
|
+
const found = await inbox.hello(h => helloCompatible(h) && h.gatewayDid === record.gatewayDid && h.instance === record.instance);
|
|
274
|
+
from = found.from;
|
|
275
|
+
const hello = found.hello;
|
|
276
|
+
sid = randomId();
|
|
277
|
+
inbox.select(from, sid);
|
|
278
|
+
handshake = await reconnectInitiator({ localStatic: localStatic(record), remoteStatic: unbase64url(record.remoteStatic),
|
|
279
|
+
prologue: { roomId: room, initiatorNodeId: transport.selfNodeId, responderNodeId: from } });
|
|
280
|
+
check(signal);
|
|
281
|
+
await inbox.sendData("mcp.auth.challenge", handshake.writeMessage());
|
|
282
|
+
handshake.readMessage(await inbox.receiveData("mcp.auth.proof"));
|
|
283
|
+
const result = handshake.finish();
|
|
284
|
+
cipher = result.cipher;
|
|
285
|
+
const binding = await bindSession(result, { signer, expectedRemoteDid: record.gatewayDid });
|
|
286
|
+
await inbox.sendData("mcp.auth.proof", binding.localBinding);
|
|
287
|
+
session = await binding.accept(await inbox.receiveData("mcp.auth.proof"));
|
|
288
|
+
check(signal);
|
|
289
|
+
if (!pairingUnchanged())
|
|
290
|
+
throw new Error("Pairing changed");
|
|
291
|
+
const context = { namespace: this.options.namespace, bootNonce: hello.bootNonce, limits: hello.limits };
|
|
292
|
+
await inbox.sendData("mcp.auth.grant", sealControl(cipher, "mcp.auth.grant", sid, { ...context, title: this.options.title, ticket: record.ticket }));
|
|
293
|
+
const accept = openControl(cipher, "mcp.auth.accept", sid, await inbox.receiveData("mcp.auth.accept"));
|
|
294
|
+
if (canonicalJson(accept) !== canonicalJson(context))
|
|
295
|
+
throw new Error("Invalid auth acceptance");
|
|
296
|
+
check(signal);
|
|
297
|
+
clearTimeout(deadline);
|
|
298
|
+
authenticated = true;
|
|
299
|
+
reassembler = new FrameReassembler(sid, cipher, undefined, hello.limits);
|
|
300
|
+
let lastReceived = performance.now();
|
|
301
|
+
const stillAuthorized = () => {
|
|
302
|
+
const now = Math.floor(Date.now() / 1000);
|
|
303
|
+
try {
|
|
304
|
+
return !signal.aborted && performance.now() - lastReceived < LIVENESS_TIMEOUT &&
|
|
305
|
+
record.ticket.nbf <= now && now < record.ticket.exp && pairingUnchanged();
|
|
306
|
+
}
|
|
307
|
+
catch {
|
|
308
|
+
return false;
|
|
309
|
+
}
|
|
310
|
+
};
|
|
311
|
+
const guard = (handler) => (args, ctx) => {
|
|
312
|
+
if (!stillAuthorized()) {
|
|
313
|
+
controller.abort();
|
|
314
|
+
throw new Error("Session no longer valid");
|
|
315
|
+
}
|
|
316
|
+
return handler(args, ctx);
|
|
317
|
+
};
|
|
318
|
+
server = new McpServer({ namespace: this.options.namespace, confirm: async (request) => {
|
|
319
|
+
if (!stillAuthorized() || !this.options.confirm)
|
|
320
|
+
return false;
|
|
321
|
+
const allowed = await this.options.confirm(request);
|
|
322
|
+
return stillAuthorized() && allowed === true;
|
|
323
|
+
},
|
|
324
|
+
onSessionError: () => { if (this.server === server)
|
|
325
|
+
this.server = undefined; controller.abort(); }, transport: {
|
|
326
|
+
onMessage: () => () => { }, // ordered inbox drives receive() directly below
|
|
327
|
+
send: async (bytes) => {
|
|
328
|
+
check(signal);
|
|
329
|
+
sending = true;
|
|
330
|
+
try {
|
|
331
|
+
for (const frame of splitFrames(bytes, sid, cipher, hello.limits))
|
|
332
|
+
await inbox.send(frame);
|
|
333
|
+
}
|
|
334
|
+
catch (error) {
|
|
335
|
+
sendFailed = true;
|
|
336
|
+
controller.abort();
|
|
337
|
+
throw error;
|
|
338
|
+
}
|
|
339
|
+
finally {
|
|
340
|
+
sending = false;
|
|
341
|
+
}
|
|
342
|
+
},
|
|
343
|
+
} });
|
|
344
|
+
for (const [name, tool] of this.tools)
|
|
345
|
+
tool.remove = server.registerTool(name, tool.definition, guard(tool.handler));
|
|
346
|
+
this.guardHandler = guard;
|
|
347
|
+
this.server = server;
|
|
348
|
+
signal.addEventListener("abort", () => { if (this.server === server)
|
|
349
|
+
this.server = undefined; server?.dispose(); }, { once: true });
|
|
350
|
+
sweep = setInterval(() => {
|
|
351
|
+
if (reassembler.expire() || !stillAuthorized())
|
|
352
|
+
controller.abort();
|
|
353
|
+
}, 1000);
|
|
354
|
+
established();
|
|
355
|
+
this.update("connected", fingerprint);
|
|
356
|
+
while (!signal.aborted) {
|
|
357
|
+
const { message } = await inbox.next();
|
|
358
|
+
if (!stillAuthorized() || reassembler.expire()) {
|
|
359
|
+
controller.abort();
|
|
360
|
+
break;
|
|
361
|
+
}
|
|
362
|
+
if (message.type === "mcp.frame") {
|
|
363
|
+
const bytes = reassembler.accept(message);
|
|
364
|
+
if (bytes) {
|
|
365
|
+
lastReceived = performance.now();
|
|
366
|
+
void server.receive(bytes).catch(() => controller.abort());
|
|
367
|
+
}
|
|
368
|
+
}
|
|
369
|
+
else if (message.type === "mcp.close") {
|
|
370
|
+
const body = openControl(cipher, "mcp.close", sid, unbase64url(message.data));
|
|
371
|
+
if (!exactKeys(body, []))
|
|
372
|
+
throw new Error("Invalid close");
|
|
373
|
+
break;
|
|
374
|
+
}
|
|
375
|
+
else
|
|
376
|
+
throw new Error("Unexpected authenticated record");
|
|
377
|
+
}
|
|
378
|
+
}
|
|
379
|
+
finally {
|
|
380
|
+
clearTimeout(deadline);
|
|
381
|
+
clearInterval(sweep);
|
|
382
|
+
if (this.server === server)
|
|
383
|
+
this.server = undefined;
|
|
384
|
+
this.guardHandler = undefined;
|
|
385
|
+
server?.dispose();
|
|
386
|
+
for (const tool of this.tools.values())
|
|
387
|
+
tool.remove = undefined;
|
|
388
|
+
// Best effort only on local shutdown, and never after a partial send.
|
|
389
|
+
if (parent.aborted && authenticated && session && !session.cipher.closed && !sending && !sendFailed && from && sid) {
|
|
390
|
+
try {
|
|
391
|
+
const data = base64url(sealControl(session.cipher, "mcp.close", sid, {}));
|
|
392
|
+
void Promise.resolve(transport.send(room, from, encodeWire({ v: 1, type: "mcp.close", sid, data }))).catch(() => { });
|
|
393
|
+
}
|
|
394
|
+
catch { /* no retry */ }
|
|
395
|
+
}
|
|
396
|
+
reassembler?.close();
|
|
397
|
+
handshake?.close();
|
|
398
|
+
cipher?.close();
|
|
399
|
+
inbox?.close();
|
|
400
|
+
detach();
|
|
401
|
+
if (joined)
|
|
402
|
+
await transport.leave(room);
|
|
403
|
+
}
|
|
404
|
+
}
|
|
405
|
+
async unpair() {
|
|
406
|
+
if (this.disposed)
|
|
407
|
+
return;
|
|
408
|
+
this.pairController?.abort();
|
|
409
|
+
this.runController?.abort();
|
|
410
|
+
this.storage.removeItem(PAIRING_KEY);
|
|
411
|
+
broadcastChange();
|
|
412
|
+
this.update("unpaired");
|
|
413
|
+
await Promise.allSettled([this.pairing, this.run]);
|
|
414
|
+
}
|
|
415
|
+
async dispose() {
|
|
416
|
+
if (!this.disposed) {
|
|
417
|
+
this.disposed = true;
|
|
418
|
+
this.pairController?.abort();
|
|
419
|
+
this.runController?.abort();
|
|
420
|
+
this.server?.dispose();
|
|
421
|
+
localListeners.delete(this.refresh);
|
|
422
|
+
globalThis.removeEventListener?.("storage", this.storageChanged);
|
|
423
|
+
this.statusListeners.clear();
|
|
424
|
+
this.tools.clear();
|
|
425
|
+
}
|
|
426
|
+
await Promise.allSettled([this.pairing, this.run]);
|
|
427
|
+
}
|
|
428
|
+
}
|
|
429
|
+
/** Create a provider; a valid saved pairing automatically starts reconnecting. */
|
|
430
|
+
export function createProvider(options) { return new Runtime(options); }
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
import type { MistTransport } from "./types.js";
|
|
2
|
+
/** mistlib event codes delivered through a shared node handle. */
|
|
3
|
+
export declare const MIST_EVENT_RAW = 0;
|
|
4
|
+
export declare const MIST_EVENT_PEER_CONNECTED = 2;
|
|
5
|
+
export declare const MIST_EVENT_PEER_DISCONNECTED = 3;
|
|
6
|
+
/**
|
|
7
|
+
* Structural shape of one handle from a shared-node scope (for example
|
|
8
|
+
* `createSharedNodeScope` in @tik-choco/mistai). One handle owns one room.
|
|
9
|
+
*/
|
|
10
|
+
export interface SharedNodeHandle {
|
|
11
|
+
init(): void | Promise<void>;
|
|
12
|
+
onEvent(handler: (event: number, from: string, payload: unknown, room?: string) => void): void;
|
|
13
|
+
joinRoom(room: string): void | Promise<void>;
|
|
14
|
+
leaveRoom(room?: string): void;
|
|
15
|
+
/** delivery 0 = reliable */
|
|
16
|
+
sendMessage(to: string, payload: Uint8Array, delivery?: 0, room?: string): void;
|
|
17
|
+
}
|
|
18
|
+
/**
|
|
19
|
+
* Builds a MistTransport from a shared-node handle factory. Each joined room
|
|
20
|
+
* gets its own handle, so leaving one room never releases another feature's
|
|
21
|
+
* membership on the same underlying node.
|
|
22
|
+
*/
|
|
23
|
+
export declare function fromSharedNodeScope(createHandle: (selfNodeId: string) => SharedNodeHandle, selfNodeId: string): MistTransport;
|
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
/** mistlib event codes delivered through a shared node handle. */
|
|
2
|
+
export const MIST_EVENT_RAW = 0;
|
|
3
|
+
export const MIST_EVENT_PEER_CONNECTED = 2;
|
|
4
|
+
export const MIST_EVENT_PEER_DISCONNECTED = 3;
|
|
5
|
+
function toBytes(payload) {
|
|
6
|
+
if (payload instanceof Uint8Array)
|
|
7
|
+
return payload;
|
|
8
|
+
if (payload instanceof ArrayBuffer)
|
|
9
|
+
return new Uint8Array(payload);
|
|
10
|
+
if (ArrayBuffer.isView(payload))
|
|
11
|
+
return new Uint8Array(payload.buffer, payload.byteOffset, payload.byteLength);
|
|
12
|
+
return undefined;
|
|
13
|
+
}
|
|
14
|
+
/**
|
|
15
|
+
* Builds a MistTransport from a shared-node handle factory. Each joined room
|
|
16
|
+
* gets its own handle, so leaving one room never releases another feature's
|
|
17
|
+
* membership on the same underlying node.
|
|
18
|
+
*/
|
|
19
|
+
export function fromSharedNodeScope(createHandle, selfNodeId) {
|
|
20
|
+
const rooms = new Map();
|
|
21
|
+
const messages = new Set();
|
|
22
|
+
const peers = new Set();
|
|
23
|
+
return {
|
|
24
|
+
selfNodeId,
|
|
25
|
+
join(room) {
|
|
26
|
+
const existing = rooms.get(room);
|
|
27
|
+
if (existing)
|
|
28
|
+
return existing.ready;
|
|
29
|
+
const node = createHandle(selfNodeId);
|
|
30
|
+
const entry = { node, ready: Promise.resolve() };
|
|
31
|
+
rooms.set(room, entry);
|
|
32
|
+
entry.ready = (async () => {
|
|
33
|
+
await node.init();
|
|
34
|
+
if (rooms.get(room) !== entry)
|
|
35
|
+
throw new Error("Room released");
|
|
36
|
+
node.onEvent((event, from, payload) => {
|
|
37
|
+
if (rooms.get(room) !== entry || !from)
|
|
38
|
+
return;
|
|
39
|
+
if (event === MIST_EVENT_RAW) {
|
|
40
|
+
const bytes = toBytes(payload);
|
|
41
|
+
if (bytes)
|
|
42
|
+
for (const cb of messages)
|
|
43
|
+
cb(room, from, bytes);
|
|
44
|
+
}
|
|
45
|
+
else if (event === MIST_EVENT_PEER_CONNECTED || event === MIST_EVENT_PEER_DISCONNECTED) {
|
|
46
|
+
for (const cb of peers)
|
|
47
|
+
cb(room, from, event === MIST_EVENT_PEER_CONNECTED);
|
|
48
|
+
}
|
|
49
|
+
});
|
|
50
|
+
await node.joinRoom(room);
|
|
51
|
+
if (rooms.get(room) !== entry)
|
|
52
|
+
throw new Error("Room released");
|
|
53
|
+
})().catch(error => {
|
|
54
|
+
if (rooms.get(room) === entry)
|
|
55
|
+
rooms.delete(room);
|
|
56
|
+
node.leaveRoom();
|
|
57
|
+
throw error;
|
|
58
|
+
});
|
|
59
|
+
return entry.ready;
|
|
60
|
+
},
|
|
61
|
+
leave(room) {
|
|
62
|
+
const entry = rooms.get(room);
|
|
63
|
+
rooms.delete(room);
|
|
64
|
+
entry?.node.leaveRoom();
|
|
65
|
+
},
|
|
66
|
+
async send(room, to, bytes) {
|
|
67
|
+
const entry = rooms.get(room);
|
|
68
|
+
if (!entry || !to)
|
|
69
|
+
throw new Error("Room or destination unavailable");
|
|
70
|
+
await entry.ready;
|
|
71
|
+
if (rooms.get(room) !== entry)
|
|
72
|
+
throw new Error("Room released");
|
|
73
|
+
entry.node.sendMessage(to, bytes, 0);
|
|
74
|
+
},
|
|
75
|
+
onMessage(cb) { messages.add(cb); return () => { messages.delete(cb); }; },
|
|
76
|
+
onPeer(cb) { peers.add(cb); return () => { peers.delete(cb); }; },
|
|
77
|
+
};
|
|
78
|
+
}
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
import type { ConfirmRequest, ToolDefinition, ToolHandler } from "../mcp/server.js";
|
|
2
|
+
import type { BindingSigner } from "../wire/noise-session.js";
|
|
3
|
+
export interface MistTransport {
|
|
4
|
+
readonly selfNodeId: string;
|
|
5
|
+
join(room: string): void | Promise<void>;
|
|
6
|
+
leave(room: string): void | Promise<void>;
|
|
7
|
+
send(room: string, toNodeId: string, bytes: Uint8Array): void | Promise<void>;
|
|
8
|
+
onMessage(cb: (room: string, from: string, bytes: Uint8Array) => void): () => void;
|
|
9
|
+
onPeer(cb: (room: string, nodeId: string, connected: boolean) => void): () => void;
|
|
10
|
+
}
|
|
11
|
+
export type PairingStorage = Pick<Storage, "getItem" | "setItem" | "removeItem">;
|
|
12
|
+
export type ProviderStatus = {
|
|
13
|
+
state: "unpaired" | "connecting" | "connected" | "error";
|
|
14
|
+
fingerprint?: string;
|
|
15
|
+
};
|
|
16
|
+
export interface ProviderOptions {
|
|
17
|
+
transport: MistTransport;
|
|
18
|
+
storage?: PairingStorage;
|
|
19
|
+
namespace: string;
|
|
20
|
+
title: string;
|
|
21
|
+
signer?: BindingSigner;
|
|
22
|
+
confirm?: (request: ConfirmRequest) => boolean | Promise<boolean>;
|
|
23
|
+
}
|
|
24
|
+
export interface Provider {
|
|
25
|
+
registerTool(name: string, definition: ToolDefinition, handler: ToolHandler): () => void;
|
|
26
|
+
pair(code: string): Promise<void>;
|
|
27
|
+
unpair(): Promise<void>;
|
|
28
|
+
readonly status: ProviderStatus;
|
|
29
|
+
onStatus(cb: (status: ProviderStatus) => void): () => void;
|
|
30
|
+
dispose(): Promise<void>;
|
|
31
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
export type Risk = "read" | "write" | "destructive";
|
|
2
|
+
interface Credential {
|
|
3
|
+
id: string;
|
|
4
|
+
iss: string;
|
|
5
|
+
aud: string;
|
|
6
|
+
origin: string;
|
|
7
|
+
instance: string;
|
|
8
|
+
epoch: number;
|
|
9
|
+
nbf: number;
|
|
10
|
+
exp: number;
|
|
11
|
+
sig: string;
|
|
12
|
+
}
|
|
13
|
+
export interface ProviderTicket extends Credential {
|
|
14
|
+
actions: ["register"];
|
|
15
|
+
}
|
|
16
|
+
export interface NamespaceGrant extends Credential {
|
|
17
|
+
namespace: string;
|
|
18
|
+
ticketId: string;
|
|
19
|
+
actions: Risk[];
|
|
20
|
+
catalogDigest: string;
|
|
21
|
+
localAgentAllowed: boolean;
|
|
22
|
+
}
|
|
23
|
+
export type SignatureVerifier = (publicKey: Uint8Array, bytes: Uint8Array, sig: Uint8Array) => boolean;
|
|
24
|
+
export interface CredentialContext {
|
|
25
|
+
iss: string;
|
|
26
|
+
aud: string;
|
|
27
|
+
origin: string;
|
|
28
|
+
instance: string;
|
|
29
|
+
epoch: number;
|
|
30
|
+
/** Seconds since Unix epoch. */
|
|
31
|
+
now: number;
|
|
32
|
+
publicKey: Uint8Array;
|
|
33
|
+
verify: SignatureVerifier;
|
|
34
|
+
isRevoked?: (id: string) => boolean;
|
|
35
|
+
}
|
|
36
|
+
export interface GrantContext extends CredentialContext {
|
|
37
|
+
namespace: string;
|
|
38
|
+
catalogDigest: string;
|
|
39
|
+
}
|
|
40
|
+
export declare function isOrigin(value: unknown): value is string;
|
|
41
|
+
export declare function isProviderTicket(v: unknown): v is ProviderTicket;
|
|
42
|
+
export declare function isNamespaceGrant(v: unknown): v is NamespaceGrant;
|
|
43
|
+
export declare function ticketSigningBytes(ticket: Omit<ProviderTicket, "sig"> | ProviderTicket): Uint8Array;
|
|
44
|
+
export declare function grantSigningBytes(grant: Omit<NamespaceGrant, "sig"> | NamespaceGrant): Uint8Array;
|
|
45
|
+
export declare function verifyTicket(v: unknown, ctx: CredentialContext): ProviderTicket;
|
|
46
|
+
export declare function verifyGrant(v: unknown, ticket: unknown, ctx: GrantContext): NamespaceGrant;
|
|
47
|
+
export {};
|