teapot-coding-agent 0.29.31 → 0.29.32
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-CUHACAGL.js} +12 -12
- package/public/assets/index-CUHACAGL.js.map +1 -0
- package/public/assets/{shiki-BHXNwDA0.js → shiki-B8vfRZ8s.js} +2 -2
- package/public/assets/{shiki-BHXNwDA0.js.map → shiki-B8vfRZ8s.js.map} +1 -1
- package/public/index.html +1 -1
- package/public/assets/index-BYYMQSQw.js.map +0 -1
|
@@ -0,0 +1,342 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The OAuth flow for MCP servers (#67): start it, wait for the browser, keep the grant.
|
|
3
|
+
*
|
|
4
|
+
* Teapot is a LOCAL server with a browser UI, so the redirect can be a real loopback
|
|
5
|
+
* callback: a tiny HTTP listener on 127.0.0.1 receives `?code=…&state=…`, the page
|
|
6
|
+
* closes itself, and the tools appear without the operator copying anything. The
|
|
7
|
+
* reference implementations (easywebui, deepseek-pp) run serverless and therefore need
|
|
8
|
+
* a host-provided browser identity; this is the simpler shape that a real local port
|
|
9
|
+
* allows.
|
|
10
|
+
*
|
|
11
|
+
* What lives where:
|
|
12
|
+
* - **access token**: MEMORY ONLY, bound to a fingerprint of the credentials. A
|
|
13
|
+
* changed client id can therefore never reuse a stale token, and it never reaches
|
|
14
|
+
* `config.json`.
|
|
15
|
+
* - **refresh token**: PERSISTED, because it is the durable grant. A rotated one is
|
|
16
|
+
* written back immediately — a server that rotates invalidates the previous token,
|
|
17
|
+
* and reusing it fails with `invalid_grant` on the next refresh.
|
|
18
|
+
*
|
|
19
|
+
* The state parameter is a random value, checked on the callback: without it any page
|
|
20
|
+
* could deliver a code to the loopback listener.
|
|
21
|
+
*/
|
|
22
|
+
import { createServer } from "node:http";
|
|
23
|
+
import { createHash, randomBytes } from "node:crypto";
|
|
24
|
+
import { mkdir, readFile, writeFile } from "node:fs/promises";
|
|
25
|
+
import path from "node:path";
|
|
26
|
+
import { buildAuthorizeUrl, detectOAuth, exchangeCode, parseBearerChallenge, pkcePair, refreshTokens, registerClient, } from "./mcp-oauth.js";
|
|
27
|
+
/** how long a started flow waits for the browser before giving up */
|
|
28
|
+
const FLOW_TIMEOUT_MS = 5 * 60_000;
|
|
29
|
+
/** refresh this long before expiry, so a token cannot expire mid-call */
|
|
30
|
+
const REFRESH_SKEW_MS = 60_000;
|
|
31
|
+
const fingerprintOf = (grant) => createHash("sha256")
|
|
32
|
+
.update(`${grant.tokenEndpoint}\u0000${grant.clientId}\u0000${grant.clientSecret ?? ""}`)
|
|
33
|
+
.digest("hex")
|
|
34
|
+
.slice(0, 32);
|
|
35
|
+
/**
|
|
36
|
+
* Listen on a free loopback port and resolve with the redirect URI plus the one-shot
|
|
37
|
+
* handler that finishes the flow.
|
|
38
|
+
*
|
|
39
|
+
* Binding 127.0.0.1 (not 0.0.0.0) matters: this listener accepts an authorization code
|
|
40
|
+
* and must not be reachable from the network.
|
|
41
|
+
*/
|
|
42
|
+
async function listenLoopback() {
|
|
43
|
+
return await new Promise((resolve, reject) => {
|
|
44
|
+
const server = createServer();
|
|
45
|
+
let deliver = null;
|
|
46
|
+
let fail = null;
|
|
47
|
+
const result = new Promise((res, rej) => {
|
|
48
|
+
deliver = res;
|
|
49
|
+
fail = rej;
|
|
50
|
+
});
|
|
51
|
+
let sawFirst = false;
|
|
52
|
+
server.on("request", (req, res) => {
|
|
53
|
+
const url = new URL(req.url ?? "/", "http://127.0.0.1");
|
|
54
|
+
const code = url.searchParams.get("code");
|
|
55
|
+
const state = url.searchParams.get("state");
|
|
56
|
+
const error = url.searchParams.get("error");
|
|
57
|
+
if (error) {
|
|
58
|
+
const desc = url.searchParams.get("error_description") ?? error;
|
|
59
|
+
res.writeHead(400, { "content-type": "text/html; charset=utf-8" }).end(page("authorization failed", desc));
|
|
60
|
+
fail?.(new Error(`authorization was refused: ${desc}`));
|
|
61
|
+
return;
|
|
62
|
+
}
|
|
63
|
+
if (!code) {
|
|
64
|
+
// a favicon or a stray probe: keep listening rather than failing the flow
|
|
65
|
+
res.writeHead(404, { "content-type": "text/plain" }).end("not the oauth callback");
|
|
66
|
+
return;
|
|
67
|
+
}
|
|
68
|
+
if (sawFirst) {
|
|
69
|
+
res.writeHead(409, { "content-type": "text/plain" }).end("already received");
|
|
70
|
+
return;
|
|
71
|
+
}
|
|
72
|
+
sawFirst = true;
|
|
73
|
+
res.writeHead(200, { "content-type": "text/html; charset=utf-8" }).end(page("authorized", "you can close this tab"));
|
|
74
|
+
deliver?.({ code, state: state ?? "" });
|
|
75
|
+
});
|
|
76
|
+
server.on("error", reject);
|
|
77
|
+
server.listen(0, "127.0.0.1", () => {
|
|
78
|
+
const addr = server.address();
|
|
79
|
+
if (!addr || typeof addr === "string") {
|
|
80
|
+
reject(new Error("could not determine the loopback port"));
|
|
81
|
+
return;
|
|
82
|
+
}
|
|
83
|
+
resolve({
|
|
84
|
+
redirectUri: `http://127.0.0.1:${addr.port}/callback`,
|
|
85
|
+
wait: (timeoutMs) => new Promise((res, rej) => {
|
|
86
|
+
const timer = setTimeout(() => rej(new Error("the authorization page was not completed in time")), timeoutMs);
|
|
87
|
+
result.then((v) => {
|
|
88
|
+
clearTimeout(timer);
|
|
89
|
+
res(v);
|
|
90
|
+
}, (e) => {
|
|
91
|
+
clearTimeout(timer);
|
|
92
|
+
rej(e);
|
|
93
|
+
});
|
|
94
|
+
}),
|
|
95
|
+
close: () => new Promise((r) => server.close(() => r())),
|
|
96
|
+
});
|
|
97
|
+
});
|
|
98
|
+
});
|
|
99
|
+
}
|
|
100
|
+
/** the page the operator sees in the callback tab */
|
|
101
|
+
function page(title, body) {
|
|
102
|
+
return `<!doctype html><meta charset="utf-8"><title>${title}</title>
|
|
103
|
+
<style>body{font:15px system-ui;margin:12vh auto;max-width:34rem;text-align:center;color:#222}
|
|
104
|
+
h1{font-size:1.1rem}</style>
|
|
105
|
+
<h1>${title}</h1><p>${body}</p>
|
|
106
|
+
<script>setTimeout(()=>window.close(),1200)</script>`;
|
|
107
|
+
}
|
|
108
|
+
export class McpOAuthManager {
|
|
109
|
+
grants = new Map();
|
|
110
|
+
tokens = new Map();
|
|
111
|
+
flows = new Map();
|
|
112
|
+
discovered = new Map();
|
|
113
|
+
/** servers known to demand OAuth, so the UI can offer "authorize" */
|
|
114
|
+
required = new Set();
|
|
115
|
+
storePath;
|
|
116
|
+
constructor(storeDir) {
|
|
117
|
+
this.storePath = path.join(storeDir, "mcp-oauth.json");
|
|
118
|
+
}
|
|
119
|
+
/** read persisted grants; a missing or corrupt file is simply no grants */
|
|
120
|
+
async load() {
|
|
121
|
+
try {
|
|
122
|
+
const raw = JSON.parse(await readFile(this.storePath, "utf8"));
|
|
123
|
+
for (const [server, g] of Object.entries(raw)) {
|
|
124
|
+
if (g && typeof g.clientId === "string" && typeof g.tokenEndpoint === "string")
|
|
125
|
+
this.grants.set(server, g);
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
catch {
|
|
129
|
+
/* first run, or an unreadable store — both mean "no grants" */
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
async save() {
|
|
133
|
+
const out = {};
|
|
134
|
+
for (const [k, v] of this.grants)
|
|
135
|
+
out[k] = v;
|
|
136
|
+
try {
|
|
137
|
+
await mkdir(path.dirname(this.storePath), { recursive: true });
|
|
138
|
+
// 0600: a refresh token is a credential
|
|
139
|
+
await writeFile(this.storePath, JSON.stringify(out, null, 2), { mode: 0o600 });
|
|
140
|
+
}
|
|
141
|
+
catch {
|
|
142
|
+
/* a failed write must not break a live session */
|
|
143
|
+
}
|
|
144
|
+
}
|
|
145
|
+
/** forget a grant entirely (disconnect) */
|
|
146
|
+
async disconnect(server) {
|
|
147
|
+
this.grants.delete(server);
|
|
148
|
+
this.tokens.delete(server);
|
|
149
|
+
this.flows.delete(server);
|
|
150
|
+
await this.save();
|
|
151
|
+
}
|
|
152
|
+
status(server) {
|
|
153
|
+
const grant = this.grants.get(server);
|
|
154
|
+
const tok = this.tokens.get(server);
|
|
155
|
+
const fresh = Boolean(tok && (tok.expiresAt === null || Date.now() < tok.expiresAt - REFRESH_SKEW_MS));
|
|
156
|
+
return {
|
|
157
|
+
required: this.required.has(server) || Boolean(grant),
|
|
158
|
+
authorized: fresh,
|
|
159
|
+
expiresAt: tok?.expiresAt ?? null,
|
|
160
|
+
hasRefreshToken: Boolean(grant?.refreshToken),
|
|
161
|
+
scopes: grant?.scopes ?? [],
|
|
162
|
+
...(this.discovered.has(server) ? { authServer: this.discovered.get(server) } : {}),
|
|
163
|
+
flow: this.flows.get(server) ?? { phase: "idle" },
|
|
164
|
+
};
|
|
165
|
+
}
|
|
166
|
+
/** mark a server as needing OAuth after a 401 challenge */
|
|
167
|
+
noteRequired(server) {
|
|
168
|
+
this.required.add(server);
|
|
169
|
+
}
|
|
170
|
+
/**
|
|
171
|
+
* Probe an endpoint and remember whether it demands OAuth.
|
|
172
|
+
*
|
|
173
|
+
* Called when a connection fails with 401, and from the settings panel's `test`, so
|
|
174
|
+
* the operator never has to know the difference between "wrong header" and "this
|
|
175
|
+
* needs a real grant" — the 401 challenge tells us.
|
|
176
|
+
*/
|
|
177
|
+
async detect(server, endpoint, opts = {}) {
|
|
178
|
+
const d = await detectOAuth(endpoint, {
|
|
179
|
+
...(opts.headers ? { headers: opts.headers } : {}),
|
|
180
|
+
...(opts.resource ? { resource: opts.resource } : {}),
|
|
181
|
+
});
|
|
182
|
+
if (d.requiresOAuth)
|
|
183
|
+
this.required.add(server);
|
|
184
|
+
if (d.authServer)
|
|
185
|
+
this.discovered.set(server, d.authServer);
|
|
186
|
+
return {
|
|
187
|
+
requiresOAuth: d.requiresOAuth,
|
|
188
|
+
...(d.reason ? { reason: d.reason } : {}),
|
|
189
|
+
...(d.authServer ? { authServer: d.authServer } : {}),
|
|
190
|
+
...(d.challenge ? { challenge: d.challenge.raw } : {}),
|
|
191
|
+
};
|
|
192
|
+
}
|
|
193
|
+
/**
|
|
194
|
+
* Run the whole flow: discover (if needed), register, authorize, exchange, store.
|
|
195
|
+
*
|
|
196
|
+
* Resolves once the redirect has been received — the caller starts the flow, hands
|
|
197
|
+
* the URL to the UI, and this promise settles when the browser comes back.
|
|
198
|
+
*/
|
|
199
|
+
async authorize(server, endpoint, opts = {}) {
|
|
200
|
+
this.flows.set(server, { phase: "idle" });
|
|
201
|
+
let loop = null;
|
|
202
|
+
try {
|
|
203
|
+
// an auth server is required; discover it when the operator has not saved one
|
|
204
|
+
let authServer = this.discovered.get(server);
|
|
205
|
+
if (!authServer) {
|
|
206
|
+
const d = await this.detect(server, endpoint, {
|
|
207
|
+
...(opts.resource ? { resource: opts.resource } : {}),
|
|
208
|
+
});
|
|
209
|
+
if (!d.requiresOAuth)
|
|
210
|
+
throw new Error("this server did not request OAuth (no 401 Bearer challenge)");
|
|
211
|
+
authServer = d.authServer;
|
|
212
|
+
if (!authServer)
|
|
213
|
+
throw new Error(d.reason ??
|
|
214
|
+
"this server requires OAuth but did not publish authorization-server metadata; " +
|
|
215
|
+
"save its authorization/token endpoints by hand");
|
|
216
|
+
}
|
|
217
|
+
loop = await listenLoopback();
|
|
218
|
+
const redirectUri = loop.redirectUri;
|
|
219
|
+
// client id: given, persisted, or dynamically registered (RFC 7591)
|
|
220
|
+
const prev = this.grants.get(server);
|
|
221
|
+
let clientId = opts.clientId ?? prev?.clientId;
|
|
222
|
+
let clientSecret = opts.clientSecret ?? prev?.clientSecret;
|
|
223
|
+
if (!clientId) {
|
|
224
|
+
if (!authServer.registrationEndpoint)
|
|
225
|
+
throw new Error("this server does not support dynamic client registration, so a client id must be entered by hand");
|
|
226
|
+
const reg = await registerClient(authServer.registrationEndpoint, redirectUri);
|
|
227
|
+
clientId = reg.clientId;
|
|
228
|
+
clientSecret = reg.clientSecret;
|
|
229
|
+
}
|
|
230
|
+
const { verifier, challenge } = pkcePair();
|
|
231
|
+
const state = randomBytes(16).toString("base64url");
|
|
232
|
+
const scopes = opts.scopes?.length ? opts.scopes : (prev?.scopes ?? authServer.scopes);
|
|
233
|
+
const url = buildAuthorizeUrl({
|
|
234
|
+
authServer,
|
|
235
|
+
clientId,
|
|
236
|
+
redirectUri,
|
|
237
|
+
codeChallenge: challenge,
|
|
238
|
+
state,
|
|
239
|
+
scopes,
|
|
240
|
+
});
|
|
241
|
+
this.flows.set(server, { phase: "authorizing", url, startedAt: Date.now() });
|
|
242
|
+
// wait for the browser WHILE the caller shows the url
|
|
243
|
+
const { code, state: got } = await loop.wait(FLOW_TIMEOUT_MS);
|
|
244
|
+
if (got !== state)
|
|
245
|
+
throw new Error("the authorization callback carried the wrong state — refusing the code");
|
|
246
|
+
const tokens = await exchangeCode({
|
|
247
|
+
authServer,
|
|
248
|
+
clientId,
|
|
249
|
+
...(clientSecret ? { clientSecret } : {}),
|
|
250
|
+
code,
|
|
251
|
+
codeVerifier: verifier,
|
|
252
|
+
redirectUri,
|
|
253
|
+
});
|
|
254
|
+
const grant = {
|
|
255
|
+
tokenEndpoint: authServer.tokenEndpoint,
|
|
256
|
+
clientId,
|
|
257
|
+
...(clientSecret ? { clientSecret } : {}),
|
|
258
|
+
...(tokens.refreshToken ? { refreshToken: tokens.refreshToken } : {}),
|
|
259
|
+
scopes: tokens.scope ? tokens.scope.split(" ") : scopes,
|
|
260
|
+
...(authServer.resource ? { resource: authServer.resource } : {}),
|
|
261
|
+
obtainedAt: Date.now(),
|
|
262
|
+
};
|
|
263
|
+
this.grants.set(server, grant);
|
|
264
|
+
this.tokens.set(server, {
|
|
265
|
+
accessToken: tokens.accessToken,
|
|
266
|
+
tokenType: tokens.tokenType,
|
|
267
|
+
expiresAt: tokens.expiresAt,
|
|
268
|
+
fingerprint: fingerprintOf(grant),
|
|
269
|
+
});
|
|
270
|
+
this.flows.set(server, { phase: "done", ok: true });
|
|
271
|
+
await this.save();
|
|
272
|
+
return { ok: true };
|
|
273
|
+
}
|
|
274
|
+
catch (err) {
|
|
275
|
+
const message = err.message;
|
|
276
|
+
this.flows.set(server, { phase: "error", message });
|
|
277
|
+
throw err;
|
|
278
|
+
}
|
|
279
|
+
finally {
|
|
280
|
+
await loop?.close();
|
|
281
|
+
}
|
|
282
|
+
}
|
|
283
|
+
/**
|
|
284
|
+
* The `Authorization` value for this server, refreshing when needed.
|
|
285
|
+
*
|
|
286
|
+
* Returns null when the server has no grant (nothing to add). Throws when a refresh
|
|
287
|
+
* is needed but fails, so the caller can surface "re-authorize" instead of sending an
|
|
288
|
+
* unauthenticated request that will 401 anyway.
|
|
289
|
+
*/
|
|
290
|
+
async authorization(server) {
|
|
291
|
+
const grant = this.grants.get(server);
|
|
292
|
+
if (!grant)
|
|
293
|
+
return null;
|
|
294
|
+
const fp = fingerprintOf(grant);
|
|
295
|
+
const cached = this.tokens.get(server);
|
|
296
|
+
if (cached && cached.fingerprint === fp) {
|
|
297
|
+
if (cached.expiresAt === null || Date.now() < cached.expiresAt - REFRESH_SKEW_MS)
|
|
298
|
+
return `${cached.tokenType || "Bearer"} ${cached.accessToken}`;
|
|
299
|
+
}
|
|
300
|
+
if (!grant.refreshToken)
|
|
301
|
+
throw new Error("the MCP grant has expired and carries no refresh token — re-authorize");
|
|
302
|
+
const authServer = this.discovered.get(server);
|
|
303
|
+
if (!authServer)
|
|
304
|
+
throw new Error("the MCP authorization server is not resolved — re-authorize");
|
|
305
|
+
const tokens = await refreshTokens({
|
|
306
|
+
authServer,
|
|
307
|
+
clientId: grant.clientId,
|
|
308
|
+
...(grant.clientSecret ? { clientSecret: grant.clientSecret } : {}),
|
|
309
|
+
refreshToken: grant.refreshToken,
|
|
310
|
+
scopes: grant.scopes,
|
|
311
|
+
});
|
|
312
|
+
// PERSIST A ROTATED TOKEN IMMEDIATELY: a server that rotates invalidates the old
|
|
313
|
+
// one, so a discarded rotation breaks the NEXT refresh with `invalid_grant`.
|
|
314
|
+
if (tokens.refreshToken && tokens.refreshToken !== grant.refreshToken) {
|
|
315
|
+
grant.refreshToken = tokens.refreshToken;
|
|
316
|
+
await this.save();
|
|
317
|
+
}
|
|
318
|
+
this.tokens.set(server, {
|
|
319
|
+
accessToken: tokens.accessToken,
|
|
320
|
+
tokenType: tokens.tokenType,
|
|
321
|
+
expiresAt: tokens.expiresAt,
|
|
322
|
+
fingerprint: fp,
|
|
323
|
+
});
|
|
324
|
+
return `${tokens.tokenType || "Bearer"} ${tokens.accessToken}`;
|
|
325
|
+
}
|
|
326
|
+
/** drop the cached ACCESS token so the next call refreshes (after a 401) */
|
|
327
|
+
invalidate(server) {
|
|
328
|
+
this.tokens.delete(server);
|
|
329
|
+
}
|
|
330
|
+
}
|
|
331
|
+
/**
|
|
332
|
+
* Process-wide manager.
|
|
333
|
+
*
|
|
334
|
+
* Starts EMPTY and inert: until `initMcpOAuth()` points it at the data dir it has no
|
|
335
|
+
* grants, which is the safe default (no token is ever read from an assumed location).
|
|
336
|
+
*/
|
|
337
|
+
export let oauth = new McpOAuthManager(path.join(process.cwd(), ".teapot-oauth"));
|
|
338
|
+
export async function initMcpOAuth(dir) {
|
|
339
|
+
oauth = new McpOAuthManager(dir);
|
|
340
|
+
await oauth.load();
|
|
341
|
+
}
|
|
342
|
+
export { parseBearerChallenge };
|