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
skipIssuerValidation?: boolean;84
/**85
* Go straight to the authorization redirect instead of refreshing stored tokens, for example when the86
* server asks for scopes the current grant lacks (a refresh keeps the old scope).87
*/88
skipRefresh?: boolean;89
}91
export type OAuthFlowResult = "AUTHORIZED" | "REDIRECT";92
type ClientAuthMethod = "client_secret_basic" | "client_secret_post" | "none";94
export interface TokenRequestOptions {95
metadata?: AuthorizationServerMetadata;96
clientInformation: OAuthClientInformationMixed;97
resource?: string;98
addClientAuthentication?: AddClientAuthentication;99
fetch?: McpFetch;100
}102
function loopback(hostname: string): boolean {103
return hostname === "localhost" || hostname === "127.0.0.1" || hostname === "[::1]" || hostname === "::1";104
}106
function secureEndpoint(value: string | URL): URL {107
const url = new URL(value);108
if (url.protocol !== "https:" && !loopback(url.hostname)) throw new OAuthInsecureEndpointError(url.href);109
return url;110
}112
function selectClientAuthMethod(information: OAuthClientInformationMixed, supported: string[]): ClientAuthMethod {113
const hinted = "token_endpoint_auth_method" in information ? information.token_endpoint_auth_method : undefined;114
if (115
hinted &&116
["client_secret_basic", "client_secret_post", "none"].includes(hinted) &&117
(supported.length === 0 || supported.includes(hinted))118
) {119
return hinted as ClientAuthMethod;120
}121
if (supported.length === 0) return information.client_secret ? "client_secret_basic" : "none";122
if (information.client_secret && supported.includes("client_secret_basic")) return "client_secret_basic";123
if (information.client_secret && supported.includes("client_secret_post")) return "client_secret_post";124
if (supported.includes("none")) return "none";125
return information.client_secret ? "client_secret_post" : "none";126
}128
function applyClientAuthentication(129
method: ClientAuthMethod,130
information: OAuthClientInformation,131
headers: Headers,132
params: URLSearchParams,133
): void {134
if (method === "client_secret_basic") {135
if (!information.client_secret) throw new Error("client_secret_basic requires a client secret");136
headers.set(137
"Authorization",138
`Basic ${Buffer.from(`${information.client_id}:${information.client_secret}`).toString("base64")}`,139
);140
} else {141
params.set("client_id", information.client_id);142
if (method === "client_secret_post" && information.client_secret)143
params.set("client_secret", information.client_secret);144
}145
}147
async function pkce(): Promise<{ verifier: string; challenge: string }> {148
const bytes = crypto.getRandomValues(new Uint8Array(32));149
const verifier = Buffer.from(bytes).toString("base64url");150
const digest = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(verifier));151
return { verifier, challenge: Buffer.from(digest).toString("base64url") };152
}154
export async function startAuthorization(155
authorizationServerUrl: string | URL,156
options: {157
metadata?: AuthorizationServerMetadata;158
clientInformation: OAuthClientInformationMixed;159
redirectUrl: string | URL;160
scope?: string;161
state?: string;162
resource?: string;163
},164
): Promise<{ authorizationUrl: URL; codeVerifier: string }> {165
const metadata = options.metadata;166
if (metadata && !metadata.response_types_supported.includes("code")) {167
throw new Error("Authorization server does not support authorization codes");168
}169
if (metadata?.code_challenge_methods_supported && !metadata.code_challenge_methods_supported.includes("S256")) {170
throw new Error("Authorization server does not support PKCE S256");171
}172
const url = new URL(metadata?.authorization_endpoint ?? new URL("/authorize", authorizationServerUrl));173
const { verifier, challenge } = await pkce();174
url.searchParams.set("response_type", "code");175
url.searchParams.set("client_id", options.clientInformation.client_id);176
url.searchParams.set("code_challenge", challenge);177
url.searchParams.set("code_challenge_method", "S256");178
url.searchParams.set("redirect_uri", String(options.redirectUrl));179
if (options.state) url.searchParams.set("state", options.state);180
if (options.scope) url.searchParams.set("scope", options.scope);181
if (options.scope?.split(/\s+/).includes("offline_access")) url.searchParams.set("prompt", "consent");182
if (options.resource) url.searchParams.set("resource", options.resource);183
return { authorizationUrl: url, codeVerifier: verifier };184
}186
async function tokenRequest(187
authorizationServerUrl: string | URL,188
options: TokenRequestOptions,189
params: URLSearchParams,190
): Promise<OAuthTokens> {191
const url = secureEndpoint(options.metadata?.token_endpoint ?? new URL("/token", authorizationServerUrl));192
const headers = new Headers({ Accept: "application/json", "content-type": "application/x-www-form-urlencoded" });193
if (options.resource) params.set("resource", options.resource);194
if (options.addClientAuthentication) {195
await options.addClientAuthentication(headers, params, url, options.metadata);196
} else {197
applyClientAuthentication(198
selectClientAuthMethod(199
options.clientInformation,200
options.metadata?.token_endpoint_auth_methods_supported ?? [],201
),202
options.clientInformation,203
headers,204
params,205
);206
}207
const response = await (options.fetch ?? globalThis.fetch)(url, { method: "POST", headers, body: params });208
const text = await response.text();209
let value: unknown;210
try {211
value = JSON.parse(text);212
} catch {}213
// Servers may report OAuth errors with any status, so check the body before the status.214
if (isObject(value) && typeof value.error === "string") {215
throw new OAuthError(216
value.error,217
typeof value.error_description === "string" ? value.error_description : value.error,218
typeof value.error_uri === "string" ? value.error_uri : undefined,219
);220
}221
if (!response.ok) throw new OAuthError("server_error", `HTTP ${response.status}: ${text}`);222
return parseOAuthTokens(value);223
}225
export async function registerClient(226
authorizationServerUrl: string | URL,227
options: {228
metadata?: AuthorizationServerMetadata;229
clientMetadata: OAuthClientMetadata;230
scope?: string;231
fetch?: McpFetch;232
},233
): Promise<OAuthClientInformationFull> {234
const endpoint = options.metadata?.registration_endpoint;235
if (options.metadata && !endpoint)236
throw new Error("Authorization server does not support dynamic client registration");237
const response = await (options.fetch ?? globalThis.fetch)(238
new URL(endpoint ?? new URL("/register", authorizationServerUrl)),239
{240
method: "POST",241
headers: { Accept: "application/json", "content-type": "application/json" },242
body: JSON.stringify({ ...options.clientMetadata, ...(options.scope ? { scope: options.scope } : {}) }),243
},244
);245
if (!response.ok) throw new OAuthRegistrationError(response.status, await response.text());246
return parseClientInformation(await response.json());247
}249
export async function exchangeAuthorizationCode(250
authorizationServerUrl: string | URL,251
options: TokenRequestOptions & { code: string; codeVerifier: string; redirectUrl: string | URL },252
): Promise<OAuthTokens> {253
return tokenRequest(254
authorizationServerUrl,255
options,256
new URLSearchParams({257
grant_type: "authorization_code",258
code: options.code,259
code_verifier: options.codeVerifier,260
redirect_uri: String(options.redirectUrl),261
}),262
);263
}265
export async function refreshAuthorization(266
authorizationServerUrl: string | URL,267
options: TokenRequestOptions & { refreshToken: string },268
): Promise<OAuthTokens> {269
const tokens = await tokenRequest(270
authorizationServerUrl,271
options,272
new URLSearchParams({ grant_type: "refresh_token", refresh_token: options.refreshToken }),273
);274
return { refresh_token: options.refreshToken, ...tokens };275
}277
function withScope(tokens: OAuthTokens, scope: string | undefined): OAuthTokens {278
return tokens.scope === undefined && scope ? { ...tokens, scope } : tokens;279
}281
/**282
* Scopes for a step-up authorization: the challenged scopes plus the ones granted so far, since a283
* challenge may list only the missing scopes and a token with just those would lose access the old284
* one had (SEP-2350). Without challenged scopes, `undefined` lets the flow pick its default.285
*/286
export function stepUpScope(granted: string | undefined, challenged: string | undefined): string | undefined {287
if (!challenged) return undefined;288
const scopes = [granted, challenged].flatMap((scope) => scope?.split(/\s+/).filter(Boolean) ?? []);289
return [...new Set(scopes)].join(" ");290
}292
async function runFlow(provider: OAuthClientProvider, options: OAuthFlowOptions): Promise<OAuthFlowResult> {293
const metadataUrl = options.authorizationServerMetadataUrl && secureEndpoint(options.authorizationServerMetadataUrl);294
// With a configured metadata URL, discovery is not cached, so changing the URL applies at once.295
const cached = metadataUrl ? undefined : await provider.discoveryState?.();296
const discovered = cached?.authorizationServerUrl297
? {298
authorizationServerUrl: cached.authorizationServerUrl,299
authorizationServerMetadata:300
cached.authorizationServerMetadata ??301
(await discoverAuthorizationServerMetadata(cached.authorizationServerUrl, {302
fetch: options.fetch,303
skipIssuerValidation: options.skipIssuerValidation,304
})),305
resourceMetadata: cached.resourceMetadata,306
}307
: await discoverOAuthServerInfo(options.serverUrl, {308
resourceMetadataUrl: options.resourceMetadataUrl,309
authorizationServerMetadataUrl: metadataUrl,310
fetch: options.fetch,311
skipIssuerValidation: options.skipIssuerValidation,312
});313
if (!metadataUrl) {314
await provider.saveDiscoveryState?.({315
...discovered,316
...(options.resourceMetadataUrl ? { resourceMetadataUrl: options.resourceMetadataUrl.href } : {}),317
});318
}319
const metadata = discovered.authorizationServerMetadata;320
const resource = selectResource(options.serverUrl, discovered.resourceMetadata);321
// `||`, not `??`: an empty scope (for example from `scopes_supported: []`) falls through to the next source.322
const scope =323
options.scope || discovered.resourceMetadata?.scopes_supported?.join(" ") || provider.clientMetadata.scope;324
const stored = await provider.clientInformation();325
const clientDocument = stored ? undefined : provider.clientMetadataDocument?.(metadata);326
if (clientDocument) {327
const url = new URL(clientDocument.url);328
if (url.protocol !== "https:" || url.pathname === "/") throw new Error("Invalid OAuth client metadata URL");329
}330
let client = stored ?? (clientDocument && { client_id: clientDocument.url });331
if (!client) {332
if (options.authorizationCode) throw new Error("OAuth client information is missing during code exchange");333
if (!provider.saveClientInformation) throw new Error("OAuth client information cannot be persisted");334
client = await registerClient(discovered.authorizationServerUrl, {335
metadata,336
clientMetadata: provider.clientMetadata,337
scope,338
fetch: options.fetch,339
});340
await provider.saveClientInformation(client);341
}342
// The document's redirect URI may differ from the provider's, for example by a server-specific path.343
const redirectUrl = clientDocument?.redirectUrl ?? provider.redirectUrl;344
const tokenOptions: TokenRequestOptions = {345
metadata,346
clientInformation: client,347
resource,348
addClientAuthentication: provider.addClientAuthentication,349
fetch: options.fetch,350
};351
if (options.authorizationCode) {352
// RFC 9207: never send a code from another authorization server to this one.353
const iss = options.iss;354
if (metadata && (iss !== undefined || metadata.authorization_response_iss_parameter_supported)) {355
if (iss !== metadata.issuer) throw new OAuthIssuerMismatchError(metadata.issuer, iss);356
}357
const tokens = await exchangeAuthorizationCode(discovered.authorizationServerUrl, {358
...tokenOptions,359
code: options.authorizationCode,360
codeVerifier: await provider.codeVerifier(),361
redirectUrl,362
});363
// A response without `scope` grants the requested scope (RFC 6749 §5.1). Recorded so a step-up can364
// keep it. Callers pass the options of the authorization request, so `scope` is what was requested.365
await provider.saveTokens(withScope(tokens, scope));366
return "AUTHORIZED";367
}368
const existing = options.skipRefresh ? undefined : await provider.tokens();369
if (existing?.refresh_token) {370
try {371
const tokens = await refreshAuthorization(discovered.authorizationServerUrl, {372
...tokenOptions,373
refreshToken: existing.refresh_token,374
});375
// A refresh without `scope` keeps the scope of the grant (RFC 6749 §6).376
await provider.saveTokens(withScope(tokens, existing.scope));377
return "AUTHORIZED";378
} catch (error) {379
if (error instanceof OAuthInsecureEndpointError) throw error;380
if (error instanceof OAuthError && error.code !== "server_error") throw error;381
}382
}383
const state = await provider.state?.();384
const authorization = await startAuthorization(discovered.authorizationServerUrl, {385
metadata,386
clientInformation: client,387
redirectUrl,388
scope,389
state,390
resource,391
});392
await provider.saveCodeVerifier(authorization.codeVerifier);393
await provider.redirectToAuthorization(authorization.authorizationUrl);394
return "REDIRECT";395
}397
export async function authorizeMcp(provider: OAuthClientProvider, options: OAuthFlowOptions): Promise<OAuthFlowResult> {398
try {399
return await runFlow(provider, options);400
} catch (error) {401
if (error instanceof OAuthError && ["invalid_client", "unauthorized_client"].includes(error.code)) {402
await provider.invalidateCredentials?.("all");403
return runFlow(provider, options);404
}405
if (error instanceof OAuthError && error.code === "invalid_grant") {406
await provider.invalidateCredentials?.("tokens");407
return runFlow(provider, options);408
}409
throw error;410
}411
}413
/**414
* Auth provider for `StreamableHttpTransport`. After a 401 it refreshes the tokens, or throws415
* `McpOAuthAuthorizationRequiredError` when the user has to authorize (again). Concurrent 401s share416
* one refresh, and a request whose token was already replaced is just retried: with rotating refresh417
* tokens, a second refresh with the old refresh token would fail and discard the new grant.418
*/419
export function adaptOAuthProvider(provider: OAuthClientProvider): AuthProvider {420
let inFlight: Promise<void> | undefined;421
return {422
token: async () => (await provider.tokens())?.access_token,423
onUnauthorized: async (context: UnauthorizedContext) => {424
const challenge = parseWwwAuthenticate(context.response.headers.get("www-authenticate"));425
const insufficientScope = challenge.error === "insufficient_scope";426
if (!insufficientScope && !inFlight && context.token !== undefined) {427
const current = (await provider.tokens())?.access_token;428
if (current !== undefined && current !== context.token) return;429
}430
inFlight ??= Promise.resolve(insufficientScope ? provider.tokens() : undefined)431
.then((granted) =>432
authorizeMcp(provider, {433
serverUrl: context.serverUrl,434
resourceMetadataUrl: challenge.resourceMetadataUrl,435
scope: insufficientScope ? stepUpScope(granted?.scope, challenge.scope) : challenge.scope,436
fetch: context.fetch,437
skipRefresh: insufficientScope,438
}),439
)440
.then((result) => {441
if (result === "REDIRECT") throw new McpOAuthAuthorizationRequiredError();442
})443
.finally(() => {444
inFlight = undefined;445
});446
await inFlight;447
},448
};449
}