Skip to content

An AI-powered search engine with a generative UI

refactor(auth): introduce pluggable auth provider interface (#1052)

Nathan Pride5931d08efe34
diff --git a/.env.local.example b/.env.local.example
index 04adf43c..f1294bb8 100644
--- a/.env.local.example
+++ b/.env.local.example
@@ -90,6 +90,12 @@ TAVILY_API_KEY=[YOUR_TAVILY_API_KEY]
ENABLE_AUTH=false
ANONYMOUS_USER_ID=anonymous-user
+# Auth provider selection. When unset, it is derived from the environment:
+# ENABLE_AUTH=false -> "none" (anonymous mode); otherwise -> "supabase".
+# Accepted values: supabase | better-auth | none
+# (better-auth requires a later release.) See docs/CONFIGURATION.md.
+# AUTH_PROVIDER=supabase
+
# To enable Supabase authentication for multi-user deployments:
# Get your project URL and API keys from: https://supabase.com/dashboard
# ENABLE_AUTH=true
diff --git a/README.md b/README.md
index f8128bc3..2ddb3896 100644
--- a/README.md
+++ b/README.md
@@ -98,6 +98,8 @@ TAVILY_API_KEY=your_tavily_key
To enable chat history, authentication, file upload, and other features, see [CONFIGURATION.md](./docs/CONFIGURATION.md).
+Auth is provided by `AUTH_PROVIDER` (`supabase | better-auth | none`). When unset it is derived from the existing environment: `ENABLE_AUTH=false` selects anonymous mode (`none`), otherwise Supabase auth is used — so existing deployments need no change. See [Authentication](./docs/CONFIGURATION.md#authentication).
+
For what a self-hosted instance sends outbound, and what is off by default, see [PRIVACY.md](./docs/PRIVACY.md).
3. Start the dev server:
diff --git a/app/api/chat/route.ts b/app/api/chat/route.ts
index 933c835a..c41e165f 100644
--- a/app/api/chat/route.ts
+++ b/app/api/chat/route.ts
@@ -9,6 +9,7 @@ import {
trackChatEvent
} from '@/lib/analytics'
import { getCurrentUser, getCurrentUserId } from '@/lib/auth/get-current-user'
+import { isAnonymousMode } from '@/lib/auth/provider'
import { getUserMessageIds } from '@/lib/db/actions'
import { generateId } from '@/lib/db/schema'
import { checkAndEnforceAdaptiveLimit } from '@/lib/rate-limit/adaptive-limit'
@@ -101,13 +102,10 @@ export async function POST(req: Request) {
const isSharePage = referer?.includes('/share/')
const authStart = performance.now()
- const currentUser =
- process.env.ENABLE_AUTH === 'false' ? null : await getCurrentUser()
+ const anonymous = isAnonymousMode()
+ const currentUser = anonymous ? null : await getCurrentUser()
const userId =
- currentUser?.id ??
- (process.env.ENABLE_AUTH === 'false'
- ? await getCurrentUserId()
- : undefined)
+ currentUser?.id ?? (anonymous ? await getCurrentUserId() : undefined)
perfTime('Auth completed', authStart)
if (isSharePage) {
@@ -249,7 +247,7 @@ export async function POST(req: Request) {
mode: searchMode,
attemptId: usageAttemptId,
messageId: message?.id ?? messageId,
- userCreatedAt: currentUser?.created_at,
+ userCreatedAt: currentUser?.createdAt,
now: usageNow
})
diff --git a/app/api/upload/__tests__/route.test.ts b/app/api/upload/__tests__/route.test.ts
index 3cf0cf1c..141b71db 100644
--- a/app/api/upload/__tests__/route.test.ts
+++ b/app/api/upload/__tests__/route.test.ts
@@ -86,6 +86,7 @@ describe('POST /api/upload', () => {
beforeEach(() => {
vi.clearAllMocks()
delete process.env.ENABLE_AUTH
+ delete process.env.AUTH_PROVIDER
vi.mocked(getObjectContentMd5).mockResolvedValue(md5OfUpload())
vi.mocked(dbActions.createLibraryFile).mockResolvedValue({
...EXISTING,
@@ -246,4 +247,13 @@ describe('POST /api/upload', () => {
expect(dbActions.findChatFileCandidates).not.toHaveBeenCalled()
expect(send).toHaveBeenCalledOnce()
})
+
+ it('skips the lookup when AUTH_PROVIDER=none with ENABLE_AUTH unset', async () => {
+ process.env.AUTH_PROVIDER = 'none'
+
+ await POST(uploadRequest())
+
+ expect(dbActions.findChatFileCandidates).not.toHaveBeenCalled()
+ expect(send).toHaveBeenCalledOnce()
+ })
})
diff --git a/app/api/upload/route.ts b/app/api/upload/route.ts
index 16d122c5..7da15f5f 100644
--- a/app/api/upload/route.ts
+++ b/app/api/upload/route.ts
@@ -5,6 +5,7 @@ import { createHash } from 'node:crypto'
import { capture } from '@/lib/analytics/dispatch'
import { getCurrentUserId } from '@/lib/auth/get-current-user'
+import { isAnonymousMode } from '@/lib/auth/provider'
import * as dbActions from '@/lib/db/actions'
import {
detectFileMediaType,
@@ -68,7 +69,7 @@ export async function POST(req: NextRequest) {
{ status: 400 }
)
}
- const isAnonymous = process.env.ENABLE_AUTH === 'false'
+ const isAnonymous = isAnonymousMode()
const buffer = Buffer.from(await file.arrayBuffer())
// The browser reports file.type from the name, so the check above says
diff --git a/app/api/usage/route.ts b/app/api/usage/route.ts
index 6704f412..d785c9fc 100644
--- a/app/api/usage/route.ts
+++ b/app/api/usage/route.ts
@@ -20,7 +20,7 @@ export async function GET() {
const usage = await getUsageBudget({
userId: user.id,
- userCreatedAt: user.created_at
+ userCreatedAt: user.createdAt
})
if (!usage) {
return NextResponse.json(
diff --git a/app/layout.tsx b/app/layout.tsx
index e04fb142..c53588bf 100644
--- a/app/layout.tsx
+++ b/app/layout.tsx
@@ -3,10 +3,10 @@ import { Inter as FontSans } from 'next/font/google'
import { Analytics } from '@vercel/analytics/next'
-import { getCurrentUserId } from '@/lib/auth/get-current-user'
+import { getCurrentUser, getCurrentUserId } from '@/lib/auth/get-current-user'
+import { getAuthProvider } from '@/lib/auth/provider'
+import { AppUserProvider } from '@/lib/contexts/app-user-context'
import { UserProvider } from '@/lib/contexts/user-context'
-import { hasSupabasePublicConfig } from '@/lib/supabase/keys'
-import { createClient } from '@/lib/supabase/server'
import {
ENFORCEMENT,
getUsageBudget,
@@ -66,15 +66,8 @@ export default async function RootLayout({
}: Readonly<{
children: React.ReactNode
}>) {
- let user = null
-
- if (hasSupabasePublicConfig()) {
- const supabase = await createClient()
- const {
- data: { user: supabaseUser }
- } = await supabase.auth.getUser()
- user = supabaseUser
- }
+ const user = await getCurrentUser()
+ const capabilities = getAuthProvider().capabilities
const userId = user?.id ?? (await getCurrentUserId())
const isCloudDeployment = process.env.MORPHIC_CLOUD_DEPLOYMENT === 'true'
@@ -89,7 +82,7 @@ export default async function RootLayout({
usageBudgetEnabled && user
? await getUsageBudget({
userId: user.id,
- userCreatedAt: user.created_at
+ userCreatedAt: user.createdAt
})
: null
const initialUsage = usageSnapshot
@@ -119,26 +112,28 @@ export default async function RootLayout({
disableTransitionOnChange
>
<PostHogProvider userId={user?.id ?? null}>
- <UserProvider hasUser={!!userId}>
- <SidebarProvider defaultOpen={false}>
- <LibraryProvider>
- <UsageBudgetProvider
- key={user?.id ?? 'guest'}
- initialUsage={initialUsage}
- enabled={usageBudgetEnabled}
- >
- {userId && <AppSidebar />}
- <KeyboardShortcutHandler />
- <div className="flex flex-col flex-1 min-w-0">
- <Header user={user} />
- <main className="flex flex-1 min-h-0 min-w-0 overflow-hidden">
- <ArtifactRoot>{children}</ArtifactRoot>
- </main>
- </div>
- </UsageBudgetProvider>
- </LibraryProvider>
- </SidebarProvider>
- </UserProvider>
+ <AppUserProvider user={user} capabilities={capabilities}>
+ <UserProvider hasUser={!!userId}>
+ <SidebarProvider defaultOpen={false}>
+ <LibraryProvider>
+ <UsageBudgetProvider
+ key={user?.id ?? 'guest'}
+ initialUsage={initialUsage}
+ enabled={usageBudgetEnabled}
+ >
+ {userId && <AppSidebar />}
+ <KeyboardShortcutHandler />
+ <div className="flex flex-col flex-1 min-w-0">
+ <Header user={user} />
+ <main className="flex flex-1 min-h-0 min-w-0 overflow-hidden">
+ <ArtifactRoot>{children}</ArtifactRoot>
+ </main>
+ </div>
+ </UsageBudgetProvider>
+ </LibraryProvider>
+ </SidebarProvider>
+ </UserProvider>
+ </AppUserProvider>
</PostHogProvider>
<Toaster />
{isCloudDeployment && <Analytics />}
diff --git a/app/page.tsx b/app/page.tsx
index 0c093f91..a93d1bf5 100644
--- a/app/page.tsx
+++ b/app/page.tsx
@@ -1,4 +1,5 @@
import { getCurrentUserId } from '@/lib/auth/get-current-user'
+import { isAnonymousMode } from '@/lib/auth/provider'
import { getModelSelectorData } from '@/lib/model-selector/get-model-selector-data'
import { Chat } from '@/components/chat'
@@ -6,7 +7,7 @@ import { Chat } from '@/components/chat'
export default async function Page() {
const userId = await getCurrentUserId()
const isCloudDeployment = process.env.MORPHIC_CLOUD_DEPLOYMENT === 'true'
- const libraryAvailable = process.env.ENABLE_AUTH !== 'false'
+ const libraryAvailable = !isAnonymousMode()
const modelSelectorData = await getModelSelectorData()
return (
diff --git a/app/search/[id]/page.tsx b/app/search/[id]/page.tsx
index 1219762e..612b25a0 100644
--- a/app/search/[id]/page.tsx
+++ b/app/search/[id]/page.tsx
@@ -4,6 +4,7 @@ import { UIMessage } from 'ai'
import { loadChat } from '@/lib/actions/chat'
import { getCurrentUserId } from '@/lib/auth/get-current-user'
+import { isAnonymousMode } from '@/lib/auth/provider'
import { getModelSelectorData } from '@/lib/model-selector/get-model-selector-data'
import { Chat } from '@/components/chat'
@@ -45,7 +46,7 @@ export default async function SearchPage(props: {
const messages: UIMessage[] = chat.messages
const isCloudDeployment = process.env.MORPHIC_CLOUD_DEPLOYMENT === 'true'
- const libraryAvailable = process.env.ENABLE_AUTH !== 'false'
+ const libraryAvailable = !isAnonymousMode()
const modelSelectorData = await getModelSelectorData()
return (
diff --git a/app/search/page.tsx b/app/search/page.tsx
index 077daa05..4b973689 100644
--- a/app/search/page.tsx
+++ b/app/search/page.tsx
@@ -1,6 +1,7 @@
import { redirect } from 'next/navigation'
import { getCurrentUserId } from '@/lib/auth/get-current-user'
+import { isAnonymousMode } from '@/lib/auth/provider'
import { getModelSelectorData } from '@/lib/model-selector/get-model-selector-data'
import { generateUUID } from '@/lib/utils'
@@ -19,7 +20,7 @@ export default async function SearchPage(props: {
const id = generateUUID()
const userId = await getCurrentUserId()
const isCloudDeployment = process.env.MORPHIC_CLOUD_DEPLOYMENT === 'true'
- const libraryAvailable = process.env.ENABLE_AUTH !== 'false'
+ const libraryAvailable = !isAnonymousMode()
const modelSelectorData = await getModelSelectorData()
return (
diff --git a/components/__tests__/account-settings-dialog.test.tsx b/components/__tests__/account-settings-dialog.test.tsx
new file mode 100644
index 00000000..10809955
--- /dev/null
+++ b/components/__tests__/account-settings-dialog.test.tsx
@@ -0,0 +1,105 @@
+import { fireEvent, render, screen, waitFor } from '@testing-library/react'
+import { beforeEach, describe, expect, it, vi } from 'vitest'
+
+import { deleteAccount } from '@/lib/actions/account'
+import { signOut } from '@/lib/actions/auth'
+import type { AppUser } from '@/lib/auth/types'
+import { AppUserProvider } from '@/lib/contexts/app-user-context'
+
+import { AccountSettingsDialog } from '@/components/account-settings-dialog'
+
+vi.mock('@/lib/actions/account', () => ({
+ deleteAccount: vi.fn()
+}))
+
+vi.mock('@/lib/actions/auth', () => ({
+ signOut: vi.fn()
+}))
+
+vi.mock('sonner', () => ({
+ toast: { success: vi.fn(), error: vi.fn() }
+}))
+
+const { mockPush, mockRefresh } = vi.hoisted(() => ({
+ mockPush: vi.fn(),
+ mockRefresh: vi.fn()
+}))
+
+vi.mock('next/navigation', () => ({
+ useRouter: () => ({ push: mockPush, refresh: mockRefresh })
+}))
+
+const user: AppUser = {
+ id: 'user-1',
+ email: '[email protected]',
+ name: 'Test Person'
+}
+
+const capabilities = { signUp: true, passwordReset: true, deleteUser: true }
+
+function renderDialog(override: Partial<typeof capabilities> = {}) {
+ return render(
+ <AppUserProvider
+ user={user}
+ capabilities={{ ...capabilities, ...override }}
+ >
+ <AccountSettingsDialog open onOpenChange={vi.fn()} user={user} />
+ </AppUserProvider>
+ )
+}
+
+describe('AccountSettingsDialog', () => {
+ beforeEach(() => {
+ vi.clearAllMocks()
+ })
+
+ it('shows the delete-account entry point when the provider supports it', () => {
+ renderDialog()
+ expect(
+ screen.getByRole('button', { name: 'Delete account' })
+ ).toBeInTheDocument()
+ })
+
+ it('hides the delete-account entry point when the provider lacks the capability', () => {
+ renderDialog({ deleteUser: false })
+ expect(
+ screen.queryByRole('button', { name: 'Delete account' })
+ ).not.toBeInTheDocument()
+ })
+
+ it('deletes the account and clears the session', async () => {
+ vi.mocked(deleteAccount).mockResolvedValue({ success: true })
+ vi.mocked(signOut).mockResolvedValue({ success: true })
+ renderDialog()
+
+ fireEvent.click(screen.getByRole('button', { name: 'Delete account' }))
+ fireEvent.click(
+ screen.getAllByRole('button', { name: 'Delete account' }).at(-1)!
+ )
+
+ await waitFor(() => {
+ expect(deleteAccount).toHaveBeenCalledTimes(1)
+ expect(signOut).toHaveBeenCalledTimes(1)
+ expect(mockPush).toHaveBeenCalledWith('/')
+ expect(mockRefresh).toHaveBeenCalled()
+ })
+ })
+
+ it('surfaces deletion errors', async () => {
+ vi.mocked(deleteAccount).mockResolvedValue({
+ success: false,
+ error: 'Account deletion is unavailable in anonymous mode.'
+ })
+ renderDialog()
+
+ fireEvent.click(screen.getByRole('button', { name: 'Delete account' }))
+ fireEvent.click(
+ screen.getAllByRole('button', { name: 'Delete account' }).at(-1)!
+ )
+
+ await waitFor(() => {
+ expect(deleteAccount).toHaveBeenCalledTimes(1)
+ expect(signOut).not.toHaveBeenCalled()
+ })
+ })
+})
diff --git a/components/__tests__/login-form.test.tsx b/components/__tests__/login-form.test.tsx
new file mode 100644
index 00000000..0b6540d8
--- /dev/null
+++ b/components/__tests__/login-form.test.tsx
@@ -0,0 +1,124 @@
+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 { AppUserProvider } from '@/lib/contexts/app-user-context'
+
+import { LoginForm } from '@/components/login-form'
+
+vi.mock('@/lib/actions/auth', () => ({
+ signIn: vi.fn(),
+ signInWithGoogle: vi.fn()
+}))
+
+const { mockPush, mockRefresh } = vi.hoisted(() => ({
+ mockPush: vi.fn(),
+ mockRefresh: vi.fn()
+}))
+
+vi.mock('next/navigation', () => ({
+ useRouter: () => ({ push: mockPush, refresh: mockRefresh })
+}))
+
+const capabilities = { signUp: true, passwordReset: true, deleteUser: true }
+
+function renderForm(override: Partial<typeof capabilities> = {}, user = null) {
+ return render(
+ <AppUserProvider
+ user={user}
+ capabilities={{ ...capabilities, ...override }}
+ >
+ <LoginForm />
+ </AppUserProvider>
+ )
+}
+
+describe('LoginForm', () => {
+ beforeEach(() => {
+ vi.clearAllMocks()
+ })
+
+ it('signs in through the auth server action and refreshes the router', async () => {
+ vi.mocked(signIn).mockResolvedValue({ success: true })
+ renderForm()
+
+ fireEvent.change(screen.getByLabelText('Email'), {
+ target: { value: '[email protected]' }
+ })
+ fireEvent.change(screen.getByLabelText('Password'), {
+ target: { value: 'secret' }
+ })
+ fireEvent.click(screen.getByRole('button', { name: 'Sign In' }))
+
+ await waitFor(() => {
+ expect(signIn).toHaveBeenCalledWith({
+ email: '[email protected]',
+ password: 'secret'
+ })
+ expect(mockPush).toHaveBeenCalledWith('/')
+ expect(mockRefresh).toHaveBeenCalled()
+ })
+ })
+
+ it('shows the error returned by the auth provider', async () => {
+ vi.mocked(signIn).mockResolvedValue({
+ success: false,
+ error: 'Invalid login credentials'
+ })
+ renderForm()
+
+ fireEvent.change(screen.getByLabelText('Email'), {
+ target: { value: '[email protected]' }
+ })
+ fireEvent.change(screen.getByLabelText('Password'), {
+ target: { value: 'wrong' }
+ })
+ fireEvent.click(screen.getByRole('button', { name: 'Sign In' }))
+
+ await waitFor(() => {
+ expect(screen.getByText('Invalid login credentials')).toBeInTheDocument()
+ })
+ expect(mockPush).not.toHaveBeenCalled()
+ })
+
+ it('redirects to the identity provider for Google sign-in', async () => {
+ const originalLocation = window.location
+ Object.defineProperty(window, 'location', {
+ configurable: true,
+ writable: true,
+ value: { href: '' }
+ })
+ vi.mocked(signInWithGoogle).mockResolvedValue({
+ success: true,
+ redirectTo: 'https://accounts.google.com/authorize'
+ })
+ renderForm()
+
+ fireEvent.click(screen.getByRole('button', { name: 'Sign In with Google' }))
+
+ await waitFor(() => {
+ expect(signInWithGoogle).toHaveBeenCalled()
+ expect(window.location.href).toBe('https://accounts.google.com/authorize')
+ })
+
+ Object.defineProperty(window, 'location', {
+ configurable: true,
+ writable: true,
+ value: originalLocation
+ })
+ })
+
+ it('offers password recovery when the provider supports it', () => {
+ renderForm()
+ expect(
+ screen.getByRole('link', { name: 'Forgot password?' })
+ ).toBeInTheDocument()
+ })
+
+ it('hides password recovery when the provider lacks the capability', () => {
+ renderForm({ passwordReset: false })
+ expect(
+ screen.queryByRole('link', { name: 'Forgot password?' })
+ ).not.toBeInTheDocument()
+ })
+})
diff --git a/components/__tests__/usage-budget.test.tsx b/components/__tests__/usage-budget.test.tsx
index 7bdddd88..81a9a0bd 100644
--- a/components/__tests__/usage-budget.test.tsx
+++ b/components/__tests__/usage-budget.test.tsx
@@ -1,9 +1,10 @@
import React from 'react'
-import type { User } from '@supabase/supabase-js'
import { fireEvent, render, screen, waitFor } from '@testing-library/react'
import { beforeEach, describe, expect, test, vi } from 'vitest'
+import type { AppUser } from '@/lib/auth/types'
+
import {
UsageBudgetProvider,
UsageBudgetWarning,
@@ -17,10 +18,6 @@ vi.mock('next/navigation', () => ({
useRouter: () => ({ push: vi.fn(), refresh: vi.fn() })
}))
-vi.mock('@/lib/supabase/client', () => ({
- createClient: () => ({ auth: { signOut: vi.fn() } })
-}))
-
vi.mock('@/components/account-settings-dialog', () => ({
AccountSettingsDialog: () => null
}))
@@ -64,11 +61,11 @@ vi.mock('@/components/ui/dropdown-menu', () => ({
DropdownMenuTrigger: ({ children }: { children: React.ReactNode }) => children
}))
-const user = {
+const user: AppUser = {
id: 'user-1',
- user_metadata: { full_name: 'Test Person' }
-} as unknown as User
+ name: 'Test Person'
+}
const initialUsage = {
remaining: 82,
diff --git a/components/__tests__/user-menu.test.tsx b/components/__tests__/user-menu.test.tsx
new file mode 100644
index 00000000..9f826257
--- /dev/null
+++ b/components/__tests__/user-menu.test.tsx
@@ -0,0 +1,117 @@
+import React from 'react'
+
+import { fireEvent, render, screen, waitFor } from '@testing-library/react'
+import { beforeEach, describe, expect, it, vi } from 'vitest'
+
+import { signOut } from '@/lib/actions/auth'
+import type { AppUser } from '@/lib/auth/types'
+import { AppUserProvider } from '@/lib/contexts/app-user-context'
+
+import UserMenu from '@/components/user-menu'
+
+vi.mock('@/lib/actions/auth', () => ({
+ signOut: vi.fn()
+}))
+
+const { mockPush, mockRefresh } = vi.hoisted(() => ({
+ mockPush: vi.fn(),
+ mockRefresh: vi.fn()
+}))
+
+vi.mock('next/navigation', () => ({
+ useRouter: () => ({ push: mockPush, refresh: mockRefresh })
+}))
+
+vi.mock('@/components/usage-budget-provider', () => ({
+ useUsageBudget: () => ({
+ usage: null,
+ isLow: false,
+ isExhausted: false,
+ refreshUsage: vi.fn()
+ })
+}))
+
+vi.mock('@/components/account-settings-dialog', () => ({
+ AccountSettingsDialog: () => null
+}))
+
+vi.mock('@/components/external-link-items', () => ({
+ ExternalLinkItems: () => null
+}))
+
+vi.mock('@/components/ui/dropdown-menu', () => ({
+ DropdownMenu: ({ children }: { children: React.ReactNode }) => children,
+ DropdownMenuContent: ({ children }: { children: React.ReactNode }) => (
+ <div role="menu">{children}</div>
+ ),
+ DropdownMenuItem: ({
+ children,
+ onSelect,
+ onClick
+ }: {
+ children: React.ReactNode
+ onSelect?: (event: { preventDefault: () => void }) => void
+ onClick?: () => void
+ }) => (
+ <button
+ role="menuitem"
+ onClick={() => {
+ onSelect?.({ preventDefault: vi.fn() })
+ onClick?.()
+ }}
+ >
+ {children}
+ </button>
+ ),
+ DropdownMenuLabel: ({ children }: { children: React.ReactNode }) => children,
+ DropdownMenuSeparator: () => <hr />,
+ DropdownMenuSub: ({ children }: { children: React.ReactNode }) => children,
+ DropdownMenuSubContent: ({ children }: { children: React.ReactNode }) =>
+ children,
+ DropdownMenuSubTrigger: ({ children }: { children: React.ReactNode }) => (
+ <div>{children}</div>
+ ),
+ DropdownMenuTrigger: ({ children }: { children: React.ReactNode }) => children
+}))
+
+const user: AppUser = {
+ id: 'user-1',
+ email: '[email protected]',
+ name: 'Test Person'
+}
+
+const capabilities = { signUp: true, passwordReset: true, deleteUser: true }
+
+describe('UserMenu', () => {
+ beforeEach(() => {
+ vi.clearAllMocks()
+ })
+
+ it('signs out through the auth server action and refreshes the router', async () => {
+ vi.mocked(signOut).mockResolvedValue({ success: true })
+ render(
+ <AppUserProvider user={user} capabilities={capabilities}>
+ <UserMenu user={user} />
+ </AppUserProvider>
+ )
+
+ fireEvent.click(screen.getByRole('menuitem', { name: /Logout/ }))
+
+ await waitFor(() => {
+ expect(signOut).toHaveBeenCalledTimes(1)
+ expect(mockPush).toHaveBeenCalledWith('/')
+ expect(mockRefresh).toHaveBeenCalled()
+ })
+ })
+
+ it('shows the user profile information', () => {
+ render(
+ <AppUserProvider user={user} capabilities={capabilities}>
+ <UserMenu user={user} />
+ </AppUserProvider>
+ )
+
+ expect(screen.getByText('Test Person')).toBeInTheDocument()
+ expect(screen.getByText('[email protected]')).toBeInTheDocument()
+ })
+})
diff --git a/components/account-settings-dialog.tsx b/components/account-settings-dialog.tsx
index 6a95e091..2b2f9f5e 100644
--- a/components/account-settings-dialog.tsx
+++ b/components/account-settings-dialog.tsx
@@ -3,7 +3,6 @@
import { useState, useTransition } from 'react'
import { useRouter } from 'next/navigation'
-import type { User } from '@supabase/supabase-js'
import {
IconDeviceLaptop as Laptop,
IconMoon as Moon,
@@ -13,7 +12,9 @@ import {
import { toast } from 'sonner'
import { deleteAccount } from '@/lib/actions/account'
-import { createClient } from '@/lib/supabase/client'
+import { signOut } from '@/lib/actions/auth'
+import type { AppUser } from '@/lib/auth/types'
+import { useAuthCapabilities } from '@/lib/contexts/app-user-context'
import {
AlertDialog,
@@ -42,7 +43,7 @@ import { useTheme } from '@/components/theme-provider'
interface AccountSettingsDialogProps {
open: boolean
onOpenChange: (open: boolean) => void
- user: User
+ user: AppUser
}
const themeOptions = [
@@ -58,12 +59,12 @@ export function AccountSettingsDialog({
}: AccountSettingsDialogProps) {
const router = useRouter()
const { setTheme, theme } = useTheme()
+ const capabilities = useAuthCapabilities()
const [isDeleting, startDeleteTransition] = useTransition()
const [confirmOpen, setConfirmOpen] = useState(false)
const activeTheme = theme ?? 'system'
- const userName =
- user.user_metadata?.full_name || user.user_metadata?.name || 'User'
+ const userName = user.name || 'User'
const handleDeleteAccount = () => {
startDeleteTransition(async () => {
@@ -71,7 +72,7 @@ export function AccountSettingsDialog({
if (result.success) {
try {
- await createClient().auth.signOut()
+ await signOut()
} catch (error) {
console.error('Failed to clear client session:', error)
}
@@ -150,64 +151,68 @@ export function AccountSettingsDialog({
</div>
</section>
- <Separator />
-
- <section className="grid gap-3">
- <div className="grid gap-1">
- <h3 className="text-sm font-medium text-destructive">
- Delete account
- </h3>
- <p className="text-sm text-muted-foreground">
- Permanently delete your account, chat history, and uploaded
- files. This action cannot be undone.
- </p>
- </div>
-
- <AlertDialog
- open={confirmOpen}
- onOpenChange={nextOpen => {
- if (!isDeleting) {
- setConfirmOpen(nextOpen)
- }
- }}
- >
- <AlertDialogTrigger asChild>
- <Button
- type="button"
- variant="destructive"
- className="w-fit gap-2"
- disabled={isDeleting}
+ {capabilities.deleteUser && (
+ <>
+ <Separator />
+
+ <section className="grid gap-3">
+ <div className="grid gap-1">
+ <h3 className="text-sm font-medium text-destructive">
+ Delete account
+ </h3>
+ <p className="text-sm text-muted-foreground">
+ Permanently delete your account, chat history, and uploaded
+ files. This action cannot be undone.
+ </p>
+ </div>
+
+ <AlertDialog
+ open={confirmOpen}
+ onOpenChange={nextOpen => {
+ if (!isDeleting) {
+ setConfirmOpen(nextOpen)
+ }
+ }}
>
- <Trash2 className="size-4" />
- Delete account
- </Button>
- </AlertDialogTrigger>
- <AlertDialogContent>
- <AlertDialogHeader>
- <AlertDialogTitle>Delete your account?</AlertDialogTitle>
- <AlertDialogDescription>
- This action cannot be undone. Your account, chat history,
- and uploaded files will be permanently deleted.
- </AlertDialogDescription>
- </AlertDialogHeader>
- <AlertDialogFooter>
- <AlertDialogCancel disabled={isDeleting}>
- Cancel
- </AlertDialogCancel>
- <AlertDialogAction
- disabled={isDeleting}
- onClick={event => {
- event.preventDefault()
- handleDeleteAccount()
- }}
- className="bg-destructive text-destructive-foreground hover:bg-destructive/90"
- >
- {isDeleting ? <Spinner /> : 'Delete account'}
- </AlertDialogAction>
- </AlertDialogFooter>
- </AlertDialogContent>
- </AlertDialog>
- </section>
+ <AlertDialogTrigger asChild>
+ <Button
+ type="button"
+ variant="destructive"
+ className="w-fit gap-2"
+ disabled={isDeleting}
+ >
+ <Trash2 className="size-4" />
+ Delete account
+ </Button>
+ </AlertDialogTrigger>
+ <AlertDialogContent>
+ <AlertDialogHeader>
+ <AlertDialogTitle>Delete your account?</AlertDialogTitle>
+ <AlertDialogDescription>
+ This action cannot be undone. Your account, chat
+ history, and uploaded files will be permanently deleted.
+ </AlertDialogDescription>
+ </AlertDialogHeader>
+ <AlertDialogFooter>
+ <AlertDialogCancel disabled={isDeleting}>
+ Cancel
+ </AlertDialogCancel>
+ <AlertDialogAction
+ disabled={isDeleting}
+ onClick={event => {
+ event.preventDefault()
+ handleDeleteAccount()
+ }}
+ className="bg-destructive text-destructive-foreground hover:bg-destructive/90"
+ >
+ {isDeleting ? <Spinner /> : 'Delete account'}
+ </AlertDialogAction>
+ </AlertDialogFooter>
+ </AlertDialogContent>
+ </AlertDialog>
+ </section>
+ </>
+ )}
</div>
</DialogContent>
</Dialog>
diff --git a/components/forgot-password-form.tsx b/components/forgot-password-form.tsx
index ed62f825..91f442c4 100644
--- a/components/forgot-password-form.tsx
+++ b/components/forgot-password-form.tsx
@@ -3,7 +3,7 @@
import { useState } from 'react'
import Link from 'next/link'
-import { createClient } from '@/lib/supabase/client'
+import { requestPasswordReset } from '@/lib/actions/auth'
import { cn } from '@/lib/utils/index'
import { Button } from '@/components/ui/button'
@@ -28,16 +28,12 @@ export function ForgotPasswordForm({
const handleForgotPassword = async (e: React.FormEvent) => {
e.preventDefault()
- const supabase = createClient()
setIsLoading(true)
setError(null)
try {
- // The url which will be included in the email. This URL needs to be configured in your redirect URLs in the Supabase dashboard at https://supabase.com/dashboard/project/_/auth/url-configuration
- const { error } = await supabase.auth.resetPasswordForEmail(email, {
- redirectTo: `${window.location.origin}/auth/update-password`
- })
- if (error) throw error
+ const result = await requestPasswordReset(email)
+ if (!result.success) throw new Error(result.error ?? 'An error occurred')
setSuccess(true)
} catch (error: unknown) {
setError(error instanceof Error ? error.message : 'An error occurred')
diff --git a/components/header.tsx b/components/header.tsx
index 4bc50d60..83a55265 100644
--- a/components/header.tsx
+++ b/components/header.tsx
@@ -4,8 +4,7 @@
import React, { useState } from 'react'
import { usePathname } from 'next/navigation'
-import { User } from '@supabase/supabase-js'
-
+import type { AppUser } from '@/lib/auth/types'
import { cn } from '@/lib/utils'
import { useSidebar } from '@/components/ui/sidebar'
@@ -17,7 +16,7 @@ import GuestMenu from './guest-menu' // Import the new GuestMenu component
import UserMenu from './user-menu'
interface HeaderProps {
- user: User | null
+ user: AppUser | null
}
export const Header: React.FC<HeaderProps> = ({ user }) => {
diff --git a/components/login-form.tsx b/components/login-form.tsx
index 6693d450..39adde24 100644
--- a/components/login-form.tsx
+++ b/components/login-form.tsx
@@ -4,7 +4,8 @@ import { useState } from 'react'
import Link from 'next/link'
import { useRouter } from 'next/navigation'
-import { createClient } from '@/lib/supabase/client'
+import { signIn, signInWithGoogle } from '@/lib/actions/auth'
+import { useAuthCapabilities } from '@/lib/contexts/app-user-context'
import { cn } from '@/lib/utils/index'
import { Button } from '@/components/ui/button'
@@ -30,19 +31,16 @@ export function LoginForm({
const [error, setError] = useState<string | null>(null)
const [isLoading, setIsLoading] = useState(false)
const router = useRouter()
+ const capabilities = useAuthCapabilities()
const handleLogin = async (e: React.FormEvent) => {
e.preventDefault()
- const supabase = createClient()
setIsLoading(true)
setError(null)
try {
- const { error } = await supabase.auth.signInWithPassword({
- email,
- password
- })
- if (error) throw error
+ const result = await signIn({ email, password })
+ if (!result.success) throw new Error(result.error ?? 'An error occurred')
// Redirect to root and refresh to ensure server components get updated session
router.push('/')
router.refresh()
@@ -54,18 +52,16 @@ export function LoginForm({
}
const handleSocialLogin = async () => {
- const supabase = createClient()
setIsLoading(true)
setError(null)
try {
- const { error } = await supabase.auth.signInWithOAuth({
- provider: 'google',
- options: {
- redirectTo: `${location.origin}/auth/oauth`
- }
- })
- if (error) throw error
+ const result = await signInWithGoogle()
+ 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'
@@ -124,12 +120,14 @@ export function LoginForm({
<div className="grid gap-2">
<div className="flex items-center">
<Label htmlFor="password">Password</Label>
- <Link
- href="/auth/forgot-password"
- className="ml-auto inline-block text-sm underline-offset-4 hover:underline"
- >
- Forgot password?
- </Link>
+ {capabilities.passwordReset && (
+ <Link
+ href="/auth/forgot-password"
+ className="ml-auto inline-block text-sm underline-offset-4 hover:underline"
+ >
+ Forgot password?
+ </Link>
+ )}
</div>
<PasswordInput
id="password"
diff --git a/components/sign-up-form.tsx b/components/sign-up-form.tsx
index bad99d65..1e1853f0 100644
--- a/components/sign-up-form.tsx
+++ b/components/sign-up-form.tsx
@@ -3,7 +3,7 @@ import { useState } from 'react'
import Link from 'next/link'
import { useRouter } from 'next/navigation'
-import { createClient } from '@/lib/supabase/client'
+import { signUp } from '@/lib/actions/auth'
import { cn } from '@/lib/utils/index'
import { Button } from '@/components/ui/button'
@@ -32,7 +32,6 @@ export function SignUpForm({
const handleSignUp = async (e: React.FormEvent) => {
e.preventDefault()
- const supabase = createClient()
setIsLoading(true)
setError(null)
@@ -43,14 +42,8 @@ export function SignUpForm({
}
try {
- const { error } = await supabase.auth.signUp({
- email,
- password,
- options: {
- emailRedirectTo: `${window.location.origin}/`
- }
- })
- if (error) throw error
+ const result = await signUp({ email, password })
+ if (!result.success) throw new Error(result.error ?? 'An error occurred')
router.push('/auth/sign-up-success')
} catch (error: unknown) {
setError(error instanceof Error ? error.message : 'An error occurred')
diff --git a/components/update-password-form.tsx b/components/update-password-form.tsx
index 70cc4e7a..dff17336 100644
--- a/components/update-password-form.tsx
+++ b/components/update-password-form.tsx
@@ -3,7 +3,7 @@
import { useState } from 'react'
import { useRouter } from 'next/navigation'
-import { createClient } from '@/lib/supabase/client'
+import { updatePassword } from '@/lib/actions/auth'
import { cn } from '@/lib/utils/index'
import { Button } from '@/components/ui/button'
@@ -28,13 +28,12 @@ export function UpdatePasswordForm({
const handleForgotPassword = async (e: React.FormEvent) => {
e.preventDefault()
- const supabase = createClient()
setIsLoading(true)
setError(null)
try {
- const { error } = await supabase.auth.updateUser({ password })
- if (error) throw error
+ const result = await updatePassword(password)
+ if (!result.success) throw new Error(result.error ?? 'An error occurred')
// Redirect to root and refresh to ensure server components get updated session.
router.push('/')
router.refresh()
diff --git a/components/user-menu.tsx b/components/user-menu.tsx
index 243827ac..23882795 100644
--- a/components/user-menu.tsx
+++ b/components/user-menu.tsx
@@ -3,7 +3,6 @@
import { useState } from 'react'
import { useRouter } from 'next/navigation'
-import type { User } from '@supabase/supabase-js'
import {
IconChartBar as ChartBar,
IconLink as Link2,
@@ -11,7 +10,8 @@ import {
IconUserCircle as UserRound
} from '@tabler/icons-react'
-import { createClient } from '@/lib/supabase/client'
+import { signOut } from '@/lib/actions/auth'
+import type { AppUser } from '@/lib/auth/types'
import { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/avatar'
import {
@@ -34,7 +34,7 @@ import { Button } from './ui/button'
import { ExternalLinkItems } from './external-link-items'
interface UserMenuProps {
- user: User
+ user: AppUser
}
export default function UserMenu({ user }: UserMenuProps) {
@@ -43,12 +43,10 @@ export default function UserMenu({ user }: UserMenuProps) {
const [accountOpen, setAccountOpen] = useState(false)
const [usageOpen, setUsageOpen] = useState(false)
const { usage, isLow, isExhausted, refreshUsage } = useUsageBudget()
- const userName =
- user.user_metadata?.full_name || user.user_metadata?.name || 'User'
- const avatarUrl =
- user.user_metadata?.avatar_url || user.user_metadata?.picture
+ const userName = user.name || 'User'
+ const avatarUrl = user.image ?? undefined
- const getInitials = (name: string, email: string | undefined) => {
+ const getInitials = (name: string, email: string | null | undefined) => {
if (name && name !== 'User') {
const names = name.split(' ')
if (names.length > 1) {
@@ -63,8 +61,7 @@ export default function UserMenu({ user }: UserMenuProps) {
}
const handleLogout = async () => {
- const supabase = createClient()
- await supabase.auth.signOut()
+ await signOut()
router.push('/')
router.refresh()
}
diff --git a/docs/CONFIGURATION.md b/docs/CONFIGURATION.md
index 1bc3cb3d..685918ec 100644
--- a/docs/CONFIGURATION.md
+++ b/docs/CONFIGURATION.md
@@ -190,6 +190,27 @@ If not configured, `type="general"` searches fall back to your configured search
By default, Morphic runs in **anonymous mode** (`ENABLE_AUTH=false`). This is ideal for personal, single-user environments.
+### Auth Provider (`AUTH_PROVIDER`)
+
+Auth behavior is controlled by an auth provider. Set `AUTH_PROVIDER` explicitly to one of:
+
+| Value | Description |
+| ------------- | --------------------------------------------------------------------- |
+| `supabase` | Supabase cloud authentication (multi-user) |
+| `none` | Anonymous mode: all users share one user ID |
+| `better-auth` | Local accounts in Morphic's own Postgres (reserved, upcoming release) |
+
+When `AUTH_PROVIDER` is **unset**, the provider is derived from the existing
+environment so current deployments keep working unchanged:
+
+- `ENABLE_AUTH=false` → `none` (anonymous mode, shared `ANONYMOUS_USER_ID`)
+- otherwise → `supabase` (when Supabase is not configured, no user is resolved
+ and the app behaves as before: guest/anonymous access without a shared ID)
+
+`MORPHIC_CLOUD_DEPLOYMENT=true` requires Supabase-backed auth: startup fails
+with a clear error when the resolved provider is `none` or any non-Supabase
+provider.
+
### Anonymous Mode (Default)
```bash
@@ -222,6 +243,18 @@ SUPABASE_SECRET_KEY=[YOUR_SUPABASE_SECRET_KEY]
- **Publishable Key**: Settings > API Keys > publishable key (`sb_publishable_...`)
- **Secret Key**: Settings > API Keys > secret key (`sb_secret_...`)
+4. For password recovery emails to work, add your site's recovery destination
+ under **Auth → URL Verification → Redirect URLs**:
+
+ ```
+ [YOUR_SITE_URL]/auth/update-password
+ ```
+
+ Recovery links point at this URL (the same destination Morphic has always
+ used, so existing allowlist entries keep working). If the destination is
+ not allowlisted, Supabase silently falls back to the project Site URL and
+ the recovery code can never be exchanged for a session.
+
## Guest Mode
Guest mode allows users to try Morphic without creating an account. Guest sessions are ephemeral — no chat history is stored.
diff --git a/hooks/__tests__/user-hooks.test.tsx b/hooks/__tests__/user-hooks.test.tsx
new file mode 100644
index 00000000..1172f976
--- /dev/null
+++ b/hooks/__tests__/user-hooks.test.tsx
@@ -0,0 +1,81 @@
+import { renderHook } from '@testing-library/react'
+import { describe, expect, it } from 'vitest'
+
+import type { AppUser } from '@/lib/auth/types'
+import { AppUserProvider } from '@/lib/contexts/app-user-context'
+
+import { useAuthCheck } from '@/hooks/use-auth-check'
+import { useCurrentUserImage } from '@/hooks/use-current-user-image'
+import { useCurrentUserName } from '@/hooks/use-current-user-name'
+
+const capabilities = { signUp: true, passwordReset: true, deleteUser: true }
+
+const user: AppUser = {
+ id: 'user-1',
+ email: '[email protected]',
+ name: 'Test Person',
+ image: 'https://example.com/avatar.png'
+}
+
+function wrapper({ children }: { children: React.ReactNode }) {
+ return (
+ <AppUserProvider user={user} capabilities={capabilities}>
+ {children}
+ </AppUserProvider>
+ )
+}
+
+function emptyWrapper({ children }: { children: React.ReactNode }) {
+ return (
+ <AppUserProvider user={null} capabilities={capabilities}>
+ {children}
+ </AppUserProvider>
+ )
+}
+
+describe('useAuthCheck', () => {
+ it('reports the authenticated user from context', () => {
+ const { result } = renderHook(() => useAuthCheck(), { wrapper })
+
+ expect(result.current.user).toEqual(user)
+ expect(result.current.isAuthenticated).toBe(true)
+ expect(result.current.loading).toBe(false)
+ })
+
+ it('reports no user when unauthenticated', () => {
+ const { result } = renderHook(() => useAuthCheck(), {
+ wrapper: emptyWrapper
+ })
+
+ expect(result.current.user).toBeNull()
+ expect(result.current.isAuthenticated).toBe(false)
+ })
+})
+
+describe('useCurrentUserName', () => {
+ it('returns the user display name', () => {
+ const { result } = renderHook(() => useCurrentUserName(), { wrapper })
+ expect(result.current).toBe('Test Person')
+ })
+
+ it('falls back to a placeholder without a user', () => {
+ const { result } = renderHook(() => useCurrentUserName(), {
+ wrapper: emptyWrapper
+ })
+ expect(result.current).toBe('?')
+ })
+})
+
+describe('useCurrentUserImage', () => {
+ it('returns the user avatar URL', () => {
+ const { result } = renderHook(() => useCurrentUserImage(), { wrapper })
+ expect(result.current).toBe('https://example.com/avatar.png')
+ })
+
+ it('returns null without an avatar or user', () => {
+ const { result } = renderHook(() => useCurrentUserImage(), {
+ wrapper: emptyWrapper
+ })
+ expect(result.current).toBeNull()
+ })
+})
diff --git a/hooks/use-auth-check.tsx b/hooks/use-auth-check.tsx
index 74598310..8e5a20fe 100644
--- a/hooks/use-auth-check.tsx
+++ b/hooks/use-auth-check.tsx
@@ -1,48 +1,9 @@
'use client'
-import { useEffect, useState } from 'react'
-
-import { User } from '@supabase/supabase-js'
-
-import { createClient } from '@/lib/supabase/client'
+import { useAppUser } from '@/lib/contexts/app-user-context'
export function useAuthCheck() {
- const [user, setUser] = useState<User | null>(null)
- const [loading, setLoading] = useState(true)
-
- useEffect(() => {
- let subscription: { unsubscribe: () => void } | null = null
-
- const checkAuth = async () => {
- try {
- const supabase = createClient()
-
- const {
- data: { session }
- } = await supabase.auth.getSession()
- setUser(session?.user ?? null)
-
- // Subscribe to auth changes
- const {
- data: { subscription: authSubscription }
- } = supabase.auth.onAuthStateChange((event, session) => {
- setUser(session?.user ?? null)
- })
- subscription = authSubscription
- } catch (error) {
- // Supabase not configured
- setUser(null)
- } finally {
- setLoading(false)
- }
- }
-
- checkAuth()
-
- return () => {
- subscription?.unsubscribe()
- }
- }, [])
+ const user = useAppUser()
- return { user, loading, isAuthenticated: !!user }
+ return { user, loading: false, isAuthenticated: !!user }
}
diff --git a/hooks/use-current-user-image.ts b/hooks/use-current-user-image.ts
index cc0eacb0..68f77ad5 100644
--- a/hooks/use-current-user-image.ts
+++ b/hooks/use-current-user-image.ts
@@ -1,24 +1,7 @@
-import { useEffect, useState } from 'react'
-
-import { createClient } from '@/lib/supabase/client'
+import { useAppUser } from '@/lib/contexts/app-user-context'
export const useCurrentUserImage = () => {
- const [image, setImage] = useState<string | null>(null)
-
- useEffect(() => {
- const fetchUserImage = async () => {
- try {
- const { data, error } = await createClient().auth.getSession()
- if (error) {
- console.error(error)
- }
- setImage(data.session?.user.user_metadata.avatar_url ?? null)
- } catch (error) {
- // Supabase not configured, skip silently
- }
- }
- fetchUserImage()
- }, [])
+ const user = useAppUser()
- return image
+ return user?.image ?? null
}
diff --git a/hooks/use-current-user-name.ts b/hooks/use-current-user-name.ts
index 2a652991..5723edf2 100644
--- a/hooks/use-current-user-name.ts
+++ b/hooks/use-current-user-name.ts
@@ -1,26 +1,7 @@
-import { useEffect, useState } from 'react'
-
-import { createClient } from '@/lib/supabase/client'
+import { useAppUser } from '@/lib/contexts/app-user-context'
export const useCurrentUserName = () => {
- const [name, setName] = useState<string | null>(null)
-
- useEffect(() => {
- const fetchProfileName = async () => {
- try {
- const { data, error } = await createClient().auth.getSession()
- if (error) {
- console.error(error)
- }
- setName(data.session?.user.user_metadata.full_name ?? '?')
- } catch (error) {
- // Supabase not configured
- setName('Anonymous')
- }
- }
-
- fetchProfileName()
- }, [])
+ const user = useAppUser()
- return name || '?'
+ return user?.name || '?'
}
diff --git a/lib/actions/__tests__/files.test.ts b/lib/actions/__tests__/files.test.ts
index 8087a541..bf649110 100644
--- a/lib/actions/__tests__/files.test.ts
+++ b/lib/actions/__tests__/files.test.ts
@@ -43,6 +43,7 @@ describe('File Actions', () => {
afterEach(() => {
process.env.ENABLE_AUTH = originalEnableAuth
+ delete process.env.AUTH_PROVIDER
})
it('lists current user files', async () => {
@@ -105,4 +106,18 @@ describe('File Actions', () => {
})
expect(dbActions.getLibraryFiles).not.toHaveBeenCalled()
})
+
+ it('rejects anonymous mode when AUTH_PROVIDER=none with ENABLE_AUTH unset', async () => {
+ process.env.AUTH_PROVIDER = 'none'
+ delete process.env.ENABLE_AUTH
+
+ const result = await listFiles()
+
+ expect(result).toEqual({
+ success: false,
+ files: [],
+ error: 'Library is unavailable in anonymous mode.'
+ })
+ expect(dbActions.getLibraryFiles).not.toHaveBeenCalled()
+ })
})
diff --git a/lib/actions/__tests__/notes.test.ts b/lib/actions/__tests__/notes.test.ts
index 667ee2bc..fc927cc3 100644
--- a/lib/actions/__tests__/notes.test.ts
+++ b/lib/actions/__tests__/notes.test.ts
@@ -38,6 +38,7 @@ describe('Note Actions', () => {
afterEach(() => {
process.env.ENABLE_AUTH = originalEnableAuth
+ delete process.env.AUTH_PROVIDER
})
it('saves a markdown note for the current user', async () => {
@@ -76,6 +77,19 @@ describe('Note Actions', () => {
expect(dbActions.createNote).not.toHaveBeenCalled()
})
+ it('rejects anonymous mode when AUTH_PROVIDER=none with ENABLE_AUTH unset', async () => {
+ process.env.AUTH_PROVIDER = 'none'
+ delete process.env.ENABLE_AUTH
+
+ const result = await saveNote({ content: 'Saved answer' })
+
+ expect(result).toEqual({
+ success: false,
+ error: 'Library is unavailable in anonymous mode.'
+ })
+ expect(dbActions.createNote).not.toHaveBeenCalled()
+ })
+
it('lists current user notes', async () => {
const result = await listNotes()
diff --git a/lib/actions/account.ts b/lib/actions/account.ts
index ded940a4..93ed6a1b 100644
--- a/lib/actions/account.ts
+++ b/lib/actions/account.ts
@@ -4,9 +4,9 @@ import { revalidateTag } from 'next/cache'
import { trackAccountDeleted } from '@/lib/analytics'
import { getCurrentUser } from '@/lib/auth/get-current-user'
+import { getAuthProvider } from '@/lib/auth/provider'
import * as dbActions from '@/lib/db/actions'
import { deleteUserObjects } from '@/lib/storage/r2-client'
-import { createAdminClient } from '@/lib/supabase/admin'
function getErrorMessage(error: unknown) {
if (error instanceof Error && error.message) {
@@ -20,7 +20,8 @@ export async function deleteAccount(): Promise<{
success: boolean
error?: string
}> {
- if (process.env.ENABLE_AUTH === 'false') {
+ const provider = getAuthProvider()
+ if (!provider.capabilities.deleteUser || !provider.deleteUser) {
return {
success: false,
error: 'Account deletion is unavailable in anonymous mode.'
@@ -32,14 +33,11 @@ export async function deleteAccount(): Promise<{
return { success: false, error: 'User not authenticated' }
}
- let adminClient: ReturnType<typeof createAdminClient>
- try {
- adminClient = createAdminClient()
- } catch (error) {
- console.error('Supabase admin client is not configured:', error)
+ const configError = provider.validateDeleteUserConfig?.() ?? null
+ if (configError) {
return {
success: false,
- error: 'Account deletion is not configured. Set SUPABASE_SECRET_KEY.'
+ error: configError
}
}
@@ -81,9 +79,9 @@ export async function deleteAccount(): Promise<{
await deleteUserObjects(user.id)
- const { error } = await adminClient.auth.admin.deleteUser(user.id)
- if (error) {
- throw error
+ const deleteAuthResult = await provider.deleteUser!(user.id)
+ if (!deleteAuthResult.success) {
+ throw new Error(deleteAuthResult.error ?? 'Failed to delete user')
}
revalidateTag('chat', 'max')
diff --git a/lib/actions/auth.ts b/lib/actions/auth.ts
new file mode 100644
index 00000000..e0110af2
--- /dev/null
+++ b/lib/actions/auth.ts
@@ -0,0 +1,66 @@
+'use server'
+
+import { getAuthProvider } from '@/lib/auth/provider'
+import type { AuthActionResult } from '@/lib/auth/types'
+
+function unavailable(): AuthActionResult {
+ return { success: false, error: 'Authentication is not available.' }
+}
+
+export async function signIn(credentials: {
+ email: string
+ password: string
+}): Promise<AuthActionResult> {
+ const provider = getAuthProvider()
+ if (!provider.signIn) {
+ return unavailable()
+ }
+ return provider.signIn(credentials)
+}
+
+export async function signInWithGoogle(): Promise<AuthActionResult> {
+ const provider = getAuthProvider()
+ if (!provider.signInWithOAuth) {
+ return unavailable()
+ }
+ return provider.signInWithOAuth('google')
+}
+
+export async function signUp(credentials: {
+ email: string
+ password: string
+}): Promise<AuthActionResult> {
+ const provider = getAuthProvider()
+ if (!provider.signUp) {
+ return unavailable()
+ }
+ return provider.signUp(credentials)
+}
+
+export async function signOut(): Promise<AuthActionResult> {
+ const provider = getAuthProvider()
+ if (!provider.signOut) {
+ return unavailable()
+ }
+ return provider.signOut()
+}
+
+export async function requestPasswordReset(
+ email: string
+): Promise<AuthActionResult> {
+ const provider = getAuthProvider()
+ if (!provider.requestPasswordReset) {
+ return unavailable()
+ }
+ return provider.requestPasswordReset(email)
+}
+
+export async function updatePassword(
+ password: string
+): Promise<AuthActionResult> {
+ const provider = getAuthProvider()
+ if (!provider.updatePassword) {
+ return unavailable()
+ }
+ return provider.updatePassword(password)
+}
diff --git a/lib/actions/files.ts b/lib/actions/files.ts
index 86e1fc1d..eeeccfd4 100644
--- a/lib/actions/files.ts
+++ b/lib/actions/files.ts
@@ -1,6 +1,7 @@
'use server'
import { getCurrentUserId } from '@/lib/auth/get-current-user'
+import { isAnonymousMode } from '@/lib/auth/provider'
import * as dbActions from '@/lib/db/actions'
import type { LibraryFile } from '@/lib/db/schema'
import { getSignedFileUrl } from '@/lib/storage/r2-client'
@@ -32,7 +33,7 @@ async function signLibraryFiles(
}
async function requireLibraryFileUserId() {
- if (process.env.ENABLE_AUTH === 'false') {
+ if (isAnonymousMode()) {
return {
userId: null,
error: 'Library is unavailable in anonymous mode.'
diff --git a/lib/actions/notes.ts b/lib/actions/notes.ts
index 8d3e8089..fb0edf76 100644
--- a/lib/actions/notes.ts
+++ b/lib/actions/notes.ts
@@ -1,6 +1,7 @@
'use server'
import { getCurrentUserId } from '@/lib/auth/get-current-user'
+import { isAnonymousMode } from '@/lib/auth/provider'
import * as dbActions from '@/lib/db/actions'
import type { Note } from '@/lib/db/schema'
import { stripMarkdownText } from '@/lib/utils/markdown'
@@ -33,7 +34,7 @@ function deriveTitle(content: string, title?: string) {
}
async function requireNoteUserId() {
- if (process.env.ENABLE_AUTH === 'false') {
+ if (isAnonymousMode()) {
return {
userId: null,
error: 'Library is unavailable in anonymous mode.'
diff --git a/lib/auth/__tests__/none-provider.test.ts b/lib/auth/__tests__/none-provider.test.ts
new file mode 100644
index 00000000..87b02028
--- /dev/null
+++ b/lib/auth/__tests__/none-provider.test.ts
@@ -0,0 +1,95 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+
+import {
+ DEFAULT_ANONYMOUS_USER_ID,
+ noneAuthProvider
+} from '@/lib/auth/providers/none'
+
+describe('none auth provider (anonymous mode)', () => {
+ const original: Record<string, string | undefined> = {}
+
+ beforeEach(() => {
+ for (const key of [
+ 'ENABLE_AUTH',
+ 'ANONYMOUS_USER_ID',
+ 'MORPHIC_CLOUD_DEPLOYMENT',
+ 'NODE_ENV'
+ ]) {
+ original[key] = process.env[key]
+ }
+ delete process.env.ANONYMOUS_USER_ID
+ delete process.env.MORPHIC_CLOUD_DEPLOYMENT
+ })
+
+ afterEach(() => {
+ for (const [key, value] of Object.entries(original)) {
+ if (value === undefined) {
+ delete process.env[key]
+ } else {
+ process.env[key] = value
+ }
+ }
+ vi.restoreAllMocks()
+ })
+
+ it('resolves the shared anonymous user ID', async () => {
+ await expect(noneAuthProvider.getCurrentUserId?.()).resolves.toBe(
+ DEFAULT_ANONYMOUS_USER_ID
+ )
+ })
+
+ it('resolves the configured anonymous user ID', async () => {
+ process.env.ANONYMOUS_USER_ID = 'my-anon'
+ await expect(noneAuthProvider.getCurrentUserId?.()).resolves.toBe('my-anon')
+ })
+
+ it('resolves no user profile', async () => {
+ await expect(noneAuthProvider.getCurrentUser()).resolves.toBeNull()
+ })
+
+ it('warns outside tests when resolving the anonymous identity', async () => {
+ vi.stubEnv('NODE_ENV', 'development')
+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {})
+
+ await noneAuthProvider.getCurrentUserId?.()
+
+ expect(warn).toHaveBeenCalledWith(
+ expect.stringContaining('Authentication disabled')
+ )
+ vi.unstubAllEnvs()
+ })
+
+ it('does not warn in tests', async () => {
+ vi.stubEnv('NODE_ENV', 'test')
+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {})
+
+ await noneAuthProvider.getCurrentUserId?.()
+
+ expect(warn).not.toHaveBeenCalled()
+ vi.unstubAllEnvs()
+ })
+
+ it('refuses to resolve the anonymous identity in Morphic Cloud deployments', async () => {
+ process.env.MORPHIC_CLOUD_DEPLOYMENT = 'true'
+
+ await expect(noneAuthProvider.getCurrentUserId?.()).rejects.toThrow(
+ 'ENABLE_AUTH=false is not allowed in MORPHIC_CLOUD_DEPLOYMENT'
+ )
+ })
+
+ it('enforces no redirects in handleSession', async () => {
+ const { NextRequest } = await import('next/server')
+ const request = new NextRequest('http://localhost:3000/search/abc')
+ const response = await noneAuthProvider.handleSession(request)
+ expect(response.status).toBe(200)
+ expect(response.headers.get('location')).toBeNull()
+ })
+
+ it('discloses no capabilities', () => {
+ expect(noneAuthProvider.capabilities).toEqual({
+ signUp: false,
+ passwordReset: false,
+ deleteUser: false
+ })
+ })
+})
diff --git a/lib/auth/__tests__/provider.test.ts b/lib/auth/__tests__/provider.test.ts
new file mode 100644
index 00000000..c2293098
--- /dev/null
+++ b/lib/auth/__tests__/provider.test.ts
@@ -0,0 +1,193 @@
+import { afterEach, beforeEach, describe, expect, it } from 'vitest'
+
+import {
+ getAuthProvider,
+ isAnonymousMode,
+ resolveAuthProviderName
+} from '@/lib/auth/provider'
+
+const AUTH_ENV_KEYS = [
+ 'AUTH_PROVIDER',
+ 'ENABLE_AUTH',
+ 'MORPHIC_CLOUD_DEPLOYMENT',
+ 'NEXT_PUBLIC_SUPABASE_URL',
+ 'NEXT_PUBLIC_SUPABASE_PUBLISHABLE_KEY'
+] as const
+
+function clearAuthEnv() {
+ for (const key of AUTH_ENV_KEYS) {
+ delete process.env[key]
+ }
+}
+
+function configureSupabase() {
+ process.env.NEXT_PUBLIC_SUPABASE_URL = 'https://example.supabase.co'
+ process.env.NEXT_PUBLIC_SUPABASE_PUBLISHABLE_KEY = 'sb_publishable_key'
+}
+
+describe('auth provider dispatch', () => {
+ const originalEnv: Record<string, string | undefined> = {}
+
+ beforeEach(() => {
+ for (const key of AUTH_ENV_KEYS) {
+ originalEnv[key] = process.env[key]
+ }
+ clearAuthEnv()
+ })
+
+ afterEach(() => {
+ for (const key of AUTH_ENV_KEYS) {
+ if (originalEnv[key] === undefined) {
+ delete process.env[key]
+ } else {
+ process.env[key] = originalEnv[key]
+ }
+ }
+ })
+
+ describe('explicit AUTH_PROVIDER configuration', () => {
+ it('resolves supabase', () => {
+ process.env.AUTH_PROVIDER = 'supabase'
+ expect(resolveAuthProviderName()).toBe('supabase')
+ expect(getAuthProvider().name).toBe('supabase')
+ })
+
+ it('resolves none', () => {
+ process.env.AUTH_PROVIDER = 'none'
+ expect(resolveAuthProviderName()).toBe('none')
+ expect(getAuthProvider().name).toBe('none')
+ })
+
+ it('trims surrounding whitespace', () => {
+ process.env.AUTH_PROVIDER = ' none '
+ expect(resolveAuthProviderName()).toBe('none')
+ })
+
+ it('rejects unknown values', () => {
+ process.env.AUTH_PROVIDER = 'auth0'
+ expect(() => resolveAuthProviderName()).toThrow(
+ 'Invalid AUTH_PROVIDER "auth0"'
+ )
+ })
+
+ it('accepts better-auth as a name but reports it unavailable in this version', () => {
+ process.env.AUTH_PROVIDER = 'better-auth'
+ expect(resolveAuthProviderName()).toBe('better-auth')
+ expect(() => getAuthProvider()).toThrow(
+ 'AUTH_PROVIDER=better-auth is not available in this version of Morphic.'
+ )
+ })
+ })
+
+ describe('isAnonymousMode', () => {
+ it('returns true when AUTH_PROVIDER=none and ENABLE_AUTH is unset', () => {
+ process.env.AUTH_PROVIDER = 'none'
+ expect(isAnonymousMode()).toBe(true)
+ })
+
+ it('returns true when AUTH_PROVIDER=none even if ENABLE_AUTH=true', () => {
+ process.env.AUTH_PROVIDER = 'none'
+ process.env.ENABLE_AUTH = 'true'
+ expect(isAnonymousMode()).toBe(true)
+ })
+
+ it('returns true when ENABLE_AUTH=false', () => {
+ process.env.ENABLE_AUTH = 'false'
+ expect(isAnonymousMode()).toBe(true)
+ })
+
+ it('returns false when unset (supabase derived)', () => {
+ expect(isAnonymousMode()).toBe(false)
+ })
+ })
+
+ describe('backward-compatible derivation when AUTH_PROVIDER is unset', () => {
+ it('derives none when ENABLE_AUTH=false', () => {
+ process.env.ENABLE_AUTH = 'false'
+ expect(resolveAuthProviderName()).toBe('none')
+ })
+
+ it('derives supabase when ENABLE_AUTH=true and Supabase is configured', () => {
+ process.env.ENABLE_AUTH = 'true'
+ configureSupabase()
+ expect(resolveAuthProviderName()).toBe('supabase')
+ })
+
+ it('derives supabase when ENABLE_AUTH is unset and Supabase is configured', () => {
+ configureSupabase()
+ expect(resolveAuthProviderName()).toBe('supabase')
+ })
+
+ it('derives supabase when ENABLE_AUTH is unset and Supabase is not configured', () => {
+ // Guest behavior: the supabase provider resolves no user when unconfigured
+ expect(resolveAuthProviderName()).toBe('supabase')
+ })
+
+ it('derives supabase when ENABLE_AUTH=true and Supabase is not configured', () => {
+ process.env.ENABLE_AUTH = 'true'
+ expect(resolveAuthProviderName()).toBe('supabase')
+ })
+
+ it('prefers none over Supabase configuration when ENABLE_AUTH=false', () => {
+ process.env.ENABLE_AUTH = 'false'
+ configureSupabase()
+ expect(resolveAuthProviderName()).toBe('none')
+ })
+ })
+
+ describe('Morphic Cloud deployment guard', () => {
+ beforeEach(() => {
+ process.env.MORPHIC_CLOUD_DEPLOYMENT = 'true'
+ })
+
+ it('allows supabase', () => {
+ configureSupabase()
+ expect(resolveAuthProviderName()).toBe('supabase')
+ })
+
+ it('refuses derived none (ENABLE_AUTH=false) with the historical error', () => {
+ process.env.ENABLE_AUTH = 'false'
+ expect(() => resolveAuthProviderName()).toThrow(
+ 'ENABLE_AUTH=false is not allowed in MORPHIC_CLOUD_DEPLOYMENT'
+ )
+ })
+
+ it('refuses explicit AUTH_PROVIDER=none', () => {
+ process.env.AUTH_PROVIDER = 'none'
+ expect(() => resolveAuthProviderName()).toThrow(
+ 'AUTH_PROVIDER=none is not allowed in MORPHIC_CLOUD_DEPLOYMENT'
+ )
+ })
+
+ it('refuses AUTH_PROVIDER=better-auth', () => {
+ process.env.AUTH_PROVIDER = 'better-auth'
+ expect(() => resolveAuthProviderName()).toThrow(
+ 'AUTH_PROVIDER=better-auth is not allowed in MORPHIC_CLOUD_DEPLOYMENT'
+ )
+ })
+ })
+})
+
+describe('supabase provider without configuration', () => {
+ beforeEach(() => {
+ delete process.env.NEXT_PUBLIC_SUPABASE_URL
+ delete process.env.NEXT_PUBLIC_SUPABASE_PUBLISHABLE_KEY
+ delete process.env.AUTH_PROVIDER
+ delete process.env.ENABLE_AUTH
+ })
+
+ it('resolves no user when Supabase is not configured', async () => {
+ const provider = getAuthProvider()
+ expect(provider.name).toBe('supabase')
+ await expect(provider.getCurrentUser()).resolves.toBeNull()
+ })
+
+ it('passes the request through when Supabase is not configured', async () => {
+ const { NextRequest } = await import('next/server')
+ const provider = getAuthProvider()
+ const request = new NextRequest('http://localhost:3000/search/abc')
+ const response = await provider.handleSession(request)
+ expect(response.status).toBe(200)
+ expect(response.headers.get('location')).toBeNull()
+ })
+})
diff --git a/lib/auth/__tests__/supabase-provider.test.ts b/lib/auth/__tests__/supabase-provider.test.ts
new file mode 100644
index 00000000..45acab76
--- /dev/null
+++ b/lib/auth/__tests__/supabase-provider.test.ts
@@ -0,0 +1,95 @@
+import { NextRequest, NextResponse } from 'next/server'
+
+import { beforeEach, describe, expect, it, vi } from 'vitest'
+
+import { supabaseAuthProvider } from '@/lib/auth/providers/supabase'
+import { createClient } from '@/lib/supabase/server'
+
+vi.mock('@/lib/supabase/server', () => ({ createClient: vi.fn() }))
+vi.mock('@/lib/supabase/middleware', () => ({
+ updateSession: vi.fn(),
+ exchangeRecoveryCode: vi.fn()
+}))
+vi.mock('@/lib/supabase/keys', () => ({
+ hasSupabasePublicConfig: vi.fn(() => true)
+}))
+vi.mock('next/headers', () => ({ headers: vi.fn() }))
+
+import { headers } from 'next/headers'
+
+import { exchangeRecoveryCode, updateSession } from '@/lib/supabase/middleware'
+
+function request(url: string) {
+ return new NextRequest(url)
+}
+
+describe('supabase provider', () => {
+ const resetPasswordForEmail = vi.fn()
+
+ beforeEach(() => {
+ vi.clearAllMocks()
+ vi.mocked(createClient).mockResolvedValue({
+ auth: { resetPasswordForEmail }
+ } as never)
+ vi.mocked(headers).mockResolvedValue(
+ new Headers({ origin: 'http://localhost:3000' }) as never
+ )
+ })
+
+ describe('requestPasswordReset', () => {
+ it('keeps the legacy allowlisted recovery destination', async () => {
+ resetPasswordForEmail.mockResolvedValue({ error: null })
+
+ const result =
+ await supabaseAuthProvider.requestPasswordReset!('[email protected]')
+
+ expect(result).toEqual({ success: true })
+ expect(resetPasswordForEmail).toHaveBeenCalledWith('[email protected]', {
+ redirectTo: 'http://localhost:3000/auth/update-password'
+ })
+ })
+ })
+
+ describe('handleSession', () => {
+ it('exchanges a recovery code arriving at update-password', async () => {
+ const exchanged = NextResponse.redirect(
+ 'http://localhost:3000/auth/update-password'
+ )
+ vi.mocked(exchangeRecoveryCode).mockResolvedValue(exchanged)
+ const req = request(
+ 'http://localhost:3000/auth/update-password?code=abc&state=xyz'
+ )
+
+ const response = await supabaseAuthProvider.handleSession!(req)
+
+ expect(exchangeRecoveryCode).toHaveBeenCalledWith(req, 'abc')
+ expect(updateSession).not.toHaveBeenCalled()
+ expect(response).toBe(exchanged)
+ })
+
+ it('runs normal session handling without a code', async () => {
+ const next = NextResponse.next()
+ vi.mocked(updateSession).mockResolvedValue(next)
+
+ const response = await supabaseAuthProvider.handleSession!(
+ request('http://localhost:3000/auth/update-password')
+ )
+
+ expect(updateSession).toHaveBeenCalledOnce()
+ expect(exchangeRecoveryCode).not.toHaveBeenCalled()
+ expect(response).toBe(next)
+ })
+
+ it('ignores code params on other paths', async () => {
+ const next = NextResponse.next()
+ vi.mocked(updateSession).mockResolvedValue(next)
+
+ await supabaseAuthProvider.handleSession!(
+ request('http://localhost:3000/auth/login?code=abc')
+ )
+
+ expect(updateSession).toHaveBeenCalledOnce()
+ expect(exchangeRecoveryCode).not.toHaveBeenCalled()
+ })
+ })
+})
diff --git a/lib/auth/get-current-user.ts b/lib/auth/get-current-user.ts
index 6b27740f..b7f46826 100644
--- a/lib/auth/get-current-user.ts
+++ b/lib/auth/get-current-user.ts
@@ -1,42 +1,22 @@
-import { hasSupabasePublicConfig } from '@/lib/supabase/keys'
-import { createClient } from '@/lib/supabase/server'
+import { getAuthProvider } from '@/lib/auth/provider'
import { perfLog } from '@/lib/utils/perf-logging'
import { incrementAuthCallCount } from '@/lib/utils/perf-tracking'
-export async function getCurrentUser() {
- if (!hasSupabasePublicConfig()) {
- return null // Supabase is not configured
- }
+import type { AppUser } from './types'
- const supabase = await createClient()
- const { data } = await supabase.auth.getUser()
- return data.user ?? null
+export async function getCurrentUser(): Promise<AppUser | null> {
+ return getAuthProvider().getCurrentUser()
}
export async function getCurrentUserId() {
const count = incrementAuthCallCount()
perfLog(`getCurrentUserId called - count: ${count}`)
- // Skip authentication mode (for personal Docker deployments)
- if (process.env.ENABLE_AUTH === 'false') {
- // Guard: Prevent disabling auth in Morphic Cloud deployments
- if (process.env.MORPHIC_CLOUD_DEPLOYMENT === 'true') {
- throw new Error(
- 'ENABLE_AUTH=false is not allowed in MORPHIC_CLOUD_DEPLOYMENT'
- )
- }
-
- // Always warn when authentication is disabled (except in tests)
- if (process.env.NODE_ENV !== 'test') {
- console.warn(
- '⚠️ Authentication disabled. Running in anonymous mode.\n' +
- ' All users share the same user ID. For personal use only.'
- )
- }
-
- return process.env.ANONYMOUS_USER_ID || 'anonymous-user'
+ const provider = getAuthProvider()
+ if (provider.getCurrentUserId) {
+ return provider.getCurrentUserId()
}
- const user = await getCurrentUser()
+ const user = await provider.getCurrentUser()
return user?.id
}
diff --git a/lib/auth/provider.ts b/lib/auth/provider.ts
new file mode 100644
index 00000000..47356591
--- /dev/null
+++ b/lib/auth/provider.ts
@@ -0,0 +1,84 @@
+import { noneAuthProvider } from '@/lib/auth/providers/none'
+import { supabaseAuthProvider } from '@/lib/auth/providers/supabase'
+import type { AuthProvider, AuthProviderName } from '@/lib/auth/types'
+
+const AUTH_PROVIDER_NAMES: AuthProviderName[] = [
+ 'supabase',
+ 'better-auth',
+ 'none'
+]
+
+// Providers register here as they ship. `better-auth` is an accepted
+// configuration value reserved for a follow-up release.
+const providerRegistry: Partial<Record<AuthProviderName, AuthProvider>> = {
+ supabase: supabaseAuthProvider,
+ none: noneAuthProvider
+}
+
+function enforceCloudDeploymentGuard(
+ name: AuthProviderName,
+ explicitlyConfigured: boolean
+): void {
+ if (process.env.MORPHIC_CLOUD_DEPLOYMENT !== 'true' || name === 'supabase') {
+ return
+ }
+ if (name === 'none' && !explicitlyConfigured) {
+ // Preserve the historical message for ENABLE_AUTH=false deployments
+ throw new Error(
+ 'ENABLE_AUTH=false is not allowed in MORPHIC_CLOUD_DEPLOYMENT'
+ )
+ }
+ throw new Error(
+ `AUTH_PROVIDER=${name} is not allowed in MORPHIC_CLOUD_DEPLOYMENT`
+ )
+}
+
+/**
+ * Resolve the active auth provider name from configuration.
+ *
+ * When `AUTH_PROVIDER` is unset the provider is derived from the existing
+ * environment so current deployments behave identically:
+ * - `ENABLE_AUTH=false` -> `none` (anonymous mode)
+ * - otherwise -> `supabase` (the Supabase provider no-ops to guest behavior
+ * when Supabase is not configured, exactly as before)
+ */
+export function resolveAuthProviderName(): AuthProviderName {
+ const configured = process.env.AUTH_PROVIDER?.trim()
+
+ let name: AuthProviderName
+ if (configured) {
+ if (!AUTH_PROVIDER_NAMES.includes(configured as AuthProviderName)) {
+ throw new Error(
+ `Invalid AUTH_PROVIDER "${configured}". Expected one of: ${AUTH_PROVIDER_NAMES.join(', ')}`
+ )
+ }
+ name = configured as AuthProviderName
+ } else {
+ name = process.env.ENABLE_AUTH === 'false' ? 'none' : 'supabase'
+ }
+
+ enforceCloudDeploymentGuard(name, Boolean(configured))
+ return name
+}
+
+/**
+ * True when the active provider shares a single identity across all visitors
+ * (anonymous mode). Feature gates must use this instead of reading
+ * `ENABLE_AUTH` directly, so that `AUTH_PROVIDER=none` and the derived
+ * `ENABLE_AUTH=false` behavior always agree.
+ */
+export function isAnonymousMode(): boolean {
+ return resolveAuthProviderName() === 'none'
+}
+
+/** Return the active auth provider implementation. */
+export function getAuthProvider(): AuthProvider {
+ const name = resolveAuthProviderName()
+ const provider = providerRegistry[name]
+ if (!provider) {
+ throw new Error(
+ `AUTH_PROVIDER=${name} is not available in this version of Morphic.`
+ )
+ }
+ return provider
+}
diff --git a/lib/auth/providers/none.ts b/lib/auth/providers/none.ts
new file mode 100644
index 00000000..b1f7c27d
--- /dev/null
+++ b/lib/auth/providers/none.ts
@@ -0,0 +1,47 @@
+import { type NextRequest, NextResponse } from 'next/server'
+
+import type { AppUser, AuthProvider } from '@/lib/auth/types'
+
+export const DEFAULT_ANONYMOUS_USER_ID = 'anonymous-user'
+
+/**
+ * Anonymous mode (`ENABLE_AUTH=false`): all users share one configured user
+ * ID. Preserves the previous skip-authentication behavior, including the
+ * Morphic Cloud guard and the startup warning.
+ */
+export const noneAuthProvider: AuthProvider = {
+ name: 'none',
+ capabilities: {
+ signUp: false,
+ passwordReset: false,
+ deleteUser: false
+ },
+
+ async getCurrentUser(): Promise<AppUser | null> {
+ return null
+ },
+
+ async getCurrentUserId(): Promise<string | undefined> {
+ // Guard: Prevent disabling auth in Morphic Cloud deployments
+ if (process.env.MORPHIC_CLOUD_DEPLOYMENT === 'true') {
+ throw new Error(
+ 'ENABLE_AUTH=false is not allowed in MORPHIC_CLOUD_DEPLOYMENT'
+ )
+ }
+
+ // Always warn when authentication is disabled (except in tests)
+ if (process.env.NODE_ENV !== 'test') {
+ console.warn(
+ '⚠️ Authentication disabled. Running in anonymous mode.\n' +
+ ' All users share the same user ID. For personal use only.'
+ )
+ }
+
+ return process.env.ANONYMOUS_USER_ID || DEFAULT_ANONYMOUS_USER_ID
+ },
+
+ async handleSession(request: NextRequest): Promise<NextResponse> {
+ // Anonymous mode enforces no redirects
+ return NextResponse.next({ request })
+ }
+}
diff --git a/lib/auth/providers/supabase.ts b/lib/auth/providers/supabase.ts
new file mode 100644
index 00000000..d9bcff66
--- /dev/null
+++ b/lib/auth/providers/supabase.ts
@@ -0,0 +1,177 @@
+import { headers } from 'next/headers'
+import { type NextRequest, NextResponse } from 'next/server'
+
+import type { User as SupabaseUser } from '@supabase/supabase-js'
+
+import type { AppUser, AuthActionResult, AuthProvider } from '@/lib/auth/types'
+import { createAdminClient } from '@/lib/supabase/admin'
+import { hasSupabasePublicConfig } from '@/lib/supabase/keys'
+import { exchangeRecoveryCode, updateSession } from '@/lib/supabase/middleware'
+import { createClient } from '@/lib/supabase/server'
+
+function metaString(
+ metadata: Record<string, unknown>,
+ ...keys: string[]
+): string | null {
+ for (const key of keys) {
+ const value = metadata[key]
+ if (typeof value === 'string' && value) {
+ return value
+ }
+ }
+ return null
+}
+
+function toAppUser(user: SupabaseUser): AppUser {
+ const metadata = (user.user_metadata ?? {}) as Record<string, unknown>
+ return {
+ id: user.id,
+ email: user.email ?? null,
+ name: metaString(metadata, 'full_name', 'name'),
+ image: metaString(metadata, 'avatar_url', 'picture'),
+ createdAt: user.created_at ?? null
+ }
+}
+
+async function getOrigin(): Promise<string> {
+ const headerStore = await headers()
+ const origin = headerStore.get('origin')
+ if (origin) {
+ return origin
+ }
+ const host = headerStore.get('x-forwarded-host') ?? headerStore.get('host')
+ const protocol = headerStore.get('x-forwarded-proto') ?? 'https'
+ return host ? `${protocol}://${host}` : ''
+}
+
+export const supabaseAuthProvider: AuthProvider = {
+ name: 'supabase',
+ capabilities: {
+ signUp: true,
+ passwordReset: true,
+ deleteUser: true
+ },
+
+ async getCurrentUser(): Promise<AppUser | null> {
+ if (!hasSupabasePublicConfig()) {
+ return null // Supabase is not configured
+ }
+
+ const supabase = await createClient()
+ const { data } = await supabase.auth.getUser()
+ return data.user ? toAppUser(data.user) : null
+ },
+
+ async handleSession(request: NextRequest): Promise<NextResponse> {
+ if (!hasSupabasePublicConfig()) {
+ // If Supabase is not configured, just pass the request through
+ return NextResponse.next({ request })
+ }
+ const code = request.nextUrl.searchParams.get('code')
+ if (request.nextUrl.pathname === '/auth/update-password' && code) {
+ return exchangeRecoveryCode(request, code)
+ }
+ return updateSession(request)
+ },
+
+ async signIn({
+ email,
+ password
+ }: {
+ email: string
+ password: string
+ }): Promise<AuthActionResult> {
+ const supabase = await createClient()
+ const { error } = await supabase.auth.signInWithPassword({
+ email,
+ password
+ })
+ return error ? { success: false, error: error.message } : { success: true }
+ },
+
+ async signInWithOAuth(provider: string): Promise<AuthActionResult> {
+ const supabase = await createClient()
+ const origin = await getOrigin()
+ const { data, error } = await supabase.auth.signInWithOAuth({
+ provider: provider as 'google',
+ options: {
+ redirectTo: `${origin}/auth/oauth`
+ }
+ })
+ if (error) {
+ return { success: false, error: error.message }
+ }
+ return { success: true, redirectTo: data.url }
+ },
+
+ async signUp({
+ email,
+ password
+ }: {
+ email: string
+ password: string
+ }): Promise<AuthActionResult> {
+ const supabase = await createClient()
+ const origin = await getOrigin()
+ const { error } = await supabase.auth.signUp({
+ email,
+ password,
+ options: {
+ emailRedirectTo: `${origin}/`
+ }
+ })
+ return error ? { success: false, error: error.message } : { success: true }
+ },
+
+ async signOut(): Promise<AuthActionResult> {
+ const supabase = await createClient()
+ const { error } = await supabase.auth.signOut()
+ return error ? { success: false, error: error.message } : { success: true }
+ },
+
+ async requestPasswordReset(email: string): Promise<AuthActionResult> {
+ const supabase = await createClient()
+ const origin = await getOrigin()
+ const { error } = await supabase.auth.resetPasswordForEmail(email, {
+ // Keep the pre-refactor destination: deployments that already allowlist
+ // /auth/update-password in Supabase keep receiving recovery links.
+ redirectTo: `${origin}/auth/update-password`
+ })
+ return error ? { success: false, error: error.message } : { success: true }
+ },
+
+ async updatePassword(password: string): Promise<AuthActionResult> {
+ const supabase = await createClient()
+ const { error } = await supabase.auth.updateUser({ password })
+ return error ? { success: false, error: error.message } : { success: true }
+ },
+
+ validateDeleteUserConfig(): string | null {
+ try {
+ createAdminClient()
+ return null
+ } catch (error) {
+ console.error('Supabase admin client is not configured:', error)
+ return 'Account deletion is not configured. Set SUPABASE_SECRET_KEY.'
+ }
+ },
+
+ async deleteUser(userId: string): Promise<AuthActionResult> {
+ try {
+ const adminClient = createAdminClient()
+ const { error } = await adminClient.auth.admin.deleteUser(userId)
+ if (error) {
+ throw error
+ }
+ return { success: true }
+ } catch (error) {
+ return {
+ success: false,
+ error:
+ error instanceof Error && error.message
+ ? error.message
+ : 'Failed to delete user'
+ }
+ }
+ }
+}
diff --git a/lib/auth/types.ts b/lib/auth/types.ts
new file mode 100644
index 00000000..1d29ab16
--- /dev/null
+++ b/lib/auth/types.ts
@@ -0,0 +1,75 @@
+import type { NextRequest, NextResponse } from 'next/server'
+
+export type AuthProviderName = 'supabase' | 'better-auth' | 'none'
+
+/**
+ * Provider-agnostic user profile resolved by the server-side identity seam
+ * (`getCurrentUser`). All application data continues to be scoped by `id`.
+ */
+export interface AppUser {
+ id: string
+ email: string | null
+ name?: string | null
+ image?: string | null
+ createdAt?: Date | string | null
+}
+
+/**
+ * Static metadata describing which auth operations a provider supports.
+ * The UI hides entry points for operations the active provider cannot perform.
+ */
+export interface AuthCapabilities {
+ signUp: boolean
+ passwordReset: boolean
+ deleteUser: boolean
+}
+
+export interface AuthActionResult {
+ success: boolean
+ error?: string
+ /**
+ * Present when the client should continue authentication at this URL
+ * (e.g. an OAuth redirect to the identity provider).
+ */
+ redirectTo?: string
+}
+
+/**
+ * The interface every auth provider implements. Dispatch happens at the
+ * existing seams: `getCurrentUser`/`getCurrentUserId` and `proxy.ts`.
+ */
+export interface AuthProvider {
+ readonly name: AuthProviderName
+ readonly capabilities: AuthCapabilities
+
+ /** Resolve the current user, or null when unauthenticated. */
+ getCurrentUser(): Promise<AppUser | null>
+
+ /** Enforce/refresh the session for an incoming request (used by proxy.ts). */
+ handleSession(request: NextRequest): Promise<NextResponse>
+
+ /**
+ * Optional identity override used by `getCurrentUserId()`.
+ * Defaults to `getCurrentUser()?.id` when not implemented.
+ */
+ getCurrentUserId?(): Promise<string | undefined>
+
+ signIn?(credentials: {
+ email: string
+ password: string
+ }): Promise<AuthActionResult>
+ signInWithOAuth?(provider: string): Promise<AuthActionResult>
+ signUp?(credentials: {
+ email: string
+ password: string
+ }): Promise<AuthActionResult>
+ signOut?(): Promise<AuthActionResult>
+ requestPasswordReset?(email: string): Promise<AuthActionResult>
+ updatePassword?(password: string): Promise<AuthActionResult>
+ deleteUser?(userId: string): Promise<AuthActionResult>
+ /**
+ * Returns an error message when the provider is not configured to delete
+ * users, or null when deletion is available.
+ */
+ validateDeleteUserConfig?(): string | null
+}
diff --git a/lib/contexts/app-user-context.tsx b/lib/contexts/app-user-context.tsx
new file mode 100644
index 00000000..31061475
--- /dev/null
+++ b/lib/contexts/app-user-context.tsx
@@ -0,0 +1,53 @@
+'use client'
+
+import { createContext, useContext } from 'react'
+
+import type { AppUser, AuthCapabilities } from '@/lib/auth/types'
+
+interface AppUserContextValue {
+ user: AppUser | null
+ capabilities: AuthCapabilities
+}
+
+const NO_CAPABILITIES: AuthCapabilities = {
+ signUp: false,
+ passwordReset: false,
+ deleteUser: false
+}
+
+const AppUserContext = createContext<AppUserContextValue>({
+ user: null,
+ capabilities: NO_CAPABILITIES
+})
+
+/**
+ * Provides the server-resolved user and the active provider's capabilities to
+ * client components, replacing direct Supabase browser-client access.
+ */
+export function AppUserProvider({
+ user,
+ capabilities,
+ children
+}: {
+ user: AppUser | null
+ capabilities: AuthCapabilities
+ children: React.ReactNode
+}) {
+ return (
+ <AppUserContext.Provider value={{ user, capabilities }}>
+ {children}
+ </AppUserContext.Provider>
+ )
+}
+
+export function useAppUser(): AppUser | null {
+ return useContext(AppUserContext).user
+}
+
+/**
+ * Capabilities of the active auth provider. UI entry points for operations
+ * the provider cannot perform must be hidden.
+ */
+export function useAuthCapabilities(): AuthCapabilities {
+ return useContext(AppUserContext).capabilities
+}
diff --git a/lib/supabase/__tests__/middleware.test.ts b/lib/supabase/__tests__/middleware.test.ts
new file mode 100644
index 00000000..48d50fb6
--- /dev/null
+++ b/lib/supabase/__tests__/middleware.test.ts
@@ -0,0 +1,69 @@
+import { NextRequest } from 'next/server'
+
+import { beforeEach, describe, expect, it, vi } from 'vitest'
+
+import { exchangeRecoveryCode } from '../middleware'
+
+vi.mock('@supabase/ssr', () => ({ createServerClient: vi.fn() }))
+vi.mock('@/lib/supabase/keys', () => ({
+ getSupabasePublishableKey: vi.fn(() => 'publishable-key')
+}))
+
+import { createServerClient } from '@supabase/ssr'
+
+describe('exchangeRecoveryCode', () => {
+ const exchangeCodeForSession = vi.fn()
+ let cookieOptions: {
+ cookies: {
+ setAll: (cookies: Array<{ name: string; value: string }>) => void
+ }
+ }
+
+ beforeEach(() => {
+ vi.clearAllMocks()
+ process.env.NEXT_PUBLIC_SUPABASE_URL = 'https://example.supabase.co'
+ vi.mocked(createServerClient).mockImplementation(((
+ _url: string,
+ _key: string,
+ options: typeof cookieOptions
+ ) => {
+ cookieOptions = options
+ return { auth: { exchangeCodeForSession } } as never
+ }) as never)
+ })
+
+ function requestWithCode() {
+ return new NextRequest(
+ 'http://localhost:3000/auth/update-password?code=abc&state=xyz'
+ )
+ }
+
+ it('persists the session and redirects to the clean URL', async () => {
+ exchangeCodeForSession.mockImplementation(async () => {
+ cookieOptions.cookies.setAll([{ name: 'sb-session', value: 'token' }])
+ return { error: null }
+ })
+
+ const response = await exchangeRecoveryCode(requestWithCode(), 'abc')
+
+ expect(exchangeCodeForSession).toHaveBeenCalledWith('abc')
+ expect(response.status).toBe(307)
+ expect(response.headers.get('location')).toBe(
+ 'http://localhost:3000/auth/update-password'
+ )
+ expect(response.cookies.get('sb-session')?.value).toBe('token')
+ })
+
+ it('bounces to login when the code cannot be exchanged', async () => {
+ exchangeCodeForSession.mockResolvedValue({
+ error: { message: 'invalid code' }
+ })
+
+ const response = await exchangeRecoveryCode(requestWithCode(), 'abc')
+
+ expect(response.status).toBe(307)
+ expect(response.headers.get('location')).toBe(
+ 'http://localhost:3000/auth/login'
+ )
+ })
+})
diff --git a/lib/supabase/middleware.ts b/lib/supabase/middleware.ts
index 30afeb71..360c2703 100644
--- a/lib/supabase/middleware.ts
+++ b/lib/supabase/middleware.ts
@@ -77,3 +77,47 @@ export async function updateSession(request: NextRequest) {
return supabaseResponse
}
+
+/**
+ * Exchange the one-time PKCE code of a password-recovery link for a session,
+ * persisting it as cookies, then redirect to the clean destination URL. The
+ * recovery link keeps pointing at `/auth/update-password` (the destination
+ * existing deployments already allowlist in Supabase), so the exchange runs
+ * here in middleware where response cookies can be written.
+ */
+export async function exchangeRecoveryCode(
+ request: NextRequest,
+ code: string
+): Promise<NextResponse> {
+ const url = request.nextUrl.clone()
+ url.search = ''
+ let supabaseResponse = NextResponse.redirect(url)
+ const supabaseKey = getSupabasePublishableKey()
+
+ const supabase = createServerClient(
+ process.env.NEXT_PUBLIC_SUPABASE_URL!,
+ supabaseKey!,
+ {
+ cookies: {
+ getAll() {
+ return request.cookies.getAll()
+ },
+ setAll(cookiesToSet) {
+ cookiesToSet.forEach(({ name, value, options }) =>
+ supabaseResponse.cookies.set(name, value, options)
+ )
+ }
+ }
+ }
+ )
+
+ const { error } = await supabase.auth.exchangeCodeForSession(code)
+ if (error) {
+ const loginUrl = request.nextUrl.clone()
+ loginUrl.pathname = '/auth/login'
+ loginUrl.search = ''
+ return NextResponse.redirect(loginUrl)
+ }
+
+ return supabaseResponse
+}
diff --git a/lib/usage-budget/gate.ts b/lib/usage-budget/gate.ts
index 9f137ba6..6fbf0bfb 100644
--- a/lib/usage-budget/gate.ts
+++ b/lib/usage-budget/gate.ts
@@ -434,7 +434,7 @@ export async function getUsageBudget(params?: {
const requestedCreatedAt =
params?.userCreatedAt !== undefined
? params.userCreatedAt
- : user?.created_at
+ : user?.createdAt
const anchor = await usageAnchor({
userId,
userCreatedAt: requestedCreatedAt
diff --git a/lib/usage-budget/grants.ts b/lib/usage-budget/grants.ts
index ead5f9d3..2b27f770 100644
--- a/lib/usage-budget/grants.ts
+++ b/lib/usage-budget/grants.ts
@@ -34,7 +34,7 @@ export async function resolveUsageAnchor(
const user = await getCurrentUser()
if (!user || user.id !== userId) return null
- return parseAnchor(user.created_at)
+ return parseAnchor(user.createdAt)
}
export async function syncUsageGrants(params: {
diff --git a/proxy.test.ts b/proxy.test.ts
new file mode 100644
index 00000000..16cba587
--- /dev/null
+++ b/proxy.test.ts
@@ -0,0 +1,73 @@
+import { NextRequest, NextResponse } from 'next/server'
+
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+
+import { updateSession } from '@/lib/supabase/middleware'
+
+import { proxy } from './proxy'
+
+vi.mock('@/lib/supabase/middleware', () => ({
+ updateSession: vi.fn()
+}))
+
+const AUTH_ENV_KEYS = [
+ 'AUTH_PROVIDER',
+ 'ENABLE_AUTH',
+ 'NEXT_PUBLIC_SUPABASE_URL',
+ 'NEXT_PUBLIC_SUPABASE_PUBLISHABLE_KEY'
+] as const
+
+describe('proxy', () => {
+ const originalEnv: Record<string, string | undefined> = {}
+
+ beforeEach(() => {
+ vi.clearAllMocks()
+ for (const key of AUTH_ENV_KEYS) {
+ originalEnv[key] = process.env[key]
+ delete process.env[key]
+ }
+ })
+
+ afterEach(() => {
+ for (const key of AUTH_ENV_KEYS) {
+ if (originalEnv[key] === undefined) {
+ delete process.env[key]
+ } else {
+ process.env[key] = originalEnv[key]
+ }
+ }
+ })
+
+ it('passes through in anonymous mode (ENABLE_AUTH=false)', async () => {
+ process.env.ENABLE_AUTH = 'false'
+
+ const request = new NextRequest('http://localhost:3000/search/abc')
+ const response = await proxy(request)
+
+ expect(updateSession).not.toHaveBeenCalled()
+ expect(response.status).toBe(200)
+ expect(response.headers.get('location')).toBeNull()
+ expect(response.headers.get('x-url')).toBe(
+ 'http://localhost:3000/search/abc'
+ )
+ })
+
+ it('passes through when Supabase is not configured', async () => {
+ const request = new NextRequest('http://localhost:3000/search/abc')
+ const response = await proxy(request)
+
+ expect(updateSession).not.toHaveBeenCalled()
+ expect(response.status).toBe(200)
+ })
+
+ it('delegates session enforcement to updateSession when Supabase is configured', async () => {
+ process.env.NEXT_PUBLIC_SUPABASE_URL = 'https://example.supabase.co'
+ process.env.NEXT_PUBLIC_SUPABASE_PUBLISHABLE_KEY = 'sb_publishable_key'
+ vi.mocked(updateSession).mockResolvedValue(NextResponse.next())
+
+ const request = new NextRequest('http://localhost:3000/search/abc')
+ await proxy(request)
+
+ expect(updateSession).toHaveBeenCalledTimes(1)
+ })
+})
diff --git a/proxy.ts b/proxy.ts
index 8048b5fe..e0844746 100644
--- a/proxy.ts
+++ b/proxy.ts
@@ -1,7 +1,6 @@
import { type NextRequest, NextResponse } from 'next/server'
-import { hasSupabasePublicConfig } from '@/lib/supabase/keys'
-import { updateSession } from '@/lib/supabase/middleware'
+import { getAuthProvider } from '@/lib/auth/provider'
export async function proxy(request: NextRequest) {
// Get the protocol from X-Forwarded-Proto header or request protocol
@@ -15,17 +14,11 @@ export async function proxy(request: NextRequest) {
// Construct the base URL - ensure protocol has :// format
const baseUrl = `${protocol}${protocol.endsWith(':') ? '//' : '://'}${host}`
- // Create a response
+ // Create a response via the active auth provider's session enforcement
+ // (supabase refreshes/validates the session, none passes through)
let response: NextResponse
- if (hasSupabasePublicConfig()) {
- response = await updateSession(request)
- } else {
- // If Supabase is not configured, just pass the request through
- response = NextResponse.next({
- request
- })
- }
+ response = await getAuthProvider().handleSession(request)
// Add request information to response headers
response.headers.set('x-url', request.url)