Add OAuth 2.1 server so claude.ai and ChatGPT can connect natively
Phase A needed a token pasted into a header, which Anthropic documents as an org-admin-scoped beta on claude.ai and is undocumented on ChatGPT. This makes the app its own authorization server so both connect through their normal "add a connector" flow, with a per-user consent screen. The whole thing funnels into the existing verifyMcpToken: an issued access token is an ordinary McpAccessToken row with source "oauth", so the resource server gained no OAuth awareness and Phase A's verification path is unchanged. Notes on the parts that fail quietly if got wrong: - scopes_supported is published in the protected resource metadata. When a 401 challenge carries no explicit scope Claude requests exactly what is advertised there, so omitting it silently makes every connection read-only. - Loopback redirect URIs match with the port ignored. Claude Code registers http://localhost/callback and then redirects to an ephemeral port; exact matching would reject every native client. RFC 8252 7.3 requires this. - CIMD is deliberately not advertised. Claude only selects it when the metadata carries client_id_metadata_document_supported, and supporting it would mean fetching a client-supplied URL server-side from a host that also reaches MinIO, Postgres and the gateway on the LAN. DCR costs nothing by comparison. - The consent page validates client_id and redirect_uri before it will redirect anywhere, because an unvalidated redirect_uri is an open redirect. - Authorization codes are consumed by one guarded updateMany, so a replay under concurrency cannot mint a second token. A PKCE mismatch burns the whole grant rather than just the code. - Refresh tokens rotate and keep the previous hash; presenting it revokes the grant, since that is either theft or a client that cannot be trusted to hold state. Also fixes the login page, which hardcoded callbackUrl and so dropped anyone sent to sign in for the consent screen onto /dashboard instead. Same-origin destinations only, absolute or relative - the middleware writes absolute. "/.well-known" joins PUBLIC_ROUTES. It is a prefix match, so nothing else should be served from there. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01W1Ee4Mc1X1SX8HgYa52zu7
This commit is contained in:
276
src/lib/mcp/oauth.ts
Normal file
276
src/lib/mcp/oauth.ts
Normal file
@@ -0,0 +1,276 @@
|
||||
import { createHash, randomBytes, timingSafeEqual } from "crypto"
|
||||
import { NextResponse } from "next/server"
|
||||
import { prisma } from "@/lib/prisma"
|
||||
import { generateMcpToken } from "@/lib/mcp/tokens"
|
||||
import { MCP_SCOPES, type McpScope } from "@/lib/mcp/config"
|
||||
|
||||
/**
|
||||
* OAuth 2.1 authorization server primitives.
|
||||
*
|
||||
* This app is both the authorization server and the resource server, and it
|
||||
* serves public clients only - no client secrets are stored anywhere, so there
|
||||
* is nothing here to leak. Clients authenticate at the token endpoint with PKCE,
|
||||
* which Claude always sends with S256.
|
||||
*/
|
||||
|
||||
/** Access tokens are short; the refresh token is what carries the session. */
|
||||
export const ACCESS_TOKEN_TTL_MS = 60 * 60 * 1000
|
||||
export const REFRESH_TOKEN_TTL_MS = 90 * 24 * 60 * 60 * 1000
|
||||
/** Long enough for a redirect and a token call, short enough to be useless if leaked. */
|
||||
export const AUTH_CODE_TTL_MS = 60 * 1000
|
||||
|
||||
export const OFFLINE_ACCESS = "offline_access"
|
||||
|
||||
/** Advertised in discovery metadata and offered on the consent screen. */
|
||||
export const SUPPORTED_SCOPES: string[] = [...MCP_SCOPES, OFFLINE_ACCESS]
|
||||
|
||||
export const SCOPE_DESCRIPTIONS: Record<string, string> = {
|
||||
"drinks:read": "See your drinks, ratings, wishlist and taste preferences",
|
||||
"drinks:write": "Add, edit and delete drinks, ratings and wishlist entries",
|
||||
"bar:read": "See your bar inventory and saved recipes",
|
||||
"bar:write": "Add, edit and delete bar items and recipes",
|
||||
[OFFLINE_ACCESS]: "Stay connected without asking you to sign in again",
|
||||
}
|
||||
|
||||
// ─── Opaque secrets ──────────────────────────────────────────────
|
||||
|
||||
export function sha256(value: string): string {
|
||||
return createHash("sha256").update(value).digest("hex")
|
||||
}
|
||||
|
||||
export function generateAuthCode(): { code: string; hash: string } {
|
||||
const code = randomBytes(32).toString("base64url")
|
||||
return { code, hash: sha256(code) }
|
||||
}
|
||||
|
||||
export function generateRefreshToken(): { token: string; hash: string } {
|
||||
const token = randomBytes(32).toString("base64url")
|
||||
return { token, hash: sha256(token) }
|
||||
}
|
||||
|
||||
export function generateClientId(): string {
|
||||
return `dtc_${randomBytes(16).toString("hex")}`
|
||||
}
|
||||
|
||||
// ─── Scopes ──────────────────────────────────────────────────────
|
||||
|
||||
/**
|
||||
* Narrow a requested scope string to what this server actually grants. Unknown
|
||||
* scopes are dropped rather than rejected: an unrecognised scope is not an error
|
||||
* per RFC 6749, and rejecting would break clients that request extras.
|
||||
*/
|
||||
export function parseScopes(requested: string | null | undefined): string[] {
|
||||
const asked = (requested ?? "").split(/\s+/).filter(Boolean)
|
||||
const granted = asked.filter((s) => SUPPORTED_SCOPES.includes(s))
|
||||
// Default to read-only when nothing usable was asked for.
|
||||
if (granted.filter((s) => s !== OFFLINE_ACCESS).length === 0) {
|
||||
return ["drinks:read", "bar:read", ...granted.filter((s) => s === OFFLINE_ACCESS)]
|
||||
}
|
||||
return granted
|
||||
}
|
||||
|
||||
/** The scopes actually stored on an access token: everything except the marker. */
|
||||
export function accessScopes(scopes: string[]): McpScope[] {
|
||||
return scopes.filter((s): s is McpScope =>
|
||||
(MCP_SCOPES as readonly string[]).includes(s)
|
||||
)
|
||||
}
|
||||
|
||||
export function coversScopes(granted: string[], requested: string[]): boolean {
|
||||
return requested.every((s) => granted.includes(s))
|
||||
}
|
||||
|
||||
// ─── PKCE ────────────────────────────────────────────────────────
|
||||
|
||||
/** RFC 7636 unreserved set, 43-128 characters. */
|
||||
const VERIFIER_RE = /^[A-Za-z0-9\-._~]{43,128}$/
|
||||
|
||||
export function verifyPkce(verifier: string, challenge: string): boolean {
|
||||
if (!VERIFIER_RE.test(verifier)) return false
|
||||
const computed = createHash("sha256").update(verifier).digest("base64url")
|
||||
const a = Buffer.from(computed)
|
||||
const b = Buffer.from(challenge)
|
||||
// Length check first: timingSafeEqual throws on a mismatch rather than
|
||||
// returning false.
|
||||
if (a.length !== b.length) return false
|
||||
return timingSafeEqual(a, b)
|
||||
}
|
||||
|
||||
// ─── Redirect URIs ───────────────────────────────────────────────
|
||||
|
||||
function isLoopback(url: URL): boolean {
|
||||
return (
|
||||
url.protocol === "http:" &&
|
||||
(url.hostname === "localhost" ||
|
||||
url.hostname === "127.0.0.1" ||
|
||||
url.hostname === "[::1]" ||
|
||||
url.hostname === "::1")
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* A redirect URI is acceptable at registration if it is https, or an RFC 8252
|
||||
* loopback address. Fragments are forbidden by RFC 6749.
|
||||
*/
|
||||
export function isRegisterableRedirectUri(value: string): boolean {
|
||||
let url: URL
|
||||
try {
|
||||
url = new URL(value)
|
||||
} catch {
|
||||
return false
|
||||
}
|
||||
if (url.hash) return false
|
||||
return url.protocol === "https:" || isLoopback(url)
|
||||
}
|
||||
|
||||
/**
|
||||
* Matching a redirect at authorize time.
|
||||
*
|
||||
* Exact string equality, except for loopback addresses where the port is
|
||||
* ignored. This is the single most common cause of a silently broken native
|
||||
* client: Claude Code registers http://localhost/callback and
|
||||
* http://127.0.0.1/callback, then redirects to an ephemeral port such as
|
||||
* http://localhost:51234/callback. RFC 8252 section 7.3 requires the port to be
|
||||
* ignored for the IP-literal form; the same is applied to localhost so Claude
|
||||
* Code works at all.
|
||||
*/
|
||||
export function redirectUriMatches(registered: string, requested: string): boolean {
|
||||
if (registered === requested) return true
|
||||
|
||||
let a: URL, b: URL
|
||||
try {
|
||||
a = new URL(registered)
|
||||
b = new URL(requested)
|
||||
} catch {
|
||||
return false
|
||||
}
|
||||
if (!isLoopback(a) || !isLoopback(b)) return false
|
||||
return (
|
||||
a.protocol === b.protocol &&
|
||||
a.hostname === b.hostname &&
|
||||
a.pathname === b.pathname
|
||||
)
|
||||
}
|
||||
|
||||
export function findMatchingRedirectUri(
|
||||
registered: string[],
|
||||
requested: string
|
||||
): string | null {
|
||||
return registered.find((uri) => redirectUriMatches(uri, requested)) ?? null
|
||||
}
|
||||
|
||||
// ─── Errors ──────────────────────────────────────────────────────
|
||||
|
||||
/**
|
||||
* RFC 6749 error body. `invalid_grant` in particular is load-bearing: Claude
|
||||
* keys off exactly that code to decide a refresh token is dead and it should
|
||||
* restart the whole flow. Any other code leaves the connection stuck.
|
||||
*/
|
||||
export function oauthError(
|
||||
error: string,
|
||||
description?: string,
|
||||
status = 400
|
||||
): NextResponse {
|
||||
return NextResponse.json(
|
||||
{ error, ...(description ? { error_description: description } : {}) },
|
||||
{ status, headers: { "Cache-Control": "no-store", Pragma: "no-cache" } }
|
||||
)
|
||||
}
|
||||
|
||||
// ─── Token issuance ──────────────────────────────────────────────
|
||||
|
||||
export interface IssuedTokens {
|
||||
access_token: string
|
||||
token_type: "Bearer"
|
||||
expires_in: number
|
||||
scope: string
|
||||
refresh_token?: string
|
||||
}
|
||||
|
||||
/**
|
||||
* Mints an access token against a grant.
|
||||
*
|
||||
* Refresh tokens are deliberately NOT handled here. The two call sites need
|
||||
* different behaviour - the code exchange creates the first one, a refresh
|
||||
* rotates the existing one and has to record the previous hash for replay
|
||||
* detection - and doing it in here once meant the rotation was silently
|
||||
* overwritten and the token handed back matched nothing on file.
|
||||
*
|
||||
* The access token is an ordinary McpAccessToken row with source "oauth", the
|
||||
* same shape a hand-minted one has, so verifyMcpToken needs no OAuth awareness.
|
||||
* Previously outstanding tokens on the grant are revoked, so a refresh replaces
|
||||
* rather than accumulates.
|
||||
*/
|
||||
export async function issueAccessToken(
|
||||
grantId: string,
|
||||
userId: string,
|
||||
scopes: string[],
|
||||
clientName: string
|
||||
): Promise<IssuedTokens> {
|
||||
const access = generateMcpToken()
|
||||
|
||||
await prisma.$transaction(async (tx) => {
|
||||
await tx.mcpAccessToken.updateMany({
|
||||
where: { grantId, revokedAt: null },
|
||||
data: { revokedAt: new Date() },
|
||||
})
|
||||
await tx.mcpAccessToken.create({
|
||||
data: {
|
||||
userId,
|
||||
tokenHash: access.hash,
|
||||
prefix: access.prefix,
|
||||
name: clientName,
|
||||
scopes: accessScopes(scopes),
|
||||
source: "oauth",
|
||||
grantId,
|
||||
expiresAt: new Date(Date.now() + ACCESS_TOKEN_TTL_MS),
|
||||
},
|
||||
})
|
||||
await tx.oAuthGrant.update({
|
||||
where: { id: grantId },
|
||||
data: { scopes, lastUsedAt: new Date() },
|
||||
})
|
||||
})
|
||||
|
||||
return {
|
||||
access_token: access.raw,
|
||||
token_type: "Bearer",
|
||||
expires_in: Math.floor(ACCESS_TOKEN_TTL_MS / 1000),
|
||||
scope: scopes.join(" "),
|
||||
}
|
||||
}
|
||||
|
||||
/** Stores a freshly minted refresh token on the grant, keeping the old hash for replay detection. */
|
||||
export async function storeRefreshToken(
|
||||
grantId: string,
|
||||
hash: string,
|
||||
previousHash: string | null
|
||||
): Promise<void> {
|
||||
await prisma.oAuthGrant.update({
|
||||
where: { id: grantId },
|
||||
data: {
|
||||
refreshHash: hash,
|
||||
refreshPrevHash: previousHash,
|
||||
refreshExpiresAt: new Date(Date.now() + REFRESH_TOKEN_TTL_MS),
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
/** Kills a grant and every access token it issued. */
|
||||
export async function revokeGrant(grantId: string): Promise<void> {
|
||||
const now = new Date()
|
||||
await prisma.$transaction([
|
||||
prisma.mcpAccessToken.updateMany({
|
||||
where: { grantId, revokedAt: null },
|
||||
data: { revokedAt: now },
|
||||
}),
|
||||
prisma.oAuthGrant.update({
|
||||
where: { id: grantId },
|
||||
data: {
|
||||
revokedAt: now,
|
||||
refreshHash: null,
|
||||
refreshPrevHash: null,
|
||||
},
|
||||
}),
|
||||
])
|
||||
}
|
||||
Reference in New Issue
Block a user