teapot-coding-agent 0.29.33 → 0.29.35

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/public/index.html CHANGED
@@ -20,8 +20,8 @@
20
20
  } catch (e) { /* private mode etc — keep defaults */ }
21
21
  })();
22
22
  </script>
23
- <script type="module" crossorigin src="/assets/index-C6gqo0nb.js"></script>
24
- <link rel="stylesheet" crossorigin href="/assets/index-CUgmNS8b.css">
23
+ <script type="module" crossorigin src="/assets/index-CYUWPPHN.js"></script>
24
+ <link rel="stylesheet" crossorigin href="/assets/index-DWK26mKp.css">
25
25
  </head>
26
26
  <body>
27
27
  <div id="root"></div>
@@ -1,429 +0,0 @@
1
- /**
2
- * MCP OAuth 2.1 (#67 follow-up): discovery, PKCE, token exchange, refresh.
3
- *
4
- * An OAuth-protected MCP server answers an unauthenticated request with **401 and a
5
- * `WWW-Authenticate: Bearer …` challenge**. That single response carries everything
6
- * needed to find the authorization server, so no configuration is required from the
7
- * operator: probe → discover → register → authorize → retry.
8
- *
9
- * The chain, and the spec each link comes from:
10
- *
11
- * 401 + WWW-Authenticate RFC 6750 (the challenge, with `resource_metadata`)
12
- * → protected-resource metadata RFC 9728 (`authorization_servers`, `scopes_supported`)
13
- * → authorization-server metadata RFC 8414 (`/.well-known/oauth-authorization-server`)
14
- * → optional dynamic registration RFC 7591 (`registration_endpoint`)
15
- * → authorization code + PKCE S256 RFC 7636 (MCP requires PKCE; it leaks nothing
16
- * because the verifier never leaves us)
17
- * → token exchange / refresh
18
- *
19
- * What is modelled from the reference implementations (akku1139/deepseek-pp PR #1 and
20
- * easywebui), and why:
21
- * - send a REAL `initialize` POST when probing, because servers police the request
22
- * shape differently and a bare GET can 200 on a health page;
23
- * - only trust a 401 that carries a Bearer challenge — a plain 401 with no
24
- * `WWW-Authenticate` is a "wrong token", not "use OAuth here";
25
- * - keep the access token in MEMORY only, bound to a fingerprint of the credentials,
26
- * so a changed client id can never reuse a stale token;
27
- * - persist the REFRESH token, and persist a ROTATED one immediately — a server that
28
- * rotates invalidates the old token, and reusing it fails with `invalid_grant`;
29
- * - re-request the originally granted scopes on refresh, or the token endpoint can
30
- * return 200 with a token the resource server then refuses.
31
- *
32
- * What is DELIBERATELY different: the redirect. easywebui runs serverless and needs a
33
- * host-provided browser identity port; teapot is a local server with a browser UI, so
34
- * it runs a real loopback callback (`OAuthPending`). That removes the copy-paste step
35
- * entirely — the operator opens a URL and the tab closes itself.
36
- */
37
- import { createHash, randomBytes } from "node:crypto";
38
- /**
39
- * Parse the FIRST Bearer challenge out of a `WWW-Authenticate` header.
40
- *
41
- * The header can carry several challenges (`Digest …, Bearer …`), and commas appear
42
- * both between challenges and INSIDE the Bearer parameters, so this scans for
43
- * `Bearer` and then reads `key="value"` / `key=token` pairs without splitting on
44
- * commas — splitting first is the classic way to lose `resource_metadata` when its URL
45
- * contains one.
46
- */
47
- export function parseBearerChallenge(header) {
48
- if (!header)
49
- return null;
50
- const at = header.search(/\bBearer\b/i);
51
- if (at === -1)
52
- return null;
53
- const rest = header.slice(at + "Bearer".length);
54
- const out = { raw: header };
55
- // stop at the next scheme if another challenge follows
56
- const nextScheme = rest.search(/,\s*[A-Za-z][A-Za-z0-9_-]*\s+[^=,\s]/);
57
- const body = nextScheme === -1 ? rest : rest.slice(0, nextScheme);
58
- const re = /([A-Za-z_][A-Za-z0-9_-]*)\s*=\s*(?:"((?:[^"\\]|\\.)*)"|([^\s,]+))/g;
59
- let m;
60
- while ((m = re.exec(body))) {
61
- const key = m[1].toLowerCase();
62
- const value = (m[2] ?? m[3] ?? "").replace(/\\(.)/g, "$1");
63
- if (key === "resource_metadata")
64
- out.resourceMetadataUrl = value;
65
- else if (key === "scope")
66
- out.scope = value;
67
- else if (key === "error")
68
- out.error = value;
69
- }
70
- return out;
71
- }
72
- /** PKCE verifier + S256 challenge (RFC 7636) */
73
- export function pkcePair() {
74
- // 32 random bytes → 43 base64url chars, inside the spec's 43..128 range
75
- const verifier = randomBytes(32).toString("base64url");
76
- const challenge = createHash("sha256").update(verifier).digest("base64url");
77
- return { verifier, challenge };
78
- }
79
- const PROBE_TIMEOUT_MS = 15_000;
80
- async function fetchJson(url, signal) {
81
- const ac = new AbortController();
82
- const timer = setTimeout(() => ac.abort(), PROBE_TIMEOUT_MS);
83
- const onAbort = () => ac.abort();
84
- signal?.addEventListener("abort", onAbort, { once: true });
85
- try {
86
- const res = await fetch(url, {
87
- headers: { accept: "application/json" },
88
- signal: ac.signal,
89
- redirect: "follow",
90
- });
91
- if (!res.ok)
92
- throw new Error(`${url} returned HTTP ${res.status}`);
93
- const text = await res.text();
94
- try {
95
- return JSON.parse(text);
96
- }
97
- catch {
98
- // keep the body visible: an HTML login page with a JSON content type is a
99
- // completely different problem from a malformed metadata document
100
- throw new Error(`${url} did not return JSON: ${text.slice(0, 160)}`);
101
- }
102
- }
103
- finally {
104
- clearTimeout(timer);
105
- signal?.removeEventListener("abort", onAbort);
106
- }
107
- }
108
- const str = (v) => (typeof v === "string" && v ? v : undefined);
109
- const strList = (v) => Array.isArray(v) ? v.filter((x) => typeof x === "string" && !!x) : undefined;
110
- /**
111
- * Probe an MCP endpoint and, when it demands OAuth, resolve its authorization server.
112
- *
113
- * Returns `requiresOAuth: false` with no error for a healthy endpoint (nothing to do)
114
- * and for one whose 401 carries no Bearer challenge (a bad token, not a missing grant).
115
- */
116
- export async function detectOAuth(endpoint, opts = {}) {
117
- let url;
118
- try {
119
- url = new URL(endpoint);
120
- }
121
- catch {
122
- return { requiresOAuth: false, reason: `invalid url: ${endpoint}` };
123
- }
124
- if (!["http:", "https:"].includes(url.protocol))
125
- return { requiresOAuth: false, reason: `not an http(s) url: ${endpoint}` };
126
- // A REAL initialize request: servers police the shape differently, and a bare GET
127
- // often 200s on a landing page, which would read as "no auth needed".
128
- const ac = new AbortController();
129
- const timer = setTimeout(() => ac.abort(), PROBE_TIMEOUT_MS);
130
- const onAbort = () => ac.abort();
131
- opts.signal?.addEventListener("abort", onAbort, { once: true });
132
- let res;
133
- try {
134
- res = await fetch(url, {
135
- method: "POST",
136
- headers: {
137
- "content-type": "application/json",
138
- accept: "application/json, text/event-stream",
139
- ...(opts.headers ?? {}),
140
- },
141
- body: JSON.stringify({
142
- jsonrpc: "2.0",
143
- id: 1,
144
- method: "initialize",
145
- params: { protocolVersion: "2025-06-18", capabilities: {}, clientInfo: { name: "teapot", version: "1" } },
146
- }),
147
- // manual so an HTML login page is visible rather than silently followed
148
- redirect: "manual",
149
- signal: ac.signal,
150
- });
151
- }
152
- catch (err) {
153
- return {
154
- requiresOAuth: false,
155
- reason: err.name === "AbortError" ? "probe timed out" : err.message,
156
- };
157
- }
158
- finally {
159
- clearTimeout(timer);
160
- opts.signal?.removeEventListener("abort", onAbort);
161
- }
162
- // drain so the socket is released
163
- await res.body?.cancel().catch(() => { });
164
- if (res.status !== 401)
165
- return { requiresOAuth: false };
166
- const challenge = parseBearerChallenge(res.headers.get("www-authenticate"));
167
- if (!challenge)
168
- return {
169
- requiresOAuth: false,
170
- reason: "the server answered 401 without a Bearer challenge — this is a rejected credential, " +
171
- "not a missing OAuth grant",
172
- };
173
- const resource = opts.resource ?? url.toString();
174
- if (!challenge.resourceMetadataUrl)
175
- return {
176
- requiresOAuth: true,
177
- challenge,
178
- reason: "the 401 challenge names no resource_metadata document",
179
- };
180
- let metadataUrl;
181
- try {
182
- // the parameter is usually absolute, but is allowed to be relative
183
- metadataUrl = new URL(challenge.resourceMetadataUrl, url).toString();
184
- }
185
- catch {
186
- return { requiresOAuth: true, challenge, reason: "the resource_metadata url is malformed" };
187
- }
188
- try {
189
- const protectedResource = await fetchJson(metadataUrl, opts.signal);
190
- const servers = strList(protectedResource.authorization_servers);
191
- const issuer = servers?.[0];
192
- if (!issuer)
193
- return {
194
- requiresOAuth: true,
195
- challenge,
196
- reason: "the protected-resource metadata names no authorization server",
197
- };
198
- // Authorization-server metadata: try EVERY shape the specs define, in order.
199
- //
200
- // MEASURED against real servers, which is the only way to get this right:
201
- //
202
- // GitHub (issuer https://github.com/login/oauth) serves
203
- // https://github.com/.well-known/oauth-authorization-server/login/oauth 200
204
- // https://github.com/login/oauth/.well-known/oauth-authorization-server 404
205
- // Notion (issuer https://mcp.notion.com, no path) serves the root form.
206
- //
207
- // So RFC 8414 §3.1 is "insert the well-known segment BEFORE the issuer's path"
208
- // (`/.well-known/oauth-authorization-server` + path), and the ".../path/.well-known/…"
209
- // shape is the **OIDC Discovery 1.0** form, which GitHub uses for
210
- // `.well-known/openid-configuration`. An earlier version of this code tried only the
211
- // post-path form and hardcoded the conclusion that the pre-path form was wrong —
212
- // GitHub returned 404 and the whole discovery failed.
213
- //
214
- // Both are legitimate and different providers publish different ones, so the fix is
215
- // to TRY ALL of them rather than to pick a favourite.
216
- //
217
- // Built by string concatenation, NOT `new URL("/.well-known/…", issuer)`: a leading
218
- // slash replaces the path, which silently drops the issuer's segment.
219
- const issuerUrl = new URL(issuer);
220
- const basePath = issuerUrl.pathname.replace(/\/$/, "");
221
- const candidates = [
222
- // RFC 8414 §3.1 — well-known BEFORE the path (GitHub's shape)
223
- `${issuerUrl.origin}/.well-known/oauth-authorization-server${basePath}`,
224
- // OIDC Discovery 1.0 §4 — well-known AFTER the path
225
- `${issuerUrl.origin}${basePath}/.well-known/openid-configuration`,
226
- // the same two for the OAuth metadata name, for providers that publish both
227
- `${issuerUrl.origin}${basePath}/.well-known/oauth-authorization-server`,
228
- // no path at all: the common case for a bare issuer
229
- `${issuerUrl.origin}/.well-known/oauth-authorization-server`,
230
- ];
231
- let meta = null;
232
- let lastErr = "";
233
- for (const candidate of [...new Set(candidates)]) {
234
- try {
235
- const m = await fetchJson(candidate, opts.signal);
236
- // accept only a document that actually describes an authorization server
237
- if (str(m.authorization_endpoint) && str(m.token_endpoint)) {
238
- meta = m;
239
- break;
240
- }
241
- lastErr = `${candidate} has no authorization_endpoint/token_endpoint`;
242
- }
243
- catch (e) {
244
- lastErr = e.message;
245
- }
246
- }
247
- if (!meta) {
248
- return {
249
- requiresOAuth: true,
250
- challenge,
251
- reason: `could not resolve authorization-server metadata for ${issuer}: ${lastErr}`,
252
- };
253
- }
254
- // `meta` is guaranteed to carry both endpoints by the loop above.
255
- const authorizationEndpoint = meta.authorization_endpoint;
256
- const tokenEndpoint = meta.token_endpoint;
257
- return {
258
- requiresOAuth: true,
259
- challenge,
260
- authServer: {
261
- authorizationEndpoint,
262
- tokenEndpoint,
263
- ...(str(meta.registration_endpoint)
264
- ? { registrationEndpoint: meta.registration_endpoint }
265
- : {}),
266
- // the RESOURCE's scopes win: they describe what this MCP server accepts
267
- scopes: strList(protectedResource.scopes_supported) ?? strList(meta.scopes_supported) ?? [],
268
- resource,
269
- ...(str(meta.issuer) ? { issuer: meta.issuer } : {}),
270
- },
271
- };
272
- }
273
- catch (err) {
274
- return { requiresOAuth: true, challenge, reason: err.message };
275
- }
276
- }
277
- /** POST an `application/x-www-form-urlencoded` body; returns the JSON response */
278
- async function postForm(url, body, signal) {
279
- const ac = new AbortController();
280
- const timer = setTimeout(() => ac.abort(), PROBE_TIMEOUT_MS);
281
- const onAbort = () => ac.abort();
282
- signal?.addEventListener("abort", onAbort, { once: true });
283
- try {
284
- const res = await fetch(url, {
285
- method: "POST",
286
- headers: { "content-type": "application/x-www-form-urlencoded", accept: "application/json" },
287
- body: new URLSearchParams(body).toString(),
288
- signal: ac.signal,
289
- });
290
- const text = await res.text();
291
- let json = {};
292
- try {
293
- json = text ? JSON.parse(text) : {};
294
- }
295
- catch {
296
- /* an HTML error page — reported with the status below */
297
- }
298
- if (!res.ok) {
299
- const detail = str(json.error_description) ?? str(json.error) ?? text.slice(0, 200);
300
- throw new Error(`${url} returned HTTP ${res.status}: ${detail || "(no body)"}`);
301
- }
302
- return json;
303
- }
304
- finally {
305
- clearTimeout(timer);
306
- signal?.removeEventListener("abort", onAbort);
307
- }
308
- }
309
- const toExpiry = (v) => {
310
- const n = typeof v === "number" ? v : typeof v === "string" ? Number(v) : NaN;
311
- return Number.isFinite(n) && n > 0 ? Date.now() + n * 1000 : null;
312
- };
313
- const tokensFrom = (payload, keepRefresh) => {
314
- const accessToken = str(payload.access_token);
315
- if (!accessToken)
316
- throw new Error("the token endpoint returned no access_token");
317
- const out = {
318
- accessToken,
319
- tokenType: str(payload.token_type) ?? "Bearer",
320
- expiresAt: toExpiry(payload.expires_in),
321
- };
322
- const rt = str(payload.refresh_token) ?? keepRefresh;
323
- if (rt)
324
- out.refreshToken = rt;
325
- if (str(payload.scope))
326
- out.scope = payload.scope;
327
- return out;
328
- };
329
- /**
330
- * Dynamic client registration (RFC 7591).
331
- *
332
- * Required by the MCP spec for servers that hand out no static client id. Sent as a
333
- * public client (`token_endpoint_auth_method: "none"`) because a local harness cannot
334
- * keep a client secret meaningful — the code runs on the operator's own machine.
335
- */
336
- export async function registerClient(registrationEndpoint, redirectUri, signal) {
337
- const ac = new AbortController();
338
- const timer = setTimeout(() => ac.abort(), PROBE_TIMEOUT_MS);
339
- const onAbort = () => ac.abort();
340
- signal?.addEventListener("abort", onAbort, { once: true });
341
- try {
342
- const res = await fetch(registrationEndpoint, {
343
- method: "POST",
344
- headers: { "content-type": "application/json", accept: "application/json" },
345
- body: JSON.stringify({
346
- client_name: "teapot",
347
- redirect_uris: [redirectUri],
348
- grant_types: ["authorization_code", "refresh_token"],
349
- response_types: ["code"],
350
- token_endpoint_auth_method: "none",
351
- }),
352
- signal: ac.signal,
353
- });
354
- const text = await res.text();
355
- if (!res.ok)
356
- throw new Error(`dynamic client registration failed (HTTP ${res.status}): ${text.slice(0, 200)}`);
357
- const json = JSON.parse(text);
358
- const clientId = str(json.client_id);
359
- if (!clientId)
360
- throw new Error("dynamic client registration returned no client_id");
361
- return { clientId, ...(str(json.client_secret) ? { clientSecret: json.client_secret } : {}) };
362
- }
363
- finally {
364
- clearTimeout(timer);
365
- signal?.removeEventListener("abort", onAbort);
366
- }
367
- }
368
- /** build the URL the operator is sent to */
369
- export function buildAuthorizeUrl(input) {
370
- const url = new URL(input.authServer.authorizationEndpoint);
371
- url.searchParams.set("response_type", "code");
372
- url.searchParams.set("client_id", input.clientId);
373
- url.searchParams.set("redirect_uri", input.redirectUri);
374
- url.searchParams.set("code_challenge", input.codeChallenge);
375
- // S256 only: MCP requires PKCE and forbids `plain`
376
- url.searchParams.set("code_challenge_method", "S256");
377
- url.searchParams.set("state", input.state);
378
- const scopes = input.scopes?.length ? input.scopes : input.authServer.scopes;
379
- if (scopes.length)
380
- url.searchParams.set("scope", scopes.join(" "));
381
- // RFC 8707: bind the grant to THIS resource, so a token minted for another server
382
- // cannot be replayed here
383
- if (input.authServer.resource)
384
- url.searchParams.set("resource", input.authServer.resource);
385
- return url.toString();
386
- }
387
- /** exchange an authorization code for tokens */
388
- export async function exchangeCode(input) {
389
- const body = {
390
- grant_type: "authorization_code",
391
- code: input.code,
392
- code_verifier: input.codeVerifier,
393
- redirect_uri: input.redirectUri,
394
- client_id: input.clientId,
395
- };
396
- if (input.clientSecret)
397
- body.client_secret = input.clientSecret;
398
- if (input.authServer.resource)
399
- body.resource = input.authServer.resource;
400
- const payload = await postForm(input.authServer.tokenEndpoint, body, input.signal);
401
- return tokensFrom(payload);
402
- }
403
- /**
404
- * Refresh an access token.
405
- *
406
- * The previously granted SCOPES are re-requested: a refresh that silently drops them
407
- * can return 200 with a token the resource server then refuses, which looks like an
408
- * authentication failure at the wrong end of the chain. A ROTATED refresh token is
409
- * returned in the result so the caller can persist it immediately — a server that
410
- * rotates invalidates the old one, so a discarded rotation breaks the next refresh.
411
- */
412
- export async function refreshTokens(input) {
413
- const body = {
414
- grant_type: "refresh_token",
415
- refresh_token: input.refreshToken,
416
- client_id: input.clientId,
417
- };
418
- if (input.clientSecret)
419
- body.client_secret = input.clientSecret;
420
- const scopes = input.scopes?.length ? input.scopes : input.authServer.scopes;
421
- if (scopes.length)
422
- body.scope = scopes.join(" ");
423
- if (input.authServer.resource)
424
- body.resource = input.authServer.resource;
425
- const payload = await postForm(input.authServer.tokenEndpoint, body, input.signal);
426
- // keepRefresh: a server that does not rotate omits refresh_token, and dropping it
427
- // would end the grant after one refresh
428
- return tokensFrom(payload, input.refreshToken);
429
- }