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:
71
src/components/oauth/consent-form.tsx
Normal file
71
src/components/oauth/consent-form.tsx
Normal file
@@ -0,0 +1,71 @@
|
||||
"use client"
|
||||
|
||||
import { useState } from "react"
|
||||
import { Button } from "@/components/ui/button"
|
||||
import { Loader2 } from "lucide-react"
|
||||
|
||||
/**
|
||||
* Approve or deny.
|
||||
*
|
||||
* The endpoint answers with JSON containing the URL to go to, and the browser
|
||||
* navigates itself, rather than the POST replying with a 302 to claude.ai. The
|
||||
* CSP sets `form-action 'self'`, and browsers have historically disagreed about
|
||||
* whether that also constrains the redirect a form submission lands on. A
|
||||
* client-side navigation sidesteps the question and gives somewhere to show an
|
||||
* error if the request fails.
|
||||
*/
|
||||
export function ConsentForm({ search }: { search: string }) {
|
||||
const [busy, setBusy] = useState<"allow" | "deny" | null>(null)
|
||||
const [error, setError] = useState("")
|
||||
|
||||
async function decide(decision: "allow" | "deny") {
|
||||
setBusy(decision)
|
||||
setError("")
|
||||
try {
|
||||
const res = await fetch("/api/oauth/authorize", {
|
||||
method: "POST",
|
||||
headers: { "content-type": "application/json" },
|
||||
body: JSON.stringify({ decision, search }),
|
||||
})
|
||||
const body = await res.json()
|
||||
if (!res.ok || !body.redirectTo) {
|
||||
setError(body.error_description ?? body.error ?? "Something went wrong.")
|
||||
setBusy(null)
|
||||
return
|
||||
}
|
||||
window.location.assign(body.redirectTo)
|
||||
} catch {
|
||||
setError("Could not reach the server. Please try again.")
|
||||
setBusy(null)
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="space-y-3">
|
||||
{error && (
|
||||
<div className="rounded-md bg-destructive/10 p-3 text-sm text-destructive">
|
||||
{error}
|
||||
</div>
|
||||
)}
|
||||
<div className="flex gap-3">
|
||||
<Button
|
||||
variant="outline"
|
||||
className="flex-1"
|
||||
disabled={busy !== null}
|
||||
onClick={() => decide("deny")}
|
||||
>
|
||||
{busy === "deny" && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}
|
||||
Deny
|
||||
</Button>
|
||||
<Button
|
||||
className="flex-1"
|
||||
disabled={busy !== null}
|
||||
onClick={() => decide("allow")}
|
||||
>
|
||||
{busy === "allow" && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}
|
||||
Allow
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -14,6 +14,7 @@ import { Input } from "@/components/ui/input"
|
||||
import { Label } from "@/components/ui/label"
|
||||
import { Badge } from "@/components/ui/badge"
|
||||
import { Select, SelectOption } from "@/components/ui/select"
|
||||
import { Separator } from "@/components/ui/separator"
|
||||
import { Check, Copy, Loader2, Plug, Trash2 } from "lucide-react"
|
||||
|
||||
interface McpToken {
|
||||
@@ -35,6 +36,15 @@ interface CreatedToken extends McpToken {
|
||||
secret: string
|
||||
}
|
||||
|
||||
interface McpGrant {
|
||||
id: string
|
||||
clientName: string
|
||||
clientUri: string | null
|
||||
scopes: string[]
|
||||
createdAt: string
|
||||
lastUsedAt: string | null
|
||||
}
|
||||
|
||||
const ACCESS_OPTIONS = [
|
||||
{ value: "read", label: "Read only" },
|
||||
{ value: "read-write", label: "Read and write" },
|
||||
@@ -103,6 +113,30 @@ export function McpTokensCard() {
|
||||
},
|
||||
})
|
||||
|
||||
// Apps connected through OAuth rather than a pasted token: claude.ai and
|
||||
// ChatGPT arrive this way.
|
||||
const { data: grantData } = useQuery<{ grants: McpGrant[] }>({
|
||||
queryKey: ["mcp-grants"],
|
||||
queryFn: async () => {
|
||||
const res = await fetch("/api/settings/mcp-grants")
|
||||
if (!res.ok) throw new Error("Failed to load connected apps")
|
||||
return res.json()
|
||||
},
|
||||
})
|
||||
|
||||
const disconnect = useMutation({
|
||||
mutationFn: async (id: string) => {
|
||||
const res = await fetch(`/api/settings/mcp-grants/${id}`, {
|
||||
method: "DELETE",
|
||||
})
|
||||
if (!res.ok) throw new Error("Failed to disconnect")
|
||||
},
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: ["mcp-grants"] })
|
||||
queryClient.invalidateQueries({ queryKey: ["mcp-tokens"] })
|
||||
},
|
||||
})
|
||||
|
||||
const serverUrl = data?.serverUrl ?? ""
|
||||
|
||||
async function copy(key: string, value: string) {
|
||||
@@ -188,6 +222,52 @@ export function McpTokensCard() {
|
||||
</div>
|
||||
)}
|
||||
|
||||
{!!grantData?.grants.length && (
|
||||
<div className="space-y-2">
|
||||
<p className="text-sm font-medium">Connected apps</p>
|
||||
{grantData.grants.map((grant) => (
|
||||
<div
|
||||
key={grant.id}
|
||||
className="flex items-center justify-between gap-3 rounded-lg border p-3"
|
||||
>
|
||||
<div className="min-w-0">
|
||||
<div className="flex flex-wrap items-center gap-2">
|
||||
<span className="font-medium">{grant.clientName}</span>
|
||||
<Badge variant="secondary">
|
||||
{grant.scopes.some((s) => s.endsWith(":write"))
|
||||
? "read/write"
|
||||
: "read only"}
|
||||
</Badge>
|
||||
</div>
|
||||
<p className="mt-1 text-xs text-muted-foreground">
|
||||
Connected {new Date(grant.createdAt).toLocaleDateString()}
|
||||
{grant.lastUsedAt
|
||||
? ` · last used ${new Date(grant.lastUsedAt).toLocaleDateString()}`
|
||||
: ""}
|
||||
</p>
|
||||
</div>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={() => disconnect.mutate(grant.id)}
|
||||
disabled={disconnect.isPending}
|
||||
>
|
||||
<Trash2 className="mr-1 h-4 w-4" />
|
||||
Disconnect
|
||||
</Button>
|
||||
</div>
|
||||
))}
|
||||
<Separator className="!mt-4" />
|
||||
</div>
|
||||
)}
|
||||
|
||||
<p className="text-sm font-medium">
|
||||
Access tokens
|
||||
<span className="ml-2 font-normal text-muted-foreground">
|
||||
for clients you configure by hand, such as Claude Code
|
||||
</span>
|
||||
</p>
|
||||
|
||||
<div className="grid gap-3 sm:grid-cols-3">
|
||||
<div className="space-y-1.5">
|
||||
<Label htmlFor="mcp-name">Name</Label>
|
||||
|
||||
Reference in New Issue
Block a user