@draht/mcp 2026.10.31 → 2026.11.5-1

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 (79) hide show
  1. package/dist/config.d.ts +126 -0
  2. package/dist/config.d.ts.map +1 -0
  3. package/dist/config.js +167 -0
  4. package/dist/config.js.map +1 -0
  5. package/dist/index.d.ts +5 -0
  6. package/dist/index.d.ts.map +1 -1
  7. package/dist/index.js +5 -0
  8. package/dist/index.js.map +1 -1
  9. package/dist/input-schema.d.ts +7 -0
  10. package/dist/input-schema.d.ts.map +1 -0
  11. package/dist/input-schema.js +13 -0
  12. package/dist/input-schema.js.map +1 -0
  13. package/dist/naming.d.ts +18 -0
  14. package/dist/naming.d.ts.map +1 -0
  15. package/dist/naming.js +29 -0
  16. package/dist/naming.js.map +1 -0
  17. package/dist/oauth/auth-provider.d.ts +63 -0
  18. package/dist/oauth/auth-provider.d.ts.map +1 -0
  19. package/dist/oauth/auth-provider.js +116 -0
  20. package/dist/oauth/auth-provider.js.map +1 -0
  21. package/dist/oauth/callback.d.ts.map +1 -1
  22. package/dist/oauth/callback.js +4 -0
  23. package/dist/oauth/callback.js.map +1 -1
  24. package/dist/oauth/client-metadata-base.d.ts +16 -0
  25. package/dist/oauth/client-metadata-base.d.ts.map +1 -0
  26. package/dist/oauth/client-metadata-base.js +27 -0
  27. package/dist/oauth/client-metadata-base.js.map +1 -0
  28. package/dist/oauth/client-settings.d.ts +131 -0
  29. package/dist/oauth/client-settings.d.ts.map +1 -0
  30. package/dist/oauth/client-settings.js +158 -0
  31. package/dist/oauth/client-settings.js.map +1 -0
  32. package/dist/oauth/errors.d.ts +7 -0
  33. package/dist/oauth/errors.d.ts.map +1 -1
  34. package/dist/oauth/errors.js +10 -0
  35. package/dist/oauth/errors.js.map +1 -1
  36. package/dist/oauth/flow.d.ts +33 -0
  37. package/dist/oauth/flow.d.ts.map +1 -1
  38. package/dist/oauth/flow.js +64 -10
  39. package/dist/oauth/flow.js.map +1 -1
  40. package/dist/oauth/index.d.ts +7 -2
  41. package/dist/oauth/index.d.ts.map +1 -1
  42. package/dist/oauth/index.js +6 -1
  43. package/dist/oauth/index.js.map +1 -1
  44. package/dist/oauth/loopback.d.ts +55 -0
  45. package/dist/oauth/loopback.d.ts.map +1 -0
  46. package/dist/oauth/loopback.js +106 -0
  47. package/dist/oauth/loopback.js.map +1 -0
  48. package/dist/oauth/provider.d.ts +4 -1
  49. package/dist/oauth/provider.d.ts.map +1 -1
  50. package/dist/oauth/provider.js +9 -3
  51. package/dist/oauth/provider.js.map +1 -1
  52. package/dist/oauth/sign-in.d.ts +82 -0
  53. package/dist/oauth/sign-in.d.ts.map +1 -0
  54. package/dist/oauth/sign-in.js +209 -0
  55. package/dist/oauth/sign-in.js.map +1 -0
  56. package/dist/oauth/types.d.ts +1 -0
  57. package/dist/oauth/types.d.ts.map +1 -1
  58. package/dist/oauth/types.js +8 -4
  59. package/dist/oauth/types.js.map +1 -1
  60. package/dist/output-limit.d.ts +24 -0
  61. package/dist/output-limit.d.ts.map +1 -0
  62. package/dist/output-limit.js +58 -0
  63. package/dist/output-limit.js.map +1 -0
  64. package/dist/transports/lines.d.ts +34 -0
  65. package/dist/transports/lines.d.ts.map +1 -0
  66. package/dist/transports/lines.js +85 -0
  67. package/dist/transports/lines.js.map +1 -0
  68. package/dist/transports/pipe.d.ts +49 -0
  69. package/dist/transports/pipe.d.ts.map +1 -0
  70. package/dist/transports/pipe.js +96 -0
  71. package/dist/transports/pipe.js.map +1 -0
  72. package/dist/transports/stdio.d.ts +1 -4
  73. package/dist/transports/stdio.d.ts.map +1 -1
  74. package/dist/transports/stdio.js +20 -51
  75. package/dist/transports/stdio.js.map +1 -1
  76. package/dist/transports/streamable-http.d.ts.map +1 -1
  77. package/dist/transports/streamable-http.js +77 -11
  78. package/dist/transports/streamable-http.js.map +1 -1
  79. package/package.json +3 -4
@@ -0,0 +1,116 @@
1
+ /**
2
+ * The auth provider for connections to an OAuth-protected MCP server: it sends the stored access token
3
+ * and refreshes it, but never starts a browser flow. When the user has to sign in, it fails with
4
+ * `McpOAuthAuthorizationRequiredError` and the application runs `startMcpSignIn`.
5
+ */
6
+ import { parseClientMetadataBaseUrl } from "./client-metadata-base.js";
7
+ import { clientMetadataBaseUrl, createOAuthClientProvider, DEFAULT_REDIRECT_URL, loopbackSettings, matchesClient, registeredRedirectUrls, timedFetch, } from "./client-settings.js";
8
+ import { parseWwwAuthenticate } from "./discovery.js";
9
+ import { McpOAuthAuthorizationRequiredError } from "./errors.js";
10
+ import { authorizeMcp } from "./flow.js";
11
+ /** Access tokens this close to expiry are refreshed before they are sent. */
12
+ const REFRESH_SKEW_MS = 30_000;
13
+ /**
14
+ * Auth provider for MCP connections: sends the stored access token and refreshes it when it is about
15
+ * to expire or after a 401. Throws `McpOAuthAuthorizationRequiredError` when the user has to sign in,
16
+ * including when the server asks for more scope (`insufficient_scope`). `onChallenge` receives the
17
+ * server's `WWW-Authenticate` challenge so sign-in can use its resource metadata URL and scope.
18
+ * `settings` is only called when a refresh is needed, so a secret that fails to resolve fails the
19
+ * refresh instead of the whole connection setup, and reading a cached token never resolves one.
20
+ *
21
+ * Many servers rotate refresh tokens, so two refreshes with the same refresh token lose the grant.
22
+ * Requests in this process share one refresh, and other processes are kept out by the store's
23
+ * refresh lock, held from reading the tokens to saving new ones. Tokens that changed meanwhile
24
+ * (another process refreshed them, or the user signed in) are used without refreshing.
25
+ *
26
+ * draht: stored tokens are only sent and refreshed when they belong to the client `clientMetadataBaseUrl`
27
+ * names; tokens of a former registration mode or metadata base need a new sign-in.
28
+ */
29
+ export function createMcpAuthProvider(options) {
30
+ const { serverUrl, store, redirectUrl } = options;
31
+ const baseUrl = options.clientMetadataBaseUrl === undefined
32
+ ? undefined
33
+ : parseClientMetadataBaseUrl(options.clientMetadataBaseUrl);
34
+ if (options.clientMetadataBaseUrl !== undefined && !baseUrl) {
35
+ throw new Error("oauth.clientMetadataBaseUrl must be an absolute HTTPS URL without userinfo, query, or fragment");
36
+ }
37
+ const owns = (state) => matchesClient(state, serverUrl, baseUrl);
38
+ let refreshing;
39
+ /** Replace `staleToken`, the access token that expired or was rejected. */
40
+ const refresh = (staleToken, fetch = globalThis.fetch, challenge) => {
41
+ refreshing ??= store
42
+ .withRefreshLock(async () => {
43
+ const state = await store.load();
44
+ if (!owns(state))
45
+ throw new McpOAuthAuthorizationRequiredError();
46
+ if (state?.tokens?.access_token !== staleToken)
47
+ return;
48
+ if (!state?.tokens?.refresh_token)
49
+ throw new McpOAuthAuthorizationRequiredError();
50
+ const client = { ...options, settings: options.settings() };
51
+ const result = await refreshStoredTokens(client, state, { fetch, challenge, redirectUrl });
52
+ if (result === "REDIRECT")
53
+ throw new McpOAuthAuthorizationRequiredError();
54
+ })
55
+ .finally(() => {
56
+ refreshing = undefined;
57
+ });
58
+ return refreshing;
59
+ };
60
+ return {
61
+ token: async () => {
62
+ await refreshing?.catch(() => undefined);
63
+ const state = await store.load();
64
+ if (!owns(state))
65
+ return undefined;
66
+ const token = state?.tokens?.access_token;
67
+ const expired = state?.tokensExpireAt !== undefined && state.tokensExpireAt - REFRESH_SKEW_MS <= Date.now();
68
+ if (!expired || !state?.tokens?.refresh_token)
69
+ return token;
70
+ // Failures fall through: the request goes out with the old token and a 401 decides what happens.
71
+ await refresh(token).catch(() => undefined);
72
+ const refreshed = await store.load();
73
+ return owns(refreshed) ? refreshed?.tokens?.access_token : undefined;
74
+ },
75
+ onUnauthorized: async (context) => {
76
+ const challenge = parseWwwAuthenticate(context.response.headers.get("www-authenticate"));
77
+ options.onChallenge(challenge);
78
+ // A refresh keeps the granted scope, so more scope needs a new sign-in.
79
+ if (challenge.error === "insufficient_scope")
80
+ throw new McpOAuthAuthorizationRequiredError();
81
+ await refresh(context.token, context.fetch, challenge);
82
+ },
83
+ settled: async () => {
84
+ await refreshing?.catch(() => undefined);
85
+ },
86
+ };
87
+ }
88
+ /**
89
+ * Refresh the tokens of `state` with the stored client (or the document it signed in with), or report
90
+ * `REDIRECT` when that is not possible. `options.redirectUrl` is a redirect URI the application signs in
91
+ * with, tried before the loopback ones of the settings and the stored client. Never registers a client or
92
+ * prepares an authorization request, so a pending sign-in stays usable. Call while holding the store's
93
+ * refresh lock. Not cancellable: a refresh the server answered may have rotated the refresh token, so its
94
+ * answer must be saved.
95
+ * draht: tokens that do not belong to the client `client.settings` identify as are not refreshed.
96
+ */
97
+ export async function refreshStoredTokens(client, state, options = {}) {
98
+ if (!matchesClient(state, client.serverUrl, clientMetadataBaseUrl(client.settings)))
99
+ return "REDIRECT";
100
+ // Refreshing never redirects the user; the redirect URI only decides whether tokens without a stored
101
+ // client can be refreshed with a Client ID Metadata Document, so any URI the documents list works.
102
+ const candidates = [
103
+ options.redirectUrl,
104
+ loopbackSettings(client.settings).fixedRedirectUrl,
105
+ registeredRedirectUrls(state.clientInformation)[0],
106
+ ].filter((url) => url !== undefined);
107
+ const redirectUrl = candidates.find((url) => client.clientMetadataDocuments?.listsRedirectUrl(url)) ?? DEFAULT_REDIRECT_URL;
108
+ return authorizeMcp(createOAuthClientProvider(client, redirectUrl), {
109
+ serverUrl: client.serverUrl,
110
+ resourceMetadataUrl: options.challenge?.resourceMetadataUrl,
111
+ authorizationServerMetadataUrl: client.settings.authServerMetadataUrl,
112
+ fetch: timedFetch(options.fetch),
113
+ refreshOnly: true,
114
+ });
115
+ }
116
+ //# sourceMappingURL=auth-provider.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"auth-provider.js","sourceRoot":"","sources":["../../src/oauth/auth-provider.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAGH,OAAO,EAAE,0BAA0B,EAAE,MAAM,2BAA2B,CAAC;AACvE,OAAO,EACN,qBAAqB,EACrB,yBAAyB,EACzB,oBAAoB,EACpB,gBAAgB,EAGhB,aAAa,EACb,sBAAsB,EACtB,UAAU,GACV,MAAM,sBAAsB,CAAC;AAC9B,OAAO,EAAE,oBAAoB,EAAE,MAAM,gBAAgB,CAAC;AAC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O,YAAY,CAAC,yBAAyB,CAAC,MAAM,EAAE,WAAW,CAAC,EAAE;QACnE,SAAS,EAAE,MAAM,CAAC,SAAS;QAC3B,mBAAmB,EAAE,OAAO,CAAC,SAAS,EAAE,mBAAmB;QAC3D,8BAA8B,EAAE,MAAM,CAAC,QAAQ,CAAC,qBAAqB;QACrE,KAAK,EAAE,UAAU,CAAC,OAAO,CAAC,KAAK,CAAC;QAChC,WAAW,EAAE,IAAI;KACjB,CAAC,CAAC;AACJ,CAAC","sourcesContent":["/**\n * The auth provider for connections to an OAuth-protected MCP server: it sends the stored access token\n * and refreshes it, but never starts a browser flow. When the user has to sign in, it fails with\n * `McpOAuthAuthorizationRequiredError` and the application runs `startMcpSignIn`.\n */\n\nimport type { AuthProvider, McpFetch } from \"../auth-provider.ts\";\nimport { parseClientMetadataBaseUrl } from \"./client-metadata-base.ts\";\nimport {\n\tclientMetadataBaseUrl,\n\tcreateOAuthClientProvider,\n\tDEFAULT_REDIRECT_URL,\n\tloopbackSettings,\n\ttype McpOAuthClientOptions,\n\ttype McpOAuthSettings,\n\tmatchesClient,\n\tregisteredRedirectUrls,\n\ttimedFetch,\n} from \"./client-settings.ts\";\nimport { parseWwwAuthenticate } from \"./discovery.ts\";\nimport { McpOAuthAuthorizationRequiredError } from \"./errors.ts\";\nimport { authorizeMcp, type OAuthFlowResult } from \"./flow.ts\";\nimport type { McpOAuthState } from \"./provider.ts\";\nimport type { OAuthChallenge } from \"./types.ts\";\n\n/** An `AuthProvider` that can say when its refreshes have finished. */\nexport interface McpAuthProvider extends AuthProvider {\n\t/** Resolves when no refresh is running, so shutdown does not drop rotated tokens before they are saved. */\n\tsettled(): Promise<void>;\n}\n\n/** Access tokens this close to expiry are refreshed before they are sent. */\nconst REFRESH_SKEW_MS = 30_000;\n\n/**\n * Auth provider for MCP connections: sends the stored access token and refreshes it when it is about\n * to expire or after a 401. Throws `McpOAuthAuthorizationRequiredError` when the user has to sign in,\n * including when the server asks for more scope (`insufficient_scope`). `onChallenge` receives the\n * server's `WWW-Authenticate` challenge so sign-in can use its resource metadata URL and scope.\n * `settings` is only called when a refresh is needed, so a secret that fails to resolve fails the\n * refresh instead of the whole connection setup, and reading a cached token never resolves one.\n *\n * Many servers rotate refresh tokens, so two refreshes with the same refresh token lose the grant.\n * Requests in this process share one refresh, and other processes are kept out by the store's\n * refresh lock, held from reading the tokens to saving new ones. Tokens that changed meanwhile\n * (another process refreshed them, or the user signed in) are used without refreshing.\n *\n * draht: stored tokens are only sent and refreshed when they belong to the client `clientMetadataBaseUrl`\n * names; tokens of a former registration mode or metadata base need a new sign-in.\n */\nexport function createMcpAuthProvider(\n\toptions: Omit<McpOAuthClientOptions, \"settings\"> & {\n\t\t/**\n\t\t * draht: the client stored tokens must belong to: the operator's validated `clientMetadataBaseUrl` with\n\t\t * `cimd`, `undefined` otherwise. Passed apart from `settings` so reading a cached token never calls\n\t\t * `settings`, which may resolve secrets. Must name the same base as `settings().clientMetadataBaseUrl`;\n\t\t * a refresh with settings that name another one is refused.\n\t\t */\n\t\tclientMetadataBaseUrl: string | undefined;\n\t\tsettings: () => McpOAuthSettings;\n\t\tonChallenge: (challenge: OAuthChallenge) => void;\n\t\t/**\n\t\t * A redirect URI the application signs in with, such as its https callback route. Refreshing tokens\n\t\t * from a sign-in with a Client ID Metadata Document needs a redirect URI the documents list; a\n\t\t * refresh never redirects, so any listed one works. Default: the loopback redirect URI of `settings`.\n\t\t */\n\t\tredirectUrl?: string;\n\t},\n): McpAuthProvider {\n\tconst { serverUrl, store, redirectUrl } = options;\n\tconst baseUrl =\n\t\toptions.clientMetadataBaseUrl === undefined\n\t\t\t? undefined\n\t\t\t: parseClientMetadataBaseUrl(options.clientMetadataBaseUrl);\n\tif (options.clientMetadataBaseUrl !== undefined && !baseUrl) {\n\t\tthrow new Error(\"oauth.clientMetadataBaseUrl must be an absolute HTTPS URL without userinfo, query, or fragment\");\n\t}\n\tconst owns = (state: McpOAuthState | undefined) => matchesClient(state, serverUrl, baseUrl);\n\tlet refreshing: Promise<void> | undefined;\n\n\t/** Replace `staleToken`, the access token that expired or was rejected. */\n\tconst refresh = (staleToken: string | undefined, fetch: McpFetch = globalThis.fetch, challenge?: OAuthChallenge) => {\n\t\trefreshing ??= store\n\t\t\t.withRefreshLock(async () => {\n\t\t\t\tconst state = await store.load();\n\t\t\t\tif (!owns(state)) throw new McpOAuthAuthorizationRequiredError();\n\t\t\t\tif (state?.tokens?.access_token !== staleToken) return;\n\t\t\t\tif (!state?.tokens?.refresh_token) throw new McpOAuthAuthorizationRequiredError();\n\t\t\t\tconst client = { ...options, settings: options.settings() };\n\t\t\t\tconst result = await refreshStoredTokens(client, state, { fetch, challenge, redirectUrl });\n\t\t\t\tif (result === \"REDIRECT\") throw new McpOAuthAuthorizationRequiredError();\n\t\t\t})\n\t\t\t.finally(() => {\n\t\t\t\trefreshing = undefined;\n\t\t\t});\n\t\treturn refreshing;\n\t};\n\n\treturn {\n\t\ttoken: async () => {\n\t\t\tawait refreshing?.catch(() => undefined);\n\t\t\tconst state = await store.load();\n\t\t\tif (!owns(state)) return undefined;\n\t\t\tconst token = state?.tokens?.access_token;\n\t\t\tconst expired = state?.tokensExpireAt !== undefined && state.tokensExpireAt - REFRESH_SKEW_MS <= Date.now();\n\t\t\tif (!expired || !state?.tokens?.refresh_token) return token;\n\t\t\t// Failures fall through: the request goes out with the old token and a 401 decides what happens.\n\t\t\tawait refresh(token).catch(() => undefined);\n\t\t\tconst refreshed = await store.load();\n\t\t\treturn owns(refreshed) ? refreshed?.tokens?.access_token : undefined;\n\t\t},\n\t\tonUnauthorized: async (context) => {\n\t\t\tconst challenge = parseWwwAuthenticate(context.response.headers.get(\"www-authenticate\"));\n\t\t\toptions.onChallenge(challenge);\n\t\t\t// A refresh keeps the granted scope, so more scope needs a new sign-in.\n\t\t\tif (challenge.error === \"insufficient_scope\") throw new McpOAuthAuthorizationRequiredError();\n\t\t\tawait refresh(context.token, context.fetch, challenge);\n\t\t},\n\t\tsettled: async () => {\n\t\t\tawait refreshing?.catch(() => undefined);\n\t\t},\n\t};\n}\n\n/**\n * Refresh the tokens of `state` with the stored client (or the document it signed in with), or report\n * `REDIRECT` when that is not possible. `options.redirectUrl` is a redirect URI the application signs in\n * with, tried before the loopback ones of the settings and the stored client. Never registers a client or\n * prepares an authorization request, so a pending sign-in stays usable. Call while holding the store's\n * refresh lock. Not cancellable: a refresh the server answered may have rotated the refresh token, so its\n * answer must be saved.\n * draht: tokens that do not belong to the client `client.settings` identify as are not refreshed.\n */\nexport async function refreshStoredTokens(\n\tclient: McpOAuthClientOptions,\n\tstate: McpOAuthState,\n\toptions: { fetch?: McpFetch; challenge?: OAuthChallenge; redirectUrl?: string } = {},\n): Promise<OAuthFlowResult> {\n\tif (!matchesClient(state, client.serverUrl, clientMetadataBaseUrl(client.settings))) return \"REDIRECT\";\n\t// Refreshing never redirects the user; the redirect URI only decides whether tokens without a stored\n\t// client can be refreshed with a Client ID Metadata Document, so any URI the documents list works.\n\tconst candidates = [\n\t\toptions.redirectUrl,\n\t\tloopbackSettings(client.settings).fixedRedirectUrl,\n\t\tregisteredRedirectUrls(state.clientInformation)[0],\n\t].filter((url) => url !== undefined);\n\tconst redirectUrl =\n\t\tcandidates.find((url) => client.clientMetadataDocuments?.listsRedirectUrl(url)) ?? DEFAULT_REDIRECT_URL;\n\treturn authorizeMcp(createOAuthClientProvider(client, redirectUrl), {\n\t\tserverUrl: client.serverUrl,\n\t\tresourceMetadataUrl: options.challenge?.resourceMetadataUrl,\n\t\tauthorizationServerMetadataUrl: client.settings.authServerMetadataUrl,\n\t\tfetch: timedFetch(options.fetch),\n\t\trefreshOnly: true,\n\t});\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"callback.d.ts","sourceRoot":"","sources":["../../src/oauth/callback.ts"],"names":[],"mappings":"AAEA,MAAM,WAAW,aAAa;IAC7B,IAAI,EAAE,MAAM,CAAC;IACb,KAAK,EAAE,MAAM,CAAC;IACd,GAAG,CAAC,EAAE,MAA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 @@ export class OAuthCallbackServer {
88
88
  this.reply(response, 400, { ok: false, message: "Invalid or expired OAuth state" });
89
89
  return;
90
90
  }
91
+ // Everything above (Host, origin, unknown path, unknown state) fails without touching the pending
92
+ // sign-in. From here on the state is consumed, by design also on the wrong one of this server's paths:
93
+ // a valid state on another redirect URI means an authorization server mixed up the response (RFC 9700
94
+ // section 4.4.2.2), so the sign-in fails instead of waiting for a second response with the same state.
91
95
  clearTimeout(pending.timer);
92
96
  this.pending.delete(state);
93
97
  if (pending.path !== undefined && url.pathname !== pending.path) {
@@ -1 +1 @@
1
- {"version":3,"file":"callback.js","sourceRoot":"","sources":["../../src/oauth/callback.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,YAAY,EAAoC,MAAM,WAAW,CAAC;AA4B3E,SAAS,SAAS,CAAC,IAAuB;IACzC,IAAI,IAAI,CAAC,EAAE;QAAE,OAAO,oDAAoD,CAAC;IACzE,OAAO,IAAI,CAAC,OAAO,CAAC,CAAC,CAAC,GAAG,IAAI,CAAC,OAAO,OAAO,IAAI,CAAC,OAAO,EAAE,CAAC,CAAC,CAAC,IAAI,CAAC,OAAO,CAAC;AAC3E,CAAC;AAED,MAAM,OAAO,mBAAmB;IACtB,WAAW,CAAS;IACrB,MAAM,CAAS;IACf,KAAK,CAAW;IAChB,SAAS,CAAS;IAClB,UAAU,CAAoD;IAC9D,OAAO,GAAG,IAAI,GAAG,EAQtB,CAAC;IAEJ,YACC,MAAc,EACd,WAAmB,EACnB,KAAe,EACf,SAAiB,EACjB,UAA6D;QAE7D,IAAI,CAAC,MAAM,GAAG,MAAM,CAAC;QACrB,IAAI,CAAC,WAAW,GAAG,WAAW,CAAC;QAC/B,IAAI,CAAC,KAAK,GAAG,KAAK,CAAC;QACnB,IAAI,CAAC,SAAS,GAAG,SAAS,CAAC;QAC3B,IAAI,CAAC,UAAU,GAAG,UAAU,CAAC;IAC9B,CAAC;IAED,MAAM,CAAC,KAAK,CAAC,MAAM,CAAC,OAAO,GAA+B,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AC;YACH,OAAO;QACR,CAAC;QACD,MAAM,IAAI,GAAG,GAAG,CAAC,YAAY,CAAC,GAAG,CAAC,MAAM,CAAC,CAAC;QAC1C,IAAI,CAAC,IAAI,EAAE,CAAC;YACX,OAAO,CAAC,MAAM,CAAC,IAAI,KAAK,CAAC,sDAAsD,CAAC,CAAC,CAAC;YAClF,IAAI,CAAC,KAAK,CAAC,QAAQ,EAAE,GAAG,EAAE,EAAE,EAAE,EAAE,KAAK,EAAE,OAAO,EAAE,4BAA4B,EAAE,CAAC,CAAC;YAChF,OAAO;QACR,CAAC;QACD,MAAM,GAAG,GAAG,GAAG,CAAC,YAAY,CAAC,GAAG,CAAC,KAAK,CAAC,CAAC;QACxC,OAAO,CAAC,OAAO,CAAC,EAAE,IAAI,EAAE,KAAK,EAAE,GAAG,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,GAAG,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC,EAAE,CAAC,CAAC;QAC1D,IAAI,CAAC,KAAK,CAAC,QAAQ,EAAE,GAAG,EAAE,EAAE,EAAE,EAAE,IAAI,EAAE,CAAC,CAAC;IACzC,CAAC;CACD","sourcesContent":["import { createServer, type Server, type ServerResponse } from \"node:http\";\n\nexport interface OAuthCallback {\n\tcode: string;\n\tstate: string;\n\tiss?: string;\n}\n\n/** Outcome shown on the browser page after the redirect. */\nexport type OAuthCallbackPage = { ok: true } | { ok: false; message: string; details?: string };\n\nexport interface OAuthCallbackServerOptions {\n\t/** Address to listen on. Default: `127.0.0.1`. */\n\thost?: string;\n\t/**\n\t * Host name in `redirectUrl`, for example `localhost` for a client registered with it while\n\t * listening on `127.0.0.1`. Default: `host`.\n\t */\n\tredirectHost?: string;\n\tport?: number;\n\tpath?: string;\n\t/** More paths that receive the callback, for example a server-specific path of a redirect URI. */\n\textraPaths?: string[];\n\ttimeoutMs?: number;\n\t/** Render the browser page as HTML. Default: a plain-text message. */\n\trenderPage?: (page: OAuthCallbackPage) => string;\n}\n\nfunction plainText(page: OAuthCallbackPage): string {\n\tif (page.ok) return \"Authorization complete. You may close this window.\";\n\treturn page.details ? `${page.message}\\n\\n${page.details}` : page.message;\n}\n\nexport class OAuthCallbackServer {\n\treadonly redirectUrl: string;\n\tprivate server: Server;\n\tprivate paths: string[];\n\tprivate timeoutMs: number;\n\tprivate renderPage: ((page: OAuthCallbackPage) => string) | undefined;\n\tprivate pending = new Map<\n\t\tstring,\n\t\t{\n\t\t\tresolve: (callback: OAuthCallback) => void;\n\t\t\treject: (error: Error) => void;\n\t\t\ttimer: ReturnType<typeof setTimeout>;\n\t\t\tpath: string | undefined;\n\t\t}\n\t>();\n\n\tprivate constructor(\n\t\tserver: Server,\n\t\tredirectUrl: string,\n\t\tpaths: string[],\n\t\ttimeoutMs: number,\n\t\trenderPage: ((page: OAuthCallbackPage) => string) | undefined,\n\t) {\n\t\tthis.server = server;\n\t\tthis.redirectUrl = redirectUrl;\n\t\tthis.paths = paths;\n\t\tthis.timeoutMs = timeoutMs;\n\t\tthis.renderPage = renderPage;\n\t}\n\n\tstatic async listen(options: OAuthCallbackServerOptions = {}): Promise<OAuthCallbackServer> {\n\t\tconst host = options.host ?? \"127.0.0.1\";\n\t\tconst redirectHost = options.redirectHost ?? host;\n\t\tconst path = options.path ?? \"/callback\";\n\t\tlet instance: OAuthCallbackServer | undefined;\n\t\tconst server = createServer((request, response) =>\n\t\t\tinstance?.handle(request.url ?? \"/\", request.headers.host, response),\n\t\t);\n\t\tawait new Promise<void>((resolve, reject) => {\n\t\t\tserver.once(\"error\", reject);\n\t\t\tserver.listen(options.port ?? 0, host, () => {\n\t\t\t\tserver.off(\"error\", reject);\n\t\t\t\tresolve();\n\t\t\t});\n\t\t});\n\t\tconst address = server.address();\n\t\tif (!address || typeof address === \"string\") throw new Error(\"OAuth callback server did not bind to TCP\");\n\t\tinstance = new OAuthCallbackServer(\n\t\t\tserver,\n\t\t\t`http://${redirectHost.includes(\":\") ? `[${redirectHost}]` : redirectHost}:${address.port}${path}`,\n\t\t\t[path, ...(options.extraPaths ?? [])],\n\t\t\toptions.timeoutMs ?? 5 * 60_000,\n\t\t\toptions.renderPage,\n\t\t);\n\t\treturn instance;\n\t}\n\n\t/**\n\t * Wait for the authorization response with `state`. With `path`, a response on another path fails, so\n\t * a server-specific redirect URI can tell authorization servers apart (RFC 9700 section 4.4.2.2).\n\t */\n\twaitForCallback(state: string, path?: string): Promise<OAuthCallback> {\n\t\tif (this.pending.has(state)) throw new Error(\"OAuth state is already pending\");\n\t\treturn new Promise((resolve, reject) => {\n\t\t\tconst timer = setTimeout(() => {\n\t\t\t\tthis.pending.delete(state);\n\t\t\t\treject(new Error(\"OAuth callback timed out\"));\n\t\t\t}, this.timeoutMs);\n\t\t\tthis.pending.set(state, { resolve, reject, timer, path });\n\t\t});\n\t}\n\n\tasync close(): Promise<void> {\n\t\tfor (const pending of this.pending.values()) {\n\t\t\tclearTimeout(pending.timer);\n\t\t\tpending.reject(new Error(\"OAuth callback server closed\"));\n\t\t}\n\t\tthis.pending.clear();\n\t\tawait new Promise<void>((resolve, reject) => {\n\t\t\tthis.server.close((error) => (error ? reject(error) : resolve()));\n\t\t});\n\t}\n\n\tprivate reply(response: ServerResponse, status: number, page: OAuthCallbackPage): void {\n\t\tif (this.renderPage) {\n\t\t\tresponse.writeHead(status, { \"content-type\": \"text/html; charset=utf-8\", \"cache-control\": \"no-store\" });\n\t\t\tresponse.end(this.renderPage(page));\n\t\t} else {\n\t\t\tresponse.writeHead(status, { \"content-type\": \"text/plain; charset=utf-8\" }).end(plainText(page));\n\t\t}\n\t}\n\n\tprivate handle(rawUrl: string, host: string | undefined, response: ServerResponse): void {\n\t\tconst url = new URL(rawUrl, this.redirectUrl);\n\t\tconst redirect = new URL(this.redirectUrl);\n\t\tif (host !== redirect.host || url.origin !== redirect.origin) {\n\t\t\tthis.reply(response, 400, { ok: false, message: \"Unexpected redirect origin\" });\n\t\t\treturn;\n\t\t}\n\t\tif (!this.paths.includes(url.pathname)) {\n\t\t\tthis.reply(response, 404, { ok: false, message: \"Not found\" });\n\t\t\treturn;\n\t\t}\n\t\tconst state = url.searchParams.get(\"state\");\n\t\tconst pending = state ? this.pending.get(state) : undefined;\n\t\tif (!state || !pending) {\n\t\t\tthis.reply(response, 400, { ok: false, message: \"Invalid or expired OAuth state\" });\n\t\t\treturn;\n\t\t}\n\t\tclearTimeout(pending.timer);\n\t\tthis.pending.delete(state);\n\t\tif (pending.path !== undefined && url.pathname !== pending.path) {\n\t\t\tpending.reject(new Error(\"The authorization response arrived on another redirect URI\"));\n\t\t\tthis.reply(response, 400, { ok: false, message: \"Unexpected redirect URI\" });\n\t\t\treturn;\n\t\t}\n\t\tconst error = url.searchParams.get(\"error\");\n\t\tif (error) {\n\t\t\tconst description = url.searchParams.get(\"error_description\") ?? error;\n\t\t\tpending.reject(new Error(description));\n\t\t\tthis.reply(response, 200, {\n\t\t\t\tok: false,\n\t\t\t\tmessage: \"Authorization failed. You may close this window.\",\n\t\t\t\tdetails: description,\n\t\t\t});\n\t\t\treturn;\n\t\t}\n\t\tconst code = url.searchParams.get(\"code\");\n\t\tif (!code) {\n\t\t\tpending.reject(new Error(\"OAuth callback did not include an authorization code\"));\n\t\t\tthis.reply(response, 400, { ok: false, message: \"Missing authorization code\" });\n\t\t\treturn;\n\t\t}\n\t\tconst iss = url.searchParams.get(\"iss\");\n\t\tpending.resolve({ code, state, ...(iss ? { iss } : {}) });\n\t\tthis.reply(response, 200, { ok: true });\n\t}\n}\n"]}
1
+ {"version":3,"file":"callback.js","sourceRoot":"","sources":["../../src/oauth/callback.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,YAAY,EAAoC,MAAM,WAAW,CAAC;AA4B3E,SAAS,SAAS,CAAC,IAAuB;IACzC,IAAI,IAAI,CAAC,EAAE;QAAE,OAAO,oDAAoD,CAAC;IACzE,OAAO,IAAI,CAAC,OAAO,CAAC,CAAC,CAAC,GAAG,IAAI,CAAC,OAAO,OAAO,IAAI,CAAC,OAAO,EAAE,CAA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AAC,KAAK,CAAC,QAAQ,EAAE,GAAG,EAAE,EAAE,EAAE,EAAE,IAAI,EAAE,CAAC,CAAC;IACzC,CAAC;CACD","sourcesContent":["import { createServer, type Server, type ServerResponse } from \"node:http\";\n\nexport interface OAuthCallback {\n\tcode: string;\n\tstate: string;\n\tiss?: string;\n}\n\n/** Outcome shown on the browser page after the redirect. */\nexport type OAuthCallbackPage = { ok: true } | { ok: false; message: string; details?: string };\n\nexport interface OAuthCallbackServerOptions {\n\t/** Address to listen on. Default: `127.0.0.1`. */\n\thost?: string;\n\t/**\n\t * Host name in `redirectUrl`, for example `localhost` for a client registered with it while\n\t * listening on `127.0.0.1`. Default: `host`.\n\t */\n\tredirectHost?: string;\n\tport?: number;\n\tpath?: string;\n\t/** More paths that receive the callback, for example a server-specific path of a redirect URI. */\n\textraPaths?: string[];\n\ttimeoutMs?: number;\n\t/** Render the browser page as HTML. Default: a plain-text message. */\n\trenderPage?: (page: OAuthCallbackPage) => string;\n}\n\nfunction plainText(page: OAuthCallbackPage): string {\n\tif (page.ok) return \"Authorization complete. You may close this window.\";\n\treturn page.details ? `${page.message}\\n\\n${page.details}` : page.message;\n}\n\nexport class OAuthCallbackServer {\n\treadonly redirectUrl: string;\n\tprivate server: Server;\n\tprivate paths: string[];\n\tprivate timeoutMs: number;\n\tprivate renderPage: ((page: OAuthCallbackPage) => string) | undefined;\n\tprivate pending = new Map<\n\t\tstring,\n\t\t{\n\t\t\tresolve: (callback: OAuthCallback) => void;\n\t\t\treject: (error: Error) => void;\n\t\t\ttimer: ReturnType<typeof setTimeout>;\n\t\t\tpath: string | undefined;\n\t\t}\n\t>();\n\n\tprivate constructor(\n\t\tserver: Server,\n\t\tredirectUrl: string,\n\t\tpaths: string[],\n\t\ttimeoutMs: number,\n\t\trenderPage: ((page: OAuthCallbackPage) => string) | undefined,\n\t) {\n\t\tthis.server = server;\n\t\tthis.redirectUrl = redirectUrl;\n\t\tthis.paths = paths;\n\t\tthis.timeoutMs = timeoutMs;\n\t\tthis.renderPage = renderPage;\n\t}\n\n\tstatic async listen(options: OAuthCallbackServerOptions = {}): Promise<OAuthCallbackServer> {\n\t\tconst host = options.host ?? \"127.0.0.1\";\n\t\tconst redirectHost = options.redirectHost ?? host;\n\t\tconst path = options.path ?? \"/callback\";\n\t\tlet instance: OAuthCallbackServer | undefined;\n\t\tconst server = createServer((request, response) =>\n\t\t\tinstance?.handle(request.url ?? \"/\", request.headers.host, response),\n\t\t);\n\t\tawait new Promise<void>((resolve, reject) => {\n\t\t\tserver.once(\"error\", reject);\n\t\t\tserver.listen(options.port ?? 0, host, () => {\n\t\t\t\tserver.off(\"error\", reject);\n\t\t\t\tresolve();\n\t\t\t});\n\t\t});\n\t\tconst address = server.address();\n\t\tif (!address || typeof address === \"string\") throw new Error(\"OAuth callback server did not bind to TCP\");\n\t\tinstance = new OAuthCallbackServer(\n\t\t\tserver,\n\t\t\t`http://${redirectHost.includes(\":\") ? `[${redirectHost}]` : redirectHost}:${address.port}${path}`,\n\t\t\t[path, ...(options.extraPaths ?? [])],\n\t\t\toptions.timeoutMs ?? 5 * 60_000,\n\t\t\toptions.renderPage,\n\t\t);\n\t\treturn instance;\n\t}\n\n\t/**\n\t * Wait for the authorization response with `state`. With `path`, a response on another path fails, so\n\t * a server-specific redirect URI can tell authorization servers apart (RFC 9700 section 4.4.2.2).\n\t */\n\twaitForCallback(state: string, path?: string): Promise<OAuthCallback> {\n\t\tif (this.pending.has(state)) throw new Error(\"OAuth state is already pending\");\n\t\treturn new Promise((resolve, reject) => {\n\t\t\tconst timer = setTimeout(() => {\n\t\t\t\tthis.pending.delete(state);\n\t\t\t\treject(new Error(\"OAuth callback timed out\"));\n\t\t\t}, this.timeoutMs);\n\t\t\tthis.pending.set(state, { resolve, reject, timer, path });\n\t\t});\n\t}\n\n\tasync close(): Promise<void> {\n\t\tfor (const pending of this.pending.values()) {\n\t\t\tclearTimeout(pending.timer);\n\t\t\tpending.reject(new Error(\"OAuth callback server closed\"));\n\t\t}\n\t\tthis.pending.clear();\n\t\tawait new Promise<void>((resolve, reject) => {\n\t\t\tthis.server.close((error) => (error ? reject(error) : resolve()));\n\t\t});\n\t}\n\n\tprivate reply(response: ServerResponse, status: number, page: OAuthCallbackPage): void {\n\t\tif (this.renderPage) {\n\t\t\tresponse.writeHead(status, { \"content-type\": \"text/html; charset=utf-8\", \"cache-control\": \"no-store\" });\n\t\t\tresponse.end(this.renderPage(page));\n\t\t} else {\n\t\t\tresponse.writeHead(status, { \"content-type\": \"text/plain; charset=utf-8\" }).end(plainText(page));\n\t\t}\n\t}\n\n\tprivate handle(rawUrl: string, host: string | undefined, response: ServerResponse): void {\n\t\tconst url = new URL(rawUrl, this.redirectUrl);\n\t\tconst redirect = new URL(this.redirectUrl);\n\t\tif (host !== redirect.host || url.origin !== redirect.origin) {\n\t\t\tthis.reply(response, 400, { ok: false, message: \"Unexpected redirect origin\" });\n\t\t\treturn;\n\t\t}\n\t\tif (!this.paths.includes(url.pathname)) {\n\t\t\tthis.reply(response, 404, { ok: false, message: \"Not found\" });\n\t\t\treturn;\n\t\t}\n\t\tconst state = url.searchParams.get(\"state\");\n\t\tconst pending = state ? this.pending.get(state) : undefined;\n\t\tif (!state || !pending) {\n\t\t\tthis.reply(response, 400, { ok: false, message: \"Invalid or expired OAuth state\" });\n\t\t\treturn;\n\t\t}\n\t\t// Everything above (Host, origin, unknown path, unknown state) fails without touching the pending\n\t\t// sign-in. From here on the state is consumed, by design also on the wrong one of this server's paths:\n\t\t// a valid state on another redirect URI means an authorization server mixed up the response (RFC 9700\n\t\t// section 4.4.2.2), so the sign-in fails instead of waiting for a second response with the same state.\n\t\tclearTimeout(pending.timer);\n\t\tthis.pending.delete(state);\n\t\tif (pending.path !== undefined && url.pathname !== pending.path) {\n\t\t\tpending.reject(new Error(\"The authorization response arrived on another redirect URI\"));\n\t\t\tthis.reply(response, 400, { ok: false, message: \"Unexpected redirect URI\" });\n\t\t\treturn;\n\t\t}\n\t\tconst error = url.searchParams.get(\"error\");\n\t\tif (error) {\n\t\t\tconst description = url.searchParams.get(\"error_description\") ?? error;\n\t\t\tpending.reject(new Error(description));\n\t\t\tthis.reply(response, 200, {\n\t\t\t\tok: false,\n\t\t\t\tmessage: \"Authorization failed. You may close this window.\",\n\t\t\t\tdetails: description,\n\t\t\t});\n\t\t\treturn;\n\t\t}\n\t\tconst code = url.searchParams.get(\"code\");\n\t\tif (!code) {\n\t\t\tpending.reject(new Error(\"OAuth callback did not include an authorization code\"));\n\t\t\tthis.reply(response, 400, { ok: false, message: \"Missing authorization code\" });\n\t\t\treturn;\n\t\t}\n\t\tconst iss = url.searchParams.get(\"iss\");\n\t\tpending.resolve({ code, state, ...(iss ? { iss } : {}) });\n\t\tthis.reply(response, 200, { ok: true });\n\t}\n}\n"]}
@@ -0,0 +1,16 @@
1
+ /**
2
+ * draht: the operator's Client ID Metadata Document base URL (`oauth.clientMetadataBaseUrl`).
3
+ *
4
+ * Upstream lets the application name where its documents live (pi's are on pi.dev) and uses them
5
+ * automatically whenever an authorization server supports them (`clientRegistration: "auto"`). draht has
6
+ * no hosted documents and must never identify with a document its operator did not configure, so the
7
+ * base comes only from configuration, `cimd` is opt-in, and dynamic client registration is the default.
8
+ * The base is validated by the configuration boundary and again wherever sign-in or refresh uses it.
9
+ */
10
+ /**
11
+ * The normalized base: an absolute https URL without userinfo, query, or fragment, whose path ends in
12
+ * exactly one `/`, so `client.json` and `<id>/client.json` resolve below the configured path prefix.
13
+ * `undefined` when `value` is not such a URL.
14
+ */
15
+ export declare function parseClientMetadataBaseUrl(value: unknown): string | undefined;
16
+ //# sourceMappingURL=client-metadata-base.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"client-metadata-base.d.ts","sourceRoot":"","sources":["../../src/oauth/client-metadata-base.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG;AAEH;;;;GAIG;AACH,wBAAgB,0BAA0B,CAAC,KAAK,EAAE,OAAO,GAAG,MAAM,GAAG,SAAS,CAQ7E"}
@@ -0,0 +1,27 @@
1
+ /**
2
+ * draht: the operator's Client ID Metadata Document base URL (`oauth.clientMetadataBaseUrl`).
3
+ *
4
+ * Upstream lets the application name where its documents live (pi's are on pi.dev) and uses them
5
+ * automatically whenever an authorization server supports them (`clientRegistration: "auto"`). draht has
6
+ * no hosted documents and must never identify with a document its operator did not configure, so the
7
+ * base comes only from configuration, `cimd` is opt-in, and dynamic client registration is the default.
8
+ * The base is validated by the configuration boundary and again wherever sign-in or refresh uses it.
9
+ */
10
+ /**
11
+ * The normalized base: an absolute https URL without userinfo, query, or fragment, whose path ends in
12
+ * exactly one `/`, so `client.json` and `<id>/client.json` resolve below the configured path prefix.
13
+ * `undefined` when `value` is not such a URL.
14
+ */
15
+ export function parseClientMetadataBaseUrl(value) {
16
+ if (typeof value !== "string" || !URL.canParse(value))
17
+ return undefined;
18
+ const url = new URL(value);
19
+ if (url.protocol !== "https:" || url.username || url.password)
20
+ return undefined;
21
+ // `search` and `hash` are empty for a bare `?` or `#`, which `href` keeps.
22
+ if (url.href.includes("?") || url.href.includes("#"))
23
+ return undefined;
24
+ url.pathname = `${url.pathname.replace(/\/+$/, "")}/`;
25
+ return url.href;
26
+ }
27
+ //# sourceMappingURL=client-metadata-base.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"client-metadata-base.js","sourceRoot":"","sources":["../../src/oauth/client-metadata-base.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG;AAEH;;;;GAIG;AACH,MAAM,UAAU,0BAA0B,CAAC,KAAc;IACxD,IAAI,OAAO,KAAK,KAAK,QAAQ,IAAI,CAAC,GAAG,CAAC,QAAQ,CAAC,KAAK,CAAC;QAAE,OAAO,SAAS,CAAC;IACxE,MAAM,GAAG,GAAG,IAAI,GAAG,CAAC,KAAK,CAAC,CAAC;IAC3B,IAAI,GAAG,CAAC,QAAQ,KAAK,QAAQ,IAAI,GAAG,CAAC,QAAQ,IAAI,GAAG,CAAC,QAAQ;QAAE,OAAO,SAAS,CAAC;IAChF,2EAA2E;IAC3E,IAAI,GAAG,CAAC,IAAI,CAAC,QAAQ,CAAC,GAAG,CAAC,IAAI,GAAG,CAAC,IAAI,CAAC,QAAQ,CAAC,GAAG,CAAC;QAAE,OAAO,SAAS,CAAC;IACvE,GAAG,CAAC,QAAQ,GAAG,GAAG,GAAG,CAAC,QAAQ,CAAC,OAAO,CAAC,MAAM,EAAE,EAAE,CAAC,GAAG,CAAC;IACtD,OAAO,GAAG,CAAC,IAAI,CAAC;AACjB,CAAC","sourcesContent":["/**\n * draht: the operator's Client ID Metadata Document base URL (`oauth.clientMetadataBaseUrl`).\n *\n * Upstream lets the application name where its documents live (pi's are on pi.dev) and uses them\n * automatically whenever an authorization server supports them (`clientRegistration: \"auto\"`). draht has\n * no hosted documents and must never identify with a document its operator did not configure, so the\n * base comes only from configuration, `cimd` is opt-in, and dynamic client registration is the default.\n * The base is validated by the configuration boundary and again wherever sign-in or refresh uses it.\n */\n\n/**\n * The normalized base: an absolute https URL without userinfo, query, or fragment, whose path ends in\n * exactly one `/`, so `client.json` and `<id>/client.json` resolve below the configured path prefix.\n * `undefined` when `value` is not such a URL.\n */\nexport function parseClientMetadataBaseUrl(value: unknown): string | undefined {\n\tif (typeof value !== \"string\" || !URL.canParse(value)) return undefined;\n\tconst url = new URL(value);\n\tif (url.protocol !== \"https:\" || url.username || url.password) return undefined;\n\t// `search` and `hash` are empty for a bare `?` or `#`, which `href` keeps.\n\tif (url.href.includes(\"?\") || url.href.includes(\"#\")) return undefined;\n\turl.pathname = `${url.pathname.replace(/\\/+$/, \"\")}/`;\n\treturn url.href;\n}\n"]}
@@ -0,0 +1,131 @@
1
+ /**
2
+ * The OAuth client that sign-in and refreshes use for one MCP server: its settings, how it identifies
3
+ * itself (a pre-registered client, the operator's Client ID Metadata Document, or dynamic client
4
+ * registration), and the `McpOAuthProvider` built from them.
5
+ */
6
+ import type { McpFetch } from "../auth-provider.ts";
7
+ import { McpOAuthProvider, type McpOAuthState, type McpOAuthStateStore } from "./provider.ts";
8
+ import type { OAuthClientInformationMixed } from "./types.ts";
9
+ /** Client settings of one MCP server, usually from the application's configuration. */
10
+ export interface McpOAuthSettings {
11
+ /** Pre-registered client id. Without it, sign-in uses a Client ID Metadata Document or registers a client. */
12
+ clientId?: string;
13
+ /** Already resolved. */
14
+ clientSecret?: string;
15
+ /**
16
+ * Port of the loopback callback server, for clients registered with a fixed redirect URI. Without
17
+ * `callbackUrl`, the redirect URI is `http://127.0.0.1:<port>/callback`. Only `listenForLoopbackSignIn`
18
+ * and the redirect URI of refreshes use it; `startMcpSignIn` and `completeMcpSignIn` take theirs from
19
+ * the caller.
20
+ */
21
+ callbackPort?: number;
22
+ /**
23
+ * Loopback redirect URI registered for `clientId`, for example `http://localhost:8080/oauth/callback`.
24
+ * Without a port, the callback server listens on `callbackPort` or a free port, which is added to the
25
+ * URI (RFC 8252). Default: `http://127.0.0.1/callback`. Like `callbackPort`, only `listenForLoopbackSignIn`
26
+ * and refreshes use it.
27
+ */
28
+ callbackUrl?: string;
29
+ /** Scopes to request, separated by spaces. Default: the scopes the server advertises. */
30
+ scope?: string;
31
+ /** `client_name` for dynamic client registration. Default: the application's `clientName`. */
32
+ clientName?: string;
33
+ /**
34
+ * How to identify without `clientId`. `dcr` (default): dynamic client registration. `cimd`: the
35
+ * operator's Client ID Metadata Document under `clientMetadataBaseUrl`, and sign-in fails when the
36
+ * authorization server does not support documents for public clients.
37
+ *
38
+ * draht: upstream's `auto` (the application's documents whenever the server supports them) is not
39
+ * offered and is rejected: a document is only ever used when the operator configured one.
40
+ */
41
+ clientRegistration?: "dcr" | "cimd";
42
+ /**
43
+ * draht: required for `cimd` and rejected otherwise. The https base the operator hosts the documents
44
+ * under (`client.json` and `<callback ID>/client.json`); see `parseClientMetadataBaseUrl`. `cimd`
45
+ * cannot be combined with `clientId`, `clientName`, or `clientSecret`: the document is a public client.
46
+ */
47
+ clientMetadataBaseUrl?: string;
48
+ /**
49
+ * Authorization server metadata document to use instead of discovery through the server, for servers
50
+ * that advertise a wrong authorization server or none. It is trusted as configured.
51
+ */
52
+ authServerMetadataUrl?: URL;
53
+ }
54
+ /**
55
+ * The redirect URIs the operator's Client ID Metadata Documents list: `<base>/client.json` lists the
56
+ * redirect URI itself, and `<base>/<callback ID>/client.json` the URI with the path `<path>/<callback ID>`.
57
+ *
58
+ * draht: upstream's `baseUrl` field is left out. It let the application name the document host (pi.dev
59
+ * for pi), so documents could be used that no operator configured. The base comes only from
60
+ * `McpOAuthSettings.clientMetadataBaseUrl`.
61
+ */
62
+ export interface McpClientMetadataDocuments {
63
+ /** Whether the documents list `redirectUrl`. Loopback redirect URIs match on any port (RFC 8252). */
64
+ listsRedirectUrl(redirectUrl: string): boolean;
65
+ }
66
+ /** State store of one MCP server, with a lock that keeps other processes from refreshing at the same time. */
67
+ export interface McpOAuthServerStore extends McpOAuthStateStore {
68
+ /**
69
+ * Run `fn` while no other process refreshes the server's tokens. Not reentrant: `startMcpSignIn` and
70
+ * `createMcpAuthProvider` take it themselves, so never call them from `fn`. Throw
71
+ * `McpRefreshLockBusyError` when another process holds the lock for the whole wait: `startMcpSignIn`
72
+ * then goes to the browser step. Any other error fails the sign-in or refresh.
73
+ */
74
+ withRefreshLock<T>(fn: () => Promise<T>): Promise<T>;
75
+ }
76
+ /** The OAuth client of one MCP server: where its state lives, its settings, and the application's identity. */
77
+ export interface McpOAuthClientOptions {
78
+ serverUrl: string;
79
+ store: McpOAuthServerStore;
80
+ settings: McpOAuthSettings;
81
+ /** `client_name` for dynamic client registration unless `settings.clientName` names another: the application. */
82
+ clientName: string;
83
+ /** Which redirect URIs the operator's documents list. Omitted: `cimd` fails. */
84
+ clientMetadataDocuments?: McpClientMetadataDocuments;
85
+ }
86
+ /**
87
+ * The validated Client ID Metadata Document base of `settings`: the normalized `clientMetadataBaseUrl`
88
+ * for `cimd`, `undefined` for dynamic client registration or a pre-registered client. Throws for settings
89
+ * the configuration boundary rejects, so an application that skips that validation still cannot fall into
90
+ * a document the operator did not configure or send a secret for a public client.
91
+ */
92
+ export declare function clientMetadataBaseUrl(settings: McpOAuthSettings): string | undefined;
93
+ /** An `McpOAuthProvider` for the client, redirecting to `redirectUrl` or the document's variant of it. */
94
+ export declare function createOAuthClientProvider(options: McpOAuthClientOptions, redirectUrl: string, onRedirect?: (url: URL) => void): McpOAuthProvider;
95
+ /**
96
+ * Whether the client identifies with a Client ID Metadata Document instead of registering: only with
97
+ * `cimd` and the operator's validated base. draht: upstream's `auto` also used the application's
98
+ * documents when the server supported them; that mode does not exist here.
99
+ */
100
+ export declare function offersClientMetadataDocument(settings: McpOAuthSettings): boolean;
101
+ /**
102
+ * Whether stored credentials belong to the client the current settings identify as: the same MCP server
103
+ * URL, and tokens issued to a document under `baseUrl` (the validated base, see `clientMetadataBaseUrl`)
104
+ * or, without one, to a registered or pre-registered client. draht: cached tokens are never sent or
105
+ * refreshed after the registration mode or the metadata base changed; the user signs in again.
106
+ */
107
+ export declare function matchesClient(state: McpOAuthState | undefined, serverUrl: string, baseUrl: string | undefined): boolean;
108
+ /** The path of the redirect URI of a server-specific Client ID Metadata Document: `<path>/<callback ID>`. */
109
+ export declare function serverSpecificPath(path: string, serverUrl: string): string;
110
+ /** Redirect URIs a stored client was registered with. */
111
+ export declare function registeredRedirectUrls(client: OAuthClientInformationMixed | undefined): string[];
112
+ /** `fetch` with `OAUTH_REQUEST_TIMEOUT_MS` per request, on top of the request's own signal. */
113
+ export declare function timedFetch(fetch?: McpFetch): McpFetch;
114
+ /** Redirect URI when the settings name none and no client is stored. */
115
+ export declare const DEFAULT_REDIRECT_URL = "http://127.0.0.1/callback";
116
+ /** Where the loopback callback server listens and the redirect URI it serves, from `callbackUrl` and `callbackPort`. */
117
+ export interface LoopbackSettings {
118
+ /** The redirect URI, without the port unless one is configured. */
119
+ url: string;
120
+ /** Address to listen on. */
121
+ host: string;
122
+ /** Host name in the redirect URI. */
123
+ redirectHost: string;
124
+ port: number | undefined;
125
+ path: string;
126
+ /** The exact redirect URI, when the port is fixed. */
127
+ fixedRedirectUrl: string | undefined;
128
+ }
129
+ /** The loopback callback settings of `settings`. */
130
+ export declare function loopbackSettings(settings: McpOAuthSettings): LoopbackSettings;
131
+ //# sourceMappingURL=client-settings.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"client-settings.d.ts","sourceRoot":"","sources":["../../src/oauth/client-settings.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAGH,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,qBAAqB,CAAC;AAGpD,OAAO,EAAE,gBAAgB,EAAE,KAAK,aAAa,EAAE,KAAK,kBAAkB,EAAE,MAAM,eAAe,CAAC;AAC9F,OAAO,KAAK,EAA+B,2BAA2B,EAAE,MAAM,YAAY,CAAC;AAE3F,uFAAuF;AACvF,MAAM,WAAW,gBAAgB;IAChC,8GAA8G;IAC9G,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,wBAAwB;IACxB,YAAY,CAAC,EAAE,MAAM,CAAC;IACtB;;;;;OAKG;IACH,YAAY,CAAC,EAAE,MAAM,CAAC;IACtB;;;;;OAKG;IACH,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB,yFAAyF;IACzF,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,8FAA8F;IAC9F,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB;;;;;;;OAOG;IACH,kBAAkB,CAAC,EAAE,KAAK,GAAG,MAAM,CAAC;IACpC;;;;OAIG;IACH,qBAAqB,CAAC,EAAE,MAAM,CAAC;IAC/B;;;OAGG;IACH,qBAAqB,CAAC,EAAE,GAAG,CAAC;CAC5B;AAED;;;;;;;GAOG;AACH,MAAM,WAAW,0BAA0B;IAC1C,qGAAqG;IACrG,gBAAgB,CAAC,WAAW,EAAE,MAAM,GAAG,OAAO,CAAC;CAC/C;AAED,8GAA8G;AAC9G,MAAM,WAAW,mBAAoB,SAAQ,kBAAkB;IAC9D;;;;;OAKG;IACH,eAAe,CAAC,CAAC,EAAE,EAAE,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,EAAE,MAAM,CAAC;IACZ,4BAA4B;IAC5B,IAAI,EAAE,MAAM,CAAC;IACb,qCAAqC;IACrC,YAAY,EAAE,MAAM,CAAC;IACrB,IAAI,EAAE,MAAM,GAAG,SAAS,CAAC;IACzB,IAAI,EAAE,MAAM,CAAC;IACb,sDAAsD;IACtD,gBAAgB,EAAE,MAAM,GAAG,SAAS,CAAC;CACrC;AAED,oDAAoD;AACpD,wBAAgB,gBAAgB,CAAC,QAAQ,EAAE,gBAAgB,GAAG,gBAAgB,CAqB7E"}
@@ -0,0 +1,158 @@
1
+ /**
2
+ * The OAuth client that sign-in and refreshes use for one MCP server: its settings, how it identifies
3
+ * itself (a pre-registered client, the operator's Client ID Metadata Document, or dynamic client
4
+ * registration), and the `McpOAuthProvider` built from them.
5
+ */
6
+ import { createHash } from "node:crypto";
7
+ import { parseClientMetadataBaseUrl } from "./client-metadata-base.js";
8
+ import { McpOAuthProvider } from "./provider.js";
9
+ /**
10
+ * The validated Client ID Metadata Document base of `settings`: the normalized `clientMetadataBaseUrl`
11
+ * for `cimd`, `undefined` for dynamic client registration or a pre-registered client. Throws for settings
12
+ * the configuration boundary rejects, so an application that skips that validation still cannot fall into
13
+ * a document the operator did not configure or send a secret for a public client.
14
+ */
15
+ export function clientMetadataBaseUrl(settings) {
16
+ const registration = settings.clientRegistration;
17
+ if (registration !== undefined && registration !== "dcr" && registration !== "cimd") {
18
+ throw new Error('oauth.clientRegistration must be "dcr" or "cimd"');
19
+ }
20
+ if (registration !== "cimd") {
21
+ if (settings.clientMetadataBaseUrl !== undefined) {
22
+ throw new Error('oauth.clientMetadataBaseUrl requires oauth.clientRegistration "cimd"');
23
+ }
24
+ return undefined;
25
+ }
26
+ if (settings.clientId !== undefined || settings.clientName !== undefined || settings.clientSecret !== undefined) {
27
+ throw new Error('oauth.clientRegistration "cimd" cannot be combined with oauth.clientId, oauth.clientName, or oauth.clientSecret');
28
+ }
29
+ if (settings.clientMetadataBaseUrl === undefined)
30
+ throw new Error('oauth.clientMetadataBaseUrl is required for "cimd"');
31
+ const base = parseClientMetadataBaseUrl(settings.clientMetadataBaseUrl);
32
+ if (!base) {
33
+ throw new Error('oauth.clientMetadataBaseUrl is required for "cimd" and must be an absolute HTTPS URL without userinfo, query, or fragment');
34
+ }
35
+ return base;
36
+ }
37
+ /** An `McpOAuthProvider` for the client, redirecting to `redirectUrl` or the document's variant of it. */
38
+ export function createOAuthClientProvider(options, redirectUrl, onRedirect = () => { }) {
39
+ const { serverUrl, settings, clientMetadataDocuments: documents } = options;
40
+ const baseUrl = clientMetadataBaseUrl(settings);
41
+ return new McpOAuthProvider({
42
+ serverUrl,
43
+ redirectUrl,
44
+ clientMetadata: { client_name: settings.clientName ?? options.clientName },
45
+ clientMetadataDocument: baseUrl
46
+ ? (metadata) => {
47
+ if (!documents?.listsRedirectUrl(redirectUrl)) {
48
+ throw new Error(`oauth.clientRegistration "cimd" needs Client ID Metadata Documents that list the redirect URI ${redirectUrl}`);
49
+ }
50
+ return clientMetadataDocument(baseUrl, serverUrl, redirectUrl, metadata);
51
+ }
52
+ : undefined,
53
+ clientId: settings.clientId,
54
+ clientSecret: settings.clientSecret,
55
+ store: options.store,
56
+ onRedirect,
57
+ });
58
+ }
59
+ /**
60
+ * Whether the client identifies with a Client ID Metadata Document instead of registering: only with
61
+ * `cimd` and the operator's validated base. draht: upstream's `auto` also used the application's
62
+ * documents when the server supported them; that mode does not exist here.
63
+ */
64
+ export function offersClientMetadataDocument(settings) {
65
+ return clientMetadataBaseUrl(settings) !== undefined;
66
+ }
67
+ /**
68
+ * The operator's Client ID Metadata Document to use, chosen like Codex chooses its own. Without the `iss`
69
+ * parameter in authorization responses (RFC 9207), the redirect URI and the document are specific to the
70
+ * MCP server, so a response cannot be mixed up with one from another authorization server (RFC 9700
71
+ * section 4.4.2.2). Fails when the authorization server does not support documents for public clients:
72
+ * draht never falls back to registering a client the operator did not ask for.
73
+ */
74
+ function clientMetadataDocument(baseUrl, serverUrl, redirectUrl, metadata) {
75
+ if (!metadata?.client_id_metadata_document_supported ||
76
+ !metadata.token_endpoint_auth_methods_supported?.includes("none")) {
77
+ throw new Error('The authorization server does not support Client ID Metadata Documents for public clients; remove oauth.clientRegistration "cimd"');
78
+ }
79
+ const [shared, serverSpecific] = clientMetadataDocumentUrls(baseUrl, serverUrl);
80
+ if (metadata.authorization_response_iss_parameter_supported)
81
+ return { url: shared, redirectUrl };
82
+ const redirect = new URL(redirectUrl);
83
+ redirect.pathname = serverSpecificPath(redirect.pathname, serverUrl);
84
+ return { url: serverSpecific, redirectUrl: redirect.href };
85
+ }
86
+ /** The shared and the server-specific document URL under the normalized `baseUrl`, keeping its path prefix. */
87
+ function clientMetadataDocumentUrls(baseUrl, serverUrl) {
88
+ return [new URL("client.json", baseUrl).href, new URL(`${callbackId(serverUrl)}/client.json`, baseUrl).href];
89
+ }
90
+ /**
91
+ * Whether stored credentials belong to the client the current settings identify as: the same MCP server
92
+ * URL, and tokens issued to a document under `baseUrl` (the validated base, see `clientMetadataBaseUrl`)
93
+ * or, without one, to a registered or pre-registered client. draht: cached tokens are never sent or
94
+ * refreshed after the registration mode or the metadata base changed; the user signs in again.
95
+ */
96
+ export function matchesClient(state, serverUrl, baseUrl) {
97
+ if (!state || state.serverUrl !== new URL(serverUrl).href)
98
+ return false;
99
+ if (!baseUrl)
100
+ return state.clientMetadataUrl === undefined;
101
+ return (state.clientMetadataUrl !== undefined &&
102
+ clientMetadataDocumentUrls(baseUrl, serverUrl).includes(state.clientMetadataUrl));
103
+ }
104
+ /** The path of the redirect URI of a server-specific Client ID Metadata Document: `<path>/<callback ID>`. */
105
+ export function serverSpecificPath(path, serverUrl) {
106
+ return `${path.replace(/\/$/, "")}/${callbackId(serverUrl)}`;
107
+ }
108
+ /** 12 characters identifying an MCP server URL in callback paths, computed like Codex does. */
109
+ function callbackId(serverUrl) {
110
+ const url = new URL(serverUrl);
111
+ url.hash = "";
112
+ return createHash("sha256").update(url.href).digest().subarray(0, 9).toString("base64url");
113
+ }
114
+ /** Redirect URIs a stored client was registered with. */
115
+ export function registeredRedirectUrls(client) {
116
+ return client && "redirect_uris" in client ? client.redirect_uris : [];
117
+ }
118
+ /**
119
+ * Bounds each request to the authorization server, so an unresponsive one cannot hold the refresh lock,
120
+ * delay shutdown, or keep a sign-in waiting for long.
121
+ */
122
+ const OAUTH_REQUEST_TIMEOUT_MS = 15_000;
123
+ /** `fetch` with `OAUTH_REQUEST_TIMEOUT_MS` per request, on top of the request's own signal. */
124
+ export function timedFetch(fetch = globalThis.fetch) {
125
+ return (input, init) => {
126
+ const timeout = AbortSignal.timeout(OAUTH_REQUEST_TIMEOUT_MS);
127
+ return fetch(input, { ...init, signal: init?.signal ? AbortSignal.any([init.signal, timeout]) : timeout });
128
+ };
129
+ }
130
+ const CALLBACK_HOST = "127.0.0.1";
131
+ const CALLBACK_PATH = "/callback";
132
+ /** Redirect URI when the settings name none and no client is stored. */
133
+ export const DEFAULT_REDIRECT_URL = `http://${CALLBACK_HOST}${CALLBACK_PATH}`;
134
+ /** The loopback callback settings of `settings`. */
135
+ export function loopbackSettings(settings) {
136
+ const configured = settings.callbackUrl ?? DEFAULT_REDIRECT_URL;
137
+ const url = new URL(configured);
138
+ const address = url.hostname.replace(/^\[|\]$/g, "");
139
+ const port = url.port ? Number(url.port) : settings.callbackPort;
140
+ let fixedRedirectUrl;
141
+ // A configured URI with a port is sent exactly as written, since servers compare it as a string.
142
+ if (url.port)
143
+ fixedRedirectUrl = settings.callbackUrl;
144
+ else if (port !== undefined) {
145
+ url.port = String(port);
146
+ fixedRedirectUrl = url.href;
147
+ }
148
+ return {
149
+ url: configured,
150
+ // `localhost` is served on 127.0.0.1; browsers fall back to it when ::1 refuses.
151
+ host: address === "localhost" ? CALLBACK_HOST : address,
152
+ redirectHost: address,
153
+ port,
154
+ path: url.pathname,
155
+ fixedRedirectUrl,
156
+ };
157
+ }
158
+ //# sourceMappingURL=client-settings.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"client-sett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,CAAC;AAgB9E,oDAAoD;AACpD,MAAM,UAAU,gBAAgB,CAAC,QAA0B;IAC1D,MAAM,UAAU,GAAG,QAAQ,CAAC,WAAW,IAAI,oBAAoB,CAAC;IAChE,MAAM,GAAG,GAAG,IAAI,GAAG,CAAC,UAAU,CAAC,CAAC;IAChC,MAAM,OAAO,GAAG,GAAG,CAAC,QAAQ,CAAC,OAAO,CAAC,UAAU,EAAE,EAAE,CAAC,CAAC;IACrD,MAAM,IAAI,GAAG,GAAG,CAAC,IAAI,CAAC,CAAC,CAAC,MAAM,CAAC,GAAG,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,QAAQ,CAAC,YAAY,CAAC;IACjE,IAAI,gBAAoC,CAAC;IACzC,iGAAiG;IACjG,IAAI,GAAG,CAAC,IAAI;QAAE,gBAAgB,GAAG,QAAQ,CAAC,WAAW,CAAC;SACjD,IAAI,IAAI,KAAK,SAAS,EAAE,CAAC;QAC7B,GAAG,CAAC,IAAI,GAAG,MAAM,CAAC,IAAI,CAAC,CAAC;QACxB,gBAAgB,GAAG,GAAG,CAAC,IAAI,CAAC;IAC7B,CAAC;IACD,OAAO;QACN,GAAG,EAAE,UAAU;QACf,iFAAiF;QACjF,IAAI,EAAE,OAAO,KAAK,WAAW,CAAC,CAAC,CAAC,aAAa,CAAC,CAAC,CAAC,OAAO;QACvD,YAAY,EAAE,OAAO;QACrB,IAAI;QACJ,IAAI,EAAE,GAAG,CAAC,QAAQ;QAClB,gBAAgB;KAChB,CAAC;AACH,CAAC","sourcesContent":["/**\n * The OAuth client that sign-in and refreshes use for one MCP server: its settings, how it identifies\n * itself (a pre-registered client, the operator's Client ID Metadata Document, or dynamic client\n * registration), and the `McpOAuthProvider` built from them.\n */\n\nimport { createHash } from \"node:crypto\";\nimport type { McpFetch } from \"../auth-provider.ts\";\nimport { parseClientMetadataBaseUrl } from \"./client-metadata-base.ts\";\nimport type { OAuthClientMetadataDocument } from \"./flow.ts\";\nimport { McpOAuthProvider, type McpOAuthState, type McpOAuthStateStore } from \"./provider.ts\";\nimport type { AuthorizationServerMetadata, OAuthClientInformationMixed } from \"./types.ts\";\n\n/** Client settings of one MCP server, usually from the application's configuration. */\nexport interface McpOAuthSettings {\n\t/** Pre-registered client id. Without it, sign-in uses a Client ID Metadata Document or registers a client. */\n\tclientId?: string;\n\t/** Already resolved. */\n\tclientSecret?: string;\n\t/**\n\t * Port of the loopback callback server, for clients registered with a fixed redirect URI. Without\n\t * `callbackUrl`, the redirect URI is `http://127.0.0.1:<port>/callback`. Only `listenForLoopbackSignIn`\n\t * and the redirect URI of refreshes use it; `startMcpSignIn` and `completeMcpSignIn` take theirs from\n\t * the caller.\n\t */\n\tcallbackPort?: number;\n\t/**\n\t * Loopback redirect URI registered for `clientId`, for example `http://localhost:8080/oauth/callback`.\n\t * Without a port, the callback server listens on `callbackPort` or a free port, which is added to the\n\t * URI (RFC 8252). Default: `http://127.0.0.1/callback`. Like `callbackPort`, only `listenForLoopbackSignIn`\n\t * and refreshes use it.\n\t */\n\tcallbackUrl?: string;\n\t/** Scopes to request, separated by spaces. Default: the scopes the server advertises. */\n\tscope?: string;\n\t/** `client_name` for dynamic client registration. Default: the application's `clientName`. */\n\tclientName?: string;\n\t/**\n\t * How to identify without `clientId`. `dcr` (default): dynamic client registration. `cimd`: the\n\t * operator's Client ID Metadata Document under `clientMetadataBaseUrl`, and sign-in fails when the\n\t * authorization server does not support documents for public clients.\n\t *\n\t * draht: upstream's `auto` (the application's documents whenever the server supports them) is not\n\t * offered and is rejected: a document is only ever used when the operator configured one.\n\t */\n\tclientRegistration?: \"dcr\" | \"cimd\";\n\t/**\n\t * draht: required for `cimd` and rejected otherwise. The https base the operator hosts the documents\n\t * under (`client.json` and `<callback ID>/client.json`); see `parseClientMetadataBaseUrl`. `cimd`\n\t * cannot be combined with `clientId`, `clientName`, or `clientSecret`: the document is a public client.\n\t */\n\tclientMetadataBaseUrl?: string;\n\t/**\n\t * Authorization server metadata document to use instead of discovery through the server, for servers\n\t * that advertise a wrong authorization server or none. It is trusted as configured.\n\t */\n\tauthServerMetadataUrl?: URL;\n}\n\n/**\n * The redirect URIs the operator's Client ID Metadata Documents list: `<base>/client.json` lists the\n * redirect URI itself, and `<base>/<callback ID>/client.json` the URI with the path `<path>/<callback ID>`.\n *\n * draht: upstream's `baseUrl` field is left out. It let the application name the document host (pi.dev\n * for pi), so documents could be used that no operator configured. The base comes only from\n * `McpOAuthSettings.clientMetadataBaseUrl`.\n */\nexport interface McpClientMetadataDocuments {\n\t/** Whether the documents list `redirectUrl`. Loopback redirect URIs match on any port (RFC 8252). */\n\tlistsRedirectUrl(redirectUrl: string): boolean;\n}\n\n/** State store of one MCP server, with a lock that keeps other processes from refreshing at the same time. */\nexport interface McpOAuthServerStore extends McpOAuthStateStore {\n\t/**\n\t * Run `fn` while no other process refreshes the server's tokens. Not reentrant: `startMcpSignIn` and\n\t * `createMcpAuthProvider` take it themselves, so never call them from `fn`. Throw\n\t * `McpRefreshLockBusyError` when another process holds the lock for the whole wait: `startMcpSignIn`\n\t * then goes to the browser step. Any other error fails the sign-in or refresh.\n\t */\n\twithRefreshLock<T>(fn: () => Promise<T>): Promise<T>;\n}\n\n/** The OAuth client of one MCP server: where its state lives, its settings, and the application's identity. */\nexport interface McpOAuthClientOptions {\n\tserverUrl: string;\n\tstore: McpOAuthServerStore;\n\tsettings: McpOAuthSettings;\n\t/** `client_name` for dynamic client registration unless `settings.clientName` names another: the application. */\n\tclientName: string;\n\t/** Which redirect URIs the operator's documents list. Omitted: `cimd` fails. */\n\tclientMetadataDocuments?: McpClientMetadataDocuments;\n}\n\n/**\n * The validated Client ID Metadata Document base of `settings`: the normalized `clientMetadataBaseUrl`\n * for `cimd`, `undefined` for dynamic client registration or a pre-registered client. Throws for settings\n * the configuration boundary rejects, so an application that skips that validation still cannot fall into\n * a document the operator did not configure or send a secret for a public client.\n */\nexport function clientMetadataBaseUrl(settings: McpOAuthSettings): string | undefined {\n\tconst registration: unknown = settings.clientRegistration;\n\tif (registration !== undefined && registration !== \"dcr\" && registration !== \"cimd\") {\n\t\tthrow new Error('oauth.clientRegistration must be \"dcr\" or \"cimd\"');\n\t}\n\tif (registration !== \"cimd\") {\n\t\tif (settings.clientMetadataBaseUrl !== undefined) {\n\t\t\tthrow new Error('oauth.clientMetadataBaseUrl requires oauth.clientRegistration \"cimd\"');\n\t\t}\n\t\treturn undefined;\n\t}\n\tif (settings.clientId !== undefined || settings.clientName !== undefined || settings.clientSecret !== undefined) {\n\t\tthrow new Error(\n\t\t\t'oauth.clientRegistration \"cimd\" cannot be combined with oauth.clientId, oauth.clientName, or oauth.clientSecret',\n\t\t);\n\t}\n\tif (settings.clientMetadataBaseUrl === undefined)\n\t\tthrow new Error('oauth.clientMetadataBaseUrl is required for \"cimd\"');\n\tconst base = parseClientMetadataBaseUrl(settings.clientMetadataBaseUrl);\n\tif (!base) {\n\t\tthrow new Error(\n\t\t\t'oauth.clientMetadataBaseUrl is required for \"cimd\" and must be an absolute HTTPS URL without userinfo, query, or fragment',\n\t\t);\n\t}\n\treturn base;\n}\n\n/** An `McpOAuthProvider` for the client, redirecting to `redirectUrl` or the document's variant of it. */\nexport function createOAuthClientProvider(\n\toptions: McpOAuthClientOptions,\n\tredirectUrl: string,\n\tonRedirect: (url: URL) => void = () => {},\n): McpOAuthProvider {\n\tconst { serverUrl, settings, clientMetadataDocuments: documents } = options;\n\tconst baseUrl = clientMetadataBaseUrl(settings);\n\treturn new McpOAuthProvider({\n\t\tserverUrl,\n\t\tredirectUrl,\n\t\tclientMetadata: { client_name: settings.clientName ?? options.clientName },\n\t\tclientMetadataDocument: baseUrl\n\t\t\t? (metadata) => {\n\t\t\t\t\tif (!documents?.listsRedirectUrl(redirectUrl)) {\n\t\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t\t`oauth.clientRegistration \"cimd\" needs Client ID Metadata Documents that list the redirect URI ${redirectUrl}`,\n\t\t\t\t\t\t);\n\t\t\t\t\t}\n\t\t\t\t\treturn clientMetadataDocument(baseUrl, serverUrl, redirectUrl, metadata);\n\t\t\t\t}\n\t\t\t: undefined,\n\t\tclientId: settings.clientId,\n\t\tclientSecret: settings.clientSecret,\n\t\tstore: options.store,\n\t\tonRedirect,\n\t});\n}\n\n/**\n * Whether the client identifies with a Client ID Metadata Document instead of registering: only with\n * `cimd` and the operator's validated base. draht: upstream's `auto` also used the application's\n * documents when the server supported them; that mode does not exist here.\n */\nexport function offersClientMetadataDocument(settings: McpOAuthSettings): boolean {\n\treturn clientMetadataBaseUrl(settings) !== undefined;\n}\n\n/**\n * The operator's Client ID Metadata Document to use, chosen like Codex chooses its own. Without the `iss`\n * parameter in authorization responses (RFC 9207), the redirect URI and the document are specific to the\n * MCP server, so a response cannot be mixed up with one from another authorization server (RFC 9700\n * section 4.4.2.2). Fails when the authorization server does not support documents for public clients:\n * draht never falls back to registering a client the operator did not ask for.\n */\nfunction clientMetadataDocument(\n\tbaseUrl: string,\n\tserverUrl: string,\n\tredirectUrl: string,\n\tmetadata: AuthorizationServerMetadata | undefined,\n): OAuthClientMetadataDocument {\n\tif (\n\t\t!metadata?.client_id_metadata_document_supported ||\n\t\t!metadata.token_endpoint_auth_methods_supported?.includes(\"none\")\n\t) {\n\t\tthrow new Error(\n\t\t\t'The authorization server does not support Client ID Metadata Documents for public clients; remove oauth.clientRegistration \"cimd\"',\n\t\t);\n\t}\n\tconst [shared, serverSpecific] = clientMetadataDocumentUrls(baseUrl, serverUrl);\n\tif (metadata.authorization_response_iss_parameter_supported) return { url: shared, redirectUrl };\n\tconst redirect = new URL(redirectUrl);\n\tredirect.pathname = serverSpecificPath(redirect.pathname, serverUrl);\n\treturn { url: serverSpecific, redirectUrl: redirect.href };\n}\n\n/** The shared and the server-specific document URL under the normalized `baseUrl`, keeping its path prefix. */\nfunction clientMetadataDocumentUrls(baseUrl: string, serverUrl: string): [string, string] {\n\treturn [new URL(\"client.json\", baseUrl).href, new URL(`${callbackId(serverUrl)}/client.json`, baseUrl).href];\n}\n\n/**\n * Whether stored credentials belong to the client the current settings identify as: the same MCP server\n * URL, and tokens issued to a document under `baseUrl` (the validated base, see `clientMetadataBaseUrl`)\n * or, without one, to a registered or pre-registered client. draht: cached tokens are never sent or\n * refreshed after the registration mode or the metadata base changed; the user signs in again.\n */\nexport function matchesClient(\n\tstate: McpOAuthState | undefined,\n\tserverUrl: string,\n\tbaseUrl: string | undefined,\n): boolean {\n\tif (!state || state.serverUrl !== new URL(serverUrl).href) return false;\n\tif (!baseUrl) return state.clientMetadataUrl === undefined;\n\treturn (\n\t\tstate.clientMetadataUrl !== undefined &&\n\t\tclientMetadataDocumentUrls(baseUrl, serverUrl).includes(state.clientMetadataUrl)\n\t);\n}\n\n/** The path of the redirect URI of a server-specific Client ID Metadata Document: `<path>/<callback ID>`. */\nexport function serverSpecificPath(path: string, serverUrl: string): string {\n\treturn `${path.replace(/\\/$/, \"\")}/${callbackId(serverUrl)}`;\n}\n\n/** 12 characters identifying an MCP server URL in callback paths, computed like Codex does. */\nfunction callbackId(serverUrl: string): string {\n\tconst url = new URL(serverUrl);\n\turl.hash = \"\";\n\treturn createHash(\"sha256\").update(url.href).digest().subarray(0, 9).toString(\"base64url\");\n}\n\n/** Redirect URIs a stored client was registered with. */\nexport function registeredRedirectUrls(client: OAuthClientInformationMixed | undefined): string[] {\n\treturn client && \"redirect_uris\" in client ? client.redirect_uris : [];\n}\n\n/**\n * Bounds each request to the authorization server, so an unresponsive one cannot hold the refresh lock,\n * delay shutdown, or keep a sign-in waiting for long.\n */\nconst OAUTH_REQUEST_TIMEOUT_MS = 15_000;\n\n/** `fetch` with `OAUTH_REQUEST_TIMEOUT_MS` per request, on top of the request's own signal. */\nexport function timedFetch(fetch: McpFetch = globalThis.fetch): McpFetch {\n\treturn (input, init) => {\n\t\tconst timeout = AbortSignal.timeout(OAUTH_REQUEST_TIMEOUT_MS);\n\t\treturn fetch(input, { ...init, signal: init?.signal ? AbortSignal.any([init.signal, timeout]) : timeout });\n\t};\n}\n\nconst CALLBACK_HOST = \"127.0.0.1\";\nconst CALLBACK_PATH = \"/callback\";\n\n/** Redirect URI when the settings name none and no client is stored. */\nexport const DEFAULT_REDIRECT_URL = `http://${CALLBACK_HOST}${CALLBACK_PATH}`;\n\n/** Where the loopback callback server listens and the redirect URI it serves, from `callbackUrl` and `callbackPort`. */\nexport interface LoopbackSettings {\n\t/** The redirect URI, without the port unless one is configured. */\n\turl: string;\n\t/** Address to listen on. */\n\thost: string;\n\t/** Host name in the redirect URI. */\n\tredirectHost: string;\n\tport: number | undefined;\n\tpath: string;\n\t/** The exact redirect URI, when the port is fixed. */\n\tfixedRedirectUrl: string | undefined;\n}\n\n/** The loopback callback settings of `settings`. */\nexport function loopbackSettings(settings: McpOAuthSettings): LoopbackSettings {\n\tconst configured = settings.callbackUrl ?? DEFAULT_REDIRECT_URL;\n\tconst url = new URL(configured);\n\tconst address = url.hostname.replace(/^\\[|\\]$/g, \"\");\n\tconst port = url.port ? Number(url.port) : settings.callbackPort;\n\tlet fixedRedirectUrl: string | undefined;\n\t// A configured URI with a port is sent exactly as written, since servers compare it as a string.\n\tif (url.port) fixedRedirectUrl = settings.callbackUrl;\n\telse if (port !== undefined) {\n\t\turl.port = String(port);\n\t\tfixedRedirectUrl = url.href;\n\t}\n\treturn {\n\t\turl: configured,\n\t\t// `localhost` is served on 127.0.0.1; browsers fall back to it when ::1 refuses.\n\t\thost: address === \"localhost\" ? CALLBACK_HOST : address,\n\t\tredirectHost: address,\n\t\tport,\n\t\tpath: url.pathname,\n\t\tfixedRedirectUrl,\n\t};\n}\n"]}