turno-cli 0.1.1 → 0.3.0

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.
Files changed (121) hide show
  1. package/CHANGELOG.md +432 -0
  2. package/README.md +228 -73
  3. package/dist/accounts/audit.js +154 -12
  4. package/dist/accounts/builtin.js +100 -25
  5. package/dist/accounts/delegate.js +199 -35
  6. package/dist/accounts/policy.js +79 -0
  7. package/dist/accounts/registry.js +39 -21
  8. package/dist/agents/adapter.js +29 -0
  9. package/dist/agents/claude.js +246 -0
  10. package/dist/agents/codex.js +186 -0
  11. package/dist/agents/copilot.js +56 -0
  12. package/dist/agents/cursor.js +58 -0
  13. package/dist/agents/index.js +26 -86
  14. package/dist/agents/snippets.js +43 -13
  15. package/dist/cli/args.js +38 -6
  16. package/dist/cli/commands/accounts.js +119 -52
  17. package/dist/cli/commands/auto.js +121 -33
  18. package/dist/cli/commands/browser-identity.js +514 -0
  19. package/dist/cli/commands/browser-session.js +102 -0
  20. package/dist/cli/commands/browser-vault.js +193 -0
  21. package/dist/cli/commands/browser.js +319 -138
  22. package/dist/cli/commands/complete.js +14 -3
  23. package/dist/cli/commands/completion.js +8 -2
  24. package/dist/cli/commands/config.js +186 -24
  25. package/dist/cli/commands/demo.js +321 -0
  26. package/dist/cli/commands/doctor.js +525 -123
  27. package/dist/cli/commands/handoff.js +33 -22
  28. package/dist/cli/commands/identity.js +192 -54
  29. package/dist/cli/commands/init.js +648 -0
  30. package/dist/cli/commands/limit.js +84 -16
  31. package/dist/cli/commands/mcp-call.js +240 -0
  32. package/dist/cli/commands/mcp-oauth.js +221 -0
  33. package/dist/cli/commands/mcp-observe.js +539 -0
  34. package/dist/cli/commands/mcp-share.js +201 -0
  35. package/dist/cli/commands/mcp.js +816 -187
  36. package/dist/cli/commands/mcpd.js +388 -76
  37. package/dist/cli/commands/migrate.js +6 -4
  38. package/dist/cli/commands/open.js +115 -27
  39. package/dist/cli/commands/profile.js +396 -78
  40. package/dist/cli/commands/resolve.js +14 -3
  41. package/dist/cli/commands/run.js +36 -6
  42. package/dist/cli/commands/secret.js +80 -76
  43. package/dist/cli/commands/session.js +17 -6
  44. package/dist/cli/commands/sessions.js +48 -12
  45. package/dist/cli/commands/setup.js +214 -164
  46. package/dist/cli/commands/status.js +227 -44
  47. package/dist/cli/commands/statusline.js +311 -114
  48. package/dist/cli/commands/ui.js +78 -68
  49. package/dist/cli/commands/undo.js +193 -18
  50. package/dist/cli/commands/uninstall.js +481 -0
  51. package/dist/cli/commands/upgrade.js +172 -79
  52. package/dist/cli/commands/usage.js +125 -51
  53. package/dist/cli/commands/version.js +21 -7
  54. package/dist/cli/commands/which.js +9 -24
  55. package/dist/cli/compile-cache.js +32 -0
  56. package/dist/cli/diagnostics.js +184 -0
  57. package/dist/cli/exit.js +65 -0
  58. package/dist/cli/group.js +24 -12
  59. package/dist/cli/help.js +62 -0
  60. package/dist/cli/highlight.js +236 -0
  61. package/dist/cli/hints.js +30 -0
  62. package/dist/cli/io.js +186 -1
  63. package/dist/cli/launch.js +52 -39
  64. package/dist/cli/launchers.js +161 -95
  65. package/dist/cli/main.js +201 -31
  66. package/dist/cli/optional.js +144 -0
  67. package/dist/cli/output.js +123 -0
  68. package/dist/cli/picker.js +459 -0
  69. package/dist/cli/registry.js +61 -6
  70. package/dist/cli/safe.js +87 -0
  71. package/dist/cli/secret-input.js +63 -0
  72. package/dist/cli/security.js +561 -0
  73. package/dist/cli/style.js +311 -0
  74. package/dist/cli/topics.js +142 -0
  75. package/dist/core/config.js +181 -23
  76. package/dist/core/exhausted.js +6 -8
  77. package/dist/core/fsutil.js +39 -0
  78. package/dist/core/journal.js +294 -16
  79. package/dist/core/manifest.js +153 -6
  80. package/dist/core/paths.js +14 -13
  81. package/dist/core/profiles.js +160 -10
  82. package/dist/core/resolve.js +139 -23
  83. package/dist/core/secrets.js +68 -23
  84. package/dist/core/sessions.js +13 -20
  85. package/dist/core/state-file.js +107 -0
  86. package/dist/core/update.js +31 -18
  87. package/dist/core/version.js +57 -10
  88. package/dist/demo/server.js +42 -0
  89. package/dist/mcpd/cache.js +23 -10
  90. package/dist/mcpd/calllog.js +254 -0
  91. package/dist/mcpd/client-names.js +46 -0
  92. package/dist/mcpd/connectors.js +188 -18
  93. package/dist/mcpd/daemon.js +472 -115
  94. package/dist/mcpd/folder-sets.js +42 -0
  95. package/dist/mcpd/gateway.js +473 -51
  96. package/dist/mcpd/health.js +313 -0
  97. package/dist/mcpd/importer.js +453 -36
  98. package/dist/mcpd/instances.js +453 -65
  99. package/dist/mcpd/jsonrpc.js +11 -1
  100. package/dist/mcpd/launchd.js +65 -48
  101. package/dist/mcpd/middleware.js +144 -0
  102. package/dist/mcpd/modern.js +686 -0
  103. package/dist/mcpd/oauth.js +845 -0
  104. package/dist/mcpd/peerpid.js +134 -6
  105. package/dist/mcpd/pressure.js +88 -0
  106. package/dist/mcpd/rss.js +166 -0
  107. package/dist/mcpd/service.js +191 -0
  108. package/dist/mcpd/share.js +217 -0
  109. package/dist/mcpd/state.js +183 -0
  110. package/dist/mcpd/sync.js +72 -87
  111. package/dist/mcpd/systemd.js +83 -0
  112. package/dist/mcpd/tokens.js +85 -0
  113. package/dist/mcpd/upstream.js +163 -46
  114. package/dist/statusline/cost.js +167 -44
  115. package/dist/statusline/input.js +78 -0
  116. package/dist/statusline/render.js +9 -3
  117. package/dist/ui/fonts.js +8 -3
  118. package/dist/ui/settings.js +33 -16
  119. package/npm-shrinkwrap.json +1102 -0
  120. package/package.json +10 -9
  121. package/dist/cli/commands/available.js +0 -18
@@ -0,0 +1,845 @@
1
+ import { createHash, randomBytes } from "node:crypto";
2
+ import { createServer } from "node:http";
3
+ import { buildDiscoveryUrls, discoverOAuthProtectedResourceMetadata, exchangeAuthorization, extractWWWAuthenticateParams, isHttpsUrl, refreshAuthorization, registerClient, startAuthorization, } from "@modelcontextprotocol/sdk/client/auth.js";
4
+ import { InvalidClientError, InvalidGrantError, UnauthorizedClientError, } from "@modelcontextprotocol/sdk/server/auth/errors.js";
5
+ import { OAuthMetadataSchema, OpenIdProviderDiscoveryMetadataSchema, } from "@modelcontextprotocol/sdk/shared/auth.js";
6
+ import { checkResourceAllowed, resourceUrlFromServerUrl } from "@modelcontextprotocol/sdk/shared/auth-utils.js";
7
+ import { LATEST_PROTOCOL_VERSION } from "@modelcontextprotocol/sdk/types.js";
8
+ import { packageInfo } from "../core/version.js";
9
+ /**
10
+ * mcpd as the OAuth client of remote MCP servers, following the MCP authorization
11
+ * specification (revision 2026-07-28): protected resource metadata (RFC 9728), authorization
12
+ * server metadata (RFC 8414, OpenID Connect Discovery) with issuer validation, pre-registration,
13
+ * Client ID Metadata Documents or Dynamic Client Registration (RFC 7591), PKCE with S256
14
+ * (RFC 7636), resource indicators (RFC 8707), and issuer identification in the authorization
15
+ * response (RFC 9207). The SDK's building blocks do the HTTP; the checks the SDK leaves out
16
+ * (issuer echo, PKCE advertised, `iss`, HTTPS endpoints) are here.
17
+ *
18
+ * Tokens live only in the secret store (one item per server variant) and in mcpd's memory.
19
+ * They are never written to a file, a log line or command output.
20
+ */
21
+ /** Seconds before `expires_at` when an access token already counts as expired. */
22
+ const EXPIRY_SKEW_MS = 60_000;
23
+ /** How long mcpd trusts its copy of a login before it looks at the secret store again. */
24
+ const RECHECK_MS = 60_000;
25
+ const CALLBACK_PATH = "/callback";
26
+ /** Secret store item that holds the login of one server variant. */
27
+ export function oauthService(server, variant) {
28
+ return `turno/oauth/${server}@${variant}`;
29
+ }
30
+ /** What `turno mcp login` passes to an authorization server about turno. */
31
+ function clientMetadata(redirectUri, scope) {
32
+ return {
33
+ client_name: "turno",
34
+ client_uri: "https://github.com/wimo-dev/turno",
35
+ redirect_uris: [redirectUri],
36
+ grant_types: ["authorization_code", "refresh_token"],
37
+ response_types: ["code"],
38
+ token_endpoint_auth_method: "none",
39
+ // The MCP spec asks for it with DCR: a CLI on a loopback redirect is a native application.
40
+ application_type: "native",
41
+ software_id: "turno",
42
+ software_version: packageInfo().version,
43
+ ...(scope ? { scope } : {}),
44
+ };
45
+ }
46
+ export function parseRecord(raw) {
47
+ if (!raw)
48
+ return undefined;
49
+ try {
50
+ const r = JSON.parse(raw);
51
+ return r && r.v === 1 && typeof r.issuer === "string" && r.client && typeof r.client.client_id === "string"
52
+ ? r
53
+ : undefined;
54
+ }
55
+ catch {
56
+ return undefined;
57
+ }
58
+ }
59
+ /** The OAuth error a session raises when nobody can fix it but the user, with the command to run. */
60
+ export class LoginRequiredError extends Error {
61
+ constructor(server, variant, why) {
62
+ const who = variant === "default" ? "" : ` --profile ${variant}`;
63
+ super(`${server}${variant === "default" ? "" : `@${variant}`} needs a login (${why}): run turno mcp login ${server}${who}`);
64
+ this.name = "LoginRequiredError";
65
+ }
66
+ }
67
+ export class OAuthFlowError extends Error {
68
+ constructor(message) {
69
+ super(message);
70
+ this.name = "OAuthFlowError";
71
+ }
72
+ }
73
+ const LOOPBACK = new Set(["127.0.0.1", "localhost", "[::1]"]);
74
+ function isLoopbackUrl(url) {
75
+ try {
76
+ const u = new URL(url);
77
+ return u.protocol === "http:" && LOOPBACK.has(u.hostname);
78
+ }
79
+ catch {
80
+ return false;
81
+ }
82
+ }
83
+ /** HTTPS, or plain HTTP on the loopback interface (local servers and tests). */
84
+ function requireSecure(url, what) {
85
+ let u;
86
+ try {
87
+ u = new URL(url);
88
+ }
89
+ catch {
90
+ throw new OAuthFlowError(`${what} is not a URL: ${url}`);
91
+ }
92
+ if (u.protocol !== "https:" && !isLoopbackUrl(u))
93
+ throw new OAuthFlowError(`${what} must use https: ${url}`);
94
+ }
95
+ /** Error text with every known secret value replaced, cut to one short line. */
96
+ function scrub(message, secrets) {
97
+ let out = message;
98
+ for (const s of secrets)
99
+ if (s && s.length >= 8)
100
+ out = out.split(s).join("[redacted]");
101
+ out = out.replace(/\s+/g, " ").trim();
102
+ return out.length > 300 ? `${out.slice(0, 297)}...` : out;
103
+ }
104
+ /** RFC 7009 endpoint; OAuth metadata has it, the OpenID type does not declare it. */
105
+ function revocationEndpoint(m) {
106
+ const v = m.revocation_endpoint;
107
+ return typeof v === "string" ? v : undefined;
108
+ }
109
+ function sameIssuer(advertised, used) {
110
+ // RFC 8414 section 3.3: identical. A lone trailing slash on a pathless issuer builds the same
111
+ // well-known URL, so it is the one difference tolerated.
112
+ if (advertised === used)
113
+ return true;
114
+ const strip = (s) => (s.endsWith("/") && new URL(s).pathname === "/" ? s.slice(0, -1) : s);
115
+ try {
116
+ return strip(advertised) === strip(used);
117
+ }
118
+ catch {
119
+ return false;
120
+ }
121
+ }
122
+ /**
123
+ * Authorization server metadata, from the well-known URLs in the order the spec gives (RFC 8414
124
+ * first, then OpenID Connect Discovery). The document's `issuer` must be the one the URL was
125
+ * built from, and it must advertise PKCE with S256; otherwise turno refuses to go on.
126
+ */
127
+ async function authorizationServerMetadata(issuer, fetchFn = fetch) {
128
+ requireSecure(issuer, "the authorization server");
129
+ for (const { url, type } of buildDiscoveryUrls(issuer)) {
130
+ let res;
131
+ try {
132
+ res = await fetchFn(url, {
133
+ headers: { Accept: "application/json", "MCP-Protocol-Version": LATEST_PROTOCOL_VERSION },
134
+ redirect: "error",
135
+ });
136
+ }
137
+ catch (err) {
138
+ throw new OAuthFlowError(`cannot reach the authorization server at ${url.origin}: ${err.message}`);
139
+ }
140
+ if (!res.ok) {
141
+ await res.body?.cancel();
142
+ if (res.status < 500)
143
+ continue;
144
+ throw new OAuthFlowError(`HTTP ${res.status} from ${url.href}`);
145
+ }
146
+ const parsed = (type === "oauth" ? OAuthMetadataSchema : OpenIdProviderDiscoveryMetadataSchema).safeParse(await res.json().catch(() => null));
147
+ if (!parsed.success)
148
+ throw new OAuthFlowError(`${url.href} is not valid authorization server metadata`);
149
+ const m = parsed.data;
150
+ if (!sameIssuer(m.issuer, issuer)) {
151
+ throw new OAuthFlowError(`the metadata at ${url.href} names issuer ${m.issuer}, not ${issuer}; refusing to use it (RFC 8414 section 3.3)`);
152
+ }
153
+ if (!m.code_challenge_methods_supported?.includes("S256")) {
154
+ throw new OAuthFlowError(`the authorization server ${issuer} does not advertise PKCE with S256 (code_challenge_methods_supported); refusing to go on`);
155
+ }
156
+ if (!m.response_types_supported.includes("code"))
157
+ throw new OAuthFlowError(`the authorization server ${issuer} does not support the authorization code flow`);
158
+ for (const [k, v] of Object.entries({
159
+ authorization_endpoint: m.authorization_endpoint,
160
+ token_endpoint: m.token_endpoint,
161
+ registration_endpoint: m.registration_endpoint,
162
+ revocation_endpoint: revocationEndpoint(m),
163
+ })) {
164
+ if (typeof v === "string")
165
+ requireSecure(v, k);
166
+ }
167
+ return m;
168
+ }
169
+ throw new OAuthFlowError(`no authorization server metadata found for ${issuer}`);
170
+ }
171
+ /** POST an unauthenticated initialize to learn the 401 challenge (resource_metadata, scope). */
172
+ async function probe(serverUrl, fetchFn) {
173
+ let res;
174
+ try {
175
+ res = await fetchFn(serverUrl, {
176
+ method: "POST",
177
+ headers: {
178
+ "Content-Type": "application/json",
179
+ Accept: "application/json, text/event-stream",
180
+ "MCP-Protocol-Version": LATEST_PROTOCOL_VERSION,
181
+ },
182
+ body: JSON.stringify({
183
+ jsonrpc: "2.0",
184
+ id: 1,
185
+ method: "initialize",
186
+ params: {
187
+ protocolVersion: LATEST_PROTOCOL_VERSION,
188
+ capabilities: {},
189
+ clientInfo: { name: "turno-mcpd", version: packageInfo().version },
190
+ },
191
+ }),
192
+ redirect: "error",
193
+ });
194
+ }
195
+ catch (err) {
196
+ throw new OAuthFlowError(`cannot reach ${serverUrl}: ${err.message}`);
197
+ }
198
+ const params = res.status === 401 ? extractWWWAuthenticateParams(res) : {};
199
+ await res.body?.cancel().catch(() => { });
200
+ return { status: res.status, ...params };
201
+ }
202
+ /**
203
+ * Find the authorization server of an MCP server. With `challenge`, first send an
204
+ * unauthenticated request and use the resource_metadata URL and scope of its 401; without one
205
+ * (refresh), go straight to the well-known URLs.
206
+ */
207
+ async function discover(server, fetchFn = fetch, challenge = false) {
208
+ requireSecure(server.url, `${server.name}'s url`);
209
+ let resourceMetadataUrl;
210
+ let challengeScope;
211
+ if (challenge) {
212
+ const p = await probe(server.url, fetchFn);
213
+ if (p.status >= 200 && p.status < 300)
214
+ return { unprotected: true };
215
+ resourceMetadataUrl = p.resourceMetadataUrl;
216
+ challengeScope = p.scope;
217
+ }
218
+ let resourceMetadata;
219
+ try {
220
+ resourceMetadata = await discoverOAuthProtectedResourceMetadata(server.url, resourceMetadataUrl ? { resourceMetadataUrl } : {}, fetchFn);
221
+ }
222
+ catch (err) {
223
+ throw new OAuthFlowError(`${server.name} does not publish OAuth protected resource metadata (RFC 9728): ${err.message}`);
224
+ }
225
+ const requested = resourceUrlFromServerUrl(server.url);
226
+ if (!checkResourceAllowed({ requestedResource: requested, configuredResource: resourceMetadata.resource })) {
227
+ throw new OAuthFlowError(`${server.name}: the protected resource ${resourceMetadata.resource} does not cover ${server.url}`);
228
+ }
229
+ const listed = resourceMetadata.authorization_servers ?? [];
230
+ if (!listed.length)
231
+ throw new OAuthFlowError(`${server.name}: the protected resource metadata lists no authorization server`);
232
+ const wanted = server.oauth?.authorizationServer;
233
+ const issuer = wanted ? listed.find((a) => sameIssuer(a, wanted)) : listed[0];
234
+ if (!issuer)
235
+ throw new OAuthFlowError(`${server.name}: authorization_server ${wanted} is not one of ${listed.join(", ")}`);
236
+ const metadata = await authorizationServerMetadata(issuer, fetchFn);
237
+ return {
238
+ resourceMetadata,
239
+ resource: resourceMetadata.resource,
240
+ issuer,
241
+ metadata,
242
+ ...(challengeScope ? { challengeScope } : {}),
243
+ };
244
+ }
245
+ /** Space-separated union, keeping the first order. */
246
+ function unionScopes(...lists) {
247
+ const out = [];
248
+ for (const l of lists)
249
+ for (const s of (l ?? "").split(/\s+/))
250
+ if (s && !out.includes(s))
251
+ out.push(s);
252
+ return out.length ? out.join(" ") : undefined;
253
+ }
254
+ /** Scope selection of the spec: configured, else the 401 challenge, else scopes_supported. */
255
+ function selectScope(d, settings, extra, previous) {
256
+ const base = settings?.scope ?? d.challengeScope ?? d.resourceMetadata.scopes_supported?.join(" ");
257
+ let scope = unionScopes(previous, base, extra);
258
+ // Refresh tokens are not a resource scope; ask for offline_access only when the server lists it.
259
+ if (scope && d.metadata.scopes_supported?.includes("offline_access"))
260
+ scope = unionScopes(scope, "offline_access");
261
+ return scope;
262
+ }
263
+ function toStored(t, now) {
264
+ return {
265
+ access_token: t.access_token,
266
+ token_type: t.token_type,
267
+ ...(t.refresh_token ? { refresh_token: t.refresh_token } : {}),
268
+ ...(t.scope ? { scope: t.scope } : {}),
269
+ ...(typeof t.expires_in === "number" && Number.isFinite(t.expires_in)
270
+ ? { expires_at: now + t.expires_in * 1000 }
271
+ : {}),
272
+ };
273
+ }
274
+ /** The client information to present: pre-registered ones get their secret from mcp.toml at use time. */
275
+ async function clientFor(rec, settings, resolve) {
276
+ if (rec.registration !== "pre-registered")
277
+ return rec.client;
278
+ return {
279
+ client_id: rec.client.client_id,
280
+ ...(settings?.clientSecret ? { client_secret: await resolve(settings.clientSecret) } : {}),
281
+ };
282
+ }
283
+ /** A one-shot HTTP listener on 127.0.0.1 (RFC 8252 section 7.3, loopback IP literal). */
284
+ async function callbackServer(port) {
285
+ let deliver;
286
+ const got = new Promise((r) => {
287
+ deliver = r;
288
+ });
289
+ const srv = createServer((req, res) => {
290
+ const url = new URL(req.url ?? "/", "http://127.0.0.1");
291
+ if (req.method !== "GET" || url.pathname !== CALLBACK_PATH) {
292
+ res.writeHead(404, { "Content-Type": "text/plain" }).end("not found");
293
+ return;
294
+ }
295
+ res.writeHead(200, { "Content-Type": "text/html; charset=utf-8", "Cache-Control": "no-store" });
296
+ res.end("<!doctype html><title>turno</title><p>turno received the answer. You can close this tab and go back to the terminal.</p>");
297
+ deliver(url.searchParams);
298
+ });
299
+ await new Promise((resolve, reject) => {
300
+ srv.once("error", reject);
301
+ srv.listen(port, "127.0.0.1", () => resolve());
302
+ });
303
+ const actual = srv.address().port;
304
+ return {
305
+ port: actual,
306
+ redirectUri: `http://127.0.0.1:${actual}${CALLBACK_PATH}`,
307
+ wait: (timeoutMs) => new Promise((resolve, reject) => {
308
+ const t = setTimeout(() => reject(new OAuthFlowError(`no answer from the browser within ${Math.round(timeoutMs / 1000)}s`)), timeoutMs);
309
+ void got.then((q) => {
310
+ clearTimeout(t);
311
+ resolve(q);
312
+ });
313
+ }),
314
+ close: () => new Promise((r) => {
315
+ srv.closeAllConnections();
316
+ srv.close(() => r());
317
+ }),
318
+ };
319
+ }
320
+ function portOf(uris) {
321
+ if (!Array.isArray(uris))
322
+ return undefined;
323
+ for (const u of uris) {
324
+ try {
325
+ const url = new URL(String(u));
326
+ if (url.hostname === "127.0.0.1" && url.port)
327
+ return Number(url.port);
328
+ }
329
+ catch {
330
+ /* not a URL */
331
+ }
332
+ }
333
+ return undefined;
334
+ }
335
+ /**
336
+ * RFC 9207 section 2.4, as the MCP spec tabulates it: a present `iss` must equal the recorded
337
+ * issuer (simple string comparison); an absent one is refused only when the server says it sends it.
338
+ */
339
+ export function checkIssuerParam(q, issuer, metadata) {
340
+ const iss = q.get("iss");
341
+ const advertised = metadata
342
+ .authorization_response_iss_parameter_supported === true;
343
+ if (iss !== null) {
344
+ if (iss !== issuer)
345
+ throw new OAuthFlowError(`the authorization response came from issuer ${iss}, not ${issuer}; refusing it (RFC 9207)`);
346
+ return;
347
+ }
348
+ if (advertised)
349
+ throw new OAuthFlowError(`the authorization response has no iss although ${issuer} advertises it; refusing it (RFC 9207)`);
350
+ }
351
+ /**
352
+ * `turno mcp login`: discovery, client registration, PKCE authorization code flow on a loopback
353
+ * redirect, token exchange, and one write to the secret store.
354
+ */
355
+ export async function login(o) {
356
+ const fetchFn = o.fetchFn ?? fetch;
357
+ const now = o.now ?? Date.now;
358
+ const settings = o.server.oauth;
359
+ const service = oauthService(o.server.name, o.variant);
360
+ const d = await discover(o.server, fetchFn, true);
361
+ if (d.unprotected)
362
+ throw new OAuthFlowError(`${o.server.name} answered without asking for authorization; it needs no login (remove auth = "oauth")`);
363
+ const previous = parseRecord(await o.store.get(service));
364
+ const sameAs = previous && sameIssuer(previous.issuer, d.issuer) ? previous : undefined;
365
+ const scope = selectScope(d, settings, o.scope, o.scope ? sameAs?.scope : undefined);
366
+ // Registration, in the spec's order: pre-registered, metadata document, dynamic.
367
+ let registration;
368
+ if (settings?.clientId)
369
+ registration = "pre-registered";
370
+ else if (d.metadata.client_id_metadata_document_supported === true && settings?.clientMetadataUrl)
371
+ registration = "metadata-document";
372
+ else if (d.metadata.registration_endpoint)
373
+ registration = "dynamic";
374
+ else {
375
+ throw new OAuthFlowError(`${d.issuer} offers neither dynamic client registration nor client ID metadata documents that turno can use; register a client there and set client_id under [server.${o.server.name}.oauth]`);
376
+ }
377
+ if (registration === "metadata-document" && !isHttpsUrl(settings?.clientMetadataUrl)) {
378
+ throw new OAuthFlowError(`client_metadata_url must be an https URL with a path`);
379
+ }
380
+ if (o.dryRun)
381
+ return { issuer: d.issuer, registration, ...(scope ? { scope } : {}), refreshToken: false, service, planned: true };
382
+ // Reuse the port of an earlier dynamic registration, so its exact redirect URI still matches.
383
+ const reusable = registration === "dynamic" && sameAs?.registration === "dynamic" ? sameAs.client : undefined;
384
+ const wantedPort = settings?.callbackPort ?? portOf(reusable?.redirect_uris) ?? 0;
385
+ let cb;
386
+ try {
387
+ cb = await callbackServer(wantedPort);
388
+ }
389
+ catch (err) {
390
+ if (settings?.callbackPort || wantedPort === 0) {
391
+ throw new OAuthFlowError(`cannot listen on 127.0.0.1:${wantedPort} for the browser's answer: ${err.message}`);
392
+ }
393
+ cb = await callbackServer(0);
394
+ }
395
+ try {
396
+ let client;
397
+ if (registration === "pre-registered") {
398
+ client = { client_id: settings.clientId };
399
+ }
400
+ else if (registration === "metadata-document") {
401
+ client = { client_id: settings.clientMetadataUrl };
402
+ }
403
+ else if (reusable && portOf(reusable.redirect_uris) === cb.port) {
404
+ client = reusable;
405
+ }
406
+ else {
407
+ try {
408
+ client = await registerClient(d.issuer, {
409
+ metadata: d.metadata,
410
+ clientMetadata: clientMetadata(cb.redirectUri, scope),
411
+ ...(scope ? { scope } : {}),
412
+ fetchFn,
413
+ });
414
+ }
415
+ catch (err) {
416
+ throw new OAuthFlowError(`dynamic client registration at ${d.issuer} failed: ${scrub(err.message, [])}`);
417
+ }
418
+ }
419
+ const presented = await clientFor({ registration, client }, settings, o.resolve);
420
+ const state = randomBytes(32).toString("base64url");
421
+ const { authorizationUrl, codeVerifier } = await startAuthorization(d.issuer, {
422
+ metadata: d.metadata,
423
+ clientInformation: presented,
424
+ redirectUrl: cb.redirectUri,
425
+ ...(scope ? { scope } : {}),
426
+ state,
427
+ resource: d.resource,
428
+ });
429
+ await o.open(authorizationUrl.href);
430
+ const q = await cb.wait(o.timeoutMs ?? 5 * 60_000);
431
+ // The issuer check comes first: on a mismatch nothing in the response is acted on or shown.
432
+ checkIssuerParam(q, d.issuer, d.metadata);
433
+ if (q.get("state") !== state)
434
+ throw new OAuthFlowError("the authorization response has a different state; refusing it");
435
+ const error = q.get("error");
436
+ if (error)
437
+ throw new OAuthFlowError(`the authorization server answered ${error}${q.get("error_description") ? `: ${scrub(q.get("error_description"), [])}` : ""}`);
438
+ const code = q.get("code");
439
+ if (!code)
440
+ throw new OAuthFlowError("the authorization response has no code");
441
+ let tokens;
442
+ try {
443
+ tokens = await exchangeAuthorization(d.issuer, {
444
+ metadata: d.metadata,
445
+ clientInformation: presented,
446
+ authorizationCode: code,
447
+ codeVerifier,
448
+ redirectUri: cb.redirectUri,
449
+ resource: d.resource,
450
+ fetchFn,
451
+ });
452
+ }
453
+ catch (err) {
454
+ throw new OAuthFlowError(`the token request failed: ${scrub(err.message, [code, codeVerifier, presented.client_secret])}`);
455
+ }
456
+ const at = now();
457
+ const rec = {
458
+ v: 1,
459
+ issuer: d.issuer,
460
+ resource: d.resource,
461
+ ...(scope ? { scope } : {}),
462
+ registration,
463
+ client: registration === "pre-registered" ? { client_id: client.client_id } : client,
464
+ tokens: toStored(tokens, at),
465
+ savedAt: at,
466
+ };
467
+ await o.store.set(service, JSON.stringify(rec));
468
+ return {
469
+ issuer: d.issuer,
470
+ registration,
471
+ ...(scope ? { scope } : {}),
472
+ redirectUri: cb.redirectUri,
473
+ ...(rec.tokens?.expires_at ? { expiresAt: rec.tokens.expires_at } : {}),
474
+ refreshToken: Boolean(rec.tokens?.refresh_token),
475
+ service,
476
+ };
477
+ }
478
+ finally {
479
+ await cb.close();
480
+ }
481
+ }
482
+ /**
483
+ * Best-effort RFC 7009 revocation of a record's refresh token (else its access token).
484
+ * Returns why it did not revoke, or undefined when the server accepted it.
485
+ */
486
+ export async function revoke(server, rec, resolve, fetchFn = fetch) {
487
+ const token = rec.tokens?.refresh_token ?? rec.tokens?.access_token;
488
+ if (!token)
489
+ return "no token to revoke";
490
+ try {
491
+ const metadata = await authorizationServerMetadata(rec.issuer, fetchFn);
492
+ const endpoint = revocationEndpoint(metadata);
493
+ if (!endpoint)
494
+ return "the authorization server has no revocation endpoint";
495
+ const client = await clientFor(rec, server.oauth, resolve);
496
+ const body = new URLSearchParams({
497
+ token,
498
+ token_type_hint: rec.tokens?.refresh_token ? "refresh_token" : "access_token",
499
+ client_id: client.client_id,
500
+ });
501
+ const headers = { "Content-Type": "application/x-www-form-urlencoded" };
502
+ if (client.client_secret)
503
+ headers.Authorization = `Basic ${Buffer.from(`${encodeURIComponent(client.client_id)}:${encodeURIComponent(client.client_secret)}`).toString("base64")}`;
504
+ const res = await fetchFn(endpoint, {
505
+ method: "POST",
506
+ headers,
507
+ body,
508
+ redirect: "error",
509
+ signal: AbortSignal.timeout(10_000),
510
+ });
511
+ await res.body?.cancel().catch(() => { });
512
+ return res.ok ? undefined : `the revocation endpoint answered HTTP ${res.status}`;
513
+ }
514
+ catch (err) {
515
+ return scrub(err.message, [token]);
516
+ }
517
+ }
518
+ /** A fingerprint of a stored value, so mcpd can tell whether someone else changed the item. */
519
+ function fp(raw) {
520
+ return raw === undefined ? "-" : createHash("sha256").update(raw).digest("hex");
521
+ }
522
+ /**
523
+ * The login of one server variant inside mcpd: hands out a valid access token, refreshes it
524
+ * when it expires or the server answers 401, and writes a rotated refresh token to the secret
525
+ * store before the new access token is used. When that write fails, the new tokens stay in
526
+ * memory (the old refresh token is already spent) and the write is retried on every later use;
527
+ * a login or logout made meanwhile with `turno mcp login/logout` wins over them.
528
+ */
529
+ export class OAuthSession {
530
+ name;
531
+ variant;
532
+ opts;
533
+ rec;
534
+ /** Fingerprint of what the store held when mcpd last read or wrote it. */
535
+ seen;
536
+ checkedAt = Number.NEGATIVE_INFINITY;
537
+ unpersisted = false;
538
+ discovery;
539
+ queue = Promise.resolve();
540
+ now;
541
+ constructor(name, variant, opts) {
542
+ this.name = name;
543
+ this.variant = variant;
544
+ this.opts = opts;
545
+ this.now = opts.now ?? Date.now;
546
+ }
547
+ get service() {
548
+ return oauthService(this.name, this.variant);
549
+ }
550
+ /** True while rotated tokens exist only in memory. */
551
+ get pendingWrite() {
552
+ return this.unpersisted;
553
+ }
554
+ /**
555
+ * `turno mcp logout` (or login) changed the item: stop trusting the copy in memory, so the
556
+ * next request reads the store at once instead of up to a minute later.
557
+ */
558
+ forget() {
559
+ this.checkedAt = Number.NEGATIVE_INFINITY;
560
+ }
561
+ /**
562
+ * mcpd is stopping: one last try to save rotated tokens that exist only in memory (a login
563
+ * or logout made meanwhile still wins). Returns true when they could not be saved and are
564
+ * lost with this process.
565
+ */
566
+ flush() {
567
+ return this.serial(async () => {
568
+ if (!this.unpersisted || !this.rec)
569
+ return false;
570
+ try {
571
+ await this.load(true);
572
+ }
573
+ catch {
574
+ /* the store cannot be read: the tokens stay unsaved */
575
+ }
576
+ if (!this.unpersisted)
577
+ return false;
578
+ this.opts.log?.(`${this.label}: mcpd stopped before the secret store accepted the rotated OAuth tokens; the next refresh needs a new login`);
579
+ return true;
580
+ });
581
+ }
582
+ get label() {
583
+ return `${this.name}${this.variant === "default" ? "" : `@${this.variant}`}`;
584
+ }
585
+ /** Run one at a time: two calls that see an expired token must not both spend the refresh token. */
586
+ serial(fn) {
587
+ const run = this.queue.then(fn, fn);
588
+ this.queue = run.catch(() => { });
589
+ return run;
590
+ }
591
+ requireStore() {
592
+ const store = this.opts.store();
593
+ if (!store)
594
+ throw new LoginRequiredError(this.name, this.variant, "this machine has no secret store to keep the login in");
595
+ return store;
596
+ }
597
+ /** The current record: memory while it is fresh, else the store (which wins when someone else changed it). */
598
+ async load(force = false) {
599
+ const now = this.now();
600
+ if (!force && !this.unpersisted && this.rec && now - this.checkedAt < (this.opts.recheckMs ?? RECHECK_MS))
601
+ return this.rec;
602
+ const store = this.requireStore();
603
+ let raw;
604
+ try {
605
+ raw = await store.get(this.service);
606
+ }
607
+ catch (err) {
608
+ if (this.rec)
609
+ return this.rec;
610
+ throw new LoginRequiredError(this.name, this.variant, `cannot read ${this.service} from the ${store.label}: ${err.message}`);
611
+ }
612
+ this.checkedAt = now;
613
+ const f = fp(raw);
614
+ if (this.unpersisted && this.rec) {
615
+ if (f === this.seen) {
616
+ // Nobody touched the item since our write failed: try again to save the rotated tokens.
617
+ await this.persist(this.rec);
618
+ return this.rec;
619
+ }
620
+ this.opts.log?.(`${this.label}: a new login or logout replaced the OAuth tokens that were waiting to be saved`);
621
+ this.unpersisted = false;
622
+ }
623
+ if (f !== this.seen) {
624
+ this.rec = parseRecord(raw);
625
+ this.seen = f;
626
+ }
627
+ return this.rec;
628
+ }
629
+ /** Memory first, then the store; a failed write leaves the record pending instead of losing it. */
630
+ async persist(next) {
631
+ this.rec = next;
632
+ this.checkedAt = this.now();
633
+ const raw = JSON.stringify(next);
634
+ try {
635
+ await this.requireStore().set(this.service, raw);
636
+ this.seen = fp(raw);
637
+ if (this.unpersisted)
638
+ this.opts.log?.(`${this.label}: saved the rotated OAuth tokens that were waiting in memory`);
639
+ this.unpersisted = false;
640
+ }
641
+ catch (err) {
642
+ if (!this.unpersisted) {
643
+ this.opts.log?.(`${this.label}: could not save the rotated OAuth tokens to the secret store (${scrub(err.message, [next.tokens?.access_token, next.tokens?.refresh_token])}); keeping them in memory and trying again on the next call`);
644
+ }
645
+ this.unpersisted = true;
646
+ }
647
+ }
648
+ usable(t) {
649
+ return t !== undefined && (t.expires_at === undefined || t.expires_at - EXPIRY_SKEW_MS > this.now());
650
+ }
651
+ checkBinding(server, rec) {
652
+ if (!checkResourceAllowed({
653
+ requestedResource: resourceUrlFromServerUrl(server.url),
654
+ configuredResource: rec.resource,
655
+ })) {
656
+ throw new LoginRequiredError(this.name, this.variant, `the login is for ${rec.resource}, and mcp.toml now says ${server.url}`);
657
+ }
658
+ const id = server.oauth?.clientId;
659
+ if (rec.registration === "pre-registered" ? id !== rec.client.client_id : id !== undefined) {
660
+ throw new LoginRequiredError(this.name, this.variant, "client_id in mcp.toml changed since the login");
661
+ }
662
+ }
663
+ /** A valid access token for a request, refreshing first when it expired. */
664
+ accessToken(server) {
665
+ return this.serial(async () => {
666
+ let rec = await this.load();
667
+ // Without usable tokens, look again at once: `turno mcp login` may have just written them.
668
+ if (!rec?.tokens)
669
+ rec = await this.load(true);
670
+ if (!rec)
671
+ throw new LoginRequiredError(this.name, this.variant, "not logged in");
672
+ this.checkBinding(server, rec);
673
+ if (!rec.tokens)
674
+ throw new LoginRequiredError(this.name, this.variant, "the authorization server rejected the last refresh token");
675
+ if (this.usable(rec.tokens))
676
+ return rec.tokens.access_token;
677
+ return (await this.refresh(server, rec)).access_token;
678
+ });
679
+ }
680
+ /** The server answered 401 to `stale`: refresh unless someone already replaced it. */
681
+ afterUnauthorized(server, stale) {
682
+ return this.serial(async () => {
683
+ const rec = await this.load(true);
684
+ if (!rec?.tokens)
685
+ throw new LoginRequiredError(this.name, this.variant, rec ? "the authorization server rejected the last refresh token" : "not logged in");
686
+ this.checkBinding(server, rec);
687
+ if (rec.tokens.access_token !== stale && this.usable(rec.tokens))
688
+ return rec.tokens.access_token;
689
+ return (await this.refresh(server, rec)).access_token;
690
+ });
691
+ }
692
+ async refresh(server, rec, retried = false) {
693
+ const tokens = rec.tokens;
694
+ const refreshToken = tokens.refresh_token;
695
+ if (!refreshToken)
696
+ throw new LoginRequiredError(this.name, this.variant, "the access token expired and the server gave no refresh token");
697
+ const fetchFn = this.opts.fetchFn ?? fetch;
698
+ let d;
699
+ try {
700
+ d = this.discovery ?? (await discover(server, fetchFn));
701
+ }
702
+ catch (err) {
703
+ throw new Error(`${this.label}: cannot refresh the OAuth token: ${err.message}`);
704
+ }
705
+ if (!sameIssuer(d.issuer, rec.issuer)) {
706
+ // Spec: credentials are bound to the authorization server that issued them.
707
+ this.discovery = undefined;
708
+ throw new LoginRequiredError(this.name, this.variant, `the server now uses the authorization server ${d.issuer}`);
709
+ }
710
+ this.discovery = d;
711
+ let fresh;
712
+ try {
713
+ fresh = await refreshAuthorization(rec.issuer, {
714
+ metadata: d.metadata,
715
+ clientInformation: await clientFor(rec, server.oauth, this.opts.resolve),
716
+ refreshToken,
717
+ resource: rec.resource,
718
+ fetchFn,
719
+ });
720
+ }
721
+ catch (err) {
722
+ if (err instanceof InvalidGrantError ||
723
+ err instanceof InvalidClientError ||
724
+ err instanceof UnauthorizedClientError) {
725
+ // A login in another process may have replaced the token we hold: read the store again once.
726
+ const latest = retried ? undefined : await this.load(true);
727
+ if (latest?.tokens?.refresh_token && latest.tokens.refresh_token !== refreshToken) {
728
+ return this.usable(latest.tokens) ? latest.tokens : this.refresh(server, latest, true);
729
+ }
730
+ const { tokens: _dropped, ...rest } = rec;
731
+ await this.persist({ ...rest, savedAt: this.now() });
732
+ this.opts.log?.(`${this.label}: the authorization server rejected the refresh token (${err.name}); a new login is needed`);
733
+ throw new LoginRequiredError(this.name, this.variant, "the authorization server rejected the refresh token (revoked or expired)");
734
+ }
735
+ // Network trouble or a server error: keep the refresh token for the next try.
736
+ this.discovery = undefined;
737
+ throw new Error(`${this.label}: cannot refresh the OAuth token: ${scrub(err.message, [refreshToken, tokens.access_token])}`);
738
+ }
739
+ const next = { ...rec, tokens: toStored(fresh, this.now()), savedAt: this.now() };
740
+ // Persist before the new access token is used: with rotation, the old refresh token is spent.
741
+ await this.persist(next);
742
+ this.opts.log?.(`${this.label}: refreshed the OAuth access token${next.tokens.refresh_token !== refreshToken ? " (refresh token rotated)" : ""}`);
743
+ return next.tokens;
744
+ }
745
+ }
746
+ /** One session per server variant, shared by every instance and profile that uses it. */
747
+ export class OAuthSessions {
748
+ opts;
749
+ sessions = new Map();
750
+ constructor(opts) {
751
+ this.opts = opts;
752
+ }
753
+ get(name, variant) {
754
+ const key = `${name}@${variant}`;
755
+ let s = this.sessions.get(key);
756
+ if (!s) {
757
+ s = new OAuthSession(name, variant, typeof this.opts === "function" ? this.opts(name, variant) : this.opts);
758
+ this.sessions.set(key, s);
759
+ }
760
+ return s;
761
+ }
762
+ /** Forget what memory holds for these variants of a server (every variant when none are named). */
763
+ forget(name, variants) {
764
+ let n = 0;
765
+ for (const s of this.sessions.values()) {
766
+ if (s.name !== name || (variants && !variants.includes(s.variant)))
767
+ continue;
768
+ s.forget();
769
+ n++;
770
+ }
771
+ return n;
772
+ }
773
+ /** Save what is still only in memory; the labels whose tokens could not be saved. */
774
+ async flush() {
775
+ const lost = [];
776
+ for (const s of this.sessions.values()) {
777
+ if (await s.flush().catch(() => true))
778
+ lost.push(s.variant === "default" ? s.name : `${s.name}@${s.variant}`);
779
+ }
780
+ return lost;
781
+ }
782
+ }
783
+ function withBearer(init, token) {
784
+ const headers = new Headers(init?.headers);
785
+ headers.set("Authorization", `Bearer ${token}`);
786
+ return { ...init, headers };
787
+ }
788
+ /**
789
+ * The fetch an OAuth server's transport uses: adds the access token to requests for the
790
+ * server's own origin (never anywhere else), and on a 401 refreshes once and retries.
791
+ */
792
+ export function oauthFetch(session, server, base = fetch) {
793
+ return async (url, init) => {
794
+ const def = server();
795
+ if (new URL(String(url)).origin !== new URL(def.url).origin)
796
+ return base(url, init);
797
+ const token = await session.accessToken(def);
798
+ const res = await base(url, withBearer(init, token));
799
+ if (res.status === 403) {
800
+ const p = extractWWWAuthenticateParams(res);
801
+ if (p.error === "insufficient_scope") {
802
+ await res.body?.cancel().catch(() => { });
803
+ const who = session.variant === "default" ? "" : ` --profile ${session.variant}`;
804
+ throw new Error(`${def.name} needs more scopes${p.scope ? ` (${p.scope})` : ""}: run turno mcp login ${def.name}${who}${p.scope ? ` --scope "${p.scope}"` : ""}`);
805
+ }
806
+ return res;
807
+ }
808
+ if (res.status !== 401)
809
+ return res;
810
+ await res.body?.cancel().catch(() => { });
811
+ const again = await session.afterUnauthorized(def, token);
812
+ const retry = await base(url, withBearer(init, again));
813
+ if (retry.status === 401) {
814
+ await retry.body?.cancel().catch(() => { });
815
+ throw new LoginRequiredError(session.name, session.variant, "the server rejected a freshly refreshed token");
816
+ }
817
+ return retry;
818
+ };
819
+ }
820
+ export async function loginState(store, name, variant, now = Date.now()) {
821
+ if (!store)
822
+ return { state: "unknown" };
823
+ let raw;
824
+ try {
825
+ raw = await store.get(oauthService(name, variant));
826
+ }
827
+ catch {
828
+ return { state: "unknown" };
829
+ }
830
+ const rec = parseRecord(raw);
831
+ if (!rec)
832
+ return { state: "not logged in" };
833
+ if (!rec.tokens)
834
+ return { state: "login required" };
835
+ const t = rec.tokens;
836
+ const expired = t.expires_at !== undefined && t.expires_at <= now;
837
+ if (expired && !t.refresh_token)
838
+ return { state: "login required" };
839
+ return {
840
+ state: expired ? "expired" : "logged in",
841
+ ...(t.expires_at ? { expiresAt: t.expires_at } : {}),
842
+ refresh: Boolean(t.refresh_token),
843
+ };
844
+ }
845
+ //# sourceMappingURL=oauth.js.map