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:
JP
2026-08-09 05:33:48 +00:00
parent 4fd339dabc
commit e77f605c9c
16 changed files with 1505 additions and 2 deletions

View File

@@ -0,0 +1,142 @@
import { NextResponse } from "next/server"
import { z } from "zod"
import { prisma } from "@/lib/prisma"
import { rateLimit } from "@/lib/rate-limit"
import {
generateClientId,
isRegisterableRedirectUri,
oauthError,
} from "@/lib/mcp/oauth"
/**
* RFC 7591 dynamic client registration.
*
* Unauthenticated by specification, which makes it the one endpoint on this
* deployment that a stranger can create rows through. Hence the rate limit, the
* global cap, and the pruning of registrations that never went on to be used.
*/
export const runtime = "nodejs"
export const dynamic = "force-dynamic"
/** Beyond this many registrations in a day, something is wrong. */
const DAILY_REGISTRATION_CAP = 500
const PRUNE_AFTER_MS = 7 * 24 * 60 * 60 * 1000
const registerSchema = z.object({
client_name: z.string().min(1).max(200).optional(),
redirect_uris: z.array(z.string().min(1)).min(1).max(10),
grant_types: z.array(z.string()).optional(),
response_types: z.array(z.string()).optional(),
token_endpoint_auth_method: z.string().optional(),
scope: z.string().max(500).optional(),
client_uri: z.string().max(2048).optional(),
logo_uri: z.string().max(2048).optional(),
software_id: z.string().max(200).optional(),
})
export async function POST(request: Request) {
const forwarded = request.headers.get("x-forwarded-for")
const hops = forwarded?.split(",").map((h) => h.trim()).filter(Boolean) ?? []
// Last hop, not first: everything before it is client-supplied and can be
// forged for a fresh bucket. Same reasoning as the register route.
const ip = hops.length > 0 ? hops[hops.length - 1] : "unknown"
const rl = rateLimit(`dcr:${ip}`, 5, 60 * 60 * 1000)
if (!rl.success) {
return oauthError(
"temporarily_unavailable",
"Too many registration attempts.",
429
)
}
const body = await request.json().catch(() => null)
if (!body) return oauthError("invalid_client_metadata", "Body must be JSON.")
const parsed = registerSchema.safeParse(body)
if (!parsed.success) {
return oauthError("invalid_client_metadata", parsed.error.issues[0]?.message)
}
const data = parsed.data
// Public clients only. Accepting a confidential client would mean storing a
// secret this server has no need for and no way to protect better than the
// PKCE it already requires.
const authMethod = data.token_endpoint_auth_method ?? "none"
if (authMethod !== "none") {
return oauthError(
"invalid_client_metadata",
"This server issues public clients only; token_endpoint_auth_method must be \"none\"."
)
}
const bad = data.redirect_uris.filter((u) => !isRegisterableRedirectUri(u))
if (bad.length) {
return oauthError(
"invalid_redirect_uri",
`Redirect URIs must be https or a loopback address, with no fragment: ${bad.join(", ")}`
)
}
const since = new Date(Date.now() - 24 * 60 * 60 * 1000)
const recent = await prisma.oAuthClient.count({
where: { createdAt: { gte: since } },
})
if (recent >= DAILY_REGISTRATION_CAP) {
return oauthError(
"temporarily_unavailable",
"Registration is temporarily closed.",
503
)
}
const clientId = generateClientId()
const client = await prisma.oAuthClient.create({
data: {
clientId,
clientName: data.client_name ?? "Unnamed client",
redirectUris: data.redirect_uris,
grantTypes: data.grant_types ?? ["authorization_code", "refresh_token"],
responseTypes: data.response_types ?? ["code"],
tokenEndpointAuthMethod: "none",
scope: data.scope ?? null,
clientUri: data.client_uri ?? null,
logoUri: data.logo_uri ?? null,
softwareId: data.software_id ?? null,
},
})
pruneUnusedClients()
return NextResponse.json(
{
client_id: client.clientId,
client_id_issued_at: Math.floor(client.createdAt.getTime() / 1000),
client_name: client.clientName,
redirect_uris: client.redirectUris,
grant_types: client.grantTypes,
response_types: client.responseTypes,
token_endpoint_auth_method: "none",
...(client.scope ? { scope: client.scope } : {}),
},
{ status: 201, headers: { "Cache-Control": "no-store" } }
)
}
/**
* Registrations that never led to a grant are abandoned handshakes. Cleared
* opportunistically rather than on a schedule, because there is no scheduler.
*/
function pruneUnusedClients(): void {
prisma.oAuthClient
.deleteMany({
where: {
createdAt: { lt: new Date(Date.now() - PRUNE_AFTER_MS) },
grants: { none: {} },
},
})
.then(({ count }) => {
if (count > 0) console.log(`[oauth] pruned ${count} unused client(s)`)
})
.catch((error) => console.warn("[oauth] client prune failed:", error))
}