An AI-powered search engine with a generative UI
TypeScript generative-aigenerative-uinextjsollamareactsearxngshadcn-uitailwindcsstavilytypescriptupstashvercel-ai-sdk
feat: Add OIDC authentication support via Better Auth (#1084)
Martin Buchleitner65c42b2b71e5
diff --git a/app/api/auth/[...all]/__tests__/route.test.ts b/app/api/auth/[...all]/__tests__/route.test.tsnew file mode 100644index 00000000..6698e714--- /dev/null+++ b/app/api/auth/[...all]/__tests__/route.test.ts@@ -0,0 +1,80 @@+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'++import { GET, POST } from '../route'++// The route resolves the better-auth handler lazily; the mock stands in for+// the auth endpoint so tests assert on request routing, not on auth itself.+const handler = vi.hoisted(() =>+ vi.fn(() => new Response('from-auth-handler', { status: 200 }))+)++vi.mock('@/lib/auth/better-auth/config', () => ({+ getAuth: () => ({ handler })+}))++function request(method: 'GET' | 'POST', path: string): Request {+ return new Request(`http://localhost/api/auth/${path}`, { method })+}++describe('GET /api/auth/[...all]', () => {+ beforeEach(() => {+ handler.mockClear()+ })++ afterEach(() => {+ vi.unstubAllEnvs()+ })++ it('lets the identity provider callback through to the auth handler', async () => {+ const req = request('GET', 'callback/oidc')+ const response = await GET(req)++ expect(handler).toHaveBeenCalledWith(req)+ expect(response.status).toBe(200)+ })++ it('accepts the callback path of a custom OIDC_PROVIDER_ID', async () => {+ vi.stubEnv('OIDC_PROVIDER_ID', 'corp-idp')+ const response = await GET(request('GET', 'callback/corp-idp'))++ expect(handler).toHaveBeenCalledTimes(1)+ expect(response.status).toBe(200)++ // Any other provider id is not mounted.+ handler.mockClear()+ const other = await GET(request('GET', 'callback/oidc'))+ expect(other.status).toBe(404)+ expect(handler).not.toHaveBeenCalled()+ })++ it('exposes the error endpoint the auth callback redirects to', async () => {+ const response = await GET(request('GET', 'error'))++ expect(handler).toHaveBeenCalledTimes(1)+ expect(response.status).toBe(200)+ })++ it.each([+ // Credential and sign-up endpoints exist in better-auth but the app only+ // exposes them through server actions, which enforce the invitation and+ // bootstrap-account policy — mounting them would be a bypass.+ request('GET', 'sign-up/email'),+ request('POST', 'sign-up/email'),+ request('GET', 'sign-in/email'),+ request('POST', 'sign-in/email'),+ request('GET', 'reset-password/token123'),+ // The callback is an authorization-response redirect: other methods+ // either do not occur or must not be answered.+ request('POST', 'callback/oidc'),+ // Path traversal and nested segments are not callbacks.+ request('GET', 'callback/../sign-up/email'),+ request('GET', 'callback/oidc/extra'),+ request('GET', 'unknown/oidc')+ ])('answers %s with 404 and never touches the auth handler', async req => {+ const dispatch = req.method === 'POST' ? POST : GET+ const response = await dispatch(req)++ expect(response.status).toBe(404)+ expect(handler).not.toHaveBeenCalled()+ })+})diff --git a/app/api/auth/[...all]/route.ts b/app/api/auth/[...all]/route.tsnew file mode 100644index 00000000..54b46277--- /dev/null+++ b/app/api/auth/[...all]/route.ts@@ -0,0 +1,57 @@+import { getAuth } from '@/lib/auth/better-auth/config'+import { getOidcProviderId } from '@/lib/auth/oauth-config'++// Better Auth's HTTP surface, restricted to the provider callback flow.+//+// Why not the full handler: mounting Better Auth's catch-all would expose+// POST /api/auth/sign-up/email directly, bypassing the invitation and+// bootstrap-account policy that betterAuthProvider.signUp enforces — an+// invite-only instance would accept anyone. The credential endpoints are+// therefore driven exclusively through server actions (lib/actions/auth.ts+// dispatches to the provider implementations), and the only HTTP surface a+// third party needs is where the identity provider redirects the browser:+//+// - GET /api/auth/callback/<OIDC_PROVIDER_ID> (default 'oidc'): the+// authorization response, where Better Auth exchanges the code, links+// the account, sets the session cookie and redirects to the page the+// login form requested.+// - GET /api/auth/error: Better Auth's target when a callback fails+// (e.g. an invite-only instance rejecting an unregistered identity).+//+// The auth instance is built lazily, per request: `next build` evaluates+// route modules to collect page data before any deployment environment is+// known, and getAuth() must not run then — it throws by design without+// BETTER_AUTH_SECRET, and the builder cannot reach the database. The+// configured provider id is likewise read per request: the route module+// must not bake it in before the deployment environment is known.++function isCallbackRequest(pathname: string, method: string): boolean {+ if (method !== 'GET') {+ return false+ }+ if (pathname === '/api/auth/error') {+ return true+ }+ return pathname === `/api/auth/callback/${getOidcProviderId()}`+}++async function handle(request: Request): Promise<Response> {+ const { pathname } = new URL(request.url)+ if (!isCallbackRequest(pathname, request.method)) {+ return new Response(+ 'Not found. This deployment exposes only the provider callback ' ++ '(GET /api/auth/callback/<OIDC_PROVIDER_ID>); authentication is ' ++ 'driven through server actions.',+ { status: 404 }+ )+ }+ return getAuth().handler(request)+}++export async function GET(request: Request) {+ return handle(request)+}++export async function POST(request: Request) {+ return handle(request)+}diff --git a/bun.lock b/bun.lockindex bde58fb1..0ce87116 100644--- a/bun.lock+++ b/bun.lock@@ -56,7 +56,7 @@"@vercel/otel": "^2.1.3","ai": "^7.0.152","ai-sdk-ollama": "^4.5.1",- "better-auth": "^1.7.7",+ "better-auth": "^1.7.12","class-variance-authority": "^0.7.1","clsx": "^2.1.0","cmdk": "1.0.0",@@ -260,21 +260,21 @@"@babel/types": ["@babel/[email protected]", "", { "dependencies": { "@babel/helper-string-parser": "^7.27.1", "@babel/helper-validator-identifier": "^7.27.1" } }, "sha512-ruv7Ae4J5dUYULmeXw1gmb7rYRz57OWCPM57pHojnLq/3Z1CK2lNSLTCVjxVk1F/TZHwOZZrOWi0ur95BbLxNQ=="],- "@better-auth/core": ["@better-auth/[email protected]", "", { "dependencies": { "@opentelemetry/semantic-conventions": "^1.41.1", "@standard-schema/spec": "^1.1.0", "zod": "^4.5.4" }, "peerDependencies": { "@better-auth/utils": "0.4.2", "@better-fetch/fetch": "1.3.2", "@opentelemetry/api": "^1.9.0", "better-call": "1.4.0", "jose": "^6.1.0", "kysely": "^0.28.5 || ^0.29.0", "nanostores": "^1.0.1" }, "optionalPeers": ["@opentelemetry/api"] }, "sha512-srgFzHEjB2WWlokFz1i4BfG41sNhsA105Pukgqu6RrEh5A+LSkzf1mCHydVipkjt9l5qswtBMi7IL6ouHbZL4Q=="],+ "@better-auth/core": ["@better-auth/[email protected]", "", { "dependencies": { "@standard-schema/spec": "^1.1.0", "zod": "^4.5.4" }, "peerDependencies": { "@better-auth/utils": "^0.4.2 || ^0.5.0", "@better-fetch/fetch": "1.3.2", "@opentelemetry/api": "^1.9.0", "better-call": "1.4.4", "jose": "^6.1.0", "kysely": "^0.28.5 || ^0.29.0", "nanostores": "^1.0.1" }, "optionalPeers": ["@opentelemetry/api"] }, "sha512-SUStBGHJ13KnSO6+7U/1DSlfuOtln4jtOrFZqzQtxZVHZIrAoMjwHNGitlF+s7hvKbuC3Z14xjnqfLLqIqGfxw=="],- "@better-auth/drizzle-adapter": ["@better-auth/[email protected]", "", { "peerDependencies": { "@better-auth/core": "^1.7.7", "@better-auth/utils": "0.4.2", "drizzle-orm": "^0.45.2 || >=1.0.0-rc.1 <2.0.0" }, "optionalPeers": ["drizzle-orm"] }, "sha512-qon0U94PR5FQysuyGoAlGVQpIIiNg5dtDpwjE63sN/HjoRWZadZzHPcS9mn7JsJyQZK6iTNhd7LD0AaXt2f78w=="],+ "@better-auth/drizzle-adapter": ["@better-auth/[email protected]", "", { "peerDependencies": { "@better-auth/core": "^1.7.12", "@better-auth/utils": "^0.4.2 || ^0.5.0", "drizzle-orm": "^0.45.2 || >=1.0.0-rc.1 <2.0.0" }, "optionalPeers": ["drizzle-orm"] }, "sha512-Qzoyuf05aK01Pc0k3EXv8Xj3XCT2m2dCWc5HoB7x+xX6N3Pm2eQsca+UIArsJcbuNEWWP3L51oIebnBoHJ5DTw=="],- "@better-auth/kysely-adapter": ["@better-auth/[email protected]", "", { "peerDependencies": { "@better-auth/core": "^1.7.7", "@better-auth/utils": "0.4.2", "kysely": "^0.28.17 || ^0.29.0" }, "optionalPeers": ["kysely"] }, "sha512-9FONOCgOcrQI9wJ5v1oDGIg9sT7pa9RjZZQ4fsCTudo8R87SrIGNUvUxDFTJhZvUblvFfGaIBR9Vb8LA+8bqLQ=="],+ "@better-auth/kysely-adapter": ["@better-auth/[email protected]", "", { "peerDependencies": { "@better-auth/core": "^1.7.12", "@better-auth/utils": "^0.4.2 || ^0.5.0", "kysely": "^0.28.17 || ^0.29.0" }, "optionalPeers": ["kysely"] }, "sha512-1PaFXktLv4n3DmrGbPaCj5SsvcT40NnWw7NLua5/J1+8/A051N5ZzqOwJifXEIQX5k6NdwvmymwDQxKytduEAQ=="],- "@better-auth/memory-adapter": ["@better-auth/[email protected]", "", { "peerDependencies": { "@better-auth/core": "^1.7.7", "@better-auth/utils": "0.4.2" } }, "sha512-FqKFEe+b5tXXV0gRbyirca+qXgMpLOeJ8Wk19yykb/scQKy0WJ4k22WzEV3TTPctQV9DZhwCXPlDtQhnlOv5Gg=="],+ "@better-auth/memory-adapter": ["@better-auth/[email protected]", "", { "peerDependencies": { "@better-auth/core": "^1.7.12", "@better-auth/utils": "^0.4.2 || ^0.5.0" } }, "sha512-glaDwXzDptnddHqRuu7fj47FAssUcOzLNgdlTGJoEPrspkX69x2vnXwgAzNuApjZI21WLtPH/rQ6CN+DQGybPA=="],- "@better-auth/mongo-adapter": ["@better-auth/[email protected]", "", { "peerDependencies": { "@better-auth/core": "^1.7.7", "@better-auth/utils": "0.4.2", "mongodb": "^6.0.0 || ^7.0.0" }, "optionalPeers": ["mongodb"] }, "sha512-ZnVDuRrXqbf0oHphrEN27oTImNH5NTO26dtWatq5cXyYAsH7goof9QIoTOmxTbBxUQahKBw9T6+9h6n+RtOE+g=="],+ "@better-auth/mongo-adapter": ["@better-auth/[email protected]", "", { "peerDependencies": { "@better-auth/core": "^1.7.12", "@better-auth/utils": "^0.4.2 || ^0.5.0", "mongodb": "^6.0.0 || ^7.0.0" }, "optionalPeers": ["mongodb"] }, "sha512-HKV4sgYSw/Gdt9AuHlESMkiKL72SWdGweDy1Wsyxoh06BpG7aNu4aSJ7marNpMdKZteyRbxWWqQkA9ediA8qFw=="],- "@better-auth/prisma-adapter": ["@better-auth/[email protected]", "", { "peerDependencies": { "@better-auth/core": "^1.7.7", "@better-auth/utils": "0.4.2", "@prisma/client": "^5.0.0 || ^6.0.0 || ^7.0.0", "prisma": "^5.0.0 || ^6.0.0 || ^7.0.0" }, "optionalPeers": ["@prisma/client", "prisma"] }, "sha512-4YcnrcVdvWiAZw0sZl63tWUClPXg5r3QsLn7C2sG7kKEBY06zOng0ibecyxRBixKq1zE1ceHuEUqez5Rhi+nQA=="],+ "@better-auth/prisma-adapter": ["@better-auth/[email protected]", "", { "peerDependencies": { "@better-auth/core": "^1.7.12", "@better-auth/utils": "^0.4.2 || ^0.5.0", "@prisma/client": "^5.0.0 || ^6.0.0 || ^7.0.0", "prisma": "^5.0.0 || ^6.0.0 || ^7.0.0" }, "optionalPeers": ["@prisma/client", "prisma"] }, "sha512-FZRX6ORbwhDmeYE1Tl0IPtUn8v3BlVFgbJxDnm/DCNHxuFRf+0t4HfddUgYeYehHFR8aSDsdYX44fEFWM9877w=="],- "@better-auth/telemetry": ["@better-auth/[email protected]", "", { "peerDependencies": { "@better-auth/core": "^1.7.7", "@better-auth/utils": "0.4.2", "@better-fetch/fetch": "1.3.2" } }, "sha512-PaRA6i+kAioVYmza2gHPcdrxP0hAotph4KV9hft2GeNJq+AZXDiBu3FuLM9HxvcmiZeUT74Vufqd9ypmB8veTA=="],+ "@better-auth/telemetry": ["@better-auth/[email protected]", "", { "peerDependencies": { "@better-auth/core": "^1.7.12", "@better-auth/utils": "^0.4.2 || ^0.5.0", "@better-fetch/fetch": "1.3.2" } }, "sha512-DaDkKNnI99vKGGbWq9KJg2uYeaOjsK9nIBw9T2m2KG/RkxpvQRjYkZ00++up2bZQkR5pB1nukGbplza3UJG/Xg=="],- "@better-auth/utils": ["@better-auth/[email protected]", "", { "dependencies": { "@noble/hashes": "^2.0.1" } }, "sha512-AUxrvu+HaaODsUyzDxFgwd/8RZ1yZaYo42LXKSrU2oGgR38pS1ij8nqQKNgtTWoYGpNevNXtCfgTy6loHveW9A=="],+ "@better-auth/utils": ["@better-auth/[email protected]", "", { "dependencies": { "@noble/hashes": "^2.0.1" } }, "sha512-BL8W4EfIZFwlu0r54m3v1ztjDhu6dDe/amLTm0xybmbZaNgYUqhD3SjpAsnq0q8YD6/ki4iwIgxJNLP/N3TxiA=="],"@better-fetch/fetch": ["@better-fetch/[email protected]", "", {}, "sha512-Gs7n99b5tqUC6cQAPbV0uED3IraHB6xQbHLQ/C3l7ZFafHScOx9pQ+DYmP5blbLFShVWLqxNUlI9wi4xU/X+ow=="],@@ -1122,9 +1122,9 @@"baseline-browser-mapping": ["[email protected]", "", { "bin": { "baseline-browser-mapping": "dist/cli.js" } }, "sha512-ipDqC8FrAl/76p2SSWKSI+H9tFwm7vYqXQrItCuiVPt26Km0jS+NzSsBWAaBusvSbQcfJG+JitdMm+wZAgTYqg=="],- "better-auth": ["[email protected]", "", { "dependencies": { "@better-auth/core": "1.7.7", "@better-auth/drizzle-adapter": "1.7.7", "@better-auth/kysely-adapter": "1.7.7", "@better-auth/memory-adapter": "1.7.7", "@better-auth/mongo-adapter": "1.7.7", "@better-auth/prisma-adapter": "1.7.7", "@better-auth/telemetry": "1.7.7", "@better-auth/utils": "0.4.2", "@better-fetch/fetch": "1.3.2", "@noble/ciphers": "^2.2.0", "@noble/hashes": "^2.2.0", "better-call": "1.4.0", "defu": "^6.1.4", "jose": "^6.2.3", "kysely": "^0.28.17 || ^0.29.0", "nanostores": "^1.3.0", "zod": "^4.5.4" }, "peerDependencies": { "@lynx-js/react": "*", "@prisma/client": "^5.0.0 || ^6.0.0 || ^7.0.0", "@sveltejs/kit": "^2.0.0", "@tanstack/react-start": "^1.0.0", "@tanstack/solid-start": "^1.0.0", "drizzle-kit": ">=0.31.4 || >=1.0.0-beta.1", "drizzle-orm": "^0.45.2 || >=1.0.0-rc.1 <2.0.0", "mongodb": "^6.0.0 || ^7.0.0", "mysql2": "^3.0.0", "next": "^14.0.0 || ^15.0.0 || ^16.0.0", "pg": "^8.0.0", "prisma": "^5.0.0 || ^6.0.0 || ^7.0.0", "react": "^18.0.0 || ^19.0.0", "react-dom": "^18.0.0 || ^19.0.0", "solid-js": "^1.0.0", "svelte": "^4.0.0 || ^5.0.0", "vitest": "^2.0.0 || ^3.0.0 || ^4.0.0 || ^5.0.0", "vue": "^3.0.0" }, "optionalPeers": ["@lynx-js/react", "@prisma/client", "@sveltejs/kit", "@tanstack/react-start", "@tanstack/solid-start", "drizzle-kit", "drizzle-orm", "mongodb", "mysql2", "next", "pg", "prisma", "react", "react-dom", "solid-js", "svelte", "vitest", "vue"] }, "sha512-Zhgxi/c5ylmfB/sX+nwnBbsFf/j6k0L8DvL6CJXZSrXgxc5pPMC/e7j812zNd4L4B4ELmdURCPw3X8nAOUdcjw=="],+ "better-auth": ["[email protected]", "", { "dependencies": { "@better-auth/core": "1.7.12", "@better-auth/drizzle-adapter": "1.7.12", "@better-auth/kysely-adapter": "1.7.12", "@better-auth/memory-adapter": "1.7.12", "@better-auth/mongo-adapter": "1.7.12", "@better-auth/prisma-adapter": "1.7.12", "@better-auth/telemetry": "1.7.12", "@better-auth/utils": "0.5.0", "@better-fetch/fetch": "1.3.2", "@noble/ciphers": "^2.2.0", "@noble/hashes": "^2.2.0", "better-call": "1.4.4", "defu": "^6.1.4", "jose": "^6.2.3", "kysely": "^0.28.17 || ^0.29.0", "nanostores": "^1.3.0", "zod": "^4.5.4" }, "peerDependencies": { "@lynx-js/react": "*", "@prisma/client": "^5.0.0 || ^6.0.0 || ^7.0.0", "@sveltejs/kit": "^2.0.0 || ^3.0.0", "@tanstack/react-start": "^1.0.0", "@tanstack/solid-start": "^1.0.0", "drizzle-kit": ">=0.31.4 || >=1.0.0-beta.1", "drizzle-orm": "^0.45.2 || >=1.0.0-rc.1 <2.0.0", "mongodb": "^6.0.0 || ^7.0.0", "mysql2": "^3.0.0", "next": "^14.0.0 || ^15.0.0 || ^16.0.0", "pg": "^8.0.0", "prisma": "^5.0.0 || ^6.0.0 || ^7.0.0", "react": "^18.0.0 || ^19.0.0", "react-dom": "^18.0.0 || ^19.0.0", "solid-js": "^1.0.0", "svelte": "^4.0.0 || ^5.0.0", "vitest": "^2.0.0 || ^3.0.0 || ^4.0.0 || ^5.0.0", "vue": "^3.0.0" }, "optionalPeers": ["@lynx-js/react", "@prisma/client", "@sveltejs/kit", "@tanstack/react-start", "@tanstack/solid-start", "drizzle-kit", "drizzle-orm", "mongodb", "mysql2", "next", "pg", "prisma", "react", "react-dom", "solid-js", "svelte", "vitest", "vue"] }, "sha512-f1fEG0QdTslzbmFA+vOGFFW/XXCWkG4kBxLeH9n1vp1otTH9+ZzV6EJ6797GStWeiYYgS5Vnt9xqE12KwSyAAw=="],- "better-call": ["[email protected]", "", { "dependencies": { "@better-auth/utils": "^0.5.0", "@better-fetch/fetch": "^1.3.1", "rou3": "^0.9.1", "set-cookie-parser": "^3.1.2" }, "peerDependencies": { "zod": "^4.0.0" }, "optionalPeers": ["zod"] }, "sha512-bBKOT4vv1kZLDgxVePdilk/Jwkn+dtRRsmi3DzHcDP+WnswyVl6dR59l2HEeP/0cB+bDoopASAesWDPIdd/zZA=="],+ "better-call": ["[email protected]", "", { "dependencies": { "@better-auth/utils": "^0.5.0", "@better-fetch/fetch": "^1.3.1", "rou3": "^0.9.1", "set-cookie-parser": "^3.1.2" }, "peerDependencies": { "zod": "^4.0.0" }, "optionalPeers": ["zod"] }, "sha512-Gq4XdGFy4dmUxFEAX2nj0ycFcFbD9ZWh8YROouZoyXeF1M11TpYbplk0pDByTFF8Wz+MYa6W9052c9m7dD+mfw=="],"boolbase": ["[email protected]", "", {}, "sha512-JZOSA7Mo9sNGB8+UjSgzdLtokWAky1zbztM3WRLCbZ70/3cTANmQmOdR7y2g+J0e2WXywy1yS468tY+IruqEww=="],@@ -2406,8 +2406,6 @@"better-auth/@noble/hashes": ["@noble/[email protected]", "", {}, "sha512-X5XaVWZIBCT7HHZGm5I7ZQXDwLG+bGXuSrMQAW+7Zvl87h1kmc1ZB1VSRJcpUfoUrGQp4Fkoxm5kZ+Ms+aW+eA=="],- "better-call/@better-auth/utils": ["@better-auth/[email protected]", "", { "dependencies": { "@noble/hashes": "^2.0.1" } }, "sha512-BL8W4EfIZFwlu0r54m3v1ztjDhu6dDe/amLTm0xybmbZaNgYUqhD3SjpAsnq0q8YD6/ki4iwIgxJNLP/N3TxiA=="],-"better-call/set-cookie-parser": ["[email protected]", "", {}, "sha512-5/r/lTwbJ3zQ+qwdUFZYeRNqda7P5HD8zQKqlSjdGt1/S0cjLAphHusj4Y58ahDtWn/g32xrIS58/ikOvwl0Lw=="],"chevrotain-allstar/lodash-es": ["[email protected]", "", {}, "sha512-mKnC+QJ9pWVzv+C4/U3rRsHapFfHvQFoFB92e52xeyGMcX6/OlIl78je1u8vePzYZSkkogMPJ2yjxxsb89cxyw=="],@@ -2584,8 +2582,6 @@"@typescript-eslint/typescript-estree/minimatch/brace-expansion": ["[email protected]", "", { "dependencies": { "balanced-match": "^4.0.2" } }, "sha512-h+DEnpVvxmfVefa4jFbCf5HdH5YMDXRsmKflpf1pILZWRFlTbJpxeU55nJl4Smt5HQaGzg1o6RHFPJaOqnmBDg=="],- "better-call/@better-auth/utils/@noble/hashes": ["@noble/[email protected]", "", {}, "sha512-X5XaVWZIBCT7HHZGm5I7ZQXDwLG+bGXuSrMQAW+7Zvl87h1kmc1ZB1VSRJcpUfoUrGQp4Fkoxm5kZ+Ms+aW+eA=="],-"cmdk/@radix-ui/react-dialog/@radix-ui/primitive": ["@radix-ui/[email protected]", "", { "dependencies": { "@babel/runtime": "^7.13.10" } }, "sha512-yQ8oGX2GVsEYMWGxcovu1uGWPCxV5BFfeeYxqPmuAzUyLT9qmaMXSAhXpb0WrspIeqYzdJpkh2vHModJPgRIaw=="],"cmdk/@radix-ui/react-dialog/@radix-ui/react-compose-refs": ["@radix-ui/[email protected]", "", { "dependencies": { "@babel/runtime": "^7.13.10" }, "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0" }, "optionalPeers": ["@types/react"] }, "sha512-fDSBgd44FKHa1FRMU59qBMPFcl2PZE+2nmqunj+BWFyYYjnhIDWL2ItDs3rrbJDQOtzt5nIebLCQc4QRfz6LJw=="],diff --git a/components/__tests__/login-form.test.tsx b/components/__tests__/login-form.test.tsxindex a6646b3e..5675d3a9 100644--- a/components/__tests__/login-form.test.tsx+++ b/components/__tests__/login-form.test.tsx@@ -1,14 +1,15 @@import { fireEvent, render, screen, waitFor } from '@testing-library/react'import { beforeEach, describe, expect, it, vi } from 'vitest'-import { signIn, signInWithGoogle } from '@/lib/actions/auth'+import { signIn, signInWithGoogle, signInWithOidc } from '@/lib/actions/auth'import { AppUserProvider } from '@/lib/contexts/app-user-context'import { LoginForm } from '@/components/login-form'vi.mock('@/lib/actions/auth', () => ({signIn: vi.fn(),- signInWithGoogle: vi.fn()+ signInWithGoogle: vi.fn(),+ signInWithOidc: vi.fn()}))const { mockPush, mockRefresh } = vi.hoisted(() => ({@@ -25,6 +26,7 @@ const capabilities = {passwordReset: true,deleteUser: true,oauth: true,+ oauthProvider: null as string | null,emailVerification: true,share: true}@@ -248,6 +250,82 @@ describe('LoginForm', () => {).not.toBeInTheDocument()})+ it('labels the OAuth button with the server-reported OIDC provider and signs in through it', async () => {+ // The form itself cannot see OIDC_* environment variables (non-public+ // vars are stripped from the client bundle); the provider name arrives+ // through AuthCapabilities instead.+ const originalLocation = window.location+ Object.defineProperty(window, 'location', {+ configurable: true,+ writable: true,+ value: { href: '' }+ })+ vi.mocked(signInWithOidc).mockResolvedValue({+ success: true,+ redirectTo: 'https://idp.example.com/authorize'+ })+ renderForm({ oauthProvider: 'Keycloak' })++ const button = screen.getByRole('button', { name: 'Sign In with Keycloak' })+ fireEvent.click(button)++ await waitFor(() => {+ expect(signInWithOidc).toHaveBeenCalled()+ expect(signInWithGoogle).not.toHaveBeenCalled()+ expect(window.location.href).toBe('https://idp.example.com/authorize')+ })++ Object.defineProperty(window, 'location', {+ configurable: true,+ writable: true,+ value: originalLocation+ })+ })++ it('falls back to Google when the capabilities carry no OIDC provider', async () => {+ vi.mocked(signInWithGoogle).mockResolvedValue({+ success: true,+ redirectTo: 'https://accounts.google.com/authorize'+ })+ renderForm({ oauthProvider: null })++ fireEvent.click(screen.getByRole('button', { name: 'Sign In with Google' }))++ await waitFor(() => {+ expect(signInWithGoogle).toHaveBeenCalled()+ expect(signInWithOidc).not.toHaveBeenCalled()+ })+ })++ it('passes the next target into the OIDC flow via the cookie', async () => {+ const originalLocation = window.location+ Object.defineProperty(window, 'location', {+ configurable: true,+ writable: true,+ value: { href: '' }+ })+ vi.mocked(signInWithOidc).mockResolvedValue({+ success: true,+ redirectTo: 'https://idp.example.com/authorize'+ })+ renderForm({ oauthProvider: 'Keycloak' }, null, '/search/abc123')++ fireEvent.click(+ screen.getByRole('button', { name: 'Sign In with Keycloak' })+ )++ await waitFor(() => {+ expect(signInWithOidc).toHaveBeenCalled()+ })+ expect(document.cookie).toContain('auth_next=%2Fsearch%2Fabc123')++ Object.defineProperty(window, 'location', {+ configurable: true,+ writable: true,+ value: originalLocation+ })+ })+it('offers password recovery when the provider supports it', () => {renderForm()expect(diff --git a/components/login-form.tsx b/components/login-form.tsxindex 9feee9cd..22a2f0d8 100644--- a/components/login-form.tsx+++ b/components/login-form.tsx@@ -4,7 +4,7 @@ import { useState } from 'react'import Link from 'next/link'import { useRouter } from 'next/navigation'-import { signIn, signInWithGoogle } from '@/lib/actions/auth'+import { signIn, signInWithGoogle, signInWithOidc } from '@/lib/actions/auth'import { safeRedirectPath } from '@/lib/auth/redirect-target'import { useAuthCapabilities } from '@/lib/contexts/app-user-context'import { cn } from '@/lib/utils/index'@@ -89,6 +89,31 @@ export function LoginForm({}}+ const handleOidcLogin = async () => {+ setIsLoading(true)+ setError(null)++ try {+ document.cookie = next+ ? `auth_next=${encodeURIComponent(+ safeRedirectPath(next)+ )}; path=/; max-age=300; SameSite=Lax`+ : 'auth_next=; path=/; max-age=0; SameSite=Lax'+ const result = await signInWithOidc()+ if (!result.success)+ throw new Error(result.error ?? 'An OAuth error occurred')+ if (result.redirectTo) {+ window.location.href = result.redirectTo+ }+ } catch (error: unknown) {+ setError(+ error instanceof Error ? error.message : 'An OAuth error occurred'+ )+ } finally {+ setIsLoading(false)+ }+ }+return (<divclassName={cn('flex flex-col items-center gap-6', className)}@@ -114,10 +139,16 @@ export function LoginForm({variant="outline"type="button"className="w-full"- onClick={handleSocialLogin}+ onClick={+ capabilities.oauthProvider+ ? handleOidcLogin+ : handleSocialLogin+ }disabled={isLoading}>- Sign In with Google+ {capabilities.oauthProvider+ ? `Sign In with ${capabilities.oauthProvider}`+ : 'Sign In with Google'}</Button><div className="relative my-2">diff --git a/docs/CONFIGURATION.md b/docs/CONFIGURATION.mdindex 700ebe59..b1351aea 100644--- a/docs/CONFIGURATION.md+++ b/docs/CONFIGURATION.md@@ -303,6 +303,85 @@ In production builds (Docker), session cookies carry the `__Secure-` prefix, soWith Better Auth, sharing chats is off until you set `ENABLE_SHARE=true`. See [Chat Sharing](#chat-sharing).+#### OIDC / OAuth Integration++Better Auth supports generic OIDC authentication for corporate identity providers like Keycloak, Authentik, Okta, Azure AD, and others.++**Required environment variables:**++```bash+OIDC_ISSUER=https://keycloak.example.com/realms/your-realm+OIDC_CLIENT_ID=morphic-client+OIDC_CLIENT_SECRET=your-client-secret+BETTER_AUTH_URL=https://your-morphic-url.com+```++`BETTER_AUTH_URL` is required: it is the canonical origin the provider redirect URI (`<BETTER_AUTH_URL>/api/auth/callback/<OIDC_PROVIDER_ID>`) and the post-SignIn redirect are derived from. Without it, OAuth sign-in is refused at click time even when OIDC is otherwise fully configured.++**Optional customization:**++```bash+# OAuth scopes (defaults to 'openid profile email')+OIDC_SCOPE=openid profile email groups++# Provider display name in login UI (defaults to 'OIDC')+OIDC_PROVIDER_NAME=Keycloak++# Provider id (defaults to 'oidc'). Becomes the plugin-registered identity+# and the last segment of the callback URL below.+OIDC_PROVIDER_ID=oidc+```++**How it works:**++- When OIDC environment variables are set, the login form replaces the Google OAuth button with your configured provider+- The provider id defaults to `oidc` (`OIDC_PROVIDER_ID`); the callback URL is `/api/auth/callback/<OIDC_PROVIDER_ID>` and the provider id must match the client's registered redirect URI exactly+- The OIDC `sub` claim is only unique per issuer: accounts are keyed by `(providerId, sub)`, so changing `OIDC_ISSUER` must come with a new `OIDC_PROVIDER_ID`; otherwise identities from the two issuers collide in the account table+- Uses OpenID Connect Discovery to automatically fetch endpoints from `OIDC_ISSUER/.well-known/openid-configuration`+- Implements PKCE (Proof Key for Code Exchange) for secure authorization flows+- User accounts are stored in the same `users` and `accounts` tables as email/password users+- The OIDC `sub` claim is stored as `accounts.accountId` with `accounts.providerId=<OIDC_PROVIDER_ID>`+- A transient discovery outage does not permanently disable the provider: a failed discovery is retried on the next sign-in attempt++**Sign-up policy:**++- `AUTH_SIGNUP_MODE=open`: any identity accepted by your IdP can create a local account on first sign-in+- `AUTH_SIGNUP_MODE=invite` (or an invalid mode): implicit sign-up through OIDC is rejected. OIDC sign-in works only for an IdP identity that is already linked to a local account. An account created through an invitation (credential flow) is not linked automatically: its email is unverified, so an OIDC sign-in with the same address is rejected with `account_not_linked`. Invited members therefore sign in with email and password, and new members cannot be onboarded through OIDC in this mode. Members of your IdP tenant are never handed an account implicitly.+- The bootstrap window applies to OIDC account creation: while the user table is still empty, OIDC cannot create the first account. The first account of a deployment must be created through the credential/bootstrap path — with SMTP configured that is the emailed bootstrap link (proof of mailbox ownership of `BOOTSTRAP_ADMIN_EMAIL`); without SMTP the address gate is the accepted proof, as for credential sign-up. Once the first account exists, OIDC sign-up follows the sign-up mode policy alone — the gate reads the live user table at creation time (Better Auth's `user.validateUserInfo` callback), so no restart is needed for it to lift, and it re-closes automatically if every account is deleted.+- The gate runs on every account creation and fails closed: if the user-table state cannot be read, OIDC registration is rejected rather than silently allowed.++**HTTP surface:**++Better Auth's API is driven through server actions. Only the provider callback is mounted as an HTTP route (`GET /api/auth/callback/<providerId>`); other endpoints (credential sign-up, sign-in, password reset) are reachable only inside the server actions, which enforce the sign-up policy — a direct `POST /api/auth/sign-up/email` on a mounted catch-all would otherwise bypass invitations.++**Identity provider setup:**++1. Create a new OAuth/OIDC client in your identity provider+2. Set the redirect/callback URL to: `https://your-morphic-url.com/api/auth/callback/<OIDC_PROVIDER_ID>` (default: `…/callback/oidc`)+3. Enable authorization code flow with PKCE+4. Request scopes: `openid`, `profile`, `email` (and any additional scopes like `groups`)+5. Copy the client ID, client secret, and issuer URL to your environment variables++**Keycloak example:**++```bash+OIDC_ISSUER=https://keycloak.example.com/realms/company+OIDC_CLIENT_ID=morphic+OIDC_CLIENT_SECRET=abc123...+OIDC_PROVIDER_NAME=Company Login+```++**Authentik example:**++```bash+OIDC_ISSUER=https://authentik.example.com/application/o/morphic/+OIDC_CLIENT_ID=morphic-client+OIDC_CLIENT_SECRET=xyz789...+OIDC_PROVIDER_NAME=Authentik+```++When OIDC is configured, users can sign in with their corporate accounts. Email/password registration and login remain available for admin bootstrap and local accounts.+### SupabaseFor deployments that already use Supabase, or that prefer a hosted auth service.diff --git a/lib/actions/auth.ts b/lib/actions/auth.tsindex 1c1c5974..dadf65d0 100644--- a/lib/actions/auth.ts+++ b/lib/actions/auth.ts@@ -1,5 +1,6 @@'use server'+import { getOidcProviderId } from '@/lib/auth/oauth-config'import { getAuthProvider } from '@/lib/auth/provider'import type { AuthActionResult } from '@/lib/auth/types'@@ -26,6 +27,16 @@ export async function signInWithGoogle(): Promise<AuthActionResult> {return provider.signInWithOAuth('google')}+export async function signInWithOidc(): Promise<AuthActionResult> {+ const provider = getAuthProvider()+ if (!provider.signInWithOAuth) {+ return unavailable()+ }+ // The provider id is resolved on the server (OIDC_PROVIDER_ID, default+ // 'oidc'); the client only asks for the OIDC sign-in flow by name.+ return provider.signInWithOAuth(getOidcProviderId())+}+export async function signUp(credentials: {email: stringpassword: stringdiff --git a/lib/auth/__tests__/better-auth-provider.test.ts b/lib/auth/__tests__/better-auth-provider.test.tsindex ff8e31be..270bf60d 100644--- a/lib/auth/__tests__/better-auth-provider.test.ts+++ b/lib/auth/__tests__/better-auth-provider.test.ts@@ -158,7 +158,11 @@ describe('better-auth provider', () => {'SMTP_PASSWORD','AUTH_SIGNUP_MODE','BOOTSTRAP_ADMIN_EMAIL',- 'BETTER_AUTH_URL'+ 'BETTER_AUTH_URL',+ 'OIDC_ISSUER',+ 'OIDC_CLIENT_ID',+ 'OIDC_CLIENT_SECRET',+ 'OIDC_PROVIDER_NAME']) {originalEnv[key] = process.env[key]delete process.env[key]@@ -193,6 +197,22 @@ describe('better-auth provider', () => {expect(betterAuthProvider.capabilities.deleteUser).toBe(true)expect(betterAuthProvider.capabilities.share).toBe(true)})++ it('hides the OAuth button until BETTER_AUTH_URL provides the callback origin', () => {+ process.env.OIDC_ISSUER = 'https://idp.example.com'+ process.env.OIDC_CLIENT_ID = 'morphic-client'+ process.env.OIDC_CLIENT_SECRET = 'secret'++ // The IdP redirect URI and the post-sign-in redirect derive from the+ // canonical origin: with OIDC credentials alone, rendering the button+ // would only ever produce "BETTER_AUTH_URL must be set" on click.+ expect(betterAuthProvider.capabilities.oauth).toBe(false)+ expect(betterAuthProvider.capabilities.oauthProvider).toBeNull()++ process.env.BETTER_AUTH_URL = 'http://localhost:3000'+ expect(betterAuthProvider.capabilities.oauth).toBe(true)+ expect(betterAuthProvider.capabilities.oauthProvider).toBe('OIDC')+ })})describe('getCurrentUser', () => {diff --git a/lib/auth/__tests__/oauth-config.test.ts b/lib/auth/__tests__/oauth-config.test.tsnew file mode 100644index 00000000..20a3d7aa--- /dev/null+++ b/lib/auth/__tests__/oauth-config.test.ts@@ -0,0 +1,37 @@+import { afterEach, describe, expect, it, vi } from 'vitest'++import { getOidcProviderId } from '../oauth-config'++afterEach(() => {+ vi.unstubAllEnvs()+})++describe('getOidcProviderId', () => {+ it('defaults to "oidc"', () => {+ expect(getOidcProviderId()).toBe('oidc')+ })++ it('reads and trims OIDC_PROVIDER_ID', () => {+ vi.stubEnv('OIDC_PROVIDER_ID', ' corporate-idp ')+ expect(getOidcProviderId()).toBe('corporate-idp')+ })++ it('accepts every character the callback path allows', () => {+ vi.stubEnv('OIDC_PROVIDER_ID', 'corp.Id-1:$ok')+ expect(getOidcProviderId()).toBe('corp.Id-1:$ok')+ })++ it('rejects characters outside the callback charset', () => {+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {})+ vi.stubEnv('OIDC_PROVIDER_ID', 'corp/idp')++ expect(() => getOidcProviderId()).toThrow(/Invalid OIDC_PROVIDER_ID/)+ expect(warn).not.toHaveBeenCalled()+ })++ it('rejects ids over 128 characters', () => {+ vi.stubEnv('OIDC_PROVIDER_ID', 'a'.repeat(129))++ expect(() => getOidcProviderId()).toThrow(/Invalid OIDC_PROVIDER_ID/)+ })+})diff --git a/lib/auth/__tests__/oidc-implicit-sign-up.test.ts b/lib/auth/__tests__/oidc-implicit-sign-up.test.tsnew file mode 100644index 00000000..57e6d16d--- /dev/null+++ b/lib/auth/__tests__/oidc-implicit-sign-up.test.ts@@ -0,0 +1,125 @@+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'++import {+ resetAuthInstance,+ validateOidcUserCreation+} from '@/lib/auth/better-auth/config'++/**+ * The generic-OAuth/OIDC sign-up policy runs inside better-auth's+ * `user.validateUserInfo` seam, at user-creation time, against the live+ * user table:+ *+ * - invite/invalid sign-up mode blocks implicit account creation;+ * - open mode blocks it while the bootstrap window is open (empty user+ * table — the first account needs the emailed bootstrap link, which+ * proves mailbox ownership an OAuth callback cannot provide);+ * - open mode with existing accounts allows it;+ * - credential sign-ups (invitation/bootstrap policy) and an existing+ * identity signing in or linking are not affected;+ * - an unreadable user table fails closed.+ */+const oauthCreateUserSource = {+ action: 'create-user',+ method: 'oauth',+ oauth: { providerId: 'oidc' }+}++function validate(+ source: NonNullable<Parameters<typeof validateOidcUserCreation>[0]>['source'],+ countUsers: () => Promise<number>+) {+ return validateOidcUserCreation({ source }, countUsers)+}++beforeEach(() => {+ resetAuthInstance()+})++afterEach(() => {+ vi.unstubAllEnvs()+})++describe('validateOidcUserCreation (sign-up mode)', () => {+ it('rejects implicit creation in invite mode', async () => {+ vi.stubEnv('AUTH_SIGNUP_MODE', 'invite')+ const result = await validate(oauthCreateUserSource, async () => 5)++ expect(result?.error).toBe('sign_up_not_allowed')+ })++ it('rejects implicit creation when AUTH_SIGNUP_MODE is invalid', async () => {+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {})+ vi.stubEnv('AUTH_SIGNUP_MODE', 'invite-only')+ const result = await validate(oauthCreateUserSource, async () => 5)++ expect(result?.error).toBe('sign_up_unavailable')+ expect(warn).toHaveBeenCalled()+ })++ it('allows universal sign-up in open mode', async () => {+ vi.stubEnv('AUTH_SIGNUP_MODE', 'open')+ const result = await validate(oauthCreateUserSource, async () => 5)++ expect(result).toBeUndefined()+ })++ it('defaults to open mode when AUTH_SIGNUP_MODE is unset', async () => {+ const result = await validate(oauthCreateUserSource, async () => 5)++ expect(result).toBeUndefined()+ })+})++describe('validateOidcUserCreation (bootstrap window)', () => {+ it('rejects the first account through OAuth (empty user table)', async () => {+ vi.stubEnv('AUTH_SIGNUP_MODE', 'open')+ const result = await validate(oauthCreateUserSource, async () => 0)++ expect(result?.error).toBe('bootstrap_window_open')+ })++ it('allows implicit creation once an account exists', async () => {+ vi.stubEnv('AUTH_SIGNUP_MODE', 'open')+ const result = await validate(oauthCreateUserSource, async () => 1)++ expect(result).toBeUndefined()+ })++ it('fails closed when the user table cannot be read', async () => {+ vi.stubEnv('AUTH_SIGNUP_MODE', 'open')+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {})+ const result = await validate(oauthCreateUserSource, async () => {+ throw new Error('db unreachable')+ })++ expect(result?.error).toBe('sign_up_unavailable')+ expect(warn).toHaveBeenCalled()+ })+})++describe('validateOidcUserCreation (unrelated provisioning)', () => {+ it.each([+ // Credential sign-ups carry their own invitation/bootstrap policy.+ { action: 'create-user', method: 'email-password' },+ // An existing identity is never subject to the sign-up gate again.+ { action: 'sign-in', method: 'oauth', oauth: { providerId: 'oidc' } },+ { action: 'link-account', method: 'oauth', oauth: { providerId: 'oidc' } }+ ] as const)('does not gate %#', async sourceTest => {+ const result = await validate(+ sourceTest as typeof oauthCreateUserSource,+ async () => 0+ )++ expect(result).toBeUndefined()+ })++ it('does not gate a missing source', async () => {+ const result = await validateOidcUserCreation(+ { source: undefined },+ async () => 0+ )++ expect(result).toBeUndefined()+ })+})diff --git a/lib/auth/better-auth/config.ts b/lib/auth/better-auth/config.tsindex 69ee9461..5e488b1f 100644--- a/lib/auth/better-auth/config.ts+++ b/lib/auth/better-auth/config.ts@@ -2,11 +2,17 @@ import { betterAuth } from 'better-auth'import { drizzleAdapter } from 'better-auth/adapters/drizzle'import { APIError } from 'better-auth/api'import { nextCookies } from 'better-auth/next-js'-import { admin } from 'better-auth/plugins'+import { admin, genericOAuth } from 'better-auth/plugins'import { asc, count, eq, sql } from 'drizzle-orm'import { db } from '@/lib/db'+import {+ getOidcProviderId,+ getOidcProviderName as getOidcProviderNameUtil,+ isOidcConfigured as isOidcConfiguredUtil+} from '../oauth-config'+import { isSmtpConfigured, sendSmtpMail } from './mailer'import * as authSchema from './schema'@@ -20,6 +26,18 @@ export function isBetterAuthSmtpConfigured(): boolean {return isSmtpConfigured()}+/**+ * True when OIDC is configured: all required environment variables are set.+ * OIDC_SCOPE is optional and defaults to 'openid profile email'.+ */+export function isOidcConfigured(): boolean {+ return isOidcConfiguredUtil()+}++export function getOidcProviderName(): string {+ return getOidcProviderNameUtil()+}+/*** Canonical origin for absolute links delivered by email. Never derived* from request headers: `Origin` and `x-forwarded-host` are caller-@@ -252,8 +270,144 @@ export async function reElectBootstrapAdmin(): Promise<void> {)}+/**+ * Count the rows of the auth user table (live read, no caching).+ */+export async function countAuthUsers(): Promise<number> {+ const [row] = await db.select({ total: count() }).from(authSchema.user)+ return row?.total ?? 0+}++/**+ * Policy gate for implicit account creation through the generic OAuth/OIDC+ * provider, run by Better Auth's `user.validateUserInfo` seam whenever a+ * brand-new user record is about to be created. It resolves the live+ * user-table state on every call, so no gate state needs to be cached,+ * calibrated or reset across requests: the first account closing the+ * bootstrap window ends the restriction on the spot, in every process.+ *+ * Rules for `oauth`-source `create-user` actions:+ *+ * - `AUTH_SIGNUP_MODE=invite` (or an invalid mode): reject — members of+ * your IdP tenant are never handed an account implicitly. OIDC sign-in+ * works only for an identity already linked to a local account; an+ * account created through the credential flow (invitation token) is not+ * linked automatically, so invited members sign in with email and+ * password.+ * - Open mode with an empty user table: reject — the first account can+ * only come through the credential/bootstrap path, where the emailed+ * bootstrap link proves ownership of `BOOTSTRAP_ADMIN_EMAIL`; an OAuth+ * callback cannot prove mailbox ownership.+ * - Open mode otherwise: allow.+ *+ * Unaffected: credential sign-ups (invitation and bootstrap-address+ * policy live in their own flow) and an existing identity signing in+ * again or linking its account — those passed this gate when their+ * account was created.+ *+ * Fails closed: if the user count cannot be read, the sign-up is+ * rejected rather than silently allowed (Better Auth surfaces the+ * returned `error` as a 403 and redirects the callback to its error+ * endpoint).+ */+export async function validateOidcUserCreation(+ data: {+ source?: { action?: string; method?: string } | null | undefined+ },+ countUsers: () => Promise<number>+): Promise<{ error: string; errorDescription?: string } | undefined> {+ const source = data?.source+ if (!source || source.action !== 'create-user' || source.method !== 'oauth') {+ return // The gate applies only to new accounts arriving through OAuth.+ }++ try {+ if (getSignUpMode() !== 'open') {+ return {+ error: 'sign_up_not_allowed',+ errorDescription:+ 'Registration is by invitation. Sign in if you already have an account.'+ }+ }+ } catch (error) {+ console.warn('AUTH_SIGNUP_MODE is invalid — OIDC sign-up rejected.', error)+ return {+ error: 'sign_up_unavailable',+ errorDescription: 'User registration is not available.'+ }+ }++ try {+ if ((await countUsers()) === 0) {+ return {+ error: 'bootstrap_window_open',+ errorDescription:+ 'The first account of this deployment must be created through its emailed bootstrap link.'+ }+ }+ } catch (error) {+ console.warn(+ 'Could not read the user table to validate OIDC sign-up ' ++ '(bootstrap window unknown) — rejecting the registration.',+ error+ )+ return {+ error: 'sign_up_unavailable',+ errorDescription:+ 'Registration cannot be validated right now, please try again.'+ }+ }++ return undefined+}+function createAuth() {const smtpConfigured = isBetterAuthSmtpConfigured()+ const oidcConfigured = isOidcConfigured()++ // Conditionally spread the OIDC plugin inline so the concrete plugin+ // types reach betterAuth(): a `plugins: any[]` assertion would strip+ // every declared endpoint (e.g. admin's setRole/setUserPassword) from+ // the inferred auth.api type.+ const oidcPlugins = oidcConfigured+ ? [+ genericOAuth({+ config: [+ {+ // The provider id the plugin registers and the IdP callback+ // URL is derived from (OIDC_PROVIDER_ID, default 'oidc').+ providerId: getOidcProviderId(),+ // Trailing slash is a common typo: without stripping, the+ // discovery URL becomes "...//.well-known/..." and most IdPs+ // answer 404, which better-auth reports as "discovery left no+ // usable authorization endpoint or token exchange".+ discoveryUrl: `${process.env.OIDC_ISSUER?.trim().replace(/\/+$/, '')}/.well-known/openid-configuration`,+ clientId: process.env.OIDC_CLIENT_ID?.trim() ?? '',+ clientSecret: process.env.OIDC_CLIENT_SECRET?.trim() ?? '',+ scopes: (+ process.env.OIDC_SCOPE?.trim() || 'openid profile email'+ ).split(' '),+ pkce: true,+ // Map OIDC claims to Better Auth user fields+ // Note: Do not map 'id' here - Better Auth gets user identity from+ // the accountSubject (OIDC 'sub' claim) automatically+ mapProfileToUser: profile => ({+ email: profile.email as string,+ emailVerified: (profile.email_verified ?? false) as boolean,+ name: (profile.name ||+ profile.preferred_username ||+ profile.email) as string,+ image: profile.picture as string | undefined+ })+ }+ ]+ })+ ]+ : []++ // nextCookies must stay last: it re-applies the session cookie+ // through next/headers so server actions (signIn/signUp/signOut)+ // deliver it to the browser without a hand-written header copy.return betterAuth({appName: 'Morphic',@@ -270,7 +424,8 @@ function createAuth() {? async ({ user, token }) => {// better-auth's generated url targets its own// /api/auth/reset-password/:token endpoint, which this app does- // not expose (the API handler is not mounted), so it would 404.+ // not expose (the mounted HTTP surface is restricted to provider+ // callbacks, see app/api/auth/[...all]/route.ts), so it would 404.// Link the in-app page directly with the raw token instead; it// resets the password through the provider's server action.const origin = getEmailLinkOrigin()@@ -292,10 +447,15 @@ function createAuth() {}: undefined},- // nextCookies must stay last: it re-applies the session cookie- // through next/headers so server actions (signIn/signUp/signOut)- // deliver it to the browser without a hand-written header copy.- plugins: [admin({ defaultRole: 'user' }), nextCookies()],+ plugins: [admin({ defaultRole: 'user' }), ...oidcPlugins, nextCookies()],+ user: {+ // Policy gate for implicit account creation through the generic+ // OAuth/OIDC provider (sign-up mode + bootstrap window). Runs at+ // user-creation time against the live user table (see+ // validateOidcUserCreation), so no cached gate state is needed.+ validateUserInfo: (data, context) =>+ validateOidcUserCreation(data, countAuthUsers)+ },databaseHooks: {user: {create: {@@ -313,6 +473,7 @@ export type BetterAuth = ReturnType<typeof createAuth>let authInstance: BetterAuth | null = null+/** Lazily create the shared Better Auth instance. *//** Lazily create the shared Better Auth instance. */export function getAuth(): BetterAuth {if (!authInstance) {diff --git a/lib/auth/oauth-config.ts b/lib/auth/oauth-config.tsnew file mode 100644index 00000000..64496ace--- /dev/null+++ b/lib/auth/oauth-config.ts@@ -0,0 +1,58 @@+/**+ * OAuth configuration utilities that are safe to use in client components.+ * This file must not import server-only modules like next/headers.+ */++/**+ * The character superclass the provider-callback path may contain, used to+ * validate OIDC_PROVIDER_ID (mirrors the callback allowlist rules).+ */+export const OIDC_PROVIDER_ID_PATTERN = /^[A-Za-z0-9_.:$-]{1,128}$/++/**+ * Check if OIDC is fully configured.+ * Returns true if all required OIDC environment variables are set.+ *+ * Required variables:+ * - OIDC_ISSUER+ * - OIDC_CLIENT_ID+ * - OIDC_CLIENT_SECRET+ *+ * OIDC_SCOPE is optional and defaults to 'openid profile email'.+ */+export function isOidcConfigured(): boolean {+ return !!(+ process.env.OIDC_ISSUER?.trim() &&+ process.env.OIDC_CLIENT_ID?.trim() &&+ process.env.OIDC_CLIENT_SECRET?.trim()+ )+}++/**+ * The provider id the generic OAuth/OIDC plugin registers and that the+ * callback URL is derived from:+ *+ * <BETTER_AUTH_URL>/api/auth/callback/<OIDC_PROVIDER_ID>+ *+ * The OIDC `sub` claim is only unique per issuer, so accounts are keyed by+ * (providerId, sub): changing OIDC_ISSUER must come with a new provider id,+ * otherwise identities from the two issuers collide in the account table.+ */+export function getOidcProviderId(): string {+ const raw = process.env.OIDC_PROVIDER_ID?.trim() || 'oidc'+ if (!OIDC_PROVIDER_ID_PATTERN.test(raw)) {+ throw new Error(+ `Invalid OIDC_PROVIDER_ID "${process.env.OIDC_PROVIDER_ID}". ` ++ 'Use 1-128 characters of letters, digits or "_.:$-".'+ )+ }+ return raw+}++/**+ * Get the display name for the OIDC provider.+ * Returns the value of OIDC_PROVIDER_NAME or 'OIDC' as default.+ */+export function getOidcProviderName(): string {+ return process.env.OIDC_PROVIDER_NAME?.trim() || 'OIDC'+}diff --git a/lib/auth/providers/better-auth.ts b/lib/auth/providers/better-auth.tsindex 85491d32..f4c7edba 100644--- a/lib/auth/providers/better-auth.ts+++ b/lib/auth/providers/better-auth.ts@@ -1,4 +1,4 @@-import { headers } from 'next/headers'+import { cookies, headers } from 'next/headers'import { type NextRequest, NextResponse } from 'next/server'import { count, eq } from 'drizzle-orm'@@ -6,9 +6,11 @@ import { count, eq } from 'drizzle-orm'import {getAuth,getEmailLinkOrigin,+ getOidcProviderName,getSignUpMode,isBetterAuthSmtpConfigured,isBootstrapAccount,+ isOidcConfigured,reElectBootstrapAdmin} from '@/lib/auth/better-auth/config'import {@@ -22,6 +24,7 @@ import {import { sendSmtpMail } from '@/lib/auth/better-auth/mailer'import { user as authUser } from '@/lib/auth/better-auth/schema'import { checkRateLimit } from '@/lib/auth/rate-limit'+import { safeRedirectPath } from '@/lib/auth/redirect-target'import { getRequestOrigin } from '@/lib/auth/request'import type {AppUser,@@ -32,6 +35,8 @@ import type {} from '@/lib/auth/types'import { db } from '@/lib/db'+import { getOidcProviderId } from '../oauth-config'+/*** Whether an account already exists for the address. Used to decide whether* an uncertain sign-up failure (a throw after better-auth may have already@@ -209,15 +214,21 @@ export const betterAuthProvider: AuthProvider = {name: 'better-auth',get capabilities() {+ // Every OAuth sign-in routes through the canonical origin: the IdP's+ // redirect_uri and the post-sign-in redirect derive from+ // BETTER_AUTH_URL (see signInWithOAuth), so OIDC credentials alone do+ // not make the button work — mirror the passwordReset gate.+ const canonicalOrigin = getEmailLinkOrigin() !== ''+ const oidcConfigured = canonicalOrigin ? isOidcConfigured() : falsereturn {signUp: true,- passwordReset:- isBetterAuthSmtpConfigured() && getEmailLinkOrigin() !== '',+ passwordReset: isBetterAuthSmtpConfigured() && canonicalOrigin,deleteUser: true,- // Email/password only: no OAuth provider is wired into the local- // instance, and accounts are usable immediately without email- // confirmation.- oauth: false,+ // OAuth available when OIDC is configured or other OAuth providers are enabled+ oauth: oidcConfigured,+ // The button label and readiness come from the server: OIDC_* env vars+ // are invisible to the client bundle, so the form cannot decide itself.+ oauthProvider: oidcConfigured ? getOidcProviderName() : null,emailVerification: false,share: true}@@ -276,6 +287,67 @@ export const betterAuthProvider: AuthProvider = {return response},+ /**+ * Start the generic-OIDC sign-in: better-auth builds the authorization+ * URL (PKCE + nonce/state cookies) and returns it for a browser+ * redirect. Its callback endpoint must be mounted at /api/auth/*+ * (app/api/auth/[...all]/route.ts) for the flow to complete.+ */+ async signInWithOAuth(provider: string): Promise<AuthActionResult> {+ if (provider !== getOidcProviderId()) {+ // The generic OAuth plugin registers exactly one OIDC provider.+ return {+ success: false,+ error: `Provider "${provider}" is not configured.`+ }+ }+ if (!isOidcConfigured()) {+ return { success: false, error: 'OAuth sign-in is not configured.' }+ }+ // The IdP's redirect_uri is derived from better-auth's baseURL; the+ // canonical origin must exist for the flow to round-trip.+ if (getEmailLinkOrigin() === '') {+ return {+ success: false,+ error: 'BETTER_AUTH_URL must be set for OAuth sign-in.'+ }+ }++ // The login form carries the post-login destination in the short-lived+ // auth_next cookie. Consume it here as better-auth's callbackURL: after+ // the callback better-auth redirects the browser straight to that page.+ const headerStore = await headers()+ const cookieStore = await cookies()+ const nextPath =+ safeRedirectPath(cookieStore.get('auth_next')?.value ?? '') ?? '/'+ if (cookieStore.get('auth_next')) {+ cookieStore.delete('auth_next')+ }++ try {+ const result = await getAuth().api.signInSocial({+ body: {+ provider,+ callbackURL: `${getEmailLinkOrigin()}${nextPath}`+ },+ headers: headerStore+ })+ if (!result.redirect || !result.url) {+ return {+ success: false,+ error: 'The identity provider did not return an authorization URL.'+ }+ }+ return { success: true, redirectTo: result.url }+ } catch (error) {+ return {+ success: false,+ error:+ error instanceof Error ? error.message : 'An OAuth error occurred'+ }+ }+ },+async signIn({email,passworddiff --git a/lib/auth/types.ts b/lib/auth/types.tsindex bf554561..077b6fd1 100644--- a/lib/auth/types.ts+++ b/lib/auth/types.ts@@ -28,6 +28,12 @@ export interface AuthCapabilities {deleteUser: boolean/** Provider implements `signInWithOAuth` (e.g. a Google button can work). */oauth: boolean+ /**+ * Display name of the configured generic OIDC provider; null when the+ * provider's social login is something else (e.g. Google). Resolved on+ * the server: the client bundle cannot see OIDC_* environment variables.+ */+ oauthProvider?: string | null/** Sign-up requires confirming the email address before signing in. */emailVerification: boolean/** Sharing a chat records it under a real user (false in anonymous mode). */diff --git a/package.json b/package.jsonindex 2898069a..d44425aa 100644--- a/package.json+++ b/package.json@@ -71,7 +71,7 @@"@vercel/otel": "^2.1.3","ai": "^7.0.152","ai-sdk-ollama": "^4.5.1",- "better-auth": "^1.7.7",+ "better-auth": "^1.7.12","class-variance-authority": "^0.7.1","clsx": "^2.1.0","cmdk": "1.0.0",