1
/*2
* Adapted from modelcontextprotocol/typescript-sdk v1.29.0 src/client/auth.ts.3
* Copyright (c) 2024 Anthropic, PBC. Licensed under MIT; see LICENSES/.4
* Modified to remove SDK/Zod dependencies and use WebCrypto for PKCE.5
*/7
import type { AuthProvider, McpFetch, UnauthorizedContext } from "../auth-provider.ts";8
import { isObject } from "../protocol/jsonrpc.ts";9
import {10
discoverAuthorizationServerMetadata,11
discoverOAuthServerInfo,12
parseWwwAuthenticate,13
selectResource,14
} from "./discovery.ts";15
import {16
McpOAuthAuthorizationRequiredError,17
OAuthError,18
OAuthInsecureEndpointError,19
OAuthIssuerMismatchError,20
OAuthRegistrationError,21
} from "./errors.ts";22
import {23
type AuthorizationServerMetadata,24
type OAuthClientInformation,25
type OAuthClientInformationFull,26
type OAuthClientInformationMixed,27
type OAuthClientMetadata,28
type OAuthDiscoveryState,29
type OAuthTokens,30
parseClientInformation,31
parseOAuthTokens,32
} from "./types.ts";34
export type AddClientAuthentication = (35
headers: Headers,36
params: URLSearchParams,37
url: string | URL,38
metadata?: AuthorizationServerMetadata,39
) => void | Promise<void>;41
/** A Client ID Metadata Document: an https URL used as `client_id`, and a redirect URI it lists. */42
export interface OAuthClientMetadataDocument {43
url: string;44
redirectUrl: string;45
}47
export interface OAuthClientProvider {48
readonly redirectUrl: string | URL;49
readonly clientMetadata: OAuthClientMetadata;50
/**51
* Client ID Metadata Document to identify as instead of registering dynamically, or `undefined` to52
* register. Called when no client information is stored; the document is not stored. `metadata` is53
* `undefined` when the authorization server has none; check `client_id_metadata_document_supported`.54
*/55
clientMetadataDocument?(metadata: AuthorizationServerMetadata | undefined): OAuthClientMetadataDocument | undefined;56
state?(): string | Promise<string>;57
clientInformation(): OAuthClientInformationMixed | undefined | Promise<OAuthClientInformationMixed | undefined>;58
saveClientInformation?(information: OAuthClientInformationMixed): void | Promise<void>;59
tokens(): OAuthTokens | undefined | Promise<OAuthTokens | undefined>;60
saveTokens(tokens: OAuthTokens): void | Promise<void>;61
redirectToAuthorization(url: URL): void | Promise<void>;62
saveCodeVerifier(verifier: string): void | Promise<void>;63
codeVerifier(): string | Promise<string>;64
addClientAuthentication?: AddClientAuthentication;65
invalidateCredentials?(kind: "all" | "client" | "tokens" | "verifier" | "discovery"): void | Promise<void>;66
saveDiscoveryState?(state: OAuthDiscoveryState): void | Promise<void>;67
discoveryState?(): OAuthDiscoveryState | undefined | Promise<OAuthDiscoveryState | undefined>;68
}70
export interface OAuthFlowOptions {71
serverUrl: string | URL;72
authorizationCode?: string;73
/** `iss` parameter of the authorization response that delivered `authorizationCode` (RFC 9207). */74
iss?: string;75
scope?: string;76
resourceMetadataUrl?: URL;77
/**78
* Authorization server metadata document to use instead of discovery, for servers that advertise a79
* wrong authorization server or none. It is trusted as configured. Must use https, except on loopback.80
*/81
authorizationServerMetadataUrl?: URL;82
fetch?: McpFetch;83
/** Aborts every request of the flow. Requests have no time limit of their own; combine with a timeout as needed. */84
signal?: AbortSignal;85
skipIssuerValidation?: boolean;86
/**87
* Go straight to the authorization redirect instead of refreshing stored tokens, for example when the88
* server asks for scopes the current grant lacks (a refresh keeps the old scope).89
*/90
skipRefresh?: boolean;91
}93
export type OAuthFlowResult = "AUTHORIZED" | "REDIRECT";94
type ClientAuthMethod = "client_secret_basic" | "client_secret_post" | "none";96
export interface TokenRequestOptions {97
metadata?: AuthorizationServerMetadata;98
clientInformation: OAuthClientInformationMixed;99
resource?: string;100
addClientAuthentication?: AddClientAuthentication;101
fetch?: McpFetch;102
signal?: AbortSignal;103
}105
function loopback(hostname: string): boolean {106
return hostname === "localhost" || hostname === "127.0.0.1" || hostname === "[::1]" || hostname === "::1";107
}109
/**110
* The OpenID Connect `application_type` for `redirect_uris` (MCP SEP-837). Without one, OpenID Connect servers111
* assume `web`, which rejects http loopback redirect URIs. Loopback hosts and custom schemes are native (RFC 8252).112
*/113
function applicationType(redirectUris: readonly string[]): "native" | "web" {114
const native = redirectUris.some((uri) => {115
if (!URL.canParse(uri)) return false;116
const url = new URL(uri);117
return (url.protocol !== "http:" && url.protocol !== "https:") || loopback(url.hostname);118
});119
return native ? "native" : "web";120
}122
function secureEndpoint(value: string | URL): URL {123
const url = new URL(value);124
if (url.protocol !== "https:" && !loopback(url.hostname)) throw new OAuthInsecureEndpointError(url.href);125
return url;126
}128
function selectClientAuthMethod(information: OAuthClientInformationMixed, supported: string[]): ClientAuthMethod {129
const hinted = "token_endpoint_auth_method" in information ? information.token_endpoint_auth_method : undefined;130
if (131
hinted &&132
["client_secret_basic", "client_secret_post", "none"].includes(hinted) &&133
(supported.length === 0 || supported.includes(hinted))134
) {135
return hinted as ClientAuthMethod;136
}137
if (supported.length === 0) return information.client_secret ? "client_secret_basic" : "none";138
if (information.client_secret && supported.includes("client_secret_basic")) return "client_secret_basic";139
if (information.client_secret && supported.includes("client_secret_post")) return "client_secret_post";140
if (supported.includes("none")) return "none";141
return information.client_secret ? "client_secret_post" : "none";142
}144
function applyClientAuthentication(145
method: ClientAuthMethod,146
information: OAuthClientInformation,147
headers: Headers,148
params: URLSearchParams,149
): void {150
if (method === "client_secret_basic") {151
if (!information.client_secret) throw new Error("client_secret_basic requires a client secret");152
headers.set(153
"Authorization",154
`Basic ${Buffer.from(`${information.client_id}:${information.client_secret}`).toString("base64")}`,155
);156
} else {157
params.set("client_id", information.client_id);158
if (method === "client_secret_post" && information.client_secret)159
params.set("client_secret", information.client_secret);160
}161
}163
async function pkce(): Promise<{ verifier: string; challenge: string }> {164
const bytes = crypto.getRandomValues(new Uint8Array(32));165
const verifier = Buffer.from(bytes).toString("base64url");166
const digest = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(verifier));167
return { verifier, challenge: Buffer.from(digest).toString("base64url") };168
}170
export async function startAuthorization(171
authorizationServerUrl: string | URL,172
options: {173
metadata?: AuthorizationServerMetadata;174
clientInformation: OAuthClientInformationMixed;175
redirectUrl: string | URL;176
scope?: string;177
state?: string;178
resource?: string;179
},180
): Promise<{ authorizationUrl: URL; codeVerifier: string }> {181
const metadata = options.metadata;182
if (metadata && !metadata.response_types_supported.includes("code")) {183
throw new Error("Authorization server does not support authorization codes");184
}185
if (metadata?.code_challenge_methods_supported && !metadata.code_challenge_methods_supported.includes("S256")) {186
throw new Error("Authorization server does not support PKCE S256");187
}188
const url = new URL(metadata?.authorization_endpoint ?? new URL("/authorize", authorizationServerUrl));189
const { verifier, challenge } = await pkce();190
url.searchParams.set("response_type", "code");191
url.searchParams.set("client_id", options.clientInformation.client_id);192
url.searchParams.set("code_challenge", challenge);193
url.searchParams.set("code_challenge_method", "S256");194
url.searchParams.set("redirect_uri", String(options.redirectUrl));195
if (options.state) url.searchParams.set("state", options.state);196
if (options.scope) url.searchParams.set("scope", options.scope);197
if (options.scope?.split(/\s+/).includes("offline_access")) url.searchParams.set("prompt", "consent");198
if (options.resource) url.searchParams.set("resource", options.resource);199
return { authorizationUrl: url, codeVerifier: verifier };200
}202
async function tokenRequest(203
authorizationServerUrl: string | URL,204
options: TokenRequestOptions,205
params: URLSearchParams,206
): Promise<OAuthTokens> {207
const url = secureEndpoint(options.metadata?.token_endpoint ?? new URL("/token", authorizationServerUrl));208
const headers = new Headers({ Accept: "application/json", "content-type": "application/x-www-form-urlencoded" });209
if (options.resource) params.set("resource", options.resource);210
if (options.addClientAuthentication) {211
await options.addClientAuthentication(headers, params, url, options.metadata);212
} else {213
applyClientAuthentication(214
selectClientAuthMethod(215
options.clientInformation,216
options.metadata?.token_endpoint_auth_methods_supported ?? [],217
),218
options.clientInformation,219
headers,220
params,221
);222
}223
const response = await (options.fetch ?? globalThis.fetch)(url, {224
method: "POST",225
headers,226
body: params,227
signal: options.signal,228
});229
const text = await response.text();230
let value: unknown;231
try {232
value = JSON.parse(text);233
} catch {}234
// Servers may report OAuth errors with any status, so check the body before the status.235
if (isObject(value) && typeof value.error === "string") {236
throw new OAuthError(237
value.error,238
typeof value.error_description === "string" ? value.error_description : value.error,239
typeof value.error_uri === "string" ? value.error_uri : undefined,240
);241
}242
if (!response.ok) throw new OAuthError("server_error", `HTTP ${response.status}: ${text}`);243
return parseOAuthTokens(value);244
}246
export async function registerClient(247
authorizationServerUrl: string | URL,248
options: {249
metadata?: AuthorizationServerMetadata;250
clientMetadata: OAuthClientMetadata;251
scope?: string;252
fetch?: McpFetch;253
signal?: AbortSignal;254
},255
): Promise<OAuthClientInformationFull> {256
const endpoint = options.metadata?.registration_endpoint;257
if (options.metadata && !endpoint)258
throw new Error("Authorization server does not support dynamic client registration");259
const response = await (options.fetch ?? globalThis.fetch)(260
new URL(endpoint ?? new URL("/register", authorizationServerUrl)),261
{262
method: "POST",263
headers: { Accept: "application/json", "content-type": "application/json" },264
body: JSON.stringify({265
...options.clientMetadata,266
application_type:267
options.clientMetadata.application_type ?? applicationType(options.clientMetadata.redirect_uris),268
...(options.scope ? { scope: options.scope } : {}),269
}),270
signal: options.signal,271
},272
);273
if (!response.ok) throw new OAuthRegistrationError(response.status, await response.text());274
return parseClientInformation(await response.json());275
}277
export async function exchangeAuthorizationCode(278
authorizationServerUrl: string | URL,279
options: TokenRequestOptions & { code: string; codeVerifier: string; redirectUrl: string | URL },280
): Promise<OAuthTokens> {281
return tokenRequest(282
authorizationServerUrl,283
options,284
new URLSearchParams({285
grant_type: "authorization_code",286
code: options.code,287
code_verifier: options.codeVerifier,288
redirect_uri: String(options.redirectUrl),289
}),290
);291
}293
export async function refreshAuthorization(294
authorizationServerUrl: string | URL,295
options: TokenRequestOptions & { refreshToken: string },296
): Promise<OAuthTokens> {297
const tokens = await tokenRequest(298
authorizationServerUrl,299
options,300
new URLSearchParams({ grant_type: "refresh_token", refresh_token: options.refreshToken }),301
);302
return { refresh_token: options.refreshToken, ...tokens };303
}305
function withScope(tokens: OAuthTokens, scope: string | undefined): OAuthTokens {306
return tokens.scope === undefined && scope ? { ...tokens, scope } : tokens;307
}309
/**310
* Scopes for a step-up authorization: the challenged scopes plus the ones granted so far, since a311
* challenge may list only the missing scopes and a token with just those would lose access the old312
* one had (SEP-2350). Without challenged scopes, `undefined` lets the flow pick its default.313
*/314
export function stepUpScope(granted: string | undefined, challenged: string | undefined): string | undefined {315
if (!challenged) return undefined;316
const scopes = [granted, challenged].flatMap((scope) => scope?.split(/\s+/).filter(Boolean) ?? []);317
return [...new Set(scopes)].join(" ");318
}320
async function runFlow(provider: OAuthClientProvider, options: OAuthFlowOptions): Promise<OAuthFlowResult> {321
const metadataUrl = options.authorizationServerMetadataUrl && secureEndpoint(options.authorizationServerMetadataUrl);322
// With a configured metadata URL, discovery is not cached, so changing the URL applies at once.323
const cached = metadataUrl ? undefined : await provider.discoveryState?.();324
const discovered = cached?.authorizationServerUrl325
? {326
authorizationServerUrl: cached.authorizationServerUrl,327
authorizationServerMetadata:328
cached.authorizationServerMetadata ??329
(await discoverAuthorizationServerMetadata(cached.authorizationServerUrl, {330
fetch: options.fetch,331
skipIssuerValidation: options.skipIssuerValidation,332
signal: options.signal,333
})),334
resourceMetadata: cached.resourceMetadata,335
}336
: await discoverOAuthServerInfo(options.serverUrl, {337
resourceMetadataUrl: options.resourceMetadataUrl,338
authorizationServerMetadataUrl: metadataUrl,339
fetch: options.fetch,340
skipIssuerValidation: options.skipIssuerValidation,341
signal: options.signal,342
});343
if (!metadataUrl) {344
await provider.saveDiscoveryState?.({345
...discovered,346
...(options.resourceMetadataUrl ? { resourceMetadataUrl: options.resourceMetadataUrl.href } : {}),347
});348
}349
const metadata = discovered.authorizationServerMetadata;350
const resource = selectResource(options.serverUrl, discovered.resourceMetadata);351
// `||`, not `??`: an empty scope (for example from `scopes_supported: []`) falls through to the next source.352
const scope =353
options.scope || discovered.resourceMetadata?.scopes_supported?.join(" ") || provider.clientMetadata.scope;354
const stored = await provider.clientInformation();355
const clientDocument = stored ? undefined : provider.clientMetadataDocument?.(metadata);356
if (clientDocument) {357
const url = new URL(clientDocument.url);358
if (url.protocol !== "https:" || url.pathname === "/") throw new Error("Invalid OAuth client metadata URL");359
}360
let client = stored ?? (clientDocument && { client_id: clientDocument.url });361
if (!client) {362
if (options.authorizationCode) throw new Error("OAuth client information is missing during code exchange");363
if (!provider.saveClientInformation) throw new Error("OAuth client information cannot be persisted");364
client = await registerClient(discovered.authorizationServerUrl, {365
metadata,366
clientMetadata: provider.clientMetadata,367
scope,368
fetch: options.fetch,369
signal: options.signal,370
});371
await provider.saveClientInformation(client);372
}373
// The document's redirect URI may differ from the provider's, for example by a server-specific path.374
const redirectUrl = clientDocument?.redirectUrl ?? provider.redirectUrl;375
const tokenOptions: TokenRequestOptions = {376
metadata,377
clientInformation: client,378
resource,379
addClientAuthentication: provider.addClientAuthentication,380
fetch: options.fetch,381
signal: options.signal,382
};383
if (options.authorizationCode) {384
// RFC 9207: never send a code from another authorization server to this one. Without metadata there385
// is no issuer to compare with, so any `iss` is rejected.386
const iss = options.iss;387
if (iss !== undefined || metadata?.authorization_response_iss_parameter_supported) {388
if (iss !== metadata?.issuer) throw new OAuthIssuerMismatchError(metadata?.issuer, iss);389
}390
const tokens = await exchangeAuthorizationCode(discovered.authorizationServerUrl, {391
...tokenOptions,392
code: options.authorizationCode,393
codeVerifier: await provider.codeVerifier(),394
redirectUrl,395
});396
// A response without `scope` grants the requested scope (RFC 6749 §5.1). Recorded so a step-up can397
// keep it. Callers pass the options of the authorization request, so `scope` is what was requested.398
await provider.saveTokens(withScope(tokens, scope));399
return "AUTHORIZED";400
}401
const existing = options.skipRefresh ? undefined : await provider.tokens();402
if (existing?.refresh_token) {403
try {404
const tokens = await refreshAuthorization(discovered.authorizationServerUrl, {405
...tokenOptions,406
refreshToken: existing.refresh_token,407
});408
// A refresh without `scope` keeps the scope of the grant (RFC 6749 §6).409
await provider.saveTokens(withScope(tokens, existing.scope));410
return "AUTHORIZED";411
} catch (error) {412
if (options.signal?.aborted || error instanceof OAuthInsecureEndpointError) throw error;413
if (error instanceof OAuthError && error.code !== "server_error") throw error;414
}415
}416
const state = await provider.state?.();417
const authorization = await startAuthorization(discovered.authorizationServerUrl, {418
metadata,419
clientInformation: client,420
redirectUrl,421
scope,422
state,423
resource,424
});425
await provider.saveCodeVerifier(authorization.codeVerifier);426
await provider.redirectToAuthorization(authorization.authorizationUrl);427
return "REDIRECT";428
}430
export async function authorizeMcp(provider: OAuthClientProvider, options: OAuthFlowOptions): Promise<OAuthFlowResult> {431
try {432
return await runFlow(provider, options);433
} catch (error) {434
if (error instanceof OAuthError && ["invalid_client", "unauthorized_client"].includes(error.code)) {435
await provider.invalidateCredentials?.("all");436
return runFlow(provider, options);437
}438
if (error instanceof OAuthError && error.code === "invalid_grant") {439
await provider.invalidateCredentials?.("tokens");440
return runFlow(provider, options);441
}442
throw error;443
}444
}446
/**447
* Auth provider for `StreamableHttpTransport`. After a 401 it refreshes the tokens, or throws448
* `McpOAuthAuthorizationRequiredError` when the user has to authorize (again). Concurrent 401s share449
* one refresh, and a request whose token was already replaced is just retried: with rotating refresh450
* tokens, a second refresh with the old refresh token would fail and discard the new grant.451
*/452
export function adaptOAuthProvider(provider: OAuthClientProvider): AuthProvider {453
let inFlight: Promise<void> | undefined;454
return {455
token: async () => (await provider.tokens())?.access_token,456
onUnauthorized: async (context: UnauthorizedContext) => {457
const challenge = parseWwwAuthenticate(context.response.headers.get("www-authenticate"));458
const insufficientScope = challenge.error === "insufficient_scope";459
if (!insufficientScope && !inFlight && context.token !== undefined) {460
const current = (await provider.tokens())?.access_token;461
if (current !== undefined && current !== context.token) return;462
}463
inFlight ??= Promise.resolve(insufficientScope ? provider.tokens() : undefined)464
.then((granted) =>465
authorizeMcp(provider, {466
serverUrl: context.serverUrl,467
resourceMetadataUrl: challenge.resourceMetadataUrl,468
scope: insufficientScope ? stepUpScope(granted?.scope, challenge.scope) : challenge.scope,469
fetch: context.fetch,470
skipRefresh: insufficientScope,471
}),472
)473
.then((result) => {474
if (result === "REDIRECT") throw new McpOAuthAuthorizationRequiredError();475
})476
.finally(() => {477
inFlight = undefined;478
});479
await inFlight;480
},481
};482
}