feat(mcp): add OAuth 2.1 for claude.ai MCP connector (#2829)

* feat(mcp): add OAuth 2.1 authentication for claude.ai MCP connector

Enable OAuth 2.1 (RFC 8414 + RFC 7591) for the MCP endpoint using
better-auth's MCP plugin. This allows claude.ai and other MCP clients
to authenticate via Dynamic Client Registration and Authorization Code
flow with PKCE, using the existing login page.

- Add `mcp()` plugin to better-auth config with login page redirect
- Add `.well-known/oauth-authorization-server` discovery endpoint
- Add `.well-known/oauth-protected-resource` metadata endpoint
- Update MCP handler to accept Bearer tokens via `getMcpSession`
- Retain `x-api-key` fallback for backward compatibility
- Return proper HTTP 401 + WWW-Authenticate header for unauthed requests
- Add `oauthApplication`, `oauthAccessToken`, `oauthConsent` tables

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* fix(mcp): use typed AuthError and suppress noisy verifyApiKey throws

- Replace string-matching error detection with instanceof AuthError
- Wrap verifyApiKey in try-catch to avoid logging malformed key errors
- Move console.error below auth check so 401s don't pollute logs

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* feat(mcp): add database migration for OAuth tables

Creates oauth_application, oauth_access_token, and oauth_consent tables
required for MCP OAuth 2.1 Dynamic Client Registration flow.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* fix(mcp): resolve OAuth Bearer token auth for oRPC tool calls

The oRPC context only checked session cookies and API keys, causing
MCP tool calls from OAuth clients (claude.ai) to fail with Unauthorized
even though the MCP endpoint itself authenticated successfully.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* fix(mcp): look up user by userId from OAuth access token

getMcpSession returns OAuthAccessToken (with userId), not a session
object with a user property. Must query the user table by userId.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* refactor(mcp): migrate from deprecated mcp() plugin to @better-auth/oauth-provider

The better-auth MCP plugin is marked for deprecation in favor of the
OAuth Provider plugin. This refactors the entire OAuth 2.1 flow to use
@better-auth/oauth-provider with JWT-based token verification, replacing
the opaque token lookup via getMcpSession().

Key changes:
- Replace mcp() with jwt() + oauthProvider() in auth config
- Replace getMcpSession() with verifyAccessToken() (JWT/JWKS)
- Replace oauthApplication table with oauthClient (RFC 7591 compliant)
- Add oauthRefreshToken table and jwks table for JWT signing keys
- Extract shared authBaseUrl and verifyOAuthToken helper
- Hoist McpServer to module scope (avoid per-request reconstruction)
- Update .well-known discovery endpoints for OAuth Provider

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* fix(mcp): resolve OAuth 2.1 flow for claude.ai MCP connector

Multiple fixes required to make the full MCP OAuth flow work with
claude.ai's implementation:

- Add RFC 8414 discovery route at /.well-known/oauth-authorization-server/api/auth
  (claude.ai appends the issuer path per spec)
- Add /auth/oauth server route to handle login/consent flow
  (generates auth codes directly, bypassing h3 cookie issues)
- Default token_endpoint_auth_method to "none" via onRequest plugin hook
  (claude.ai omits this field, causing confidential client rejection)
- Strip prompt=consent from authorize requests via onRequest hook
  (better-auth checks prompt before skipConsent, causing redirect loops)
- Add validAudiences for MCP resource URL
  (JWT aud claim contains the MCP URL, not the base URL)
- Disable CSRF check for cross-origin OAuth flows
- Log token endpoint errors for debugging
- Set skipConsent on OAuth clients via /auth/oauth route

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* fix(mcp): harden OAuth security and enforce lock on delete

- Scope CSRF bypass to OAuth2 paths only instead of disabling globally
- Validate redirect_uri against registered client URIs (prevents code interception)
- Use pathname matching instead of fragile url.includes() for route guards
- Replace biased modulo code generation with crypto.randomBytes
- Enforce resume lock check on delete (previously silently ignored)
- Remove debug console.error logging of OAuth token response bodies
- Use Response.json() consistently for MCP 401 response

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* Update dependencies, refine ignore patterns, and enhance documentation

- Updated various dependencies in package.json and pnpm-lock.yaml for improved stability and features.
- Adjusted ignore patterns in knip.json to include specific component directories.
- Enhanced documentation for the MCP server, clarifying authentication methods and configuration options.
- Made minor adjustments to VSCode settings for better code organization.

* fix(mcp): resolve OAuth client registration and stale token handling

Claude.ai sends token_endpoint_auth_method: "client_secret_post" without
a client_secret during Dynamic Client Registration, causing Better Auth to
reject it as an unauthenticated confidential client. Force to "none" for
unauthenticated registrations.

Also catch JWKS verification errors (e.g. key rotation after redeployment)
so stale Bearer tokens return 401 instead of 200 with an error body,
allowing clients to re-initiate the OAuth flow.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* reiterate on tests

---------

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
Co-authored-by: Amruth Pillai <im.amruth@gmail.com>
This commit is contained in:
Christian Pojoni
2026-03-24 11:03:56 +01:00
committed by GitHub
parent e3274d7c95
commit b4aaf9712f
103 changed files with 5221 additions and 3174 deletions
-3
View File
@@ -21,9 +21,6 @@ type LoaderData = Omit<RouterOutput["resume"]["getBySlug"], "data"> & { data: Re
export const Route = createFileRoute("/$username/$slug")({
component: RouteComponent,
loader: async ({ context, params: { username, slug } }) => {
// Ignore .well-known requests
if (username === ".well-known") throw notFound();
const resume = await context.queryClient.ensureQueryData(
orpc.resume.getBySlug.queryOptions({ input: { username, slug } }),
);
@@ -0,0 +1,14 @@
import { oauthProviderAuthServerMetadata } from "@better-auth/oauth-provider";
import { createFileRoute } from "@tanstack/react-router";
import { auth } from "@/integrations/auth/config";
const handler = oauthProviderAuthServerMetadata(auth);
export const Route = createFileRoute("/.well-known/oauth-authorization-server/$")({
server: {
handlers: {
GET: ({ request }) => handler(request),
},
},
});
@@ -0,0 +1,14 @@
import { oauthProviderAuthServerMetadata } from "@better-auth/oauth-provider";
import { createFileRoute } from "@tanstack/react-router";
import { auth } from "@/integrations/auth/config";
const handler = oauthProviderAuthServerMetadata(auth);
export const Route = createFileRoute("/.well-known/oauth-authorization-server")({
server: {
handlers: {
GET: ({ request }) => handler(request),
},
},
});
@@ -0,0 +1,25 @@
import { createFileRoute } from "@tanstack/react-router";
import { authClient } from "@/integrations/auth/client";
import { authBaseUrl } from "@/integrations/auth/config";
export const Route = createFileRoute("/.well-known/oauth-protected-resource/$")({
server: {
handlers: {
GET: async () => {
const metadata = await authClient.getProtectedResourceMetadata({
resource: authBaseUrl,
bearer_methods_supported: ["header"],
authorization_servers: [authBaseUrl, `${authBaseUrl}/api/auth`],
});
return Response.json(metadata, {
headers: {
"Content-Type": "application/json",
"Cache-Control": "public, max-age=15, stale-while-revalidate=15, stale-if-error=86400",
},
});
},
},
},
});
@@ -0,0 +1,25 @@
import { createFileRoute } from "@tanstack/react-router";
import { authClient } from "@/integrations/auth/client";
import { authBaseUrl } from "@/integrations/auth/config";
export const Route = createFileRoute("/.well-known/oauth-protected-resource")({
server: {
handlers: {
GET: async () => {
const metadata = await authClient.getProtectedResourceMetadata({
resource: authBaseUrl,
bearer_methods_supported: ["header"],
authorization_servers: [authBaseUrl, `${authBaseUrl}/api/auth`],
});
return Response.json(metadata, {
headers: {
"Content-Type": "application/json",
"Cache-Control": "public, max-age=15, stale-while-revalidate=15, stale-if-error=86400",
},
});
},
},
},
});
@@ -0,0 +1,14 @@
import { oauthProviderOpenIdConfigMetadata } from "@better-auth/oauth-provider";
import { createFileRoute } from "@tanstack/react-router";
import { auth } from "@/integrations/auth/config";
const handler = oauthProviderOpenIdConfigMetadata(auth);
export const Route = createFileRoute("/.well-known/openid-configuration")({
server: {
handlers: {
GET: ({ request }) => handler(request),
},
},
});
+76 -1
View File
@@ -2,14 +2,89 @@ import { createFileRoute } from "@tanstack/react-router";
import { auth } from "@/integrations/auth/config";
function sanitizeOAuthAuthorizeRequest(request: Request): Request {
if (request.method !== "GET") return request;
const url = new URL(request.url);
if (!url.pathname.endsWith("/oauth2/authorize")) return request;
const sanitizeValue = (value: string) =>
value
.replace(/[\r\n\t]+/g, " ")
.replace(/\s+/g, " ")
.trim();
const sanitizeParam = (key: string) => {
const value = url.searchParams.get(key);
if (!value) return;
url.searchParams.set(key, sanitizeValue(value));
};
sanitizeParam("prompt");
sanitizeParam("redirect_uri");
sanitizeParam("client_id");
sanitizeParam("code_challenge");
sanitizeParam("code_challenge_method");
sanitizeParam("response_type");
sanitizeParam("scope");
sanitizeParam("state");
sanitizeParam("resource");
const redirectUri = url.searchParams.get("redirect_uri");
if (redirectUri && !URL.canParse(redirectUri)) {
try {
const decodedRedirectUri = decodeURIComponent(redirectUri);
if (URL.canParse(decodedRedirectUri)) {
url.searchParams.set("redirect_uri", decodedRedirectUri);
}
} catch {
// Ignore malformed encoded values and let Better Auth validation handle them.
}
}
if (url.toString() === request.url) return request;
return new Request(url, request);
}
async function defaultPublicClientRegistration(request: Request): Promise<Request> {
if (request.method !== "POST") return request;
const url = new URL(request.url);
if (!url.pathname.endsWith("/oauth2/register")) return request;
const cloned = request.clone();
let body: Record<string, unknown>;
try {
body = await cloned.json();
} catch {
return request;
}
// Claude.ai sends token_endpoint_auth_method: "client_secret_post" without a
// client_secret, causing Better Auth to require authentication for what is
// effectively a public client. Force to "none" for unauthenticated registrations.
if (!request.headers.get("authorization")) {
body.token_endpoint_auth_method = "none";
}
return new Request(url, {
method: request.method,
headers: request.headers,
body: JSON.stringify(body),
});
}
async function handler({ request }: { request: Request }) {
const sanitizedRequest = sanitizeOAuthAuthorizeRequest(request);
const finalRequest = await defaultPublicClientRegistration(sanitizedRequest);
if (request.method === "GET" && request.url.endsWith("/spec.json")) {
const spec = await auth.api.generateOpenAPISchema();
return Response.json(spec);
}
return auth.handler(request);
return auth.handler(finalRequest);
}
export const Route = createFileRoute("/api/auth/$")({
+103
View File
@@ -0,0 +1,103 @@
import { createFileRoute } from "@tanstack/react-router";
import { eq } from "drizzle-orm";
import crypto from "node:crypto";
import { auth, authBaseUrl } from "@/integrations/auth/config";
import { db } from "@/integrations/drizzle/client";
import { oauthClient, verification } from "@/integrations/drizzle/schema";
import { generateId } from "@/utils/string";
function generateCode() {
return crypto.randomBytes(32).toString("base64url");
}
function hashCode(code: string) {
return crypto.createHash("sha256").update(code).digest("base64url");
}
export const Route = createFileRoute("/auth/oauth")({
server: {
handlers: {
GET: async ({ request }) => {
const session = await auth.api.getSession({ headers: request.headers });
const url = new URL(request.url);
if (session?.user) {
const clientId = url.searchParams.get("client_id");
const redirectUri = url.searchParams.get("redirect_uri");
const state = url.searchParams.get("state");
const scope = url.searchParams.get("scope");
const codeChallenge = url.searchParams.get("code_challenge");
const codeChallengeMethod = url.searchParams.get("code_challenge_method");
if (!clientId || !redirectUri) {
return Response.json({ error: "missing client_id or redirect_uri" }, { status: 400 });
}
const [client] = await db.select().from(oauthClient).where(eq(oauthClient.clientId, clientId)).limit(1);
if (!client) {
return Response.json({ error: "invalid client" }, { status: 400 });
}
if (!client.redirectUris.includes(redirectUri)) {
return Response.json({ error: "invalid redirect_uri" }, { status: 400 });
}
const code = generateCode();
const hashedCode = hashCode(code);
const now = new Date();
const expiresAt = new Date(now.getTime() + 600_000); // 10 min
await db.insert(verification).values({
id: generateId(),
identifier: hashedCode,
value: JSON.stringify({
type: "authorization_code",
query: {
response_type: "code",
client_id: clientId,
redirect_uri: redirectUri,
scope,
state,
code_challenge: codeChallenge,
code_challenge_method: codeChallengeMethod,
},
userId: session.user.id,
sessionId: session.session.id,
authTime: new Date(session.session.createdAt).getTime(),
}),
expiresAt,
createdAt: now,
updatedAt: now,
});
const callbackUrl = new URL(redirectUri);
callbackUrl.searchParams.set("code", code);
if (state) callbackUrl.searchParams.set("state", state);
callbackUrl.searchParams.set("iss", `${authBaseUrl}/api/auth`);
return new Response(null, {
status: 302,
headers: { Location: callbackUrl.toString() },
});
}
// Not logged in — redirect to the real login page with a callback
const loginUrl = new URL("/auth/login", url.origin);
const oauthParams = new URLSearchParams();
for (const [key, value] of url.searchParams) {
if (!["exp", "sig"].includes(key)) {
oauthParams.set(key, value);
}
}
loginUrl.searchParams.set("callbackURL", `/auth/oauth?${oauthParams.toString()}`);
return new Response(null, {
status: 302,
headers: { Location: loginUrl.toString() },
});
},
},
},
});
@@ -21,7 +21,6 @@ import { useControls } from "react-zoom-pan-pinch";
import { toast } from "sonner";
import { useCopyToClipboard } from "usehooks-ts";
import { AIChat } from "@/components/ai/chat";
import { useTemporalStore } from "@/components/resume/store/resume";
import { Button } from "@/components/ui/button";
import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";
@@ -138,7 +137,6 @@ export function BuilderDock() {
<DockIcon icon={MagnifyingGlassMinusIcon} title={t`Zoom out`} onClick={() => zoomOut(0.1)} />
<DockIcon icon={CubeFocusIcon} title={t`Center view`} onClick={() => centerView()} />
<div className="mx-1 h-8 w-px bg-border" />
<AIChat />
<DockIcon icon={LinkSimpleIcon} title={t`Copy URL`} onClick={() => onCopyUrl()} />
<DockIcon icon={FileJsIcon} title={t`Download JSON`} onClick={() => onDownloadJSON()} />
<DockIcon icon={FileDocIcon} title={t`Download DOCX`} onClick={() => onDownloadDOCX()} />
@@ -1,4 +1,4 @@
import { describe, expect, it } from "vitest";
import { describe, expect, it } from "vite-plus/test";
import {
buildPostFilters,
+49 -2
View File
@@ -2,6 +2,8 @@ import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
import { WebStandardStreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/webStandardStreamableHttp.js";
import { createFileRoute } from "@tanstack/react-router";
import { auth, authBaseUrl, verifyOAuthToken } from "@/integrations/auth/config";
import { registerPrompts } from "./-helpers/prompts";
import { registerResources } from "./-helpers/resources";
import { registerTools } from "./-helpers/tools";
@@ -35,13 +37,46 @@ function createMcpServer() {
return server;
}
class AuthError extends Error {
constructor() {
super("Unauthorized");
}
}
async function authenticateRequest(request: Request): Promise<void> {
// Try OAuth Bearer token first (for claude.ai and other MCP OAuth clients)
const authHeader = request.headers.get("authorization");
if (authHeader?.startsWith("Bearer ")) {
try {
const payload = await verifyOAuthToken(authHeader.slice(7));
if (payload?.sub) return;
} catch {
// Invalid or expired token (e.g. JWKS key mismatch) — fall through to AuthError
}
}
// Fall back to API key authentication
const apiKey = request.headers.get("x-api-key");
if (apiKey) {
try {
const result = await auth.api.verifyApiKey({ body: { key: apiKey } });
if (result.valid) return;
} catch {
// Invalid or malformed key — fall through to AuthError
}
}
throw new AuthError();
}
export const Route = createFileRoute("/mcp/")({
server: {
handlers: {
ANY: async ({ request }) => {
try {
const apiKey = request.headers.get("x-api-key");
if (!apiKey) throw new Error("Unauthorized");
await authenticateRequest(request);
const server = createMcpServer();
const transport = new WebStandardStreamableHTTPServerTransport({
@@ -52,6 +87,18 @@ export const Route = createFileRoute("/mcp/")({
return await transport.handleRequest(request);
} catch (error) {
if (error instanceof AuthError) {
return Response.json(
{ id: null, jsonrpc: "2.0", error: { code: -32603, message: "Unauthorized" } },
{
status: 401,
headers: {
"WWW-Authenticate": `Bearer resource_metadata="${authBaseUrl}/.well-known/oauth-protected-resource"`,
},
},
);
}
console.error("[MCP]", error);
return Response.json({