1
import { createHash } from "node:crypto";2
import { afterEach, describe, expect, it } from "vitest";3
import { McpClient, StreamableHttpTransport } from "../src/index.ts";4
import {5
adaptOAuthProvider,6
authorizeMcp,7
discoverAuthorizationServerMetadata,8
McpOAuthAuthorizationRequiredError,9
McpOAuthProvider,10
MemoryOAuthStateStore,11
type OAuthCallbackPage,12
OAuthCallbackServer,13
type OAuthClientInformationMixed,14
type OAuthClientProvider,15
type OAuthDiscoveryState,16
OAuthInsecureEndpointError,17
OAuthIssuerMismatchError,18
type OAuthTokens,19
registerClient,20
} from "../src/oauth/index.ts";21
import { closeServers, listen, readBody } from "./helpers.ts";23
class TestOAuthProvider implements OAuthClientProvider {24
readonly redirectUrl: string;25
readonly clientMetadata;26
client: OAuthClientInformationMixed | undefined;27
tokenSet: OAuthTokens | undefined;28
verifier: string | undefined;29
discovery: OAuthDiscoveryState | undefined;30
authorizationUrl: URL | undefined;32
constructor(redirectUrl: string) {33
this.redirectUrl = redirectUrl;34
this.clientMetadata = {35
redirect_uris: [redirectUrl],36
client_name: "pi-mcp-test",37
grant_types: ["authorization_code", "refresh_token"],38
response_types: ["code"],39
token_endpoint_auth_method: "none",40
};41
}43
state(): string {44
return "expected-state";45
}47
clientInformation(): OAuthClientInformationMixed | undefined {48
return this.client;49
}51
saveClientInformation(information: OAuthClientInformationMixed): void {52
this.client = information;53
}55
tokens(): OAuthTokens | undefined {56
return this.tokenSet;57
}59
saveTokens(tokens: OAuthTokens): void {60
this.tokenSet = tokens;61
}63
redirectToAuthorization(url: URL): void {64
this.authorizationUrl = url;65
}67
saveCodeVerifier(verifier: string): void {68
this.verifier = verifier;69
}71
codeVerifier(): string {72
if (!this.verifier) throw new Error("Missing code verifier");73
return this.verifier;74
}76
invalidateCredentials(kind: "all" | "client" | "tokens" | "verifier" | "discovery"): void {77
if (kind === "all" || kind === "client") this.client = undefined;78
if (kind === "all" || kind === "tokens") this.tokenSet = undefined;79
if (kind === "all" || kind === "verifier") this.verifier = undefined;80
if (kind === "all" || kind === "discovery") this.discovery = undefined;81
}83
saveDiscoveryState(state: OAuthDiscoveryState): void {84
this.discovery = state;85
}87
discoveryState(): OAuthDiscoveryState | undefined {88
return this.discovery;89
}90
}92
afterEach(closeServers);94
describe("MCP OAuth", () => {95
it("discovers, registers, authorizes with PKCE, and refreshes on 401", async () => {96
let expectedChallenge: string | undefined;97
let refreshes = 0;98
const origin = await listen(async (request, response, serverOrigin) => {99
const url = new URL(request.url ?? "/", serverOrigin);100
if (url.pathname === "/.well-known/oauth-protected-resource/mcp") {101
response.setHeader("content-type", "application/json");102
response.end(103
JSON.stringify({104
resource: `${serverOrigin}/mcp`,105
authorization_servers: [serverOrigin],106
scopes_supported: ["org:read"],107
}),108
);109
return;110
}111
if (url.pathname === "/.well-known/oauth-authorization-server") {112
response.setHeader("content-type", "application/json");113
response.end(114
JSON.stringify({115
issuer: serverOrigin,116
authorization_endpoint: `${serverOrigin}/authorize`,117
token_endpoint: `${serverOrigin}/token`,118
registration_endpoint: `${serverOrigin}/register`,119
response_types_supported: ["code"],120
grant_types_supported: ["authorization_code", "refresh_token"],121
token_endpoint_auth_methods_supported: ["none"],122
code_challenge_methods_supported: ["S256"],123
}),124
);125
return;126
}127
if (url.pathname === "/register") {128
const metadata = JSON.parse(await readBody(request)) as Record<string, unknown>;129
response.writeHead(201, { "content-type": "application/json" });130
// Empty and null optional fields count as absent (#10266).131
response.end(JSON.stringify({ ...metadata, client_id: "test-client", client_secret: "" }));132
return;133
}134
if (url.pathname === "/authorize") {135
expectedChallenge = url.searchParams.get("code_challenge") ?? undefined;136
const redirect = new URL(url.searchParams.get("redirect_uri") ?? "");137
redirect.searchParams.set("code", "test-code");138
redirect.searchParams.set("state", url.searchParams.get("state") ?? "");139
response.writeHead(302, { location: redirect.href }).end();140
return;141
}142
if (url.pathname === "/token") {143
const params = new URLSearchParams(await readBody(request));144
if (params.get("grant_type") === "refresh_token") {145
refreshes++;146
response.setHeader("content-type", "application/json");147
response.end(148
JSON.stringify({149
access_token: "refreshed-token",150
token_type: "Bearer",151
refresh_token: "",152
expires_in: null,153
}),154
);155
return;156
}157
const challenge = createHash("sha256")158
.update(params.get("code_verifier") ?? "")159
.digest("base64url");160
if (params.get("code") !== "test-code" || challenge !== expectedChallenge) {161
response.writeHead(400, { "content-type": "application/json" });162
response.end(JSON.stringify({ error: "invalid_grant" }));163
return;164
}165
response.setHeader("content-type", "application/json");166
response.end(167
JSON.stringify({168
access_token: "first-token",169
refresh_token: "refresh-token",170
token_type: "Bearer",171
scope: "",172
}),173
);174
return;175
}176
if (url.pathname !== "/mcp") {177
response.statusCode = 404;178
response.end();179
return;180
}181
if (request.method === "GET") {182
response.statusCode = 405;183
response.end();184
return;185
}186
if (request.method === "DELETE") {187
response.statusCode = 200;188
response.end();189
return;190
}191
const token = request.headers.authorization;192
if (token !== "Bearer first-token" && token !== "Bearer refreshed-token") {193
await readBody(request);194
response.writeHead(401, {195
// An empty scope falls through to the resource metadata's scopes_supported.196
"www-authenticate": `Bearer resource_metadata="${serverOrigin}/.well-known/oauth-protected-resource/mcp", scope=""`,197
});198
response.end("Unauthorized");199
return;200
}201
const message = JSON.parse(await readBody(request)) as Record<string, unknown>;202
if (!("id" in message)) {203
response.statusCode = 202;204
response.end();205
return;206
}207
const result =208
message.method === "initialize"209
? {210
protocolVersion: "2025-06-18",211
capabilities: { tools: {} },212
serverInfo: { name: "oauth-test", version: "1.0.0" },213
}214
: { tools: [{ name: "issues", inputSchema: { type: "object" } }] };215
response.setHeader("content-type", "application/json");216
response.end(JSON.stringify({ jsonrpc: "2.0", id: message.id, result }));217
});219
const callback = await OAuthCallbackServer.listen();220
const provider = new TestOAuthProvider(callback.redirectUrl);221
const firstClient = new McpClient({ name: "oauth-test", version: "1.0.0" });222
await expect(223
firstClient.connect(224
new StreamableHttpTransport({225
url: `${origin}/mcp`,226
headers: { Authorization: "Bearer caller-supplied-stale-token" },227
authProvider: adaptOAuthProvider(provider),228
openGetStream: false,229
}),230
),231
).rejects.toBeInstanceOf(McpOAuthAuthorizationRequiredError);232
expect(provider.authorizationUrl?.searchParams.get("scope")).toBe("org:read");233
expect(provider.authorizationUrl?.searchParams.get("resource")).toBe(`${origin}/mcp`);235
const callbackResult = callback.waitForCallback("expected-state");236
const authorizationResponse = await fetch(provider.authorizationUrl as URL, { redirect: "manual" });237
await fetch(authorizationResponse.headers.get("location") as string);238
const { code } = await callbackResult;239
expect(240
await authorizeMcp(provider, {241
serverUrl: `${origin}/mcp`,242
authorizationCode: code,243
fetch,244
}),245
).toBe("AUTHORIZED");247
const client = new McpClient({ name: "oauth-test", version: "1.0.0" });248
await client.connect(249
new StreamableHttpTransport({250
url: `${origin}/mcp`,251
headers: { Authorization: "Bearer caller-supplied-stale-token" },252
authProvider: adaptOAuthProvider(provider),253
openGetStream: false,254
}),255
);256
expect(await client.listTools()).toEqual([{ name: "issues", inputSchema: { type: "object" } }]);257
await client.close();259
provider.tokenSet = { ...provider.tokenSet!, access_token: "stale-token" };260
const refreshedClient = new McpClient({ name: "oauth-test", version: "1.0.0" });261
await refreshedClient.connect(262
new StreamableHttpTransport({263
url: `${origin}/mcp`,264
headers: { Authorization: "Bearer caller-supplied-stale-token" },265
authProvider: adaptOAuthProvider(provider),266
openGetStream: false,267
}),268
);269
// Neither token response names a scope, so the grant has the requested scope.270
expect(provider.tokenSet).toEqual({271
access_token: "refreshed-token",272
refresh_token: "refresh-token",273
token_type: "Bearer",274
scope: "org:read",275
});276
expect(refreshes).toBe(1);277
await refreshedClient.close();278
await callback.close();279
});281
it("shares one refresh between concurrent 401s when refresh tokens rotate", async () => {282
const grants: string[] = [];283
const origin = await listen(async (request, response, serverOrigin) => {284
const url = new URL(request.url ?? "/", serverOrigin);285
if (url.pathname === "/.well-known/oauth-protected-resource/mcp") {286
// Invalid resource metadata falls back to the server origin instead of failing discovery.287
response.setHeader("content-type", "application/json");288
response.end(JSON.stringify({ resource: `${serverOrigin}/mcp`, authorization_servers: ["not a url"] }));289
return;290
}291
if (url.pathname === "/.well-known/oauth-authorization-server") {292
response.setHeader("content-type", "application/json");293
response.end(294
JSON.stringify({295
// Issuer without the trailing slash that URL parsing adds to the fallback server URL.296
issuer: serverOrigin,297
authorization_endpoint: `${serverOrigin}/authorize`,298
token_endpoint: `${serverOrigin}/token`,299
response_types_supported: ["code"],300
}),301
);302
return;303
}304
if (url.pathname === "/token") {305
const params = new URLSearchParams(await readBody(request));306
const refreshToken = params.get("refresh_token") ?? "";307
grants.push(refreshToken);308
response.setHeader("content-type", "application/json");309
if (refreshToken !== "r1") {310
response.statusCode = 400;311
response.end(JSON.stringify({ error: "invalid_grant" }));312
return;313
}314
await new Promise((resolve) => setTimeout(resolve, 20));315
response.end(316
JSON.stringify({ access_token: "a2", refresh_token: "r2", token_type: "Bearer", expires_in: 3600 }),317
);318
return;319
}320
response.statusCode = 404;321
response.end();322
});323
const store = new MemoryOAuthStateStore();324
const provider = new McpOAuthProvider({325
serverUrl: `${origin}/mcp`,326
redirectUrl: "http://127.0.0.1/callback",327
clientMetadata: { client_name: "test" },328
clientId: "client",329
store,330
onRedirect: () => {},331
});332
await provider.saveTokens({ access_token: "a1", refresh_token: "r1", token_type: "Bearer" });333
const auth = adaptOAuthProvider(provider);334
const unauthorized = () => ({335
response: new Response(null, { status: 401, headers: { "www-authenticate": "Bearer" } }),336
serverUrl: new URL(`${origin}/mcp`),337
fetch,338
token: "a1",339
});340
await Promise.all([auth.onUnauthorized?.(unauthorized()), auth.onUnauthorized?.(unauthorized())]);341
// A late 401 for a request that still carried the old token must not refresh again.342
await auth.onUnauthorized?.(unauthorized());343
expect(grants).toEqual(["r1"]);344
expect(await auth.token()).toBe("a2");345
const state = await store.load();346
expect(state?.tokens?.refresh_token).toBe("r2");347
expect(state?.tokensExpireAt).toBeGreaterThan(Date.now() + 3_500_000);348
});350
it("asks for authorization instead of refreshing when the server needs more scope", async () => {351
const provider = new TestOAuthProvider("http://127.0.0.1/callback");352
provider.client = { client_id: "client" };353
provider.tokenSet = { access_token: "a1", refresh_token: "r1", token_type: "Bearer", scope: "repo read:org" };354
const origin = await listen(async (request, response, serverOrigin) => {355
const url = new URL(request.url ?? "/", serverOrigin);356
if (url.pathname === "/.well-known/oauth-authorization-server") {357
response.setHeader("content-type", "application/json");358
response.end(359
JSON.stringify({360
issuer: serverOrigin,361
authorization_endpoint: `${serverOrigin}/authorize`,362
token_endpoint: `${serverOrigin}/token`,363
response_types_supported: ["code"],364
}),365
);366
return;367
}368
response.statusCode = url.pathname === "/token" ? 500 : 404;369
response.end();370
});371
const auth = adaptOAuthProvider(provider);372
await expect(373
auth.onUnauthorized?.({374
response: new Response(null, {375
status: 403,376
headers: { "www-authenticate": 'Bearer error="insufficient_scope", scope="repo admin"' },377
}),378
serverUrl: new URL(`${origin}/mcp`),379
fetch,380
token: "a1",381
}),382
).rejects.toBeInstanceOf(McpOAuthAuthorizationRequiredError);383
// The challenge may list only the missing scopes; the new grant keeps the old ones too.384
expect(provider.authorizationUrl?.searchParams.get("scope")).toBe("repo read:org admin");385
// The working grant is kept until the user authorizes the new scope.386
expect(provider.tokenSet?.access_token).toBe("a1");387
});389
it("binds persisted credentials to the exact MCP server URL", async () => {390
const store = new MemoryOAuthStateStore();391
const first = new McpOAuthProvider({392
serverUrl: "https://one.example/mcp",393
redirectUrl: "http://127.0.0.1/callback",394
clientMetadata: { client_name: "test" },395
store,396
onRedirect: () => {},397
});398
await first.saveTokens({ access_token: "secret", token_type: "Bearer" });399
expect((await first.tokens())?.access_token).toBe("secret");401
const second = new McpOAuthProvider({402
serverUrl: "https://two.example/mcp",403
redirectUrl: "http://127.0.0.1/callback",404
clientMetadata: { client_name: "test" },405
store,406
onRedirect: () => {},407
});408
expect(await second.tokens()).toBeUndefined();409
});411
// #10493412
it("registers with an application_type derived from the redirect URIs unless one is set", async () => {413
const bodies: Record<string, unknown>[] = [];414
const origin = await listen(async (request, response) => {415
const metadata = JSON.parse(await readBody(request)) as Record<string, unknown>;416
bodies.push(metadata);417
response.writeHead(201, { "content-type": "application/json" });418
response.end(JSON.stringify({ ...metadata, client_id: "client" }));419
});420
const register = (redirect_uris: string[], application_type?: string) =>421
registerClient(origin, {422
clientMetadata: { redirect_uris, ...(application_type ? { application_type } : {}) },423
});424
await register(["http://127.0.0.1:1234/callback"]);425
await register(["http://[::1]/callback"]);426
await register(["com.example.app:/callback"]);427
await register(["https://app.example/callback"]);428
await register(["http://localhost/callback"], "web");429
expect(bodies.map((body) => body.application_type)).toEqual(["native", "native", "native", "web", "web"]);430
});432
it("rejects authorization metadata whose issuer does not match discovery", async () => {433
const origin = await listen(async (request, response, serverOrigin) => {434
const url = new URL(request.url ?? "/", serverOrigin);435
if (url.pathname === "/.well-known/oauth-authorization-server") {436
response.setHeader("content-type", "application/json");437
response.end(438
JSON.stringify({439
issuer: "https://attacker.example",440
authorization_endpoint: `${serverOrigin}/authorize`,441
token_endpoint: `${serverOrigin}/token`,442
response_types_supported: ["code"],443
}),444
);445
return;446
}447
response.statusCode = 404;448
response.end();449
});450
await expect(discoverAuthorizationServerMetadata(origin)).rejects.toBeInstanceOf(OAuthIssuerMismatchError);451
});453
// #10172454
it("uses a configured authorization server metadata document as is", async () => {455
const origin = await listen(async (request, response, serverOrigin) => {456
const url = new URL(request.url ?? "/", serverOrigin);457
response.setHeader("content-type", "application/json");458
if (url.pathname === "/.well-known/oauth-protected-resource/mcp") {459
// Names the MCP server itself, which serves no authorization server metadata.460
response.end(JSON.stringify({ resource: `${serverOrigin}/mcp`, authorization_servers: [serverOrigin] }));461
} else if (url.pathname === "/idp/metadata.json") {462
response.end(463
JSON.stringify({464
// Not derivable from the document URL; a configured document is not checked.465
issuer: "https://idp.example",466
authorization_endpoint: `${serverOrigin}/idp/authorize`,467
token_endpoint: `${serverOrigin}/idp/token`,468
response_types_supported: ["code"],469
}),470
);471
} else {472
response.statusCode = 404;473
response.end();474
}475
});476
const provider = new TestOAuthProvider("http://127.0.0.1/callback");477
provider.client = { client_id: "client" };478
const options = {479
serverUrl: `${origin}/mcp`,480
authorizationServerMetadataUrl: new URL(`${origin}/idp/metadata.json`),481
};482
expect(await authorizeMcp(provider, options)).toBe("REDIRECT");483
const authorizationUrl = provider.authorizationUrl as URL;484
expect(`${authorizationUrl.origin}${authorizationUrl.pathname}`).toBe(`${origin}/idp/authorize`);485
expect(authorizationUrl.searchParams.get("resource")).toBe(`${origin}/mcp`);487
const insecure = { ...options, authorizationServerMetadataUrl: new URL("http://idp.example/metadata.json") };488
await expect(authorizeMcp(provider, insecure)).rejects.toBeInstanceOf(OAuthInsecureEndpointError);489
});491
it("exchanges a code only when its iss parameter names the authorization server", async () => {492
const codes: string[] = [];493
const origin = await listen(async (request, response) => {494
if (request.method !== "POST") {495
response.statusCode = 404;496
response.end();497
return;498
}499
codes.push(new URLSearchParams(await readBody(request)).get("code") ?? "");500
response.setHeader("content-type", "application/json");501
response.end(JSON.stringify({ access_token: "token", token_type: "Bearer" }));502
});503
const exchange = (code: string, iss: string | undefined, issParameterSupported: boolean, metadata = true) => {504
const provider = new TestOAuthProvider("http://127.0.0.1/callback");505
provider.client = { client_id: "client" };506
provider.verifier = "verifier";507
provider.discovery = {508
authorizationServerUrl: origin,509
authorizationServerMetadata: metadata510
? {511
issuer: origin,512
authorization_endpoint: `${origin}/authorize`,513
token_endpoint: `${origin}/token`,514
response_types_supported: ["code"],515
authorization_response_iss_parameter_supported: issParameterSupported,516
}517
: undefined,518
};519
return authorizeMcp(provider, { serverUrl: `${origin}/mcp`, authorizationCode: code, iss });520
};521
await expect(exchange("other", "https://attacker.example", false)).rejects.toBeInstanceOf(522
OAuthIssuerMismatchError,523
);524
await expect(exchange("missing", undefined, true)).rejects.toBeInstanceOf(OAuthIssuerMismatchError);525
expect(await exchange("matching", origin, true)).toBe("AUTHORIZED");526
// Servers that do not promise the parameter may omit it.527
expect(await exchange("omitted", undefined, false)).toBe("AUTHORIZED");528
// Without metadata there is no issuer to compare with, so a server cannot skip the check by hiding it.529
await expect(exchange("unverifiable", "https://attacker.example", false, false)).rejects.toBeInstanceOf(530
OAuthIssuerMismatchError,531
);532
expect(await exchange("no-metadata", undefined, false, false)).toBe("AUTHORIZED");533
expect(codes).toEqual(["matching", "omitted", "no-metadata"]);534
});536
// #10565537
it("stops when its signal aborts, without falling back to a redirect", async () => {538
const stalled: string[] = [];539
// Accepts every request and never answers.540
const origin = await listen(async (request, _response, serverOrigin) => {541
stalled.push(new URL(request.url ?? "/", serverOrigin).pathname);542
});543
const run = async (provider: TestOAuthProvider) => {544
const controller = new AbortController();545
const count = stalled.length;546
const flow = authorizeMcp(provider, { serverUrl: `${origin}/mcp`, signal: controller.signal });547
const settled = flow.catch((error: unknown) => error);548
await expect.poll(() => stalled.length).toBe(count + 1);549
controller.abort();550
expect(await settled).toMatchObject({ name: "AbortError" });551
expect(provider.authorizationUrl).toBeUndefined();552
return stalled.at(-1);553
};555
// Discovery.556
expect(await run(new TestOAuthProvider("http://127.0.0.1/callback"))).toBe(557
"/.well-known/oauth-protected-resource/mcp",558
);560
// A failed refresh otherwise falls back to a new authorization.561
const refreshing = new TestOAuthProvider("http://127.0.0.1/callback");562
refreshing.client = { client_id: "client" };563
refreshing.tokenSet = { access_token: "a1", refresh_token: "r1", token_type: "Bearer" };564
refreshing.discovery = {565
authorizationServerUrl: origin,566
authorizationServerMetadata: {567
issuer: origin,568
authorization_endpoint: `${origin}/authorize`,569
token_endpoint: `${origin}/token`,570
response_types_supported: ["code"],571
},572
};573
expect(await run(refreshing)).toBe("/token");574
});575
});577
describe("OAuthCallbackServer pages", () => {578
it("renders plain text by default", async () => {579
const callback = await OAuthCallbackServer.listen();580
try {581
const pending = callback.waitForCallback("s1");582
const response = await fetch(`${callback.redirectUrl}?code=abc&state=s1`);583
expect(response.headers.get("content-type")).toBe("text/plain; charset=utf-8");584
expect(await response.text()).toBe("Authorization complete. You may close this window.");585
expect((await pending).code).toBe("abc");586
} finally {587
await callback.close();588
}589
});591
// #10302592
it("rejects a response on another path than the expected one", async () => {593
const callback = await OAuthCallbackServer.listen({ extraPaths: ["/callback/server-id"] });594
try {595
const origin = new URL(callback.redirectUrl).origin;596
const mixedUp = callback.waitForCallback("s1", "/callback/server-id");597
mixedUp.catch(() => undefined);598
const wrong = await fetch(`${origin}/callback?code=abc&state=s1`);599
expect(wrong.status).toBe(400);600
await expect(mixedUp).rejects.toThrow("arrived on another redirect URI");602
const pending = callback.waitForCallback("s2", "/callback/server-id");603
const right = await fetch(`${origin}/callback/server-id?code=abc&state=s2`);604
expect(right.status).toBe(200);605
expect((await pending).code).toBe("abc");606
} finally {607
await callback.close();608
}609
});611
it("renders pages through renderPage", async () => {612
const pages: OAuthCallbackPage[] = [];613
const callback = await OAuthCallbackServer.listen({614
renderPage: (page) => {615
pages.push(page);616
return page.ok ? "<p>ok</p>" : `<p>${page.message}</p>`;617
},618
});619
try {620
const denied = callback.waitForCallback("s1");621
denied.catch(() => undefined);622
const failure = await fetch(`${callback.redirectUrl}?error=access_denied&error_description=Denied&state=s1`);623
expect(failure.headers.get("content-type")).toBe("text/html; charset=utf-8");624
await expect(denied).rejects.toThrow("Denied");625
expect(pages.at(-1)).toEqual({626
ok: false,627
message: "Authorization failed. You may close this window.",628
details: "Denied",629
});631
const pending = callback.waitForCallback("s2");632
const success = await fetch(`${callback.redirectUrl}?code=abc&state=s2`);633
expect(await success.text()).toBe("<p>ok</p>");634
expect((await pending).code).toBe("abc");635
} finally {636
await callback.close();637
}638
});639
});