@ractive-ch/tab-mcp-client 0.18.1 → 0.19.0-rc.2
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/CHANGELOG.md +175 -0
- package/README.md +360 -68
- package/allowed.d.ts +2 -2
- package/allowed.js.map +1 -1
- package/always-allowed.d.ts +15 -15
- package/cdn/allowed.min.js +2 -2
- package/cdn/allowed.min.js.map +2 -2
- package/cdn/confirm-ba3dkf9p.min.js +4 -0
- package/cdn/confirm-ba3dkf9p.min.js.map +10 -0
- package/cdn/connect-my0pbqd7.min.js +6 -0
- package/cdn/connect-my0pbqd7.min.js.map +12 -0
- package/cdn/connection-yf2x9zz2.min.js +17 -0
- package/cdn/{connection-0xqwz17v.min.js.map → connection-yf2x9zz2.min.js.map} +5 -5
- package/cdn/strings.min.js +4 -0
- package/cdn/strings.min.js.map +9 -0
- package/cdn/{tab-mcp-client-2vx9mcww.min.js → tab-mcp-client-8r6h3wza.min.js} +9 -8
- package/cdn/tab-mcp-client-8r6h3wza.min.js.map +11 -0
- package/cdn/tab-mcp-client-nnxcwrxp.min.js +5 -0
- package/cdn/tab-mcp-client-nnxcwrxp.min.js.map +11 -0
- package/cdn/{tab-mcp-client-5j3brdf3.min.js → tab-mcp-client-q758jr4g.min.js} +4 -4
- package/cdn/tab-mcp-client-q758jr4g.min.js.map +10 -0
- package/cdn/tab-mcp-client.min.js +3 -3
- package/cdn/tab-mcp-client.min.js.map +4 -4
- package/cdn/webmcp-84k58gsw.min.js +4 -0
- package/cdn/webmcp-84k58gsw.min.js.map +11 -0
- package/{confirm-bqfdrx3f.js → confirm-hymzwx3b.js} +7 -5
- package/confirm-hymzwx3b.js.map +10 -0
- package/confirm.d.ts +2 -2
- package/{connect-ztsgybpq.js → connect-fhtjdmf3.js} +75 -37
- package/connect-fhtjdmf3.js.map +10 -0
- package/connect.d.ts +7 -6
- package/{connection-gang7f5x.js → connection-73fbg99k.js} +70 -8
- package/connection-73fbg99k.js.map +16 -0
- package/connection.d.ts +23 -2
- package/dialog.d.ts +19 -9
- package/extension.d.ts +373 -0
- package/extension.js +415 -0
- package/extension.js.map +10 -0
- package/handshake.d.ts +82 -0
- package/index-00p8b969.js +221 -0
- package/index-00p8b969.js.map +11 -0
- package/index-1tssct09.js +58 -0
- package/index-1tssct09.js.map +11 -0
- package/{index-c1c266tm.js → index-7qqhn3zv.js} +28 -110
- package/index-7qqhn3zv.js.map +10 -0
- package/index-s31xrfa2.js.map +1 -1
- package/index.d.ts +1 -1
- package/index.js +59 -64
- package/index.js.map +4 -4
- package/internal.d.ts +2 -0
- package/mcp.d.ts +5 -3
- package/package.json +11 -2
- package/protocol.d.ts +11 -1
- package/react.d.ts +11 -4
- package/react.js +57 -10
- package/react.js.map +5 -4
- package/secret.d.ts +1 -1
- package/setup.d.ts +4 -1
- package/setup.js +3 -2
- package/setup.js.map +1 -1
- package/strings.d.ts +149 -28
- package/strings.js +13 -0
- package/strings.js.map +9 -0
- package/tab-mcp.d.ts +30 -7
- package/text.d.ts +39 -0
- package/types.d.ts +76 -17
- package/webmcp-d2ec3v3g.js +221 -0
- package/webmcp-d2ec3v3g.js.map +11 -0
- package/webmcp.d.ts +17 -4
- package/cdn/confirm-d722a9eb.min.js +0 -4
- package/cdn/confirm-d722a9eb.min.js.map +0 -10
- package/cdn/connect-x6ws6wqt.min.js +0 -6
- package/cdn/connect-x6ws6wqt.min.js.map +0 -12
- package/cdn/connection-0xqwz17v.min.js +0 -17
- package/cdn/tab-mcp-client-2vx9mcww.min.js.map +0 -12
- package/cdn/tab-mcp-client-5j3brdf3.min.js.map +0 -10
- package/cdn/webmcp-khy4f5rj.min.js +0 -4
- package/cdn/webmcp-khy4f5rj.min.js.map +0 -10
- package/confirm-bqfdrx3f.js.map +0 -10
- package/connect-ztsgybpq.js.map +0 -10
- package/connection-gang7f5x.js.map +0 -16
- package/index-5jyqehpk.js +0 -63
- package/index-5jyqehpk.js.map +0 -11
- package/index-c1c266tm.js.map +0 -11
- package/webmcp-zq1enyz0.js +0 -57
- package/webmcp-zq1enyz0.js.map +0 -10
package/extension.js
ADDED
|
@@ -0,0 +1,415 @@
|
|
|
1
|
+
// src/extension.ts
|
|
2
|
+
var PAIRING_PORT = "pairing-page";
|
|
3
|
+
var PAIRING_PATH = "/authorize";
|
|
4
|
+
var MAX_CLIENT_NAME = 200;
|
|
5
|
+
var MAX_CLIENT_HOST = 253;
|
|
6
|
+
var isString = (value) => typeof value === "string";
|
|
7
|
+
function parseHello(message) {
|
|
8
|
+
if (typeof message !== "object" || message === null)
|
|
9
|
+
return;
|
|
10
|
+
const m = message;
|
|
11
|
+
if (m["type"] !== "pairing-page" || !isString(m["nonce"]) || !/^[\w-]{16,64}$/.test(m["nonce"]) || !isString(m["app"]) || !isString(m["clientName"]) || !isString(m["clientHost"]) || m["clientHost"] === "" || !isString(m["requestId"]) || !/^[\w-]{1,128}$/.test(m["requestId"]) || m["clientName"].length > MAX_CLIENT_NAME || m["clientHost"].length > MAX_CLIENT_HOST)
|
|
12
|
+
return;
|
|
13
|
+
return {
|
|
14
|
+
type: "pairing-page",
|
|
15
|
+
nonce: m["nonce"],
|
|
16
|
+
app: m["app"],
|
|
17
|
+
clientName: m["clientName"],
|
|
18
|
+
clientHost: m["clientHost"],
|
|
19
|
+
requestId: m["requestId"]
|
|
20
|
+
};
|
|
21
|
+
}
|
|
22
|
+
function parseFill(message, nonce) {
|
|
23
|
+
if (typeof message !== "object" || message === null)
|
|
24
|
+
return;
|
|
25
|
+
const m = message;
|
|
26
|
+
return m["type"] === "fill" && m["nonce"] === nonce && isString(m["code"]) && m["code"] !== "" ? { type: "fill", nonce, code: m["code"] } : undefined;
|
|
27
|
+
}
|
|
28
|
+
function relayPageOrigin(relay) {
|
|
29
|
+
let url;
|
|
30
|
+
try {
|
|
31
|
+
url = new URL(relay);
|
|
32
|
+
} catch {
|
|
33
|
+
return;
|
|
34
|
+
}
|
|
35
|
+
const scheme = url.protocol === "wss:" ? "https:" : url.protocol === "ws:" ? "http:" : url.protocol;
|
|
36
|
+
if (scheme !== "https:" && scheme !== "http:")
|
|
37
|
+
return;
|
|
38
|
+
return `${scheme}//${url.host}`;
|
|
39
|
+
}
|
|
40
|
+
function hostPattern(relay, path) {
|
|
41
|
+
const origin = relayPageOrigin(relay);
|
|
42
|
+
if (origin === undefined)
|
|
43
|
+
return;
|
|
44
|
+
const { protocol, hostname } = new URL(origin);
|
|
45
|
+
const host = hostname.toLowerCase().replace(/\.$/, "");
|
|
46
|
+
if (!/^[a-z0-9-]+(\.[a-z0-9-]+)*$/.test(host))
|
|
47
|
+
return;
|
|
48
|
+
return `${protocol}//${host}${path}`;
|
|
49
|
+
}
|
|
50
|
+
function relaySitePattern(relay) {
|
|
51
|
+
return hostPattern(relay, "/*");
|
|
52
|
+
}
|
|
53
|
+
function pairingPagePattern(relay) {
|
|
54
|
+
return hostPattern(relay, `${PAIRING_PATH}*`);
|
|
55
|
+
}
|
|
56
|
+
function findPairingForm(doc, where, app) {
|
|
57
|
+
if (!where.topLevel || where.pathname !== PAIRING_PATH)
|
|
58
|
+
return;
|
|
59
|
+
const forms = doc.querySelectorAll('form[data-tab-mcp-pairing="1"]');
|
|
60
|
+
const [form] = forms;
|
|
61
|
+
if (forms.length !== 1 || form === undefined)
|
|
62
|
+
return;
|
|
63
|
+
if (form.dataset["app"] !== app)
|
|
64
|
+
return;
|
|
65
|
+
const field = form.querySelector('input[data-tab-mcp-field="code"]');
|
|
66
|
+
const button = form.querySelector('button[data-tab-mcp-action="connect"]');
|
|
67
|
+
const clientName = form.dataset["clientName"];
|
|
68
|
+
const clientHost = form.dataset["clientHost"];
|
|
69
|
+
const requestId = form.querySelector('input[type="hidden"][name="request_id"]')?.value;
|
|
70
|
+
if (field === null || button === null || clientName === undefined || clientHost === undefined || clientHost === "" || !requestId)
|
|
71
|
+
return;
|
|
72
|
+
return { form, field, button, app, clientName, clientHost, requestId };
|
|
73
|
+
}
|
|
74
|
+
function fillIn(found, code) {
|
|
75
|
+
found.field.value = code;
|
|
76
|
+
const Input = found.field.ownerDocument.defaultView?.Event ?? Event;
|
|
77
|
+
found.field.dispatchEvent(new Input("input", { bubbles: true }));
|
|
78
|
+
found.form.requestSubmit(found.button);
|
|
79
|
+
}
|
|
80
|
+
function helloFor(found, nonce) {
|
|
81
|
+
return {
|
|
82
|
+
type: "pairing-page",
|
|
83
|
+
nonce,
|
|
84
|
+
app: found.app,
|
|
85
|
+
clientName: found.clientName,
|
|
86
|
+
clientHost: found.clientHost,
|
|
87
|
+
requestId: found.requestId
|
|
88
|
+
};
|
|
89
|
+
}
|
|
90
|
+
function runPairingPage(options) {
|
|
91
|
+
const flag = "__tabMcpPairingPage";
|
|
92
|
+
const scope = options.page?.document ?? globalThis;
|
|
93
|
+
if (scope[flag] === true)
|
|
94
|
+
return false;
|
|
95
|
+
scope[flag] = true;
|
|
96
|
+
const page = options.page ?? {
|
|
97
|
+
document,
|
|
98
|
+
topLevel: window.top === window,
|
|
99
|
+
pathname: location.pathname
|
|
100
|
+
};
|
|
101
|
+
const found = findPairingForm(page.document, page, options.app);
|
|
102
|
+
if (found === undefined)
|
|
103
|
+
return false;
|
|
104
|
+
const nonce = crypto.randomUUID();
|
|
105
|
+
const port = options.connect();
|
|
106
|
+
let filled = false;
|
|
107
|
+
port.onMessage.addListener((message) => {
|
|
108
|
+
const fill = parseFill(message, nonce);
|
|
109
|
+
if (fill === undefined || filled)
|
|
110
|
+
return;
|
|
111
|
+
filled = true;
|
|
112
|
+
fillIn(found, fill.code);
|
|
113
|
+
});
|
|
114
|
+
port.postMessage(helloFor(found, nonce));
|
|
115
|
+
return true;
|
|
116
|
+
}
|
|
117
|
+
function isPairingSender(sender, extensionId, relayOrigin) {
|
|
118
|
+
if (relayOrigin === undefined)
|
|
119
|
+
return false;
|
|
120
|
+
if (sender.id !== extensionId)
|
|
121
|
+
return false;
|
|
122
|
+
if (sender.tab === undefined || sender.frameId !== 0)
|
|
123
|
+
return false;
|
|
124
|
+
if (sender.origin !== undefined && sender.origin !== relayOrigin)
|
|
125
|
+
return false;
|
|
126
|
+
try {
|
|
127
|
+
const url = new URL(sender.url ?? "");
|
|
128
|
+
return url.origin === relayOrigin && url.pathname === PAIRING_PATH;
|
|
129
|
+
} catch {
|
|
130
|
+
return false;
|
|
131
|
+
}
|
|
132
|
+
}
|
|
133
|
+
var HELLO_WAIT_MS = 5000;
|
|
134
|
+
var RETRY_WINDOW_MS = 30000;
|
|
135
|
+
var CODE_WAIT_MS = 1e4;
|
|
136
|
+
var MIN_CODE_LEFT_MS = 5000;
|
|
137
|
+
var FILLED_CLOSE_MS = 5000;
|
|
138
|
+
function pagePort(port) {
|
|
139
|
+
const gone = new AbortController;
|
|
140
|
+
let first = () => {};
|
|
141
|
+
const hello = new Promise((resolve) => {
|
|
142
|
+
first = resolve;
|
|
143
|
+
});
|
|
144
|
+
const take = (message) => {
|
|
145
|
+
port.onMessage.removeListener(take);
|
|
146
|
+
first(message);
|
|
147
|
+
};
|
|
148
|
+
port.onMessage.addListener(take);
|
|
149
|
+
port.onDisconnect.addListener(() => {
|
|
150
|
+
gone.abort();
|
|
151
|
+
first(undefined);
|
|
152
|
+
});
|
|
153
|
+
return {
|
|
154
|
+
sender: port.sender ?? {},
|
|
155
|
+
hello,
|
|
156
|
+
signal: gone.signal,
|
|
157
|
+
send: (message) => {
|
|
158
|
+
try {
|
|
159
|
+
port.postMessage(message);
|
|
160
|
+
} catch {}
|
|
161
|
+
},
|
|
162
|
+
close: () => {
|
|
163
|
+
if (gone.signal.aborted)
|
|
164
|
+
return;
|
|
165
|
+
gone.abort();
|
|
166
|
+
first(undefined);
|
|
167
|
+
try {
|
|
168
|
+
port.disconnect();
|
|
169
|
+
} catch {}
|
|
170
|
+
}
|
|
171
|
+
};
|
|
172
|
+
}
|
|
173
|
+
var tabIdOf = (sender) => {
|
|
174
|
+
const id = sender.tab?.id;
|
|
175
|
+
return typeof id === "number" ? id : undefined;
|
|
176
|
+
};
|
|
177
|
+
function within(promise, ms) {
|
|
178
|
+
let timer;
|
|
179
|
+
return Promise.race([
|
|
180
|
+
promise,
|
|
181
|
+
new Promise((resolve) => {
|
|
182
|
+
timer = setTimeout(() => resolve(undefined), ms);
|
|
183
|
+
})
|
|
184
|
+
]).finally(() => clearTimeout(timer));
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
class CodeFiller {
|
|
188
|
+
#host;
|
|
189
|
+
#waiting = new Set;
|
|
190
|
+
#filled = new Map;
|
|
191
|
+
#grants;
|
|
192
|
+
#closeAfterMs;
|
|
193
|
+
#retry;
|
|
194
|
+
constructor(host, options = {}) {
|
|
195
|
+
this.#host = host;
|
|
196
|
+
this.#grants = options.grants === undefined ? undefined : new Set(options.grants);
|
|
197
|
+
this.#retry = options.retry ?? true;
|
|
198
|
+
this.#closeAfterMs = options.closeAfterMs ?? FILLED_CLOSE_MS;
|
|
199
|
+
}
|
|
200
|
+
async page(port) {
|
|
201
|
+
try {
|
|
202
|
+
await this.#page(port);
|
|
203
|
+
} catch (error) {
|
|
204
|
+
console.warn("tab-mcp: pairing page", error);
|
|
205
|
+
port.close();
|
|
206
|
+
}
|
|
207
|
+
}
|
|
208
|
+
async#page(port) {
|
|
209
|
+
const host = this.#host;
|
|
210
|
+
const tabId = tabIdOf(port.sender);
|
|
211
|
+
if (tabId === undefined || !isPairingSender(port.sender, host.extensionId, host.relayOrigin())) {
|
|
212
|
+
port.close();
|
|
213
|
+
return;
|
|
214
|
+
}
|
|
215
|
+
const hello = parseHello(await within(port.hello, HELLO_WAIT_MS));
|
|
216
|
+
if (hello === undefined || hello.app !== host.app || port.signal.aborted || !host.enabled() || !host.aiOn() || !isPairingSender(port.sender, host.extensionId, host.relayOrigin())) {
|
|
217
|
+
port.close();
|
|
218
|
+
return;
|
|
219
|
+
}
|
|
220
|
+
const context = {
|
|
221
|
+
tabId,
|
|
222
|
+
client: { name: hello.clientName, host: hello.clientHost }
|
|
223
|
+
};
|
|
224
|
+
const before = this.#lastFill(tabId);
|
|
225
|
+
if (this.#retry && before?.requestId === hello.requestId) {
|
|
226
|
+
if (before.count === 1)
|
|
227
|
+
await this.#fill(port, context, hello, 2);
|
|
228
|
+
else
|
|
229
|
+
port.close();
|
|
230
|
+
return;
|
|
231
|
+
}
|
|
232
|
+
const waiting = {
|
|
233
|
+
host: hello.clientHost,
|
|
234
|
+
withdraw: new AbortController
|
|
235
|
+
};
|
|
236
|
+
this.#waiting.add(waiting);
|
|
237
|
+
const signal = AbortSignal.any([port.signal, waiting.withdraw.signal]);
|
|
238
|
+
let answer;
|
|
239
|
+
try {
|
|
240
|
+
answer = await host.ask(tabId, { ...context.client }, signal);
|
|
241
|
+
} finally {
|
|
242
|
+
this.#waiting.delete(waiting);
|
|
243
|
+
}
|
|
244
|
+
if (answer === "busy")
|
|
245
|
+
host.failed("busy", context);
|
|
246
|
+
if (answer !== "allow" || signal.aborted || !host.enabled() || !host.aiOn() || !isPairingSender(port.sender, host.extensionId, host.relayOrigin())) {
|
|
247
|
+
port.close();
|
|
248
|
+
return;
|
|
249
|
+
}
|
|
250
|
+
await this.#fill(port, context, hello, 1);
|
|
251
|
+
}
|
|
252
|
+
#anyFill() {
|
|
253
|
+
this.#dropStale();
|
|
254
|
+
return this.#filled.size > 0;
|
|
255
|
+
}
|
|
256
|
+
#lastFill(tabId) {
|
|
257
|
+
this.#dropStale();
|
|
258
|
+
return this.#filled.get(tabId);
|
|
259
|
+
}
|
|
260
|
+
#dropStale() {
|
|
261
|
+
const now = this.#host.now();
|
|
262
|
+
for (const [id, filled] of this.#filled)
|
|
263
|
+
if (now - filled.at > RETRY_WINDOW_MS)
|
|
264
|
+
this.#filled.delete(id);
|
|
265
|
+
}
|
|
266
|
+
async#fill(port, context, hello, count) {
|
|
267
|
+
const host = this.#host;
|
|
268
|
+
const { tabId } = context;
|
|
269
|
+
const before = this.#filled.get(tabId);
|
|
270
|
+
const mark = {
|
|
271
|
+
requestId: hello.requestId,
|
|
272
|
+
host: hello.clientHost,
|
|
273
|
+
count,
|
|
274
|
+
at: host.now()
|
|
275
|
+
};
|
|
276
|
+
this.#filled.set(tabId, mark);
|
|
277
|
+
const waiting = {
|
|
278
|
+
host: hello.clientHost,
|
|
279
|
+
withdraw: new AbortController
|
|
280
|
+
};
|
|
281
|
+
this.#waiting.add(waiting);
|
|
282
|
+
const signal = AbortSignal.any([port.signal, waiting.withdraw.signal]);
|
|
283
|
+
let sent = false;
|
|
284
|
+
let keepBefore = true;
|
|
285
|
+
try {
|
|
286
|
+
const code = await host.code(signal, {
|
|
287
|
+
tabId,
|
|
288
|
+
client: { ...context.client }
|
|
289
|
+
});
|
|
290
|
+
const off = waiting.withdraw.signal.aborted || !host.enabled() || !host.aiOn() || !isPairingSender(port.sender, host.extensionId, host.relayOrigin());
|
|
291
|
+
if (off)
|
|
292
|
+
keepBefore = false;
|
|
293
|
+
if (off || port.signal.aborted)
|
|
294
|
+
return;
|
|
295
|
+
if (code === undefined) {
|
|
296
|
+
host.failed("no-code", { tabId, client: { ...context.client } });
|
|
297
|
+
return;
|
|
298
|
+
}
|
|
299
|
+
mark.at = host.now();
|
|
300
|
+
port.send({ type: "fill", nonce: hello.nonce, code });
|
|
301
|
+
sent = true;
|
|
302
|
+
setTimeout(() => port.close(), this.#closeAfterMs);
|
|
303
|
+
} finally {
|
|
304
|
+
this.#waiting.delete(waiting);
|
|
305
|
+
if (!sent) {
|
|
306
|
+
port.close();
|
|
307
|
+
if (this.#filled.get(tabId) === mark) {
|
|
308
|
+
if (keepBefore && before !== undefined)
|
|
309
|
+
this.#filled.set(tabId, before);
|
|
310
|
+
else
|
|
311
|
+
this.#filled.delete(tabId);
|
|
312
|
+
}
|
|
313
|
+
if (!this.#anyFill())
|
|
314
|
+
host.release();
|
|
315
|
+
}
|
|
316
|
+
}
|
|
317
|
+
}
|
|
318
|
+
grantsChanged(grants) {
|
|
319
|
+
if (this.#grants === undefined) {
|
|
320
|
+
this.#grants = new Set(grants.map((grant) => grant.grantId));
|
|
321
|
+
return;
|
|
322
|
+
}
|
|
323
|
+
const connected = new Set;
|
|
324
|
+
for (const grant of grants)
|
|
325
|
+
if (!this.#grants.has(grant.grantId)) {
|
|
326
|
+
this.#grants.add(grant.grantId);
|
|
327
|
+
connected.add(grant.host);
|
|
328
|
+
}
|
|
329
|
+
if (connected.size === 0)
|
|
330
|
+
return;
|
|
331
|
+
for (const waiting of this.#waiting)
|
|
332
|
+
if (connected.has(waiting.host))
|
|
333
|
+
waiting.withdraw.abort();
|
|
334
|
+
let done = false;
|
|
335
|
+
for (const [tabId, filled] of this.#filled)
|
|
336
|
+
if (connected.has(filled.host)) {
|
|
337
|
+
this.#filled.delete(tabId);
|
|
338
|
+
done = true;
|
|
339
|
+
}
|
|
340
|
+
if (done && !this.#anyFill())
|
|
341
|
+
this.#host.release();
|
|
342
|
+
}
|
|
343
|
+
withdrawAll() {
|
|
344
|
+
for (const waiting of this.#waiting)
|
|
345
|
+
waiting.withdraw.abort();
|
|
346
|
+
this.#filled.clear();
|
|
347
|
+
}
|
|
348
|
+
reset() {
|
|
349
|
+
this.withdrawAll();
|
|
350
|
+
this.#grants = undefined;
|
|
351
|
+
}
|
|
352
|
+
}
|
|
353
|
+
function pairingCodes(mcp) {
|
|
354
|
+
return {
|
|
355
|
+
current: () => mcp.pairingCode,
|
|
356
|
+
onChange: (listener) => {
|
|
357
|
+
mcp.addEventListener("pairingcode", listener);
|
|
358
|
+
return () => mcp.removeEventListener("pairingcode", listener);
|
|
359
|
+
}
|
|
360
|
+
};
|
|
361
|
+
}
|
|
362
|
+
function takeCode(source, signal, options) {
|
|
363
|
+
const { waitMs = CODE_WAIT_MS, minLeftMs = MIN_CODE_LEFT_MS } = options;
|
|
364
|
+
const started = Date.now();
|
|
365
|
+
const leaves = (code) => !(Date.parse(code.expiresAt) - (options.now + Date.now() - started) < minLeftMs);
|
|
366
|
+
const current = source.current();
|
|
367
|
+
if (current !== undefined && leaves(current))
|
|
368
|
+
return Promise.resolve(current.code);
|
|
369
|
+
if (signal.aborted)
|
|
370
|
+
return Promise.resolve(undefined);
|
|
371
|
+
return new Promise((resolve) => {
|
|
372
|
+
const done = (code) => {
|
|
373
|
+
clearTimeout(timer);
|
|
374
|
+
stop();
|
|
375
|
+
signal.removeEventListener("abort", aborted);
|
|
376
|
+
resolve(code);
|
|
377
|
+
};
|
|
378
|
+
const stop = source.onChange(() => {
|
|
379
|
+
const next = source.current();
|
|
380
|
+
if (next !== undefined && (next.code !== current?.code || leaves(next)))
|
|
381
|
+
done(next.code);
|
|
382
|
+
});
|
|
383
|
+
const aborted = () => done(undefined);
|
|
384
|
+
const timer = setTimeout(() => done(source.current()?.code), waitMs);
|
|
385
|
+
signal.addEventListener("abort", aborted, { once: true });
|
|
386
|
+
});
|
|
387
|
+
}
|
|
388
|
+
export {
|
|
389
|
+
CODE_WAIT_MS,
|
|
390
|
+
CodeFiller,
|
|
391
|
+
FILLED_CLOSE_MS,
|
|
392
|
+
HELLO_WAIT_MS,
|
|
393
|
+
MAX_CLIENT_HOST,
|
|
394
|
+
MAX_CLIENT_NAME,
|
|
395
|
+
MIN_CODE_LEFT_MS,
|
|
396
|
+
PAIRING_PATH,
|
|
397
|
+
PAIRING_PORT,
|
|
398
|
+
RETRY_WINDOW_MS,
|
|
399
|
+
fillIn,
|
|
400
|
+
findPairingForm,
|
|
401
|
+
helloFor,
|
|
402
|
+
isPairingSender,
|
|
403
|
+
pagePort,
|
|
404
|
+
pairingCodes,
|
|
405
|
+
pairingPagePattern,
|
|
406
|
+
parseFill,
|
|
407
|
+
parseHello,
|
|
408
|
+
relayPageOrigin,
|
|
409
|
+
relaySitePattern,
|
|
410
|
+
runPairingPage,
|
|
411
|
+
takeCode
|
|
412
|
+
};
|
|
413
|
+
|
|
414
|
+
//# debugId=61A1AFC13E8CBA8064756E2164756E21
|
|
415
|
+
//# sourceMappingURL=extension.js.map
|
package/extension.js.map
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["../src/extension.ts"],
|
|
4
|
+
"sourcesContent": [
|
|
5
|
+
"/**\n * `@ractive-ch/tab-mcp-client/extension`: for a browser extension that is a\n * tab-mcp page itself (the tab-mcp browser extension, Sitegloss). It fills\n * in the extension's own pairing code on the relay's pairing page\n * (`/authorize`) when an AI app opens it in the same browser, after asking\n * the user (DEC-199, DEC-203). What is the same for every such extension\n * lives here, reviewed once (DEC-206); how the user is asked, where the\n * setting is kept, the permission prompt, the content script's registration\n * and holding pairing on are each extension's own, given as callbacks.\n *\n * The relay's page has no scripts (DEC-057), so it cannot call the\n * extension: a content script reads the form's `data-tab-mcp-*` hooks and\n * tells the worker who asks (the AI app's name and verified host). The\n * worker asks its user and, on Allow, hands the code to that one page over\n * its port. The content script never sees a code before that, and the\n * worker never takes a page's word for where it is: any site can copy the\n * markup, so the origin the browser reports for the port is the check.\n *\n * An entry of its own that a web page never loads, out of the core. It\n * imports nothing of the rest of the library at run time and touches no\n * `window` or `document` until called, so a service worker and a content\n * script can both import it; a content script's bundle keeps only the page\n * side (`runPairingPage` and what it uses). No `chrome` types: the browser's\n * ports and senders are taken as the small structural types below.\n *\n * ```ts\n * // The content script, registered for the relay's /authorize page:\n * import { PAIRING_PORT, runPairingPage } from \"@ractive-ch/tab-mcp-client/extension\";\n * runPairingPage({ app: \"my-app\", connect: () => chrome.runtime.connect({ name: PAIRING_PORT }) });\n *\n * // The worker:\n * import { CodeFiller, PAIRING_PORT, pagePort } from \"@ractive-ch/tab-mcp-client/extension\";\n * const filler = new CodeFiller({ extensionId: chrome.runtime.id, app: \"my-app\", ... });\n * chrome.runtime.onConnect.addListener((port) => {\n * if (port.name === PAIRING_PORT) void filler.page(pagePort(port));\n * });\n * ```\n */\n\nimport type { TabMcp } from \"./tab-mcp.ts\";\nimport type { PairingCode } from \"./types.ts\";\n\n// --- What the content script and the worker say to each other ---\n\n/** The name of the port a pairing page's content script opens. */\nexport const PAIRING_PORT = \"pairing-page\";\n\n/** The relay's pairing page. */\nexport const PAIRING_PATH = \"/authorize\";\n\n/** What the content script says once, on its page's port. */\nexport interface PairingHello {\n\ttype: \"pairing-page\";\n\t/** This page load's own: the code comes back only with it. */\n\tnonce: string;\n\t/** `data-app`: the app the AI app asks to connect to. */\n\tapp: string;\n\t/** `data-client-name`: the AI app's name for itself. */\n\tclientName: string;\n\t/** `data-client-host`: the host the relay verified for the AI app. */\n\tclientHost: string;\n\t/**\n\t * The form's hidden `request_id`: the relay's id of this authorization\n\t * request, the same on its page again after a wrong code. The one fill\n\t * without a question is for this request only.\n\t */\n\trequestId: string;\n}\n\n/** What the worker sends after the user's Allow: the code to fill in and submit. */\nexport interface FillMessage {\n\ttype: \"fill\";\n\tnonce: string;\n\tcode: string;\n}\n\n/** The longest name and host a hello may carry (the relay's own limits are lower). */\nexport const MAX_CLIENT_NAME = 200;\nexport const MAX_CLIENT_HOST = 253;\n\nconst isString = (value: unknown): value is string => typeof value === \"string\";\n\n/**\n * The content script's hello, checked; `undefined` for anything else. The\n * name and host are what the relay's page says, kept as they are: the\n * extension's question must show invisible characters escaped (`./visible`).\n */\nexport function parseHello(message: unknown): PairingHello | undefined {\n\tif (typeof message !== \"object\" || message === null) return undefined;\n\tconst m = message as Record<string, unknown>;\n\tif (\n\t\tm[\"type\"] !== \"pairing-page\" ||\n\t\t!isString(m[\"nonce\"]) ||\n\t\t!/^[\\w-]{16,64}$/.test(m[\"nonce\"]) ||\n\t\t!isString(m[\"app\"]) ||\n\t\t!isString(m[\"clientName\"]) ||\n\t\t!isString(m[\"clientHost\"]) ||\n\t\tm[\"clientHost\"] === \"\" ||\n\t\t!isString(m[\"requestId\"]) ||\n\t\t!/^[\\w-]{1,128}$/.test(m[\"requestId\"]) ||\n\t\tm[\"clientName\"].length > MAX_CLIENT_NAME ||\n\t\tm[\"clientHost\"].length > MAX_CLIENT_HOST\n\t)\n\t\treturn undefined;\n\treturn {\n\t\ttype: \"pairing-page\",\n\t\tnonce: m[\"nonce\"],\n\t\tapp: m[\"app\"],\n\t\tclientName: m[\"clientName\"],\n\t\tclientHost: m[\"clientHost\"],\n\t\trequestId: m[\"requestId\"],\n\t};\n}\n\n/** The worker's fill message, checked against this page's nonce. */\nexport function parseFill(\n\tmessage: unknown,\n\tnonce: string,\n): FillMessage | undefined {\n\tif (typeof message !== \"object\" || message === null) return undefined;\n\tconst m = message as Record<string, unknown>;\n\treturn m[\"type\"] === \"fill\" &&\n\t\tm[\"nonce\"] === nonce &&\n\t\tisString(m[\"code\"]) &&\n\t\tm[\"code\"] !== \"\"\n\t\t? { type: \"fill\", nonce, code: m[\"code\"] }\n\t\t: undefined;\n}\n\n// --- Where the relay's pages are ---\n\n/**\n * The origin of the relay's web pages for the relay address `relay`: its\n * `ws:`/`wss:` forms are the same server's `http:`/`https:`. `undefined` for\n * anything that is not one.\n */\nexport function relayPageOrigin(relay: string): string | undefined {\n\tlet url: URL;\n\ttry {\n\t\turl = new URL(relay);\n\t} catch {\n\t\treturn undefined;\n\t}\n\tconst scheme =\n\t\turl.protocol === \"wss:\"\n\t\t\t? \"https:\"\n\t\t\t: url.protocol === \"ws:\"\n\t\t\t\t? \"http:\"\n\t\t\t\t: url.protocol;\n\tif (scheme !== \"https:\" && scheme !== \"http:\") return undefined;\n\treturn `${scheme}//${url.host}`;\n}\n\n/**\n * The match pattern for the relay's host, without its port: Firefox's\n * patterns take none, and Chrome's without one match every port. The exact\n * origin, port and all, is checked in the content script and in the worker.\n * The host in lower case without a trailing dot; one that is no plain name\n * or IPv4 address (an IPv6 literal, say) gives no pattern, as the browsers\n * do not agree on one for it.\n */\nfunction hostPattern(relay: string, path: string): string | undefined {\n\tconst origin = relayPageOrigin(relay);\n\tif (origin === undefined) return undefined;\n\tconst { protocol, hostname } = new URL(origin);\n\tconst host = hostname.toLowerCase().replace(/\\.$/, \"\");\n\tif (!/^[a-z0-9-]+(\\.[a-z0-9-]+)*$/.test(host)) return undefined;\n\treturn `${protocol}//${host}${path}`;\n}\n\n/**\n * The host permission for the relay's site (`<scheme>://<host>/*`), the one\n * origin to ask for (`permissions.request({ origins: [it] })`) before the\n * extension can see the pairing page. `undefined` for an address that has\n * no pattern: the user types the code.\n */\nexport function relaySitePattern(relay: string): string | undefined {\n\treturn hostPattern(relay, \"/*\");\n}\n\n/** The match pattern of the relay's pairing page, for a content script's `matches`. */\nexport function pairingPagePattern(relay: string): string | undefined {\n\treturn hostPattern(relay, `${PAIRING_PATH}*`);\n}\n\n// --- The content script on the relay's page ---\n\n/** The page's pairing form, as far as filling it in needs it. */\nexport interface PairingForm {\n\tform: HTMLFormElement;\n\tfield: HTMLInputElement;\n\tbutton: HTMLButtonElement;\n\tapp: string;\n\tclientName: string;\n\tclientHost: string;\n\t/** The relay's id of this request (the form's hidden `request_id`). */\n\trequestId: string;\n}\n\n/**\n * The pairing form of app `app` on `doc`, if this is a top-level page at\n * `/authorize` with exactly one such form that has a code field and a\n * Connect button (DEC-199's hooks, version 1). The worker checks the origin\n * itself; this only spares it the pages that are not one. A page that pairs\n * by sign-in only has no code field.\n */\nexport function findPairingForm(\n\tdoc: Document,\n\twhere: { topLevel: boolean; pathname: string },\n\tapp: string,\n): PairingForm | undefined {\n\tif (!where.topLevel || where.pathname !== PAIRING_PATH) return undefined;\n\tconst forms = doc.querySelectorAll<HTMLFormElement>(\n\t\t'form[data-tab-mcp-pairing=\"1\"]',\n\t);\n\tconst [form] = forms;\n\tif (forms.length !== 1 || form === undefined) return undefined;\n\tif (form.dataset[\"app\"] !== app) return undefined;\n\tconst field = form.querySelector<HTMLInputElement>(\n\t\t'input[data-tab-mcp-field=\"code\"]',\n\t);\n\tconst button = form.querySelector<HTMLButtonElement>(\n\t\t'button[data-tab-mcp-action=\"connect\"]',\n\t);\n\tconst clientName = form.dataset[\"clientName\"];\n\tconst clientHost = form.dataset[\"clientHost\"];\n\tconst requestId = form.querySelector<HTMLInputElement>(\n\t\t'input[type=\"hidden\"][name=\"request_id\"]',\n\t)?.value;\n\tif (\n\t\tfield === null ||\n\t\tbutton === null ||\n\t\tclientName === undefined ||\n\t\tclientHost === undefined ||\n\t\tclientHost === \"\" ||\n\t\t!requestId\n\t)\n\t\treturn undefined;\n\treturn { form, field, button, app, clientName, clientHost, requestId };\n}\n\n/**\n * Write `code` into the form's field and submit it with its Connect button:\n * the page's own post, as if the user had typed it and clicked.\n */\nexport function fillIn(found: PairingForm, code: string): void {\n\tfound.field.value = code;\n\t// The document's own Event (a test's DOM need not be the global one).\n\tconst Input = found.field.ownerDocument.defaultView?.Event ?? Event;\n\tfound.field.dispatchEvent(new Input(\"input\", { bubbles: true }));\n\tfound.form.requestSubmit(found.button);\n}\n\n/** The hello for `found`, with this page load's nonce. */\nexport function helloFor(found: PairingForm, nonce: string): PairingHello {\n\treturn {\n\t\ttype: \"pairing-page\",\n\t\tnonce,\n\t\tapp: found.app,\n\t\tclientName: found.clientName,\n\t\tclientHost: found.clientHost,\n\t\trequestId: found.requestId,\n\t};\n}\n\n/** The content script's end of its port (`chrome.runtime.Port` is one). */\nexport interface ContentPort {\n\tpostMessage(message: unknown): void;\n\treadonly onMessage: {\n\t\taddListener(listener: (message: unknown) => void): void;\n\t};\n}\n\n/**\n * The content script of the relay's pairing page: if the page has app\n * `app`'s pairing form, open a port to the worker (`connect`, with the name\n * PAIRING_PORT), say who asks, and wait. Only the worker's fill with this\n * page load's nonce is taken, once: its code is written into the field and\n * the form submitted. Once per document, also if the script is put in again\n * (after the user gave access with the page already open). Whether the\n * page has the form. `page` is the content script's own page unless a test\n * gives one.\n */\nexport function runPairingPage(options: {\n\tapp: string;\n\tconnect: () => ContentPort;\n\tpage?: { document: Document; topLevel: boolean; pathname: string };\n}): boolean {\n\tconst flag = \"__tabMcpPairingPage\";\n\t// A content script put in again runs in the same isolated world, so its\n\t// global marks the document. The document a test gives carries the mark\n\t// itself: two such pages in one test are independent.\n\tconst scope = (options.page?.document ?? globalThis) as unknown as Record<\n\t\tstring,\n\t\tunknown\n\t>;\n\tif (scope[flag] === true) return false;\n\tscope[flag] = true;\n\tconst page = options.page ?? {\n\t\tdocument,\n\t\ttopLevel: window.top === window,\n\t\tpathname: location.pathname,\n\t};\n\tconst found = findPairingForm(page.document, page, options.app);\n\tif (found === undefined) return false;\n\tconst nonce = crypto.randomUUID();\n\tconst port = options.connect();\n\tlet filled = false;\n\tport.onMessage.addListener((message) => {\n\t\tconst fill = parseFill(message, nonce);\n\t\t// One fill per page load: the page posts and goes.\n\t\tif (fill === undefined || filled) return;\n\t\tfilled = true;\n\t\tfillIn(found, fill.code);\n\t});\n\tport.postMessage(helloFor(found, nonce));\n\treturn true;\n}\n\n// --- The worker ---\n\n/** The sender of a port, as far as the check needs it (`chrome.runtime.MessageSender`). */\nexport interface PageSender {\n\tid?: string;\n\turl?: string;\n\t/** Chrome gives the document's origin; Firefox may not. */\n\torigin?: string;\n\ttab?: unknown;\n\tframeId?: number;\n}\n\n/**\n * A port from the pairing page of the relay at `relayOrigin`: this\n * extension's content script, in a tab, in its top frame, on a page whose\n * origin is exactly the relay's (port included) and whose path is\n * `/authorize`. A page anywhere else can carry the same markup: it is\n * ignored.\n */\nexport function isPairingSender(\n\tsender: PageSender,\n\textensionId: string,\n\trelayOrigin: string | undefined,\n): boolean {\n\tif (relayOrigin === undefined) return false;\n\tif (sender.id !== extensionId) return false;\n\tif (sender.tab === undefined || sender.frameId !== 0) return false;\n\t// Where the browser gives the document's origin, it is the one to trust\n\t// (a URL can be a `blob:` or `about:` of another origin's making).\n\tif (sender.origin !== undefined && sender.origin !== relayOrigin)\n\t\treturn false;\n\ttry {\n\t\tconst url = new URL(sender.url ?? \"\");\n\t\treturn url.origin === relayOrigin && url.pathname === PAIRING_PATH;\n\t} catch {\n\t\treturn false;\n\t}\n}\n\n/** A page will not say who asks in this time: it is dropped. */\nexport const HELLO_WAIT_MS = 5_000;\n/**\n * The same request's page in the same tab within this time after a fill is\n * the relay's answer to it: the code was not taken.\n */\nexport const RETRY_WINDOW_MS = 30_000;\n/** `takeCode`: how long to wait for the next code. */\nexport const CODE_WAIT_MS = 10_000;\n/** `takeCode`: a code with less time left than this is not used, the next one is. */\nexport const MIN_CODE_LEFT_MS = 5_000;\n/**\n * A filled-in page's port is closed this long after the fill: the page has\n * posted by then, and its answer, if any, is a new document with a port of\n * its own.\n */\nexport const FILLED_CLOSE_MS = 5_000;\n\n/** The worker's end of a page's port (`chrome.runtime.Port` is one). */\nexport interface WorkerPort {\n\treadonly sender?: PageSender;\n\tpostMessage(message: unknown): void;\n\tdisconnect(): void;\n\treadonly onMessage: {\n\t\taddListener(listener: (message: unknown) => void): void;\n\t\tremoveListener(listener: (message: unknown) => void): void;\n\t};\n\treadonly onDisconnect: { addListener(listener: () => void): void };\n}\n\n/**\n * A pairing page's port in the worker. Its first message and its end are\n * taken from the moment it connects: the worker may still be starting, and\n * Chrome hands a message only to the listeners there are.\n */\nexport interface PagePort {\n\treadonly sender: PageSender;\n\t/** The first message; `undefined` if the port went before one came. */\n\treadonly hello: Promise<unknown>;\n\t/** Aborted when the page goes (or the worker closes the port). */\n\treadonly signal: AbortSignal;\n\tsend(message: FillMessage): void;\n\tclose(): void;\n}\n\n/**\n * `port`, taken over at once (see PagePort): call it in `onConnect` itself,\n * before any `await`.\n */\nexport function pagePort(port: WorkerPort): PagePort {\n\tconst gone = new AbortController();\n\tlet first: (message: unknown) => void = () => {};\n\tconst hello = new Promise<unknown>((resolve) => {\n\t\tfirst = resolve;\n\t});\n\tconst take = (message: unknown) => {\n\t\tport.onMessage.removeListener(take);\n\t\tfirst(message);\n\t};\n\tport.onMessage.addListener(take);\n\tport.onDisconnect.addListener(() => {\n\t\tgone.abort();\n\t\tfirst(undefined);\n\t});\n\treturn {\n\t\tsender: port.sender ?? {},\n\t\thello,\n\t\tsignal: gone.signal,\n\t\tsend: (message) => {\n\t\t\ttry {\n\t\t\t\tport.postMessage(message);\n\t\t\t} catch {\n\t\t\t\t// The page went meanwhile.\n\t\t\t}\n\t\t},\n\t\tclose: () => {\n\t\t\tif (gone.signal.aborted) return;\n\t\t\t// Our own `disconnect()` fires no `onDisconnect` here.\n\t\t\tgone.abort();\n\t\t\tfirst(undefined);\n\t\t\ttry {\n\t\t\t\tport.disconnect();\n\t\t\t} catch {\n\t\t\t\t// Gone already.\n\t\t\t}\n\t\t},\n\t};\n}\n\n/**\n * The user's answer to \"Connect <name> (<host>)?\": only `allow` fills in.\n * `busy`: the extension could not ask (too many questions wait); the page is\n * reported (`failed(\"busy\")`), not dropped unseen.\n */\nexport type FillAnswer = \"allow\" | \"deny\" | \"timeout\" | \"busy\";\n\n/** Why a page that asked got no code: the extension tells its user. */\nexport type FillFailure =\n\t/** It could not be asked about (`ask` answered `busy`). */\n\t| \"busy\"\n\t/** Allow, but no code came from the relay (`code` gave none). */\n\t| \"no-code\";\n\n/** The page a fill is for: its tab and the AI app that asks there. */\nexport interface FillContext {\n\ttabId: number;\n\t/** The AI app's own name (may be `\"\"`) and the host the relay verified, as `ask` gets them. */\n\tclient: { name: string; host: string };\n}\n\n/** What `CodeFiller` needs from the extension: its parts of the fill-in. */\nexport interface FillHost {\n\t/** This extension's id (`chrome.runtime.id`): only its own content script speaks. */\n\textensionId: string;\n\t/** The app id of the extension's page: only forms with this `data-app`. */\n\tapp: string;\n\t/**\n\t * The origin of the relay's pages (`relayPageOrigin`) whose pairing page\n\t * may be filled in; `undefined` for none (another relay than the one the\n\t * extension fills in for).\n\t */\n\trelayOrigin(): string | undefined;\n\t/** AI access is on: connected, or on its way. Off, nothing is asked. */\n\taiOn(): boolean;\n\t/** The user turned filling in on, for this relay (opt-in, off by default). */\n\tenabled(): boolean;\n\t/**\n\t * Ask the user whether to connect the AI app `client` (its own name for\n\t * itself and the host the relay verified, both to be shown with invisible\n\t * characters escaped) in tab `tabId`. `signal` withdraws the question:\n\t * the page went, AI access or the setting went off, the relay changed,\n\t * or the AI app connected meanwhile; answer then with anything but\n\t * `allow`.\n\t */\n\task(\n\t\ttabId: number,\n\t\tclient: { name: string; host: string },\n\t\tsignal: AbortSignal,\n\t): Promise<FillAnswer>;\n\t/**\n\t * The code to fill in now on the page `context`, with pairing held on for\n\t * the relay to check it (`takeCode`); `undefined` if none came or\n\t * `signal` aborted (the page went, or the fill was withdrawn as a\n\t * question is). Even with a code, nothing is sent if what holds for\n\t * asking no longer does.\n\t */\n\tcode(signal: AbortSignal, context: FillContext): Promise<string | undefined>;\n\t/**\n\t * No fill needs pairing held on any more: a filled-in code paired its AI\n\t * app, or a fill ended without sending its code (withdrawn, the page\n\t * went, no code) while no other fill is under way or waits for the\n\t * relay's check. It may come again with nothing held: ignore it then.\n\t */\n\trelease(): void;\n\t/** The page `context` filled in nothing for `why`, or was not asked about: say so. */\n\tfailed(why: FillFailure, context: FillContext): void;\n\t/** The clock (`Date.now`; a test's own). */\n\tnow(): number;\n}\n\n/** A page whose question waits. */\ninterface Waiting {\n\thost: string;\n\twithdraw: AbortController;\n}\n\n/** The last fill in a tab. */\ninterface Filled {\n\t/** The relay's id of the request filled in. */\n\trequestId: string;\n\thost: string;\n\t/** Fills for it so far: 1 after Allow, 2 after the one more. */\n\tcount: number;\n\tat: number;\n}\n\nconst tabIdOf = (sender: PageSender): number | undefined => {\n\tconst id = (sender.tab as { id?: unknown } | undefined)?.id;\n\treturn typeof id === \"number\" ? id : undefined;\n};\n\nfunction within<T>(promise: Promise<T>, ms: number): Promise<T | undefined> {\n\tlet timer: ReturnType<typeof setTimeout> | undefined;\n\treturn Promise.race([\n\t\tpromise,\n\t\tnew Promise<undefined>((resolve) => {\n\t\t\ttimer = setTimeout(() => resolve(undefined), ms);\n\t\t}),\n\t]).finally(() => clearTimeout(timer));\n}\n\n/**\n * The worker's side of filling in the code (DEC-199, DEC-203): a page's port\n * is taken only from this extension's content script in the top frame of a\n * tab at exactly the relay's origin, and only while AI access is on and the\n * user turned filling in on. Then the user is asked, with the AI app's\n * verified host; on Allow the code goes to that one page, which fills it in\n * and submits.\n *\n * No loops: one question per page load (one port per document, one hello\n * per port). When the same tab shows the page of the same request (the\n * relay's `request_id`) again soon after a fill, it is the relay's answer\n * that the code was not taken (it had just changed): filled once more with\n * the code of then, without asking; the time after, nothing. Any other\n * request asks. With `retry: false` that page is asked about like any\n * other: every fill has a yes of its own. Don't allow, a timeout, the page\n * going, AI access or the setting going off, another relay or the AI app\n * connecting meanwhile fill nothing, and typing by hand works as before.\n */\nexport class CodeFiller {\n\treadonly #host: FillHost;\n\treadonly #waiting = new Set<Waiting>();\n\t/**\n\t * By tab: what was filled in there last, or is being filled in (marked\n\t * before the wait for the code, so that a page of the same request\n\t * meanwhile counts it).\n\t */\n\treadonly #filled = new Map<number, Filled>();\n\t/**\n\t * The grants seen so far: a new one is an AI app that just connected.\n\t * `undefined` until the first list, which is taken as it is: a worker\n\t * that starts before its connection is up has none to compare with.\n\t */\n\t#grants: Set<string> | undefined;\n\treadonly #closeAfterMs: number;\n\treadonly #retry: boolean;\n\n\t/**\n\t * `grants`: the ids of the grants there are already, if the extension kept\n\t * them between worker starts (not new when listed again); without them,\n\t * the first `grantsChanged` is taken as the list there is, nothing in it\n\t * new. `retry`: the one more fill without asking when the same request's\n\t * page comes back to the same tab soon after a fill (on unless `false`;\n\t * off, that page is asked about like any other, one question per page\n\t * load, and never filled without a yes). `closeAfterMs`: FILLED_CLOSE_MS\n\t * unless a test's is shorter.\n\t */\n\tconstructor(\n\t\thost: FillHost,\n\t\toptions: {\n\t\t\tgrants?: Iterable<string>;\n\t\t\tretry?: boolean;\n\t\t\tcloseAfterMs?: number;\n\t\t} = {},\n\t) {\n\t\tthis.#host = host;\n\t\tthis.#grants =\n\t\t\toptions.grants === undefined ? undefined : new Set(options.grants);\n\t\tthis.#retry = options.retry ?? true;\n\t\tthis.#closeAfterMs = options.closeAfterMs ?? FILLED_CLOSE_MS;\n\t}\n\n\t/**\n\t * A pairing page's port: checked, then asked about and maybe filled in.\n\t * Never rejects: a host callback that throws fills nothing, closes the\n\t * port and is logged.\n\t */\n\tasync page(port: PagePort): Promise<void> {\n\t\ttry {\n\t\t\tawait this.#page(port);\n\t\t} catch (error) {\n\t\t\tconsole.warn(\"tab-mcp: pairing page\", error);\n\t\t\tport.close();\n\t\t}\n\t}\n\n\tasync #page(port: PagePort): Promise<void> {\n\t\tconst host = this.#host;\n\t\tconst tabId = tabIdOf(port.sender);\n\t\tif (\n\t\t\ttabId === undefined ||\n\t\t\t!isPairingSender(port.sender, host.extensionId, host.relayOrigin())\n\t\t) {\n\t\t\tport.close();\n\t\t\treturn;\n\t\t}\n\t\tconst hello = parseHello(await within(port.hello, HELLO_WAIT_MS));\n\t\t// Only this extension's own app, only if the user turned filling in\n\t\t// on, only while AI access is on, and only while the relay is still\n\t\t// the one the page is of (it may have changed during the wait for\n\t\t// the hello): otherwise they have not asked for it.\n\t\tif (\n\t\t\thello === undefined ||\n\t\t\thello.app !== host.app ||\n\t\t\tport.signal.aborted ||\n\t\t\t!host.enabled() ||\n\t\t\t!host.aiOn() ||\n\t\t\t!isPairingSender(port.sender, host.extensionId, host.relayOrigin())\n\t\t) {\n\t\t\tport.close();\n\t\t\treturn;\n\t\t}\n\t\tconst context: FillContext = {\n\t\t\ttabId,\n\t\t\tclient: { name: hello.clientName, host: hello.clientHost },\n\t\t};\n\t\tconst before = this.#lastFill(tabId);\n\t\tif (this.#retry && before?.requestId === hello.requestId) {\n\t\t\t// The same request's page again after a fill: the code was not\n\t\t\t// taken. Once more with the code of now, then never again for it.\n\t\t\tif (before.count === 1) await this.#fill(port, context, hello, 2);\n\t\t\telse port.close();\n\t\t\treturn;\n\t\t}\n\t\tconst waiting: Waiting = {\n\t\t\thost: hello.clientHost,\n\t\t\twithdraw: new AbortController(),\n\t\t};\n\t\tthis.#waiting.add(waiting);\n\t\tconst signal = AbortSignal.any([port.signal, waiting.withdraw.signal]);\n\t\tlet answer: FillAnswer;\n\t\ttry {\n\t\t\tanswer = await host.ask(tabId, { ...context.client }, signal);\n\t\t} finally {\n\t\t\tthis.#waiting.delete(waiting);\n\t\t}\n\t\t// Too many questions wait: not dropped unseen.\n\t\tif (answer === \"busy\") host.failed(\"busy\", context);\n\t\tif (\n\t\t\tanswer !== \"allow\" ||\n\t\t\tsignal.aborted ||\n\t\t\t!host.enabled() ||\n\t\t\t!host.aiOn() ||\n\t\t\t!isPairingSender(port.sender, host.extensionId, host.relayOrigin())\n\t\t) {\n\t\t\tport.close();\n\t\t\treturn;\n\t\t}\n\t\tawait this.#fill(port, context, hello, 1);\n\t}\n\n\t/**\n\t * Whether a fill is under way or was sent recently enough for the relay\n\t * to be checking its code (the tabs' last fills, the stale ones dropped).\n\t */\n\t#anyFill(): boolean {\n\t\tthis.#dropStale();\n\t\treturn this.#filled.size > 0;\n\t}\n\n\t/** The last fill in `tabId`, if it is recent enough to be answered by this page. */\n\t#lastFill(tabId: number): Filled | undefined {\n\t\tthis.#dropStale();\n\t\treturn this.#filled.get(tabId);\n\t}\n\n\t#dropStale(): void {\n\t\tconst now = this.#host.now();\n\t\tfor (const [id, filled] of this.#filled)\n\t\t\tif (now - filled.at > RETRY_WINDOW_MS) this.#filled.delete(id);\n\t}\n\n\t/**\n\t * Fill `count` (1 after Allow, 2 the one more) of `hello`'s request in\n\t * `tabId`. The wait for the code is withdrawn like a question, and what\n\t * holds for asking is checked again once the code is there.\n\t */\n\tasync #fill(\n\t\tport: PagePort,\n\t\tcontext: FillContext,\n\t\thello: PairingHello,\n\t\tcount: number,\n\t): Promise<void> {\n\t\tconst host = this.#host;\n\t\tconst { tabId } = context;\n\t\tconst before = this.#filled.get(tabId);\n\t\t// Marked before the wait: a page of the same request that comes\n\t\t// meanwhile sees this count, so there is never a third fill.\n\t\tconst mark: Filled = {\n\t\t\trequestId: hello.requestId,\n\t\t\thost: hello.clientHost,\n\t\t\tcount,\n\t\t\tat: host.now(),\n\t\t};\n\t\tthis.#filled.set(tabId, mark);\n\t\tconst waiting: Waiting = {\n\t\t\thost: hello.clientHost,\n\t\t\twithdraw: new AbortController(),\n\t\t};\n\t\tthis.#waiting.add(waiting);\n\t\tconst signal = AbortSignal.any([port.signal, waiting.withdraw.signal]);\n\t\tlet sent = false;\n\t\t// A page that went or a code that did not come leaves the tab's last\n\t\t// fill as it was; a withdrawal leaves nothing to fill once more.\n\t\tlet keepBefore = true;\n\t\ttry {\n\t\t\tconst code = await host.code(signal, {\n\t\t\t\ttabId,\n\t\t\t\tclient: { ...context.client },\n\t\t\t});\n\t\t\tconst off =\n\t\t\t\twaiting.withdraw.signal.aborted ||\n\t\t\t\t!host.enabled() ||\n\t\t\t\t!host.aiOn() ||\n\t\t\t\t!isPairingSender(port.sender, host.extensionId, host.relayOrigin());\n\t\t\tif (off) keepBefore = false;\n\t\t\tif (off || port.signal.aborted) return;\n\t\t\tif (code === undefined) {\n\t\t\t\thost.failed(\"no-code\", { tabId, client: { ...context.client } });\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tmark.at = host.now();\n\t\t\tport.send({ type: \"fill\", nonce: hello.nonce, code });\n\t\t\tsent = true;\n\t\t\tsetTimeout(() => port.close(), this.#closeAfterMs);\n\t\t} finally {\n\t\t\tthis.#waiting.delete(waiting);\n\t\t\tif (!sent) {\n\t\t\t\tport.close();\n\t\t\t\tif (this.#filled.get(tabId) === mark) {\n\t\t\t\t\tif (keepBefore && before !== undefined)\n\t\t\t\t\t\tthis.#filled.set(tabId, before);\n\t\t\t\t\telse this.#filled.delete(tabId);\n\t\t\t\t}\n\t\t\t\t// `code` may have held pairing on for this fill: with no other\n\t\t\t\t// fill to hold it for, the host need not keep it on.\n\t\t\t\tif (!this.#anyFill()) host.release();\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * The relay's list of grants (`grantschange`): an AI app that just\n\t * connected (typed by hand, or filled in) withdraws the questions for its\n\t * host, and its fills are done with.\n\t */\n\tgrantsChanged(grants: readonly { grantId: string; host: string }[]): void {\n\t\tif (this.#grants === undefined) {\n\t\t\t// The first list without a seed: the grants there are, none new.\n\t\t\tthis.#grants = new Set(grants.map((grant) => grant.grantId));\n\t\t\treturn;\n\t\t}\n\t\tconst connected = new Set<string>();\n\t\tfor (const grant of grants)\n\t\t\tif (!this.#grants.has(grant.grantId)) {\n\t\t\t\tthis.#grants.add(grant.grantId);\n\t\t\t\tconnected.add(grant.host);\n\t\t\t}\n\t\tif (connected.size === 0) return;\n\t\tfor (const waiting of this.#waiting)\n\t\t\tif (connected.has(waiting.host)) waiting.withdraw.abort();\n\t\tlet done = false;\n\t\tfor (const [tabId, filled] of this.#filled)\n\t\t\tif (connected.has(filled.host)) {\n\t\t\t\tthis.#filled.delete(tabId);\n\t\t\t\tdone = true;\n\t\t\t}\n\t\t// Another AI app's fill may still be under way or wait for the relay's\n\t\t// check: stopping pairing now would void its code.\n\t\tif (done && !this.#anyFill()) this.#host.release();\n\t}\n\n\t/**\n\t * AI access off, or filling in turned off: the questions waiting are\n\t * withdrawn and no page gets the one more fill.\n\t */\n\twithdrawAll(): void {\n\t\tfor (const waiting of this.#waiting) waiting.withdraw.abort();\n\t\tthis.#filled.clear();\n\t}\n\n\t/**\n\t * Another relay: no page of the one before is asked about or filled in,\n\t * and the new relay's first list of grants is taken as it is.\n\t */\n\treset(): void {\n\t\tthis.withdrawAll();\n\t\tthis.#grants = undefined;\n\t}\n}\n\n/** Where the pairing codes come from (`pairingCodes(mcp)`). */\nexport interface CodeSource {\n\tcurrent(): PairingCode | undefined;\n\t/** Call `listener` on every new code (or none); returns how to stop. */\n\tonChange(listener: () => void): () => void;\n}\n\n/** The pairing codes of the extension's `TabMcp`, for `takeCode`. */\nexport function pairingCodes(\n\tmcp: Pick<TabMcp, \"pairingCode\" | \"addEventListener\" | \"removeEventListener\">,\n): CodeSource {\n\treturn {\n\t\tcurrent: () => mcp.pairingCode,\n\t\tonChange: (listener) => {\n\t\t\tmcp.addEventListener(\"pairingcode\", listener);\n\t\t\treturn () => mcp.removeEventListener(\"pairingcode\", listener);\n\t\t},\n\t};\n}\n\n/**\n * The code to fill in. The current one if it has `minLeftMs` left by this\n * clock (or an expiry that cannot be read); else the next one the relay\n * sends, which is fresh whatever the clocks say. The same code sent again\n * is not the next one: the relay answers each `pairing.start` with the code\n * it shows, so `startPairing()` with pairing on already brings back the\n * code that is about to change; it counts only if its expiry now leaves\n * `minLeftMs`. If no next one comes within `waitMs`, the current one after\n * all: with this clock ahead every code would look expired, so the fill\n * then waits the whole `waitMs` before it gets that code. The relay\n * refuses a code that has expired; the one more fill for the same request\n * covers that, or with `retry: false` a new question. `undefined` only\n * without any code, or when `signal` aborts. Pairing must be on\n * (`startPairing()`) for codes to come.\n */\nexport function takeCode(\n\tsource: CodeSource,\n\tsignal: AbortSignal,\n\toptions: { now: number; waitMs?: number; minLeftMs?: number },\n): Promise<string | undefined> {\n\tconst { waitMs = CODE_WAIT_MS, minLeftMs = MIN_CODE_LEFT_MS } = options;\n\t// `now` is the caller's clock; the time since is the real one's.\n\tconst started = Date.now();\n\tconst leaves = (code: PairingCode) =>\n\t\t!(\n\t\t\tDate.parse(code.expiresAt) - (options.now + Date.now() - started) <\n\t\t\tminLeftMs\n\t\t);\n\tconst current = source.current();\n\tif (current !== undefined && leaves(current))\n\t\treturn Promise.resolve(current.code);\n\tif (signal.aborted) return Promise.resolve(undefined);\n\treturn new Promise((resolve) => {\n\t\tconst done = (code: string | undefined) => {\n\t\t\tclearTimeout(timer);\n\t\t\tstop();\n\t\t\tsignal.removeEventListener(\"abort\", aborted);\n\t\t\tresolve(code);\n\t\t};\n\t\tconst stop = source.onChange(() => {\n\t\t\tconst next = source.current();\n\t\t\tif (next !== undefined && (next.code !== current?.code || leaves(next)))\n\t\t\t\tdone(next.code);\n\t\t});\n\t\tconst aborted = () => done(undefined);\n\t\tconst timer = setTimeout(() => done(source.current()?.code), waitMs);\n\t\tsignal.addEventListener(\"abort\", aborted, { once: true });\n\t});\n}\n"
|
|
6
|
+
],
|
|
7
|
+
"mappings": ";AA6CO,IAAM,eAAe;AAGrB,IAAM,eAAe;AA6BrB,IAAM,kBAAkB;AACxB,IAAM,kBAAkB;AAE/B,IAAM,WAAW,CAAC,UAAoC,OAAO,UAAU;AAOhE,SAAS,UAAU,CAAC,SAA4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AAA,MAClB,KAAK;AAAA,MACL,OAAO,oBAAoB,SAAS,OAAO;AAAA,MAC3C,QAAQ,IAAI;AAAA;AAAA,IAEb,MAAM,OAAO,OAAO,SAAS,MAAM;AAAA,MAClC,MAAM,OAAO,OAAO,QAAQ;AAAA,MAC5B,IAAI,SAAS,cAAc,KAAK,SAAS,SAAS,QAAQ,OAAO,IAAI;AAAA,QACpE,KAAK,KAAK,IAAI;AAAA,KACf;AAAA,IACD,MAAM,UAAU,MAAM,KAAK,SAAS;AAAA,IACpC,MAAM,QAAQ,WAAW,MAAM,KAAK,OAAO,QAAQ,GAAG,IAAI,GAAG,MAAM;AAAA,IACnE,OAAO,iBAAiB,SAAS,SAAS,EAAE,MAAM,KAAK,CAAC;AAAA,GACxD;AAAA;",
|
|
8
|
+
"debugId": "61A1AFC13E8CBA8064756E2164756E21",
|
|
9
|
+
"names": []
|
|
10
|
+
}
|
package/handshake.d.ts
ADDED
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The page's side of the handshake with the tab-mcp browser extension
|
|
3
|
+
* (DEC-207), in the WebMCP mirror's chunk: only a page that offers its tools
|
|
4
|
+
* to agents in the browser (`webmcp: true`) takes part.
|
|
5
|
+
*
|
|
6
|
+
* Plain DOM events on `document`, each with a JSON string as `detail`
|
|
7
|
+
* (objects do not cross between a content script's world and the page's in
|
|
8
|
+
* every browser): `tab-mcp-page` from the page, `tab-mcp-extension` from
|
|
9
|
+
* the extension. Every message has `v: 1` and a `type`; a message of
|
|
10
|
+
* another version, an unknown type or a malformed one is ignored, and so
|
|
11
|
+
* are unknown fields.
|
|
12
|
+
*
|
|
13
|
+
* - The page announces itself (`hello`: the library's version, the app id,
|
|
14
|
+
* the AI apps connected to it directly) when it starts, again (`update`)
|
|
15
|
+
* when those apps change, and answers the extension's `hello` with an
|
|
16
|
+
* `update`. It marks `<html data-tab-mcp-handshake>`, so that an
|
|
17
|
+
* extension that starts later (its content script comes at
|
|
18
|
+
* `document_idle`, or with a click) knows it may speak without having
|
|
19
|
+
* heard the `hello`.
|
|
20
|
+
* - The extension says what it is, whether it serves the page now and
|
|
21
|
+
* which AI apps are connected to it (`hello`, `update`), and, right before
|
|
22
|
+
* it runs a page tool the user allowed there, `vouch`: the tool, the exact
|
|
23
|
+
* arguments, a nonce and the AI app; once that call ended or failed,
|
|
24
|
+
* `withdraw` with the nonce, and a vouch still unused is dropped.
|
|
25
|
+
* - Each side cuts the other's list of AI apps to 64 and sends no more.
|
|
26
|
+
*
|
|
27
|
+
* No proof of who sent what: anything that could fake the extension runs in
|
|
28
|
+
* the page already, where it could skip any check. A convenience between
|
|
29
|
+
* two parts the user trusts, not a security boundary.
|
|
30
|
+
*/
|
|
31
|
+
import type { RegisteredTool, ToolRegistry } from "./registry.js";
|
|
32
|
+
import type { BrowserExtension, Grant } from "./types.js";
|
|
33
|
+
/** From the page to the extension. */
|
|
34
|
+
export declare const PAGE_EVENT = "tab-mcp-page";
|
|
35
|
+
/** From the extension to the page. */
|
|
36
|
+
export declare const EXTENSION_EVENT = "tab-mcp-extension";
|
|
37
|
+
/** On `<html>`: this page takes part (for an extension that starts later). */
|
|
38
|
+
export declare const MARK = "data-tab-mcp-handshake";
|
|
39
|
+
/** A vouch is kept this long (milliseconds), then dropped unused. */
|
|
40
|
+
export declare const VOUCH_MS = 2000;
|
|
41
|
+
/** One `TabMcp` of the page, as the handshake sees it. */
|
|
42
|
+
export interface HandshakePage {
|
|
43
|
+
/** The library's version. */
|
|
44
|
+
readonly version: string;
|
|
45
|
+
readonly app: string;
|
|
46
|
+
readonly registry: ToolRegistry;
|
|
47
|
+
/** Vouches are taken for its tools (`trustExtension`). */
|
|
48
|
+
readonly trust: boolean;
|
|
49
|
+
/** The `TabMcp`: its `grants` and `grantschange`. */
|
|
50
|
+
readonly mcp: EventTarget & {
|
|
51
|
+
readonly grants: readonly Grant[];
|
|
52
|
+
};
|
|
53
|
+
/** The extension's state changed. */
|
|
54
|
+
set(extension: BrowserExtension | undefined): void;
|
|
55
|
+
}
|
|
56
|
+
/** The AI app a vouched call came from. */
|
|
57
|
+
export interface VouchedBy {
|
|
58
|
+
name: string;
|
|
59
|
+
host: string;
|
|
60
|
+
}
|
|
61
|
+
/**
|
|
62
|
+
* `value` as JSON with the keys of every object sorted: two argument
|
|
63
|
+
* objects are equal when their canonical forms are.
|
|
64
|
+
*/
|
|
65
|
+
export declare function canonical(value: unknown): string;
|
|
66
|
+
declare class Handshake {
|
|
67
|
+
#private;
|
|
68
|
+
constructor(doc: Document);
|
|
69
|
+
join(page: HandshakePage): void;
|
|
70
|
+
/**
|
|
71
|
+
* The vouch for this call of `tool` with `input`, used up; `undefined`
|
|
72
|
+
* if there is none (the call is asked as without the extension).
|
|
73
|
+
*/
|
|
74
|
+
take(tool: RegisteredTool, input: unknown): VouchedBy | undefined;
|
|
75
|
+
}
|
|
76
|
+
/**
|
|
77
|
+
* The handshake of the page's top-level document, which `page` joins; the
|
|
78
|
+
* extension speaks only to the top frame. `undefined` in a frame or
|
|
79
|
+
* without a document.
|
|
80
|
+
*/
|
|
81
|
+
export declare function joinHandshake(page: HandshakePage): Handshake | undefined;
|
|
82
|
+
export {};
|