@dev-crowagent/pigeon-mcp 0.0.0-stage → 1.7.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 (136) hide show
  1. package/CHANGELOG.md +143 -0
  2. package/README.md +256 -2
  3. package/THIRD_PARTY_NOTICES/modelcontextprotocol-typescript-sdk.txt +21 -0
  4. package/dist/auth-provider.d.ts +19 -0
  5. package/dist/auth-provider.d.ts.map +1 -0
  6. package/dist/auth-provider.js +2 -0
  7. package/dist/auth-provider.js.map +1 -0
  8. package/dist/client.d.ts +193 -0
  9. package/dist/client.d.ts.map +1 -0
  10. package/dist/client.js +747 -0
  11. package/dist/client.js.map +1 -0
  12. package/dist/config-schema.d.ts +105 -0
  13. package/dist/config-schema.d.ts.map +1 -0
  14. package/dist/config-schema.js +101 -0
  15. package/dist/config-schema.js.map +1 -0
  16. package/dist/config.d.ts +57 -0
  17. package/dist/config.d.ts.map +1 -0
  18. package/dist/config.js +160 -0
  19. package/dist/config.js.map +1 -0
  20. package/dist/index.d.ts +16 -0
  21. package/dist/index.d.ts.map +1 -0
  22. package/dist/index.js +14 -0
  23. package/dist/index.js.map +1 -0
  24. package/dist/input-schema.d.ts +7 -0
  25. package/dist/input-schema.d.ts.map +1 -0
  26. package/dist/input-schema.js +13 -0
  27. package/dist/input-schema.js.map +1 -0
  28. package/dist/model-content.d.ts +19 -0
  29. package/dist/model-content.d.ts.map +1 -0
  30. package/dist/model-content.js +67 -0
  31. package/dist/model-content.js.map +1 -0
  32. package/dist/naming.d.ts +23 -0
  33. package/dist/naming.d.ts.map +1 -0
  34. package/dist/naming.js +37 -0
  35. package/dist/naming.js.map +1 -0
  36. package/dist/oauth/auth-provider.d.ts +52 -0
  37. package/dist/oauth/auth-provider.d.ts.map +1 -0
  38. package/dist/oauth/auth-provider.js +97 -0
  39. package/dist/oauth/auth-provider.js.map +1 -0
  40. package/dist/oauth/callback.d.ts +48 -0
  41. package/dist/oauth/callback.d.ts.map +1 -0
  42. package/dist/oauth/callback.js +121 -0
  43. package/dist/oauth/callback.js.map +1 -0
  44. package/dist/oauth/client-settings.d.ts +107 -0
  45. package/dist/oauth/client-settings.d.ts.map +1 -0
  46. package/dist/oauth/client-settings.js +114 -0
  47. package/dist/oauth/client-settings.js.map +1 -0
  48. package/dist/oauth/discovery.d.ts +30 -0
  49. package/dist/oauth/discovery.d.ts.map +1 -0
  50. package/dist/oauth/discovery.js +156 -0
  51. package/dist/oauth/discovery.js.map +1 -0
  52. package/dist/oauth/errors.d.ts +32 -0
  53. package/dist/oauth/errors.d.ts.map +1 -0
  54. package/dist/oauth/errors.js +58 -0
  55. package/dist/oauth/errors.js.map +1 -0
  56. package/dist/oauth/flow.d.ts +112 -0
  57. package/dist/oauth/flow.d.ts.map +1 -0
  58. package/dist/oauth/flow.js +360 -0
  59. package/dist/oauth/flow.js.map +1 -0
  60. package/dist/oauth/index.d.ts +11 -0
  61. package/dist/oauth/index.d.ts.map +1 -0
  62. package/dist/oauth/index.js +9 -0
  63. package/dist/oauth/index.js.map +1 -0
  64. package/dist/oauth/loopback.d.ts +51 -0
  65. package/dist/oauth/loopback.d.ts.map +1 -0
  66. package/dist/oauth/loopback.js +98 -0
  67. package/dist/oauth/loopback.js.map +1 -0
  68. package/dist/oauth/provider.d.ts +62 -0
  69. package/dist/oauth/provider.d.ts.map +1 -0
  70. package/dist/oauth/provider.js +118 -0
  71. package/dist/oauth/provider.js.map +1 -0
  72. package/dist/oauth/sign-in.d.ts +73 -0
  73. package/dist/oauth/sign-in.d.ts.map +1 -0
  74. package/dist/oauth/sign-in.js +182 -0
  75. package/dist/oauth/sign-in.js.map +1 -0
  76. package/dist/oauth/types.d.ts +83 -0
  77. package/dist/oauth/types.d.ts.map +1 -0
  78. package/dist/oauth/types.js +113 -0
  79. package/dist/oauth/types.js.map +1 -0
  80. package/dist/output-limit.d.ts +24 -0
  81. package/dist/output-limit.d.ts.map +1 -0
  82. package/dist/output-limit.js +58 -0
  83. package/dist/output-limit.js.map +1 -0
  84. package/dist/protocol/content.d.ts +83 -0
  85. package/dist/protocol/content.d.ts.map +1 -0
  86. package/dist/protocol/content.js +41 -0
  87. package/dist/protocol/content.js.map +1 -0
  88. package/dist/protocol/http-headers.d.ts +31 -0
  89. package/dist/protocol/http-headers.d.ts.map +1 -0
  90. package/dist/protocol/http-headers.js +129 -0
  91. package/dist/protocol/http-headers.js.map +1 -0
  92. package/dist/protocol/jsonrpc.d.ts +64 -0
  93. package/dist/protocol/jsonrpc.d.ts.map +1 -0
  94. package/dist/protocol/jsonrpc.js +74 -0
  95. package/dist/protocol/jsonrpc.js.map +1 -0
  96. package/dist/protocol/stateless.d.ts +47 -0
  97. package/dist/protocol/stateless.d.ts.map +1 -0
  98. package/dist/protocol/stateless.js +102 -0
  99. package/dist/protocol/stateless.js.map +1 -0
  100. package/dist/protocol/types.d.ts +156 -0
  101. package/dist/protocol/types.d.ts.map +1 -0
  102. package/dist/protocol/types.js +12 -0
  103. package/dist/protocol/types.js.map +1 -0
  104. package/dist/result-schema.d.ts +10 -0
  105. package/dist/result-schema.d.ts.map +1 -0
  106. package/dist/result-schema.js +78 -0
  107. package/dist/result-schema.js.map +1 -0
  108. package/dist/testing/index.d.ts +2 -0
  109. package/dist/testing/index.d.ts.map +1 -0
  110. package/dist/testing/index.js +2 -0
  111. package/dist/testing/index.js.map +1 -0
  112. package/dist/transports/in-memory.d.ts +19 -0
  113. package/dist/transports/in-memory.d.ts.map +1 -0
  114. package/dist/transports/in-memory.js +50 -0
  115. package/dist/transports/in-memory.js.map +1 -0
  116. package/dist/transports/lines.d.ts +34 -0
  117. package/dist/transports/lines.d.ts.map +1 -0
  118. package/dist/transports/lines.js +85 -0
  119. package/dist/transports/lines.js.map +1 -0
  120. package/dist/transports/pipe.d.ts +49 -0
  121. package/dist/transports/pipe.d.ts.map +1 -0
  122. package/dist/transports/pipe.js +96 -0
  123. package/dist/transports/pipe.js.map +1 -0
  124. package/dist/transports/stdio.d.ts +29 -0
  125. package/dist/transports/stdio.d.ts.map +1 -0
  126. package/dist/transports/stdio.js +170 -0
  127. package/dist/transports/stdio.js.map +1 -0
  128. package/dist/transports/streamable-http.d.ts +113 -0
  129. package/dist/transports/streamable-http.d.ts.map +1 -0
  130. package/dist/transports/streamable-http.js +586 -0
  131. package/dist/transports/streamable-http.js.map +1 -0
  132. package/dist/transports/transport.d.ts +48 -0
  133. package/dist/transports/transport.d.ts.map +1 -0
  134. package/dist/transports/transport.js +38 -0
  135. package/dist/transports/transport.js.map +1 -0
  136. package/package.json +65 -5
@@ -0,0 +1 @@
1
+ {"version":3,"file":"flow.js","sourceRoot":"","sources":["../../src/oauth/flow.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAGH,OAAO,EAAE,QAAQ,EAAE,MAAM,wBAAwB,CAAC;AAClD,OAAO,EACN,mCAAmC,EACnC,uBAAuB,EACvB,oBAAoB,EACpB,cAAc,GACd,MAAM,gBAAgB,CAAC;AACxB,OAAO,EACN,kCAAkC,EAClC,UAAU,EACV,0BAA0B,EAC1B,wBAAwB,EACxB,sBAAsB,GACtB,MAAM,aAAa,CAAC;AACrB,OAAO,EAEN,SAAS,EAOT,sBAAsB,EACtB,gBAAgB,GAChB,MAAM,YAAY,CAAC;AAmFpB,SAAS,QAAQ,CAAC,QAAgB;IACjC,OAAO,QAAQ,KAAK,WAAW,IAAI,QAAQ,KAAK,WAAW,IAAI,QAAQ,KAAK,OAAO,IAAI,QAAQ,KAAK,KAAK,CAAC;AAC3G,CAAC;AAED;;;GAGG;AACH,SAAS,eAAe,CAAC,YAA+B;IACvD,MAAM,MAAM,GAAG,YAAY,CAAC,IAAI,CAAC,CAAC,GAAG,EAAE,EAAE;QACxC,IAAI,CAAC,GAAG,CAAC,QAAQ,CAAC,GAAG,CAAC;YAAE,OAAO,KAAK,CAAC;QACrC,MAAM,GAAG,GAAG,IAAI,GAAG,CAAC,GAAG,CAAC,CAAC;QACzB,OAAO,CAAC,GAAG,CAAC,QAAQ,K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E,MAAM,IAAI,kCAAkC,EAAE,CAAC;YAC3E,CAAC,CAAC;iBACD,OAAO,CAAC,GAAG,EAAE;gBACb,QAAQ,GAAG,SAAS,CAAC;YACtB,CAAC,CAAC,CAAC;YACJ,MAAM,QAAQ,CAAC;QAChB,CAAC;KACD,CAAC;AACH,CAAC","sourcesContent":["/*\n * Adapted from modelcontextprotocol/typescript-sdk v1.29.0 src/client/auth.ts.\n * Copyright (c) 2024 Anthropic, PBC. Licensed under MIT; see THIRD_PARTY_NOTICES/.\n * Modified to remove SDK/Zod dependencies and use WebCrypto for PKCE.\n */\n\nimport type { AuthProvider, McpFetch, UnauthorizedContext } from \"../auth-provider.ts\";\nimport { isObject } from \"../protocol/jsonrpc.ts\";\nimport {\n\tdiscoverAuthorizationServerMetadata,\n\tdiscoverOAuthServerInfo,\n\tparseWwwAuthenticate,\n\tselectResource,\n} from \"./discovery.ts\";\nimport {\n\tMcpOAuthAuthorizationRequiredError,\n\tOAuthError,\n\tOAuthInsecureEndpointError,\n\tOAuthIssuerMismatchError,\n\tOAuthRegistrationError,\n} from \"./errors.ts\";\nimport {\n\ttype AuthorizationServerMetadata,\n\tisHttpUrl,\n\ttype OAuthClientInformation,\n\ttype OAuthClientInformationFull,\n\ttype OAuthClientInformationMixed,\n\ttype OAuthClientMetadata,\n\ttype OAuthDiscoveryState,\n\ttype OAuthTokens,\n\tparseClientInformation,\n\tparseOAuthTokens,\n} from \"./types.ts\";\n\nexport type AddClientAuthentication = (\n\theaders: Headers,\n\tparams: URLSearchParams,\n\turl: string | URL,\n\tmetadata?: AuthorizationServerMetadata,\n) => void | Promise<void>;\n\n/** A Client ID Metadata Document: an https URL used as `client_id`, and a redirect URI it lists. */\nexport interface OAuthClientMetadataDocument {\n\turl: string;\n\tredirectUrl: string;\n}\n\nexport interface OAuthClientProvider {\n\treadonly redirectUrl: string | URL;\n\treadonly clientMetadata: OAuthClientMetadata;\n\t/**\n\t * Client ID Metadata Document to identify as instead of registering dynamically, or `undefined` to\n\t * register. Called when no client information is stored; the document is not stored. `metadata` is\n\t * `undefined` when the authorization server has none; check `client_id_metadata_document_supported`.\n\t */\n\tclientMetadataDocument?(metadata: AuthorizationServerMetadata | undefined): OAuthClientMetadataDocument | undefined;\n\tstate?(): string | Promise<string>;\n\tclientInformation(): OAuthClientInformationMixed | undefined | Promise<OAuthClientInformationMixed | undefined>;\n\tsaveClientInformation?(information: OAuthClientInformationMixed): void | Promise<void>;\n\ttokens(): OAuthTokens | undefined | Promise<OAuthTokens | undefined>;\n\tsaveTokens(tokens: OAuthTokens): void | Promise<void>;\n\tredirectToAuthorization(url: URL): void | Promise<void>;\n\tsaveCodeVerifier(verifier: string): void | Promise<void>;\n\tcodeVerifier(): string | Promise<string>;\n\taddClientAuthentication?: AddClientAuthentication;\n\tinvalidateCredentials?(kind: \"all\" | \"client\" | \"tokens\" | \"verifier\" | \"discovery\"): void | Promise<void>;\n\tsaveDiscoveryState?(state: OAuthDiscoveryState): void | Promise<void>;\n\tdiscoveryState?(): OAuthDiscoveryState | undefined | Promise<OAuthDiscoveryState | undefined>;\n}\n\nexport interface OAuthFlowOptions {\n\tserverUrl: string | URL;\n\tauthorizationCode?: string;\n\t/** `iss` parameter of the authorization response that delivered `authorizationCode` (RFC 9207). */\n\tiss?: string;\n\tscope?: string;\n\tresourceMetadataUrl?: URL;\n\t/**\n\t * Authorization server metadata document to use instead of discovery, for servers that advertise a\n\t * wrong authorization server or none. It is trusted as configured. Must use https, except on loopback.\n\t */\n\tauthorizationServerMetadataUrl?: URL;\n\tfetch?: McpFetch;\n\t/** Aborts every request of the flow. Requests have no time limit of their own; combine with a timeout as needed. */\n\tsignal?: AbortSignal;\n\tskipIssuerValidation?: boolean;\n\t/**\n\t * Go straight to the authorization redirect instead of refreshing stored tokens, for example when the\n\t * server asks for scopes the current grant lacks (a refresh keeps the old scope).\n\t */\n\tskipRefresh?: boolean;\n\t/**\n\t * Only refresh the stored tokens: return `REDIRECT` instead of registering a client or preparing an\n\t * authorization request, so a pending authorization (its `state` and PKCE verifier) stays usable.\n\t */\n\trefreshOnly?: boolean;\n\t/**\n\t * With `authorizationCode`: the redirect URI the authorization request used. The exchange fails before\n\t * sending the code when the flow would send another one (RFC 6749 section 4.1.3 requires the same).\n\t */\n\tauthorizationRedirectUrl?: string;\n}\n\nexport type OAuthFlowResult = \"AUTHORIZED\" | \"REDIRECT\";\ntype ClientAuthMethod = \"client_secret_basic\" | \"client_secret_post\" | \"none\";\n\nexport interface TokenRequestOptions {\n\tmetadata?: AuthorizationServerMetadata;\n\tclientInformation: OAuthClientInformationMixed;\n\tresource?: string;\n\taddClientAuthentication?: AddClientAuthentication;\n\tfetch?: McpFetch;\n\tsignal?: AbortSignal;\n}\n\nfunction loopback(hostname: string): boolean {\n\treturn hostname === \"localhost\" || hostname === \"127.0.0.1\" || hostname === \"[::1]\" || hostname === \"::1\";\n}\n\n/**\n * The OpenID Connect `application_type` for `redirect_uris` (MCP SEP-837). Without one, OpenID Connect servers\n * assume `web`, which rejects http loopback redirect URIs. Loopback hosts and custom schemes are native (RFC 8252).\n */\nfunction applicationType(redirectUris: readonly string[]): \"native\" | \"web\" {\n\tconst native = redirectUris.some((uri) => {\n\t\tif (!URL.canParse(uri)) return false;\n\t\tconst url = new URL(uri);\n\t\treturn (url.protocol !== \"http:\" && url.protocol !== \"https:\") || loopback(url.hostname);\n\t});\n\treturn native ? \"native\" : \"web\";\n}\n\nfunction secureEndpoint(value: string | URL): URL {\n\tconst url = new URL(value);\n\tif (url.protocol !== \"https:\" && !loopback(url.hostname)) throw new OAuthInsecureEndpointError(url.href);\n\treturn url;\n}\n\nfunction selectClientAuthMethod(information: OAuthClientInformationMixed, supported: string[]): ClientAuthMethod {\n\tconst hinted = \"token_endpoint_auth_method\" in information ? information.token_endpoint_auth_method : undefined;\n\tif (\n\t\thinted &&\n\t\t[\"client_secret_basic\", \"client_secret_post\", \"none\"].includes(hinted) &&\n\t\t(supported.length === 0 || supported.includes(hinted))\n\t) {\n\t\treturn hinted as ClientAuthMethod;\n\t}\n\tif (supported.length === 0) return information.client_secret ? \"client_secret_basic\" : \"none\";\n\tif (information.client_secret && supported.includes(\"client_secret_basic\")) return \"client_secret_basic\";\n\tif (information.client_secret && supported.includes(\"client_secret_post\")) return \"client_secret_post\";\n\tif (supported.includes(\"none\")) return \"none\";\n\treturn information.client_secret ? \"client_secret_post\" : \"none\";\n}\n\nfunction applyClientAuthentication(\n\tmethod: ClientAuthMethod,\n\tinformation: OAuthClientInformation,\n\theaders: Headers,\n\tparams: URLSearchParams,\n): void {\n\tif (method === \"client_secret_basic\") {\n\t\tif (!information.client_secret) throw new Error(\"client_secret_basic requires a client secret\");\n\t\theaders.set(\n\t\t\t\"Authorization\",\n\t\t\t`Basic ${Buffer.from(`${information.client_id}:${information.client_secret}`).toString(\"base64\")}`,\n\t\t);\n\t} else {\n\t\tparams.set(\"client_id\", information.client_id);\n\t\tif (method === \"client_secret_post\" && information.client_secret)\n\t\t\tparams.set(\"client_secret\", information.client_secret);\n\t}\n}\n\nasync function pkce(): Promise<{ verifier: string; challenge: string }> {\n\tconst bytes = crypto.getRandomValues(new Uint8Array(32));\n\tconst verifier = Buffer.from(bytes).toString(\"base64url\");\n\tconst digest = await crypto.subtle.digest(\"SHA-256\", new TextEncoder().encode(verifier));\n\treturn { verifier, challenge: Buffer.from(digest).toString(\"base64url\") };\n}\n\nexport async function startAuthorization(\n\tauthorizationServerUrl: string | URL,\n\toptions: {\n\t\tmetadata?: AuthorizationServerMetadata;\n\t\tclientInformation: OAuthClientInformationMixed;\n\t\tredirectUrl: string | URL;\n\t\tscope?: string;\n\t\tstate?: string;\n\t\tresource?: string;\n\t},\n): Promise<{ authorizationUrl: URL; codeVerifier: string }> {\n\tconst metadata = options.metadata;\n\tif (metadata && !metadata.response_types_supported.includes(\"code\")) {\n\t\tthrow new Error(\"Authorization server does not support authorization codes\");\n\t}\n\tif (metadata?.code_challenge_methods_supported && !metadata.code_challenge_methods_supported.includes(\"S256\")) {\n\t\tthrow new Error(\"Authorization server does not support PKCE S256\");\n\t}\n\tconst url = new URL(metadata?.authorization_endpoint ?? new URL(\"/authorize\", authorizationServerUrl));\n\t// Callers open this URL with the platform URL handler, which also launches files and custom protocols.\n\tif (!isHttpUrl(url)) throw new Error(`Invalid authorization endpoint ${url.href}`);\n\tconst { verifier, challenge } = await pkce();\n\turl.searchParams.set(\"response_type\", \"code\");\n\turl.searchParams.set(\"client_id\", options.clientInformation.client_id);\n\turl.searchParams.set(\"code_challenge\", challenge);\n\turl.searchParams.set(\"code_challenge_method\", \"S256\");\n\turl.searchParams.set(\"redirect_uri\", String(options.redirectUrl));\n\tif (options.state) url.searchParams.set(\"state\", options.state);\n\tif (options.scope) url.searchParams.set(\"scope\", options.scope);\n\tif (options.scope?.split(/\\s+/).includes(\"offline_access\")) url.searchParams.set(\"prompt\", \"consent\");\n\tif (options.resource) url.searchParams.set(\"resource\", options.resource);\n\treturn { authorizationUrl: url, codeVerifier: verifier };\n}\n\nasync function tokenRequest(\n\tauthorizationServerUrl: string | URL,\n\toptions: TokenRequestOptions,\n\tparams: URLSearchParams,\n): Promise<OAuthTokens> {\n\tconst url = secureEndpoint(options.metadata?.token_endpoint ?? new URL(\"/token\", authorizationServerUrl));\n\tconst headers = new Headers({ Accept: \"application/json\", \"content-type\": \"application/x-www-form-urlencoded\" });\n\tif (options.resource) params.set(\"resource\", options.resource);\n\tif (options.addClientAuthentication) {\n\t\tawait options.addClientAuthentication(headers, params, url, options.metadata);\n\t} else {\n\t\tapplyClientAuthentication(\n\t\t\tselectClientAuthMethod(\n\t\t\t\toptions.clientInformation,\n\t\t\t\toptions.metadata?.token_endpoint_auth_methods_supported ?? [],\n\t\t\t),\n\t\t\toptions.clientInformation,\n\t\t\theaders,\n\t\t\tparams,\n\t\t);\n\t}\n\tconst response = await (options.fetch ?? globalThis.fetch)(url, {\n\t\tmethod: \"POST\",\n\t\theaders,\n\t\tbody: params,\n\t\tsignal: options.signal,\n\t});\n\tconst text = await response.text();\n\tlet value: unknown;\n\ttry {\n\t\tvalue = JSON.parse(text);\n\t} catch {}\n\t// Servers may report OAuth errors with any status, so check the body before the status.\n\tif (isObject(value) && typeof value.error === \"string\") {\n\t\tthrow new OAuthError(\n\t\t\tvalue.error,\n\t\t\ttypeof value.error_description === \"string\" ? value.error_description : value.error,\n\t\t\ttypeof value.error_uri === \"string\" ? value.error_uri : undefined,\n\t\t);\n\t}\n\tif (!response.ok) throw new OAuthError(\"server_error\", `HTTP ${response.status}: ${text}`);\n\treturn parseOAuthTokens(value);\n}\n\nexport async function registerClient(\n\tauthorizationServerUrl: string | URL,\n\toptions: {\n\t\tmetadata?: AuthorizationServerMetadata;\n\t\tclientMetadata: OAuthClientMetadata;\n\t\tscope?: string;\n\t\tfetch?: McpFetch;\n\t\tsignal?: AbortSignal;\n\t},\n): Promise<OAuthClientInformationFull> {\n\tconst endpoint = options.metadata?.registration_endpoint;\n\tif (options.metadata && !endpoint)\n\t\tthrow new Error(\"Authorization server does not support dynamic client registration\");\n\tconst response = await (options.fetch ?? globalThis.fetch)(\n\t\tnew URL(endpoint ?? new URL(\"/register\", authorizationServerUrl)),\n\t\t{\n\t\t\tmethod: \"POST\",\n\t\t\theaders: { Accept: \"application/json\", \"content-type\": \"application/json\" },\n\t\t\tbody: JSON.stringify({\n\t\t\t\t...options.clientMetadata,\n\t\t\t\tapplication_type:\n\t\t\t\t\toptions.clientMetadata.application_type ?? applicationType(options.clientMetadata.redirect_uris),\n\t\t\t\t...(options.scope ? { scope: options.scope } : {}),\n\t\t\t}),\n\t\t\tsignal: options.signal,\n\t\t},\n\t);\n\tif (!response.ok) throw new OAuthRegistrationError(response.status, await response.text());\n\treturn parseClientInformation(await response.json());\n}\n\nexport async function exchangeAuthorizationCode(\n\tauthorizationServerUrl: string | URL,\n\toptions: TokenRequestOptions & { code: string; codeVerifier: string; redirectUrl: string | URL },\n): Promise<OAuthTokens> {\n\treturn tokenRequest(\n\t\tauthorizationServerUrl,\n\t\toptions,\n\t\tnew URLSearchParams({\n\t\t\tgrant_type: \"authorization_code\",\n\t\t\tcode: options.code,\n\t\t\tcode_verifier: options.codeVerifier,\n\t\t\tredirect_uri: String(options.redirectUrl),\n\t\t}),\n\t);\n}\n\nexport async function refreshAuthorization(\n\tauthorizationServerUrl: string | URL,\n\toptions: TokenRequestOptions & { refreshToken: string },\n): Promise<OAuthTokens> {\n\tconst tokens = await tokenRequest(\n\t\tauthorizationServerUrl,\n\t\toptions,\n\t\tnew URLSearchParams({ grant_type: \"refresh_token\", refresh_token: options.refreshToken }),\n\t);\n\treturn { refresh_token: options.refreshToken, ...tokens };\n}\n\nfunction withScope(tokens: OAuthTokens, scope: string | undefined): OAuthTokens {\n\treturn tokens.scope === undefined && scope ? { ...tokens, scope } : tokens;\n}\n\n/**\n * Scopes for a step-up authorization: the challenged scopes plus the ones granted so far, since a\n * challenge may list only the missing scopes and a token with just those would lose access the old\n * one had (SEP-2350). Without challenged scopes, `undefined` lets the flow pick its default.\n */\nexport function stepUpScope(granted: string | undefined, challenged: string | undefined): string | undefined {\n\tif (!challenged) return undefined;\n\tconst scopes = [granted, challenged].flatMap((scope) => scope?.split(/\\s+/).filter(Boolean) ?? []);\n\treturn [...new Set(scopes)].join(\" \");\n}\n\n/** What a flow used, for deciding what to invalidate after it failed. */\ninterface FlowUse {\n\t/** `client_id` of the stored client the flow used; `undefined` when none was stored. */\n\tstoredClientId?: string;\n}\n\nasync function runFlow(\n\tprovider: OAuthClientProvider,\n\toptions: OAuthFlowOptions,\n\tuse: FlowUse = {},\n): Promise<OAuthFlowResult> {\n\tconst metadataUrl = options.authorizationServerMetadataUrl && secureEndpoint(options.authorizationServerMetadataUrl);\n\t// With a configured metadata URL, discovery is not cached, so changing the URL applies at once.\n\tconst cached = metadataUrl ? undefined : await provider.discoveryState?.();\n\tconst discovered = cached?.authorizationServerUrl\n\t\t? {\n\t\t\t\tauthorizationServerUrl: cached.authorizationServerUrl,\n\t\t\t\tauthorizationServerMetadata:\n\t\t\t\t\tcached.authorizationServerMetadata ??\n\t\t\t\t\t(await discoverAuthorizationServerMetadata(cached.authorizationServerUrl, {\n\t\t\t\t\t\tfetch: options.fetch,\n\t\t\t\t\t\tskipIssuerValidation: options.skipIssuerValidation,\n\t\t\t\t\t\tsignal: options.signal,\n\t\t\t\t\t})),\n\t\t\t\tresourceMetadata: cached.resourceMetadata,\n\t\t\t}\n\t\t: await discoverOAuthServerInfo(options.serverUrl, {\n\t\t\t\tresourceMetadataUrl: options.resourceMetadataUrl,\n\t\t\t\tauthorizationServerMetadataUrl: metadataUrl,\n\t\t\t\tfetch: options.fetch,\n\t\t\t\tskipIssuerValidation: options.skipIssuerValidation,\n\t\t\t\tsignal: options.signal,\n\t\t\t});\n\tif (!metadataUrl) {\n\t\tawait provider.saveDiscoveryState?.({\n\t\t\t...discovered,\n\t\t\t...(options.resourceMetadataUrl ? { resourceMetadataUrl: options.resourceMetadataUrl.href } : {}),\n\t\t});\n\t}\n\tconst metadata = discovered.authorizationServerMetadata;\n\tconst resource = selectResource(options.serverUrl, discovered.resourceMetadata);\n\t// `||`, not `??`: an empty scope (for example from `scopes_supported: []`) falls through to the next source.\n\tconst scope =\n\t\toptions.scope || discovered.resourceMetadata?.scopes_supported?.join(\" \") || provider.clientMetadata.scope;\n\tconst stored = await provider.clientInformation();\n\tuse.storedClientId = stored?.client_id;\n\tconst clientDocument = stored ? undefined : provider.clientMetadataDocument?.(metadata);\n\tif (clientDocument) {\n\t\tconst url = new URL(clientDocument.url);\n\t\tif (url.protocol !== \"https:\" || url.pathname === \"/\") throw new Error(\"Invalid OAuth client metadata URL\");\n\t}\n\t// The document's redirect URI may differ from the provider's, for example by a server-specific path.\n\tconst redirectUrl = clientDocument?.redirectUrl ?? String(provider.redirectUrl);\n\t// Checked first: another redirect URI also explains a client that is missing for the exchange.\n\tif (options.authorizationCode && options.authorizationRedirectUrl !== undefined) {\n\t\tif (redirectUrl !== options.authorizationRedirectUrl) {\n\t\t\tthrow new Error(\n\t\t\t\t`The code exchange would use the redirect URI ${redirectUrl}, but the authorization request used ${options.authorizationRedirectUrl}`,\n\t\t\t);\n\t\t}\n\t}\n\tlet client = stored ?? (clientDocument && { client_id: clientDocument.url });\n\tif (!client) {\n\t\tif (options.refreshOnly) return \"REDIRECT\";\n\t\tif (options.authorizationCode) {\n\t\t\tthrow new Error(\n\t\t\t\t\"OAuth client information is missing during code exchange: the authorization request's client was removed, or the client settings changed\",\n\t\t\t);\n\t\t}\n\t\tif (!provider.saveClientInformation) throw new Error(\"OAuth client information cannot be persisted\");\n\t\tclient = await registerClient(discovered.authorizationServerUrl, {\n\t\t\tmetadata,\n\t\t\tclientMetadata: provider.clientMetadata,\n\t\t\tscope,\n\t\t\tfetch: options.fetch,\n\t\t\tsignal: options.signal,\n\t\t});\n\t\tawait provider.saveClientInformation(client);\n\t}\n\tconst tokenOptions: TokenRequestOptions = {\n\t\tmetadata,\n\t\tclientInformation: client,\n\t\tresource,\n\t\taddClientAuthentication: provider.addClientAuthentication,\n\t\tfetch: options.fetch,\n\t\tsignal: options.signal,\n\t};\n\tif (options.authorizationCode) {\n\t\t// RFC 9207: never send a code from another authorization server to this one. Without metadata there\n\t\t// is no issuer to compare with, so any `iss` is rejected.\n\t\tconst iss = options.iss;\n\t\tif (iss !== undefined || metadata?.authorization_response_iss_parameter_supported) {\n\t\t\tif (iss !== metadata?.issuer) throw new OAuthIssuerMismatchError(metadata?.issuer, iss);\n\t\t}\n\t\tconst tokens = await exchangeAuthorizationCode(discovered.authorizationServerUrl, {\n\t\t\t...tokenOptions,\n\t\t\tcode: options.authorizationCode,\n\t\t\tcodeVerifier: await provider.codeVerifier(),\n\t\t\tredirectUrl,\n\t\t});\n\t\t// A response without `scope` grants the requested scope (RFC 6749 §5.1). Recorded so a step-up can\n\t\t// keep it. Callers pass the options of the authorization request, so `scope` is what was requested.\n\t\tawait provider.saveTokens(withScope(tokens, scope));\n\t\treturn \"AUTHORIZED\";\n\t}\n\tconst existing = options.skipRefresh ? undefined : await provider.tokens();\n\tif (existing?.refresh_token) {\n\t\ttry {\n\t\t\tconst tokens = await refreshAuthorization(discovered.authorizationServerUrl, {\n\t\t\t\t...tokenOptions,\n\t\t\t\trefreshToken: existing.refresh_token,\n\t\t\t});\n\t\t\t// A refresh without `scope` keeps the scope of the grant (RFC 6749 §6).\n\t\t\tawait provider.saveTokens(withScope(tokens, existing.scope));\n\t\t\treturn \"AUTHORIZED\";\n\t\t} catch (error) {\n\t\t\tif (options.signal?.aborted || error instanceof OAuthInsecureEndpointError) throw error;\n\t\t\tif (error instanceof OAuthError && error.code !== \"server_error\") throw error;\n\t\t}\n\t}\n\tif (options.refreshOnly) return \"REDIRECT\";\n\tconst state = await provider.state?.();\n\tconst authorization = await startAuthorization(discovered.authorizationServerUrl, {\n\t\tmetadata,\n\t\tclientInformation: client,\n\t\tredirectUrl,\n\t\tscope,\n\t\tstate,\n\t\tresource,\n\t});\n\tawait provider.saveCodeVerifier(authorization.codeVerifier);\n\tawait provider.redirectToAuthorization(authorization.authorizationUrl);\n\treturn \"REDIRECT\";\n}\n\nexport async function authorizeMcp(provider: OAuthClientProvider, options: OAuthFlowOptions): Promise<OAuthFlowResult> {\n\tconst use: FlowUse = {};\n\ttry {\n\t\treturn await runFlow(provider, options, use);\n\t} catch (error) {\n\t\tif (error instanceof OAuthError && [\"invalid_client\", \"unauthorized_client\"].includes(error.code)) {\n\t\t\t// A refresh keeps a pending authorization's `state` and verifier: they are the user's sign-in. A client\n\t\t\t// stored meanwhile (by a sign-in that completed) is not the one the server rejected, so it stays.\n\t\t\tif (options.refreshOnly) {\n\t\t\t\tif ((await provider.clientInformation())?.client_id === use.storedClientId) {\n\t\t\t\t\tfor (const kind of [\"client\", \"tokens\", \"discovery\"] as const)\n\t\t\t\t\t\tawait provider.invalidateCredentials?.(kind);\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tawait provider.invalidateCredentials?.(\"all\");\n\t\t\t}\n\t\t\treturn runFlow(provider, options);\n\t\t}\n\t\tif (error instanceof OAuthError && error.code === \"invalid_grant\") {\n\t\t\tawait provider.invalidateCredentials?.(\"tokens\");\n\t\t\treturn runFlow(provider, options);\n\t\t}\n\t\tthrow error;\n\t}\n}\n\n/**\n * Auth provider for `StreamableHttpTransport`. After a 401 it refreshes the tokens, or throws\n * `McpOAuthAuthorizationRequiredError` when the user has to authorize (again). Concurrent 401s share\n * one refresh, and a request whose token was already replaced is just retried: with rotating refresh\n * tokens, a second refresh with the old refresh token would fail and discard the new grant.\n */\nexport function adaptOAuthProvider(provider: OAuthClientProvider): AuthProvider {\n\tlet inFlight: Promise<void> | undefined;\n\treturn {\n\t\ttoken: async () => (await provider.tokens())?.access_token,\n\t\tonUnauthorized: async (context: UnauthorizedContext) => {\n\t\t\tconst challenge = parseWwwAuthenticate(context.response.headers.get(\"www-authenticate\"));\n\t\t\tconst insufficientScope = challenge.error === \"insufficient_scope\";\n\t\t\tif (!insufficientScope && !inFlight && context.token !== undefined) {\n\t\t\t\tconst current = (await provider.tokens())?.access_token;\n\t\t\t\tif (current !== undefined && current !== context.token) return;\n\t\t\t}\n\t\t\tinFlight ??= Promise.resolve(insufficientScope ? provider.tokens() : undefined)\n\t\t\t\t.then((granted) =>\n\t\t\t\t\tauthorizeMcp(provider, {\n\t\t\t\t\t\tserverUrl: context.serverUrl,\n\t\t\t\t\t\tresourceMetadataUrl: challenge.resourceMetadataUrl,\n\t\t\t\t\t\tscope: insufficientScope ? stepUpScope(granted?.scope, challenge.scope) : challenge.scope,\n\t\t\t\t\t\tfetch: context.fetch,\n\t\t\t\t\t\tskipRefresh: insufficientScope,\n\t\t\t\t\t}),\n\t\t\t\t)\n\t\t\t\t.then((result) => {\n\t\t\t\t\tif (result === \"REDIRECT\") throw new McpOAuthAuthorizationRequiredError();\n\t\t\t\t})\n\t\t\t\t.finally(() => {\n\t\t\t\t\tinFlight = undefined;\n\t\t\t\t});\n\t\t\tawait inFlight;\n\t\t},\n\t};\n}\n"]}
@@ -0,0 +1,11 @@
1
+ export { createMcpAuthProvider, type McpAuthProvider } from "./auth-provider.ts";
2
+ export { type OAuthCallback, type OAuthCallbackPage, OAuthCallbackServer, type OAuthCallbackServerOptions, } from "./callback.ts";
3
+ export type { McpClientMetadataDocuments, McpOAuthClientOptions, McpOAuthServerStore, McpOAuthSettings, } from "./client-settings.ts";
4
+ export { buildAuthorizationServerDiscoveryUrls, discoverAuthorizationServerMetadata, discoverOAuthServerInfo, discoverProtectedResourceMetadata, parseWwwAuthenticate, resourceUrlFromServerUrl, selectResource, } from "./discovery.ts";
5
+ export { McpOAuthAuthorizationRequiredError, McpRefreshLockBusyError, OAuthError, OAuthInsecureEndpointError, OAuthIssuerMismatchError, OAuthRegistrationError, } from "./errors.ts";
6
+ export { type AddClientAuthentication, adaptOAuthProvider, authorizeMcp, exchangeAuthorizationCode, type OAuthClientMetadataDocument, type OAuthClientProvider, type OAuthFlowOptions, type OAuthFlowResult, refreshAuthorization, registerClient, startAuthorization, stepUpScope, type TokenRequestOptions, } from "./flow.ts";
7
+ export { listenForLoopbackSignIn, type McpLoopbackCallback, responseFromRedirectUrl, waitForLoopbackSignIn, } from "./loopback.ts";
8
+ export { McpOAuthProvider, type McpOAuthProviderOptions, type McpOAuthState, type McpOAuthStateStore, MemoryOAuthStateStore, } from "./provider.ts";
9
+ export { completeMcpSignIn, type McpAuthorizationResponse, McpSignInCancelledError, type McpSignInOptions, type McpSignInRedirect, type McpSignInStart, startMcpSignIn, } from "./sign-in.ts";
10
+ export type { AuthorizationServerMetadata, OAuthChallenge, OAuthClientInformation, OAuthClientInformationFull, OAuthClientInformationMixed, OAuthClientMetadata, OAuthDiscoveryState, OAuthProtectedResourceMetadata, OAuthServerInfo, OAuthTokens, } from "./types.ts";
11
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/oauth/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,qBAAqB,EAAE,KAAK,eAAe,E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AA8B,EAC9B,eAAe,EACf,WAAW,GACX,MAAM,YAAY,CAAC"}
@@ -0,0 +1,9 @@
1
+ export { createMcpAuthProvider } from "./auth-provider.js";
2
+ export { OAuthCallbackServer, } from "./callback.js";
3
+ export { buildAuthorizationServerDiscoveryUrls, discoverAuthorizationServerMetadata, discoverOAuthServerInfo, discoverProtectedResourceMetadata, parseWwwAuthenticate, resourceUrlFromServerUrl, selectResource, } from "./discovery.js";
4
+ export { McpOAuthAuthorizationRequiredError, McpRefreshLockBusyError, OAuthError, OAuthInsecureEndpointError, OAuthIssuerMismatchError, OAuthRegistrationError, } from "./errors.js";
5
+ export { adaptOAuthProvider, authorizeMcp, exchangeAuthorizationCode, refreshAuthorization, registerClient, startAuthorization, stepUpScope, } from "./flow.js";
6
+ export { listenForLoopbackSignIn, responseFromRedirectUrl, waitForLoopbackSignIn, } from "./loopback.js";
7
+ export { McpOAuthProvider, MemoryOAuthStateStore, } from "./provider.js";
8
+ export { completeMcpSignIn, McpSignInCancelledError, startMcpSignIn, } from "./sign-in.js";
9
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/oauth/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,qBAAqB,EAAwB,MAAM,oBAAoB,CAAC;AACjF,OAAO,EAGN,mBAAmB,GAEnB,MAAM,eAAe,CAAC;AAOvB,OAAO,EACN,qCAAqC,EACrC,mCAAmC,EACnC,uBAAuB,EACvB,iCAAiC,EACjC,oBAAoB,EACpB,wBAAwB,EACxB,cAAc,GACd,MAAM,gBAAgB,CAAC;AACxB,OAAO,EACN,kCAAkC,EAClC,uBAAuB,EACvB,UAAU,EACV,0BAA0B,EAC1B,wBAAwB,EACxB,sBAAsB,GACtB,MAAM,aAAa,CAAC;AACrB,OAAO,EAEN,kBAAkB,EAClB,YAAY,EACZ,yBAAyB,EAKzB,oBAAoB,EACpB,cAAc,EACd,kBAAkB,EAClB,WAAW,GAEX,MAAM,WAAW,CAAC;AACnB,OAAO,EACN,uBAAuB,EAEvB,uBAAuB,EACvB,qBAAqB,GACrB,MAAM,eAAe,CAAC;AACvB,OAAO,EACN,gBAAgB,EAIhB,qBAAqB,GACrB,MAAM,eAAe,CAAC;AACvB,OAAO,EACN,iBAAiB,EAEjB,uBAAuB,EAIvB,cAAc,GACd,MAAM,cAAc,CAAC","sourcesContent":["export { createMcpAuthProvider, type McpAuthProvider } from \"./auth-provider.ts\";\nexport {\n\ttype OAuthCallback,\n\ttype OAuthCallbackPage,\n\tOAuthCallbackServer,\n\ttype OAuthCallbackServerOptions,\n} from \"./callback.ts\";\nexport type {\n\tMcpClientMetadataDocuments,\n\tMcpOAuthClientOptions,\n\tMcpOAuthServerStore,\n\tMcpOAuthSettings,\n} from \"./client-settings.ts\";\nexport {\n\tbuildAuthorizationServerDiscoveryUrls,\n\tdiscoverAuthorizationServerMetadata,\n\tdiscoverOAuthServerInfo,\n\tdiscoverProtectedResourceMetadata,\n\tparseWwwAuthenticate,\n\tresourceUrlFromServerUrl,\n\tselectResource,\n} from \"./discovery.ts\";\nexport {\n\tMcpOAuthAuthorizationRequiredError,\n\tMcpRefreshLockBusyError,\n\tOAuthError,\n\tOAuthInsecureEndpointError,\n\tOAuthIssuerMismatchError,\n\tOAuthRegistrationError,\n} from \"./errors.ts\";\nexport {\n\ttype AddClientAuthentication,\n\tadaptOAuthProvider,\n\tauthorizeMcp,\n\texchangeAuthorizationCode,\n\ttype OAuthClientMetadataDocument,\n\ttype OAuthClientProvider,\n\ttype OAuthFlowOptions,\n\ttype OAuthFlowResult,\n\trefreshAuthorization,\n\tregisterClient,\n\tstartAuthorization,\n\tstepUpScope,\n\ttype TokenRequestOptions,\n} from \"./flow.ts\";\nexport {\n\tlistenForLoopbackSignIn,\n\ttype McpLoopbackCallback,\n\tresponseFromRedirectUrl,\n\twaitForLoopbackSignIn,\n} from \"./loopback.ts\";\nexport {\n\tMcpOAuthProvider,\n\ttype McpOAuthProviderOptions,\n\ttype McpOAuthState,\n\ttype McpOAuthStateStore,\n\tMemoryOAuthStateStore,\n} from \"./provider.ts\";\nexport {\n\tcompleteMcpSignIn,\n\ttype McpAuthorizationResponse,\n\tMcpSignInCancelledError,\n\ttype McpSignInOptions,\n\ttype McpSignInRedirect,\n\ttype McpSignInStart,\n\tstartMcpSignIn,\n} from \"./sign-in.ts\";\nexport type {\n\tAuthorizationServerMetadata,\n\tOAuthChallenge,\n\tOAuthClientInformation,\n\tOAuthClientInformationFull,\n\tOAuthClientInformationMixed,\n\tOAuthClientMetadata,\n\tOAuthDiscoveryState,\n\tOAuthProtectedResourceMetadata,\n\tOAuthServerInfo,\n\tOAuthTokens,\n} from \"./types.ts\";\n"]}
@@ -0,0 +1,51 @@
1
+ /**
2
+ * How the authorization response of a sign-in reaches a local application: a loopback callback server
3
+ * the browser redirects to, or a redirect URL the user pastes from the browser address bar.
4
+ */
5
+ import { type OAuthCallbackPage, OAuthCallbackServer } from "./callback.ts";
6
+ import { type McpClientMetadataDocuments, type McpOAuthSettings } from "./client-settings.ts";
7
+ import type { McpOAuthStateStore } from "./provider.ts";
8
+ import { type McpAuthorizationResponse, type McpSignInRedirect } from "./sign-in.ts";
9
+ /** A loopback callback server and the redirect URI it serves. */
10
+ export interface McpLoopbackCallback {
11
+ callback: OAuthCallbackServer;
12
+ /** Pass to `startMcpSignIn` and `completeMcpSignIn`. */
13
+ redirectUrl: string;
14
+ }
15
+ /**
16
+ * Listen for the authorization response of a sign-in on loopback, where `settings` say: `callbackUrl`
17
+ * and `callbackPort`, else the port of the stored client's redirect URI (so that client stays valid) or
18
+ * a free one. Pass the sign-in's `clientMetadataDocuments`, so the callback server also serves the
19
+ * server-specific redirect URI. Close the callback server when the sign-in ends.
20
+ */
21
+ export declare function listenForLoopbackSignIn(options: {
22
+ serverUrl: string;
23
+ store: McpOAuthStateStore;
24
+ settings: McpOAuthSettings;
25
+ clientMetadataDocuments?: McpClientMetadataDocuments;
26
+ /** Renders the browser page after the redirect. Default: plain text. */
27
+ renderPage?: (page: OAuthCallbackPage) => string;
28
+ }): Promise<McpLoopbackCallback>;
29
+ /**
30
+ * Wait for the authorization response on a loopback callback server, or for a redirect URL the user
31
+ * pastes from the browser address bar, whichever comes first. Aborting `signal` stops the wait with
32
+ * `McpSignInCancelledError`.
33
+ */
34
+ export declare function waitForLoopbackSignIn(options: {
35
+ callback: OAuthCallbackServer;
36
+ /** The `redirect` result of `startMcpSignIn`. */
37
+ authorization: McpSignInRedirect;
38
+ /**
39
+ * Ask for the redirect URL, for when the browser cannot reach the loopback callback (for example over
40
+ * SSH). Aborted once the callback arrives or the sign-in is cancelled. Resolving to `undefined` or an
41
+ * empty string cancels the sign-in.
42
+ */
43
+ promptForRedirectUrl?: (signal: AbortSignal) => Promise<string | undefined>;
44
+ signal?: AbortSignal;
45
+ }): Promise<McpAuthorizationResponse>;
46
+ /**
47
+ * The authorization response in a redirect URL the user pasted from the browser address bar. Fails when
48
+ * the URL is not on the sign-in's redirect URI, carries another `state`, or reports an error.
49
+ */
50
+ export declare function responseFromRedirectUrl(input: string, authorization: Pick<McpSignInRedirect, "state" | "redirectUrl">): McpAuthorizationResponse;
51
+ //# sourceMappingURL=loopback.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"loopback.d.ts","sourceRoot":"","sources":["../../src/oauth/loopback.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAEH,OAAO,EAAE,KAAK,iBAAiB,EAAE,mBAAmB,EAAE,MAAM,eAAe,CAAC;AAC5E,OAAO,EAEN,KAAK,0BAA0B,EAC/B,KAAK,gBAAgB,EAIrB,MAAM,sBAAsB,CAAC;AAC9B,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,eAAe,CAAC;AACxD,OAAO,EAEN,KAAK,wBAAwB,EAE7B,KAAK,iBAAiB,EACtB,MAAM,cAAc,CAAC;AAEtB,iEAAiE;AACjE,MAAM,WAAW,mBAAmB;IACnC,QAAQ,EAAE,mBAAmB,CAAC;IAC9B,wDAAwD;IACxD,WAAW,EAAE,MAAM,CAAC;CACpB;AAED;;;;;GAKG;AACH,wBAAsB,uBAAuB,CAAC,OAAO,EAAE;IACtD,SAAS,EAAE,MAAM,CAAC;IAClB,KAAK,EAAE,kBAAkB,CAAC;IAC1B,QAAQ,EAAE,gBAAgB,CAAC;IAC3B,uBAAuB,CAAC,EAAE,0BAA0B,CAAC;IACrD,wEAAwE;IACxE,UAAU,CAAC,EAAE,CAAC,IAAI,EAAE,iBAAiB,KAAK,MAAM,CAAC;CACjD,GAAG,OAAO,CAAC,mBAAmB,CAAC,CAuB/B;AAED;;;;GAIG;AACH,wBAAsB,qBAAqB,CAAC,OAAO,EAAE;IACpD,QAAQ,EAAE,mBAAmB,CAAC;IAC9B,iDAAiD;IACjD,aAAa,EAAE,iBAAiB,CAAC;IACjC;;;;OAIG;IACH,oBAAoB,CAAC,EAAE,CAAC,MAAM,EAAE,WAAW,KAAK,OAAO,CAAC,MAAM,GAAG,SAAS,CAAC,CAAC;IAC5E,MAAM,CAAC,EAAE,WAAW,CAAC;CACrB,GAAG,OAAO,CAAC,wBAAwB,CAAC,CAwBpC;AAED;;;GAGG;AACH,wBAAgB,uBAAuB,CACtC,KAAK,EAAE,MAAM,EACb,aAAa,EAAE,IAAI,CAAC,iBAAiB,EAAE,OAAO,GAAG,aAAa,CAAC,GAC7D,wBAAwB,CAoB1B"}
@@ -0,0 +1,98 @@
1
+ /**
2
+ * How the authorization response of a sign-in reaches a local application: a loopback callback server
3
+ * the browser redirects to, or a redirect URL the user pastes from the browser address bar.
4
+ */
5
+ import { OAuthCallbackServer } from "./callback.js";
6
+ import { loopbackSettings, offersClientMetadataDocument, registeredRedirectUrls, serverSpecificPath, } from "./client-settings.js";
7
+ import { cancellable, McpSignInCancelledError, } from "./sign-in.js";
8
+ /**
9
+ * Listen for the authorization response of a sign-in on loopback, where `settings` say: `callbackUrl`
10
+ * and `callbackPort`, else the port of the stored client's redirect URI (so that client stays valid) or
11
+ * a free one. Pass the sign-in's `clientMetadataDocuments`, so the callback server also serves the
12
+ * server-specific redirect URI. Close the callback server when the sign-in ends.
13
+ */
14
+ export async function listenForLoopbackSignIn(options) {
15
+ const { settings } = options;
16
+ const loopback = loopbackSettings(settings);
17
+ const registered = registeredRedirectUrls((await options.store.load())?.clientInformation)[0];
18
+ const port = loopback.port ?? (registered ? Number(new URL(registered).port) || undefined : undefined);
19
+ const offersDocument = offersClientMetadataDocument(settings, options.clientMetadataDocuments, loopback.url);
20
+ const listenOptions = {
21
+ host: loopback.host,
22
+ redirectHost: loopback.redirectHost,
23
+ path: loopback.path,
24
+ // The redirect URI of a server-specific Client ID Metadata Document.
25
+ extraPaths: offersDocument ? [serverSpecificPath(loopback.path, options.serverUrl)] : [],
26
+ renderPage: options.renderPage,
27
+ };
28
+ let callback;
29
+ try {
30
+ callback = await OAuthCallbackServer.listen({ ...listenOptions, port: port ?? 0 });
31
+ }
32
+ catch (error) {
33
+ // A configured port is required; the stored client's port is only preferred.
34
+ if (loopback.port !== undefined || port === undefined)
35
+ throw error;
36
+ callback = await OAuthCallbackServer.listen(listenOptions);
37
+ }
38
+ return { callback, redirectUrl: loopback.fixedRedirectUrl ?? callback.redirectUrl };
39
+ }
40
+ /**
41
+ * Wait for the authorization response on a loopback callback server, or for a redirect URL the user
42
+ * pastes from the browser address bar, whichever comes first. Aborting `signal` stops the wait with
43
+ * `McpSignInCancelledError`.
44
+ */
45
+ export async function waitForLoopbackSignIn(options) {
46
+ const { authorization } = options;
47
+ const controller = new AbortController();
48
+ const signal = options.signal ? AbortSignal.any([controller.signal, options.signal]) : controller.signal;
49
+ const fromBrowser = options.callback.waitForCallback(authorization.state, new URL(authorization.redirectUrl).pathname);
50
+ const fromUser = options.promptForRedirectUrl
51
+ ? options.promptForRedirectUrl(signal).then((input) => {
52
+ if (!input?.trim())
53
+ throw new McpSignInCancelledError();
54
+ return responseFromRedirectUrl(input, authorization);
55
+ })
56
+ : new Promise((_, reject) => {
57
+ signal.addEventListener("abort", () => reject(new McpSignInCancelledError()), { once: true });
58
+ });
59
+ try {
60
+ return await cancellable(options.signal, () => Promise.race([fromBrowser, fromUser]));
61
+ }
62
+ finally {
63
+ // The losing side rejects once the prompt is aborted or the callback server closes.
64
+ controller.abort();
65
+ fromBrowser.catch(() => undefined);
66
+ fromUser.catch(() => undefined);
67
+ }
68
+ }
69
+ /**
70
+ * The authorization response in a redirect URL the user pasted from the browser address bar. Fails when
71
+ * the URL is not on the sign-in's redirect URI, carries another `state`, or reports an error.
72
+ */
73
+ export function responseFromRedirectUrl(input, authorization) {
74
+ let url;
75
+ try {
76
+ url = new URL(input.trim());
77
+ }
78
+ catch {
79
+ throw new Error("Expected the full redirect URL from the browser address bar");
80
+ }
81
+ const redirectUrl = new URL(authorization.redirectUrl);
82
+ // A server-specific redirect URI tells authorization servers apart, so it must match exactly.
83
+ if (url.origin !== redirectUrl.origin || url.pathname !== redirectUrl.pathname) {
84
+ throw new Error("The redirect URL does not match this sign-in's redirect URI");
85
+ }
86
+ const error = url.searchParams.get("error");
87
+ if (error)
88
+ throw new Error(url.searchParams.get("error_description") ?? error);
89
+ const state = url.searchParams.get("state");
90
+ if (state !== authorization.state)
91
+ throw new Error("The redirect URL belongs to a different sign-in");
92
+ const code = url.searchParams.get("code");
93
+ if (!code)
94
+ throw new Error("The redirect URL does not contain an authorization code");
95
+ const iss = url.searchParams.get("iss");
96
+ return { code, state, ...(iss ? { iss } : {}) };
97
+ }
98
+ //# sourceMappingURL=loopback.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"loopback.js","sourceRoot":"","sources":["../../src/oauth/loopback.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAEH,OAAO,EAA0B,mBAAmB,EAAE,MAAM,eAAe,CAAC;AAC5E,OAAO,EACN,gBAAgB,EAGhB,4BAA4B,EAC5B,sBAAsB,EACtB,kBAAkB,GAClB,MAAM,sBAAsB,CAAC;AAE9B,OAAO,EACN,WAAW,EAEX,uBAAuB,GAEvB,MAA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YAAY,CAAC,GAAG,CAAC,OAAO,CAAC,CAAC;IAC5C,IAAI,KAAK,KAAK,aAAa,CAAC,KAAK;QAAE,MAAM,IAAI,KAAK,CAAC,iDAAiD,CAAC,CAAC;IACtG,MAAM,IAAI,GAAG,GAAG,CAAC,YAAY,CAAC,GAAG,CAAC,MAAM,CAAC,CAAC;IAC1C,IAAI,CAAC,IAAI;QAAE,MAAM,IAAI,KAAK,CAAC,yDAAyD,CAAC,CAAC;IACtF,MAAM,GAAG,GAAG,GAAG,CAAC,YAAY,CAAC,GAAG,CAAC,KAAK,CAAC,CAAC;IACxC,OAAO,EAAE,IAAI,EAAE,KAAK,EAAE,GAAG,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,GAAG,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC,EAAE,CAAC;AACjD,CAAC","sourcesContent":["/**\n * How the authorization response of a sign-in reaches a local application: a loopback callback server\n * the browser redirects to, or a redirect URL the user pastes from the browser address bar.\n */\n\nimport { type OAuthCallbackPage, OAuthCallbackServer } from \"./callback.ts\";\nimport {\n\tloopbackSettings,\n\ttype McpClientMetadataDocuments,\n\ttype McpOAuthSettings,\n\toffersClientMetadataDocument,\n\tregisteredRedirectUrls,\n\tserverSpecificPath,\n} from \"./client-settings.ts\";\nimport type { McpOAuthStateStore } from \"./provider.ts\";\nimport {\n\tcancellable,\n\ttype McpAuthorizationResponse,\n\tMcpSignInCancelledError,\n\ttype McpSignInRedirect,\n} from \"./sign-in.ts\";\n\n/** A loopback callback server and the redirect URI it serves. */\nexport interface McpLoopbackCallback {\n\tcallback: OAuthCallbackServer;\n\t/** Pass to `startMcpSignIn` and `completeMcpSignIn`. */\n\tredirectUrl: string;\n}\n\n/**\n * Listen for the authorization response of a sign-in on loopback, where `settings` say: `callbackUrl`\n * and `callbackPort`, else the port of the stored client's redirect URI (so that client stays valid) or\n * a free one. Pass the sign-in's `clientMetadataDocuments`, so the callback server also serves the\n * server-specific redirect URI. Close the callback server when the sign-in ends.\n */\nexport async function listenForLoopbackSignIn(options: {\n\tserverUrl: string;\n\tstore: McpOAuthStateStore;\n\tsettings: McpOAuthSettings;\n\tclientMetadataDocuments?: McpClientMetadataDocuments;\n\t/** Renders the browser page after the redirect. Default: plain text. */\n\trenderPage?: (page: OAuthCallbackPage) => string;\n}): Promise<McpLoopbackCallback> {\n\tconst { settings } = options;\n\tconst loopback = loopbackSettings(settings);\n\tconst registered = registeredRedirectUrls((await options.store.load())?.clientInformation)[0];\n\tconst port = loopback.port ?? (registered ? Number(new URL(registered).port) || undefined : undefined);\n\tconst offersDocument = offersClientMetadataDocument(settings, options.clientMetadataDocuments, loopback.url);\n\tconst listenOptions = {\n\t\thost: loopback.host,\n\t\tredirectHost: loopback.redirectHost,\n\t\tpath: loopback.path,\n\t\t// The redirect URI of a server-specific Client ID Metadata Document.\n\t\textraPaths: offersDocument ? [serverSpecificPath(loopback.path, options.serverUrl)] : [],\n\t\trenderPage: options.renderPage,\n\t};\n\tlet callback: OAuthCallbackServer;\n\ttry {\n\t\tcallback = await OAuthCallbackServer.listen({ ...listenOptions, port: port ?? 0 });\n\t} catch (error) {\n\t\t// A configured port is required; the stored client's port is only preferred.\n\t\tif (loopback.port !== undefined || port === undefined) throw error;\n\t\tcallback = await OAuthCallbackServer.listen(listenOptions);\n\t}\n\treturn { callback, redirectUrl: loopback.fixedRedirectUrl ?? callback.redirectUrl };\n}\n\n/**\n * Wait for the authorization response on a loopback callback server, or for a redirect URL the user\n * pastes from the browser address bar, whichever comes first. Aborting `signal` stops the wait with\n * `McpSignInCancelledError`.\n */\nexport async function waitForLoopbackSignIn(options: {\n\tcallback: OAuthCallbackServer;\n\t/** The `redirect` result of `startMcpSignIn`. */\n\tauthorization: McpSignInRedirect;\n\t/**\n\t * Ask for the redirect URL, for when the browser cannot reach the loopback callback (for example over\n\t * SSH). Aborted once the callback arrives or the sign-in is cancelled. Resolving to `undefined` or an\n\t * empty string cancels the sign-in.\n\t */\n\tpromptForRedirectUrl?: (signal: AbortSignal) => Promise<string | undefined>;\n\tsignal?: AbortSignal;\n}): Promise<McpAuthorizationResponse> {\n\tconst { authorization } = options;\n\tconst controller = new AbortController();\n\tconst signal = options.signal ? AbortSignal.any([controller.signal, options.signal]) : controller.signal;\n\tconst fromBrowser = options.callback.waitForCallback(\n\t\tauthorization.state,\n\t\tnew URL(authorization.redirectUrl).pathname,\n\t);\n\tconst fromUser = options.promptForRedirectUrl\n\t\t? options.promptForRedirectUrl(signal).then((input) => {\n\t\t\t\tif (!input?.trim()) throw new McpSignInCancelledError();\n\t\t\t\treturn responseFromRedirectUrl(input, authorization);\n\t\t\t})\n\t\t: new Promise<never>((_, reject) => {\n\t\t\t\tsignal.addEventListener(\"abort\", () => reject(new McpSignInCancelledError()), { once: true });\n\t\t\t});\n\ttry {\n\t\treturn await cancellable(options.signal, () => Promise.race([fromBrowser, fromUser]));\n\t} finally {\n\t\t// The losing side rejects once the prompt is aborted or the callback server closes.\n\t\tcontroller.abort();\n\t\tfromBrowser.catch(() => undefined);\n\t\tfromUser.catch(() => undefined);\n\t}\n}\n\n/**\n * The authorization response in a redirect URL the user pasted from the browser address bar. Fails when\n * the URL is not on the sign-in's redirect URI, carries another `state`, or reports an error.\n */\nexport function responseFromRedirectUrl(\n\tinput: string,\n\tauthorization: Pick<McpSignInRedirect, \"state\" | \"redirectUrl\">,\n): McpAuthorizationResponse {\n\tlet url: URL;\n\ttry {\n\t\turl = new URL(input.trim());\n\t} catch {\n\t\tthrow new Error(\"Expected the full redirect URL from the browser address bar\");\n\t}\n\tconst redirectUrl = new URL(authorization.redirectUrl);\n\t// A server-specific redirect URI tells authorization servers apart, so it must match exactly.\n\tif (url.origin !== redirectUrl.origin || url.pathname !== redirectUrl.pathname) {\n\t\tthrow new Error(\"The redirect URL does not match this sign-in's redirect URI\");\n\t}\n\tconst error = url.searchParams.get(\"error\");\n\tif (error) throw new Error(url.searchParams.get(\"error_description\") ?? error);\n\tconst state = url.searchParams.get(\"state\");\n\tif (state !== authorization.state) throw new Error(\"The redirect URL belongs to a different sign-in\");\n\tconst code = url.searchParams.get(\"code\");\n\tif (!code) throw new Error(\"The redirect URL does not contain an authorization code\");\n\tconst iss = url.searchParams.get(\"iss\");\n\treturn { code, state, ...(iss ? { iss } : {}) };\n}\n"]}
@@ -0,0 +1,62 @@
1
+ import type { OAuthClientMetadataDocument, OAuthClientProvider } from "./flow.ts";
2
+ import type { AuthorizationServerMetadata, OAuthClientInformationMixed, OAuthClientMetadata, OAuthDiscoveryState, OAuthTokens } from "./types.ts";
3
+ export interface McpOAuthState {
4
+ serverUrl: string;
5
+ clientInformation?: OAuthClientInformationMixed;
6
+ tokens?: OAuthTokens;
7
+ /** When the access token expires, in milliseconds since the epoch, from `expires_in` at the time it was saved. */
8
+ tokensExpireAt?: number;
9
+ codeVerifier?: string;
10
+ oauthState?: string;
11
+ discovery?: OAuthDiscoveryState;
12
+ }
13
+ export interface McpOAuthStateStore {
14
+ load(): McpOAuthState | undefined | Promise<McpOAuthState | undefined>;
15
+ save(state: McpOAuthState): void | Promise<void>;
16
+ }
17
+ export interface McpOAuthProviderOptions {
18
+ serverUrl: string | URL;
19
+ redirectUrl: string | URL;
20
+ clientMetadata: Omit<OAuthClientMetadata, "redirect_uris"> & {
21
+ redirect_uris?: string[];
22
+ };
23
+ /** See `OAuthClientProvider.clientMetadataDocument`. */
24
+ clientMetadataDocument?: (metadata: AuthorizationServerMetadata | undefined) => OAuthClientMetadataDocument | undefined;
25
+ clientId?: string;
26
+ clientSecret?: string;
27
+ store?: McpOAuthStateStore;
28
+ onRedirect(url: URL): void | Promise<void>;
29
+ }
30
+ export declare class MemoryOAuthStateStore implements McpOAuthStateStore {
31
+ private value;
32
+ load(): McpOAuthState | undefined;
33
+ save(state: McpOAuthState): void;
34
+ }
35
+ /** Default stateful provider for one exact MCP server URL. Applications inject durable storage if needed. */
36
+ export declare class McpOAuthProvider implements OAuthClientProvider {
37
+ readonly redirectUrl: string;
38
+ readonly clientMetadata: OAuthClientMetadata;
39
+ readonly clientMetadataDocument?: (metadata: AuthorizationServerMetadata | undefined) => OAuthClientMetadataDocument | undefined;
40
+ private serverUrl;
41
+ private configuredClient;
42
+ private store;
43
+ private onRedirect;
44
+ private writes;
45
+ constructor(options: McpOAuthProviderOptions);
46
+ state(): Promise<string>;
47
+ clientInformation(): Promise<OAuthClientInformationMixed | undefined>;
48
+ saveClientInformation(information: OAuthClientInformationMixed): Promise<void>;
49
+ tokens(): Promise<OAuthTokens | undefined>;
50
+ saveTokens(tokens: OAuthTokens): Promise<void>;
51
+ redirectToAuthorization(url: URL): Promise<void>;
52
+ saveCodeVerifier(verifier: string): Promise<void>;
53
+ codeVerifier(): Promise<string>;
54
+ invalidateCredentials(kind: "all" | "client" | "tokens" | "verifier" | "discovery"): Promise<void>;
55
+ saveDiscoveryState(discovery: OAuthDiscoveryState): Promise<void>;
56
+ discoveryState(): Promise<OAuthDiscoveryState | undefined>;
57
+ private load;
58
+ private update;
59
+ /** Stored state for another server URL is ignored so credentials never leak across servers. */
60
+ private own;
61
+ }
62
+ //# sourceMappingURL=provider.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"provider.d.ts","sourceRoot":"","sources":["../../src/oauth/provider.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,2BAA2B,EAAE,mBAAmB,EAAE,MAAM,WAAW,CAAC;AAClF,OAAO,KAAK,EACX,2BAA2B,EAC3B,2BAA2B,EAC3B,mBAAmB,EACnB,mBAAmB,EACnB,WAAW,EACX,MAAM,YAAY,CAAC;AAEpB,MAAM,WAAW,aAAa;IAC7B,SAAS,EAAE,MAAM,CAAC;IAClB,iBAAiB,CAAC,EAAE,2BAA2B,CAAC;IAChD,MAAM,CAAC,EAAE,WAAW,CAAC;IACrB,kHAAkH;IAClH,cAAc,CAAC,EAAE,MAAM,CAAC;IACxB,YAAY,CAAC,EAAE,MAAM,CAAC;IACtB,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB,SAAS,CAAC,EAAE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1B,OAAO,CAAC,gBAAgB,CAA0C;IAClE,OAAO,CAAC,KAAK,CAAqB;IAClC,OAAO,CAAC,UAAU,CAAqC;IACvD,OAAO,CAAC,MAAM,CAAoC;IAElD,YAAY,OAAO,EAAE,uBAAuB,EAiB3C;IAEK,KAAK,IAAI,OAAO,CAAC,MAAM,CAAC,CAM7B;IAEK,iBAAiB,IAAI,OAAO,CAAC,2BAA2B,GAAG,SAAS,CAAC,CAE1E;IAEK,qBAAqB,CAAC,WAAW,EAAE,2BAA2B,GAAG,OAAO,CAAC,IAAI,CAAC,CAGnF;IAEK,MAAM,IAAI,OAAO,CAAC,WAAW,GAAG,SAAS,CAAC,CAE/C;IAEK,UAAU,CAAC,MAAM,EAAE,WAAW,GAAG,OAAO,CAAC,IAAI,CAAC,CAQnD;IAEK,uBAAuB,CAAC,GAAG,EAAE,GAAG,GAAG,OAAO,CAAC,IAAI,CAAC,CAErD;IAEK,gBAAgB,CAAC,QAAQ,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC,CAEtD;IAEK,YAAY,IAAI,OAAO,CAAC,MAAM,CAAC,CAIpC;IAEK,qBAAqB,CAAC,IAAI,EAAE,KAAK,GAAG,QAAQ,GAAG,QAAQ,GAAG,UAAU,GAAG,WAAW,GAAG,OAAO,CAAC,IAAI,CAAC,CAavG;IAEK,kBAAkB,CAAC,SAAS,EAAE,mBAAmB,GAAG,OAAO,CAAC,IAAI,CAAC,CAEtE;IAEK,cAAc,IAAI,OAAO,CAAC,mBAAmB,GAAG,SAAS,CAAC,CAE/D;YAEa,IAAI;YAKJ,MAAM;IAOpB,+FAA+F;IAC/F,OAAO,CAAC,GAAG;CAGX"}
@@ -0,0 +1,118 @@
1
+ export class MemoryOAuthStateStore {
2
+ value;
3
+ load() {
4
+ return this.value === undefined ? undefined : structuredClone(this.value);
5
+ }
6
+ save(state) {
7
+ this.value = structuredClone(state);
8
+ }
9
+ }
10
+ /** Default stateful provider for one exact MCP server URL. Applications inject durable storage if needed. */
11
+ export class McpOAuthProvider {
12
+ redirectUrl;
13
+ clientMetadata;
14
+ clientMetadataDocument;
15
+ serverUrl;
16
+ configuredClient;
17
+ store;
18
+ onRedirect;
19
+ writes = Promise.resolve();
20
+ constructor(options) {
21
+ this.serverUrl = String(new URL(options.serverUrl));
22
+ this.redirectUrl = String(options.redirectUrl);
23
+ this.clientMetadata = {
24
+ ...options.clientMetadata,
25
+ redirect_uris: options.clientMetadata.redirect_uris ?? [this.redirectUrl],
26
+ grant_types: options.clientMetadata.grant_types ?? ["authorization_code", "refresh_token"],
27
+ response_types: options.clientMetadata.response_types ?? ["code"],
28
+ token_endpoint_auth_method: options.clientMetadata.token_endpoint_auth_method ?? (options.clientSecret ? "client_secret_post" : "none"),
29
+ };
30
+ this.clientMetadataDocument = options.clientMetadataDocument;
31
+ this.configuredClient = options.clientId
32
+ ? { client_id: options.clientId, ...(options.clientSecret ? { client_secret: options.clientSecret } : {}) }
33
+ : undefined;
34
+ this.store = options.store ?? new MemoryOAuthStateStore();
35
+ this.onRedirect = options.onRedirect;
36
+ }
37
+ async state() {
38
+ const existing = (await this.load()).oauthState;
39
+ if (existing)
40
+ return existing;
41
+ const state = Buffer.from(crypto.getRandomValues(new Uint8Array(32))).toString("hex");
42
+ await this.update((value) => ({ ...value, oauthState: state }));
43
+ return state;
44
+ }
45
+ async clientInformation() {
46
+ return this.configuredClient ?? (await this.load()).clientInformation;
47
+ }
48
+ async saveClientInformation(information) {
49
+ if (this.configuredClient)
50
+ return;
51
+ await this.update((value) => ({ ...value, clientInformation: information }));
52
+ }
53
+ async tokens() {
54
+ return (await this.load()).tokens;
55
+ }
56
+ async saveTokens(tokens) {
57
+ const expiresAt = tokens.expires_in === undefined ? undefined : Date.now() + tokens.expires_in * 1000;
58
+ await this.update((value) => {
59
+ const next = { ...value, tokens };
60
+ if (expiresAt === undefined)
61
+ delete next.tokensExpireAt;
62
+ else
63
+ next.tokensExpireAt = expiresAt;
64
+ return next;
65
+ });
66
+ }
67
+ async redirectToAuthorization(url) {
68
+ await this.onRedirect(url);
69
+ }
70
+ async saveCodeVerifier(verifier) {
71
+ await this.update((value) => ({ ...value, codeVerifier: verifier }));
72
+ }
73
+ async codeVerifier() {
74
+ const verifier = (await this.load()).codeVerifier;
75
+ if (!verifier)
76
+ throw new Error("No OAuth PKCE code verifier is stored");
77
+ return verifier;
78
+ }
79
+ async invalidateCredentials(kind) {
80
+ await this.update((value) => {
81
+ const next = { ...value };
82
+ if (kind === "all" || kind === "client")
83
+ delete next.clientInformation;
84
+ if (kind === "all" || kind === "tokens") {
85
+ delete next.tokens;
86
+ delete next.tokensExpireAt;
87
+ }
88
+ if (kind === "all" || kind === "verifier")
89
+ delete next.codeVerifier;
90
+ if (kind === "all" || kind === "discovery")
91
+ delete next.discovery;
92
+ if (kind === "all")
93
+ delete next.oauthState;
94
+ return next;
95
+ });
96
+ }
97
+ async saveDiscoveryState(discovery) {
98
+ await this.update((value) => ({ ...value, discovery }));
99
+ }
100
+ async discoveryState() {
101
+ return (await this.load()).discovery;
102
+ }
103
+ async load() {
104
+ await this.writes;
105
+ return this.own(await this.store.load());
106
+ }
107
+ async update(update) {
108
+ this.writes = this.writes.then(async () => {
109
+ await this.store.save(update(this.own(await this.store.load())));
110
+ });
111
+ await this.writes;
112
+ }
113
+ /** Stored state for another server URL is ignored so credentials never leak across servers. */
114
+ own(state) {
115
+ return state?.serverUrl === this.serverUrl ? state : { serverUrl: this.serverUrl };
116
+ }
117
+ }
118
+ //# sourceMappingURL=provider.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"provider.js","sourceRoot":"","sources":["../../src/oauth/provider.ts"],"names":[],"mappings":"AAuCA,MAAM,OAAO,qBAAqB;IACzB,KAAK,CAA4B;IAEzC,IAAI;QACH,OAAO,IAAI,CAAC,KAAK,KAAK,SAAS,CAAC,CAAC,CAAC,SAAS,CAAC,CAAC,CAAC,eAAe,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC;IAC3E,CAAC;IAED,IA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AED,+FAA+F;IACvF,GAAG,CAAC,KAAgC;QAC3C,OAAO,KAAK,EAAE,SAAS,KAAK,IAAI,CAAC,SAAS,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,EAAE,SAAS,EAAE,IAAI,CAAC,SAAS,EAAE,CAAC;IACpF,CAAC;CACD","sourcesContent":["import type { OAuthClientMetadataDocument, OAuthClientProvider } from \"./flow.ts\";\nimport type {\n\tAuthorizationServerMetadata,\n\tOAuthClientInformationMixed,\n\tOAuthClientMetadata,\n\tOAuthDiscoveryState,\n\tOAuthTokens,\n} from \"./types.ts\";\n\nexport interface McpOAuthState {\n\tserverUrl: string;\n\tclientInformation?: OAuthClientInformationMixed;\n\ttokens?: OAuthTokens;\n\t/** When the access token expires, in milliseconds since the epoch, from `expires_in` at the time it was saved. */\n\ttokensExpireAt?: number;\n\tcodeVerifier?: string;\n\toauthState?: string;\n\tdiscovery?: OAuthDiscoveryState;\n}\n\nexport interface McpOAuthStateStore {\n\tload(): McpOAuthState | undefined | Promise<McpOAuthState | undefined>;\n\tsave(state: McpOAuthState): void | Promise<void>;\n}\n\nexport interface McpOAuthProviderOptions {\n\tserverUrl: string | URL;\n\tredirectUrl: string | URL;\n\tclientMetadata: Omit<OAuthClientMetadata, \"redirect_uris\"> & { redirect_uris?: string[] };\n\t/** See `OAuthClientProvider.clientMetadataDocument`. */\n\tclientMetadataDocument?: (\n\t\tmetadata: AuthorizationServerMetadata | undefined,\n\t) => OAuthClientMetadataDocument | undefined;\n\tclientId?: string;\n\tclientSecret?: string;\n\tstore?: McpOAuthStateStore;\n\tonRedirect(url: URL): void | Promise<void>;\n}\n\nexport class MemoryOAuthStateStore implements McpOAuthStateStore {\n\tprivate value: McpOAuthState | undefined;\n\n\tload(): McpOAuthState | undefined {\n\t\treturn this.value === undefined ? undefined : structuredClone(this.value);\n\t}\n\n\tsave(state: McpOAuthState): void {\n\t\tthis.value = structuredClone(state);\n\t}\n}\n\n/** Default stateful provider for one exact MCP server URL. Applications inject durable storage if needed. */\nexport class McpOAuthProvider implements OAuthClientProvider {\n\treadonly redirectUrl: string;\n\treadonly clientMetadata: OAuthClientMetadata;\n\treadonly clientMetadataDocument?: (\n\t\tmetadata: AuthorizationServerMetadata | undefined,\n\t) => OAuthClientMetadataDocument | undefined;\n\tprivate serverUrl: string;\n\tprivate configuredClient: OAuthClientInformationMixed | undefined;\n\tprivate store: McpOAuthStateStore;\n\tprivate onRedirect: (url: URL) => void | Promise<void>;\n\tprivate writes: Promise<void> = Promise.resolve();\n\n\tconstructor(options: McpOAuthProviderOptions) {\n\t\tthis.serverUrl = String(new URL(options.serverUrl));\n\t\tthis.redirectUrl = String(options.redirectUrl);\n\t\tthis.clientMetadata = {\n\t\t\t...options.clientMetadata,\n\t\t\tredirect_uris: options.clientMetadata.redirect_uris ?? [this.redirectUrl],\n\t\t\tgrant_types: options.clientMetadata.grant_types ?? [\"authorization_code\", \"refresh_token\"],\n\t\t\tresponse_types: options.clientMetadata.response_types ?? [\"code\"],\n\t\t\ttoken_endpoint_auth_method:\n\t\t\t\toptions.clientMetadata.token_endpoint_auth_method ?? (options.clientSecret ? \"client_secret_post\" : \"none\"),\n\t\t};\n\t\tthis.clientMetadataDocument = options.clientMetadataDocument;\n\t\tthis.configuredClient = options.clientId\n\t\t\t? { client_id: options.clientId, ...(options.clientSecret ? { client_secret: options.clientSecret } : {}) }\n\t\t\t: undefined;\n\t\tthis.store = options.store ?? new MemoryOAuthStateStore();\n\t\tthis.onRedirect = options.onRedirect;\n\t}\n\n\tasync state(): Promise<string> {\n\t\tconst existing = (await this.load()).oauthState;\n\t\tif (existing) return existing;\n\t\tconst state = Buffer.from(crypto.getRandomValues(new Uint8Array(32))).toString(\"hex\");\n\t\tawait this.update((value) => ({ ...value, oauthState: state }));\n\t\treturn state;\n\t}\n\n\tasync clientInformation(): Promise<OAuthClientInformationMixed | undefined> {\n\t\treturn this.configuredClient ?? (await this.load()).clientInformation;\n\t}\n\n\tasync saveClientInformation(information: OAuthClientInformationMixed): Promise<void> {\n\t\tif (this.configuredClient) return;\n\t\tawait this.update((value) => ({ ...value, clientInformation: information }));\n\t}\n\n\tasync tokens(): Promise<OAuthTokens | undefined> {\n\t\treturn (await this.load()).tokens;\n\t}\n\n\tasync saveTokens(tokens: OAuthTokens): Promise<void> {\n\t\tconst expiresAt = tokens.expires_in === undefined ? undefined : Date.now() + tokens.expires_in * 1000;\n\t\tawait this.update((value) => {\n\t\t\tconst next: McpOAuthState = { ...value, tokens };\n\t\t\tif (expiresAt === undefined) delete next.tokensExpireAt;\n\t\t\telse next.tokensExpireAt = expiresAt;\n\t\t\treturn next;\n\t\t});\n\t}\n\n\tasync redirectToAuthorization(url: URL): Promise<void> {\n\t\tawait this.onRedirect(url);\n\t}\n\n\tasync saveCodeVerifier(verifier: string): Promise<void> {\n\t\tawait this.update((value) => ({ ...value, codeVerifier: verifier }));\n\t}\n\n\tasync codeVerifier(): Promise<string> {\n\t\tconst verifier = (await this.load()).codeVerifier;\n\t\tif (!verifier) throw new Error(\"No OAuth PKCE code verifier is stored\");\n\t\treturn verifier;\n\t}\n\n\tasync invalidateCredentials(kind: \"all\" | \"client\" | \"tokens\" | \"verifier\" | \"discovery\"): Promise<void> {\n\t\tawait this.update((value) => {\n\t\t\tconst next = { ...value };\n\t\t\tif (kind === \"all\" || kind === \"client\") delete next.clientInformation;\n\t\t\tif (kind === \"all\" || kind === \"tokens\") {\n\t\t\t\tdelete next.tokens;\n\t\t\t\tdelete next.tokensExpireAt;\n\t\t\t}\n\t\t\tif (kind === \"all\" || kind === \"verifier\") delete next.codeVerifier;\n\t\t\tif (kind === \"all\" || kind === \"discovery\") delete next.discovery;\n\t\t\tif (kind === \"all\") delete next.oauthState;\n\t\t\treturn next;\n\t\t});\n\t}\n\n\tasync saveDiscoveryState(discovery: OAuthDiscoveryState): Promise<void> {\n\t\tawait this.update((value) => ({ ...value, discovery }));\n\t}\n\n\tasync discoveryState(): Promise<OAuthDiscoveryState | undefined> {\n\t\treturn (await this.load()).discovery;\n\t}\n\n\tprivate async load(): Promise<McpOAuthState> {\n\t\tawait this.writes;\n\t\treturn this.own(await this.store.load());\n\t}\n\n\tprivate async update(update: (state: McpOAuthState) => McpOAuthState): Promise<void> {\n\t\tthis.writes = this.writes.then(async () => {\n\t\t\tawait this.store.save(update(this.own(await this.store.load())));\n\t\t});\n\t\tawait this.writes;\n\t}\n\n\t/** Stored state for another server URL is ignored so credentials never leak across servers. */\n\tprivate own(state: McpOAuthState | undefined): McpOAuthState {\n\t\treturn state?.serverUrl === this.serverUrl ? state : { serverUrl: this.serverUrl };\n\t}\n}\n"]}
@@ -0,0 +1,73 @@
1
+ /**
2
+ * Sign-in to an OAuth-protected MCP server, in two halves so an application can complete it in another
3
+ * request with the same state store: `startMcpSignIn` refreshes the stored tokens when it can, or else
4
+ * prepares the browser step and returns the authorization URL; `completeMcpSignIn` exchanges the
5
+ * authorization code. The code arrives through a loopback callback server (`loopback.ts`), the
6
+ * application's own https callback route, or a redirect URL the user pastes.
7
+ */
8
+ import type { OAuthCallback } from "./callback.ts";
9
+ import { type McpOAuthClientOptions } from "./client-settings.ts";
10
+ import type { OAuthChallenge } from "./types.ts";
11
+ /** Options of both halves of a sign-in. Pass the same values to `startMcpSignIn` and `completeMcpSignIn`. */
12
+ export interface McpSignInOptions extends McpOAuthClientOptions {
13
+ /**
14
+ * Redirect URI chosen by the caller: a loopback one (`listenForLoopbackSignIn`) or an https callback
15
+ * route of the application. Pass the same one to both halves: the authorization request may use a
16
+ * variant specific to the MCP server (`McpSignInRedirect.redirectUrl`), which the flow derives from it.
17
+ */
18
+ redirectUrl: string;
19
+ /** The server's challenge that asked for the sign-in; its resource metadata URL and scope apply. */
20
+ challenge?: OAuthChallenge;
21
+ /**
22
+ * Aborting stops the sign-in at once with `McpSignInCancelledError`, also while `startMcpSignIn` waits
23
+ * for the store's refresh lock. A refresh already sent still completes and saves its tokens.
24
+ */
25
+ signal?: AbortSignal;
26
+ }
27
+ /** The browser step of a sign-in, from `startMcpSignIn`. Plain data, so an application can persist it. */
28
+ export interface McpSignInRedirect {
29
+ kind: "redirect";
30
+ /** Open in the user's browser. */
31
+ authorizationUrl: string;
32
+ /** The redirect URI of the authorization request; the authorization response must arrive on it. */
33
+ redirectUrl: string;
34
+ /** The `state` parameter the authorization response must carry. */
35
+ state: string;
36
+ /** The scope requested, if any. Saved with the tokens when the token response names none. */
37
+ scope?: string;
38
+ }
39
+ /** Result of `startMcpSignIn`: signed in by refreshing the stored tokens, or the browser step. */
40
+ export type McpSignInStart = {
41
+ kind: "authorized";
42
+ } | McpSignInRedirect;
43
+ /** An authorization response: from a callback server, a callback route, or `responseFromRedirectUrl`. */
44
+ export type McpAuthorizationResponse = OAuthCallback;
45
+ /** The user or the application cancelled a sign-in (its `signal` was aborted, or the user gave up). */
46
+ export declare class McpSignInCancelledError extends Error {
47
+ constructor();
48
+ }
49
+ /**
50
+ * First half of a sign-in. Without a step-up (`insufficient_scope`), it first tries to refresh the stored
51
+ * tokens with the stored client, whatever `redirectUrl` is (`authorized`). The refresh takes the store's
52
+ * refresh lock, so never call this while holding it; when another process holds the lock for the whole
53
+ * wait (`McpRefreshLockBusyError`), the refresh is skipped, and any other failure of the lock fails the
54
+ * sign-in. Otherwise it prepares the browser step (`redirect`): a fresh `state`, and a stored client that
55
+ * cannot use `redirectUrl` is dropped with its tokens. Requests to the authorization server are
56
+ * time-limited.
57
+ */
58
+ export declare function startMcpSignIn(options: McpSignInOptions): Promise<McpSignInStart>;
59
+ /**
60
+ * Second half of a sign-in: exchanges the authorization code of `response` and saves the tokens. Pass
61
+ * the options given to `startMcpSignIn`, including its `redirectUrl` (not `authorization.redirectUrl`).
62
+ * Fails when the response carries another `state`, when another sign-in started with the store since, or
63
+ * when the exchange would use another redirect URI than the authorization request (the options changed).
64
+ * A redirect URL the user pasted goes through `responseFromRedirectUrl` first, which checks its path.
65
+ */
66
+ export declare function completeMcpSignIn(options: McpSignInOptions & {
67
+ /** The `redirect` result of `startMcpSignIn`. */
68
+ authorization: McpSignInRedirect;
69
+ response: McpAuthorizationResponse;
70
+ }): Promise<void>;
71
+ /** Run `fn`, reporting an abort of `signal` as `McpSignInCancelledError`. */
72
+ export declare function cancellable<T>(signal: AbortSignal | undefined, fn: () => Promise<T>): Promise<T>;
73
+ //# sourceMappingURL=sign-in.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"sign-in.d.ts","sourceRoot":"","sources":["../../src/oauth/sign-in.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AAGH,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,eAAe,CAAC;AACnD,OAAO,EAEN,KAAK,qBAAqB,EAI1B,MAAM,sBAAsB,CAAC;AAI9B,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,YAAY,CAAC;AAEjD,6GAA6G;AAC7G,MAAM,WAAW,gBAAiB,SAAQ,qBAAqB;IAC9D;;;;OAIG;IACH,WAAW,EAAE,MAAM,CAAC;IACpB,oGAAoG;IACpG,SAAS,CAAC,EAAE,cAAc,CAAC;IAC3B;;;OAGG;IACH,MAAM,CAAC,EAAE,WAAW,CAAC;CACrB;AAED,0GAA0G;AAC1G,MAAM,WAAW,iBAAiB;IACjC,IAAI,EAAE,UAAU,CAAC;IACjB,kCAAkC;IAClC,gBAAgB,EAAE,MAAM,CAAC;IACzB,mGAAmG;IACnG,WAAW,EAAE,MAAM,CAAC;IACpB,mEAAmE;IACnE,KAAK,EAAE,MAAM,CAAC;IACd,6FAA6F;IAC7F,KAAK,CAAC,EAAE,MAAM,CAAC;CACf;AAED,kGAAkG;AAClG,MAAM,MAAM,cAAc,GAAG;IAAE,IAAI,EAAE,YAAY,CAAA;CAAE,GAAG,iBAAiB,CAAC;AAExE,yGAAyG;AACzG,MAAM,MAAM,wBAAwB,GAAG,aAAa,CAAC;AAErD,uGAAuG;AACvG,qBAAa,uBAAwB,SAAQ,KAAK;IACjD,cAGC;CACD;AAED;;;;;;;;GAQG;AACH,wBAAsB,cAAc,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