teapot-coding-agent 0.29.31 → 0.29.33
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/dist/agent/mcp-oauth-manager.js +342 -0
- package/dist/agent/mcp-oauth.js +429 -0
- package/dist/agent/mcp-registry.js +45 -2
- package/dist/agent/mcp.js +20 -0
- package/dist/server/api.js +83 -0
- package/package.json +1 -1
- package/public/assets/{index-BYYMQSQw.js → index-C6gqo0nb.js} +13 -13
- package/public/assets/index-C6gqo0nb.js.map +1 -0
- package/public/assets/index-CUgmNS8b.css +1 -0
- package/public/assets/{shiki-BHXNwDA0.js → shiki-CQ_TLTlI.js} +2 -2
- package/public/assets/{shiki-BHXNwDA0.js.map → shiki-CQ_TLTlI.js.map} +1 -1
- package/public/index.html +2 -2
- package/public/assets/index-BYYMQSQw.js.map +0 -1
- package/public/assets/index-CCnsAOJa.css +0 -1
|
@@ -0,0 +1,429 @@
|
|
|
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
|
+
}
|
|
@@ -15,6 +15,7 @@
|
|
|
15
15
|
* original name is what gets sent to the server.
|
|
16
16
|
*/
|
|
17
17
|
import { connectMcp, McpError } from "./mcp.js";
|
|
18
|
+
import { oauth } from "./mcp-oauth-manager.js";
|
|
18
19
|
/** the prefix a model-visible MCP tool name carries */
|
|
19
20
|
export const MCP_PREFIX = "mcp__";
|
|
20
21
|
/** `mcp__server__tool` — the flat name handed to the LLM */
|
|
@@ -75,7 +76,19 @@ export class McpRegistry {
|
|
|
75
76
|
states() {
|
|
76
77
|
return [...this.servers.values()];
|
|
77
78
|
}
|
|
78
|
-
/**
|
|
79
|
+
/** the OAuth state for one server, for the settings panel */
|
|
80
|
+
oauthStatus(name) {
|
|
81
|
+
return oauth.status(name);
|
|
82
|
+
}
|
|
83
|
+
/**
|
|
84
|
+
* Connect one server (idempotent) and discover its tools.
|
|
85
|
+
*
|
|
86
|
+
* A 401 is not the end of the story: an OAuth-protected server answers with a Bearer
|
|
87
|
+
* challenge, so on auth failure we DETECT and RECORD that, which is what lets the
|
|
88
|
+
* settings panel offer "authorize" instead of showing a bare "error". Detection is
|
|
89
|
+
* tried BEFORE the challenge reaches the operator — the reference implementations do
|
|
90
|
+
* the same, and it turns "it just says 401" into "click authorize".
|
|
91
|
+
*/
|
|
79
92
|
async connect(name) {
|
|
80
93
|
const st = this.servers.get(name);
|
|
81
94
|
if (!st)
|
|
@@ -88,8 +101,15 @@ export class McpRegistry {
|
|
|
88
101
|
return st;
|
|
89
102
|
st.status = "connecting";
|
|
90
103
|
st.lastError = undefined;
|
|
104
|
+
// Attach the OAuth authorization when a grant exists, resolved PER REQUEST so a
|
|
105
|
+
// refreshed token takes effect without reconnecting.
|
|
106
|
+
const withOAuth = {
|
|
107
|
+
...st.config,
|
|
108
|
+
oauthAuthorization: () => oauth.authorization(name),
|
|
109
|
+
onUnauthorized: () => oauth.invalidate(name),
|
|
110
|
+
};
|
|
91
111
|
try {
|
|
92
|
-
const conn = await connectMcp(
|
|
112
|
+
const conn = await connectMcp(withOAuth);
|
|
93
113
|
const tools = await conn.tools();
|
|
94
114
|
st.connection = conn;
|
|
95
115
|
st.tools = tools;
|
|
@@ -103,6 +123,29 @@ export class McpRegistry {
|
|
|
103
123
|
st.lastChecked = Date.now();
|
|
104
124
|
st.connection = undefined;
|
|
105
125
|
st.tools = [];
|
|
126
|
+
// A 401 means "find out what auth this wants" — the challenge names it. Only for
|
|
127
|
+
// HTTP transports: a stdio server has no OAuth to discover.
|
|
128
|
+
if (err instanceof McpError && err.authRequired && st.config.url) {
|
|
129
|
+
try {
|
|
130
|
+
const d = await oauth.detect(name, st.config.url, {
|
|
131
|
+
...(st.config.headers ? { headers: st.config.headers } : {}),
|
|
132
|
+
});
|
|
133
|
+
if (d.requiresOAuth) {
|
|
134
|
+
st.oauthRequired = true;
|
|
135
|
+
st.lastError =
|
|
136
|
+
`this server requires OAuth` +
|
|
137
|
+
(d.authServer
|
|
138
|
+
? ` (authorization server: ${new URL(d.authServer.authorizationEndpoint).host})`
|
|
139
|
+
: d.reason
|
|
140
|
+
? ` — ${d.reason}`
|
|
141
|
+
: "") +
|
|
142
|
+
" — use “authorize” in ⚙ settings → MCP servers";
|
|
143
|
+
}
|
|
144
|
+
}
|
|
145
|
+
catch {
|
|
146
|
+
/* detection is best-effort: the original error stands */
|
|
147
|
+
}
|
|
148
|
+
}
|
|
106
149
|
throw err;
|
|
107
150
|
}
|
|
108
151
|
}
|
package/dist/agent/mcp.js
CHANGED
|
@@ -167,6 +167,22 @@ async function connectHttp(cfg) {
|
|
|
167
167
|
accept: "application/json, text/event-stream",
|
|
168
168
|
...(cfg.headers ?? {}),
|
|
169
169
|
};
|
|
170
|
+
// OAuth wins over a static authorization header: it is the more specific grant, and
|
|
171
|
+
// resolving it per request is what lets a refresh take effect mid-session.
|
|
172
|
+
if (cfg.oauthAuthorization) {
|
|
173
|
+
const auth = await cfg.oauthAuthorization().catch(() => null);
|
|
174
|
+
if (auth) {
|
|
175
|
+
// Remove any spelling of the header the CONFIG supplied first. Keys are
|
|
176
|
+
// case-insensitive on the wire but not in a JS object, so leaving
|
|
177
|
+
// `Authorization` beside `authorization` would send BOTH and let the server
|
|
178
|
+
// pick — the exact ambiguity this precedence rule exists to remove.
|
|
179
|
+
for (const k of Object.keys(headers)) {
|
|
180
|
+
if (k.toLowerCase() === "authorization")
|
|
181
|
+
delete headers[k];
|
|
182
|
+
}
|
|
183
|
+
headers.authorization = auth;
|
|
184
|
+
}
|
|
185
|
+
}
|
|
170
186
|
if (sessionId)
|
|
171
187
|
headers["mcp-session-id"] = sessionId;
|
|
172
188
|
if (version)
|
|
@@ -197,6 +213,10 @@ async function connectHttp(cfg) {
|
|
|
197
213
|
const body = (await res.text().catch(() => "")).slice(0, 300);
|
|
198
214
|
if (res.status === 405)
|
|
199
215
|
throw new McpError(`MCP endpoint answered 405 — it does not accept POST (Streamable HTTP): ${body || "(no body)"}`);
|
|
216
|
+
// Tell the caller so it can drop a cached token: a 401 here means the access
|
|
217
|
+
// token was rejected, and retrying with the same one would loop.
|
|
218
|
+
if (res.status === 401 || res.status === 403)
|
|
219
|
+
cfg.onUnauthorized?.();
|
|
200
220
|
throw new McpError(`MCP server returned HTTP ${res.status}: ${body || "(no body)"}`, res.status === 401 || res.status === 403);
|
|
201
221
|
}
|
|
202
222
|
if (notification) {
|
package/dist/server/api.js
CHANGED
|
@@ -55,6 +55,7 @@ import { bus } from "../bus.js";
|
|
|
55
55
|
import { readEvents, readEventsTail, filterByBranch } from "../log/events.js";
|
|
56
56
|
import { mcp } from "../agent/mcp-registry.js";
|
|
57
57
|
import { connectMcp } from "../agent/mcp.js";
|
|
58
|
+
import { oauth } from "../agent/mcp-oauth-manager.js";
|
|
58
59
|
/** media categories the file tree can preview inline */
|
|
59
60
|
const IMAGE_EXT = new Set(["png", "jpg", "jpeg", "gif", "webp", "svg", "bmp", "ico", "avif"]);
|
|
60
61
|
const VIDEO_EXT = new Set(["mp4", "webm", "mov", "mkv", "avi", "m4v"]);
|
|
@@ -876,6 +877,88 @@ export function buildApp(master) {
|
|
|
876
877
|
warnings: p.warnings,
|
|
877
878
|
})),
|
|
878
879
|
}));
|
|
880
|
+
/**
|
|
881
|
+
* Start an OAuth flow for one server.
|
|
882
|
+
*
|
|
883
|
+
* Responds with the URL to open IMMEDIATELY; the exchange finishes when the browser
|
|
884
|
+
* comes back to the loopback listener. That split is what lets the panel show a
|
|
885
|
+
* clickable link instead of hanging the request for minutes.
|
|
886
|
+
*/
|
|
887
|
+
app.post("/api/mcp/oauth/start", async (c) => {
|
|
888
|
+
const body = await c.req
|
|
889
|
+
.json()
|
|
890
|
+
.catch(() => null);
|
|
891
|
+
if (!body?.name)
|
|
892
|
+
return c.json({ error: "missing name" }, 400);
|
|
893
|
+
const saved = (master.config.mcpServers ?? []).find((m) => m.name === body.name);
|
|
894
|
+
const url = body.url ?? saved?.url;
|
|
895
|
+
if (!url)
|
|
896
|
+
return c.json({ error: "this server has no url — OAuth needs an http(s) endpoint" }, 400);
|
|
897
|
+
// Kick the flow off; it settles when the redirect arrives. The promise is NOT
|
|
898
|
+
// awaited here — awaiting it would hold this request open until the operator
|
|
899
|
+
// finishes in the browser.
|
|
900
|
+
const flow = oauth.authorize(body.name, url, {
|
|
901
|
+
...(body.scopes?.length ? { scopes: body.scopes } : {}),
|
|
902
|
+
...(body.clientId ? { clientId: body.clientId } : {}),
|
|
903
|
+
...(body.clientSecret ? { clientSecret: body.clientSecret } : {}),
|
|
904
|
+
});
|
|
905
|
+
flow.catch(() => {
|
|
906
|
+
/* recorded in oauth.status(...).flow; nobody is listening here */
|
|
907
|
+
});
|
|
908
|
+
// Wait only long enough for the flow to produce its URL (discovery + registration
|
|
909
|
+
// are network round-trips, but short ones).
|
|
910
|
+
const deadline = Date.now() + 20_000;
|
|
911
|
+
let url_;
|
|
912
|
+
while (Date.now() < deadline) {
|
|
913
|
+
const st = oauth.status(body.name);
|
|
914
|
+
if (st.flow.phase === "authorizing") {
|
|
915
|
+
url_ = st.flow.url;
|
|
916
|
+
break;
|
|
917
|
+
}
|
|
918
|
+
if (st.flow.phase === "error")
|
|
919
|
+
break;
|
|
920
|
+
await new Promise((r) => setTimeout(r, 50));
|
|
921
|
+
}
|
|
922
|
+
const st = oauth.status(body.name);
|
|
923
|
+
if (!url_)
|
|
924
|
+
return c.json({
|
|
925
|
+
ok: false,
|
|
926
|
+
error: st.flow.phase === "error"
|
|
927
|
+
? st.flow.message
|
|
928
|
+
: "the authorization server did not produce a URL in time",
|
|
929
|
+
}, 200);
|
|
930
|
+
return c.json({ ok: true, url: url_, redirectUri: "http://127.0.0.1/<port>/callback" });
|
|
931
|
+
});
|
|
932
|
+
app.get("/api/mcp/oauth/status", async (c) => {
|
|
933
|
+
const name = c.req.query("name");
|
|
934
|
+
if (!name)
|
|
935
|
+
return c.json({ error: "missing name" }, 400);
|
|
936
|
+
const detect = c.req.query("detect") === "1";
|
|
937
|
+
// `detect=1` probes the endpoint for a Bearer challenge. That is the ONLY way the
|
|
938
|
+
// panel can learn "this needs a grant" before the operator has guessed it, and it
|
|
939
|
+
// is opt-in because the probe is a real request to the server.
|
|
940
|
+
if (detect && !oauth.status(name).required) {
|
|
941
|
+
const saved = (master.config.mcpServers ?? []).find((m) => m.name === name);
|
|
942
|
+
if (saved?.url) {
|
|
943
|
+
try {
|
|
944
|
+
await oauth.detect(name, saved.url, {
|
|
945
|
+
...(saved.headers ? { headers: saved.headers } : {}),
|
|
946
|
+
});
|
|
947
|
+
}
|
|
948
|
+
catch {
|
|
949
|
+
/* best-effort: the status is still returned */
|
|
950
|
+
}
|
|
951
|
+
}
|
|
952
|
+
}
|
|
953
|
+
return c.json(oauth.status(name));
|
|
954
|
+
});
|
|
955
|
+
app.post("/api/mcp/oauth/disconnect", async (c) => {
|
|
956
|
+
const body = await c.req.json().catch(() => null);
|
|
957
|
+
if (!body?.name)
|
|
958
|
+
return c.json({ error: "missing name" }, 400);
|
|
959
|
+
await oauth.disconnect(body.name);
|
|
960
|
+
return c.json({ ok: true });
|
|
961
|
+
});
|
|
879
962
|
app.post("/api/mcp/test", async (c) => {
|
|
880
963
|
const body = await c.req.json().catch(() => null);
|
|
881
964
|
if (!body?.name)
|