mirror of
https://github.com/shumaiOne/shumai.git
synced 2026-11-30 04:44:28 +00:00
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:
@@ -1,8 +1,12 @@
|
||||
import { createAuthClient } from 'better-auth/react'
|
||||
import { oauthProviderClient } from '@better-auth/oauth-provider/client'
|
||||
|
||||
export const authClient = createAuthClient({
|
||||
// eslint-disable-next-line @typescript-eslint/naming-convention
|
||||
baseURL: window.location.origin,
|
||||
baseURL: typeof window !== 'undefined' ? window.location.origin : '',
|
||||
plugins: [oauthProviderClient()],
|
||||
})
|
||||
|
||||
export const getAuthSession = async () => authClient.getSession()
|
||||
|
||||
export const { signIn, signUp, useSession, signOut, resetPassword } = authClient
|
||||
|
||||
@@ -1593,5 +1593,16 @@
|
||||
"hide_agent": "Hide Agent",
|
||||
"hide_agent_description": "Hide the AGENTS.md button, agent-chat sidebar, and chatbot trigger button across the entire team.",
|
||||
"appearance_settings_updated": "Appearance settings updated",
|
||||
"failed_update_appearance_settings": "Failed to update appearance settings"
|
||||
"failed_update_appearance_settings": "Failed to update appearance settings",
|
||||
"authorize_application": "Authorize Application",
|
||||
"authorize_application_subtitle": "An application is requesting access to your Shumai account and tools.",
|
||||
"application_client_id": "Client ID",
|
||||
"requested_permissions": "Requested Permissions",
|
||||
"logged_in_as": "Logged in as",
|
||||
"authorize": "Authorize",
|
||||
"authorizing": "Authorizing...",
|
||||
"deny": "Deny",
|
||||
"denying": "Denying...",
|
||||
"consent_failed": "Failed to process authorization",
|
||||
"mcp_access_scope_desc": "Full user-level access to Shumai workspace and MCP tools"
|
||||
}
|
||||
|
||||
@@ -1593,5 +1593,16 @@
|
||||
"hide_agent": "隐藏 Agent",
|
||||
"hide_agent_description": "在整个团队中隐藏 AGENTS.md 按钮、Agent 聊天侧边栏和触发按钮。",
|
||||
"appearance_settings_updated": "外观设置已更新",
|
||||
"failed_update_appearance_settings": "更新外观设置失败"
|
||||
"failed_update_appearance_settings": "更新外观设置失败",
|
||||
"authorize_application": "授权应用",
|
||||
"authorize_application_subtitle": "某个应用正在请求访问您的 Shumai 账户及相关工具。",
|
||||
"application_client_id": "客户端 ID",
|
||||
"requested_permissions": "请求的权限",
|
||||
"logged_in_as": "当前登录账号",
|
||||
"authorize": "授权",
|
||||
"authorizing": "授权中...",
|
||||
"deny": "拒绝",
|
||||
"denying": "拒绝中...",
|
||||
"consent_failed": "处理授权失败",
|
||||
"mcp_access_scope_desc": "以当前用户权限完全访问 Shumai 工作空间及 MCP 工具"
|
||||
}
|
||||
|
||||
@@ -6,6 +6,7 @@
|
||||
"main": "./index.html",
|
||||
"dependencies": {
|
||||
"@base-ui/react": "1.7.0",
|
||||
"@better-auth/oauth-provider": "1.7.12",
|
||||
"@dnd-kit/abstract": "0.5.0",
|
||||
"@dnd-kit/dom": "0.5.0",
|
||||
"@dnd-kit/react": "0.5.0",
|
||||
@@ -57,7 +58,7 @@
|
||||
"@uppy/aws-s3": "6.0.0",
|
||||
"@uppy/core": "6.0.0",
|
||||
"@uppy/xhr-upload": "6.0.0",
|
||||
"better-auth": "1.6.11",
|
||||
"better-auth": "1.7.12",
|
||||
"class-variance-authority": "0.7.1",
|
||||
"clsx": "2.1.1",
|
||||
"cmdk": "1.1.1",
|
||||
|
||||
@@ -12,6 +12,7 @@ import { Route as rootRouteImport } from './routes/__root'
|
||||
import { Route as SignupRouteImport } from './routes/signup'
|
||||
import { Route as ResetPasswordRouteImport } from './routes/reset-password'
|
||||
import { Route as LoginRouteImport } from './routes/login'
|
||||
import { Route as ConsentRouteImport } from './routes/consent'
|
||||
import { Route as IndexRouteImport } from './routes/index'
|
||||
import { Route as ShareShareIdRouteImport } from './routes/share/$shareId'
|
||||
import { Route as TeamsTeamIdIndexRouteImport } from './routes/teams/$teamId/index'
|
||||
@@ -48,6 +49,11 @@ const LoginRoute = LoginRouteImport.update({
|
||||
path: '/login',
|
||||
getParentRoute: () => rootRouteImport,
|
||||
} as any)
|
||||
const ConsentRoute = ConsentRouteImport.update({
|
||||
id: '/consent',
|
||||
path: '/consent',
|
||||
getParentRoute: () => rootRouteImport,
|
||||
} as any).lazy(() => import('./routes/consent.lazy').then((d) => d.Route))
|
||||
const IndexRoute = IndexRouteImport.update({
|
||||
id: '/',
|
||||
path: '/',
|
||||
@@ -165,6 +171,7 @@ const ProjectsProjectIdFoldersFolderIdAgentsmdRoute =
|
||||
|
||||
export interface FileRoutesByFullPath {
|
||||
'/': typeof IndexRoute
|
||||
'/consent': typeof ConsentRoute
|
||||
'/login': typeof LoginRoute
|
||||
'/reset-password': typeof ResetPasswordRoute
|
||||
'/signup': typeof SignupRoute
|
||||
@@ -190,6 +197,7 @@ export interface FileRoutesByFullPath {
|
||||
}
|
||||
export interface FileRoutesByTo {
|
||||
'/': typeof IndexRoute
|
||||
'/consent': typeof ConsentRoute
|
||||
'/login': typeof LoginRoute
|
||||
'/reset-password': typeof ResetPasswordRoute
|
||||
'/signup': typeof SignupRoute
|
||||
@@ -215,6 +223,7 @@ export interface FileRoutesByTo {
|
||||
export interface FileRoutesById {
|
||||
__root__: typeof rootRouteImport
|
||||
'/': typeof IndexRoute
|
||||
'/consent': typeof ConsentRoute
|
||||
'/login': typeof LoginRoute
|
||||
'/reset-password': typeof ResetPasswordRoute
|
||||
'/signup': typeof SignupRoute
|
||||
@@ -242,6 +251,7 @@ export interface FileRouteTypes {
|
||||
fileRoutesByFullPath: FileRoutesByFullPath
|
||||
fullPaths:
|
||||
| '/'
|
||||
| '/consent'
|
||||
| '/login'
|
||||
| '/reset-password'
|
||||
| '/signup'
|
||||
@@ -267,6 +277,7 @@ export interface FileRouteTypes {
|
||||
fileRoutesByTo: FileRoutesByTo
|
||||
to:
|
||||
| '/'
|
||||
| '/consent'
|
||||
| '/login'
|
||||
| '/reset-password'
|
||||
| '/signup'
|
||||
@@ -291,6 +302,7 @@ export interface FileRouteTypes {
|
||||
id:
|
||||
| '__root__'
|
||||
| '/'
|
||||
| '/consent'
|
||||
| '/login'
|
||||
| '/reset-password'
|
||||
| '/signup'
|
||||
@@ -317,6 +329,7 @@ export interface FileRouteTypes {
|
||||
}
|
||||
export interface RootRouteChildren {
|
||||
IndexRoute: typeof IndexRoute
|
||||
ConsentRoute: typeof ConsentRoute
|
||||
LoginRoute: typeof LoginRoute
|
||||
ResetPasswordRoute: typeof ResetPasswordRoute
|
||||
SignupRoute: typeof SignupRoute
|
||||
@@ -361,6 +374,13 @@ declare module '@tanstack/react-router' {
|
||||
preLoaderRoute: typeof LoginRouteImport
|
||||
parentRoute: typeof rootRouteImport
|
||||
}
|
||||
'/consent': {
|
||||
id: '/consent'
|
||||
path: '/consent'
|
||||
fullPath: '/consent'
|
||||
preLoaderRoute: typeof ConsentRouteImport
|
||||
parentRoute: typeof rootRouteImport
|
||||
}
|
||||
'/': {
|
||||
id: '/'
|
||||
path: '/'
|
||||
@@ -520,6 +540,7 @@ const ShareShareIdRouteWithChildren = ShareShareIdRoute._addFileChildren(ShareSh
|
||||
|
||||
const rootRouteChildren: RootRouteChildren = {
|
||||
IndexRoute: IndexRoute,
|
||||
ConsentRoute: ConsentRoute,
|
||||
LoginRoute: LoginRoute,
|
||||
ResetPasswordRoute: ResetPasswordRoute,
|
||||
SignupRoute: SignupRoute,
|
||||
|
||||
@@ -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>
|
||||
)
|
||||
}
|
||||
@@ -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()
|
||||
})
|
||||
})
|
||||
@@ -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',
|
||||
})
|
||||
}
|
||||
},
|
||||
})
|
||||
@@ -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: '/',
|
||||
|
||||
Reference in New Issue
Block a user