Skip to content

A self-improving RLM agent for coding workflows and long-running autonomous tasks.

Rust

fix(ai): follow MCP protected-resource OAuth discovery (#1591)

Seth Karten8c749fb98ecd
diff --git a/packages/ai/.changes/mcp-oauth-resource-discovery.md b/packages/ai/.changes/mcp-oauth-resource-discovery.md
new file mode 100644
index 0000000000..11148cfe56
--- /dev/null
+++ b/packages/ai/.changes/mcp-oauth-resource-discovery.md
@@ -0,0 +1 @@
+- Fixed path-scoped protected-resource discovery and resource-bound refresh for MCP OAuth servers.
diff --git a/packages/ai/src/mcp/oauth.ts b/packages/ai/src/mcp/oauth.ts
index cfa43612d1..525d6b4fb1 100644
--- a/packages/ai/src/mcp/oauth.ts
+++ b/packages/ai/src/mcp/oauth.ts
@@ -15,19 +15,30 @@ const ALL_REDIRECT_URIS = CALLBACK_PORTS.map(redirectUriFor);
const TOKEN_EXPIRY_BUFFER_MS = 5 * 60 * 1000;
interface AuthServerMetadata {
- issuer?: string;
+ issuer: string;
authorization_endpoint: string;
token_endpoint: string;
registration_endpoint?: string;
scopes_supported?: string[];
}
+interface ProtectedResourceMetadata {
+ resource: string;
+ authorization_servers: string[];
+}
+
+interface Discovery {
+ metadata: AuthServerMetadata;
+ resource?: string;
+ issuer?: string;
+}
+
export interface McpOAuthConfig {
/** MCP server name; provider id becomes `mcp:<server>`. */
server: string;
/** Human-readable label shown in OAuth UI; defaults to `server`. */
label?: string;
- /** The MCP endpoint URL — discovery is rooted at its origin. */
+ /** MCP resource URL used for protected-resource and authorization-server discovery. */
url: string;
/** Pre-registered client id (servers without DCR, e.g. Slack). */
clientId?: string;
@@ -40,51 +51,175 @@ interface McpCredentials extends OAuthCredentials {
clientId?: string;
/** MCP endpoint the token was issued for; consumers refuse to send it elsewhere. */
endpoint?: string;
+ /** RFC 9728 resource indicator. Its presence marks a PRM-based login. */
+ resource?: string;
+ /** RFC 8414/OIDC issuer selected by the protected-resource metadata. */
+ issuer?: string;
+}
+
+function validatedHttpsUrl(value: string, name: string): URL {
+ let url: URL;
+ try {
+ url = new URL(value);
+ } catch {
+ throw new Error(`${name} must be an absolute HTTPS URL`);
+ }
+ if (url.protocol !== "https:" || url.username || url.password || url.hash) {
+ throw new Error(`${name} must be an absolute HTTPS URL without credentials or a fragment`);
+ }
+ return url;
+}
+
+function canonicalResource(url: URL): string {
+ if (url.pathname === "/" && !url.search) return url.origin;
+ return `${url.origin}${url.pathname}${url.search}`;
+}
+
+function authorizationServerMetadataUrls(issuer: string): string[] {
+ const url = validatedHttpsUrl(issuer, "Authorization server issuer");
+ if (url.search) throw new Error("Authorization server issuer must not contain a query string");
+ const path = url.pathname === "/" ? "" : url.pathname.replace(/\/$/, "");
+ return [
+ new URL(`/.well-known/oauth-authorization-server${path}`, url.origin).toString(),
+ new URL(`${path}/.well-known/openid-configuration`, url.origin).toString(),
+ ];
+}
+
+async function fetchResponse(url: string, init?: RequestInit): Promise<Response> {
+ return fetch(url, { ...init, redirect: "error" });
}
async function fetchJson(url: string, init?: RequestInit): Promise<unknown> {
- const res = await fetch(url, init);
+ const res = await fetchResponse(url, init);
if (!res.ok) {
- throw new Error(`${init?.method ?? "GET"} ${url} failed: ${res.status} ${await res.text()}`);
+ throw new Error(`${init?.method ?? "GET"} ${url} failed: ${res.status}`);
}
return res.json();
}
-/** Random, URL-safe CSRF `state` value, independent of the PKCE verifier. */
-function randomState(): string {
- const bytes = new Uint8Array(32);
- crypto.getRandomValues(bytes);
- return btoa(String.fromCharCode(...bytes))
- .replace(/\+/g, "-")
- .replace(/\//g, "_")
- .replace(/=/g, "");
+function authorizationServerMetadata(value: unknown, issuer: string, requireExactIssuer: boolean): AuthServerMetadata {
+ if (!value || typeof value !== "object") throw new Error(`Authorization server metadata for ${issuer} is invalid`);
+ const metadata = value as Partial<AuthServerMetadata>;
+ if (typeof metadata.issuer !== "string") {
+ throw new Error(`Authorization server metadata for ${issuer} is missing its issuer`);
+ }
+ if (requireExactIssuer) {
+ if (metadata.issuer !== issuer) {
+ throw new Error(`Authorization server metadata issuer does not exactly match ${issuer}`);
+ }
+ } else {
+ const advertisedIssuer = validatedHttpsUrl(metadata.issuer, "Authorization server metadata issuer");
+ if (advertisedIssuer.origin !== new URL(issuer).origin || advertisedIssuer.search) {
+ throw new Error(`Origin authorization server metadata issuer must stay on ${new URL(issuer).origin}`);
+ }
+ }
+ if (typeof metadata.authorization_endpoint !== "string" || typeof metadata.token_endpoint !== "string") {
+ throw new Error(`Authorization server metadata for ${issuer} is missing required endpoints`);
+ }
+ validatedHttpsUrl(metadata.authorization_endpoint, "Authorization endpoint");
+ validatedHttpsUrl(metadata.token_endpoint, "Token endpoint");
+ if (metadata.registration_endpoint) validatedHttpsUrl(metadata.registration_endpoint, "Registration endpoint");
+ return metadata as AuthServerMetadata;
}
-/** Try the protected-resource and auth-server well-known docs at the URL's origin. */
-async function discover(url: string): Promise<AuthServerMetadata> {
- const origin = new URL(url).origin;
- const candidates = [
- `${origin}/.well-known/oauth-authorization-server`,
- `${origin}/.well-known/openid-configuration`,
- ];
+async function jsonMetadata(response: Response, url: string): Promise<unknown> {
+ if (response.status !== 200) throw new Error(`GET ${url} failed: ${response.status}`);
+ const contentType = response.headers.get("content-type")?.split(";", 1)[0].trim().toLowerCase();
+ if (contentType !== "application/json") throw new Error(`GET ${url} did not return application/json`);
+ return response.json();
+}
+
+async function discoverAuthorizationServer(issuer: string, requireExactIssuer: boolean): Promise<AuthServerMetadata> {
+ const candidates = authorizationServerMetadataUrls(issuer);
let lastError: unknown;
for (const candidate of candidates) {
try {
- const meta = (await fetchJson(candidate)) as AuthServerMetadata;
- if (meta.authorization_endpoint && meta.token_endpoint) {
- return meta;
- }
+ const response = await fetchResponse(candidate);
+ if (response.status === 404) continue;
+ return authorizationServerMetadata(await jsonMetadata(response, candidate), issuer, requireExactIssuer);
} catch (error) {
lastError = error;
}
}
throw new Error(
- `Could not discover OAuth metadata for ${origin}. ` +
- `Tried ${candidates.join(", ")}. Last error: ${String(lastError)}`,
+ `Could not discover OAuth metadata for ${issuer}. Tried ${candidates.join(", ")}. Last error: ${String(lastError)}`,
);
}
+/** Random, URL-safe CSRF `state` value, independent of the PKCE verifier. */
+function randomState(): string {
+ const bytes = new Uint8Array(32);
+ crypto.getRandomValues(bytes);
+ return btoa(String.fromCharCode(...bytes))
+ .replace(/\+/g, "-")
+ .replace(/\//g, "_")
+ .replace(/=/g, "");
+}
+
+function resourceMetadata(value: unknown, resource: string): ProtectedResourceMetadata {
+ if (!value || typeof value !== "object") throw new Error("Protected-resource metadata is invalid");
+ const metadata = value as Partial<ProtectedResourceMetadata>;
+ if (metadata.resource !== resource)
+ throw new Error(`Protected-resource metadata resource does not exactly match ${resource}`);
+ if (!Array.isArray(metadata.authorization_servers) || metadata.authorization_servers.length === 0) {
+ throw new Error("Protected-resource metadata has no authorization_servers");
+ }
+ for (const issuer of metadata.authorization_servers) {
+ if (typeof issuer !== "string")
+ throw new Error("Protected-resource metadata has an invalid authorization server");
+ validatedHttpsUrl(issuer, "Authorization server issuer");
+ }
+ return metadata as ProtectedResourceMetadata;
+}
+
+function resourceMetadataUrl(resource: URL): string {
+ const path = resource.pathname === "/" ? "" : resource.pathname;
+ return `${resource.origin}/.well-known/oauth-protected-resource${path}${resource.search}`;
+}
+
+function headerResourceMetadata(value: string | null): string | undefined {
+ const match = value?.match(/(?:^|[,\s])resource_metadata\s*=\s*"((?:[^"\\]|\\.)*)"/i);
+ if (!match) return undefined;
+ return match[1].replace(/\\(.)/g, "$1");
+}
+
+async function tryProtectedResourceMetadata(url: string): Promise<ProtectedResourceMetadata | undefined> {
+ const resource = validatedHttpsUrl(url, "MCP endpoint");
+ let headerUrl: string | undefined;
+ try {
+ // This probe deliberately has no Authorization header. It must not leak an existing token.
+ const response = await fetchResponse(resource.toString());
+ headerUrl = headerResourceMetadata(response.headers.get("www-authenticate"));
+ await response.body?.cancel();
+ } catch {
+ // The server need not support a GET probe; use the RFC well-known locations below.
+ }
+
+ const candidate = headerUrl
+ ? validatedHttpsUrl(headerUrl, "resource_metadata").toString()
+ : resourceMetadataUrl(resource);
+ const response = await fetchResponse(candidate);
+ if (response.status === 404 && !headerUrl) return undefined;
+ return resourceMetadata(await jsonMetadata(response, candidate), canonicalResource(resource));
+}
+
+/** Discover RFC 9728 protected-resource metadata before the origin-level authorization server fallback. */
+async function discover(url: string): Promise<Discovery> {
+ const protectedResource = await tryProtectedResourceMetadata(url);
+ if (protectedResource) {
+ const issuer = protectedResource.authorization_servers[0];
+ return {
+ metadata: await discoverAuthorizationServer(issuer, true),
+ resource: protectedResource.resource,
+ issuer,
+ };
+ }
+ const issuer = validatedHttpsUrl(url, "MCP endpoint").origin;
+ return { metadata: await discoverAuthorizationServer(issuer, false) };
+}
+
async function registerClient(registrationEndpoint: string, label: string): Promise<string> {
+ validatedHttpsUrl(registrationEndpoint, "Registration endpoint");
const body = {
client_name: label,
redirect_uris: ALL_REDIRECT_URIS,
@@ -96,8 +231,8 @@ async function registerClient(registrationEndpoint: string, label: string): Prom
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(body),
- })) as { client_id?: string };
- if (!data.client_id) {
+ })) as { client_id?: unknown };
+ if (typeof data.client_id !== "string" || !data.client_id) {
throw new Error(`Dynamic client registration at ${registrationEndpoint} returned no client_id`);
}
return data.client_id;
@@ -212,16 +347,37 @@ async function exchangeToken(
tokenEndpoint: string,
params: Record<string, string>,
): Promise<{ access_token: string; refresh_token?: string; expires_in?: number }> {
- const res = await fetch(tokenEndpoint, {
+ validatedHttpsUrl(tokenEndpoint, "Token endpoint");
+ const res = await fetchResponse(tokenEndpoint, {
method: "POST",
headers: { "Content-Type": "application/x-www-form-urlencoded" },
body: new URLSearchParams(params).toString(),
});
const text = await res.text();
if (!res.ok) {
- throw new Error(`Token request to ${tokenEndpoint} failed: ${res.status} ${text}`);
+ throw new Error(`Token request to ${tokenEndpoint} failed: ${res.status}`);
+ }
+ let token: unknown;
+ try {
+ token = JSON.parse(text);
+ } catch {
+ throw new Error(`Token request to ${tokenEndpoint} returned invalid JSON`);
+ }
+ if (!token || typeof token !== "object" || typeof (token as { access_token?: unknown }).access_token !== "string") {
+ throw new Error(`Token request to ${tokenEndpoint} returned no access_token`);
+ }
+ const result = token as { access_token: string; refresh_token?: unknown; expires_in?: unknown };
+ if (!result.access_token) throw new Error(`Token request to ${tokenEndpoint} returned no access_token`);
+ if (result.refresh_token !== undefined && typeof result.refresh_token !== "string") {
+ throw new Error(`Token request to ${tokenEndpoint} returned an invalid refresh_token`);
}
- return JSON.parse(text);
+ if (
+ result.expires_in !== undefined &&
+ (typeof result.expires_in !== "number" || !Number.isFinite(result.expires_in))
+ ) {
+ throw new Error(`Token request to ${tokenEndpoint} returned an invalid expires_in`);
+ }
+ return result as { access_token: string; refresh_token?: string; expires_in?: number };
}
function toCredentials(
@@ -229,6 +385,8 @@ function toCredentials(
tokenEndpoint: string,
clientId: string,
endpoint: string | undefined,
+ resource: string | undefined,
+ issuer: string | undefined,
previousRefresh?: string,
): McpCredentials {
return {
@@ -241,6 +399,8 @@ function toCredentials(
tokenEndpoint,
clientId,
endpoint,
+ resource,
+ issuer,
};
}
@@ -248,8 +408,9 @@ export function createMcpOAuthProvider(config: McpOAuthConfig): OAuthProviderInt
const label = config.label ?? config.server;
async function login(callbacks: OAuthLoginCallbacks): Promise<OAuthCredentials> {
- const meta = await discover(config.url);
- callbacks.onProgress?.(`Discovered ${meta.issuer ?? new URL(config.url).origin}`);
+ const discovery = await discover(config.url);
+ const { metadata: meta } = discovery;
+ callbacks.onProgress?.(`Discovered ${discovery.issuer ?? meta.issuer}`);
let clientId = config.clientId;
if (!clientId) {
@@ -279,9 +440,12 @@ export function createMcpOAuthProvider(config: McpOAuthConfig): OAuthProviderInt
state,
});
if (scope) authParams.set("scope", scope);
+ if (discovery.resource) authParams.set("resource", discovery.resource);
+ const authorizationUrl = new URL(meta.authorization_endpoint);
+ for (const [name, value] of authParams) authorizationUrl.searchParams.set(name, value);
callbacks.onAuth({
- url: `${meta.authorization_endpoint}?${authParams.toString()}`,
+ url: authorizationUrl.toString(),
instructions:
"Complete login in your browser. If the browser is on another machine, paste the final redirect URL here.",
});
@@ -344,8 +508,9 @@ export function createMcpOAuthProvider(config: McpOAuthConfig): OAuthProviderInt
redirect_uri: cb.redirectUri,
client_id: clientId,
code_verifier: verifier,
+ ...(discovery.resource ? { resource: discovery.resource } : {}),
});
- return toCredentials(token, meta.token_endpoint, clientId, config.url);
+ return toCredentials(token, meta.token_endpoint, clientId, config.url, discovery.resource, discovery.issuer);
} finally {
cb.server.close();
}
@@ -353,18 +518,58 @@ export function createMcpOAuthProvider(config: McpOAuthConfig): OAuthProviderInt
async function refreshToken(credentials: OAuthCredentials): Promise<OAuthCredentials> {
const creds = credentials as McpCredentials;
- const tokenEndpoint = creds.tokenEndpoint ?? (await discover(config.url)).token_endpoint;
- const clientId = creds.clientId ?? config.clientId;
+ if (creds.endpoint !== config.url) {
+ throw new Error(`Stored OAuth credentials are not bound to ${config.url}; re-run /mcp login ${config.server}`);
+ }
+ const configuredResource = canonicalResource(validatedHttpsUrl(config.url, "MCP endpoint"));
+ if (creds.resource !== undefined && creds.resource !== configuredResource) {
+ throw new Error(
+ `Stored OAuth credentials are not bound to ${configuredResource}; re-run /mcp login ${config.server}`,
+ );
+ }
+ if ((creds.resource === undefined) !== (creds.issuer === undefined)) {
+ throw new Error(
+ `Stored OAuth credentials for ${label} have incomplete resource binding; re-run /mcp login ${config.server}`,
+ );
+ }
+ if (creds.issuer !== undefined) validatedHttpsUrl(creds.issuer, "Stored authorization server issuer");
if (!creds.refresh) {
throw new Error(`No refresh token stored for ${label}; re-run /mcp login ${config.server}`);
}
+ const discovery = await discover(config.url);
+ if ((creds.resource === undefined) !== (discovery.resource === undefined)) {
+ throw new Error(`OAuth discovery mode changed for ${config.url}; re-run /mcp login ${config.server}`);
+ }
+ if (creds.resource) {
+ if (discovery.resource !== creds.resource || discovery.issuer !== creds.issuer) {
+ throw new Error(
+ `Stored OAuth credentials do not match current protected-resource metadata for ${config.url}`,
+ );
+ }
+ }
+ const tokenEndpoint = creds.tokenEndpoint ?? discovery.metadata.token_endpoint;
+ if (creds.tokenEndpoint && discovery.metadata.token_endpoint !== creds.tokenEndpoint) {
+ throw new Error(
+ `Stored OAuth token endpoint does not match current authorization-server metadata for ${config.url}`,
+ );
+ }
+ const clientId = creds.clientId ?? config.clientId;
+ if (!tokenEndpoint) throw new Error(`No token endpoint stored for ${label}; re-run /mcp login ${config.server}`);
const token = await exchangeToken(tokenEndpoint, {
grant_type: "refresh_token",
refresh_token: creds.refresh,
...(clientId ? { client_id: clientId } : {}),
+ ...(creds.resource ? { resource: creds.resource } : {}),
});
- // Never infer a binding: refreshing an unbound credential must not rebind it to the current URL.
- return toCredentials(token, tokenEndpoint, clientId ?? "", creds.endpoint, creds.refresh);
+ return toCredentials(
+ token,
+ tokenEndpoint,
+ clientId ?? "",
+ creds.endpoint,
+ creds.resource,
+ creds.issuer,
+ creds.refresh,
+ );
}
return {
diff --git a/packages/ai/test/mcp-oauth.test.ts b/packages/ai/test/mcp-oauth.test.ts
index fe90b12785..e35f2a009d 100644
--- a/packages/ai/test/mcp-oauth.test.ts
+++ b/packages/ai/test/mcp-oauth.test.ts
@@ -1,8 +1,9 @@
+import { createServer } from "node:http";
import { afterEach, describe, expect, it, vi } from "vitest";
import { createMcpOAuthProvider } from "../src/mcp/oauth.js";
-function jsonResponse(body: unknown, status = 200): Response {
- return new Response(JSON.stringify(body), { status, headers: { "Content-Type": "application/json" } });
+function jsonResponse(body: unknown, status = 200, headers?: Record<string, string>): Response {
+ return new Response(JSON.stringify(body), { status, headers: { "Content-Type": "application/json", ...headers } });
}
function urlOf(input: unknown): string {
@@ -12,158 +13,435 @@ function urlOf(input: unknown): string {
throw new Error(`Unsupported fetch input: ${String(input)}`);
}
-const META = {
- issuer: "https://srv.test",
+const RESOURCE = "https://mcp.plane.so/http/mcp";
+const PLANE_ISSUER = "https://mcp.plane.so/http";
+const PLANE_PRM_URL = "https://mcp.plane.so/.well-known/oauth-protected-resource/http/mcp";
+const PLANE_META_URL = "https://mcp.plane.so/.well-known/oauth-authorization-server/http";
+const PLANE_META = {
+ issuer: PLANE_ISSUER,
+ authorization_endpoint: "https://mcp.plane.so/http/authorize",
+ token_endpoint: "https://mcp.plane.so/http/token",
+ registration_endpoint: "https://mcp.plane.so/http/register",
+ scopes_supported: ["read", "write"],
+};
+const ORIGIN_URL = "https://srv.test/mcp";
+const ORIGIN_META = {
+ issuer: "https://srv.test/tenant",
authorization_endpoint: "https://srv.test/authorize",
token_endpoint: "https://srv.test/token",
registration_endpoint: "https://srv.test/register",
scopes_supported: ["read", "write"],
};
+function absentPrm(input: unknown): Response | undefined {
+ const url = urlOf(input);
+ if (url === ORIGIN_URL) return new Response("", { status: 404 });
+ if (url === "https://srv.test/.well-known/oauth-protected-resource/mcp") return new Response("", { status: 404 });
+ if (url === "https://srv.test/.well-known/oauth-protected-resource") return new Response("", { status: 404 });
+ return undefined;
+}
+
+async function loginWithManualCode(
+ provider: ReturnType<typeof createMcpOAuthProvider>,
+): Promise<{ creds: object; authUrl: string }> {
+ let authUrl = "";
+ const creds = await provider.login({
+ onAuth: (info) => {
+ authUrl = info.url;
+ },
+ onPrompt: async () => "",
+ onManualCodeInput: async () => {
+ const params = new URL(authUrl).searchParams;
+ return `${params.get("redirect_uri")}?code=the-code&state=${params.get("state")}`;
+ },
+ });
+ return { creds, authUrl };
+}
+
describe.sequential("MCP OAuth provider", () => {
afterEach(() => {
vi.unstubAllGlobals();
});
it("has a namespaced id and label", () => {
- const provider = createMcpOAuthProvider({ server: "linear", label: "Linear", url: "https://srv.test/mcp" });
+ const provider = createMcpOAuthProvider({ server: "linear", label: "Linear", url: ORIGIN_URL });
expect(provider.id).toBe("mcp:linear");
expect(provider.name).toBe("Linear");
expect(provider.usesCallbackServer).toBe(true);
});
- it("discovers, registers a client, and exchanges the code for tokens", async () => {
- let authUrl = "";
+ it("discovers Plane protected-resource metadata and its external pathful issuer", async () => {
const fetchMock = vi.fn(async (input: unknown, init?: RequestInit): Promise<Response> => {
const url = urlOf(input);
- if (url.endsWith("/.well-known/oauth-authorization-server")) return jsonResponse(META);
- if (url === META.registration_endpoint) return jsonResponse({ client_id: "client-xyz" });
- if (url === META.token_endpoint) {
+ if (url === RESOURCE) {
+ expect(init?.headers).toBeUndefined();
+ return new Response("", { status: 401 });
+ }
+ if (url === PLANE_PRM_URL) return jsonResponse({ resource: RESOURCE, authorization_servers: [PLANE_ISSUER] });
+ if (url === PLANE_META_URL) return jsonResponse(PLANE_META);
+ if (url === PLANE_META.registration_endpoint) {
+ expect(init?.redirect).toBe("error");
+ return jsonResponse({ client_id: "plane-client" });
+ }
+ if (url === PLANE_META.token_endpoint) {
+ expect(init?.redirect).toBe("error");
const params = new URLSearchParams(String(init?.body));
expect(params.get("grant_type")).toBe("authorization_code");
- expect(params.get("client_id")).toBe("client-xyz");
- expect(params.get("code")).toBe("the-code");
- expect(params.get("code_verifier")).toBeTruthy();
+ expect(params.get("resource")).toBe(RESOURCE);
return jsonResponse({ access_token: "access-1", refresh_token: "refresh-1", expires_in: 3600 });
}
throw new Error(`unexpected fetch: ${url}`);
});
vi.stubGlobal("fetch", fetchMock);
- const provider = createMcpOAuthProvider({ server: "demo", url: "https://srv.test/mcp" });
- const creds = await provider.login({
- onAuth: (info) => {
- authUrl = info.url;
- },
- onPrompt: async () => "",
- onManualCodeInput: async () => {
- const state = new URL(authUrl).searchParams.get("state") ?? "";
- return `${REDIRECT}?code=the-code&state=${state}`;
- },
+ const { creds, authUrl } = await loginWithManualCode(createMcpOAuthProvider({ server: "plane", url: RESOURCE }));
+ expect(creds).toMatchObject({
+ access: "access-1",
+ endpoint: RESOURCE,
+ resource: RESOURCE,
+ issuer: PLANE_ISSUER,
+ tokenEndpoint: PLANE_META.token_endpoint,
});
-
- expect(creds.access).toBe("access-1");
- expect(creds.refresh).toBe("refresh-1");
- expect(creds.expires).toBeGreaterThan(Date.now());
- expect((creds as { endpoint?: string }).endpoint).toBe("https://srv.test/mcp");
const authParams = new URL(authUrl).searchParams;
- expect(authParams.get("client_id")).toBe("client-xyz");
- expect(authParams.get("code_challenge")).toBeTruthy();
+ expect(authParams.get("client_id")).toBe("plane-client");
+ expect(authParams.get("resource")).toBe(RESOURCE);
expect(authParams.get("scope")).toBe("read write");
+ expect(fetchMock).toHaveBeenCalledWith(RESOURCE, expect.objectContaining({ redirect: "error" }));
});
- it("falls back to the next port when the base callback port is in use", async () => {
- const http = await import("node:http");
- const blocker = http.createServer();
- const blockerBound = await new Promise<boolean>((resolve) => {
- blocker.once("error", () => resolve(false));
- blocker.listen(53700, "127.0.0.1", () => resolve(true));
- });
- try {
- let authUrl = "";
- vi.stubGlobal(
- "fetch",
- vi.fn(async (input: unknown): Promise<Response> => {
- const url = urlOf(input);
- if (url.endsWith("/.well-known/oauth-authorization-server")) return jsonResponse(META);
- if (url === META.registration_endpoint) return jsonResponse({ client_id: "c" });
- if (url === META.token_endpoint) return jsonResponse({ access_token: "a", expires_in: 60 });
- throw new Error(`unexpected fetch: ${url}`);
- }),
- );
- const provider = createMcpOAuthProvider({ server: "demo", url: "https://srv.test/mcp" });
- const creds = await provider.login({
- onAuth: (info) => {
- authUrl = info.url;
- },
+ it("uses pathful OIDC metadata when RFC 8414 returns a non-metadata document", async () => {
+ const issuer = "https://login.example/tenant";
+ const oidcMeta = "https://login.example/tenant/.well-known/openid-configuration";
+ const metadata = {
+ ...PLANE_META,
+ issuer,
+ authorization_endpoint: "https://login.example/tenant/authorize",
+ token_endpoint: "https://login.example/tenant/token",
+ registration_endpoint: "https://login.example/tenant/register",
+ };
+ vi.stubGlobal(
+ "fetch",
+ vi.fn(async (input: unknown): Promise<Response> => {
+ const url = urlOf(input);
+ if (url === RESOURCE) return new Response("", { status: 404 });
+ if (url === PLANE_PRM_URL) return jsonResponse({ resource: RESOURCE, authorization_servers: [issuer] });
+ if (url === "https://login.example/.well-known/oauth-authorization-server/tenant")
+ return new Response("<html>not metadata</html>", {
+ status: 200,
+ headers: { "Content-Type": "text/html" },
+ });
+ if (url === oidcMeta) return jsonResponse(metadata);
+ if (url === metadata.registration_endpoint) return jsonResponse({ client_id: "c" });
+ if (url === metadata.token_endpoint) return jsonResponse({ access_token: "a", expires_in: 60 });
+ throw new Error(`unexpected fetch: ${url}`);
+ }),
+ );
+ const { creds } = await loginWithManualCode(createMcpOAuthProvider({ server: "plane", url: RESOURCE }));
+ expect(creds).toMatchObject({ resource: RESOURCE, issuer });
+ });
+
+ it("fails closed after protected-resource metadata selects an issuer", async () => {
+ vi.stubGlobal(
+ "fetch",
+ vi.fn(async (input: unknown): Promise<Response> => {
+ const url = urlOf(input);
+ if (url === RESOURCE)
+ return new Response("", {
+ status: 401,
+ headers: { "WWW-Authenticate": `Bearer resource_metadata="${PLANE_PRM_URL}"` },
+ });
+ if (url === PLANE_PRM_URL)
+ return jsonResponse({ resource: RESOURCE, authorization_servers: [PLANE_ISSUER] });
+ if (url === PLANE_META_URL) return jsonResponse({ ...PLANE_META, issuer: "https://wrong.example" });
+ if (url === "https://mcp.plane.so/http/.well-known/openid-configuration")
+ return new Response("", { status: 404 });
+ throw new Error(`unexpected fetch: ${url}`);
+ }),
+ );
+ await expect(
+ createMcpOAuthProvider({ server: "plane", url: RESOURCE }).login({
+ onAuth: () => {},
onPrompt: async () => "",
- onManualCodeInput: async () => {
- const p = new URL(authUrl).searchParams;
- return `${p.get("redirect_uri")}?code=x&state=${p.get("state")}`;
- },
- });
- expect(creds.access).toBe("a");
- const redirect = new URL(authUrl).searchParams.get("redirect_uri") ?? "";
- expect(redirect).not.toContain(":53700/");
- expect(redirect).toContain(":5370");
- } finally {
- if (blockerBound) await new Promise<void>((resolve) => blocker.close(() => resolve()));
- }
+ }),
+ ).rejects.toThrow("issuer does not exactly match");
});
- it("refreshes tokens, keeping the prior refresh token when omitted", async () => {
+ it("accepts a same-origin pathful issuer from origin-level metadata when protected-resource metadata is absent", async () => {
const fetchMock = vi.fn(async (input: unknown, init?: RequestInit): Promise<Response> => {
+ const missing = absentPrm(input);
+ if (missing) return missing;
const url = urlOf(input);
- if (url === META.token_endpoint) {
+ if (url === "https://srv.test/.well-known/oauth-authorization-server") return jsonResponse(ORIGIN_META);
+ if (url === ORIGIN_META.registration_endpoint) return jsonResponse({ client_id: "origin-client" });
+ if (url === ORIGIN_META.token_endpoint) {
const params = new URLSearchParams(String(init?.body));
- expect(params.get("grant_type")).toBe("refresh_token");
- expect(params.get("refresh_token")).toBe("old-refresh");
- return jsonResponse({ access_token: "access-2", expires_in: 1800 });
+ expect(params.get("resource")).toBeNull();
+ return jsonResponse({ access_token: "origin-access", refresh_token: "origin-refresh", expires_in: 3600 });
}
throw new Error(`unexpected fetch: ${url}`);
});
vi.stubGlobal("fetch", fetchMock);
+ const { creds, authUrl } = await loginWithManualCode(
+ createMcpOAuthProvider({ server: "origin", url: ORIGIN_URL }),
+ );
+ expect(creds).toMatchObject({
+ access: "origin-access",
+ endpoint: ORIGIN_URL,
+ resource: undefined,
+ issuer: undefined,
+ });
+ expect(new URL(authUrl).searchParams.get("resource")).toBeNull();
+ expect(fetchMock.mock.calls.map(([input]) => urlOf(input))).not.toContain(
+ "https://srv.test/.well-known/oauth-protected-resource",
+ );
+ });
- const provider = createMcpOAuthProvider({ server: "demo", url: "https://srv.test/mcp" });
+ it("validates refresh binding and retains the protected-resource resource indicator", async () => {
+ const fetchMock = vi.fn(async (input: unknown, init?: RequestInit): Promise<Response> => {
+ const url = urlOf(input);
+ if (url === RESOURCE)
+ return new Response("", {
+ status: 401,
+ headers: { "WWW-Authenticate": `Bearer resource_metadata="${PLANE_PRM_URL}"` },
+ });
+ if (url === PLANE_PRM_URL) return jsonResponse({ resource: RESOURCE, authorization_servers: [PLANE_ISSUER] });
+ if (url === PLANE_META_URL) return jsonResponse(PLANE_META);
+ if (url === PLANE_META.token_endpoint) {
+ const params = new URLSearchParams(String(init?.body));
+ expect(params.get("resource")).toBe(RESOURCE);
+ return jsonResponse({ access_token: "access-2", expires_in: 1800 });
+ }
+ throw new Error(`unexpected fetch: ${url}`);
+ });
+ vi.stubGlobal("fetch", fetchMock);
+ const provider = createMcpOAuthProvider({ server: "plane", url: RESOURCE });
const refreshed = await provider.refreshToken({
access: "access-1",
refresh: "old-refresh",
- expires: Date.now() - 1000,
- tokenEndpoint: META.token_endpoint,
+ expires: 0,
+ endpoint: RESOURCE,
+ resource: RESOURCE,
+ issuer: PLANE_ISSUER,
+ tokenEndpoint: PLANE_META.token_endpoint,
clientId: "client-xyz",
- endpoint: "https://old.test/mcp",
} as never);
+ expect(refreshed).toMatchObject({
+ access: "access-2",
+ refresh: "old-refresh",
+ endpoint: RESOURCE,
+ resource: RESOURCE,
+ issuer: PLANE_ISSUER,
+ });
+ await expect(
+ provider.refreshToken({ access: "a", refresh: "r", expires: 0, endpoint: "https://other.test/mcp" } as never),
+ ).rejects.toThrow("not bound");
+ await expect(
+ provider.refreshToken({
+ access: "a",
+ refresh: "r",
+ expires: 0,
+ endpoint: RESOURCE,
+ resource: RESOURCE,
+ issuer: PLANE_ISSUER,
+ tokenEndpoint: "https://attacker.example/token",
+ clientId: "client-xyz",
+ } as never),
+ ).rejects.toThrow("token endpoint does not match");
+ expect(fetchMock.mock.calls.map(([input]) => urlOf(input))).not.toContain("https://attacker.example/token");
+ });
+
+ it("keeps an origin-level resource identifier free of a synthetic trailing slash", async () => {
+ const resource = "https://root.example";
+ const prm = "https://root.example/.well-known/oauth-protected-resource";
+ const issuer = "https://root.example";
+ const asMetadata = "https://root.example/.well-known/oauth-authorization-server";
+ const metadata = {
+ issuer,
+ authorization_endpoint: "https://root.example/authorize",
+ token_endpoint: "https://root.example/token",
+ };
+ vi.stubGlobal(
+ "fetch",
+ vi.fn(async (input: unknown): Promise<Response> => {
+ const url = urlOf(input);
+ if (url === "https://root.example/") return new Response("", { status: 401 });
+ if (url === prm) return jsonResponse({ resource, authorization_servers: [issuer] });
+ if (url === asMetadata) return jsonResponse(metadata);
+ if (url === metadata.token_endpoint) return jsonResponse({ access_token: "root-access" });
+ throw new Error(`unexpected fetch: ${url}`);
+ }),
+ );
+ const { creds, authUrl } = await loginWithManualCode(
+ createMcpOAuthProvider({ server: "root", url: resource, clientId: "root-client" }),
+ );
+ expect(creds).toMatchObject({ endpoint: resource, resource, issuer });
+ expect(new URL(authUrl).searchParams.get("resource")).toBe(resource);
+ });
- expect(refreshed.access).toBe("access-2");
- expect(refreshed.refresh).toBe("old-refresh");
- expect((refreshed as { endpoint?: string }).endpoint).toBe("https://old.test/mcp");
+ it("preserves the resource query in RFC 9728 discovery and never probes root metadata", async () => {
+ const resource = "https://mcp.example/mcp?tenant=a";
+ const prm = "https://mcp.example/.well-known/oauth-protected-resource/mcp?tenant=a";
+ const issuer = "https://login.example/tenant";
+ const asMetadata = "https://login.example/.well-known/oauth-authorization-server/tenant";
+ const metadata = {
+ issuer,
+ authorization_endpoint: "https://login.example/tenant/authorize",
+ token_endpoint: "https://login.example/tenant/token",
+ };
+ const fetchMock = vi.fn(async (input: unknown): Promise<Response> => {
+ const url = urlOf(input);
+ if (url === resource) return new Response("", { status: 401 });
+ if (url === prm) return jsonResponse({ resource, authorization_servers: [issuer] });
+ if (url === asMetadata) return jsonResponse(metadata);
+ if (url === metadata.token_endpoint) return jsonResponse({ access_token: "query-access" });
+ throw new Error(`unexpected fetch: ${url}`);
+ });
+ vi.stubGlobal("fetch", fetchMock);
+ const { creds } = await loginWithManualCode(
+ createMcpOAuthProvider({ server: "query", url: resource, clientId: "query-client" }),
+ );
+ expect(creds).toMatchObject({ resource, issuer });
+ expect(fetchMock.mock.calls.map(([input]) => urlOf(input))).not.toContain(
+ "https://mcp.example/.well-known/oauth-protected-resource",
+ );
+ });
- const unbound = await provider.refreshToken({
- access: "access-1",
- refresh: "old-refresh",
- expires: Date.now() - 1000,
- tokenEndpoint: META.token_endpoint,
- clientId: "client-xyz",
- } as never);
- // An unbound credential stays unbound, so consumers keep requiring re-login.
- expect((unbound as { endpoint?: string }).endpoint).toBeUndefined();
+ it("requires re-login when refresh discovery changes from origin-only to resource-bound", async () => {
+ const fetchMock = vi.fn(async (input: unknown): Promise<Response> => {
+ const url = urlOf(input);
+ if (url === RESOURCE) return new Response("", { status: 401 });
+ if (url === PLANE_PRM_URL) return jsonResponse({ resource: RESOURCE, authorization_servers: [PLANE_ISSUER] });
+ if (url === PLANE_META_URL) return jsonResponse(PLANE_META);
+ throw new Error(`unexpected fetch: ${url}`);
+ });
+ vi.stubGlobal("fetch", fetchMock);
+ await expect(
+ createMcpOAuthProvider({ server: "plane", url: RESOURCE }).refreshToken({
+ access: "origin-access",
+ refresh: "origin-refresh",
+ expires: 0,
+ endpoint: RESOURCE,
+ tokenEndpoint: PLANE_META.token_endpoint,
+ clientId: "origin-client",
+ } as never),
+ ).rejects.toThrow("discovery mode changed");
+ expect(fetchMock.mock.calls.map(([input]) => urlOf(input))).not.toContain(PLANE_META.token_endpoint);
+ });
+
+ it("rejects a redirected token POST", async () => {
+ vi.stubGlobal(
+ "fetch",
+ vi.fn(async (input: unknown, init?: RequestInit): Promise<Response> => {
+ const missing = absentPrm(input);
+ if (missing) return missing;
+ const url = urlOf(input);
+ if (url === "https://srv.test/.well-known/oauth-authorization-server") return jsonResponse(ORIGIN_META);
+ if (url === ORIGIN_META.token_endpoint) {
+ expect(init?.redirect).toBe("error");
+ return new Response("redirect", { status: 302, headers: { Location: "https://evil.test/token" } });
+ }
+ throw new Error(`unexpected fetch: ${url}`);
+ }),
+ );
+ const provider = createMcpOAuthProvider({ server: "origin", url: ORIGIN_URL, clientId: "c" });
+ await expect(
+ provider.refreshToken({
+ access: "a",
+ refresh: "r",
+ expires: 0,
+ endpoint: ORIGIN_URL,
+ tokenEndpoint: ORIGIN_META.token_endpoint,
+ } as never),
+ ).rejects.toThrow("Token request");
+ });
+
+ it("uses a WWW-Authenticate resource_metadata pointer before derived locations", async () => {
+ const pointer = "https://metadata.example/resources/plane";
+ const fetchMock = vi.fn(async (input: unknown): Promise<Response> => {
+ const url = urlOf(input);
+ if (url === RESOURCE)
+ return new Response("", {
+ status: 401,
+ headers: { "WWW-Authenticate": `Bearer realm="mcp", resource_metadata="${pointer}"` },
+ });
+ if (url === pointer) return jsonResponse({ resource: RESOURCE, authorization_servers: [PLANE_ISSUER] });
+ if (url === PLANE_META_URL) return jsonResponse(PLANE_META);
+ if (url === PLANE_META.registration_endpoint) return jsonResponse({ client_id: "pointer-client" });
+ if (url === PLANE_META.token_endpoint) return jsonResponse({ access_token: "pointer-access" });
+ throw new Error(`unexpected fetch: ${url}`);
+ });
+ vi.stubGlobal("fetch", fetchMock);
+
+ const { creds } = await loginWithManualCode(createMcpOAuthProvider({ server: "plane", url: RESOURCE }));
+ expect(creds).toMatchObject({ access: "pointer-access", resource: RESOURCE, issuer: PLANE_ISSUER });
+ expect(fetchMock.mock.calls.map(([input]) => urlOf(input))).not.toContain(PLANE_PRM_URL);
});
- it("fails clearly when DCR is unavailable and no clientId is set", async () => {
- const noReg = { ...META, registration_endpoint: undefined };
+ it("rejects protected-resource metadata for a different resource", async () => {
vi.stubGlobal(
"fetch",
- vi.fn(async (input: unknown) => {
+ vi.fn(async (input: unknown): Promise<Response> => {
const url = urlOf(input);
- if (url.endsWith("/.well-known/oauth-authorization-server")) return jsonResponse(noReg);
+ if (url === RESOURCE) return new Response("", { status: 401 });
+ if (url === PLANE_PRM_URL)
+ return jsonResponse({ resource: "https://attacker.example/mcp", authorization_servers: [PLANE_ISSUER] });
throw new Error(`unexpected fetch: ${url}`);
}),
);
- const provider = createMcpOAuthProvider({ server: "slackish", url: "https://srv.test/mcp" });
- await expect(provider.login({ onAuth: () => {}, onPrompt: async () => "" })).rejects.toThrow(
- "dynamic client registration",
+
+ await expect(
+ createMcpOAuthProvider({ server: "plane", url: RESOURCE }).login({
+ onAuth: () => {},
+ onPrompt: async () => "",
+ }),
+ ).rejects.toThrow("resource does not exactly match");
+ });
+
+ it("falls back to the next callback port when the base port is occupied", async () => {
+ const blocker = createServer();
+ const blockerBound = await new Promise<boolean>((resolve) => {
+ blocker.once("error", () => resolve(false));
+ blocker.listen(53700, "127.0.0.1", () => resolve(true));
+ });
+ try {
+ vi.stubGlobal(
+ "fetch",
+ vi.fn(async (input: unknown): Promise<Response> => {
+ const missing = absentPrm(input);
+ if (missing) return missing;
+ const url = urlOf(input);
+ if (url === "https://srv.test/.well-known/oauth-authorization-server") return jsonResponse(ORIGIN_META);
+ if (url === ORIGIN_META.registration_endpoint) return jsonResponse({ client_id: "c" });
+ if (url === ORIGIN_META.token_endpoint) return jsonResponse({ access_token: "a", expires_in: 60 });
+ throw new Error(`unexpected fetch: ${url}`);
+ }),
+ );
+ const { authUrl } = await loginWithManualCode(createMcpOAuthProvider({ server: "demo", url: ORIGIN_URL }));
+ const redirect = new URL(authUrl).searchParams.get("redirect_uri") ?? "";
+ expect(redirect).not.toContain(":53700/");
+ expect(redirect).toContain(":5370");
+ } finally {
+ if (blockerBound) await new Promise<void>((resolve) => blocker.close(() => resolve()));
+ }
+ });
+
+ it("fails clearly when dynamic client registration is unavailable", async () => {
+ vi.stubGlobal(
+ "fetch",
+ vi.fn(async (input: unknown): Promise<Response> => {
+ const missing = absentPrm(input);
+ if (missing) return missing;
+ const url = urlOf(input);
+ if (url === "https://srv.test/.well-known/oauth-authorization-server")
+ return jsonResponse({ ...ORIGIN_META, registration_endpoint: undefined });
+ throw new Error(`unexpected fetch: ${url}`);
+ }),
);
+ await expect(
+ createMcpOAuthProvider({ server: "slackish", url: ORIGIN_URL }).login({
+ onAuth: () => {},
+ onPrompt: async () => "",
+ }),
+ ).rejects.toThrow("dynamic client registration");
});
});
-
-const REDIRECT = `http://localhost:${process.env.PI_MCP_OAUTH_CALLBACK_PORT || 53700}/callback`;