feat(mcp): add OAuth 2.1 support (#505)

* feat(mcp): add OAuth 2.1 support with dynamic client registration

* feat(api): alias bare oauth-authorization-server discovery endpoint

* fix(auth): preserve user session on OAuth sign-in redirect to consent
This commit is contained in:
Yiling-J
2026-10-29 15:39:37 +08:00
committed by GitHub
parent 96539207d0
commit baf30730af
39 changed files with 19604 additions and 44 deletions
+151
View File
@@ -0,0 +1,151 @@
import { AuthLayout } from '@/ui/components/auth-layout'
import { Button } from '@/ui/components/ui/button'
import { authClient } from '@/ui/lib/auth-client'
import { useAuthStore } from '@/ui/stores/auth'
import { m } from '@/ui/paraglide/messages.js'
import { createLazyFileRoute } from '@tanstack/react-router'
import { Check, Key, Loader2, ShieldCheck, User, X } from 'lucide-react'
import { useState } from 'react'
export const Route = createLazyFileRoute('/consent')({
component: ConsentPage,
})
function ConsentPage() {
const search = Route.useSearch()
const rawUser = useAuthStore((state) => state.user)
const user =
rawUser && typeof rawUser === 'object' ? (rawUser as { email?: string; name?: string }) : null
const [loading, setLoading] = useState<'accept' | 'deny' | null>(null)
const [error, setError] = useState<string | null>(null)
const clientId = search.client_id || 'MCP Client'
const scopes = search.scope ? search.scope.split(' ') : ['mcp']
const handleConsent = async (accept: boolean) => {
setLoading(accept ? 'accept' : 'deny')
setError(null)
try {
const res = await authClient.oauth2.consent({
accept,
})
if (res.data?.url) {
window.location.href = res.data.url
} else if (res.error) {
setError(res.error.message || m.consent_failed())
setLoading(null)
}
} catch (err) {
setError(err instanceof Error ? err.message : m.consent_failed())
setLoading(null)
}
}
return (
<AuthLayout>
<div className="mb-6">
<div className="flex items-center gap-2 mb-2 text-primary">
<ShieldCheck className="w-6 h-6" />
<h1 className="text-2xl font-bold tracking-tight text-foreground">
{m.authorize_application()}
</h1>
</div>
<p className="text-muted-foreground text-sm">{m.authorize_application_subtitle()}</p>
</div>
{error && (
<div className="mb-6 p-3 bg-destructive/10 border border-destructive/20 text-destructive rounded-xl text-sm text-center font-medium">
{error}
</div>
)}
<div className="space-y-4 rounded-xl border border-border bg-card p-4 mb-6 shadow-xs">
<div className="flex items-center justify-between text-sm pb-3 border-b border-border">
<span className="text-muted-foreground flex items-center gap-1.5">
<Key className="w-4 h-4" />
{m.application_client_id()}
</span>
<span className="font-mono font-medium text-foreground text-xs bg-muted px-2 py-0.5 rounded">
{clientId}
</span>
</div>
{user && (
<div className="flex items-center justify-between text-sm pb-3 border-b border-border">
<span className="text-muted-foreground flex items-center gap-1.5">
<User className="w-4 h-4" />
{m.logged_in_as()}
</span>
<span className="font-medium text-foreground text-xs">{user.email || user.name}</span>
</div>
)}
<div className="pt-1">
<span className="text-xs font-semibold uppercase tracking-wider text-muted-foreground block mb-2">
{m.requested_permissions()}
</span>
<div className="space-y-2">
<div className="flex items-start gap-2 text-sm bg-muted/50 p-2.5 rounded-lg border border-border/50">
<Check className="w-4 h-4 text-emerald-500 mt-0.5 shrink-0" />
<div>
<p className="font-medium text-foreground text-xs">{m.mcp_access_scope_desc()}</p>
<div className="flex flex-wrap gap-1 mt-1">
{scopes.map((s) => (
<span
key={s}
className="font-mono text-[10px] text-muted-foreground bg-background px-1.5 py-0.5 rounded border border-border"
>
{s}
</span>
))}
</div>
</div>
</div>
</div>
</div>
</div>
<div className="flex gap-3">
<Button
type="button"
variant="outline"
className="flex-1 h-11 rounded-xl cursor-pointer"
disabled={loading !== null}
onClick={() => handleConsent(false)}
>
{loading === 'deny' ? (
<>
<Loader2 className="w-4 h-4 animate-spin mr-2" />
{m.denying()}
</>
) : (
<>
<X className="w-4 h-4 mr-1.5" />
{m.deny()}
</>
)}
</Button>
<Button
type="button"
className="flex-1 h-11 bg-primary text-primary-foreground font-semibold rounded-xl shadow-xs cursor-pointer"
disabled={loading !== null}
onClick={() => handleConsent(true)}
>
{loading === 'accept' ? (
<>
<Loader2 className="w-4 h-4 animate-spin mr-2" />
{m.authorizing()}
</>
) : (
<>
<Check className="w-4 h-4 mr-1.5" />
{m.authorize()}
</>
)}
</Button>
</div>
</AuthLayout>
)
}
+76
View File
@@ -0,0 +1,76 @@
import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest'
import * as authClientModule from '@/ui/lib/auth-client'
import { useAuthStore } from '@/ui/stores/auth'
import { Route } from './consent'
describe('Consent Route beforeLoad guard', () => {
beforeEach(() => {
useAuthStore.getState().clearAuth()
vi.restoreAllMocks()
})
afterEach(() => {
vi.restoreAllMocks()
})
it('redirects to /login when user is not authenticated in store or server session', async () => {
vi.spyOn(authClientModule, 'getAuthSession').mockResolvedValue({
data: null,
error: null,
} as unknown as Awaited<ReturnType<typeof authClientModule.getAuthSession>>)
const beforeLoad = Route.options.beforeLoad
expect(beforeLoad).toBeDefined()
await expect(
beforeLoad!({
search: {
// eslint-disable-next-line @typescript-eslint/naming-convention
client_id: 'client-1',
},
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- TanStack router internal BeforeLoadContextOptions in test
} as any),
).rejects.toThrow()
})
it('populates user in auth store and allows access when server session exists', async () => {
vi.spyOn(authClientModule, 'getAuthSession').mockResolvedValue({
data: {
user: { id: 'user-oauth', email: 'oauth@example.com' },
session: { id: 'session-1' },
},
error: null,
} as unknown as Awaited<ReturnType<typeof authClientModule.getAuthSession>>)
const beforeLoad = Route.options.beforeLoad
expect(beforeLoad).toBeDefined()
await expect(
beforeLoad!({
search: {
// eslint-disable-next-line @typescript-eslint/naming-convention
client_id: 'client-1',
},
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- TanStack router internal BeforeLoadContextOptions in test
} as any),
).resolves.not.toThrow()
expect(useAuthStore.getState().user).toEqual({ id: 'user-oauth', email: 'oauth@example.com' })
})
it('allows access when user is already authenticated in store without calling getSession', async () => {
useAuthStore.getState().setUser({ id: 'user-1', email: 'test@example.com' })
const getSessionSpy = vi.spyOn(authClientModule, 'getAuthSession')
const beforeLoad = Route.options.beforeLoad
expect(beforeLoad).toBeDefined()
await expect(
beforeLoad!({
search: {
// eslint-disable-next-line @typescript-eslint/naming-convention
client_id: 'client-1',
},
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- TanStack router internal BeforeLoadContextOptions in test
} as any),
).resolves.not.toThrow()
expect(getSessionSpy).not.toHaveBeenCalled()
})
})
+38
View File
@@ -0,0 +1,38 @@
import { createFileRoute, redirect } from '@tanstack/react-router'
import { getAuthSession } from '@/ui/lib/auth-client'
import { useAuthStore } from '@/ui/stores/auth'
import { z } from 'zod'
const searchSchema = z
.object({
// eslint-disable-next-line @typescript-eslint/naming-convention
client_id: z.string().optional().catch(''),
scope: z.string().optional().catch(''),
// eslint-disable-next-line @typescript-eslint/naming-convention
redirect_uri: z.string().optional().catch(''),
})
.passthrough()
export const Route = createFileRoute('/consent')({
validateSearch: (search) => searchSchema.parse(search),
beforeLoad: async () => {
let currentUser = useAuthStore.getState().user
if (!currentUser) {
try {
const sessionData = await getAuthSession()
if (sessionData?.data?.user) {
useAuthStore.getState().setUser(sessionData.data.user)
currentUser = sessionData.data.user
}
} catch {
// Fall through to redirect
}
}
if (!currentUser) {
throw redirect({
to: '/login',
})
}
},
})
+51 -3
View File
@@ -4,7 +4,7 @@ import { Button } from '@/ui/components/ui/button'
import { ShumaiLogo } from '@/ui/components/ui/icons'
import { Input } from '@/ui/components/ui/input'
import { Label } from '@/ui/components/ui/label'
import { signIn } from '@/ui/lib/auth-client'
import { getAuthSession, signIn } from '@/ui/lib/auth-client'
import { useAuthStore } from '@/ui/stores/auth'
import { zodResolver } from '@hookform/resolvers/zod'
import { useQuery } from '@tanstack/react-query'
@@ -44,6 +44,16 @@ function LoginPage() {
}
}, [signupInfo, navigate])
useEffect(() => {
const user = useAuthStore.getState().user
if (user && typeof window !== 'undefined') {
const searchParams = new URLSearchParams(window.location.search)
if (searchParams.has('client_id')) {
window.location.href = `/api/auth/oauth2/authorize?${searchParams.toString()}`
}
}
}, [])
const isDemoEnv = signupInfo?.demoMode === true
const form = useForm<LoginSchema>({
@@ -65,7 +75,23 @@ function LoginPage() {
}
if (session) {
setUser(session.user)
const redirectUrl = (session as { url?: string }).url
if (redirectUrl) {
try {
const sessionData = await getAuthSession()
if (sessionData?.data?.user) {
setUser(sessionData.data.user)
}
} catch {
// Ignore and continue redirect
}
window.location.href = redirectUrl
return
}
if ('user' in session && session.user) {
setUser(session.user)
}
navigate({ to: '/' })
}
}
@@ -89,7 +115,23 @@ function LoginPage() {
}
if (session) {
setUser(session.user)
const redirectUrl = (session as { url?: string }).url
if (redirectUrl) {
try {
const sessionData = await getAuthSession()
if (sessionData?.data?.user) {
setUser(sessionData.data.user)
}
} catch {
// Ignore and continue redirect
}
window.location.href = redirectUrl
return
}
if ('user' in session && session.user) {
setUser(session.user)
}
navigate({ to: '/' })
}
}
@@ -245,6 +287,12 @@ function LoginPage() {
export const Route = createFileRoute('/login')({
component: LoginPage,
beforeLoad: () => {
if (typeof window !== 'undefined') {
const searchParams = new URLSearchParams(window.location.search)
if (searchParams.has('client_id')) {
return
}
}
if (useAuthStore.getState().user) {
throw redirect({
to: '/',