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/dist/agent/agent.js +47 -0
- package/dist/agent/mcp-oauth-manager.js +197 -255
- package/dist/agent/mcp-registry.js +169 -65
- package/dist/agent/mcp.js +131 -591
- package/dist/master.js +34 -3
- package/dist/server/api.js +41 -61
- package/package.json +5 -3
- package/public/assets/{index-C6gqo0nb.js → index-CYUWPPHN.js} +7 -7
- package/public/assets/index-CYUWPPHN.js.map +1 -0
- package/public/assets/index-DWK26mKp.css +1 -0
- package/public/assets/{shiki-CQ_TLTlI.js → shiki-Dsqq25fY.js} +2 -2
- package/public/assets/{shiki-CQ_TLTlI.js.map → shiki-Dsqq25fY.js.map} +1 -1
- package/public/index.html +2 -2
- package/dist/agent/mcp-oauth.js +0 -429
- package/public/assets/index-C6gqo0nb.js.map +0 -1
- package/public/assets/index-CUgmNS8b.css +0 -1
package/dist/agent/agent.js
CHANGED
|
@@ -334,6 +334,43 @@ export class Agent {
|
|
|
334
334
|
*/
|
|
335
335
|
opts;
|
|
336
336
|
messages = [];
|
|
337
|
+
/**
|
|
338
|
+
* The conversation this agent holds, for INSPECTION.
|
|
339
|
+
*
|
|
340
|
+
* Tests need to assert what the agent will actually send (compaction, tool pairing,
|
|
341
|
+
* restoration), and reaching into a private field meant every assertion had to launder
|
|
342
|
+
* the type through `as unknown as { messages: … }` — thirty of them, each of which would
|
|
343
|
+
* keep compiling after the shape changed. A read-only view makes the intent explicit and
|
|
344
|
+
* lets the type checker do its job. There is no setter: mutation belongs to the class.
|
|
345
|
+
*/
|
|
346
|
+
get conversation() {
|
|
347
|
+
return this.messages;
|
|
348
|
+
}
|
|
349
|
+
/**
|
|
350
|
+
* The live array, for SEEDING a scenario in a test.
|
|
351
|
+
*
|
|
352
|
+
* Separate from `conversation` on purpose: reading and appending are different
|
|
353
|
+
* intents, and a test that plants 4000-character turns to reach a compaction threshold
|
|
354
|
+
* should look like what it is. Production code never calls this — history is appended
|
|
355
|
+
* by the turn loop.
|
|
356
|
+
*/
|
|
357
|
+
get conversationForTest() {
|
|
358
|
+
return this.messages;
|
|
359
|
+
}
|
|
360
|
+
/**
|
|
361
|
+
* The endpoint this agent resolved, for INSPECTION.
|
|
362
|
+
*
|
|
363
|
+
* Tests assert that a per-agent override, a provider preset and the default all land on
|
|
364
|
+
* the same baseUrl/key/model — reaching into `opts` to do it meant the assertions had to
|
|
365
|
+
* defeat `private` and would have kept compiling after the shape changed.
|
|
366
|
+
*/
|
|
367
|
+
get llmConfig() {
|
|
368
|
+
return this.opts.llm;
|
|
369
|
+
}
|
|
370
|
+
/** the provider this agent resolved, for inspection (which preset won, and why) */
|
|
371
|
+
get providerName() {
|
|
372
|
+
return this.opts.provider;
|
|
373
|
+
}
|
|
337
374
|
/**
|
|
338
375
|
* User prompts waiting for the next turn boundary. Deliberately NOT queued
|
|
339
376
|
* on runChain: that chain holds the long-running loop, so queueing behind
|
|
@@ -900,6 +937,12 @@ export class Agent {
|
|
|
900
937
|
* Everything that touches history (prompts, start, fork, UI selection)
|
|
901
938
|
* funnels through here; boot stays cheap no matter how many sessions exist.
|
|
902
939
|
*/
|
|
940
|
+
/**
|
|
941
|
+
* Resolve the session/workspace this agent operates on.
|
|
942
|
+
*
|
|
943
|
+
* Public because `load()` is a thin wrapper over it and a test that reproduces a
|
|
944
|
+
* restart needs the same step WITHOUT the reload side effects.
|
|
945
|
+
*/
|
|
903
946
|
ensureReady() {
|
|
904
947
|
if (!this.readyPromise) {
|
|
905
948
|
this.readyPromise = (async () => {
|
|
@@ -2746,6 +2789,10 @@ export class Agent {
|
|
|
2746
2789
|
* Scans the tail of `messages` for `tool_call_id`s, so it is correct whichever
|
|
2747
2790
|
* path left the batch unfinished — a stop, a throw, or a normal completion
|
|
2748
2791
|
* where a handler returned early. Answered calls are left alone.
|
|
2792
|
+
*
|
|
2793
|
+
* PUBLIC so a test can reproduce "the batch was left half-answered" directly. That
|
|
2794
|
+
* state is what the provider rejects the next request over, and reaching it through a
|
|
2795
|
+
* whole turn would make the assertion depend on everything else in the loop.
|
|
2749
2796
|
*/
|
|
2750
2797
|
async answerUnansweredToolCalls(m) {
|
|
2751
2798
|
const calls = m.tool_calls ?? [];
|
|
@@ -1,45 +1,178 @@
|
|
|
1
1
|
/**
|
|
2
|
-
*
|
|
2
|
+
* OAuth for MCP servers (#67), on the official client's `OAuthClientProvider`.
|
|
3
3
|
*
|
|
4
|
-
*
|
|
5
|
-
*
|
|
6
|
-
*
|
|
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.
|
|
4
|
+
* The hand-written discovery/PKCE/token-exchange layer is GONE. What remains is the part
|
|
5
|
+
* the SDK cannot own: **where the grant is stored**, and **how the operator completes the
|
|
6
|
+
* browser step**. The SDK calls this interface at each stage:
|
|
10
7
|
*
|
|
11
|
-
*
|
|
12
|
-
*
|
|
13
|
-
*
|
|
14
|
-
*
|
|
15
|
-
*
|
|
16
|
-
*
|
|
17
|
-
*
|
|
8
|
+
* clientMetadata() → who we are, for dynamic registration
|
|
9
|
+
* clientInformation() → the client id/secret obtained earlier, or undefined
|
|
10
|
+
* saveClientInformation() → persist what registration returned
|
|
11
|
+
* tokens() → the current grant, or undefined
|
|
12
|
+
* saveTokens() → persist a token PAIR
|
|
13
|
+
* redirectToAuthorization() → the URL to open in a browser
|
|
14
|
+
* saveCodeVerifier() → keep the PKCE verifier for the exchange
|
|
15
|
+
* codeVerifier() → hand it back afterwards
|
|
18
16
|
*
|
|
19
|
-
*
|
|
20
|
-
*
|
|
17
|
+
* Storage choices, unchanged from the previous implementation because they are the
|
|
18
|
+
* security-relevant part and were already right:
|
|
19
|
+
* - **access token: memory only.** It is short-lived and bound to a fingerprint of the
|
|
20
|
+
* client credentials, so a changed client id can never reuse a stale token.
|
|
21
|
+
* - **refresh token + client info: on disk at 0600**, beside the data dir, never in
|
|
22
|
+
* `config.json` (which operators copy around).
|
|
23
|
+
*
|
|
24
|
+
* The redirect is a real LOOPBACK listener: this is a local harness with a browser UI, so
|
|
25
|
+
* the tab can close itself. The reference implementations (easywebui, deepseek-pp) run
|
|
26
|
+
* serverless and need a host-provided browser identity instead.
|
|
21
27
|
*/
|
|
22
28
|
import { createServer } from "node:http";
|
|
23
|
-
import { createHash, randomBytes } from "node:crypto";
|
|
24
29
|
import { mkdir, readFile, writeFile } from "node:fs/promises";
|
|
25
30
|
import path from "node:path";
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
31
|
+
/** how long a started flow waits for the browser */
|
|
32
|
+
export const FLOW_TIMEOUT_MS = 5 * 60_000;
|
|
33
|
+
/**
|
|
34
|
+
* One server's OAuth state.
|
|
35
|
+
*
|
|
36
|
+
* The pieces the SDK needs and the pieces the UI needs live together because they are
|
|
37
|
+
* two views of the same grant: a token saved here is what `status()` reports as
|
|
38
|
+
* authorized.
|
|
39
|
+
*/
|
|
40
|
+
export class ServerAuth {
|
|
41
|
+
/** the URL the browser must be sent to, set by `redirectToAuthorization` */
|
|
42
|
+
authUrl;
|
|
43
|
+
verifier;
|
|
44
|
+
flow = { phase: "idle" };
|
|
45
|
+
lastError;
|
|
46
|
+
store = {};
|
|
47
|
+
server;
|
|
48
|
+
redirectUrl;
|
|
49
|
+
persist;
|
|
50
|
+
// Explicit fields, NOT parameter properties (`constructor(readonly x)`): Node's
|
|
51
|
+
// type-stripping loader refuses that syntax and `pnpm test` runs the sources directly
|
|
52
|
+
// (ERR_UNSUPPORTED_TYPESCRIPT_SYNTAX).
|
|
53
|
+
constructor(server, redirectUrl, persist) {
|
|
54
|
+
this.server = server;
|
|
55
|
+
this.redirectUrl = redirectUrl;
|
|
56
|
+
this.persist = persist;
|
|
57
|
+
}
|
|
58
|
+
/** load persisted state (called once, before the server is connected) */
|
|
59
|
+
async hydrate(data) {
|
|
60
|
+
if (data)
|
|
61
|
+
this.store = { ...data };
|
|
62
|
+
}
|
|
63
|
+
/** the persisted payload, for the store */
|
|
64
|
+
snapshot() {
|
|
65
|
+
return { ...this.store };
|
|
66
|
+
}
|
|
67
|
+
// ---- OAuthClientProvider ----
|
|
68
|
+
get clientMetadata() {
|
|
69
|
+
return {
|
|
70
|
+
client_name: "teapot",
|
|
71
|
+
// a local harness is a PUBLIC client: it cannot keep a secret meaningful, and the
|
|
72
|
+
// SDK sends `token_endpoint_auth_method: none` for exactly this shape
|
|
73
|
+
redirect_uris: [this.redirectUrl],
|
|
74
|
+
grant_types: ["authorization_code", "refresh_token"],
|
|
75
|
+
response_types: ["code"],
|
|
76
|
+
};
|
|
77
|
+
}
|
|
78
|
+
clientInformation() {
|
|
79
|
+
if (!this.store.clientId)
|
|
80
|
+
return undefined;
|
|
81
|
+
if (this.store.clientInformation)
|
|
82
|
+
return this.store.clientInformation;
|
|
83
|
+
return {
|
|
84
|
+
client_id: this.store.clientId,
|
|
85
|
+
...(this.store.clientSecret ? { client_secret: this.store.clientSecret } : {}),
|
|
86
|
+
};
|
|
87
|
+
}
|
|
88
|
+
async saveClientInformation(info, _ctx) {
|
|
89
|
+
const i = info;
|
|
90
|
+
if (typeof i?.client_id === "string")
|
|
91
|
+
this.store.clientId = i.client_id;
|
|
92
|
+
if (typeof i?.client_secret === "string")
|
|
93
|
+
this.store.clientSecret = i.client_secret;
|
|
94
|
+
// keep the whole payload: a future field (a client id issued with metadata) survives
|
|
95
|
+
this.store.clientInformation = info;
|
|
96
|
+
await this.persist(this.server, this.store);
|
|
97
|
+
}
|
|
98
|
+
tokens(_ctx) {
|
|
99
|
+
if (!this.store.accessToken)
|
|
100
|
+
return undefined;
|
|
101
|
+
return {
|
|
102
|
+
access_token: this.store.accessToken,
|
|
103
|
+
token_type: "Bearer",
|
|
104
|
+
...(this.store.refreshToken ? { refresh_token: this.store.refreshToken } : {}),
|
|
105
|
+
...(this.store.expiresAt ? { expires_in: Math.max(0, Math.round((this.store.expiresAt - Date.now()) / 1000)) } : {}),
|
|
106
|
+
...(this.store.scope ? { scope: this.store.scope } : {}),
|
|
107
|
+
};
|
|
108
|
+
}
|
|
109
|
+
async saveTokens(tokens, _ctx) {
|
|
110
|
+
this.store.accessToken = tokens.access_token;
|
|
111
|
+
// PERSIST A ROTATED REFRESH TOKEN IMMEDIATELY: a server that rotates invalidates the
|
|
112
|
+
// previous one, so keeping the old token breaks the NEXT refresh with invalid_grant.
|
|
113
|
+
if (tokens.refresh_token)
|
|
114
|
+
this.store.refreshToken = tokens.refresh_token;
|
|
115
|
+
if (typeof tokens.expires_in === "number" && tokens.expires_in > 0)
|
|
116
|
+
this.store.expiresAt = Date.now() + tokens.expires_in * 1000;
|
|
117
|
+
if (typeof tokens.scope === "string")
|
|
118
|
+
this.store.scope = tokens.scope;
|
|
119
|
+
this.flow = { phase: "done" };
|
|
120
|
+
await this.persist(this.server, this.store);
|
|
121
|
+
}
|
|
122
|
+
redirectToAuthorization(url) {
|
|
123
|
+
this.authUrl = url;
|
|
124
|
+
this.flow = { phase: "authorizing", url: url.toString(), startedAt: Date.now() };
|
|
125
|
+
}
|
|
126
|
+
async saveCodeVerifier(verifier) {
|
|
127
|
+
this.verifier = verifier;
|
|
128
|
+
this.store.codeVerifier = verifier;
|
|
129
|
+
}
|
|
130
|
+
codeVerifier() {
|
|
131
|
+
if (!this.verifier)
|
|
132
|
+
throw new Error("no PKCE verifier — the authorization flow did not start here");
|
|
133
|
+
return this.verifier;
|
|
134
|
+
}
|
|
135
|
+
// ---- teapot-facing ----
|
|
136
|
+
/** the url the browser must open, once `redirectToAuthorization` has been called */
|
|
137
|
+
pendingUrl() {
|
|
138
|
+
return this.flow.phase === "authorizing" ? this.flow.url : undefined;
|
|
139
|
+
}
|
|
140
|
+
markError(message) {
|
|
141
|
+
this.lastError = message;
|
|
142
|
+
this.flow = { phase: "error", message };
|
|
143
|
+
}
|
|
144
|
+
/** drop the grant (disconnect) */
|
|
145
|
+
async clear() {
|
|
146
|
+
this.store = {};
|
|
147
|
+
this.verifier = undefined;
|
|
148
|
+
this.authUrl = undefined;
|
|
149
|
+
this.flow = { phase: "idle" };
|
|
150
|
+
this.lastError = undefined;
|
|
151
|
+
await this.persist(this.server, this.store);
|
|
152
|
+
}
|
|
153
|
+
status() {
|
|
154
|
+
const expiresAt = this.store.expiresAt ?? null;
|
|
155
|
+
// a token with no advertised expiry counts as usable; the SDK refreshes on 401 anyway
|
|
156
|
+
const fresh = Boolean(this.store.accessToken) && (expiresAt === null || Date.now() < expiresAt - 60_000);
|
|
157
|
+
return {
|
|
158
|
+
pending: this.flow.phase === "authorizing",
|
|
159
|
+
authorized: fresh,
|
|
160
|
+
expiresAt,
|
|
161
|
+
hasRefreshToken: Boolean(this.store.refreshToken),
|
|
162
|
+
...(this.store.clientId ? { clientId: this.store.clientId } : {}),
|
|
163
|
+
flow: this.flow,
|
|
164
|
+
...(this.lastError ? { lastError: this.lastError } : {}),
|
|
165
|
+
};
|
|
166
|
+
}
|
|
167
|
+
}
|
|
35
168
|
/**
|
|
36
|
-
*
|
|
37
|
-
* handler that finishes the flow.
|
|
169
|
+
* The loopback listener an OAuth flow needs.
|
|
38
170
|
*
|
|
39
|
-
*
|
|
40
|
-
*
|
|
171
|
+
* Bound to 127.0.0.1, never 0.0.0.0: this endpoint accepts an authorization code and must
|
|
172
|
+
* not be reachable from the network. The `state` check lives in the caller (the SDK
|
|
173
|
+
* generates and verifies it), so this only has to deliver `code` and `iss`.
|
|
41
174
|
*/
|
|
42
|
-
async function
|
|
175
|
+
export async function listenForCallback() {
|
|
43
176
|
return await new Promise((resolve, reject) => {
|
|
44
177
|
const server = createServer();
|
|
45
178
|
let deliver = null;
|
|
@@ -52,7 +185,6 @@ async function listenLoopback() {
|
|
|
52
185
|
server.on("request", (req, res) => {
|
|
53
186
|
const url = new URL(req.url ?? "/", "http://127.0.0.1");
|
|
54
187
|
const code = url.searchParams.get("code");
|
|
55
|
-
const state = url.searchParams.get("state");
|
|
56
188
|
const error = url.searchParams.get("error");
|
|
57
189
|
if (error) {
|
|
58
190
|
const desc = url.searchParams.get("error_description") ?? error;
|
|
@@ -71,7 +203,8 @@ async function listenLoopback() {
|
|
|
71
203
|
}
|
|
72
204
|
sawFirst = true;
|
|
73
205
|
res.writeHead(200, { "content-type": "text/html; charset=utf-8" }).end(page("authorized", "you can close this tab"));
|
|
74
|
-
|
|
206
|
+
const iss = url.searchParams.get("iss") ?? undefined;
|
|
207
|
+
deliver?.({ code, ...(iss ? { iss } : {}) });
|
|
75
208
|
});
|
|
76
209
|
server.on("error", reject);
|
|
77
210
|
server.listen(0, "127.0.0.1", () => {
|
|
@@ -81,7 +214,7 @@ async function listenLoopback() {
|
|
|
81
214
|
return;
|
|
82
215
|
}
|
|
83
216
|
resolve({
|
|
84
|
-
|
|
217
|
+
redirectUrl: `http://127.0.0.1:${addr.port}/callback`,
|
|
85
218
|
wait: (timeoutMs) => new Promise((res, rej) => {
|
|
86
219
|
const timer = setTimeout(() => rej(new Error("the authorization page was not completed in time")), timeoutMs);
|
|
87
220
|
result.then((v) => {
|
|
@@ -105,238 +238,47 @@ h1{font-size:1.1rem}</style>
|
|
|
105
238
|
<h1>${title}</h1><p>${body}</p>
|
|
106
239
|
<script>setTimeout(()=>window.close(),1200)</script>`;
|
|
107
240
|
}
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
241
|
+
/**
|
|
242
|
+
* Grants for every server, persisted together.
|
|
243
|
+
*
|
|
244
|
+
* One file rather than one per server: the set is small, and a single atomic write keeps
|
|
245
|
+
* a rotation from racing a second write.
|
|
246
|
+
*/
|
|
247
|
+
export class McpAuthStore {
|
|
248
|
+
file;
|
|
249
|
+
cache = null;
|
|
250
|
+
constructor(dir) {
|
|
251
|
+
this.file = path.join(dir, "mcp-oauth.json");
|
|
118
252
|
}
|
|
119
|
-
/** read persisted grants; a missing or corrupt file is simply no grants */
|
|
120
253
|
async load() {
|
|
254
|
+
if (this.cache)
|
|
255
|
+
return this.cache;
|
|
121
256
|
try {
|
|
122
|
-
const raw = JSON.parse(await readFile(this.
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
257
|
+
const raw = JSON.parse(await readFile(this.file, "utf8"));
|
|
258
|
+
// tolerate hand edits: keep only entries that look like ours
|
|
259
|
+
const out = {};
|
|
260
|
+
for (const [k, v] of Object.entries(raw ?? {}))
|
|
261
|
+
if (v && typeof v === "object")
|
|
262
|
+
out[k] = v;
|
|
263
|
+
this.cache = out;
|
|
127
264
|
}
|
|
128
265
|
catch {
|
|
129
|
-
|
|
266
|
+
this.cache = {};
|
|
130
267
|
}
|
|
268
|
+
return this.cache;
|
|
269
|
+
}
|
|
270
|
+
async get(server) {
|
|
271
|
+
return (await this.load())[server];
|
|
131
272
|
}
|
|
132
|
-
async
|
|
133
|
-
const
|
|
134
|
-
|
|
135
|
-
out[k] = v;
|
|
273
|
+
async set(server, data) {
|
|
274
|
+
const all = await this.load();
|
|
275
|
+
all[server] = data;
|
|
136
276
|
try {
|
|
137
|
-
await mkdir(path.dirname(this.
|
|
138
|
-
|
|
139
|
-
await writeFile(this.storePath, JSON.stringify(out, null, 2), { mode: 0o600 });
|
|
277
|
+
await mkdir(path.dirname(this.file), { recursive: true });
|
|
278
|
+
await writeFile(this.file, JSON.stringify(all, null, 2), { mode: 0o600 });
|
|
140
279
|
}
|
|
141
280
|
catch {
|
|
142
281
|
/* a failed write must not break a live session */
|
|
143
282
|
}
|
|
144
283
|
}
|
|
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
284
|
}
|
|
342
|
-
export { parseBearerChallenge };
|