Skip to content

An AI-powered search engine with a generative UI

feat(auth): add Better Auth provider for self-hosted multi-user instances (#1063)

Nathan Pride2cc1e236104f
diff --git a/.env.local.example b/.env.local.example
index f1294bb8..5f13f670 100644
--- a/.env.local.example
+++ b/.env.local.example
@@ -93,7 +93,7 @@ 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.
+# See docs/CONFIGURATION.md.
# AUTH_PROVIDER=supabase
# To enable Supabase authentication for multi-user deployments:
@@ -104,6 +104,25 @@ ANONYMOUS_USER_ID=anonymous-user
# Required for account deletion. Never expose this key to the browser.
# SUPABASE_SECRET_KEY=[YOUR_SUPABASE_SECRET_KEY]
+# Local multi-user accounts in Morphic's own Postgres (no Supabase needed).
+# See the "Local Authentication" section in README.md for the full walkthrough.
+# AUTH_PROVIDER=better-auth
+# BETTER_AUTH_SECRET=[RUN: openssl rand -hex 32]
+# Only this email may sign up while the user table is empty (recommended):
+# open (default) or invite (sign-up requires an admin-created invitation):
+# AUTH_SIGNUP_MODE=open
+# Optional SMTP (enables password-reset emails; also emails invitations):
+# SMTP_HOST=smtp.example.com
+# SMTP_PORT=587
+# SMTP_USER=[SMTP_USER]
+# SMTP_PASSWORD=[SMTP_PASSWORD]
+# EMAIL_FROM="Morphic <[email protected]>"
+# Required whenever SMTP is set: the canonical public origin used to build
+# every emailed link (resets, invitations, bootstrap). Without it those
+# flows refuse to send rather than trust request headers.
+# BETTER_AUTH_URL=https://morphic.example.com
+
# -----------------------------------------------------------------------------
# File Upload (Cloudflare R2 / S3-Compatible)
# -----------------------------------------------------------------------------
diff --git a/AGENTS.md b/AGENTS.md
index 3c9e099a..c3616843 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -120,7 +120,7 @@ DATABASE_URL= # PostgreSQL connection string
- Chat history: Set `ENABLE_SAVE_CHAT_HISTORY=true` and configure Redis
- Alternative AI providers: Add corresponding API keys (ANTHROPIC_API_KEY, GOOGLE_GENERATIVE_AI_API_KEY, etc.)
- Alternative search: Configure SEARCH_API and provider-specific settings
-- Sharing: Set `NEXT_PUBLIC_ENABLE_SHARE=true`
+- Sharing: Set `ENABLE_SHARE=true` (runtime flag; `NEXT_PUBLIC_ENABLE_SHARE=true` also works for source builds)
## Key Development Patterns
@@ -152,6 +152,10 @@ These checks are enforced in CI/CD and PRs will fail if any of these steps don't
Note: Import sorting is handled by ESLint using `eslint-plugin-simple-import-sort`. Run `bun lint --fix` to automatically sort imports according to the configured order.
+### Review-Fix Discipline
+
+When addressing review feedback, treat each fix as a change in its own right: walk every affected user journey (each auth provider, logged-in and logged-out states) and add test or harness coverage in the same commit rather than waiting for the next review round. See [docs/lessons-learned-review-fixes.md](docs/lessons-learned-review-fixes.md) for the full fix-round checklist.
+
## Model Configuration
Models are defined in `public/config/models.json` with:
diff --git a/README.md b/README.md
index 2ddb3896..4647af26 100644
--- a/README.md
+++ b/README.md
@@ -110,6 +110,50 @@ bun dev
Visit http://localhost:3000.
+### Local Authentication (better-auth)
+
+To run a multi-user Morphic on your own machine or LAN without Supabase, use the built-in `better-auth` provider. Accounts live in Morphic's own Postgres database.
+
+1. Configure `.env.local`:
+
+```bash
+AUTH_PROVIDER=better-auth
+BETTER_AUTH_SECRET=run-openssl-rand-hex-32-for-a-stable-value
+# Recommended whenever the instance is reachable by anyone but you:
+```
+
+2. Start Morphic. With Docker (`docker compose up -d`), database migrations run automatically at container start and create the auth tables. For local development (`bun dev` with a local Postgres), run `bun migrate` once before starting the dev server.
+
+3. First boot: open http://localhost:3000/auth/sign-up and create your account. The first account becomes the instance admin; the bootstrap window then closes. Note that the window is tied to the user table being empty: if the last account is ever deleted, the window reopens and the gated address (or, without SMTP, whoever signs up first) can claim admin again. Keep at least one account, or unset `BOOTSTRAP_ADMIN_EMAIL` before deleting the last one. When `BOOTSTRAP_ADMIN_EMAIL` is set, only that address can sign up during the window. If SMTP is configured, the bootstrap sign-up emails a one-time link to that address, so only someone who controls the mailbox can complete it — this requires `BETTER_AUTH_URL` (the link origin); without SMTP the first person to submit the gated address wins the window, so finish first boot before exposing the instance to others.
+
+#### Invite-only sign-up
+
+Set `AUTH_SIGNUP_MODE=invite` to require an invitation for new accounts:
+
+- On a fresh instance there are no invitations yet: set `BOOTSTRAP_ADMIN_EMAIL` and the first account for that address can sign up without an invitation (with SMTP configured, the bootstrap link is emailed to that address first), then create invitations from the admin page.
+- As admin, open the admin page (user menu → **Admin**) and create an invitation link for an email address. Each link is bound to that address, valid for one sign-up for 7 days, and can be revoked until used.
+- The invitee opens the link and completes sign-up; the token is consumed automatically.
+
+#### Password reset and SMTP
+
+Password reset requires SMTP and `BETTER_AUTH_URL`; without them the forgot-password flow is hidden and the admin can set member passwords from the admin page instead. `BETTER_AUTH_URL` is the canonical origin embedded in emailed links (password resets, invitations, bootstrap) — it is never derived from request headers, so a spoofed `Host` cannot redirect a live credential to an attacker domain.
+
+```bash
+SMTP_HOST=smtp.example.com
+SMTP_PORT=587
+SMTP_USER=smtp-user
+SMTP_PASSWORD=smtp-password
+EMAIL_FROM="Morphic <[email protected]>"
+BETTER_AUTH_URL=https://morphic.example.com
+```
+
+With SMTP configured, password-reset emails are sent and invitation links are additionally emailed to invitees.
+
+#### HTTPS and secure cookies
+
+In production builds (Docker), session cookies carry the `__Secure-` prefix, so browsers only store and send them over HTTPS or on `localhost`. An instance reached via `http://<LAN-IP>:3000` will not stay logged in; serve it over HTTPS (reverse proxy, Tailscale Serve, etc.). Development mode (`bun dev`) is not affected.
+
## Deploy
### Vercel
diff --git a/app/api/chat/__tests__/route.test.ts b/app/api/chat/__tests__/route.test.ts
index 0fa7be8e..1d60e06d 100644
--- a/app/api/chat/__tests__/route.test.ts
+++ b/app/api/chat/__tests__/route.test.ts
@@ -17,6 +17,9 @@ vi.mock('@/lib/auth/get-current-user', () => ({
getCurrentUser: vi.fn(),
getCurrentUserId: vi.fn()
}))
+vi.mock('@/lib/auth/provider', () => ({
+ isAnonymousMode: vi.fn(() => false)
+}))
vi.mock('@/lib/db/actions', () => ({ getUserMessageIds: vi.fn() }))
vi.mock('@/lib/db/schema', () => ({ generateId: vi.fn(() => 'message-id') }))
vi.mock('@/lib/rate-limit/adaptive-limit', () => ({
diff --git a/app/api/feedback/__tests__/route.test.ts b/app/api/feedback/__tests__/route.test.ts
index 89573ea5..12925be3 100644
--- a/app/api/feedback/__tests__/route.test.ts
+++ b/app/api/feedback/__tests__/route.test.ts
@@ -10,15 +10,9 @@ vi.mock('next/headers', () => ({
}))
}))
-// Mock Supabase
-vi.mock('@/lib/supabase/server', () => ({
- createClient: vi.fn(() => ({
- auth: {
- getUser: vi.fn(() =>
- Promise.resolve({ data: { user: null }, error: null })
- )
- }
- }))
+// Mock the auth provider seam
+vi.mock('@/lib/auth/get-current-user', () => ({
+ getCurrentUser: vi.fn(async () => null)
}))
// Mock the modules
@@ -45,6 +39,7 @@ vi.mock('@langfuse/client', () => ({
import { LangfuseClient } from '@langfuse/client'
import { updateMessageFeedback } from '@/lib/actions/feedback'
+import { getCurrentUser } from '@/lib/auth/get-current-user'
import { isTracingEnabled } from '@/lib/utils/telemetry'
import { POST } from '../route'
@@ -105,6 +100,48 @@ describe('Feedback API Route', () => {
)
})
+ it('should attribute feedback to the active provider user', async () => {
+ vi.mocked(isTracingEnabled).mockReturnValue(true)
+ vi.mocked(updateMessageFeedback).mockResolvedValue({
+ success: true
+ })
+ vi.mocked(getCurrentUser).mockResolvedValue({
+ id: 'provider-user-1',
+ })
+
+ const mockScoreCreate = vi.fn()
+ vi.mocked(LangfuseClient).mockImplementation(function () {
+ return {
+ score: {
+ create: mockScoreCreate,
+ flush: vi.fn(() => Promise.resolve())
+ }
+ } as any
+ } as any)
+
+ const request = new Request('http://localhost:3000/api/feedback', {
+ method: 'POST',
+ headers: {
+ 'Content-Type': 'application/json'
+ },
+ body: JSON.stringify({
+ traceId: 'test-trace-id',
+ score: 1,
+ messageId: 'test-message-id'
+ })
+ })
+
+ const response = await POST(request)
+
+ expect(response.status).toBe(200)
+ expect(updateMessageFeedback).toHaveBeenCalledWith(
+ 'test-message-id',
+ 1,
+ 'provider-user-1'
+ )
+ })
+
it('should handle negative feedback', async () => {
vi.mocked(isTracingEnabled).mockReturnValue(true)
vi.mocked(updateMessageFeedback).mockResolvedValue({
diff --git a/app/api/feedback/route.ts b/app/api/feedback/route.ts
index 2e275a91..8015a736 100644
--- a/app/api/feedback/route.ts
+++ b/app/api/feedback/route.ts
@@ -1,8 +1,7 @@
import { LangfuseClient } from '@langfuse/client'
import { updateMessageFeedback } from '@/lib/actions/feedback'
-import { hasSupabasePublicConfig } from '@/lib/supabase/keys'
-import { createClient } from '@/lib/supabase/server'
+import { getCurrentUser } from '@/lib/auth/get-current-user'
import { isTracingEnabled } from '@/lib/utils/telemetry'
export async function POST(req: Request) {
@@ -45,16 +44,11 @@ export async function POST(req: Request) {
// Flush to ensure the score is sent
await langfuse.score.flush()
- // Get current user for RLS context
+ // Get current user for RLS context (provider-agnostic seam)
let userId: string | null = null
- if (hasSupabasePublicConfig()) {
- const supabase = await createClient()
- const {
- data: { user }
- } = await supabase.auth.getUser()
- userId = user?.id || null
- }
+ const user = await getCurrentUser()
+ userId = user?.id ?? null
// Update the message metadata with the feedback score using the action
if (messageId) {
diff --git a/app/auth/__tests__/sign-up-page.test.ts b/app/auth/__tests__/sign-up-page.test.ts
new file mode 100644
index 00000000..fa1ea6f5
--- /dev/null
+++ b/app/auth/__tests__/sign-up-page.test.ts
@@ -0,0 +1,141 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest'
+
+import {
+ getSignUpMode,
+ isBootstrapWindowOpen
+} from '@/lib/auth/better-auth/config'
+import { validateInvitation } from '@/lib/auth/better-auth/invitations'
+import { getAuthProvider } from '@/lib/auth/provider'
+
+import Page from '../sign-up/page'
+
+vi.mock('next/navigation', () => ({ redirect: vi.fn() }))
+vi.mock('@/lib/auth/provider', () => ({ getAuthProvider: vi.fn() }))
+vi.mock('@/lib/auth/better-auth/config', () => ({
+ getSignUpMode: vi.fn(() => 'open'),
+ isBootstrapWindowOpen: vi.fn(async () => false)
+}))
+vi.mock('@/lib/auth/better-auth/invitations', () => ({
+ validateInvitation: vi.fn()
+}))
+vi.mock('@/components/sign-up-form', () => ({ SignUpForm: () => null }))
+vi.mock('@/components/invite-required', () => ({ InviteRequired: () => null }))
+
+import { redirect } from 'next/navigation'
+
+import { InviteRequired } from '@/components/invite-required'
+
+describe('sign-up page', () => {
+ beforeEach(() => {
+ vi.clearAllMocks()
+ })
+
+ it('redirects to login when the provider cannot sign up', async () => {
+ vi.mocked(getAuthProvider).mockReturnValue({
+ capabilities: { signUp: false }
+ } as never)
+
+ await Page({ searchParams: Promise.resolve({}) })
+
+ expect(redirect).toHaveBeenCalledWith('/auth/login')
+ })
+
+ it('renders the form when sign-up is supported', async () => {
+ vi.mocked(getAuthProvider).mockReturnValue({
+ capabilities: { signUp: true }
+ } as never)
+
+ await Page({ searchParams: Promise.resolve({}) })
+
+ expect(redirect).not.toHaveBeenCalled()
+ })
+
+ it('passes the bound invitation email to the form', async () => {
+ vi.mocked(getAuthProvider).mockReturnValue({
+ name: 'better-auth',
+ capabilities: { signUp: true }
+ } as never)
+ vi.mocked(getSignUpMode).mockReturnValue('invite')
+ vi.mocked(validateInvitation).mockResolvedValue({
+ id: 'inv-1',
+ } as never)
+
+ const tree = (await Page({
+ searchParams: Promise.resolve({ token: 'tok' })
+ })) as unknown as {
+ props: {
+ children: { props: { children: { props: Record<string, unknown> } } }
+ }
+ }
+
+ expect(tree.props.children.props.children.props).toMatchObject({
+ token: 'tok',
+ inviteEmail: '[email protected]'
+ })
+ })
+
+ it('forwards a valid invitation token in open mode too', async () => {
+ // SMTP bootstrap flow: the emailed link must reach the form even in
+ // open mode, or submitting the gated address restarts the email loop.
+ vi.mocked(getAuthProvider).mockReturnValue({
+ name: 'better-auth',
+ capabilities: { signUp: true }
+ } as never)
+ vi.mocked(validateInvitation).mockResolvedValue({
+ id: 'inv-1',
+ } as never)
+
+ const tree = (await Page({
+ searchParams: Promise.resolve({ token: 'boot-token' })
+ })) as unknown as {
+ props: {
+ children: { props: { children: { props: Record<string, unknown> } } }
+ }
+ }
+
+ expect(tree.props.children.props.children.props).toMatchObject({
+ token: 'boot-token',
+ inviteEmail: '[email protected]'
+ })
+ })
+
+ it('renders the form while the bootstrap window is open in invite mode', async () => {
+ // Fresh invite-only instance: the gated address must reach the form;
+ // the address itself is enforced at creation time.
+ vi.mocked(getAuthProvider).mockReturnValue({
+ name: 'better-auth',
+ capabilities: { signUp: true }
+ } as never)
+ vi.mocked(getSignUpMode).mockReturnValue('invite')
+ vi.mocked(validateInvitation).mockResolvedValue(null)
+ vi.mocked(isBootstrapWindowOpen).mockResolvedValue(true)
+
+ const tree = (await Page({
+ searchParams: Promise.resolve({})
+ })) as unknown as {
+ props: { children: { props: { children: { type: unknown } } } }
+ }
+
+ expect(tree.props.children.props.children.type).not.toBe(InviteRequired)
+ })
+
+ it('shows the invite wall in invite mode once the bootstrap window closed', async () => {
+ vi.mocked(getAuthProvider).mockReturnValue({
+ name: 'better-auth',
+ capabilities: { signUp: true }
+ } as never)
+ vi.mocked(getSignUpMode).mockReturnValue('invite')
+ vi.mocked(validateInvitation).mockResolvedValue(null)
+ vi.mocked(isBootstrapWindowOpen).mockResolvedValue(false)
+
+ const tree = (await Page({
+ searchParams: Promise.resolve({})
+ })) as unknown as {
+ props: { children: { props: { children: { type: unknown } } } }
+ }
+
+ expect(tree.props.children.props.children.type).toBe(InviteRequired)
+ })
+})
diff --git a/app/auth/admin/page.tsx b/app/auth/admin/page.tsx
new file mode 100644
index 00000000..8538a586
--- /dev/null
+++ b/app/auth/admin/page.tsx
@@ -0,0 +1,90 @@
+import { redirect } from 'next/navigation'
+
+import { invitationView } from '@/lib/actions/admin-views'
+import { listInvitations } from '@/lib/auth/better-auth/invitations'
+import { listMembers } from '@/lib/auth/better-auth/members'
+import { getCurrentUser } from '@/lib/auth/get-current-user'
+import { getAuthProvider } from '@/lib/auth/provider'
+
+import {
+ Card,
+ CardContent,
+ CardDescription,
+ CardHeader,
+ CardTitle
+} from '@/components/ui/card'
+
+import { InvitationsManager } from '@/components/admin/invitations-manager'
+import { MemberRoleManager } from '@/components/admin/member-role-manager'
+import { ResetMemberPasswordForm } from '@/components/admin/reset-member-password-form'
+
+// The provider check below short-circuits at build time (the build has no
+// better-auth configuration), which would bake the redirect('/') into a
+// static route and make the admin page unreachable at runtime.
+export const dynamic = 'force-dynamic'
+
+export default async function AdminPage() {
+ const provider = getAuthProvider()
+ if (provider.name !== 'better-auth') {
+ redirect('/')
+ }
+
+ const user = await getCurrentUser()
+ if (!user || user.role !== 'admin') {
+ redirect('/')
+ }
+
+ const [invitations, members] = await Promise.all([
+ listInvitations(),
+ listMembers()
+ ])
+
+ return (
+ <div className="mx-auto flex w-full max-w-3xl flex-col gap-6 p-6">
+ <div>
+ <h1 className="text-2xl font-semibold">Instance administration</h1>
+ <p className="text-sm text-muted-foreground">
+ Manage invitations and member accounts for this Morphic instance.
+ </p>
+ </div>
+
+ <Card>
+ <CardHeader>
+ <CardTitle>Invitations</CardTitle>
+ <CardDescription>
+ Create invitation links for sign-up when the instance runs in invite
+ mode.
+ </CardDescription>
+ </CardHeader>
+ <CardContent>
+ <InvitationsManager invitations={invitations.map(invitationView)} />
+ </CardContent>
+ </Card>
+
+ <Card>
+ <CardHeader>
+ <CardTitle>Member roles</CardTitle>
+ <CardDescription>
+ Promote members to admin. The last remaining admin cannot delete
+ their own account until another admin exists.
+ </CardDescription>
+ </CardHeader>
+ <CardContent>
+ <MemberRoleManager members={members} />
+ </CardContent>
+ </Card>
+
+ <Card>
+ <CardHeader>
+ <CardTitle>Reset member password</CardTitle>
+ <CardDescription>
+ Set a new password for a member without email delivery.
+ </CardDescription>
+ </CardHeader>
+ <CardContent>
+ <ResetMemberPasswordForm members={members} />
+ </CardContent>
+ </Card>
+ </div>
+ )
+}
diff --git a/app/auth/forgot-password/page.tsx b/app/auth/forgot-password/page.tsx
index c2568ca2..f5b744a4 100644
--- a/app/auth/forgot-password/page.tsx
+++ b/app/auth/forgot-password/page.tsx
@@ -1,6 +1,19 @@
+import { redirect } from 'next/navigation'
+
+import { getAuthProvider } from '@/lib/auth/provider'
+
import { ForgotPasswordForm } from '@/components/forgot-password-form'
-export default function Page() {
+// The passwordReset capability depends on runtime env (SMTP configuration),
+// so the gate must not be frozen into a static prerender.
+export const dynamic = 'force-dynamic'
+
+export default function ForgotPasswordPage() {
+ const provider = getAuthProvider()
+ if (!provider.capabilities.passwordReset) {
+ redirect('/auth/login')
+ }
+
return (
<div className="flex min-h-svh w-full items-center justify-center p-6 md:p-10">
<div className="w-full max-w-sm">
diff --git a/app/auth/login/page.tsx b/app/auth/login/page.tsx
index 3ac37e2c..e9c5774c 100644
--- a/app/auth/login/page.tsx
+++ b/app/auth/login/page.tsx
@@ -1,10 +1,18 @@
import { LoginForm } from '@/components/login-form'
-export default function Page() {
+// Capabilities and provider selection depend on runtime env (AUTH_PROVIDER);
+// a prerendered login page would bake in build-time values in prebuilt images.
+export const dynamic = 'force-dynamic'
+
+export default async function Page(props: {
+ searchParams: Promise<{ next?: string }>
+}) {
+ const { next } = await props.searchParams
+
return (
<div className="flex min-h-svh w-full items-center justify-center p-6 md:p-10">
<div className="w-full max-w-sm">
- <LoginForm />
+ <LoginForm next={next} />
</div>
</div>
)
diff --git a/app/auth/oauth/route.ts b/app/auth/oauth/route.ts
index f46745eb..947d8dc0 100644
--- a/app/auth/oauth/route.ts
+++ b/app/auth/oauth/route.ts
@@ -1,13 +1,22 @@
-import { NextResponse } from 'next/server'
+import { NextRequest, NextResponse } from 'next/server'
// The client you created from the Server-Side Auth instructions
+import { safeRedirectPath } from '@/lib/auth/redirect-target'
import { createClient } from '@/lib/supabase/server'
-export async function GET(request: Request) {
+export async function GET(request: NextRequest) {
const { searchParams, origin } = new URL(request.url)
const code = searchParams.get('code')
- // if "next" is in param, use it as the redirect URL
- const next = searchParams.get('next') ?? '/'
+ // if "next" is in param, use it as the redirect URL (same-origin paths
+ // only, so a crafted ?next= cannot bounce the signed-in user off-site).
+ // The login form carries the destination in a short-lived cookie because
+ // Supabase's redirect allowlist matches the callback URL exactly and
+ // would reject a query-string variant of it.
+ const next = safeRedirectPath(
+ searchParams.get('next') ??
+ request.cookies.get('auth_next')?.value ??
+ undefined
+ )
if (code) {
const supabase = await createClient()
@@ -15,14 +24,14 @@ export async function GET(request: Request) {
if (!error) {
const forwardedHost = request.headers.get('x-forwarded-host') // original origin before load balancer
const isLocalEnv = process.env.NODE_ENV === 'development'
- if (isLocalEnv) {
- // we can be sure that there is no load balancer in between, so no need to watch for X-Forwarded-Host
- return NextResponse.redirect(`${origin}${next}`)
- } else if (forwardedHost) {
- return NextResponse.redirect(`https://${forwardedHost}${next}`)
- } else {
- return NextResponse.redirect(`${origin}${next}`)
- }
+ const target = isLocalEnv
+ ? `${origin}${next}`
+ : forwardedHost
+ ? `https://${forwardedHost}${next}`
+ : `${origin}${next}`
+ const response = NextResponse.redirect(target)
+ response.cookies.delete('auth_next')
+ return response
}
}
diff --git a/app/auth/sign-up/page.tsx b/app/auth/sign-up/page.tsx
index 9662667e..e5e49614 100644
--- a/app/auth/sign-up/page.tsx
+++ b/app/auth/sign-up/page.tsx
@@ -1,10 +1,62 @@
+import { redirect } from 'next/navigation'
+
+import {
+ getSignUpMode,
+ isBootstrapWindowOpen
+} from '@/lib/auth/better-auth/config'
+import { validateInvitation } from '@/lib/auth/better-auth/invitations'
+import { getAuthProvider } from '@/lib/auth/provider'
+
+import { InviteRequired } from '@/components/invite-required'
import { SignUpForm } from '@/components/sign-up-form'
-export default function Page() {
+// The provider, sign-up mode, and invitation validity are runtime concerns.
+// Without this, a build where the better-auth branch is not taken gets
+// prerendered as a static page, so the invite wall and ?token= prefill
+// never run in an invite-mode deployment.
+export const dynamic = 'force-dynamic'
+
+export default async function SignUpPage({
+ searchParams
+}: {
+ searchParams: Promise<{ token?: string }>
+}) {
+ const provider = getAuthProvider()
+
+ if (!provider.capabilities.signUp) {
+ redirect('/auth/login')
+ }
+
+ let inviteRequired = false
+ let validToken: string | undefined
+ let inviteEmail: string | undefined
+
+ if (provider.name === 'better-auth') {
+ // Read the token in every sign-up mode: with SMTP configured the
+ // bootstrap address receives its link by email, and open mode must
+ // pass that token through or the form would restart the email flow
+ // forever.
+ const { token } = await searchParams
+ const invitation = token ? await validateInvitation(token) : null
+ if (invitation) {
+ validToken = token
+ inviteEmail = invitation.email ?? undefined
+ } else if (getSignUpMode() === 'invite') {
+ // A fresh invite-only instance has no invitations yet: show the form
+ // while the bootstrap window is open so the gated address can create
+ // the first account. The address itself is enforced at creation time.
+ inviteRequired = !(await isBootstrapWindowOpen())
+ }
+ }
+
return (
<div className="flex min-h-svh w-full items-center justify-center p-6 md:p-10">
<div className="w-full max-w-sm">
- <SignUpForm />
+ {inviteRequired ? (
+ <InviteRequired />
+ ) : (
+ <SignUpForm token={validToken} inviteEmail={inviteEmail} />
+ )}
</div>
</div>
)
diff --git a/app/auth/update-password/page.tsx b/app/auth/update-password/page.tsx
index 96a68390..477decfb 100644
--- a/app/auth/update-password/page.tsx
+++ b/app/auth/update-password/page.tsx
@@ -1,10 +1,16 @@
import { UpdatePasswordForm } from '@/components/update-password-form'
-export default function Page() {
+export default async function UpdatePasswordPage({
+ searchParams
+}: {
+ searchParams: Promise<{ token?: string }>
+}) {
+ const { token } = await searchParams
+
return (
<div className="flex min-h-svh w-full items-center justify-center p-6 md:p-10">
<div className="w-full max-w-sm">
- <UpdatePasswordForm />
+ <UpdatePasswordForm token={token} />
</div>
</div>
)
diff --git a/app/layout.tsx b/app/layout.tsx
index c53588bf..8c10272b 100644
--- a/app/layout.tsx
+++ b/app/layout.tsx
@@ -4,7 +4,7 @@ import { Inter as FontSans } from 'next/font/google'
import { Analytics } from '@vercel/analytics/next'
import { getCurrentUser, getCurrentUserId } from '@/lib/auth/get-current-user'
-import { getAuthProvider } from '@/lib/auth/provider'
+import { getAuthProvider, withShareOptIn } from '@/lib/auth/provider'
import { AppUserProvider } from '@/lib/contexts/app-user-context'
import { UserProvider } from '@/lib/contexts/user-context'
import {
@@ -67,7 +67,15 @@ export default async function RootLayout({
children: React.ReactNode
}>) {
const user = await getCurrentUser()
- const capabilities = getAuthProvider().capabilities
+ // Sharing is opt-in for Better Auth (ENABLE_SHARE=true); the flag is
+ // folded into the capabilities on the server so a prebuilt image can
+ // still toggle it at runtime. Supabase shares without the flag, as it
+ // always has. shareChat enforces the same rule again.
+ const authProvider = getAuthProvider()
+ const capabilities = withShareOptIn(
+ authProvider.capabilities,
+ authProvider.name
+ )
const userId = user?.id ?? (await getCurrentUserId())
const isCloudDeployment = process.env.MORPHIC_CLOUD_DEPLOYMENT === 'true'
diff --git a/app/relay/[...path]/route.test.ts b/app/relay/[...path]/route.test.ts
new file mode 100644
index 00000000..f2613845
--- /dev/null
+++ b/app/relay/[...path]/route.test.ts
@@ -0,0 +1,155 @@
+import { NextRequest } from 'next/server'
+
+import { afterEach, describe, expect, it, vi } from 'vitest'
+
+import { cappedBody, GET, POST } from './route'
+
+function upstreamResponse() {
+ return new Response('{"status":"ok"}', {
+ status: 200,
+ headers: {
+ 'content-type': 'application/json',
+ 'cache-control': 'public, max-age=60'
+ }
+ })
+}
+
+describe('relay route', () => {
+ afterEach(() => {
+ vi.unstubAllGlobals()
+ })
+
+ it('proxies capture requests without credentials and forwards the payload', async () => {
+ const fetchMock = vi.fn(async () => upstreamResponse())
+ vi.stubGlobal('fetch', fetchMock)
+
+ const request = new NextRequest(
+ 'http://localhost:3000/relay/capture?batch=1',
+ {
+ method: 'POST',
+ headers: {
+ 'content-type': 'application/json',
+ cookie: 'better-auth.session_token=abc',
+ authorization: 'Bearer token',
+ 'x-forwarded-for': '203.0.113.7',
+ 'user-agent': 'Mozilla/5.0 (test)'
+ },
+ body: '{"api_key":"phk"}'
+ }
+ )
+
+ const response = await POST(request, {
+ params: Promise.resolve({ path: ['capture'] })
+ })
+
+ expect(response.status).toBe(200)
+ expect(await response.text()).toBe('{"status":"ok"}')
+
+ expect(fetchMock).toHaveBeenCalledTimes(1)
+ const [url, init] = fetchMock.mock.calls[0] as unknown as [
+ URL,
+ { method: string; headers: Headers; body: ReadableStream }
+ ]
+ expect(url.toString()).toBe('https://us.i.posthog.com/capture?batch=1')
+ expect(init.method).toBe('POST')
+ expect(init.headers.get('content-type')).toBe('application/json')
+ // PostHog geo/device stats need these (the old rewrites forwarded
+ // them too).
+ expect(init.headers.get('x-forwarded-for')).toBe('203.0.113.7')
+ expect(init.headers.get('user-agent')).toBe('Mozilla/5.0 (test)')
+ // Session credentials must never be forwarded to the analytics host.
+ expect(init.headers.get('cookie')).toBeNull()
+ expect(init.headers.get('authorization')).toBeNull()
+ // The body is streamed through, not buffered.
+ expect(await new Response(init.body).text()).toBe('{"api_key":"phk"}')
+ })
+
+ it('refuses declared payloads above the cap', async () => {
+ const fetchMock = vi.fn(async () => upstreamResponse())
+ vi.stubGlobal('fetch', fetchMock)
+
+ const request = new NextRequest('http://localhost:3000/relay/capture', {
+ method: 'POST',
+ headers: { 'content-type': 'application/json' },
+ body: '{}'
+ })
+ request.headers.set('content-length', String(64 * 1024 * 1024))
+
+ const response = await POST(request, {
+ params: Promise.resolve({ path: ['capture'] })
+ })
+
+ expect(response.status).toBe(413)
+ expect(fetchMock).not.toHaveBeenCalled()
+ })
+
+ it('refuses paths that resolve off the PostHog origin', async () => {
+ const fetchMock = vi.fn(async () => upstreamResponse())
+ vi.stubGlobal('fetch', fetchMock)
+
+ // A decoded segment starting with a slash would turn the joined path
+ // protocol-relative and resolve the target to an attacker host.
+ const request = new NextRequest(
+ 'http://localhost:3000/relay/%2f%2fevil.example/x'
+ )
+
+ const response = await GET(request, {
+ params: Promise.resolve({ path: ['//evil.example', 'x'] })
+ })
+
+ expect(response.status).toBe(404)
+ expect(fetchMock).not.toHaveBeenCalled()
+ })
+
+ it('routes static and array paths to the asset host', async () => {
+ const fetchMock = vi.fn(async () => upstreamResponse())
+ vi.stubGlobal('fetch', fetchMock)
+
+ const request = new NextRequest(
+ 'http://localhost:3000/relay/static/array.js'
+ )
+ await GET(request, {
+ params: Promise.resolve({ path: ['static', 'array.js'] })
+ })
+
+ const [url, init] = fetchMock.mock.calls[0] as unknown as [
+ URL,
+ { method: string; body: undefined }
+ ]
+ expect(url.toString()).toBe(
+ 'https://us-assets.i.posthog.com/static/array.js'
+ )
+ expect(init.method).toBe('GET')
+ expect(init.body).toBeUndefined()
+ })
+})
+
+describe('cappedBody', () => {
+ it('errors the stream when actual bytes exceed the cap', async () => {
+ // A chunked (undeclared) payload must be bounded by counting the
+ // bytes as they flow, not by the declared content-length.
+ const source = new ReadableStream<Uint8Array>({
+ start(controller) {
+ controller.enqueue(new Uint8Array(100))
+ controller.enqueue(new Uint8Array(100))
+ controller.close()
+ }
+ })
+
+ const capped = cappedBody(source, 150)
+
+ await expect(new Response(capped).text()).rejects.toBeDefined()
+ })
+
+ it('passes through bodies within the cap', async () => {
+ const source = new Response('hello').body
+
+ const capped = cappedBody(source, 10)
+
+ expect(await new Response(capped).text()).toBe('hello')
+ })
+
+ it('returns null for a missing body', () => {
+ expect(cappedBody(null)).toBeNull()
+ })
+})
diff --git a/app/relay/[...path]/route.ts b/app/relay/[...path]/route.ts
new file mode 100644
index 00000000..ff9e72ba
--- /dev/null
+++ b/app/relay/[...path]/route.ts
@@ -0,0 +1,131 @@
+import { type NextRequest } from 'next/server'
+
+// Mirrors the destinations of the PostHog proxy rewrites this handler
+// replaced.
+const ASSET_SEGMENTS = new Set(['static', 'array'])
+const ASSET_HOST = 'us-assets.i.posthog.com'
+const API_HOST = 'us.i.posthog.com'
+// Generous cap that only rejects absurd declared sizes; the body itself
+// is streamed through, so an undeclared (chunked) payload cannot be
+// used to balloon process memory.
+const MAX_BODY_BYTES = 32 * 1024 * 1024
+
+export class PayloadTooLargeError extends Error {}
+
+/**
+ * Passes the stream through while counting bytes, erroring the stream
+ * when the cap is exceeded: a declared content-length can be absent
+ * (chunked) or a lie, so the actual bytes must be counted as they flow.
+ * Nothing is buffered; the cap only bounds how much is forwarded.
+ */
+export function cappedBody(
+ body: ReadableStream<Uint8Array> | null,
+ max: number = MAX_BODY_BYTES
+): ReadableStream<Uint8Array> | null {
+ if (!body) {
+ return null
+ }
+ let total = 0
+ return body.pipeThrough(
+ new TransformStream<Uint8Array, Uint8Array>({
+ transform(chunk, controller) {
+ total += chunk.byteLength
+ if (total > max) {
+ controller.error(new PayloadTooLargeError())
+ return
+ }
+ controller.enqueue(chunk)
+ }
+ })
+ )
+}
+
+/**
+ * Same-origin PostHog relay, implemented as a route handler instead of a
+ * next.config rewrite so credentials are structurally never forwarded:
+ * a rewrite proxies the incoming request headers (session cookie
+ * included) to an external host, and keeping any middleware strip in
+ * sync with the rewrite's path matching is a drift hazard. This handler
+ * forwards only what PostHog needs and nothing else.
+ */
+async function relay(
+ request: NextRequest,
+ { params }: { params: Promise<{ path: string[] }> }
+): Promise<Response> {
+ const { path } = await params
+ const host = ASSET_SEGMENTS.has(path[0]) ? ASSET_HOST : API_HOST
+ const target = new URL(`/${path.join('/')}`, `https://${host}`)
+ if (target.host !== host) {
+ // A decoded path segment escaped the PostHog origin (e.g. an encoded
+ // slash turning the joined path protocol-relative). Refuse rather
+ // than proxy payloads to an attacker-chosen host.
+ return new Response('Not found', { status: 404 })
+ }
+ target.search = request.nextUrl.search
+
+ const contentLength = Number(request.headers.get('content-length'))
+ if (Number.isFinite(contentLength) && contentLength > MAX_BODY_BYTES) {
+ return new Response('Payload too large', { status: 413 })
+ }
+
+ const headers = new Headers()
+ const contentType = request.headers.get('content-type')
+ if (contentType) {
+ headers.set('content-type', contentType)
+ }
+ // PostHog derives geo/device stats from these; the old next.config
+ // rewrites forwarded them too. Cookie and Authorization are
+ // deliberately not forwarded: session credentials must never reach
+ // the analytics provider.
+ const forwardedFor = request.headers.get('x-forwarded-for')
+ if (forwardedFor) {
+ headers.set('x-forwarded-for', forwardedFor)
+ }
+ const userAgent = request.headers.get('user-agent')
+ if (userAgent) {
+ headers.set('user-agent', userAgent)
+ }
+
+ // The body is streamed through rather than buffered: /relay is
+ // reachable without a session, so materializing an attacker-sized
+ // POST in memory would be a denial-of-service vector. cappedBody
+ // bounds the forwarded bytes even when no content-length was sent.
+ const body =
+ request.method === 'GET' || request.method === 'HEAD'
+ ? undefined
+ : cappedBody(request.body)
+
+ let upstream: Response
+ try {
+ upstream = await fetch(target, {
+ method: request.method,
+ headers,
+ body,
+ duplex: 'half'
+ } as RequestInit & { duplex?: 'half' })
+ } catch (error) {
+ if (
+ error instanceof PayloadTooLargeError ||
+ (error instanceof Error && error.cause instanceof PayloadTooLargeError)
+ ) {
+ return new Response('Payload too large', { status: 413 })
+ }
+ throw error
+ }
+
+ const responseHeaders = new Headers()
+ const upstreamContentType = upstream.headers.get('content-type')
+ if (upstreamContentType) {
+ responseHeaders.set('content-type', upstreamContentType)
+ }
+ const cacheControl = upstream.headers.get('cache-control')
+ if (cacheControl) {
+ responseHeaders.set('cache-control', cacheControl)
+ }
+ return new Response(upstream.body, {
+ status: upstream.status,
+ headers: responseHeaders
+ })
+}
+
+export { relay as GET, relay as POST }
diff --git a/app/search/[id]/page.tsx b/app/search/[id]/page.tsx
index 612b25a0..d57b87d5 100644
--- a/app/search/[id]/page.tsx
+++ b/app/search/[id]/page.tsx
@@ -37,11 +37,19 @@ export default async function SearchPage(props: {
const chat = await loadChat(id, userId)
if (!chat) {
+ // A logged-out visitor cannot tell a private chat from a missing one:
+ // both are hidden behind null by the permission check in the loader.
+ // Send them to sign in (the owner can then open their private link)
+ // instead of a dead-end 404; public chats render above without a
+ // login bounce. The ?next= carries the chat back through the login.
+ if (!userId) {
+ redirect(`/auth/login?next=${encodeURIComponent(`/search/${id}`)}`)
+ }
notFound()
}
if (chat.visibility === 'private' && !userId) {
- redirect('/auth/login')
+ redirect(`/auth/login?next=${encodeURIComponent(`/search/${id}`)}`)
}
const messages: UIMessage[] = chat.messages
diff --git a/bun.lock b/bun.lock
index 24fc4fd9..6417878c 100644
--- a/bun.lock
+++ b/bun.lock
@@ -56,6 +56,7 @@
"@vercel/otel": "^2.1.3",
"ai": "^7.0.66",
"ai-sdk-ollama": "^4.1.0",
+ "better-auth": "^1.7.7",
"class-variance-authority": "^0.7.1",
"clsx": "^2.1.0",
"cmdk": "1.0.0",
@@ -69,6 +70,7 @@
"katex": "^0.16.10",
"next": "^16.2.6",
"node-html-parser": "^6.1.13",
+ "nodemailer": "^10.0.15",
"postgres": "^3.4.5",
"posthog-js": "^1.382.0",
"posthog-node": "^5.36.4",
@@ -255,6 +257,24 @@
"@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/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/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/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/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/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/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/utils": ["@better-auth/[email protected]", "", { "dependencies": { "@noble/hashes": "^2.0.1" } }, "sha512-AUxrvu+HaaODsUyzDxFgwd/8RZ1yZaYo42LXKSrU2oGgR38pS1ij8nqQKNgtTWoYGpNevNXtCfgTy6loHveW9A=="],
+
+ "@better-fetch/fetch": ["@better-fetch/[email protected]", "", {}, "sha512-Gs7n99b5tqUC6cQAPbV0uED3IraHB6xQbHLQ/C3l7ZFafHScOx9pQ+DYmP5blbLFShVWLqxNUlI9wi4xU/X+ow=="],
+
"@braintree/sanitize-url": ["@braintree/[email protected]", "", {}, "sha512-i1L7noDNxtFyL5DmZafWy1wRVhGehQmzZaz1HiN5e7iylJMSZR7ekOV7NsIqa5qBldlLrsKv4HbgFUVlQrz8Mw=="],
"@chevrotain/cst-dts-gen": ["@chevrotain/[email protected]", "", { "dependencies": { "@chevrotain/gast": "11.1.2", "@chevrotain/types": "11.1.2", "lodash-es": "4.17.23" } }, "sha512-XTsjvDVB5nDZBQB8o0o/0ozNelQtn2KrUVteIHSlPd2VAV2utEb6JzyCJaJ8tGxACR4RiBNWy5uYUHX2eji88Q=="],
@@ -473,6 +493,8 @@
"@next/swc-win32-x64-msvc": ["@next/[email protected]", "", { "os": "win32", "cpu": "x64" }, "sha512-F0+4i0h9J6C4eE3EAPWsoCk7UW/dbzOjyzxY0qnDUOYFu6FFmdZ6l97/XdV3/Nz3VYyO7UWjyEJUXkGqcoXfMA=="],
+ "@noble/ciphers": ["@noble/[email protected]", "", {}, "sha512-AnjFn0Jv92laAkvMrghlFZq4qQCIN/4DxFV/eooqtC2YTjB7kBeLMS2T9KJX4Dn+ZVXLOwK0lSgqDtx9gvxtiw=="],
+
"@noble/hashes": ["@noble/[email protected]", "", {}, "sha512-jCs9ldd7NwzpgXDIf6P3+NrHh9/sD6CQdxHyjQI+h/6rDNo88ypBxxz45UDuZHz9r3tNz7N/VInSVoVdtXEI4A=="],
"@nodelib/fs.scandir": ["@nodelib/[email protected]", "", { "dependencies": { "@nodelib/fs.stat": "2.0.5", "run-parallel": "^1.1.9" } }, "sha512-vq24Bq3ym5HEQm2NKCr3yXDwjc7vTsEThRDnkp2DK9p1uqLR+DHurm/NOTo0KG7HYHU7eppKZj3MyqYuMBf62g=="],
@@ -1097,6 +1119,10 @@
"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-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=="],
+
"boolbase": ["[email protected]", "", {}, "sha512-JZOSA7Mo9sNGB8+UjSgzdLtokWAky1zbztM3WRLCbZ70/3cTANmQmOdR7y2g+J0e2WXywy1yS468tY+IruqEww=="],
"bowser": ["[email protected]", "", {}, "sha512-AlcaJBi/pqqJBIQ8U9Mcpc9i8Aqxn88Skv5d+xBX006BY5u8N3mGLHa5Lgppa7L/HfwgwLgZ6NYs+Ag6uUmJRA=="],
@@ -1283,6 +1309,8 @@
"define-properties": ["[email protected]", "", { "dependencies": { "define-data-property": "^1.0.1", "has-property-descriptors": "^1.0.0", "object-keys": "^1.1.1" } }, "sha512-8QmQKqEASLd5nx0U1B1okLElbUuuttJ/AnYmRXbbbGDWh6uS208EjD4Xqq/I9wK7u0v6O08XhTWnt5XtEbR6Dg=="],
+ "defu": ["[email protected]", "", {}, "sha512-7z22QmUWiQ/2d0KkdYmANbRUVABpZ9SNYyH5vx6PZ+nE5bcC0l7uFvEfHlyld/HcGBFTL536ClDt3DEcSlEJAQ=="],
+
"delaunator": ["[email protected]", "", { "dependencies": { "robust-predicates": "^3.0.2" } }, "sha512-8nvh+XBe96aCESrGOqMp/84b13H9cdKbG5P2ejQCh4d4sK9RL4371qou9drQjMhvnPmhWl5hnmqbEE0fXr9Xnw=="],
"dequal": ["[email protected]", "", {}, "sha512-0je+qPKHEMohvfRTCEo3CrPG6cAzAYgmzKyxRiYSSDkS6eGJdyVJm7WaYA5ECaAD9wLB2T4EEeymA5aFVcYXCA=="],
@@ -1611,7 +1639,7 @@
"jiti": ["[email protected]", "", { "bin": { "jiti": "lib/jiti-cli.mjs" } }, "sha512-twQoecYPiVA5K/h6SxtORw/Bs3ar+mLUtoPSc7iMXzQzK8d7eJ/R09wmTwAjiamETn1cXYPGfNnu7DMoHgu12w=="],
- "jose": ["[email protected]", "", {}, "sha512-1vUQX+IdDMVPj4k8kOxgUqlcK518yluMuGZwqlr44FS1ppZB/5GWh4rZG89erpOBOJjU/OBsnCVFfapsRz6nEA=="],
+ "jose": ["[email protected]", "", {}, "sha512-9NiFmJEex0sy2Dk58j2UGBSHgUs2ypF9eZSu4L6vjOX3Dp96Sw1F3uL+H+D1sx02jZZdzUT0HgvCy59CuvXcWw=="],
"js-tiktoken": ["[email protected]", "", { "dependencies": { "base64-js": "^1.5.1" } }, "sha512-Xlaqhhs8VfCd6Sh7a1cFkZHQbYTLCwVJJWiHVxBYzLPxW0XsoxBy1hitmjkdIjD3Aon5BXLHFwU5O8WUx6HH+A=="],
@@ -1643,6 +1671,8 @@
"khroma": ["[email protected]", "", {}, "sha512-Ls993zuzfayK269Svk9hzpeGUKob/sIgZzyHYdjQoAdQetRKpOLj+k/QQQ/6Qi0Yz65mlROrfd+Ev+1+7dz9Kw=="],
+ "kysely": ["[email protected]", "", {}, "sha512-hHaB8C/rfzDDtr/t8YZwxAuPJTT0zHyaPoVzcXwDYhYNAgH/4sIfVhi/XLLIY+bL/FqaIJnjATDbi8ObSELmxg=="],
+
"langium": ["[email protected]", "", { "dependencies": { "chevrotain": "~11.1.1", "chevrotain-allstar": "~0.3.1", "vscode-languageserver": "~9.0.1", "vscode-languageserver-textdocument": "~1.0.11", "vscode-uri": "~3.1.0" } }, "sha512-zu9QWmjpzJcomzdJQAHgDVhLGq5bLosVak1KVa40NzQHXfqr4eAHupvnPOVXEoLkg6Ocefvf/93d//SB7du4YQ=="],
"language-subtag-registry": ["[email protected]", "", {}, "sha512-0K65Lea881pHotoGEa5gDlMxt3pctLi2RplBb7Ezh4rRdLEOtgi7n4EwK9lamnUCkKBqaeKRVebTq6BAxSkpXQ=="],
@@ -1821,6 +1851,8 @@
"nanoid": ["[email protected]", "", { "bin": { "nanoid": "bin/nanoid.cjs" } }, "sha512-N8SpfPUnUp1bK+PMYW8qSWdl9U+wwNWI4QKxOYDy9JAro3WMX7p2OeVRF9v+347pnakNevPmiHhNmZ2HbFA76w=="],
+ "nanostores": ["[email protected]", "", {}, "sha512-4UXY7OAJEK0Y6V3SudBU7cXjAzTDc189R78dDOh0Xbm19gpKYto6WizSg58LJf12lTsRxKSLGyE117OiLpM4DQ=="],
+
"napi-postinstall": ["[email protected]", "", { "bin": { "napi-postinstall": "lib/cli.js" } }, "sha512-tWVJxJHmBWLy69PvO96TZMZDrzmw5KeiZBz3RHmiM2XZ9grBJ2WgMAFVVg25nqp3ZjTFUs2Ftw1JhscL3Teliw=="],
"natural-compare": ["[email protected]", "", {}, "sha512-OWND8ei3VtNC9h7V60qff3SVobHr996CTwgxubgyQYEpg290h9J0buyECNNJexkFm5sOajh5G116RYA1c8ZMSw=="],
@@ -1833,6 +1865,8 @@
"node-releases": ["[email protected]", "", {}, "sha512-xxOWJsBKtzAq7DY0J+DTzuz58K8e7sJbdgwkbMWQe8UYB6ekmsQ45q0M/tJDsGaZmbC+l7n57UV8Hl5tHxO9uw=="],
+ "nodemailer": ["[email protected]", "", {}, "sha512-EUqp5PhtcsYXs9Fq/lS7s/8zlTrnBqmzZWzFFROrNikMiz+om/YRKMwqN907t+0A1KKyT8jd39CBUbFZmaZmcA=="],
+
"nth-check": ["[email protected]", "", { "dependencies": { "boolbase": "^1.0.0" } }, "sha512-lqjrjmaOoAnWfMmBPL+XNnynZh2+swxiX3WUE0s4yEHI6m+AwrK2UZOimIRl3X/4QctVqS8AiZjFqyOGrMXb/w=="],
"nwsapi": ["[email protected]", "", {}, "sha512-o6nIY3qwiSXl7/LuOU0Dmuctd34Yay0yeuZRLFmDPrrdHpXKFndPj3hM+YEPVHYC5fx2otBx4Ilc/gyYSAUaIA=="],
@@ -1985,6 +2019,8 @@
"rollup": ["[email protected]", "", { "dependencies": { "@types/estree": "1.0.8" }, "optionalDependencies": { "@rollup/rollup-android-arm-eabi": "4.46.2", "@rollup/rollup-android-arm64": "4.46.2", "@rollup/rollup-darwin-arm64": "4.46.2", "@rollup/rollup-darwin-x64": "4.46.2", "@rollup/rollup-freebsd-arm64": "4.46.2", "@rollup/rollup-freebsd-x64": "4.46.2", "@rollup/rollup-linux-arm-gnueabihf": "4.46.2", "@rollup/rollup-linux-arm-musleabihf": "4.46.2", "@rollup/rollup-linux-arm64-gnu": "4.46.2", "@rollup/rollup-linux-arm64-musl": "4.46.2", "@rollup/rollup-linux-loongarch64-gnu": "4.46.2", "@rollup/rollup-linux-ppc64-gnu": "4.46.2", "@rollup/rollup-linux-riscv64-gnu": "4.46.2", "@rollup/rollup-linux-riscv64-musl": "4.46.2", "@rollup/rollup-linux-s390x-gnu": "4.46.2", "@rollup/rollup-linux-x64-gnu": "4.46.2", "@rollup/rollup-linux-x64-musl": "4.46.2", "@rollup/rollup-win32-arm64-msvc": "4.46.2", "@rollup/rollup-win32-ia32-msvc": "4.46.2", "@rollup/rollup-win32-x64-msvc": "4.46.2", "fsevents": "~2.3.2" }, "bin": { "rollup": "dist/bin/rollup" } }, "sha512-WMmLFI+Boh6xbop+OAGo9cQ3OgX9MIg7xOQjn+pTCwOkk+FNDAeAemXkJ3HzDJrVXleLOFVa1ipuc1AmEx1Dwg=="],
+ "rou3": ["[email protected]", "", {}, "sha512-3SOzvaAg8rkHrXtRjpCvCvbyO5to9oOO27Z/XqHEYXfMRVSw/qMIVdmaOk9W2lcRLtR6dlqTjo9hDeJk70QBYQ=="],
+
"roughjs": ["[email protected]", "", { "dependencies": { "hachure-fill": "^0.5.2", "path-data-parser": "^0.1.0", "points-on-curve": "^0.2.0", "points-on-path": "^0.2.1" } }, "sha512-ZUz/69+SYpFN/g/lUlo2FXcIjRkSu3nDarreVdGGndHEBJ6cXPdKguS8JGxwj5HA5xIbVKSmLgr5b3AWxtRfvQ=="],
"rrweb-cssom": ["[email protected]", "", {}, "sha512-guoltQEx+9aMf2gDZ0s62EcV8lsXR+0w8915TC3ITdn2YueuNjdAYh/levpU9nFaoChh9RUS5ZdQMrKfVEN9tw=="],
@@ -2255,8 +2291,6 @@
"yallist": ["[email protected]", "", {}, "sha512-3wdGidZyq5PB084XLES5TpOSRA3wjXAlIWMhum2kRcv/41Sn2emQ0dycQW4uZXLejwKvg6EsvbdlVL+FYEct7A=="],
- "yaml": ["[email protected]", "", { "bin": { "yaml": "bin.mjs" } }, "sha512-4lLa/EcQCB0cJkyts+FpIRx5G/llPxfP6VQU5KByHEhLxY3IJCH0f0Hy1MHI8sClTvsIb8qwRJ6R/ZdlDJ/leQ=="],
-
"yocto-queue": ["[email protected]", "", {}, "sha512-rVksvsnNCdJ/ohGc6xgPwyN8eheCxsiLM8mxuE/t/mOVqJewPuO1miLpTHQiRgTKCLexL4MeAFVagts7HmNZ2Q=="],
"zod": ["[email protected]", "", {}, "sha512-rftlrkhHZOcjDwkGlnUtZZkvaPHCsDATp4pGpuOOMDaTdDDXF91wuVDJoWoPsKX/3YPQ5fHuF3STjcYyKr+Qhg=="],
@@ -2287,6 +2321,10 @@
"@babel/traverse/debug": ["[email protected]", "", { "dependencies": { "ms": "^2.1.3" } }, "sha512-KcKCqiftBJcZr++7ykoDIEwSa3XWowTfNPo92BYxjXiyYEVrUQh2aLyhxBCwww+heortUFxEJYcRzosstTEBYQ=="],
+ "@better-auth/core/zod": ["[email protected]", "", {}, "sha512-v5l/aFXZQeai4awLbOpSoHecE9UiMrnfx75tEXLjNonXVARxQ5mOeipTjROUchszUNCqnE+hqAMujRsRHsut2Q=="],
+
+ "@better-auth/utils/@noble/hashes": ["@noble/[email protected]", "", {}, "sha512-X5XaVWZIBCT7HHZGm5I7ZQXDwLG+bGXuSrMQAW+7Zvl87h1kmc1ZB1VSRJcpUfoUrGQp4Fkoxm5kZ+Ms+aW+eA=="],
+
"@esbuild-kit/core-utils/esbuild": ["[email protected]", "", { "optionalDependencies": { "@esbuild/android-arm": "0.18.20", "@esbuild/android-arm64": "0.18.20", "@esbuild/android-x64": "0.18.20", "@esbuild/darwin-arm64": "0.18.20", "@esbuild/darwin-x64": "0.18.20", "@esbuild/freebsd-arm64": "0.18.20", "@esbuild/freebsd-x64": "0.18.20", "@esbuild/linux-arm": "0.18.20", "@esbuild/linux-arm64": "0.18.20", "@esbuild/linux-ia32": "0.18.20", "@esbuild/linux-loong64": "0.18.20", "@esbuild/linux-mips64el": "0.18.20", "@esbuild/linux-ppc64": "0.18.20", "@esbuild/linux-riscv64": "0.18.20", "@esbuild/linux-s390x": "0.18.20", "@esbuild/linux-x64": "0.18.20", "@esbuild/netbsd-x64": "0.18.20", "@esbuild/openbsd-x64": "0.18.20", "@esbuild/sunos-x64": "0.18.20", "@esbuild/win32-arm64": "0.18.20", "@esbuild/win32-ia32": "0.18.20", "@esbuild/win32-x64": "0.18.20" }, "bin": { "esbuild": "bin/esbuild" } }, "sha512-ceqxoedUrcayh7Y7ZX6NdbbDzGROiyVBgC4PriJThBKSVPWnnFHZAkfI1lJT8QFkOwH4qOS2SJkS4wvpGl8BpA=="],
"@eslint-community/eslint-utils/eslint-visitor-keys": ["[email protected]", "", {}, "sha512-wpc+LXeiyiisxPlEkUzU6svyS1frIO3Mgxj1fdy7Pm8Ygzguax2N3Fa/D/ag1WqbOprdI+uY6wMUl8/a2G+iag=="],
@@ -2329,6 +2367,8 @@
"@streamdown/math/katex": ["[email protected]", "", { "dependencies": { "commander": "^8.3.0" }, "bin": { "katex": "cli.js" } }, "sha512-EkxoDTk8ufHqHlf9QxGwcxeLkWRR3iOuYfRpfORgYfqc8s13bgb+YtRY59NK5ZpRaCwq1kqA6a5lpX8C/eLphQ=="],
+ "@supabase/auth-helpers-shared/jose": ["[email protected]", "", {}, "sha512-1vUQX+IdDMVPj4k8kOxgUqlcK518yluMuGZwqlr44FS1ppZB/5GWh4rZG89erpOBOJjU/OBsnCVFfapsRz6nEA=="],
+
"@supabase/auth-ui-react/react": ["[email protected]", "", { "dependencies": { "loose-envify": "^1.1.0" } }, "sha512-wS+hAgJShR0KhEvPJArfuPVN1+Hz1t0Y6n5jLrGQbkb4urgPE/0Rve+1kMB1v/oWgHgm4WIcV+i7F2pTVj+2iQ=="],
"@supabase/auth-ui-react/react-dom": ["[email protected]", "", { "dependencies": { "loose-envify": "^1.1.0", "scheduler": "^0.23.2" }, "peerDependencies": { "react": "^18.3.1" } }, "sha512-5m4nQKp+rZRb09LNH59GM4BxTh9251/ylbKIbpe7TpGxfJ+9kv6BLkLBXIjjspbgbnIBNqlI23tRnTWT0snUIw=="],
@@ -2363,6 +2403,14 @@
"@typescript-eslint/visitor-keys/eslint-visitor-keys": ["[email protected]", "", {}, "sha512-tD40eHxA35h0PEIZNeIjkHoDR4YjjJp34biM0mDvplBe//mB+IHCqHDGV7pxF+7MklTvighcCPPZC7ynWyjdTA=="],
+ "better-auth/@noble/hashes": ["@noble/[email protected]", "", {}, "sha512-X5XaVWZIBCT7HHZGm5I7ZQXDwLG+bGXuSrMQAW+7Zvl87h1kmc1ZB1VSRJcpUfoUrGQp4Fkoxm5kZ+Ms+aW+eA=="],
+
+ "better-auth/zod": ["[email protected]", "", {}, "sha512-v5l/aFXZQeai4awLbOpSoHecE9UiMrnfx75tEXLjNonXVARxQ5mOeipTjROUchszUNCqnE+hqAMujRsRHsut2Q=="],
+
+ "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=="],
"cmdk/@radix-ui/react-dialog": ["@radix-ui/[email protected]", "", { "dependencies": { "@babel/runtime": "^7.13.10", "@radix-ui/primitive": "1.0.1", "@radix-ui/react-compose-refs": "1.0.1", "@radix-ui/react-context": "1.0.1", "@radix-ui/react-dismissable-layer": "1.0.5", "@radix-ui/react-focus-guards": "1.0.1", "@radix-ui/react-focus-scope": "1.0.4", "@radix-ui/react-id": "1.0.1", "@radix-ui/react-portal": "1.0.4", "@radix-ui/react-presence": "1.0.1", "@radix-ui/react-primitive": "1.0.3", "@radix-ui/react-slot": "1.0.2", "@radix-ui/react-use-controllable-state": "1.0.1", "aria-hidden": "^1.1.1", "react-remove-scroll": "2.5.5" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0", "react-dom": "^16.8 || ^17.0 || ^18.0" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-GjWJX/AUpB703eEBanuBnIWdIXg6NvJFCXcNlSZk4xdszCdhrJgBoUd1cGk67vFO+WdA2pfI/plOpqz/5GUP6Q=="],
@@ -2537,6 +2585,8 @@
"@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__/account-settings-dialog.test.tsx b/components/__tests__/account-settings-dialog.test.tsx
index 10809955..4c400bdf 100644
--- a/components/__tests__/account-settings-dialog.test.tsx
+++ b/components/__tests__/account-settings-dialog.test.tsx
@@ -35,7 +35,14 @@ const user: AppUser = {
name: 'Test Person'
}
-const capabilities = { signUp: true, passwordReset: true, deleteUser: true }
+const capabilities = {
+ signUp: true,
+ passwordReset: true,
+ deleteUser: true,
+ oauth: false,
+ emailVerification: false,
+ share: true
+}
function renderDialog(override: Partial<typeof capabilities> = {}) {
return render(
diff --git a/components/__tests__/app-sidebar.test.tsx b/components/__tests__/app-sidebar.test.tsx
index 6960468e..b6c21e24 100644
--- a/components/__tests__/app-sidebar.test.tsx
+++ b/components/__tests__/app-sidebar.test.tsx
@@ -52,4 +52,11 @@ describe('AppSidebar library entry', () => {
expect(screen.queryByText('Library')).not.toBeInTheDocument()
expect(screen.getByText('New')).toBeInTheDocument()
})
+
+ test('hides the Library entry when AUTH_PROVIDER=none with ENABLE_AUTH unset', () => {
+ vi.stubEnv('AUTH_PROVIDER', 'none')
+ renderSidebar()
+
+ expect(screen.queryByText('Library')).not.toBeInTheDocument()
+ })
})
diff --git a/components/__tests__/invitations-manager.test.tsx b/components/__tests__/invitations-manager.test.tsx
new file mode 100644
index 00000000..3d56c2ff
--- /dev/null
+++ b/components/__tests__/invitations-manager.test.tsx
@@ -0,0 +1,140 @@
+import { act, fireEvent, render, screen, waitFor } from '@testing-library/react'
+import { beforeEach, describe, expect, it, vi } from 'vitest'
+
+import {
+ createInvitationAction,
+ type InvitationView,
+ revokeInvitationAction
+} from '@/lib/actions/admin'
+
+import { InvitationsManager } from '@/components/admin/invitations-manager'
+
+vi.mock('@/lib/actions/admin', () => ({
+ createInvitationAction: vi.fn(),
+ revokeInvitationAction: vi.fn()
+}))
+
+const invitations: InvitationView[] = [
+ {
+ id: 'inv-1',
+ email: '[email protected]',
+ revoked: false,
+ used: false,
+ expired: false,
+ expiresAt: new Date(Date.now() + 60_000).toISOString(),
+ createdAt: new Date().toISOString()
+ },
+ {
+ id: 'inv-2',
+ email: '[email protected]',
+ revoked: true,
+ used: false,
+ expired: false,
+ expiresAt: new Date(Date.now() - 60_000).toISOString(),
+ createdAt: new Date().toISOString()
+ }
+]
+
+describe('InvitationsManager', () => {
+ beforeEach(() => {
+ vi.clearAllMocks()
+ })
+
+ it('lists invitations with their status', () => {
+ render(<InvitationsManager invitations={invitations} />)
+
+ expect(screen.getByText('[email protected]')).toBeInTheDocument()
+ expect(screen.getByText('Active')).toBeInTheDocument()
+ expect(screen.getByText('Revoked')).toBeInTheDocument()
+ expect(screen.queryByText('[email protected]')).toBeInTheDocument()
+ })
+
+ it('marks elapsed invitations as expired without a revoke action', () => {
+ render(
+ <InvitationsManager
+ invitations={[
+ {
+ id: 'inv-4',
+ email: '[email protected]',
+ revoked: false,
+ used: false,
+ expired: true,
+ expiresAt: new Date(Date.now() - 60_000).toISOString(),
+ createdAt: new Date().toISOString()
+ }
+ ]}
+ />
+ )
+
+ expect(screen.getByText('Expired')).toBeInTheDocument()
+ expect(screen.queryByText('Active')).not.toBeInTheDocument()
+ expect(screen.queryByText('Revoke')).not.toBeInTheDocument()
+ })
+
+ it('creates an invitation and shows a copyable link', async () => {
+ const created: InvitationView = {
+ id: 'inv-3',
+ email: '[email protected]',
+ revoked: false,
+ used: false,
+ expired: false,
+ expiresAt: new Date(Date.now() + 60_000).toISOString(),
+ createdAt: new Date().toISOString()
+ }
+ vi.mocked(createInvitationAction).mockResolvedValue({
+ success: true,
+ invitation: created,
+ link: 'http://localhost:3000/auth/sign-up?token=tok3'
+ })
+
+ render(<InvitationsManager invitations={invitations} />)
+
+ fireEvent.change(screen.getByPlaceholderText(/invitee/i), {
+ target: { value: '[email protected]' }
+ })
+ fireEvent.click(screen.getByRole('button', { name: 'Create invitation' }))
+
+ await waitFor(() => {
+ expect(createInvitationAction).toHaveBeenCalledWith({
+ })
+ expect(screen.getByText('[email protected]')).toBeInTheDocument()
+ expect(
+ screen.getByDisplayValue(
+ 'http://localhost:3000/auth/sign-up?token=tok3'
+ )
+ ).toBeInTheDocument()
+ })
+ })
+
+ it('shows the error when a non-admin is denied', async () => {
+ vi.mocked(createInvitationAction).mockResolvedValue({
+ success: false,
+ error: 'Admin access required.'
+ })
+
+ render(<InvitationsManager invitations={[]} />)
+
+ fireEvent.change(screen.getByPlaceholderText(/invitee/i), {
+ target: { value: '[email protected]' }
+ })
+ fireEvent.click(screen.getByRole('button', { name: 'Create invitation' }))
+
+ await waitFor(() => {
+ expect(screen.getByText('Admin access required.')).toBeInTheDocument()
+ })
+ })
+
+ it('revokes an invitation', async () => {
+ vi.mocked(revokeInvitationAction).mockResolvedValue({ success: true })
+
+ render(<InvitationsManager invitations={invitations} />)
+
+ fireEvent.click(screen.getByRole('button', { name: 'Revoke' }))
+
+ await waitFor(() => {
+ expect(revokeInvitationAction).toHaveBeenCalledWith('inv-1')
+ expect(screen.getAllByText('Revoked')).toHaveLength(2)
+ })
+ })
+})
diff --git a/components/__tests__/login-form.test.tsx b/components/__tests__/login-form.test.tsx
index 0b6540d8..2ed0cc21 100644
--- a/components/__tests__/login-form.test.tsx
+++ b/components/__tests__/login-form.test.tsx
@@ -20,15 +20,26 @@ vi.mock('next/navigation', () => ({
useRouter: () => ({ push: mockPush, refresh: mockRefresh })
}))
-const capabilities = { signUp: true, passwordReset: true, deleteUser: true }
+const capabilities = {
+ signUp: true,
+ passwordReset: true,
+ deleteUser: true,
+ oauth: true,
+ emailVerification: true,
+ share: true
+}
-function renderForm(override: Partial<typeof capabilities> = {}, user = null) {
+function renderForm(
+ override: Partial<typeof capabilities> = {},
+ user = null,
+ next?: string
+) {
return render(
<AppUserProvider
user={user}
capabilities={{ ...capabilities, ...override }}
>
- <LoginForm />
+ <LoginForm next={next} />
</AppUserProvider>
)
}
@@ -60,6 +71,60 @@ describe('LoginForm', () => {
})
})
+ it('returns to the requested page after sign-in', async () => {
+ // A logged-out owner of a private shared chat arrives via
+ // /auth/login?next=/search/<id>; the link must survive the sign-in.
+ vi.mocked(signIn).mockResolvedValue({ success: true })
+ renderForm({}, null, '/search/abc123')
+
+ 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(mockPush).toHaveBeenCalledWith('/search/abc123')
+ })
+ })
+
+ it('ignores an off-site next target', async () => {
+ vi.mocked(signIn).mockResolvedValue({ success: true })
+ renderForm({}, null, '//evil.example.com')
+
+ 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(mockPush).toHaveBeenCalledWith('/')
+ })
+ })
+
+ it('ignores a backslash-normalized next target', async () => {
+ // Browsers resolve /\evil.example.com to an off-site origin.
+ vi.mocked(signIn).mockResolvedValue({ success: true })
+ renderForm({}, null, '/\\evil.example.com')
+
+ 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(mockPush).toHaveBeenCalledWith('/')
+ })
+ })
+
it('shows the error returned by the auth provider', async () => {
vi.mocked(signIn).mockResolvedValue({
success: false,
@@ -108,6 +173,72 @@ describe('LoginForm', () => {
})
})
+ it('carries the next target to the OAuth callback via a cookie', async () => {
+ // Supabase's redirect allowlist matches the callback URL exactly, so
+ // the destination rides in a short-lived cookie, not the redirectTo.
+ 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({}, null, '/search/abc123')
+
+ fireEvent.click(screen.getByRole('button', { name: 'Sign In with Google' }))
+
+ await waitFor(() => {
+ expect(signInWithGoogle).toHaveBeenCalled()
+ })
+ expect(document.cookie).toContain('auth_next=%2Fsearch%2Fabc123')
+
+ Object.defineProperty(window, 'location', {
+ configurable: true,
+ writable: true,
+ value: originalLocation
+ })
+ })
+
+ it('clears a stale next cookie when the later login has no destination', async () => {
+ // An abandoned OAuth attempt leaves the cookie behind; the next
+ // destination-less sign-in must not be sent to the old page.
+ const originalLocation = window.location
+ Object.defineProperty(window, 'location', {
+ configurable: true,
+ writable: true,
+ value: { href: '' }
+ })
+ document.cookie = 'auth_next=%2Fstale; path=/; max-age=300; SameSite=Lax'
+ 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(document.cookie).not.toContain('auth_next')
+
+ Object.defineProperty(window, 'location', {
+ configurable: true,
+ writable: true,
+ value: originalLocation
+ })
+ })
+
+ it('hides the Google button when the provider has no OAuth', () => {
+ renderForm({ oauth: false })
+ expect(
+ screen.queryByRole('button', { name: 'Sign In with Google' })
+ ).not.toBeInTheDocument()
+ })
+
it('offers password recovery when the provider supports it', () => {
renderForm()
expect(
@@ -121,4 +252,16 @@ describe('LoginForm', () => {
screen.queryByRole('link', { name: 'Forgot password?' })
).not.toBeInTheDocument()
})
+
+ it('shows the Sign Up link by default', () => {
+ renderForm()
+ expect(screen.getByRole('link', { name: 'Sign Up' })).toBeInTheDocument()
+ })
+
+ it('hides Sign Up when the provider lacks the capability', () => {
+ renderForm({ signUp: false })
+ expect(
+ screen.queryByRole('link', { name: 'Sign Up' })
+ ).not.toBeInTheDocument()
+ })
})
diff --git a/components/__tests__/member-role-manager.test.tsx b/components/__tests__/member-role-manager.test.tsx
new file mode 100644
index 00000000..7e2ddae8
--- /dev/null
+++ b/components/__tests__/member-role-manager.test.tsx
@@ -0,0 +1,62 @@
+import { fireEvent, render, screen, waitFor } from '@testing-library/react'
+import { beforeEach, describe, expect, it, vi } from 'vitest'
+
+import { promoteMemberAction } from '@/lib/actions/admin'
+
+import { MemberRoleManager } from '@/components/admin/member-role-manager'
+
+vi.mock('@/lib/actions/admin', () => ({
+ promoteMemberAction: vi.fn()
+}))
+
+const members = [
+ { id: 'admin-1', email: '[email protected]', name: 'Admin', role: 'admin' },
+ { id: 'user-1', email: '[email protected]', name: 'Member', role: 'user' }
+]
+
+describe('MemberRoleManager', () => {
+ beforeEach(() => {
+ vi.clearAllMocks()
+ })
+
+ it('promotes a member and marks the row', async () => {
+ vi.mocked(promoteMemberAction).mockResolvedValue({ success: true })
+
+ render(<MemberRoleManager members={members} />)
+
+ fireEvent.click(screen.getByRole('button', { name: 'Promote to admin' }))
+
+ await waitFor(() => {
+ expect(promoteMemberAction).toHaveBeenCalledWith({ userId: 'user-1' })
+ expect(screen.getByText('Promoted')).toBeInTheDocument()
+ })
+ expect(
+ screen.queryByRole('button', { name: 'Promote to admin' })
+ ).toBeNull()
+ })
+
+ it('shows the error when promotion fails', async () => {
+ vi.mocked(promoteMemberAction).mockResolvedValue({
+ success: false,
+ error: 'Admin access required.'
+ })
+
+ render(<MemberRoleManager members={members} />)
+
+ fireEvent.click(screen.getByRole('button', { name: 'Promote to admin' }))
+
+ await waitFor(() => {
+ expect(screen.getByText('Admin access required.')).toBeInTheDocument()
+ })
+ expect(screen.queryByText('Promoted')).not.toBeInTheDocument()
+ })
+
+ it('renders no promote button for existing admins', () => {
+ render(<MemberRoleManager members={[members[0]]} />)
+
+ expect(screen.getByText('Admin')).toBeInTheDocument()
+ expect(
+ screen.queryByRole('button', { name: 'Promote to admin' })
+ ).toBeNull()
+ })
+})
diff --git a/components/__tests__/reset-member-password-form.test.tsx b/components/__tests__/reset-member-password-form.test.tsx
new file mode 100644
index 00000000..d7bae52c
--- /dev/null
+++ b/components/__tests__/reset-member-password-form.test.tsx
@@ -0,0 +1,73 @@
+import { fireEvent, render, screen, waitFor } from '@testing-library/react'
+import { beforeEach, describe, expect, it, vi } from 'vitest'
+
+import { resetMemberPasswordAction } from '@/lib/actions/admin'
+
+import { ResetMemberPasswordForm } from '@/components/admin/reset-member-password-form'
+
+vi.mock('@/lib/actions/admin', () => ({
+ resetMemberPasswordAction: vi.fn()
+}))
+
+const members = [
+ { id: 'admin-1', email: '[email protected]', name: 'Admin', role: 'admin' },
+ { id: 'user-1', email: '[email protected]', name: 'Member', role: 'user' }
+]
+
+describe('ResetMemberPasswordForm', () => {
+ beforeEach(() => {
+ vi.clearAllMocks()
+ })
+
+ it('resets a member password', async () => {
+ vi.mocked(resetMemberPasswordAction).mockResolvedValue({ success: true })
+
+ render(<ResetMemberPasswordForm members={members} />)
+
+ fireEvent.change(screen.getByLabelText('Member'), {
+ target: { value: 'user-1' }
+ })
+ fireEvent.change(screen.getByLabelText('New password'), {
+ target: { value: 'brand-new-password' }
+ })
+ fireEvent.click(screen.getByRole('button', { name: 'Reset password' }))
+
+ await waitFor(() => {
+ expect(resetMemberPasswordAction).toHaveBeenCalledWith({
+ userId: 'user-1',
+ newPassword: 'brand-new-password'
+ })
+ expect(screen.getByText('Password updated.')).toBeInTheDocument()
+ })
+ })
+
+ it('shows the error when a non-admin is denied', async () => {
+ vi.mocked(resetMemberPasswordAction).mockResolvedValue({
+ success: false,
+ error: 'Admin access required.'
+ })
+
+ render(<ResetMemberPasswordForm members={members} />)
+
+ fireEvent.change(screen.getByLabelText('Member'), {
+ target: { value: 'user-1' }
+ })
+ fireEvent.change(screen.getByLabelText('New password'), {
+ target: { value: 'brand-new-password' }
+ })
+ fireEvent.click(screen.getByRole('button', { name: 'Reset password' }))
+
+ await waitFor(() => {
+ expect(screen.getByText('Admin access required.')).toBeInTheDocument()
+ })
+ expect(screen.queryByText('Password updated.')).not.toBeInTheDocument()
+ })
+
+ it('disables submit until a member is selected', () => {
+ render(<ResetMemberPasswordForm members={members} />)
+
+ expect(
+ screen.getByRole('button', { name: 'Reset password' })
+ ).toBeDisabled()
+ })
+})
diff --git a/components/__tests__/sign-up-form.test.tsx b/components/__tests__/sign-up-form.test.tsx
new file mode 100644
index 00000000..b68a14f7
--- /dev/null
+++ b/components/__tests__/sign-up-form.test.tsx
@@ -0,0 +1,190 @@
+import { fireEvent, render, screen, waitFor } from '@testing-library/react'
+import { beforeEach, describe, expect, it, vi } from 'vitest'
+
+import { signUp } from '@/lib/actions/auth'
+import { AppUserProvider } from '@/lib/contexts/app-user-context'
+
+import { InviteRequired } from '@/components/invite-required'
+import { SignUpForm } from '@/components/sign-up-form'
+
+vi.mock('@/lib/actions/auth', () => ({
+ signUp: vi.fn()
+}))
+
+const { push, refresh } = vi.hoisted(() => ({
+ push: vi.fn(),
+ refresh: vi.fn()
+}))
+
+vi.mock('next/navigation', () => ({
+ useRouter: () => ({ push, refresh })
+}))
+
+function fillAndSubmit() {
+ fireEvent.change(screen.getByLabelText('Email'), {
+ target: { value: '[email protected]' }
+ })
+ fireEvent.change(screen.getByLabelText('Password'), {
+ target: { value: 'secret-password' }
+ })
+ fireEvent.change(screen.getByLabelText('Repeat Password'), {
+ target: { value: 'secret-password' }
+ })
+ fireEvent.click(screen.getByRole('button', { name: 'Sign Up' }))
+}
+
+describe('SignUpForm', () => {
+ beforeEach(() => {
+ vi.clearAllMocks()
+ })
+
+ it('forwards the invitation token to the sign-up action', async () => {
+ vi.mocked(signUp).mockResolvedValue({ success: true })
+
+ render(<SignUpForm token="inv-token" />)
+ fillAndSubmit()
+
+ await waitFor(() => {
+ expect(signUp).toHaveBeenCalledWith({
+ email: '[email protected]',
+ password: 'secret-password',
+ token: 'inv-token'
+ })
+ })
+ })
+
+ it('shows a notice and stays on the page when sign-up continues out-of-band', async () => {
+ // E.g. the bootstrap mailbox-proof flow: an emailed link finishes the
+ // admin account, so the form must not redirect.
+ vi.mocked(signUp).mockResolvedValue({
+ success: true,
+ notice: 'A bootstrap link was sent to [email protected].'
+ })
+
+ render(<SignUpForm />)
+ fillAndSubmit()
+
+ expect(
+ await screen.findByText('A bootstrap link was sent to [email protected].')
+ ).toBeInTheDocument()
+ expect(push).not.toHaveBeenCalled()
+ })
+
+ it('clears a previous notice when a later attempt fails', async () => {
+ vi.mocked(signUp)
+ .mockResolvedValueOnce({
+ success: true,
+ notice: 'A bootstrap link was sent to [email protected].'
+ })
+ .mockResolvedValueOnce({ success: false, error: 'Server error' })
+
+ render(<SignUpForm />)
+ fillAndSubmit()
+ expect(
+ await screen.findByText('A bootstrap link was sent to [email protected].')
+ ).toBeInTheDocument()
+
+ fillAndSubmit()
+ expect(await screen.findByText('Server error')).toBeInTheDocument()
+ expect(
+ screen.queryByText('A bootstrap link was sent to [email protected].')
+ ).not.toBeInTheDocument()
+ })
+
+ it('prefills and flags the email an invitation is bound to', async () => {
+ vi.mocked(signUp).mockResolvedValue({ success: true })
+
+ render(<SignUpForm token="inv-token" inviteEmail="[email protected]" />)
+
+ expect(screen.getByLabelText('Email')).toHaveValue('[email protected]')
+ expect(
+ screen.getByText(/bound to friend@example\.com/i)
+ ).toBeInTheDocument()
+
+ fireEvent.change(screen.getByLabelText('Password'), {
+ target: { value: 'secret-password' }
+ })
+ fireEvent.change(screen.getByLabelText('Repeat Password'), {
+ target: { value: 'secret-password' }
+ })
+ fireEvent.click(screen.getByRole('button', { name: 'Sign Up' }))
+
+ await waitFor(() => {
+ expect(signUp).toHaveBeenCalledWith({
+ email: '[email protected]',
+ password: 'secret-password',
+ token: 'inv-token'
+ })
+ })
+ })
+
+ it('signs up without a token in open mode', async () => {
+ vi.mocked(signUp).mockResolvedValue({ success: true })
+
+ render(<SignUpForm />)
+ fillAndSubmit()
+
+ await waitFor(() => {
+ expect(signUp).toHaveBeenCalledWith({
+ email: '[email protected]',
+ password: 'secret-password',
+ token: undefined
+ })
+ })
+ })
+})
+
+describe('InviteRequired', () => {
+ it('routes to the app when the provider signs users in immediately', async () => {
+ vi.mocked(signUp).mockResolvedValue({ success: true })
+ render(
+ <AppUserProvider
+ user={null}
+ capabilities={{
+ signUp: true,
+ passwordReset: false,
+ deleteUser: true,
+ oauth: false,
+ emailVerification: false,
+ share: true
+ }}
+ >
+ <SignUpForm />
+ </AppUserProvider>
+ )
+ fillAndSubmit()
+ await waitFor(() => expect(push).toHaveBeenCalledWith('/'))
+ })
+
+ it('routes to the confirmation page when email verification is required', async () => {
+ vi.mocked(signUp).mockResolvedValue({ success: true })
+ render(
+ <AppUserProvider
+ user={null}
+ capabilities={{
+ signUp: true,
+ passwordReset: true,
+ deleteUser: true,
+ oauth: true,
+ emailVerification: true,
+ share: true
+ }}
+ >
+ <SignUpForm />
+ </AppUserProvider>
+ )
+ fillAndSubmit()
+ await waitFor(() =>
+ expect(push).toHaveBeenCalledWith('/auth/sign-up-success')
+ )
+ })
+
+ it('explains that sign-up requires an invitation', () => {
+ render(<InviteRequired />)
+
+ expect(
+ screen.getByRole('heading', { name: 'Invitation required' })
+ ).toBeInTheDocument()
+ expect(screen.getByText(/invite-only/i)).toBeInTheDocument()
+ })
+})
diff --git a/components/__tests__/update-password-form.test.tsx b/components/__tests__/update-password-form.test.tsx
new file mode 100644
index 00000000..7f2ef0e1
--- /dev/null
+++ b/components/__tests__/update-password-form.test.tsx
@@ -0,0 +1,61 @@
+import { fireEvent, render, screen, waitFor } from '@testing-library/react'
+import { beforeEach, describe, expect, it, vi } from 'vitest'
+
+import { updatePassword } from '@/lib/actions/auth'
+
+import { UpdatePasswordForm } from '@/components/update-password-form'
+
+vi.mock('@/lib/actions/auth', () => ({
+ updatePassword: vi.fn()
+}))
+
+const { push, refresh } = vi.hoisted(() => ({
+ push: vi.fn(),
+ refresh: vi.fn()
+}))
+
+vi.mock('next/navigation', () => ({
+ useRouter: () => ({ push, refresh })
+}))
+
+function fillAndSubmit() {
+ fireEvent.change(screen.getByLabelText('New password'), {
+ target: { value: 'new-password' }
+ })
+ fireEvent.click(screen.getByRole('button', { name: 'Save new password' }))
+}
+
+describe('UpdatePasswordForm', () => {
+ beforeEach(() => {
+ vi.clearAllMocks()
+ })
+
+ it('follows the provider redirect after a token reset', async () => {
+ // A better-auth token reset establishes no session: the provider
+ // redirects to sign-in instead of landing logged-out on the root.
+ vi.mocked(updatePassword).mockResolvedValue({
+ success: true,
+ redirectTo: '/auth/login'
+ })
+
+ render(<UpdatePasswordForm token="reset-token" />)
+ fillAndSubmit()
+
+ await waitFor(() => {
+ expect(updatePassword).toHaveBeenCalledWith('new-password', 'reset-token')
+ })
+ expect(push).toHaveBeenCalledWith('/auth/login')
+ })
+
+ it('lands on the app root when the provider establishes a session', async () => {
+ vi.mocked(updatePassword).mockResolvedValue({ success: true })
+
+ render(<UpdatePasswordForm />)
+ fillAndSubmit()
+
+ await waitFor(() => {
+ expect(push).toHaveBeenCalledWith('/')
+ })
+ expect(refresh).toHaveBeenCalled()
+ })
+})
diff --git a/components/__tests__/user-menu.test.tsx b/components/__tests__/user-menu.test.tsx
index 9f826257..0349efd7 100644
--- a/components/__tests__/user-menu.test.tsx
+++ b/components/__tests__/user-menu.test.tsx
@@ -80,7 +80,14 @@ const user: AppUser = {
name: 'Test Person'
}
-const capabilities = { signUp: true, passwordReset: true, deleteUser: true }
+const capabilities = {
+ signUp: true,
+ passwordReset: true,
+ deleteUser: true,
+ oauth: false,
+ emailVerification: false,
+ share: true
+}
describe('UserMenu', () => {
beforeEach(() => {
diff --git a/components/admin/invitations-manager.tsx b/components/admin/invitations-manager.tsx
new file mode 100644
index 00000000..ed550397
--- /dev/null
+++ b/components/admin/invitations-manager.tsx
@@ -0,0 +1,166 @@
+'use client'
+
+import { useState } from 'react'
+
+import {
+ createInvitationAction,
+ type InvitationView,
+ revokeInvitationAction
+} from '@/lib/actions/admin'
+
+import { Badge } from '@/components/ui/badge'
+import { Button } from '@/components/ui/button'
+import { Input } from '@/components/ui/input'
+
+export function InvitationsManager({
+ invitations: initialInvitations
+}: {
+ invitations: InvitationView[]
+}) {
+ const [invitations, setInvitations] = useState(initialInvitations)
+ // Expiration is computed server-side when the list is rendered, and
+ // each row shows its exact expiry time. The server rejects expired
+ // invitations at redemption, so a badge that goes stale while the
+ // page sits open is cosmetic only — no client clock is kept, because
+ // a client clock cannot tell its own skew or sleep from real time.
+ const isExpired = (invitation: InvitationView) => invitation.expired
+ const [email, setEmail] = useState('')
+ const [error, setError] = useState<string | null>(null)
+ const [isCreating, setIsCreating] = useState(false)
+ const [newLink, setNewLink] = useState<string | null>(null)
+ const [copied, setCopied] = useState(false)
+
+ const handleCreate = async (e: React.FormEvent) => {
+ e.preventDefault()
+ setIsCreating(true)
+ setError(null)
+ setNewLink(null)
+
+ try {
+ const result = await createInvitationAction({ email })
+ if (result.success && result.invitation) {
+ setInvitations(current => [result.invitation!, ...current])
+ setNewLink(result.link ?? null)
+ setEmail('')
+ } else {
+ setError(result.error ?? 'Failed to create invitation')
+ }
+ } catch (error: unknown) {
+ setError(
+ error instanceof Error ? error.message : 'Failed to create invitation'
+ )
+ }
+ setIsCreating(false)
+ }
+
+ const handleRevoke = async (id: string) => {
+ setError(null)
+ let result
+ try {
+ result = await revokeInvitationAction(id)
+ } catch (error: unknown) {
+ setError(
+ error instanceof Error ? error.message : 'Failed to revoke invitation'
+ )
+ return
+ }
+ if (result.success) {
+ setInvitations(current =>
+ current.map(invitation =>
+ invitation.id === id ? { ...invitation, revoked: true } : invitation
+ )
+ )
+ } else {
+ setError(result.error ?? 'Failed to revoke invitation')
+ }
+ }
+
+ const handleCopy = async (link: string) => {
+ try {
+ await navigator.clipboard.writeText(link)
+ setCopied(true)
+ setTimeout(() => setCopied(false), 2000)
+ } catch {
+ setError('Copy failed — select the link and copy manually.')
+ }
+ }
+
+ return (
+ <div className="flex flex-col gap-4">
+ <form className="flex flex-col gap-2 sm:flex-row" onSubmit={handleCreate}>
+ <Input
+ type="email"
+ placeholder="[email protected]"
+ value={email}
+ onChange={e => setEmail(e.target.value)}
+ required
+ />
+ <Button type="submit" disabled={isCreating}>
+ {isCreating ? 'Creating...' : 'Create invitation'}
+ </Button>
+ </form>
+ <p className="text-xs text-muted-foreground">
+ Each invitation is single-use and can only be redeemed by this address.
+ </p>
+
+ {newLink && (
+ <div className="flex flex-col gap-2 rounded-md border p-3 sm:flex-row sm:items-center">
+ <Input readOnly value={newLink} className="font-mono text-xs" />
+ <Button
+ type="button"
+ variant="outline"
+ onClick={() => handleCopy(newLink)}
+ >
+ {copied ? 'Copied' : 'Copy link'}
+ </Button>
+ </div>
+ )}
+
+ {error && <p className="text-sm text-red-500">{error}</p>}
+
+ <ul className="flex flex-col gap-2">
+ {invitations.length === 0 && (
+ <li className="text-sm text-muted-foreground">No invitations yet.</li>
+ )}
+ {invitations.map(invitation => (
+ <li
+ key={invitation.id}
+ className="flex flex-col gap-1 rounded-md border p-3 text-sm sm:flex-row sm:items-center sm:justify-between"
+ >
+ <div className="flex flex-col gap-1">
+ <span className="font-medium">
+ {invitation.email ?? 'No email specified'}
+ </span>
+ <span className="text-xs text-muted-foreground">
+ Expires {new Date(invitation.expiresAt).toLocaleString()}
+ </span>
+ </div>
+ <div className="flex items-center gap-2">
+ {invitation.used ? (
+ <Badge variant="secondary">Used</Badge>
+ ) : invitation.revoked ? (
+ <Badge variant="destructive">Revoked</Badge>
+ ) : isExpired(invitation) ? (
+ <Badge variant="outline">Expired</Badge>
+ ) : (
+ <Badge>Active</Badge>
+ )}
+ {!invitation.revoked &&
+ !invitation.used &&
+ !isExpired(invitation) && (
+ <Button
+ type="button"
+ size="sm"
+ variant="outline"
+ onClick={() => handleRevoke(invitation.id)}
+ >
+ Revoke
+ </Button>
+ )}
+ </div>
+ </li>
+ ))}
+ </ul>
+ </div>
+ )
+}
diff --git a/components/admin/member-role-manager.tsx b/components/admin/member-role-manager.tsx
new file mode 100644
index 00000000..d5fdfe2d
--- /dev/null
+++ b/components/admin/member-role-manager.tsx
@@ -0,0 +1,65 @@
+'use client'
+
+import { useState } from 'react'
+
+import { promoteMemberAction } from '@/lib/actions/admin'
+import type { MemberSummary } from '@/lib/auth/better-auth/members'
+
+import { Button } from '@/components/ui/button'
+
+export function MemberRoleManager({ members }: { members: MemberSummary[] }) {
+ const [promotedIds, setPromotedIds] = useState<Set<string>>(new Set())
+ const [error, setError] = useState<string | null>(null)
+ const [busyId, setBusyId] = useState<string | null>(null)
+
+ const promote = async (userId: string) => {
+ setBusyId(userId)
+ setError(null)
+ try {
+ const result = await promoteMemberAction({ userId })
+ if (result.success) {
+ setPromotedIds(prev => new Set(prev).add(userId))
+ } else {
+ setError(result.error ?? 'Failed to promote member')
+ }
+ } catch (error: unknown) {
+ setError(
+ error instanceof Error ? error.message : 'Failed to promote member'
+ )
+ }
+ setBusyId(null)
+ }
+
+ return (
+ <div className="flex flex-col gap-3">
+ <ul className="flex flex-col gap-2">
+ {members.map(member => (
+ <li
+ key={member.id}
+ className="flex items-center justify-between gap-4"
+ >
+ <span className="truncate text-sm">
+ {member.email}
+ {member.role === 'admin' ? ' (admin)' : ''}
+ </span>
+ {member.role === 'admin' ? (
+ <span className="text-xs text-muted-foreground">Admin</span>
+ ) : promotedIds.has(member.id) ? (
+ <span className="text-xs text-muted-foreground">Promoted</span>
+ ) : (
+ <Button
+ size="sm"
+ variant="outline"
+ disabled={busyId !== null}
+ onClick={() => promote(member.id)}
+ >
+ {busyId === member.id ? 'Promoting...' : 'Promote to admin'}
+ </Button>
+ )}
+ </li>
+ ))}
+ </ul>
+ {error && <p className="text-sm text-red-500">{error}</p>}
+ </div>
+ )
+}
diff --git a/components/admin/reset-member-password-form.tsx b/components/admin/reset-member-password-form.tsx
new file mode 100644
index 00000000..9d1d73f9
--- /dev/null
+++ b/components/admin/reset-member-password-form.tsx
@@ -0,0 +1,90 @@
+'use client'
+
+import { useState } from 'react'
+
+import { resetMemberPasswordAction } from '@/lib/actions/admin'
+import type { MemberSummary } from '@/lib/auth/better-auth/members'
+
+import { Button } from '@/components/ui/button'
+import { Input } from '@/components/ui/input'
+import { Label } from '@/components/ui/label'
+
+export function ResetMemberPasswordForm({
+ members
+}: {
+ members: MemberSummary[]
+}) {
+ const [userId, setUserId] = useState<string>('')
+ const [password, setPassword] = useState('')
+ const [error, setError] = useState<string | null>(null)
+ const [success, setSuccess] = useState(false)
+ const [isSubmitting, setIsSubmitting] = useState(false)
+
+ const handleSubmit = async (e: React.FormEvent) => {
+ e.preventDefault()
+ setIsSubmitting(true)
+ setError(null)
+ setSuccess(false)
+
+ try {
+ const result = await resetMemberPasswordAction({
+ userId,
+ newPassword: password
+ })
+
+ if (result.success) {
+ setSuccess(true)
+ setPassword('')
+ } else {
+ setError(result.error ?? 'Failed to reset password')
+ }
+ } catch (error: unknown) {
+ setError(
+ error instanceof Error ? error.message : 'Failed to reset password'
+ )
+ }
+ setIsSubmitting(false)
+ }
+
+ return (
+ <form className="flex flex-col gap-4" onSubmit={handleSubmit}>
+ <div className="grid gap-2">
+ <Label htmlFor="member">Member</Label>
+ <select
+ id="member"
+ className="flex h-9 w-full rounded-md border border-input bg-transparent px-3 py-1 text-sm shadow-xs"
+ value={userId}
+ onChange={e => setUserId(e.target.value)}
+ >
+ <option value="">Select a member</option>
+ {members.map(member => (
+ <option key={member.id} value={member.id}>
+ {member.email}
+ {member.role === 'admin' ? ' (admin)' : ''}
+ </option>
+ ))}
+ </select>
+ </div>
+ <div className="grid gap-2">
+ <Label htmlFor="new-password">New password</Label>
+ <Input
+ id="new-password"
+ type="password"
+ required
+ minLength={8}
+ value={password}
+ onChange={e => setPassword(e.target.value)}
+ />
+ </div>
+ {error && <p className="text-sm text-red-500">{error}</p>}
+ {success && (
+ <p className="text-sm text-green-600 dark:text-green-500">
+ Password updated.
+ </p>
+ )}
+ <Button type="submit" disabled={isSubmitting || !userId}>
+ {isSubmitting ? 'Resetting...' : 'Reset password'}
+ </Button>
+ </form>
+ )
+}
diff --git a/components/answer-section.tsx b/components/answer-section.tsx
index 8eb13d5c..0456bb2c 100644
--- a/components/answer-section.tsx
+++ b/components/answer-section.tsx
@@ -13,6 +13,7 @@ import { toast } from 'sonner'
import { saveNote } from '@/lib/actions/notes'
import { captureClient } from '@/lib/analytics/posthog-client'
+import { useAuthCapabilities } from '@/lib/contexts/app-user-context'
import { stripSourceContextBlocks } from '@/lib/render/strip-source-context-blocks'
import type { SearchResultItem } from '@/lib/types'
import type {
@@ -83,8 +84,13 @@ export function AnswerSection({
const [authPromptOpen, setAuthPromptOpen] = useState(false)
const lastTrackedSelectionKeyRef = useRef<string | null>(null)
const { openLibrary, upsertCachedNote } = useLibrary()
- const enableShare =
- process.env.NEXT_PUBLIC_SUPABASE_URL !== undefined && !isGuest
+ // Sharing records the chat under the signed-in user, so it needs a real
+ // auth provider (supabase or better-auth), not the anonymous one. The
+ // opt-in flag (ENABLE_SHARE) is folded into this capability server-side
+ // by the root layout, so a prebuilt image can still enable sharing at
+ // runtime; shareChat enforces the same flag again.
+ const capabilities = useAuthCapabilities()
+ const enableShare = capabilities.share && !isGuest
const showSelectionSaveButton =
libraryAvailable && (!isGuest || isCloudDeployment)
const showSelectionDeepDiveButton = Boolean(onQuoteContext)
diff --git a/components/app-sidebar.tsx b/components/app-sidebar.tsx
index 8a745bdf..de1d08e8 100644
--- a/components/app-sidebar.tsx
+++ b/components/app-sidebar.tsx
@@ -1,6 +1,7 @@
import { Suspense } from 'react'
import Link from 'next/link'
+import { isAnonymousMode } from '@/lib/auth/provider'
import { cn } from '@/lib/utils'
import {
@@ -21,7 +22,7 @@ import { IconLogo } from './ui/icons'
export default function AppSidebar() {
// Anonymous mode has no per-user library, and the server actions reject it,
// so the entry point follows the same switch the pages use.
- const libraryAvailable = process.env.ENABLE_AUTH !== 'false'
+ const libraryAvailable = !isAnonymousMode()
return (
<Sidebar side="left" variant="sidebar" collapsible="offcanvas">
diff --git a/components/invite-required.tsx b/components/invite-required.tsx
new file mode 100644
index 00000000..5599fe32
--- /dev/null
+++ b/components/invite-required.tsx
@@ -0,0 +1,43 @@
+import Link from 'next/link'
+
+import {
+ Card,
+ CardContent,
+ CardDescription,
+ CardHeader,
+ CardTitle
+} from '@/components/ui/card'
+import { IconLogo } from '@/components/ui/icons'
+
+export function InviteRequired() {
+ return (
+ <div className="flex flex-col items-center gap-6">
+ <Card className="w-full max-w-sm">
+ <CardHeader className="text-center">
+ <CardTitle className="text-2xl flex flex-col items-center justify-center gap-4">
+ <IconLogo className="size-12" />
+ Invitation required
+ </CardTitle>
+ <CardDescription>
+ Sign-up on this Morphic instance is invite-only. Ask an
+ administrator for an invitation link and open it to create your
+ account.
+ </CardDescription>
+ </CardHeader>
+ <CardContent>
+ <div className="mt-2 text-center text-sm">
+ Already have an account?{' '}
+ <Link href="/auth/login" className="underline underline-offset-4">
+ Sign In
+ </Link>
+ </div>
+ </CardContent>
+ </Card>
+ <div className="text-center text-xs text-muted-foreground">
+ <Link href="/" className="hover:underline">
+ &larr; Back to Home
+ </Link>
+ </div>
+ </div>
+ )
+}
diff --git a/components/login-form.tsx b/components/login-form.tsx
index 39adde24..a4d4e489 100644
--- a/components/login-form.tsx
+++ b/components/login-form.tsx
@@ -5,6 +5,7 @@ import Link from 'next/link'
import { useRouter } from 'next/navigation'
import { signIn, signInWithGoogle } 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'
@@ -24,8 +25,9 @@ import { PasswordInput } from './ui/password-input'
export function LoginForm({
className,
+ next,
...props
-}: React.ComponentPropsWithoutRef<'div'>) {
+}: React.ComponentPropsWithoutRef<'div'> & { next?: string }) {
const [email, setEmail] = useState('')
const [password, setPassword] = useState('')
const [error, setError] = useState<string | null>(null)
@@ -41,8 +43,10 @@ export function LoginForm({
try {
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('/')
+ // Redirect to the page that required sign-in (when it is a safe
+ // relative path) and refresh to ensure server components get
+ // updated session
+ router.push(safeRedirectPath(next))
router.refresh()
} catch (error: unknown) {
setError(error instanceof Error ? error.message : 'An error occurred')
@@ -56,6 +60,16 @@ export function LoginForm({
setError(null)
try {
+ // Supabase's redirect allowlist matches the callback URL exactly, so
+ // the destination rides in a short-lived cookie, not the redirectTo.
+ // Always write it: a login without a destination must clear a stale
+ // cookie left by an abandoned attempt, or that old destination would
+ // hijack the later sign-in.
+ 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 signInWithGoogle()
if (!result.success)
throw new Error(result.error ?? 'An OAuth error occurred')
@@ -86,24 +100,30 @@ export function LoginForm({
</CardHeader>
<CardContent>
<div className="flex flex-col gap-4">
- <Button
- variant="outline"
- type="button"
- className="w-full"
- onClick={handleSocialLogin}
- disabled={isLoading}
- >
- Sign In with Google
- </Button>
+ {capabilities.oauth && (
+ <>
+ <Button
+ variant="outline"
+ type="button"
+ className="w-full"
+ onClick={handleSocialLogin}
+ disabled={isLoading}
+ >
+ Sign In with Google
+ </Button>
- <div className="relative my-2">
- <div className="absolute inset-0 flex items-center">
- <span className="w-full border-t" />
- </div>
- <div className="relative flex justify-center text-xs uppercase">
- <span className="bg-muted px-2 text-muted-foreground">Or</span>
- </div>
- </div>
+ <div className="relative my-2">
+ <div className="absolute inset-0 flex items-center">
+ <span className="w-full border-t" />
+ </div>
+ <div className="relative flex justify-center text-xs uppercase">
+ <span className="bg-muted px-2 text-muted-foreground">
+ Or
+ </span>
+ </div>
+ </div>
+ </>
+ )}
<form onSubmit={handleLogin} className="flex flex-col gap-4">
<div className="grid gap-2">
@@ -144,12 +164,17 @@ export function LoginForm({
</Button>
</form>
</div>
- <div className="mt-6 text-center text-sm">
- Don&apos;t have an account?{' '}
- <Link href="/auth/sign-up" className="underline underline-offset-4">
- Sign Up
- </Link>
- </div>
+ {capabilities.signUp && (
+ <div className="mt-6 text-center text-sm">
+ Don&apos;t have an account?{' '}
+ <Link
+ href="/auth/sign-up"
+ className="underline underline-offset-4"
+ >
+ Sign Up
+ </Link>
+ </div>
+ )}
</CardContent>
</Card>
<div className="text-center text-xs text-muted-foreground">
diff --git a/components/sign-up-form.tsx b/components/sign-up-form.tsx
index 1e1853f0..b36f40ef 100644
--- a/components/sign-up-form.tsx
+++ b/components/sign-up-form.tsx
@@ -4,6 +4,7 @@ import Link from 'next/link'
import { useRouter } from 'next/navigation'
import { signUp } from '@/lib/actions/auth'
+import { useAuthCapabilities } from '@/lib/contexts/app-user-context'
import { cn } from '@/lib/utils/index'
import { Button } from '@/components/ui/button'
@@ -21,19 +22,27 @@ import { PasswordInput } from '@/components/ui/password-input'
export function SignUpForm({
className,
+ token,
+ inviteEmail,
...props
-}: React.ComponentPropsWithoutRef<'div'>) {
- const [email, setEmail] = useState('')
+}: React.ComponentPropsWithoutRef<'div'> & {
+ token?: string
+ inviteEmail?: string
+}) {
+ const [email, setEmail] = useState(inviteEmail ?? '')
const [password, setPassword] = useState('')
const [repeatPassword, setRepeatPassword] = useState('')
const [error, setError] = useState<string | null>(null)
+ const [notice, setNotice] = useState<string | null>(null)
const [isLoading, setIsLoading] = useState(false)
const router = useRouter()
+ const capabilities = useAuthCapabilities()
const handleSignUp = async (e: React.FormEvent) => {
e.preventDefault()
setIsLoading(true)
setError(null)
+ setNotice(null)
if (password !== repeatPassword) {
setError('Passwords do not match')
@@ -42,9 +51,22 @@ export function SignUpForm({
}
try {
- const result = await signUp({ email, password })
+ const result = await signUp({ email, password, token })
if (!result.success) throw new Error(result.error ?? 'An error occurred')
- router.push('/auth/sign-up-success')
+ if (result.notice) {
+ // Sign-up continues out-of-band (e.g. an emailed bootstrap link);
+ // show the message instead of redirecting.
+ setNotice(result.notice)
+ return
+ }
+ if (capabilities.emailVerification) {
+ router.push('/auth/sign-up-success')
+ } else {
+ // Providers without email verification sign the user in immediately;
+ // send them straight to the app instead of a confirmation notice.
+ router.push('/')
+ router.refresh()
+ }
} catch (error: unknown) {
setError(error instanceof Error ? error.message : 'An error occurred')
} finally {
@@ -80,6 +102,11 @@ export function SignUpForm({
value={email}
onChange={e => setEmail(e.target.value)}
/>
+ {inviteEmail && (
+ <p className="text-xs text-muted-foreground">
+ This invitation is bound to {inviteEmail}.
+ </p>
+ )}
</div>
<div className="grid gap-2">
<div className="flex items-center">
@@ -108,6 +135,7 @@ export function SignUpForm({
/>
</div>
{error && <p className="text-sm text-red-500">{error}</p>}
+ {notice && <p className="text-sm text-green-600">{notice}</p>}
<Button type="submit" className="w-full" disabled={isLoading}>
{isLoading ? 'Creating account...' : 'Sign Up'}
</Button>
diff --git a/components/update-password-form.tsx b/components/update-password-form.tsx
index dff17336..faddd2a7 100644
--- a/components/update-password-form.tsx
+++ b/components/update-password-form.tsx
@@ -19,8 +19,9 @@ import { Label } from '@/components/ui/label'
export function UpdatePasswordForm({
className,
+ token,
...props
-}: React.ComponentPropsWithoutRef<'div'>) {
+}: React.ComponentPropsWithoutRef<'div'> & { token?: string }) {
const [password, setPassword] = useState('')
const [error, setError] = useState<string | null>(null)
const [isLoading, setIsLoading] = useState(false)
@@ -32,10 +33,12 @@ export function UpdatePasswordForm({
setError(null)
try {
- const result = await updatePassword(password)
+ const result = await updatePassword(password, token)
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('/')
+ // A token reset (better-auth) establishes no session: the provider
+ // redirects to the sign-in page instead.
+ router.push(result.redirectTo ?? '/')
router.refresh()
} catch (error: unknown) {
setError(error instanceof Error ? error.message : 'An error occurred')
diff --git a/components/user-menu.tsx b/components/user-menu.tsx
index 23882795..9053aec9 100644
--- a/components/user-menu.tsx
+++ b/components/user-menu.tsx
@@ -1,12 +1,14 @@
'use client'
import { useState } from 'react'
+import Link from 'next/link'
import { useRouter } from 'next/navigation'
import {
IconChartBar as ChartBar,
IconLink as Link2,
IconLogout as LogOut,
+ IconShield,
IconUserCircle as UserRound
} from '@tabler/icons-react'
@@ -130,6 +132,14 @@ export default function UserMenu({ user }: UserMenuProps) {
<UserRound className="size-4" />
<span>Account</span>
</DropdownMenuItem>
+ {user.role === 'admin' && (
+ <DropdownMenuItem asChild>
+ <Link href="/auth/admin">
+ <IconShield className="size-4" />
+ <span>Admin</span>
+ </Link>
+ </DropdownMenuItem>
+ )}
{usage && (
<DropdownMenuItem
onSelect={event => {
diff --git a/docker-compose.yaml b/docker-compose.yaml
index cd99f577..d91667ac 100644
--- a/docker-compose.yaml
+++ b/docker-compose.yaml
@@ -20,6 +20,13 @@ services:
# Authentication settings (default: disabled for personal Docker use)
ENABLE_AUTH: ${ENABLE_AUTH:-false}
ANONYMOUS_USER_ID: ${ANONYMOUS_USER_ID:-docker-anonymous}
+ # Better Auth and SMTP settings are deliberately NOT declared here:
+ # `environment` entries override `env_file`, and ${VAR} interpolation
+ # reads the shell or a project .env file — never .env.local. Declaring
+ # them with empty defaults would wipe the values users put in
+ # .env.local. Configure AUTH_PROVIDER, BETTER_AUTH_SECRET,
+ # AUTH_SIGNUP_MODE, BOOTSTRAP_ADMIN_EMAIL and SMTP_* in .env.local
+ # (see README "Local Authentication").
MORPHIC_CLOUD_DEPLOYMENT: 'false'
# Docker-internal service URLs
LOCAL_REDIS_URL: ${LOCAL_REDIS_URL:-redis://redis:6379}
diff --git a/docs/CONFIGURATION.md b/docs/CONFIGURATION.md
index 7a8d29db..114dd034 100644
--- a/docs/CONFIGURATION.md
+++ b/docs/CONFIGURATION.md
@@ -194,11 +194,11 @@ By default, Morphic runs in **anonymous mode** (`ENABLE_AUTH=false`). This is id
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) |
+| 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 (see "Local Authentication" in the README) |
When `AUTH_PROVIDER` is **unset**, the provider is derived from the existing
environment so current deployments keep working unchanged:
@@ -207,7 +207,7 @@ environment so current deployments keep working unchanged:
- 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
+`MORPHIC_CLOUD_DEPLOYMENT=true` requires Supabase-backed auth: requests fail
with a clear error when the resolved provider is `none` or any non-Supabase
provider.
@@ -307,6 +307,16 @@ LANGFUSE_BASE_URL=https://cloud.langfuse.com
Off by default. Traces include full prompts and completions, so point `LANGFUSE_BASE_URL` at a self-hosted instance if that content should not leave your infrastructure. See [Privacy and Telemetry](./PRIVACY.md) for everything else a self-hosted instance can send outbound.
+### Chat Sharing
+
+Sharing chats is opt-in:
+
+```bash
+ENABLE_SHARE=true # runtime flag; works with prebuilt Docker images
+```
+
+`NEXT_PUBLIC_ENABLE_SHARE=true` also works when building from source, but Next.js inlines `NEXT_PUBLIC_*` values at build time, so setting it at runtime has no effect in a published image.
+
### Outbound Fetch
The `fetch` tool and the advanced-search crawler refuse private address space: loopback, RFC1918, link-local (which carries the cloud metadata endpoint), and the other non-global ranges. To let them read a service on the host's own network:
diff --git a/docs/PRIVACY.md b/docs/PRIVACY.md
index 56697935..ede60d11 100644
--- a/docs/PRIVACY.md
+++ b/docs/PRIVACY.md
@@ -8,21 +8,22 @@ This document lists everything a self-hosted Morphic instance can send outside y
Requests made by your server:
-| Destination | What it receives | Default when self-hosting |
-| -------------------------------------------------------- | ----------------------------------------------------------------------------- | ------------------------------------------- |
-| AI provider (OpenAI, Anthropic, Google, ...) | Full prompt: system prompt, conversation history, search results, attachments | **On.** Required to answer |
-| Search provider (Tavily, SearXNG, Exa, Brave, Firecrawl) | The search query the agent generates | **On.** Required to search |
-| Web pages the agent reads | Your server's IP and user agent, to whichever site the agent chose | On |
-| Jina Reader or Tavily Extract | The URL being read | Only when the agent asks for API extraction |
-| PostgreSQL | Chats, messages, attachment metadata, feedback | On. Local container under Docker |
-| Redis | Cached search results, rate limit counters, usage counters | Local container under Docker |
-| Supabase | Email, password, OAuth identity, sessions | Off unless configured |
-| R2 / S3 | Uploaded file bytes, under a key holding the user id, chat id, and filename | Off unless configured |
-| Favicon provider (Google by default) | The hostname of each cited source | On. Configurable, and can be turned off |
-| Slack | Feedback text and the submitter's email | Off unless `SLACK_WEBHOOK_URL` is set |
-| PostHog | Product analytics events. Not the user's query text | **Off** |
-| Langfuse | Full prompts and completions as traces | **Off** |
-| Vercel Analytics | Page views | **Off** |
+| Destination | What it receives | Default when self-hosting |
+| -------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------- |
+| AI provider (OpenAI, Anthropic, Google, ...) | Full prompt: system prompt, conversation history, search results, attachments | **On.** Required to answer |
+| Search provider (Tavily, SearXNG, Exa, Brave, Firecrawl) | The search query the agent generates | **On.** Required to search |
+| Web pages the agent reads | Your server's IP and user agent, to whichever site the agent chose | On |
+| Jina Reader or Tavily Extract | The URL being read | Only when the agent asks for API extraction |
+| PostgreSQL | Chats, messages, attachment metadata, feedback; with `AUTH_PROVIDER=better-auth`, also the auth tables: accounts, sessions, linked identities, verification tokens, invitations | On. Local container under Docker |
+| Redis | Cached search results, rate limit counters, usage counters | Local container under Docker |
+| Supabase | Email, password, OAuth identity, sessions | Off unless configured |
+| SMTP server | Invitation, password reset, and bootstrap emails: recipient address and a one-time link | Off unless configured |
+| R2 / S3 | Uploaded file bytes, under a key holding the user id, chat id, and filename | Off unless configured |
+| Favicon provider (Google by default) | The hostname of each cited source | On. Configurable, and can be turned off |
+| Slack | Feedback text and the submitter's email | Off unless `SLACK_WEBHOOK_URL` is set |
+| PostHog | Product analytics events. Not the user's query text | **Off** |
+| Langfuse | Full prompts and completions as traces | **Off** |
+| Vercel Analytics | Page views | **Off** |
Requests made by the user's browser, which env vars do not control:
@@ -63,6 +64,10 @@ PostgreSQL, Redis, Supabase, and R2 or S3 hold whatever you point them at. All f
Three details worth knowing if you point Redis at a hosted instance such as Upstash: the advanced-search cache uses the raw search query as part of its cache key, the guest rate limiter uses the visitor's IP address as part of its key, and the rate limit and usage budget keys carry the authenticated user's id.
+### Email (SMTP)
+
+With the Better Auth provider and SMTP configured (`SMTP_HOST`, `SMTP_USER`, `SMTP_PASSWORD`), Morphic sends invitation emails, password-reset links, and bootstrap sign-up links through your SMTP server. Each message carries the recipient address and a one-time link; no chat content is included. Without SMTP nothing is emailed: the links are shown in the admin UI instead, so the mail path stays local. Supabase-based auth sends its own auth emails through Supabase instead (covered in the Supabase row above).
+
### Source favicons
Result lists, citations, and image credits show the favicon of each source. Your server fetches those icons and serves them from your own origin at `/api/favicon`, so the visitor's browser never contacts the icon provider and the provider never learns who is reading what. What it does learn is the set of hostnames your instance cites, without any visitor attached.
diff --git a/docs/lessons-learned-review-fixes.md b/docs/lessons-learned-review-fixes.md
new file mode 100644
index 00000000..da1bed03
--- /dev/null
+++ b/docs/lessons-learned-review-fixes.md
@@ -0,0 +1,93 @@
+# Lessons Learned: Review-Fix Discipline
+
+A checklist for rounds of review fixes, born from one auth PR where roughly
+half of ~30 automated review comments were regressions introduced by the
+fixes for earlier comments — not defects in the original branch. Read it
+before starting a round of review fixes.
+
+## Why fixes beget fixes
+
+A fix treated as a line-level patch instead of a change to a user journey
+spawns regressions. The recurring root causes:
+
+1. **Fix-local thinking.** The change was reasoned about at the edited line,
+ not across every flow that consumes it (redirect chains, cookies,
+ feature flags).
+2. **Cross-provider blindness.** Auth plumbing is shared between Supabase
+ and Better Auth, and fixes were reasoned about only for the provider
+ being tested. Each provider carries external constraints (e.g.
+ Supabase's exact-match redirect allowlist).
+3. **Security primitives written from intuition.** Hand-rolled prefix
+ checks for open redirects or URL joins have well-documented bypasses.
+4. **Distribution model ignored.** Prebuilt Docker images freeze
+ `NEXT_PUBLIC_*` values at build time, and the primary deployment is a
+ single-user instance — guards designed for multi-admin setups must be
+ checked against the single-user shape first.
+5. **Test layers journey-blind.** Unit tests mock at exactly the seams
+ where the regressions lived (redirect shapes, cookie lifecycle,
+ middleware redirects); the Docker integration harness only caught
+ journey bugs after checks were added to it.
+
+## Fix-round checklist
+
+Before committing any review fix:
+
+- [ ] **Walk the journeys.** List every user flow that touches the changed
+ code path, crossed with each auth mode (anonymous, Supabase,
+ Better Auth) and each session state (logged in, logged out,
+ in-flight OAuth). If the change touches a redirect URL, follow the
+ chain through every consumer of it.
+- [ ] **Both providers.** For shared plumbing (`proxy.ts`, the provider
+ interface, login forms, redirect helpers), re-check the _other_
+ provider's constraints before shipping.
+- [ ] **Research external-facing URL shapes before changing them.** OAuth
+ redirect/callback URLs have provider-side constraints (allowlists,
+ exact matches, registered origins). Verify, don't assume.
+- [ ] **Use established safe patterns for security primitives.** Open
+ redirects: parse with `URL` and reject anything that resolves
+ off-origin (see `lib/auth/redirect-target.ts`). Never hand-roll
+ prefix checks.
+- [ ] **Concatenating user input into a URL is a security primitive too.**
+ `new URL('/' + userInput, base)` escapes the origin when a decoded
+ segment starts with a slash (an encoded `%2f` turns the path
+ protocol-relative). Assert the resolved `host` matches the expected
+ allowlist after construction.
+- [ ] **Runtime-configurable flags are server-side.** `NEXT_PUBLIC_*`
+ reads are inlined at build time even in server bundles, so they are
+ frozen in prebuilt images. Evaluate the flag server-side (e.g. fold
+ it into capabilities in `app/layout.tsx`) and pass it down; prefer
+ a non-public env var for anything that must be flippable at runtime.
+- [ ] **Add the journey test in the same commit.** If the fix changes a
+ user-visible flow, extend the integration harness (or a test) in
+ the same commit — not after the next review round finds it.
+- [ ] **Enumerate the failure/clock/race model once.** When a fix
+ introduces time, retries, or concurrency, write down every source
+ of skew/delay/race that can hit it and handle them in one pass.
+- [ ] **Mirror test:** ask what the fix _newly enables_ (a stale cookie,
+ a re-enabled link, a hidden button) and check that state too.
+- [ ] **Trace callers of a function you guard.** A guard inside a callee
+ runs _after_ the caller's side effects — a deletion guard inside
+ `deleteUser` cannot protect data the caller already deleted. In
+ destructive flows the check must run before the first destructive
+ step.
+- [ ] **A fast pre-check and the authoritative check can diverge.** Under
+ concurrency an unlocked pre-check and a locked authoritative check
+ can disagree; order destructive steps after the _authoritative_
+ check, not merely after the pre-check.
+- [ ] **Never leave an identified race "acceptable" in silence.** If a
+ check must not be passed twice, serialize it (transaction +
+ `SELECT ... FOR UPDATE`); at minimum, document the accepted race
+ where the reader will see it.
+- [ ] **An insert can always commit just after your count — re-check
+ after commit.** Row locks serialize updates to existing rows but
+ not new inserts. When the invariant is "at least one X exists",
+ re-run the deterministic election after the deleting transaction
+ commits: the racing writer's own after-commit hook and the
+ re-election cannot both miss each other without a timestamp cycle.
+
+## The meta-lesson
+
+Automated reviewers review the **diff**, not the **journey** — and so does
+a fixer with "does this resolve the flagged comment?" eyes. Every fix is a
+change with its own blast radius; give it the same rigor as the original
+feature.
diff --git a/drizzle/0019_rainy_jack_flag.sql b/drizzle/0019_rainy_jack_flag.sql
new file mode 100644
index 00000000..9e30a4b1
--- /dev/null
+++ b/drizzle/0019_rainy_jack_flag.sql
@@ -0,0 +1,81 @@
+CREATE TABLE "account" (
+ "id" text PRIMARY KEY NOT NULL,
+ "account_id" text NOT NULL,
+ "provider_id" text NOT NULL,
+ "user_id" text NOT NULL,
+ "access_token" text,
+ "refresh_token" text,
+ "id_token" text,
+ "access_token_expires_at" timestamp,
+ "refresh_token_expires_at" timestamp,
+ "scope" text,
+ "password" text,
+ "created_at" timestamp NOT NULL,
+ "updated_at" timestamp NOT NULL
+);
+--> statement-breakpoint
+CREATE TABLE "invitations" (
+ "id" text PRIMARY KEY NOT NULL,
+ "email" text,
+ "token" text NOT NULL,
+ "invited_by" text NOT NULL,
+ "revoked_at" timestamp,
+ "used_at" timestamp,
+ "expires_at" timestamp NOT NULL,
+ "created_at" timestamp DEFAULT now() NOT NULL,
+ CONSTRAINT "invitations_token_unique" UNIQUE("token")
+);
+--> statement-breakpoint
+CREATE TABLE "session" (
+ "id" text PRIMARY KEY NOT NULL,
+ "expires_at" timestamp NOT NULL,
+ "token" text NOT NULL,
+ "created_at" timestamp NOT NULL,
+ "updated_at" timestamp NOT NULL,
+ "ip_address" text,
+ "user_agent" text,
+ "impersonated_by" text,
+ "user_id" text NOT NULL,
+ CONSTRAINT "session_token_unique" UNIQUE("token")
+);
+--> statement-breakpoint
+CREATE TABLE "user" (
+ "id" text PRIMARY KEY NOT NULL,
+ "name" text NOT NULL,
+ "email" text NOT NULL,
+ "email_verified" boolean DEFAULT false NOT NULL,
+ "image" text,
+ "role" text DEFAULT 'user',
+ "banned" boolean DEFAULT false,
+ "ban_reason" text,
+ "ban_expires" timestamp,
+ "created_at" timestamp DEFAULT now() NOT NULL,
+ "updated_at" timestamp DEFAULT now() NOT NULL,
+ CONSTRAINT "user_email_unique" UNIQUE("email")
+);
+--> statement-breakpoint
+CREATE TABLE "verification" (
+ "id" text PRIMARY KEY NOT NULL,
+ "identifier" text NOT NULL,
+ "value" text NOT NULL,
+ "expires_at" timestamp NOT NULL,
+ "created_at" timestamp,
+ "updated_at" timestamp
+);
+--> statement-breakpoint
+ALTER TABLE "account" ADD CONSTRAINT "account_user_id_user_id_fk" FOREIGN KEY ("user_id") REFERENCES "public"."user"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
+ALTER TABLE "session" ADD CONSTRAINT "session_user_id_user_id_fk" FOREIGN KEY ("user_id") REFERENCES "public"."user"("id") ON DELETE cascade ON UPDATE no action;
+
+-- The production restricted connection uses app_user. Keep local databases
+-- without that role migratable while granting the minimum runtime privileges
+-- when it is present (same pattern as 0017).
+DO $$
+BEGIN
+ IF EXISTS (SELECT 1 FROM pg_roles WHERE rolname = 'app_user') THEN
+ GRANT SELECT, INSERT, UPDATE, DELETE ON TABLE "user" TO app_user;
+ GRANT SELECT, INSERT, UPDATE, DELETE ON TABLE "session" TO app_user;
+ GRANT SELECT, INSERT, UPDATE, DELETE ON TABLE "account" TO app_user;
+ GRANT SELECT, INSERT, UPDATE, DELETE ON TABLE "verification" TO app_user;
+ GRANT SELECT, INSERT, UPDATE, DELETE ON TABLE "invitations" TO app_user;
+ END IF;
+END $$;
diff --git a/drizzle/meta/0019_snapshot.json b/drizzle/meta/0019_snapshot.json
new file mode 100644
index 00000000..d8062fba
--- /dev/null
+++ b/drizzle/meta/0019_snapshot.json
@@ -0,0 +1,1732 @@
+{
+ "id": "6d6db4de-99ff-4a6b-8657-4ab00ce53c3b",
+ "prevId": "a2e83481-f715-4745-9be8-b349abc10e34",
+ "version": "7",
+ "dialect": "postgresql",
+ "tables": {
+ "public.additional_usage_interest": {
+ "name": "additional_usage_interest",
+ "schema": "",
+ "columns": {
+ "user_id": {
+ "name": "user_id",
+ "type": "varchar(255)",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "count": {
+ "name": "count",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "default": 1
+ },
+ "first_clicked_at": {
+ "name": "first_clicked_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "last_clicked_at": {
+ "name": "last_clicked_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {
+ "users_write_own_additional_usage_interest": {
+ "name": "users_write_own_additional_usage_interest",
+ "as": "PERMISSIVE",
+ "for": "ALL",
+ "to": ["public"],
+ "using": "user_id = (select current_setting('app.current_user_id', true))",
+ "withCheck": "user_id = (select current_setting('app.current_user_id', true))"
+ }
+ },
+ "checkConstraints": {},
+ "isRLSEnabled": true
+ },
+ "public.chats": {
+ "name": "chats",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "varchar(191)",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "title": {
+ "name": "title",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "user_id": {
+ "name": "user_id",
+ "type": "varchar(255)",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "visibility": {
+ "name": "visibility",
+ "type": "varchar(256)",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'private'"
+ }
+ },
+ "indexes": {
+ "chats_user_id_idx": {
+ "name": "chats_user_id_idx",
+ "columns": [
+ {
+ "expression": "user_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "chats_user_id_created_at_idx": {
+ "name": "chats_user_id_created_at_idx",
+ "columns": [
+ {
+ "expression": "user_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "created_at",
+ "isExpression": false,
+ "asc": false,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "chats_created_at_idx": {
+ "name": "chats_created_at_idx",
+ "columns": [
+ {
+ "expression": "created_at",
+ "isExpression": false,
+ "asc": false,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "chats_id_user_id_idx": {
+ "name": "chats_id_user_id_idx",
+ "columns": [
+ {
+ "expression": "id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "user_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {
+ "users_manage_own_chats": {
+ "name": "users_manage_own_chats",
+ "as": "PERMISSIVE",
+ "for": "ALL",
+ "to": ["public"],
+ "using": "user_id = (select current_setting('app.current_user_id', true))",
+ "withCheck": "user_id = (select current_setting('app.current_user_id', true))"
+ },
+ "public_chats_readable": {
+ "name": "public_chats_readable",
+ "as": "PERMISSIVE",
+ "for": "SELECT",
+ "to": ["public"],
+ "using": "visibility = 'public'"
+ }
+ },
+ "checkConstraints": {},
+ "isRLSEnabled": true
+ },
+ "public.feedback": {
+ "name": "feedback",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "varchar(191)",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "user_id": {
+ "name": "user_id",
+ "type": "varchar(255)",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "sentiment": {
+ "name": "sentiment",
+ "type": "varchar(256)",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "message": {
+ "name": "message",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "page_url": {
+ "name": "page_url",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "user_agent": {
+ "name": "user_agent",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "feedback_user_id_idx": {
+ "name": "feedback_user_id_idx",
+ "columns": [
+ {
+ "expression": "user_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "feedback_created_at_idx": {
+ "name": "feedback_created_at_idx",
+ "columns": [
+ {
+ "expression": "created_at",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {
+ "feedback_select_policy": {
+ "name": "feedback_select_policy",
+ "as": "PERMISSIVE",
+ "for": "SELECT",
+ "to": ["public"],
+ "using": "true"
+ },
+ "anyone_can_insert_feedback": {
+ "name": "anyone_can_insert_feedback",
+ "as": "PERMISSIVE",
+ "for": "INSERT",
+ "to": ["public"],
+ "withCheck": "true"
+ },
+ "users_anonymize_own_feedback": {
+ "name": "users_anonymize_own_feedback",
+ "as": "PERMISSIVE",
+ "for": "UPDATE",
+ "to": ["public"],
+ "using": "user_id = (select current_setting('app.current_user_id', true))",
+ "withCheck": "user_id IS NULL"
+ }
+ },
+ "checkConstraints": {},
+ "isRLSEnabled": true
+ },
+ "public.files": {
+ "name": "files",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "varchar(191)",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "user_id": {
+ "name": "user_id",
+ "type": "varchar(255)",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "chat_id": {
+ "name": "chat_id",
+ "type": "varchar(191)",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "filename": {
+ "name": "filename",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "object_key": {
+ "name": "object_key",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "media_type": {
+ "name": "media_type",
+ "type": "varchar(256)",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "size": {
+ "name": "size",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "files_user_id_idx": {
+ "name": "files_user_id_idx",
+ "columns": [
+ {
+ "expression": "user_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "files_user_id_updated_at_idx": {
+ "name": "files_user_id_updated_at_idx",
+ "columns": [
+ {
+ "expression": "user_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "updated_at",
+ "isExpression": false,
+ "asc": false,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "files_chat_id_idx": {
+ "name": "files_chat_id_idx",
+ "columns": [
+ {
+ "expression": "chat_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "files_media_type_idx": {
+ "name": "files_media_type_idx",
+ "columns": [
+ {
+ "expression": "media_type",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "files_object_key_idx": {
+ "name": "files_object_key_idx",
+ "columns": [
+ {
+ "expression": "object_key",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "files_chat_id_chats_id_fk": {
+ "name": "files_chat_id_chats_id_fk",
+ "tableFrom": "files",
+ "tableTo": "chats",
+ "columnsFrom": ["chat_id"],
+ "columnsTo": ["id"],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {
+ "users_manage_own_files": {
+ "name": "users_manage_own_files",
+ "as": "PERMISSIVE",
+ "for": "ALL",
+ "to": ["public"],
+ "using": "user_id = (select current_setting('app.current_user_id', true))",
+ "withCheck": "user_id = (select current_setting('app.current_user_id', true))"
+ }
+ },
+ "checkConstraints": {},
+ "isRLSEnabled": true
+ },
+ "public.messages": {
+ "name": "messages",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "varchar(191)",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "chat_id": {
+ "name": "chat_id",
+ "type": "varchar(191)",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "role": {
+ "name": "role",
+ "type": "varchar(256)",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "metadata": {
+ "name": "metadata",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false
+ }
+ },
+ "indexes": {
+ "messages_chat_id_idx": {
+ "name": "messages_chat_id_idx",
+ "columns": [
+ {
+ "expression": "chat_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "messages_chat_id_created_at_idx": {
+ "name": "messages_chat_id_created_at_idx",
+ "columns": [
+ {
+ "expression": "chat_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "created_at",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "messages_chat_id_chats_id_fk": {
+ "name": "messages_chat_id_chats_id_fk",
+ "tableFrom": "messages",
+ "tableTo": "chats",
+ "columnsFrom": ["chat_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {
+ "users_manage_chat_messages": {
+ "name": "users_manage_chat_messages",
+ "as": "PERMISSIVE",
+ "for": "ALL",
+ "to": ["public"],
+ "using": "EXISTS (\n SELECT 1 FROM \"chats\"\n WHERE \"chats\".id = chat_id\n AND \"chats\".user_id = current_setting('app.current_user_id', true)\n )",
+ "withCheck": "EXISTS (\n SELECT 1 FROM \"chats\"\n WHERE \"chats\".id = chat_id\n AND \"chats\".user_id = current_setting('app.current_user_id', true)\n )"
+ },
+ "public_chat_messages_readable": {
+ "name": "public_chat_messages_readable",
+ "as": "PERMISSIVE",
+ "for": "SELECT",
+ "to": ["public"],
+ "using": "EXISTS (\n SELECT 1 FROM \"chats\"\n WHERE \"chats\".id = chat_id\n AND \"chats\".visibility = 'public'\n )"
+ }
+ },
+ "checkConstraints": {},
+ "isRLSEnabled": true
+ },
+ "public.notes": {
+ "name": "notes",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "varchar(191)",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "user_id": {
+ "name": "user_id",
+ "type": "varchar(255)",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "chat_id": {
+ "name": "chat_id",
+ "type": "varchar(191)",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "source_message_id": {
+ "name": "source_message_id",
+ "type": "varchar(191)",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "title": {
+ "name": "title",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "content": {
+ "name": "content",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "notes_user_id_idx": {
+ "name": "notes_user_id_idx",
+ "columns": [
+ {
+ "expression": "user_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "notes_user_id_updated_at_idx": {
+ "name": "notes_user_id_updated_at_idx",
+ "columns": [
+ {
+ "expression": "user_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "updated_at",
+ "isExpression": false,
+ "asc": false,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "notes_chat_id_idx": {
+ "name": "notes_chat_id_idx",
+ "columns": [
+ {
+ "expression": "chat_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "notes_source_message_id_idx": {
+ "name": "notes_source_message_id_idx",
+ "columns": [
+ {
+ "expression": "source_message_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "notes_chat_id_chats_id_fk": {
+ "name": "notes_chat_id_chats_id_fk",
+ "tableFrom": "notes",
+ "tableTo": "chats",
+ "columnsFrom": ["chat_id"],
+ "columnsTo": ["id"],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {
+ "users_manage_own_notes": {
+ "name": "users_manage_own_notes",
+ "as": "PERMISSIVE",
+ "for": "ALL",
+ "to": ["public"],
+ "using": "user_id = (select current_setting('app.current_user_id', true))",
+ "withCheck": "user_id = (select current_setting('app.current_user_id', true))"
+ }
+ },
+ "checkConstraints": {},
+ "isRLSEnabled": true
+ },
+ "public.parts": {
+ "name": "parts",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "varchar(191)",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "message_id": {
+ "name": "message_id",
+ "type": "varchar(191)",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "order": {
+ "name": "order",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "type": {
+ "name": "type",
+ "type": "varchar(256)",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "text_text": {
+ "name": "text_text",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "reasoning_text": {
+ "name": "reasoning_text",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "file_media_type": {
+ "name": "file_media_type",
+ "type": "varchar(256)",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "file_filename": {
+ "name": "file_filename",
+ "type": "varchar(1024)",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "file_url": {
+ "name": "file_url",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "file_key": {
+ "name": "file_key",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "source_url_source_id": {
+ "name": "source_url_source_id",
+ "type": "varchar(256)",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "source_url_url": {
+ "name": "source_url_url",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "source_url_title": {
+ "name": "source_url_title",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "source_document_source_id": {
+ "name": "source_document_source_id",
+ "type": "varchar(256)",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "source_document_media_type": {
+ "name": "source_document_media_type",
+ "type": "varchar(256)",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "source_document_title": {
+ "name": "source_document_title",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "source_document_filename": {
+ "name": "source_document_filename",
+ "type": "varchar(1024)",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "source_document_url": {
+ "name": "source_document_url",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "source_document_snippet": {
+ "name": "source_document_snippet",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "tool_tool_call_id": {
+ "name": "tool_tool_call_id",
+ "type": "varchar(256)",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "tool_state": {
+ "name": "tool_state",
+ "type": "varchar(256)",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "tool_error_text": {
+ "name": "tool_error_text",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "tool_search_input": {
+ "name": "tool_search_input",
+ "type": "json",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "tool_search_output": {
+ "name": "tool_search_output",
+ "type": "json",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "tool_fetch_input": {
+ "name": "tool_fetch_input",
+ "type": "json",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "tool_fetch_output": {
+ "name": "tool_fetch_output",
+ "type": "json",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "tool_question_input": {
+ "name": "tool_question_input",
+ "type": "json",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "tool_question_output": {
+ "name": "tool_question_output",
+ "type": "json",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "tool_todoWrite_input": {
+ "name": "tool_todoWrite_input",
+ "type": "json",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "tool_todoWrite_output": {
+ "name": "tool_todoWrite_output",
+ "type": "json",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "tool_todoRead_input": {
+ "name": "tool_todoRead_input",
+ "type": "json",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "tool_todoRead_output": {
+ "name": "tool_todoRead_output",
+ "type": "json",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "tool_dynamic_input": {
+ "name": "tool_dynamic_input",
+ "type": "json",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "tool_dynamic_output": {
+ "name": "tool_dynamic_output",
+ "type": "json",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "tool_dynamic_name": {
+ "name": "tool_dynamic_name",
+ "type": "varchar(256)",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "tool_dynamic_type": {
+ "name": "tool_dynamic_type",
+ "type": "varchar(256)",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "data_prefix": {
+ "name": "data_prefix",
+ "type": "varchar(256)",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "data_content": {
+ "name": "data_content",
+ "type": "json",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "data_id": {
+ "name": "data_id",
+ "type": "varchar(256)",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "provider_metadata": {
+ "name": "provider_metadata",
+ "type": "json",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "parts_message_id_idx": {
+ "name": "parts_message_id_idx",
+ "columns": [
+ {
+ "expression": "message_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "parts_message_id_order_idx": {
+ "name": "parts_message_id_order_idx",
+ "columns": [
+ {
+ "expression": "message_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "order",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "parts_message_id_messages_id_fk": {
+ "name": "parts_message_id_messages_id_fk",
+ "tableFrom": "parts",
+ "tableTo": "messages",
+ "columnsFrom": ["message_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {
+ "users_manage_message_parts": {
+ "name": "users_manage_message_parts",
+ "as": "PERMISSIVE",
+ "for": "ALL",
+ "to": ["public"],
+ "using": "EXISTS (\n SELECT 1 FROM \"messages\"\n INNER JOIN \"chats\" ON \"chats\".id = \"messages\".chat_id\n WHERE \"messages\".id = message_id\n AND \"chats\".user_id = current_setting('app.current_user_id', true)\n )",
+ "withCheck": "EXISTS (\n SELECT 1 FROM \"messages\"\n INNER JOIN \"chats\" ON \"chats\".id = \"messages\".chat_id\n WHERE \"messages\".id = message_id\n AND \"chats\".user_id = current_setting('app.current_user_id', true)\n )"
+ },
+ "public_chat_parts_readable": {
+ "name": "public_chat_parts_readable",
+ "as": "PERMISSIVE",
+ "for": "SELECT",
+ "to": ["public"],
+ "using": "EXISTS (\n SELECT 1 FROM \"messages\"\n INNER JOIN \"chats\" ON \"chats\".id = \"messages\".chat_id\n WHERE \"messages\".id = message_id\n AND \"chats\".visibility = 'public'\n )"
+ }
+ },
+ "checkConstraints": {
+ "text_text_required": {
+ "name": "text_text_required",
+ "value": "(type != 'text' OR text_text IS NOT NULL)"
+ },
+ "reasoning_text_required": {
+ "name": "reasoning_text_required",
+ "value": "(type != 'reasoning' OR reasoning_text IS NOT NULL)"
+ },
+ "file_fields_required": {
+ "name": "file_fields_required",
+ "value": "(type != 'file' OR (file_media_type IS NOT NULL AND file_filename IS NOT NULL AND (file_key IS NOT NULL OR file_url IS NOT NULL)))"
+ },
+ "tool_state_valid": {
+ "name": "tool_state_valid",
+ "value": "(tool_state IS NULL OR tool_state IN ('input-streaming', 'input-available', 'output-available', 'output-error'))"
+ },
+ "tool_fields_required": {
+ "name": "tool_fields_required",
+ "value": "(type NOT LIKE 'tool-%' OR (tool_tool_call_id IS NOT NULL AND tool_state IS NOT NULL))"
+ }
+ },
+ "isRLSEnabled": true
+ },
+ "public.usage_events": {
+ "name": "usage_events",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "varchar(191)",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "user_id": {
+ "name": "user_id",
+ "type": "varchar(255)",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "event_type": {
+ "name": "event_type",
+ "type": "varchar(256)",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "amount": {
+ "name": "amount",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "mode": {
+ "name": "mode",
+ "type": "varchar(256)",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "attempt_id": {
+ "name": "attempt_id",
+ "type": "varchar(191)",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "message_id": {
+ "name": "message_id",
+ "type": "varchar(191)",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "remaining": {
+ "name": "remaining",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "usage_events_user_type_attempt_idx": {
+ "name": "usage_events_user_type_attempt_idx",
+ "columns": [
+ {
+ "expression": "user_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "event_type",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "attempt_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": true,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "usage_events_user_created_idx": {
+ "name": "usage_events_user_created_idx",
+ "columns": [
+ {
+ "expression": "user_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "created_at",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {
+ "users_read_own_usage_events": {
+ "name": "users_read_own_usage_events",
+ "as": "PERMISSIVE",
+ "for": "SELECT",
+ "to": ["public"],
+ "using": "user_id = (select current_setting('app.current_user_id', true))"
+ },
+ "users_insert_own_usage_events": {
+ "name": "users_insert_own_usage_events",
+ "as": "PERMISSIVE",
+ "for": "INSERT",
+ "to": ["public"],
+ "withCheck": "user_id = (select current_setting('app.current_user_id', true))"
+ }
+ },
+ "checkConstraints": {},
+ "isRLSEnabled": true
+ },
+ "public.usage_grants": {
+ "name": "usage_grants",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "varchar(191)",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "user_id": {
+ "name": "user_id",
+ "type": "varchar(255)",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "idempotency_key": {
+ "name": "idempotency_key",
+ "type": "varchar(256)",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "kind": {
+ "name": "kind",
+ "type": "varchar(256)",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "amount": {
+ "name": "amount",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "granted_at": {
+ "name": "granted_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "expires_at": {
+ "name": "expires_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "usage_grants_user_idempotency_idx": {
+ "name": "usage_grants_user_idempotency_idx",
+ "columns": [
+ {
+ "expression": "user_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "idempotency_key",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": true,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "usage_grants_user_expires_idx": {
+ "name": "usage_grants_user_expires_idx",
+ "columns": [
+ {
+ "expression": "user_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "expires_at",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {
+ "users_read_own_usage_grants": {
+ "name": "users_read_own_usage_grants",
+ "as": "PERMISSIVE",
+ "for": "SELECT",
+ "to": ["public"],
+ "using": "user_id = (select current_setting('app.current_user_id', true))"
+ },
+ "users_insert_own_usage_grants": {
+ "name": "users_insert_own_usage_grants",
+ "as": "PERMISSIVE",
+ "for": "INSERT",
+ "to": ["public"],
+ "withCheck": "user_id = (select current_setting('app.current_user_id', true))"
+ }
+ },
+ "checkConstraints": {},
+ "isRLSEnabled": true
+ },
+ "public.account": {
+ "name": "account",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "account_id": {
+ "name": "account_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "provider_id": {
+ "name": "provider_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "user_id": {
+ "name": "user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "access_token": {
+ "name": "access_token",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "refresh_token": {
+ "name": "refresh_token",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "id_token": {
+ "name": "id_token",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "access_token_expires_at": {
+ "name": "access_token_expires_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "refresh_token_expires_at": {
+ "name": "refresh_token_expires_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "scope": {
+ "name": "scope",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "password": {
+ "name": "password",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "account_user_id_user_id_fk": {
+ "name": "account_user_id_user_id_fk",
+ "tableFrom": "account",
+ "tableTo": "user",
+ "columnsFrom": ["user_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.invitations": {
+ "name": "invitations",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "email": {
+ "name": "email",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "token": {
+ "name": "token",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "invited_by": {
+ "name": "invited_by",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "revoked_at": {
+ "name": "revoked_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "used_at": {
+ "name": "used_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "expires_at": {
+ "name": "expires_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {
+ "invitations_token_unique": {
+ "name": "invitations_token_unique",
+ "nullsNotDistinct": false,
+ "columns": ["token"]
+ }
+ },
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.session": {
+ "name": "session",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "expires_at": {
+ "name": "expires_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "token": {
+ "name": "token",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "ip_address": {
+ "name": "ip_address",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "user_agent": {
+ "name": "user_agent",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "impersonated_by": {
+ "name": "impersonated_by",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "user_id": {
+ "name": "user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "session_user_id_user_id_fk": {
+ "name": "session_user_id_user_id_fk",
+ "tableFrom": "session",
+ "tableTo": "user",
+ "columnsFrom": ["user_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {
+ "session_token_unique": {
+ "name": "session_token_unique",
+ "nullsNotDistinct": false,
+ "columns": ["token"]
+ }
+ },
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.user": {
+ "name": "user",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "name": {
+ "name": "name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "email": {
+ "name": "email",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "email_verified": {
+ "name": "email_verified",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": true,
+ "default": false
+ },
+ "image": {
+ "name": "image",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "role": {
+ "name": "role",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "default": "'user'"
+ },
+ "banned": {
+ "name": "banned",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": false,
+ "default": false
+ },
+ "ban_reason": {
+ "name": "ban_reason",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "ban_expires": {
+ "name": "ban_expires",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {
+ "user_email_unique": {
+ "name": "user_email_unique",
+ "nullsNotDistinct": false,
+ "columns": ["email"]
+ }
+ },
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.verification": {
+ "name": "verification",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "identifier": {
+ "name": "identifier",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "value": {
+ "name": "value",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "expires_at": {
+ "name": "expires_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ }
+ },
+ "enums": {},
+ "schemas": {},
+ "sequences": {},
+ "roles": {},
+ "policies": {},
+ "views": {},
+ "_meta": {
+ "columns": {},
+ "schemas": {},
+ "tables": {}
+ }
+}
diff --git a/drizzle/meta/_journal.json b/drizzle/meta/_journal.json
index 4dcd1fcd..f1c40d5d 100644
--- a/drizzle/meta/_journal.json
+++ b/drizzle/meta/_journal.json
@@ -134,6 +134,13 @@
"when": 1789527844631,
"tag": "0018_reconcile_usage_budget_snapshot",
"breakpoints": true
+ },
+ {
+ "idx": 19,
+ "version": "7",
+ "when": 1791284859864,
+ "tag": "0019_rainy_jack_flag",
+ "breakpoints": true
}
]
}
diff --git a/hooks/__tests__/user-hooks.test.tsx b/hooks/__tests__/user-hooks.test.tsx
index 1172f976..77166d94 100644
--- a/hooks/__tests__/user-hooks.test.tsx
+++ b/hooks/__tests__/user-hooks.test.tsx
@@ -8,7 +8,14 @@ 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 capabilities = {
+ signUp: true,
+ passwordReset: true,
+ deleteUser: true,
+ oauth: false,
+ emailVerification: false,
+ share: true
+}
const user: AppUser = {
id: 'user-1',
diff --git a/lib/actions/__tests__/account-better-auth.test.ts b/lib/actions/__tests__/account-better-auth.test.ts
new file mode 100644
index 00000000..5a205f54
--- /dev/null
+++ b/lib/actions/__tests__/account-better-auth.test.ts
@@ -0,0 +1,182 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+
+import { trackAccountDeleted } from '@/lib/analytics'
+import { getCurrentUser } from '@/lib/auth/get-current-user'
+import { db } from '@/lib/db'
+import * as dbActions from '@/lib/db/actions'
+import { deleteUserObjects } from '@/lib/storage/r2-client'
+
+import { deleteAccount } from '../account'
+
+vi.mock('@/lib/analytics')
+vi.mock('@/lib/auth/get-current-user')
+vi.mock('@/lib/db/actions')
+vi.mock('@/lib/storage/r2-client')
+vi.mock('@/lib/db', () => {
+ const db: Record<string, unknown> = {
+ delete: vi.fn(() => ({
+ where: vi.fn(async () => undefined)
+ })),
+ // Role lookup for the last-admin guard: no row -> guard skipped.
+ select: vi.fn(() => ({
+ from: vi.fn(() =>
+ Object.assign(Promise.resolve([{ n: 0 }]), {
+ where: vi.fn(() =>
+ Object.assign(Promise.resolve([{ n: 0 }]), {
+ limit: vi.fn(() =>
+ Object.assign(Promise.resolve([]), {
+ for: vi.fn(async () => [])
+ })
+ ),
+ for: vi.fn(async () => [])
+ })
+ )
+ })
+ )
+ }))
+ }
+ // Transactions receive the same mock object so deletes through tx
+ // are visible on db.delete. A callback that throws simulates an
+ // aborted transaction: deletes recorded inside it are undone.
+ db.transaction = vi.fn(async (cb: (tx: unknown) => unknown) => {
+ const mark = (db.delete as ReturnType<typeof vi.fn>).mock.calls.length
+ try {
+ return await cb(db)
+ } catch (error) {
+ ;(db.delete as ReturnType<typeof vi.fn>).mock.calls.length = mark
+ throw error
+ }
+ })
+ return { db }
+})
+
+describe('deleteAccount with the better-auth provider', () => {
+ const originalEnv: Record<string, string | undefined> = {}
+
+ beforeEach(() => {
+ for (const key of ['AUTH_PROVIDER', 'MORPHIC_CLOUD_DEPLOYMENT']) {
+ originalEnv[key] = process.env[key]
+ }
+ process.env.AUTH_PROVIDER = 'better-auth'
+ delete process.env.MORPHIC_CLOUD_DEPLOYMENT
+
+ vi.mocked(getCurrentUser).mockResolvedValue({
+ id: 'user-1',
+ email: '[email protected]',
+ role: 'user'
+ })
+ vi.mocked(dbActions.deleteUserChats).mockResolvedValue({ success: true })
+ vi.mocked(dbActions.deleteUserNotes).mockResolvedValue({ success: true })
+ vi.mocked(dbActions.deleteUserLibraryFiles).mockResolvedValue({
+ success: true
+ })
+ vi.mocked(dbActions.anonymizeUserFeedback).mockResolvedValue({
+ success: true
+ })
+ vi.mocked(deleteUserObjects).mockResolvedValue({ deletedCount: 0 } as never)
+ vi.mocked(trackAccountDeleted).mockResolvedValue()
+ })
+
+ afterEach(() => {
+ for (const [key, value] of Object.entries(originalEnv)) {
+ if (value === undefined) {
+ delete process.env[key]
+ } else {
+ process.env[key] = value
+ }
+ }
+ vi.clearAllMocks()
+ })
+
+ it('removes chats, notes, files, and the auth user record', async () => {
+ const result = await deleteAccount()
+
+ expect(result).toEqual({ success: true })
+ expect(dbActions.deleteUserChats).toHaveBeenCalledWith('user-1')
+ expect(dbActions.deleteUserNotes).toHaveBeenCalledWith('user-1')
+ expect(dbActions.deleteUserLibraryFiles).toHaveBeenCalledWith('user-1')
+ expect(dbActions.anonymizeUserFeedback).toHaveBeenCalledWith('user-1')
+ expect(deleteUserObjects).toHaveBeenCalledWith('user-1')
+ expect(db.delete).toHaveBeenCalled()
+ })
+
+ it('rolls back the identity deletion when cleanup fails', async () => {
+ vi.mocked(dbActions.deleteUserChats).mockResolvedValue({
+ success: false,
+ error: 'db down'
+ })
+
+ const result = await deleteAccount()
+
+ expect(result.success).toBe(false)
+ expect(result.error).toBe('db down')
+ // The cleanup failure aborts the transaction, so the identity
+ // delete that ran inside it is rolled back (the mock transaction
+ // undoes recorded deletes when the callback throws). The user
+ // keeps the account and its sessions, and can retry the deletion.
+ expect(db.delete).not.toHaveBeenCalled()
+ expect(trackAccountDeleted).not.toHaveBeenCalled()
+ })
+
+ it('serializes concurrent deletions in-process', async () => {
+ // The guard transaction holds a pooled connection while cleanup
+ // steps check out their own; unbounded concurrency could occupy the
+ // whole pool. Deletions must run one at a time per process.
+ let active = 0
+ let maxActive = 0
+ vi.mocked(dbActions.deleteUserChats).mockImplementation(async () => {
+ active++
+ maxActive = Math.max(maxActive, active)
+ await new Promise(resolve => setTimeout(resolve, 5))
+ active--
+ return { success: true }
+ })
+
+ await Promise.all([deleteAccount(), deleteAccount()])
+
+ expect(maxActive).toBe(1)
+ })
+
+ it('refuses before destroying any data when the user is the only admin', async () => {
+ vi.mocked(db.select).mockImplementation((() => ({
+ from: () =>
+ Object.assign(Promise.resolve([{ n: 2 }]), {
+ where: () =>
+ Object.assign(Promise.resolve([{ n: 1 }]), {
+ limit: () =>
+ Object.assign(
+ Promise.resolve([{ id: 'user-1', role: 'admin' }]),
+ {
+ for: async () => [{ id: 'user-1', role: 'admin' }]
+ }
+ ),
+ for: async () => [{ id: 'user-1' }]
+ })
+ })
+ })) as never)
+
+ const result = await deleteAccount()
+
+ expect(result.success).toBe(false)
+ expect(result.error).toMatch(/only admin/i)
+ // The rejection must happen before the destructive steps: a rejected
+ // deletion must leave the account's chats, notes, and files intact.
+ expect(dbActions.deleteUserChats).not.toHaveBeenCalled()
+ expect(dbActions.deleteUserNotes).not.toHaveBeenCalled()
+ expect(dbActions.deleteUserLibraryFiles).not.toHaveBeenCalled()
+ expect(deleteUserObjects).not.toHaveBeenCalled()
+ expect(db.delete).not.toHaveBeenCalled()
+ })
+
+ it('returns an error result when the pre-check throws', async () => {
+ vi.mocked(db.select).mockImplementation(() => {
+ throw new Error('db down')
+ })
+
+ const result = await deleteAccount()
+
+ expect(result.success).toBe(false)
+ expect(result.error).toBe('db down')
+ expect(dbActions.deleteUserChats).not.toHaveBeenCalled()
+ })
+})
diff --git a/lib/actions/__tests__/account.test.ts b/lib/actions/__tests__/account.test.ts
index b1d58d78..641f9860 100644
--- a/lib/actions/__tests__/account.test.ts
+++ b/lib/actions/__tests__/account.test.ts
@@ -4,6 +4,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { trackAccountDeleted } from '@/lib/analytics'
import { getCurrentUser } from '@/lib/auth/get-current-user'
+import { db } from '@/lib/db'
import * as dbActions from '@/lib/db/actions'
import { deleteUserObjects } from '@/lib/storage/r2-client'
import { createAdminClient } from '@/lib/supabase/admin'
@@ -15,6 +16,14 @@ vi.mock('@/lib/auth/get-current-user')
vi.mock('@/lib/db/actions')
vi.mock('@/lib/storage/r2-client')
vi.mock('@/lib/supabase/admin')
+vi.mock('@/lib/db', () => {
+ // deleteAccount wraps the flow in a transaction; the supabase provider
+ // has no in-database guard, so the transaction body only runs mocked
+ // cleanup and the mocked admin API call.
+ const db: Record<string, unknown> = {}
+ db.transaction = vi.fn((cb: (tx: unknown) => unknown) => cb(db))
+ return { db }
+})
const originalEnableAuth = process.env.ENABLE_AUTH
@@ -102,9 +111,54 @@ describe('Account Actions', () => {
expect(deleteUser).toHaveBeenCalledWith(user.id)
expect(revalidateTag).toHaveBeenCalledWith('chat', 'max')
expect(trackAccountDeleted).toHaveBeenCalledTimes(1)
+ // supabase has no in-database guard, so no transaction is opened:
+ // an outer transaction would hold a pooled connection while the
+ // cleanup steps check out their own.
+ expect(db.transaction).not.toHaveBeenCalled()
+ })
+
+ it('deletes the auth user only after all data cleanup succeeds', async () => {
+ const calls: string[] = []
+ deleteUser.mockImplementation(async () => {
+ calls.push('auth')
+ return { data: { user: null }, error: null }
+ })
+ vi.mocked(dbActions.deleteUserChats).mockImplementation(async () => {
+ calls.push('chats')
+ return { success: true }
+ })
+ vi.mocked(dbActions.deleteUserNotes).mockImplementation(async () => {
+ calls.push('notes')
+ return { success: true }
+ })
+ vi.mocked(dbActions.deleteUserLibraryFiles).mockImplementation(async () => {
+ calls.push('files')
+ return { success: true }
+ })
+ vi.mocked(dbActions.anonymizeUserFeedback).mockImplementation(async () => {
+ calls.push('feedback')
+ return { success: true }
+ })
+ vi.mocked(deleteUserObjects).mockImplementation(async () => {
+ calls.push('objects')
+ return { deletedCount: 0, skipped: true }
+ })
+
+ await deleteAccount()
+
+ // The identity is removed last so that any cleanup failure leaves
+ // the account in place and the user can retry the deletion.
+ expect(calls).toEqual([
+ 'chats',
+ 'notes',
+ 'files',
+ 'feedback',
+ 'objects',
+ 'auth'
+ ])
})
- it('stops before storage and auth deletion when app data deletion fails', async () => {
+ it('keeps the identity and stops before remaining cleanup when app data deletion fails', async () => {
vi.mocked(dbActions.deleteUserChats).mockResolvedValue({
success: false,
error: 'Failed to delete user chats'
@@ -116,12 +170,13 @@ describe('Account Actions', () => {
success: false,
error: 'Failed to delete user chats'
})
- expect(deleteUserObjects).not.toHaveBeenCalled()
expect(deleteUser).not.toHaveBeenCalled()
+ expect(dbActions.deleteUserNotes).not.toHaveBeenCalled()
+ expect(deleteUserObjects).not.toHaveBeenCalled()
expect(trackAccountDeleted).not.toHaveBeenCalled()
})
- it('stops before storage and auth deletion when notes deletion fails', async () => {
+ it('keeps the identity and stops before remaining cleanup when notes deletion fails', async () => {
vi.mocked(dbActions.deleteUserNotes).mockResolvedValue({
success: false,
error: 'Failed to delete user notes'
@@ -133,12 +188,13 @@ describe('Account Actions', () => {
success: false,
error: 'Failed to delete user notes'
})
- expect(deleteUserObjects).not.toHaveBeenCalled()
expect(deleteUser).not.toHaveBeenCalled()
+ expect(dbActions.deleteUserLibraryFiles).not.toHaveBeenCalled()
+ expect(deleteUserObjects).not.toHaveBeenCalled()
expect(trackAccountDeleted).not.toHaveBeenCalled()
})
- it('stops before storage and auth deletion when feedback anonymization fails', async () => {
+ it('keeps the identity and stops before remaining cleanup when feedback anonymization fails', async () => {
vi.mocked(dbActions.anonymizeUserFeedback).mockResolvedValue({
success: false,
error: 'Failed to anonymize user feedback'
@@ -150,12 +206,12 @@ describe('Account Actions', () => {
success: false,
error: 'Failed to anonymize user feedback'
})
- expect(deleteUserObjects).not.toHaveBeenCalled()
expect(deleteUser).not.toHaveBeenCalled()
+ expect(deleteUserObjects).not.toHaveBeenCalled()
expect(trackAccountDeleted).not.toHaveBeenCalled()
})
- it('stops before storage and auth deletion when library file deletion fails', async () => {
+ it('keeps the identity and stops before remaining cleanup when library file deletion fails', async () => {
vi.mocked(dbActions.deleteUserLibraryFiles).mockResolvedValue({
success: false,
error: 'Failed to delete user files'
@@ -167,12 +223,12 @@ describe('Account Actions', () => {
success: false,
error: 'Failed to delete user files'
})
- expect(deleteUserObjects).not.toHaveBeenCalled()
expect(deleteUser).not.toHaveBeenCalled()
+ expect(deleteUserObjects).not.toHaveBeenCalled()
expect(trackAccountDeleted).not.toHaveBeenCalled()
})
- it('stops before auth deletion when uploaded file deletion fails', async () => {
+ it('keeps the identity when uploaded file deletion fails', async () => {
vi.mocked(deleteUserObjects).mockRejectedValue(new Error('Storage error'))
const result = await deleteAccount()
diff --git a/lib/actions/__tests__/admin.test.ts b/lib/actions/__tests__/admin.test.ts
new file mode 100644
index 00000000..73a92618
--- /dev/null
+++ b/lib/actions/__tests__/admin.test.ts
@@ -0,0 +1,303 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+
+import {
+ createInvitationAction,
+ promoteMemberAction,
+ resetMemberPasswordAction,
+ revokeInvitationAction
+} from '@/lib/actions/admin'
+import { getAuth } from '@/lib/auth/better-auth/config'
+import {
+ createInvitation,
+ revokeInvitation
+} from '@/lib/auth/better-auth/invitations'
+import { getCurrentUser } from '@/lib/auth/get-current-user'
+
+vi.mock('@/lib/auth/get-current-user')
+vi.mock('@/lib/auth/better-auth/invitations')
+vi.mock('nodemailer', () => ({
+ default: {
+ createTransport: vi.fn(() => ({ sendMail: vi.fn(async () => {}) }))
+ }
+}))
+
+const { mockSetUserPassword, mockSetRole } = vi.hoisted(() => ({
+ mockSetUserPassword: vi.fn(),
+ mockSetRole: vi.fn()
+}))
+
+vi.mock('@/lib/auth/better-auth/config', () => ({
+ getAuth: () => ({
+ api: { setUserPassword: mockSetUserPassword, setRole: mockSetRole }
+ }),
+ getEmailLinkOrigin: () =>
+ (process.env.BETTER_AUTH_URL ?? '').trim().replace(/\/+$/, '')
+}))
+
+vi.mock('next/headers', () => ({
+ headers: vi.fn(async () => new Headers({ origin: 'http://localhost:3000' })),
+ cookies: vi.fn(async () => ({ append: vi.fn() }))
+}))
+
+vi.mock('@/lib/auth/request', () => ({
+ getRequestOrigin: vi.fn(async () => 'http://localhost:3000')
+}))
+
+const adminUser = {
+ id: 'admin-1',
+ email: '[email protected]',
+ name: 'Admin',
+ role: 'admin'
+}
+const memberUser = {
+ id: 'user-1',
+ email: '[email protected]',
+ name: 'Member',
+ role: 'user'
+}
+
+const invitationRecord = {
+ id: 'inv-1',
+ email: '[email protected]',
+ token: 'tok123',
+ invitedBy: 'admin-1',
+ revokedAt: null,
+ usedAt: null,
+ expiresAt: new Date(Date.now() + 60_000),
+ createdAt: new Date()
+}
+
+describe('admin actions', () => {
+ const originalEnv: Record<string, string | undefined> = {}
+
+ beforeEach(() => {
+ for (const key of [
+ 'SMTP_HOST',
+ 'SMTP_USER',
+ 'SMTP_PASSWORD',
+ 'BETTER_AUTH_URL'
+ ]) {
+ originalEnv[key] = process.env[key]
+ delete process.env[key]
+ }
+ vi.clearAllMocks()
+ })
+
+ afterEach(() => {
+ for (const [key, value] of Object.entries(originalEnv)) {
+ if (value === undefined) {
+ delete process.env[key]
+ } else {
+ process.env[key] = value
+ }
+ }
+ })
+
+ describe('non-admin denial', () => {
+ it('rejects unauthenticated callers', async () => {
+ vi.mocked(getCurrentUser).mockResolvedValue(null)
+
+ await expect(createInvitationAction({})).resolves.toMatchObject({
+ success: false,
+ error: 'Not authenticated.'
+ })
+ await expect(revokeInvitationAction('inv-1')).resolves.toMatchObject({
+ success: false
+ })
+ await expect(
+ resetMemberPasswordAction({ userId: 'u', newPassword: 'password123' })
+ ).resolves.toMatchObject({ success: false })
+ })
+
+ it('rejects authenticated non-admins', async () => {
+ vi.mocked(getCurrentUser).mockResolvedValue(memberUser)
+
+ await expect(createInvitationAction({})).resolves.toMatchObject({
+ success: false,
+ error: 'Admin access required.'
+ })
+ await expect(revokeInvitationAction('inv-1')).resolves.toMatchObject({
+ success: false,
+ error: 'Admin access required.'
+ })
+ await expect(
+ resetMemberPasswordAction({ userId: 'u', newPassword: 'password123' })
+ ).resolves.toMatchObject({
+ success: false,
+ error: 'Admin access required.'
+ })
+ expect(createInvitation).not.toHaveBeenCalled()
+ expect(mockSetUserPassword).not.toHaveBeenCalled()
+ })
+ })
+
+ describe('createInvitationAction', () => {
+ it('creates an invitation and returns a redeemable link', async () => {
+ vi.mocked(getCurrentUser).mockResolvedValue(adminUser)
+ vi.mocked(createInvitation).mockResolvedValue({
+ invitation: invitationRecord,
+ token: 'tok123'
+ })
+
+ const result = await createInvitationAction({
+ })
+
+ expect(result.success).toBe(true)
+ expect(result.link).toBe(
+ 'http://localhost:3000/auth/sign-up?token=tok123'
+ )
+ expect(result.invitation).toMatchObject({ id: 'inv-1', revoked: false })
+ })
+
+ it('rejects invitations without a valid email address', async () => {
+ vi.mocked(getCurrentUser).mockResolvedValue(adminUser)
+
+ await expect(createInvitationAction({})).resolves.toMatchObject({
+ success: false,
+ error: 'A valid email address is required.'
+ })
+ await expect(
+ createInvitationAction({ email: 'not-an-email' })
+ ).resolves.toMatchObject({
+ success: false,
+ error: 'A valid email address is required.'
+ })
+ expect(createInvitation).not.toHaveBeenCalled()
+ })
+
+ it('emails the invitation when SMTP is configured', async () => {
+ process.env.SMTP_HOST = 'smtp.example.com'
+ process.env.SMTP_USER = 'user'
+ process.env.SMTP_PASSWORD = 'secret'
+ process.env.BETTER_AUTH_URL = 'http://localhost:3000'
+ const sendMail = vi.fn(async () => {})
+ const nodemailer = await import('nodemailer')
+ vi.mocked(nodemailer.default.createTransport).mockReturnValue({
+ sendMail
+ } as never)
+
+ vi.mocked(getCurrentUser).mockResolvedValue(adminUser)
+ vi.mocked(createInvitation).mockResolvedValue({
+ invitation: invitationRecord,
+ token: 'tok123'
+ })
+
+ const result = await createInvitationAction({
+ })
+
+ expect(result.success).toBe(true)
+ expect(sendMail).toHaveBeenCalled()
+ // The emailed link must use the canonical origin, never request
+ // headers: a spoofed Host could ship the live token to an attacker.
+ expect(JSON.stringify(sendMail.mock.calls)).toContain(
+ 'http://localhost:3000/auth/sign-up?token=tok123'
+ )
+ })
+
+ it('withholds the invitation email without a canonical origin', async () => {
+ // SMTP configured but BETTER_AUTH_URL unset: the link is still
+ // returned to the admin, but nothing is emailed.
+ process.env.SMTP_HOST = 'smtp.example.com'
+ process.env.SMTP_USER = 'user'
+ process.env.SMTP_PASSWORD = 'secret'
+ const sendMail = vi.fn(async () => {})
+ const nodemailer = await import('nodemailer')
+ vi.mocked(nodemailer.default.createTransport).mockReturnValue({
+ sendMail
+ } as never)
+
+ vi.mocked(getCurrentUser).mockResolvedValue(adminUser)
+ vi.mocked(createInvitation).mockResolvedValue({
+ invitation: invitationRecord,
+ token: 'tok123'
+ })
+
+ const result = await createInvitationAction({
+ })
+
+ expect(result.success).toBe(true)
+ expect(result.link).toContain('auth/sign-up?token=tok123')
+ expect(sendMail).not.toHaveBeenCalled()
+ })
+ })
+
+ describe('revokeInvitationAction', () => {
+ it('revokes an invitation', async () => {
+ vi.mocked(getCurrentUser).mockResolvedValue(adminUser)
+ vi.mocked(revokeInvitation).mockResolvedValue(true)
+
+ await expect(revokeInvitationAction('inv-1')).resolves.toEqual({
+ success: true
+ })
+ })
+ })
+
+ describe('resetMemberPasswordAction', () => {
+ it('sets a member password for admins', async () => {
+ vi.mocked(getCurrentUser).mockResolvedValue(adminUser)
+
+ const result = await resetMemberPasswordAction({
+ userId: 'user-1',
+ newPassword: 'brand-new-password'
+ })
+
+ expect(result).toEqual({ success: true })
+ expect(mockSetUserPassword).toHaveBeenCalledWith(
+ expect.objectContaining({
+ body: {
+ userId: 'user-1',
+ newPassword: 'brand-new-password'
+ }
+ })
+ )
+ })
+
+ it('rejects short passwords', async () => {
+ vi.mocked(getCurrentUser).mockResolvedValue(adminUser)
+
+ await expect(
+ resetMemberPasswordAction({ userId: 'user-1', newPassword: 'short' })
+ ).resolves.toMatchObject({ success: false })
+ expect(mockSetUserPassword).not.toHaveBeenCalled()
+ })
+ })
+
+ describe('promoteMemberAction', () => {
+ it('promotes a member to admin for admins', async () => {
+ vi.mocked(getCurrentUser).mockResolvedValue(adminUser)
+
+ const result = await promoteMemberAction({ userId: 'user-1' })
+
+ expect(result).toEqual({ success: true })
+ expect(mockSetRole).toHaveBeenCalledWith(
+ expect.objectContaining({
+ body: { userId: 'user-1', role: 'admin' }
+ })
+ )
+ })
+
+ it('rejects non-admin callers', async () => {
+ vi.mocked(getCurrentUser).mockResolvedValue(memberUser)
+
+ await expect(
+ promoteMemberAction({ userId: 'user-2' })
+ ).resolves.toMatchObject({
+ success: false,
+ error: 'Admin access required.'
+ })
+ expect(mockSetRole).not.toHaveBeenCalled()
+ })
+
+ it('surfaces provider failures as error results', async () => {
+ vi.mocked(getCurrentUser).mockResolvedValue(adminUser)
+ mockSetRole.mockRejectedValueOnce(new Error('cannot promote self'))
+
+ await expect(
+ promoteMemberAction({ userId: 'user-1' })
+ ).resolves.toMatchObject({ success: false, error: 'cannot promote self' })
+ })
+ })
+})
diff --git a/lib/actions/__tests__/chat.test.ts b/lib/actions/__tests__/chat.test.ts
index 6893d345..84c0566a 100644
--- a/lib/actions/__tests__/chat.test.ts
+++ b/lib/actions/__tests__/chat.test.ts
@@ -1,9 +1,10 @@
import { revalidateTag } from 'next/cache'
-import { beforeEach, describe, expect, it, vi } from 'vitest'
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { generateChatTitle } from '@/lib/agents/title-generator'
import { getCurrentUserId } from '@/lib/auth/get-current-user'
+import { getAuthProvider } from '@/lib/auth/provider'
import * as dbActions from '@/lib/db/actions'
import type { Chat, Message } from '@/lib/db/schema'
import {
@@ -32,6 +33,15 @@ import {
vi.mock('@/lib/auth/get-current-user')
vi.mock('@/lib/db/actions')
vi.mock('@/lib/agents/title-generator')
+vi.mock('@/lib/auth/provider', async importOriginal => ({
+ ...(await importOriginal<typeof import('@/lib/auth/provider')>()),
+ // Default: a supabase-shaped provider that supports sharing;
+ // individual tests override for other providers.
+ getAuthProvider: vi.fn(() => ({
+ name: 'supabase',
+ capabilities: { share: true }
+ }))
+}))
vi.mock('@/lib/storage/r2-client', () => ({
getUserFileObjectKeyPrefix: vi.fn((userId: string) => `${userId}/`),
signFilePartUrlsInMessages: vi.fn(async messages => messages)
@@ -505,6 +515,24 @@ describe('Chat Actions', () => {
})
describe('shareChat', () => {
+ const originalShareFlag = process.env.NEXT_PUBLIC_ENABLE_SHARE
+
+ beforeEach(() => {
+ // Default: supabase, which shares without any flag (as on main).
+ vi.mocked(getAuthProvider).mockReturnValue({
+ name: 'supabase',
+ capabilities: { share: true }
+ } as never)
+ })
+
+ afterEach(() => {
+ if (originalShareFlag === undefined) {
+ delete process.env.NEXT_PUBLIC_ENABLE_SHARE
+ } else {
+ process.env.NEXT_PUBLIC_ENABLE_SHARE = originalShareFlag
+ }
+ })
+
it('should update chat visibility to public', async () => {
const chatId = 'chat-123'
const userId = 'user-123'
@@ -538,6 +566,75 @@ describe('Chat Actions', () => {
expect(result).toBeNull()
expect(dbActions.updateChatVisibility).not.toHaveBeenCalled()
})
+
+ it('shares on supabase without any opt-in flag', async () => {
+ // The default Supabase path must behave as on main: no env var
+ // required.
+ delete process.env.NEXT_PUBLIC_ENABLE_SHARE
+ delete process.env.ENABLE_SHARE
+ vi.mocked(getCurrentUserId).mockResolvedValue('user-123')
+ vi.mocked(dbActions.updateChatVisibility).mockResolvedValue({
+ id: 'chat-123',
+ userId: 'user-123',
+ visibility: 'public'
+ } as Chat)
+
+ const result = await shareChat('chat-123')
+
+ expect(result).not.toBeNull()
+ expect(dbActions.updateChatVisibility).toHaveBeenCalled()
+ })
+
+ it('requires the opt-in flag for better-auth', async () => {
+ delete process.env.NEXT_PUBLIC_ENABLE_SHARE
+ delete process.env.ENABLE_SHARE
+ vi.mocked(getAuthProvider).mockReturnValue({
+ name: 'better-auth',
+ capabilities: { share: true }
+ } as never)
+ vi.mocked(getCurrentUserId).mockResolvedValue('user-123')
+
+ const result = await shareChat('chat-123')
+
+ expect(result).toBeNull()
+ expect(dbActions.updateChatVisibility).not.toHaveBeenCalled()
+ })
+
+ it('allows better-auth sharing once the opt-in flag is set', async () => {
+ process.env.NEXT_PUBLIC_ENABLE_SHARE = 'true'
+ vi.mocked(getAuthProvider).mockReturnValue({
+ name: 'better-auth',
+ capabilities: { share: true }
+ } as never)
+ vi.mocked(getCurrentUserId).mockResolvedValue('user-123')
+ vi.mocked(dbActions.updateChatVisibility).mockResolvedValue({
+ id: 'chat-123',
+ userId: 'user-123',
+ visibility: 'public'
+ } as Chat)
+
+ const result = await shareChat('chat-123')
+
+ expect(result).not.toBeNull()
+ expect(dbActions.updateChatVisibility).toHaveBeenCalled()
+ })
+
+ it('should return null when the active provider has no sharing capability', async () => {
+ // Anonymous mode: every chat belongs to one shared identity, so
+ // the action must not publish even with ENABLE_SHARE set while
+ // the provider (and the UI) has sharing disabled.
+ process.env.NEXT_PUBLIC_ENABLE_SHARE = 'true'
+ vi.mocked(getAuthProvider).mockReturnValue({
+ name: 'none',
+ capabilities: { share: false }
+ } as never)
+ vi.mocked(getCurrentUserId).mockResolvedValue('user-123')
+
+ const result = await shareChat('chat-123')
+
+ expect(result).toBeNull()
+ expect(dbActions.updateChatVisibility).not.toHaveBeenCalled()
+ })
})
describe('deleteMessagesFromIndex', () => {
diff --git a/lib/actions/account.ts b/lib/actions/account.ts
index 93ed6a1b..c66b537a 100644
--- a/lib/actions/account.ts
+++ b/lib/actions/account.ts
@@ -5,6 +5,7 @@ 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 { db } from '@/lib/db'
import * as dbActions from '@/lib/db/actions'
import { deleteUserObjects } from '@/lib/storage/r2-client'
@@ -16,6 +17,24 @@ function getErrorMessage(error: unknown) {
return 'Failed to delete account'
}
+// Serializes account deletion within this process. The better-auth flow
+// holds a pooled connection for its guard transaction while the cleanup
+// steps check out their own connections; unbounded concurrent deletions
+// could occupy the whole pool (each outer transaction waiting on inner
+// cleanup connections that can no longer be checked out). Deletions are
+// rare, so an in-process chain bounds the held connections to one per
+// process.
+let deletionChain: Promise<unknown> = Promise.resolve()
+
+function withDeletionLock<T>(task: () => Promise<T>): Promise<T> {
+ const result = deletionChain.then(task, task)
+ deletionChain = result.then(
+ () => undefined,
+ () => undefined
+ )
+ return result
+}
+
export async function deleteAccount(): Promise<{
success: boolean
error?: string
@@ -42,48 +61,134 @@ export async function deleteAccount(): Promise<{
}
try {
- const deleteChatsResult = await dbActions.deleteUserChats(user.id)
- if (!deleteChatsResult.success) {
- return {
- success: false,
- error: deleteChatsResult.error ?? 'Failed to delete account data'
- }
+ // Per-account refusal (e.g. the last admin) before any destructive
+ // step. A throw here must surface as an error result, not reject
+ // the action.
+ const deleteCheck = await provider.canDeleteUser?.(user.id)
+ if (deleteCheck) {
+ return { success: false, error: deleteCheck }
}
- const deleteNotesResult = await dbActions.deleteUserNotes(user.id)
- if (!deleteNotesResult.success) {
- return {
- success: false,
- error: deleteNotesResult.error ?? 'Failed to delete account data'
- }
+ const cleanupFailed = (step: string, error: string) => {
+ console.error(
+ `Account deletion cleanup failed (${step}) for user ${user.id}: ${error}`
+ )
+ return { success: false as const, error }
}
- const deleteFilesResult = await dbActions.deleteUserLibraryFiles(user.id)
- if (!deleteFilesResult.success) {
- return {
- success: false,
- error: deleteFilesResult.error ?? 'Failed to delete account data'
+ const cleanup = async (): Promise<
+ { success: true } | { success: false; error: string }
+ > => {
+ const deleteChatsResult = await dbActions.deleteUserChats(user.id)
+ if (!deleteChatsResult.success) {
+ return cleanupFailed(
+ 'chats',
+ deleteChatsResult.error ?? 'Failed to delete account data'
+ )
+ }
+
+ const deleteNotesResult = await dbActions.deleteUserNotes(user.id)
+ if (!deleteNotesResult.success) {
+ return cleanupFailed(
+ 'notes',
+ deleteNotesResult.error ?? 'Failed to delete account data'
+ )
}
- }
- const anonymizeFeedbackResult = await dbActions.anonymizeUserFeedback(
- user.id
- )
- if (!anonymizeFeedbackResult.success) {
- return {
- success: false,
- error:
+ const deleteFilesResult = await dbActions.deleteUserLibraryFiles(user.id)
+ if (!deleteFilesResult.success) {
+ return cleanupFailed(
+ 'files',
+ deleteFilesResult.error ?? 'Failed to delete account data'
+ )
+ }
+
+ const anonymizeFeedbackResult = await dbActions.anonymizeUserFeedback(
+ user.id
+ )
+ if (!anonymizeFeedbackResult.success) {
+ return cleanupFailed(
+ 'feedback',
anonymizeFeedbackResult.error ?? 'Failed to anonymize user feedback'
+ )
}
+
+ await deleteUserObjects(user.id)
+ return { success: true as const }
}
- await deleteUserObjects(user.id)
+ let wasAdmin = false
+ let result: { success: true } | { success: false; error: string }
+
+ if (provider.validateDeletion) {
+ // better-auth: guard, identity deletion, and cleanup share one
+ // transaction. The guard's FOR UPDATE locks are held until the
+ // commit, so a concurrent deletion cannot flip the answer. The
+ // identity delete runs before the cleanup inside that transaction:
+ // a failed delete rolls back with nothing destroyed, and a cleanup
+ // failure rolls the identity back too, leaving the user able to
+ // retry. The cleanup steps run on their own connections (RLS
+ // transactions), so a rollback cannot undo partial cleanup —
+ // retrying the action completes it. The transaction holds a pooled
+ // connection while cleanup checks out another, so deletions are
+ // serialized in-process (withDeletionLock) to keep the pool from
+ // being exhausted by outer transactions waiting on inner ones.
+ result = await withDeletionLock(() =>
+ db.transaction(async tx => {
+ const guard = await provider.validateDeletion!(user.id, tx)
+ if (guard.error) {
+ return { success: false as const, error: guard.error }
+ }
+ wasAdmin = guard.wasAdmin
+
+ const deleteAuthResult = await provider.deleteUser!(user.id, tx)
+ if (!deleteAuthResult.success) {
+ throw new Error(deleteAuthResult.error ?? 'Failed to delete user')
+ }
- const deleteAuthResult = await provider.deleteUser!(user.id)
- if (!deleteAuthResult.success) {
- throw new Error(deleteAuthResult.error ?? 'Failed to delete user')
+ const cleanupResult = await cleanup()
+ if (!cleanupResult.success) {
+ // Throwing (rather than returning the error) is what makes
+ // the transaction roll back: returning would commit the
+ // identity deletion that ran above, destroying the account
+ // while reporting failure.
+ throw new Error(cleanupResult.error)
+ }
+ return { success: true as const }
+ })
+ )
+ } else {
+ // supabase: the identity deletion is an admin-API call that cannot
+ // join a transaction, so it runs last: a cleanup failure leaves the
+ // account in place and the user can retry (each step is
+ // idempotent). A failed identity deletion after committed cleanup
+ // is the accepted mirror of that trade-off — the account and its
+ // sessions survive, so retrying the deletion completes it.
+ const cleanupResult = await cleanup()
+ if (!cleanupResult.success) {
+ result = cleanupResult
+ } else {
+ const deleteAuthResult = await provider.deleteUser!(user.id)
+ if (deleteAuthResult.success) {
+ result = { success: true as const }
+ } else {
+ const error = deleteAuthResult.error ?? 'Failed to delete user'
+ console.error(
+ `Account deletion identity step failed for user ${user.id}: ${error}`
+ )
+ result = { success: false as const, error }
+ }
+ }
+ }
+
+ if (!result.success) {
+ return { success: false, error: result.error }
}
+ // Runs after the deletion committed: completes any role election the
+ // provider deferred because of concurrent sign-ups.
+ await provider.postDeletion?.(wasAdmin)
+
revalidateTag('chat', 'max')
await trackAccountDeleted(user.id)
diff --git a/lib/actions/admin-views.ts b/lib/actions/admin-views.ts
new file mode 100644
index 00000000..f370ad81
--- /dev/null
+++ b/lib/actions/admin-views.ts
@@ -0,0 +1,34 @@
+export interface InvitationView {
+ id: string
+ email: string | null
+ revoked: boolean
+ used: boolean
+ expired: boolean
+ expiresAt: string
+ createdAt: string
+}
+
+/**
+ * Project an invitation row onto the shape the admin UI renders. Lives
+ * outside the `'use server'` action module so server components can call
+ * it during render; the expiration is computed here (not in the client
+ * component) because render functions must stay pure.
+ */
+export function invitationView(invitation: {
+ id: string
+ email: string | null
+ revokedAt: Date | null
+ usedAt: Date | null
+ expiresAt: Date
+ createdAt: Date
+}): InvitationView {
+ return {
+ id: invitation.id,
+ email: invitation.email,
+ revoked: Boolean(invitation.revokedAt),
+ used: Boolean(invitation.usedAt),
+ expired: invitation.expiresAt.getTime() <= Date.now(),
+ expiresAt: invitation.expiresAt.toISOString(),
+ createdAt: invitation.createdAt.toISOString()
+ }
+}
diff --git a/lib/actions/admin.ts b/lib/actions/admin.ts
new file mode 100644
index 00000000..b3447776
--- /dev/null
+++ b/lib/actions/admin.ts
@@ -0,0 +1,204 @@
+'use server'
+
+import { headers } from 'next/headers'
+
+import { type InvitationView, invitationView } from '@/lib/actions/admin-views'
+import { getAuth, getEmailLinkOrigin } from '@/lib/auth/better-auth/config'
+import {
+ createInvitation,
+ revokeInvitation
+} from '@/lib/auth/better-auth/invitations'
+import { sendSmtpMail } from '@/lib/auth/better-auth/mailer'
+import { getCurrentUser } from '@/lib/auth/get-current-user'
+import { getRequestOrigin } from '@/lib/auth/request'
+import type { AppUser } from '@/lib/auth/types'
+
+export type { InvitationView } from '@/lib/actions/admin-views'
+
+export interface AdminActionResult {
+ success: boolean
+ error?: string
+}
+
+/** Pragmatic format check; better-auth enforces deliverable emails at sign-up. */
+const EMAIL_REGEX = /^[^\s@]+@[^\s@]+\.[^\s@]+$/
+
+function escapeHtml(value: string): string {
+ return value
+ .replace(/&/g, '&amp;')
+ .replace(/</g, '&lt;')
+ .replace(/>/g, '&gt;')
+ .replace(/"/g, '&quot;')
+}
+
+async function requireAdmin(): Promise<AppUser | AdminActionResult> {
+ const user = await getCurrentUser()
+ if (!user) {
+ return { success: false, error: 'Not authenticated.' }
+ }
+ if (user.role !== 'admin') {
+ return { success: false, error: 'Admin access required.' }
+ }
+ return user
+}
+
+function isAdmin(
+ result: AppUser | AdminActionResult
+): result is AdminActionResult {
+ return typeof (result as AdminActionResult).success === 'boolean'
+}
+
+async function sendInvitationEmail(params: {
+ to: string
+ inviteLink: string
+ invitedByName: string
+}): Promise<void> {
+ await sendSmtpMail({
+ to: params.to,
+ subject: 'You are invited to Morphic',
+ text: `${params.invitedByName} invited you to Morphic. Accept the invitation: ${params.inviteLink}`,
+ html: `<p>${escapeHtml(params.invitedByName)} invited you to Morphic.</p><p><a href="${escapeHtml(params.inviteLink)}">Accept the invitation</a></p>`
+ })
+}
+
+export async function createInvitationAction(params: {
+ email?: string
+}): Promise<
+ AdminActionResult & { invitation?: InvitationView; link?: string }
+> {
+ const adminUser = await requireAdmin()
+ if (isAdmin(adminUser)) {
+ return adminUser
+ }
+
+ // Invitations are always addressed to a specific person: an unaddressed
+ // link would just be open sign-up behind an obscure URL, and open sign-up
+ // is already an explicit choice via AUTH_SIGNUP_MODE=open.
+ const email = params.email?.trim()
+ if (!email || !EMAIL_REGEX.test(email)) {
+ return { success: false, error: 'A valid email address is required.' }
+ }
+
+ try {
+ // The plaintext token is only available here, at creation time: the
+ // database stores just its hash, so the link cannot be rebuilt later.
+ const { invitation, token } = await createInvitation({
+ invitedBy: adminUser.id,
+ email
+ })
+
+ const canonical = getEmailLinkOrigin()
+ const link = `${canonical || (await getRequestOrigin())}/auth/sign-up?token=${token}`
+
+ // Additionally email the invitation when SMTP is configured. The
+ // emailed link uses only the canonical BETTER_AUTH_URL origin: a link
+ // built from request headers could ship the live token to an attacker
+ // domain via a spoofed Host. Without a canonical origin the admin
+ // copies the link manually instead.
+ if (
+ canonical &&
+ process.env.SMTP_HOST &&
+ process.env.SMTP_USER &&
+ process.env.SMTP_PASSWORD
+ ) {
+ try {
+ await sendInvitationEmail({
+ to: email,
+ inviteLink: `${canonical}/auth/sign-up?token=${token}`,
+ invitedByName: adminUser.name || adminUser.email || 'An admin'
+ })
+ } catch (error) {
+ console.error('Failed to send invitation email:', error)
+ }
+ }
+
+ return { success: true, invitation: invitationView(invitation), link }
+ } catch (error) {
+ return {
+ success: false,
+ error:
+ error instanceof Error ? error.message : 'Failed to create invitation'
+ }
+ }
+}
+
+export async function revokeInvitationAction(
+ id: string
+): Promise<AdminActionResult> {
+ const adminUser = await requireAdmin()
+ if (isAdmin(adminUser)) {
+ return adminUser
+ }
+
+ try {
+ const revoked = await revokeInvitation(id)
+ return revoked
+ ? { success: true }
+ : { success: false, error: 'Invitation not found or already revoked.' }
+ } catch (error) {
+ return {
+ success: false,
+ error:
+ error instanceof Error ? error.message : 'Failed to revoke invitation'
+ }
+ }
+}
+
+export async function resetMemberPasswordAction(params: {
+ userId: string
+ newPassword: string
+}): Promise<AdminActionResult> {
+ const adminUser = await requireAdmin()
+ if (isAdmin(adminUser)) {
+ return adminUser
+ }
+
+ if (!params.newPassword || params.newPassword.length < 8) {
+ return { success: false, error: 'Password must be at least 8 characters.' }
+ }
+
+ try {
+ // Note: better-auth's setUserPassword re-hashes the credential but
+ // leaves the member's existing sessions valid; a reset done because of
+ // a suspected compromise does not log the member out until those
+ // sessions expire naturally.
+ await getAuth().api.setUserPassword({
+ body: {
+ userId: params.userId,
+ newPassword: params.newPassword
+ },
+ headers: await headers()
+ })
+ return { success: true }
+ } catch (error) {
+ return {
+ success: false,
+ error: error instanceof Error ? error.message : 'Failed to reset password'
+ }
+ }
+}
+
+export async function promoteMemberAction(params: {
+ userId: string
+}): Promise<AdminActionResult> {
+ const adminUser = await requireAdmin()
+ if (isAdmin(adminUser)) {
+ return adminUser
+ }
+
+ try {
+ // Promotion only ever adds an admin, so it cannot strand the instance
+ // without one; demotion is deliberately not offered because the
+ // last-admin deletion guard has no equivalent for role changes.
+ await getAuth().api.setRole({
+ body: { userId: params.userId, role: 'admin' },
+ headers: await headers()
+ })
+ return { success: true }
+ } catch (error) {
+ return {
+ success: false,
+ error: error instanceof Error ? error.message : 'Failed to promote member'
+ }
+ }
+}
diff --git a/lib/actions/auth.ts b/lib/actions/auth.ts
index e0110af2..1c1c5974 100644
--- a/lib/actions/auth.ts
+++ b/lib/actions/auth.ts
@@ -29,6 +29,7 @@ export async function signInWithGoogle(): Promise<AuthActionResult> {
export async function signUp(credentials: {
email: string
password: string
+ token?: string
}): Promise<AuthActionResult> {
const provider = getAuthProvider()
if (!provider.signUp) {
@@ -56,11 +57,12 @@ export async function requestPasswordReset(
}
export async function updatePassword(
- password: string
+ password: string,
+ token?: string
): Promise<AuthActionResult> {
const provider = getAuthProvider()
if (!provider.updatePassword) {
return unavailable()
}
- return provider.updatePassword(password)
+ return provider.updatePassword(password, token)
}
diff --git a/lib/actions/chat.ts b/lib/actions/chat.ts
index 12af028f..82f1e18c 100644
--- a/lib/actions/chat.ts
+++ b/lib/actions/chat.ts
@@ -4,6 +4,7 @@ import { revalidateTag, unstable_cache } from 'next/cache'
import { generateChatTitle } from '@/lib/agents/title-generator'
import { getCurrentUserId } from '@/lib/auth/get-current-user'
+import { getAuthProvider, isShareEnabled } from '@/lib/auth/provider'
import * as dbActions from '@/lib/db/actions'
import type { Chat, Message } from '@/lib/db/schema'
import { generateId } from '@/lib/db/schema'
@@ -297,6 +298,21 @@ export async function deleteMessagesAfter(chatId: string, messageId: string) {
* Share a chat (make it public)
*/
export async function shareChat(chatId: string) {
+ // The active provider must support sharing: anonymous mode maps every
+ // chat to one shared identity and has no share capability, so the
+ // action must not publish chats the UI refuses to share.
+ const provider = getAuthProvider()
+ if (!provider.capabilities.share) {
+ return null
+ }
+ // Better Auth additionally requires the ENABLE_SHARE opt-in; Supabase
+ // sharing has never needed a flag, so the default path behaves as on
+ // main. Enforced here, not just in the UI, so the action cannot be
+ // called directly while sharing is disabled.
+ if (provider.name === 'better-auth' && !isShareEnabled()) {
+ return null
+ }
+
const userId = await getCurrentUserId()
if (!userId) {
return null
diff --git a/lib/actions/site-feedback.ts b/lib/actions/site-feedback.ts
index 7e29a5ee..bab4e64b 100644
--- a/lib/actions/site-feedback.ts
+++ b/lib/actions/site-feedback.ts
@@ -1,10 +1,9 @@
'use server'
+import { getCurrentUser } from '@/lib/auth/get-current-user'
import { db } from '@/lib/db'
import { feedback, generateId } from '@/lib/db/schema'
import { withOptionalRLS } from '@/lib/db/with-rls'
-import { hasSupabasePublicConfig } from '@/lib/supabase/keys'
-import { createClient } from '@/lib/supabase/server'
export async function submitFeedback(data: {
sentiment: 'positive' | 'neutral' | 'negative'
@@ -12,18 +11,10 @@ export async function submitFeedback(data: {
pageUrl: string
}) {
try {
- // Get current user if logged in
- let userId: string | undefined
- let userEmail: string | undefined
-
- if (hasSupabasePublicConfig()) {
- const supabase = await createClient()
- const {
- data: { user }
- } = await supabase.auth.getUser()
- userId = user?.id
- userEmail = user?.email
- }
+ // Get current user if logged in (provider-agnostic seam)
+ const user = await getCurrentUser()
+ const userId = user?.id
+ const userEmail = user?.email ?? undefined
// Get user agent from headers
const { headers } = await import('next/headers')
diff --git a/lib/analytics/__tests__/sanitize.test.ts b/lib/analytics/__tests__/sanitize.test.ts
new file mode 100644
index 00000000..4efa6aa1
--- /dev/null
+++ b/lib/analytics/__tests__/sanitize.test.ts
@@ -0,0 +1,63 @@
+import type { CaptureResult } from 'posthog-js'
+import { describe, expect, it } from 'vitest'
+
+import { scrubTokenFromEvent } from '../sanitize'
+
+function pageview(currentUrl: unknown): CaptureResult {
+ return {
+ event_name: '$pageview',
+ properties: { $current_url: currentUrl }
+ } as unknown as CaptureResult
+}
+
+describe('scrubTokenFromEvent', () => {
+ it('strips the token query parameter from the pageview url', () => {
+ const result = scrubTokenFromEvent(
+ pageview('http://localhost:3000/auth/update-password?token=abc123')
+ )
+
+ expect(result?.properties?.$current_url).toBe(
+ 'http://localhost:3000/auth/update-password'
+ )
+ })
+
+ it('keeps other query parameters', () => {
+ const result = scrubTokenFromEvent(
+ pageview('http://localhost:3000/auth/sign-up?token=abc&x=1')
+ )
+
+ const url = result?.properties?.$current_url as string
+ expect(url).toContain('x=1')
+ expect(url).not.toContain('token=abc')
+ })
+
+ it('strips the token from the referrer on later events', () => {
+ // Arriving from an auth link leaves the credential in $referrer even
+ // though $current_url is clean.
+ const result = scrubTokenFromEvent({
+ event_name: '$pageview',
+ properties: {
+ $current_url: 'http://localhost:3000/',
+ $referrer: 'http://localhost:3000/auth/update-password?token=abc123'
+ }
+ } as unknown as CaptureResult)
+
+ expect(result?.properties?.$current_url).toBe('http://localhost:3000/')
+ expect(result?.properties?.$referrer).toBe(
+ 'http://localhost:3000/auth/update-password'
+ )
+ })
+
+ it('leaves events without a token untouched', () => {
+ const event = pageview('http://localhost:3000/search?q=hello')
+
+ expect(scrubTokenFromEvent(event)).toBe(event)
+ })
+
+ it('leaves null events and non-string urls untouched', () => {
+ expect(scrubTokenFromEvent(null)).toBeNull()
+
+ const event = pageview(42)
+ expect(scrubTokenFromEvent(event)).toBe(event)
+ })
+})
diff --git a/lib/analytics/posthog-client.ts b/lib/analytics/posthog-client.ts
index 5c5ebd8d..16c6f0ee 100644
--- a/lib/analytics/posthog-client.ts
+++ b/lib/analytics/posthog-client.ts
@@ -2,6 +2,8 @@
import posthog from 'posthog-js'
+import { scrubTokenFromEvent } from '@/lib/analytics/sanitize'
+
let initialized = false
function clientKey(): string | undefined {
@@ -25,7 +27,11 @@ export function initPostHog(): void {
autocapture: false,
capture_pageview: false,
disable_session_recording: true,
- session_recording: { maskAllInputs: true }
+ session_recording: { maskAllInputs: true },
+ // Auth links (invitations, password resets, bootstrap) carry one-time
+ // credentials in ?token= and posthog-js attaches the page URL to every
+ // event; strip the parameter before anything leaves the browser.
+ before_send: scrubTokenFromEvent
})
initialized = true
}
diff --git a/lib/analytics/sanitize.ts b/lib/analytics/sanitize.ts
new file mode 100644
index 00000000..bf1115a4
--- /dev/null
+++ b/lib/analytics/sanitize.ts
@@ -0,0 +1,48 @@
+import type { CaptureResult } from 'posthog-js'
+
+/**
+ * Event properties that carry a full page URL. Auth links (invitations,
+ * password resets, bootstrap) carry one-time credentials in the `?token=`
+ * query parameter, so the parameter is stripped from every event before
+ * it leaves the browser. The `Referer` transport header is handled
+ * separately via the `Referrer-Policy: no-referrer` header scoped to the
+ * `/auth/*` pages, the only pages that carry token-bearing URLs.
+ */
+const URL_PROPERTIES = ['$current_url', '$referrer'] as const
+
+function stripToken(url: string): string | null {
+ if (!url.includes('token=')) {
+ return null
+ }
+ try {
+ const parsed = new URL(url)
+ if (!parsed.searchParams.has('token')) {
+ return null
+ }
+ parsed.searchParams.delete('token')
+ return parsed.toString()
+ } catch {
+ return null
+ }
+}
+
+export function scrubTokenFromEvent(
+ event: CaptureResult | null
+): CaptureResult | null {
+ if (!event) {
+ return null
+ }
+ const properties: Record<string, unknown> = { ...event.properties }
+ let changed = false
+ for (const key of URL_PROPERTIES) {
+ const value = properties[key]
+ if (typeof value === 'string') {
+ const stripped = stripToken(value)
+ if (stripped !== null) {
+ properties[key] = stripped
+ changed = true
+ }
+ }
+ }
+ return changed ? { ...event, properties } : event
+}
diff --git a/lib/auth/__tests__/better-auth-provider.test.ts b/lib/auth/__tests__/better-auth-provider.test.ts
new file mode 100644
index 00000000..8c80bbd0
--- /dev/null
+++ b/lib/auth/__tests__/better-auth-provider.test.ts
@@ -0,0 +1,1116 @@
+import type { NextRequest } from 'next/server'
+
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+
+import { getAuth, reElectBootstrapAdmin } from '@/lib/auth/better-auth/config'
+import {
+ consumeInvitation,
+ createInvitation,
+ hasRecentBootstrapInvitation,
+ releaseInvitation,
+ revokeInvitation,
+ validateInvitation
+} from '@/lib/auth/better-auth/invitations'
+import { sendSmtpMail } from '@/lib/auth/better-auth/mailer'
+import { betterAuthProvider } from '@/lib/auth/providers/better-auth'
+import { resetRateLimits } from '@/lib/auth/rate-limit'
+
+const { mockAuth, mockSetCookie } = vi.hoisted(() => ({
+ mockAuth: {
+ api: {
+ getSession: vi.fn(),
+ signInEmail: vi.fn(),
+ signUpEmail: vi.fn(),
+ signOut: vi.fn(),
+ requestPasswordReset: vi.fn(),
+ resetPassword: vi.fn()
+ }
+ },
+ mockSetCookie: vi.fn()
+}))
+
+vi.mock('@/lib/auth/better-auth/config', async importOriginal => {
+ const actual =
+ await importOriginal<typeof import('@/lib/auth/better-auth/config')>()
+ return {
+ ...actual,
+ getAuth: () => mockAuth,
+ reElectBootstrapAdmin: vi.fn()
+ }
+})
+
+vi.mock('@/lib/auth/better-auth/invitations', () => ({
+ validateInvitation: vi.fn(),
+ consumeInvitation: vi.fn(),
+ createInvitation: vi.fn(),
+ hasRecentBootstrapInvitation: vi.fn(async () => false),
+ releaseInvitation: vi.fn(async () => {}),
+ revokeInvitation: vi.fn(async () => true)
+}))
+
+vi.mock('@/lib/auth/better-auth/mailer', async importOriginal => ({
+ ...(await importOriginal<typeof import('@/lib/auth/better-auth/mailer')>()),
+ sendSmtpMail: vi.fn()
+}))
+
+const { state } = vi.hoisted(() => ({
+ state: {
+ accounts: [] as unknown[],
+ adminCount: 1,
+ userCount: 2,
+ targetLocked: false
+ }
+}))
+
+vi.mock('@/lib/db', () => {
+ const db: Record<string, unknown> = {
+ delete: vi.fn(() => ({
+ where: vi.fn(async () => undefined)
+ })),
+ select: vi.fn(() => ({
+ // Awaitable (user-count and admin-count queries) and chainable
+ // (.where().limit() for the account-exists and role lookups,
+ // .where().for() for the locked admin listing) so all query
+ // shapes resolve.
+ from: vi.fn(() =>
+ Object.assign(Promise.resolve([{ total: 0, n: state.userCount }]), {
+ // Awaited directly it is the admin listing (one row per admin);
+ // chained it serves the role lookup (.limit) and the locked
+ // admin listing (.for) inside deletionGuard.
+ where: vi.fn(() =>
+ Object.assign(
+ Promise.resolve(
+ Array.from({ length: state.adminCount }, (_, i) => ({
+ id: `admin-${i}`,
+ n: state.adminCount
+ }))
+ ),
+ {
+ limit: vi.fn(() =>
+ Object.assign(Promise.resolve(state.accounts), {
+ // The role lookup goes through FOR UPDATE when the
+ // guard runs inside a transaction.
+ for: vi.fn(async () => {
+ state.targetLocked = true
+ return state.accounts
+ })
+ })
+ ),
+ for: vi.fn(async () =>
+ Array.from({ length: state.adminCount }, (_, i) => ({
+ id: `admin-${i}`
+ }))
+ )
+ }
+ )
+ )
+ })
+ )
+ }))
+ }
+ // Transactions receive the same mock object, so assertions on db.delete
+ // also cover deletes issued through tx.
+ db.transaction = vi.fn((cb: (tx: unknown) => unknown) => cb(db))
+ return { db }
+})
+
+vi.mock('next/headers', () => ({
+ headers: vi.fn(async () => new Headers({ origin: 'http://localhost:3000' })),
+ cookies: vi.fn(async () => ({ set: mockSetCookie }))
+}))
+
+function makeRequest(pathname: string): NextRequest {
+ const href = `http://localhost:3000${pathname}`
+ const url = new URL(href)
+ return {
+ nextUrl: {
+ href,
+ pathname: url.pathname,
+ search: url.search,
+ clone: () => new URL(href)
+ },
+ headers: new Headers()
+ } as unknown as NextRequest
+}
+
+const sessionUser = {
+ id: 'user-1',
+ email: '[email protected]',
+ name: 'Admin',
+ image: null,
+ createdAt: new Date('2026-01-01'),
+ role: 'admin'
+}
+
+describe('better-auth provider', () => {
+ const originalEnv: Record<string, string | undefined> = {}
+
+ beforeEach(() => {
+ resetRateLimits()
+ state.accounts = []
+ state.adminCount = 1
+ state.userCount = 2
+ state.targetLocked = false
+ for (const key of [
+ 'SMTP_HOST',
+ 'SMTP_USER',
+ 'SMTP_PASSWORD',
+ 'AUTH_SIGNUP_MODE',
+ 'BOOTSTRAP_ADMIN_EMAIL',
+ 'BETTER_AUTH_URL'
+ ]) {
+ originalEnv[key] = process.env[key]
+ delete process.env[key]
+ }
+ vi.clearAllMocks()
+ })
+
+ afterEach(() => {
+ for (const [key, value] of Object.entries(originalEnv)) {
+ if (value === undefined) {
+ delete process.env[key]
+ } else {
+ process.env[key] = value
+ }
+ }
+ })
+
+ describe('capabilities', () => {
+ it('gates passwordReset on SMTP configuration', () => {
+ expect(betterAuthProvider.capabilities.passwordReset).toBe(false)
+
+ process.env.SMTP_HOST = 'smtp.example.com'
+ process.env.SMTP_USER = 'user'
+ process.env.SMTP_PASSWORD = 'secret'
+
+ // Emailed links need a canonical origin, never request headers
+ expect(betterAuthProvider.capabilities.passwordReset).toBe(false)
+ process.env.BETTER_AUTH_URL = 'http://localhost:3000'
+
+ expect(betterAuthProvider.capabilities.passwordReset).toBe(true)
+ expect(betterAuthProvider.capabilities.signUp).toBe(true)
+ expect(betterAuthProvider.capabilities.deleteUser).toBe(true)
+ expect(betterAuthProvider.capabilities.share).toBe(true)
+ })
+ })
+
+ describe('getCurrentUser', () => {
+ it('resolves the session user', async () => {
+ vi.mocked(mockAuth.api.getSession).mockResolvedValue({
+ user: sessionUser
+ } as never)
+
+ const user = await betterAuthProvider.getCurrentUser()
+
+ expect(user).toMatchObject({
+ id: 'user-1',
+ email: '[email protected]',
+ name: 'Admin',
+ role: 'admin'
+ })
+ })
+
+ it('returns null without a session', async () => {
+ vi.mocked(mockAuth.api.getSession).mockResolvedValue(null)
+
+ await expect(betterAuthProvider.getCurrentUser()).resolves.toBeNull()
+ })
+ })
+
+ describe('handleSession', () => {
+ it('redirects unauthenticated requests to protected paths', async () => {
+ vi.mocked(mockAuth.api.getSession).mockResolvedValue({
+ response: null,
+ headers: new Headers()
+ } as never)
+
+ const response = await betterAuthProvider.handleSession!(
+ makeRequest('/some-protected-page')
+ )
+
+ expect(response.status).toBe(307)
+ expect(response.headers.get('location')).toBe(
+ 'http://localhost:3000/auth/login?next=%2Fsome-protected-page'
+ )
+ })
+
+ it('carries the query string through the login redirect', async () => {
+ vi.mocked(mockAuth.api.getSession).mockResolvedValue({
+ response: null,
+ headers: new Headers()
+ } as never)
+
+ const response = await betterAuthProvider.handleSession!(
+ makeRequest('/some-protected-page?q=hello%20world')
+ )
+
+ expect(response.status).toBe(307)
+ expect(response.headers.get('location')).toBe(
+ 'http://localhost:3000/auth/login?next=%2Fsome-protected-page%3Fq%3Dhello%2520world'
+ )
+ })
+
+ it('lets unauthenticated requests through on public paths', async () => {
+ vi.mocked(mockAuth.api.getSession).mockResolvedValue({
+ response: null,
+ headers: new Headers()
+ } as never)
+
+ const response = await betterAuthProvider.handleSession!(
+ makeRequest('/auth/login')
+ )
+
+ expect(response.status).toBe(200)
+ })
+
+ it('lets unauthenticated analytics through the posthog relay', async () => {
+ // Guest pageviews from the login and sign-up pages must reach PostHog
+ // instead of bouncing to /auth/login.
+ vi.mocked(mockAuth.api.getSession).mockResolvedValue({
+ response: null,
+ headers: new Headers()
+ } as never)
+
+ const response = await betterAuthProvider.handleSession!(
+ makeRequest('/relay/e/?ip=1')
+ )
+
+ expect(response.status).toBe(200)
+ })
+
+ it('lets logged-out users open shared chat links', async () => {
+ // /search/<id> is the share URL: app/search/[id]/page.tsx enforces
+ // visibility (public chats viewable, private rejected), so the proxy
+ // must not pre-empt that check with a login redirect.
+ vi.mocked(mockAuth.api.getSession).mockResolvedValue({
+ response: null,
+ headers: new Headers()
+ } as never)
+
+ const response = await betterAuthProvider.handleSession!(
+ makeRequest('/search/abc123')
+ )
+
+ expect(response.status).toBe(200)
+ })
+
+ it('lets authenticated requests through', async () => {
+ vi.mocked(mockAuth.api.getSession).mockResolvedValue({
+ response: { user: sessionUser },
+ headers: new Headers()
+ } as never)
+
+ const response = await betterAuthProvider.handleSession!(
+ makeRequest('/some-protected-page')
+ )
+
+ expect(response.status).toBe(200)
+ })
+
+ it('forwards refreshed session cookies to the response', async () => {
+ // better-auth renews the cookie past half the session lifetime; the
+ // middleware must pass it on or active users expire at the old time.
+ const responseHeaders = new Headers()
+ responseHeaders.append(
+ 'set-cookie',
+ 'better-auth.session_token=refreshed; Path=/; HttpOnly'
+ )
+ vi.mocked(mockAuth.api.getSession).mockResolvedValue({
+ response: { user: sessionUser },
+ headers: responseHeaders
+ } as never)
+
+ const response = await betterAuthProvider.handleSession!(
+ makeRequest('/some-protected-page')
+ )
+
+ expect(response.headers.get('set-cookie')).toContain('refreshed')
+ })
+ })
+
+ describe('signIn', () => {
+ it('signs in without a manual set-cookie copy', async () => {
+ vi.mocked(mockAuth.api.signInEmail).mockResolvedValue({
+ session: {},
+ user: sessionUser
+ } as never)
+
+ const result = await betterAuthProvider.signIn!({
+ email: '[email protected]',
+ password: 'secret'
+ })
+
+ expect(result).toEqual({ success: true })
+ // The nextCookies plugin (registered on the real auth instance)
+ // stores the cookie via next/headers; the action must not ask for
+ // raw headers and re-apply them, which would double-encode the
+ // signed value.
+ expect(mockAuth.api.signInEmail).toHaveBeenCalledWith(
+ expect.not.objectContaining({ returnHeaders: true })
+ )
+ expect(mockSetCookie).not.toHaveBeenCalled()
+ })
+
+ it('reports invalid credentials', async () => {
+ vi.mocked(mockAuth.api.signInEmail).mockRejectedValue(
+ new Error('Invalid email or password')
+ )
+
+ const result = await betterAuthProvider.signIn!({
+ email: '[email protected]',
+ password: 'wrong'
+ })
+
+ expect(result).toEqual({
+ success: false,
+ error: 'Invalid email or password'
+ })
+ expect(mockSetCookie).not.toHaveBeenCalled()
+ })
+
+ it('blocks repeated attempts for the same ip and email', async () => {
+ // better-auth's own limiter only runs in its HTTP handler; the
+ // direct action needs the in-process limiter.
+ vi.mocked(mockAuth.api.signInEmail).mockResolvedValue({} as never)
+
+ for (let attempt = 0; attempt < 10; attempt++) {
+ await betterAuthProvider.signIn!({
+ email: '[email protected]',
+ password: 'x'
+ })
+ }
+
+ const result = await betterAuthProvider.signIn!({
+ email: '[email protected]',
+ password: 'x'
+ })
+
+ expect(result).toEqual({
+ success: false,
+ error: expect.stringContaining('Too many attempts')
+ })
+ })
+ })
+
+ describe('signUp', () => {
+ const signUpResult = { token: 'session-token', user: sessionUser }
+
+ it('signs up in open mode without a token', async () => {
+ vi.mocked(mockAuth.api.signUpEmail).mockResolvedValue(
+ signUpResult as never
+ )
+
+ const result = await betterAuthProvider.signUp!({
+ email: '[email protected]',
+ password: 'secret'
+ })
+
+ expect(result).toEqual({ success: true })
+ expect(validateInvitation).not.toHaveBeenCalled()
+ })
+
+ it('reports failure when the response carries no session token', async () => {
+ // Regression: signUpEmail resolves to `{ token, user }`; a response
+ // without a token means the account was not created.
+ vi.mocked(mockAuth.api.signUpEmail).mockResolvedValue({
+ user: sessionUser
+ } as never)
+
+ const result = await betterAuthProvider.signUp!({
+ email: '[email protected]',
+ password: 'secret'
+ })
+
+ expect(result.success).toBe(false)
+ })
+
+ it('requires a valid invitation in invite mode', async () => {
+ process.env.AUTH_SIGNUP_MODE = 'invite'
+ vi.mocked(validateInvitation).mockResolvedValue(null)
+
+ const result = await betterAuthProvider.signUp!({
+ email: '[email protected]',
+ password: 'secret'
+ })
+
+ expect(result).toEqual({
+ success: false,
+ error: 'Sign-up requires a valid invitation token.'
+ })
+ expect(mockAuth.api.signUpEmail).not.toHaveBeenCalled()
+ })
+
+ it('lets the BOOTSTRAP_ADMIN_EMAIL account sign up without an invitation', async () => {
+ // Fresh invite-only instance: invitations require an admin, so the
+ // gated seed address must be able to create the first account.
+ process.env.AUTH_SIGNUP_MODE = 'invite'
+ process.env.BOOTSTRAP_ADMIN_EMAIL = '[email protected]'
+ vi.mocked(mockAuth.api.signUpEmail).mockResolvedValue(
+ signUpResult as never
+ )
+
+ const result = await betterAuthProvider.signUp!({
+ email: '[email protected]',
+ password: 'secret'
+ })
+
+ expect(result).toEqual({ success: true })
+ expect(validateInvitation).not.toHaveBeenCalled()
+ })
+
+ it('emails a bootstrap invitation instead of creating the gated account when SMTP is set', async () => {
+ // The gate only compares caller-supplied text; with SMTP available the
+ // gated address must prove mailbox control before the admin account
+ // is created.
+ process.env.AUTH_SIGNUP_MODE = 'invite'
+ process.env.BOOTSTRAP_ADMIN_EMAIL = '[email protected]'
+ process.env.SMTP_HOST = 'smtp.example.com'
+ process.env.SMTP_USER = 'user'
+ process.env.SMTP_PASSWORD = 'pass'
+ process.env.BETTER_AUTH_URL = 'http://localhost:3000'
+ vi.mocked(createInvitation).mockResolvedValue({
+ invitation: {} as never,
+ token: 'boot-token'
+ })
+
+ const result = await betterAuthProvider.signUp!({
+ email: '[email protected]',
+ password: 'secret'
+ })
+
+ expect(result.success).toBe(true)
+ expect(result.notice).toContain('bootstrap link')
+ expect(createInvitation).toHaveBeenCalledWith({
+ invitedBy: 'bootstrap',
+ })
+ expect(sendSmtpMail).toHaveBeenCalledWith(
+ expect.objectContaining({
+ text: expect.stringContaining('/auth/sign-up?token=boot-token')
+ })
+ )
+ expect(mockAuth.api.signUpEmail).not.toHaveBeenCalled()
+ })
+
+ it('still validates the emailed bootstrap invitation through the normal token path', async () => {
+ // Following the emailed link must go through invitation validation,
+ // not the mailbox-proof branch (which would loop forever).
+ process.env.AUTH_SIGNUP_MODE = 'invite'
+ process.env.BOOTSTRAP_ADMIN_EMAIL = '[email protected]'
+ process.env.SMTP_HOST = 'smtp.example.com'
+ process.env.SMTP_USER = 'user'
+ process.env.SMTP_PASSWORD = 'pass'
+ process.env.BETTER_AUTH_URL = 'http://localhost:3000'
+ vi.mocked(validateInvitation).mockResolvedValue({
+ id: 'inv-1',
+ email: '[email protected]',
+ invitedBy: 'bootstrap'
+ } as never)
+ vi.mocked(consumeInvitation).mockResolvedValue(true)
+ vi.mocked(mockAuth.api.signUpEmail).mockResolvedValue(
+ signUpResult as never
+ )
+
+ const result = await betterAuthProvider.signUp!({
+ email: '[email protected]',
+ password: 'secret',
+ token: 'boot-token'
+ })
+
+ expect(result).toEqual({ success: true })
+ expect(createInvitation).not.toHaveBeenCalled()
+ expect(consumeInvitation).toHaveBeenCalledWith('inv-1')
+ })
+
+ it('releases the invitation when sign-up is rejected', async () => {
+ // better-auth validates the password after the claim: a rejected
+ // credential (e.g. below the minimum length) must not burn the link,
+ // or the invitee needs a fresh invitation for a typo.
+ process.env.AUTH_SIGNUP_MODE = 'invite'
+ vi.mocked(validateInvitation).mockResolvedValue({
+ id: 'inv-9',
+ } as never)
+ vi.mocked(consumeInvitation).mockResolvedValue(true)
+ vi.mocked(mockAuth.api.signUpEmail).mockResolvedValue({
+ response: null,
+ headers: new Headers()
+ } as never)
+
+ const result = await betterAuthProvider.signUp!({
+ email: '[email protected]',
+ password: 'short',
+ token: 'invite-token'
+ })
+
+ expect(result.success).toBe(false)
+ expect(releaseInvitation).toHaveBeenCalledWith('inv-9')
+ })
+
+ it('releases the invitation when sign-up throws', async () => {
+ process.env.AUTH_SIGNUP_MODE = 'invite'
+ vi.mocked(validateInvitation).mockResolvedValue({
+ id: 'inv-9',
+ } as never)
+ vi.mocked(consumeInvitation).mockResolvedValue(true)
+ vi.mocked(mockAuth.api.signUpEmail).mockRejectedValue(
+ new Error('Password must be at least 8 characters')
+ )
+
+ const result = await betterAuthProvider.signUp!({
+ email: '[email protected]',
+ password: 'short',
+ token: 'invite-token'
+ })
+
+ expect(result.success).toBe(false)
+ expect(result.error).toContain('at least 8 characters')
+ expect(releaseInvitation).toHaveBeenCalledWith('inv-9')
+ })
+
+ it('keeps the invitation consumed when the account exists despite a throw', async () => {
+ // The throw may have happened after better-auth committed the user:
+ // releasing the claim would re-enable a link whose address is taken.
+ process.env.AUTH_SIGNUP_MODE = 'invite'
+ state.accounts = [{ id: 'user-1' }]
+ vi.mocked(validateInvitation).mockResolvedValue({
+ id: 'inv-9',
+ } as never)
+ vi.mocked(consumeInvitation).mockResolvedValue(true)
+ vi.mocked(mockAuth.api.signUpEmail).mockRejectedValue(
+ new Error('connection dropped')
+ )
+
+ const result = await betterAuthProvider.signUp!({
+ email: '[email protected]',
+ password: 'secret',
+ token: 'invite-token'
+ })
+
+ expect(result.success).toBe(false)
+ expect(releaseInvitation).not.toHaveBeenCalled()
+ })
+
+ it('rejects an arbitrary token on the gated address in open mode', async () => {
+ // Open mode ignores tokens for regular sign-ups, so the bootstrap
+ // proof must validate them itself: any non-empty token must not be
+ // enough to skip mailbox control.
+ process.env.BOOTSTRAP_ADMIN_EMAIL = '[email protected]'
+ process.env.SMTP_HOST = 'smtp.example.com'
+ process.env.SMTP_USER = 'user'
+ process.env.SMTP_PASSWORD = 'pass'
+ process.env.BETTER_AUTH_URL = 'http://localhost:3000'
+ vi.mocked(validateInvitation).mockResolvedValue(null)
+
+ const result = await betterAuthProvider.signUp!({
+ email: '[email protected]',
+ password: 'secret',
+ token: 'arbitrary-token'
+ })
+
+ expect(result.success).toBe(false)
+ expect(result.error).toContain('link sent to your email')
+ expect(mockAuth.api.signUpEmail).not.toHaveBeenCalled()
+ expect(createInvitation).not.toHaveBeenCalled()
+ })
+
+ it('redeems the emailed bootstrap invitation in open mode too', async () => {
+ process.env.BOOTSTRAP_ADMIN_EMAIL = '[email protected]'
+ process.env.SMTP_HOST = 'smtp.example.com'
+ process.env.SMTP_USER = 'user'
+ process.env.SMTP_PASSWORD = 'pass'
+ process.env.BETTER_AUTH_URL = 'http://localhost:3000'
+ vi.mocked(validateInvitation).mockResolvedValue({
+ id: 'inv-2',
+ email: '[email protected]',
+ invitedBy: 'bootstrap'
+ } as never)
+ vi.mocked(consumeInvitation).mockResolvedValue(true)
+ vi.mocked(mockAuth.api.signUpEmail).mockResolvedValue(
+ signUpResult as never
+ )
+
+ const result = await betterAuthProvider.signUp!({
+ email: '[email protected]',
+ password: 'secret',
+ token: 'boot-token'
+ })
+
+ expect(result).toEqual({ success: true })
+ expect(consumeInvitation).toHaveBeenCalledWith('inv-2')
+ })
+
+ it('rejects a bootstrap token not bound to the gated address', async () => {
+ process.env.BOOTSTRAP_ADMIN_EMAIL = '[email protected]'
+ process.env.SMTP_HOST = 'smtp.example.com'
+ process.env.SMTP_USER = 'user'
+ process.env.SMTP_PASSWORD = 'pass'
+ process.env.BETTER_AUTH_URL = 'http://localhost:3000'
+ vi.mocked(validateInvitation).mockResolvedValue({
+ id: 'inv-3',
+ email: null
+ } as never)
+
+ const result = await betterAuthProvider.signUp!({
+ email: '[email protected]',
+ password: 'secret',
+ token: 'unbound-token'
+ })
+
+ expect(result.success).toBe(false)
+ expect(mockAuth.api.signUpEmail).not.toHaveBeenCalled()
+ expect(consumeInvitation).not.toHaveBeenCalled()
+ })
+
+ it('rejects an ordinary invitation used for bootstrap sign-up', async () => {
+ // In a reopened bootstrap window, an ordinary invitation (from an
+ // inviting admin) for the same address must not claim admin:
+ // only the invitation this branch mailed itself (invitedBy =
+ // 'bootstrap') proves mailbox control of the gated address.
+ process.env.BOOTSTRAP_ADMIN_EMAIL = '[email protected]'
+ process.env.SMTP_HOST = 'smtp.example.com'
+ process.env.SMTP_USER = 'user'
+ process.env.SMTP_PASSWORD = 'pass'
+ process.env.BETTER_AUTH_URL = 'http://localhost:3000'
+ vi.mocked(validateInvitation).mockResolvedValue({
+ id: 'inv-5',
+ email: '[email protected]',
+ invitedBy: 'some-admin-id'
+ } as never)
+
+ const result = await betterAuthProvider.signUp!({
+ email: '[email protected]',
+ password: 'secret',
+ token: 'ordinary-invitation-token'
+ })
+
+ expect(result.success).toBe(false)
+ expect(result.error).toContain('link sent to your email')
+ expect(mockAuth.api.signUpEmail).not.toHaveBeenCalled()
+ expect(consumeInvitation).not.toHaveBeenCalled()
+ })
+
+ it('does not send a second bootstrap link within the cooldown', async () => {
+ // The branch runs before better-auth's rate limiter: a caller who
+ // knows the gated address must not be able to flood the mailbox.
+ process.env.BOOTSTRAP_ADMIN_EMAIL = '[email protected]'
+ process.env.SMTP_HOST = 'smtp.example.com'
+ process.env.SMTP_USER = 'user'
+ process.env.SMTP_PASSWORD = 'pass'
+ process.env.BETTER_AUTH_URL = 'http://localhost:3000'
+ vi.mocked(hasRecentBootstrapInvitation).mockResolvedValue(true)
+
+ const result = await betterAuthProvider.signUp!({
+ email: '[email protected]',
+ password: 'secret'
+ })
+
+ expect(result.success).toBe(true)
+ expect(result.notice).toContain('bootstrap link')
+ expect(createInvitation).not.toHaveBeenCalled()
+ expect(sendSmtpMail).not.toHaveBeenCalled()
+ expect(mockAuth.api.signUpEmail).not.toHaveBeenCalled()
+ })
+
+ it('refuses the bootstrap flow when SMTP is set without a canonical origin', async () => {
+ // Fail closed: silently falling back to first-come sign-up would
+ // let anyone who guesses the gated address claim admin while the
+ // operator believes mailbox proof is active.
+ process.env.BOOTSTRAP_ADMIN_EMAIL = '[email protected]'
+ process.env.SMTP_HOST = 'smtp.example.com'
+ process.env.SMTP_USER = 'user'
+ process.env.SMTP_PASSWORD = 'pass'
+
+ const result = await betterAuthProvider.signUp!({
+ email: '[email protected]',
+ password: 'secret'
+ })
+
+ expect(result.success).toBe(false)
+ expect(result.error).toContain('BETTER_AUTH_URL')
+ expect(createInvitation).not.toHaveBeenCalled()
+ expect(sendSmtpMail).not.toHaveBeenCalled()
+ expect(mockAuth.api.signUpEmail).not.toHaveBeenCalled()
+ })
+
+ it('releases the invitation when the bootstrap email fails to send', async () => {
+ // Otherwise the cooldown would treat the unsent invitation as
+ // delivered and block retries for 15 minutes.
+ process.env.BOOTSTRAP_ADMIN_EMAIL = '[email protected]'
+ process.env.SMTP_HOST = 'smtp.example.com'
+ process.env.SMTP_USER = 'user'
+ process.env.SMTP_PASSWORD = 'pass'
+ process.env.BETTER_AUTH_URL = 'http://localhost:3000'
+ vi.mocked(hasRecentBootstrapInvitation).mockResolvedValue(false)
+ vi.mocked(createInvitation).mockResolvedValue({
+ invitation: { id: 'inv-boot' } as never,
+ token: 'boot-token'
+ })
+ vi.mocked(sendSmtpMail).mockRejectedValue(new Error('smtp down'))
+
+ const result = await betterAuthProvider.signUp!({
+ email: '[email protected]',
+ password: 'secret'
+ })
+
+ expect(result.success).toBe(false)
+ expect(result.error).toContain('smtp down')
+ expect(revokeInvitation).toHaveBeenCalledWith('inv-boot')
+ })
+
+ it('serializes concurrent bootstrap requests per address', async () => {
+ // The cooldown check and the insert are separate queries: without the
+ // per-address lock, two concurrent calls would both pass the check
+ // before either insert landed and each would mail a live admin link.
+ process.env.BOOTSTRAP_ADMIN_EMAIL = '[email protected]'
+ process.env.SMTP_HOST = 'smtp.example.com'
+ process.env.SMTP_USER = 'user'
+ process.env.SMTP_PASSWORD = 'pass'
+ process.env.BETTER_AUTH_URL = 'http://localhost:3000'
+ let created = false
+ vi.mocked(hasRecentBootstrapInvitation).mockImplementation(
+ async () => created
+ )
+ vi.mocked(createInvitation).mockImplementation(async () => {
+ created = true
+ return { invitation: { id: 'inv-boot' } as never, token: 'boot-token' }
+ })
+ vi.mocked(sendSmtpMail).mockResolvedValue(undefined)
+
+ const [first, second] = await Promise.all([
+ betterAuthProvider.signUp!({
+ email: '[email protected]',
+ password: 'secret'
+ }),
+ betterAuthProvider.signUp!({
+ email: '[email protected]',
+ password: 'secret'
+ })
+ ])
+
+ expect(first.success).toBe(true)
+ expect(second.success).toBe(true)
+ expect(createInvitation).toHaveBeenCalledTimes(1)
+ expect(sendSmtpMail).toHaveBeenCalledTimes(1)
+ })
+
+ it('claims the invitation before creating the account', async () => {
+ process.env.AUTH_SIGNUP_MODE = 'invite'
+ vi.mocked(validateInvitation).mockResolvedValue({
+ id: 'inv-1',
+ token: 'tok'
+ } as never)
+ vi.mocked(consumeInvitation).mockResolvedValue(true)
+ vi.mocked(mockAuth.api.signUpEmail).mockResolvedValue(
+ signUpResult as never
+ )
+
+ const result = await betterAuthProvider.signUp!({
+ email: '[email protected]',
+ password: 'secret',
+ token: 'tok'
+ })
+
+ expect(result).toEqual({ success: true })
+ expect(consumeInvitation).toHaveBeenCalledWith('inv-1')
+ })
+
+ it('rejects a sign-up whose email does not match the invitation', async () => {
+ process.env.AUTH_SIGNUP_MODE = 'invite'
+ vi.mocked(validateInvitation).mockResolvedValue({
+ id: 'inv-1',
+ } as never)
+
+ const result = await betterAuthProvider.signUp!({
+ email: '[email protected]',
+ password: 'secret',
+ token: 'tok'
+ })
+
+ expect(result).toEqual({
+ success: false,
+ error: 'This invitation was issued for a different email address.'
+ })
+ // A mismatched attempt must not burn the invitation for its recipient
+ expect(consumeInvitation).not.toHaveBeenCalled()
+ expect(mockAuth.api.signUpEmail).not.toHaveBeenCalled()
+ })
+
+ it('accepts a case-insensitive match with the invited email', async () => {
+ process.env.AUTH_SIGNUP_MODE = 'invite'
+ vi.mocked(validateInvitation).mockResolvedValue({
+ id: 'inv-1',
+ } as never)
+ vi.mocked(consumeInvitation).mockResolvedValue(true)
+ vi.mocked(mockAuth.api.signUpEmail).mockResolvedValue(
+ signUpResult as never
+ )
+
+ const result = await betterAuthProvider.signUp!({
+ email: '[email protected]',
+ password: 'secret',
+ token: 'tok'
+ })
+
+ expect(result).toEqual({ success: true })
+ })
+
+ it('rejects when the invitation was already claimed concurrently', async () => {
+ process.env.AUTH_SIGNUP_MODE = 'invite'
+ vi.mocked(validateInvitation).mockResolvedValue({
+ id: 'inv-1',
+ token: 'tok'
+ } as never)
+ vi.mocked(consumeInvitation).mockResolvedValue(false)
+
+ const result = await betterAuthProvider.signUp!({
+ email: '[email protected]',
+ password: 'secret',
+ token: 'tok'
+ })
+
+ expect(result).toEqual({
+ success: false,
+ error: 'Sign-up requires a valid invitation token.'
+ })
+ expect(mockAuth.api.signUpEmail).not.toHaveBeenCalled()
+ })
+ })
+
+ describe('requestPasswordReset', () => {
+ it('fails without SMTP configuration', async () => {
+ const result =
+ await betterAuthProvider.requestPasswordReset!('[email protected]')
+
+ expect(result.success).toBe(false)
+ expect(mockAuth.api.requestPasswordReset).not.toHaveBeenCalled()
+ })
+
+ it('sends a reset email when SMTP is configured', async () => {
+ process.env.SMTP_HOST = 'smtp.example.com'
+ process.env.SMTP_USER = 'user'
+ process.env.SMTP_PASSWORD = 'secret'
+ vi.mocked(mockAuth.api.requestPasswordReset).mockResolvedValue(
+ {} as never
+ )
+
+ const result =
+ await betterAuthProvider.requestPasswordReset!('[email protected]')
+
+ expect(result).toEqual({ success: true })
+ expect(mockAuth.api.requestPasswordReset).toHaveBeenCalledWith(
+ expect.objectContaining({
+ body: {
+ email: '[email protected]',
+ redirectTo: 'http://localhost:3000/auth/update-password'
+ }
+ })
+ )
+ })
+ })
+
+ describe('updatePassword', () => {
+ it('routes token resets to the sign-in page', async () => {
+ // A token reset changes the credential only: no session cookie is
+ // issued, so landing on the app root would show the anonymous UI.
+ vi.mocked(mockAuth.api.resetPassword).mockResolvedValue({} as never)
+
+ const result = await betterAuthProvider.updatePassword!(
+ 'new-password',
+ 'reset-token'
+ )
+
+ expect(result).toEqual({
+ success: true,
+ redirectTo: '/auth/login'
+ })
+ })
+
+ it('keeps the session-based flow on the app root', async () => {
+ vi.mocked(mockAuth.api.resetPassword).mockResolvedValue({} as never)
+
+ const result = await betterAuthProvider.updatePassword!('new-password')
+
+ expect(result).toEqual({ success: true })
+ })
+ })
+
+ describe('canDeleteUser', () => {
+ it('returns null for non-admin accounts', async () => {
+ state.accounts = [{ id: 'user-1', role: 'user' }]
+
+ await expect(
+ betterAuthProvider.canDeleteUser!('user-1')
+ ).resolves.toBeNull()
+ })
+
+ it('refuses for the only remaining admin', async () => {
+ state.accounts = [{ id: 'user-1', role: 'admin' }]
+ state.adminCount = 1
+
+ await expect(
+ betterAuthProvider.canDeleteUser!('user-1')
+ ).resolves.toMatch(/only admin/i)
+ })
+
+ it('allows an admin while another remains', async () => {
+ state.accounts = [{ id: 'user-1', role: 'admin' }]
+ state.adminCount = 2
+
+ await expect(
+ betterAuthProvider.canDeleteUser!('user-1')
+ ).resolves.toBeNull()
+ })
+
+ it('allows the sole account of a single-user instance', async () => {
+ state.accounts = [{ id: 'user-1', role: 'admin' }]
+ state.adminCount = 1
+ state.userCount = 1
+
+ await expect(
+ betterAuthProvider.canDeleteUser!('user-1')
+ ).resolves.toBeNull()
+ })
+
+ it('does not take row locks from the unlocked pre-check', async () => {
+ state.accounts = [{ id: 'user-1', role: 'admin' }]
+ state.adminCount = 2
+
+ await expect(
+ betterAuthProvider.canDeleteUser!('user-1')
+ ).resolves.toBeNull()
+
+ // The pre-check runs outside any transaction; FOR UPDATE there
+ // would be pointless contention for a UX-only answer.
+ expect(state.targetLocked).toBe(false)
+ })
+ })
+
+ describe('deleteUser', () => {
+ it('deletes the auth user row', async () => {
+ const { db } = await import('@/lib/db')
+
+ const result = await betterAuthProvider.deleteUser!('user-1')
+
+ expect(result).toEqual({ success: true })
+ expect(db.delete).toHaveBeenCalled()
+ })
+
+ it('refuses to delete the only remaining admin', async () => {
+ state.accounts = [{ id: 'user-1', role: 'admin' }]
+ state.adminCount = 1
+ const { db } = await import('@/lib/db')
+
+ const result = await betterAuthProvider.deleteUser!('user-1')
+
+ expect(result.success).toBe(false)
+ expect(result.error).toMatch(/only admin/i)
+ expect(db.delete).not.toHaveBeenCalled()
+ })
+
+ it('deletes an admin account while another admin remains', async () => {
+ state.accounts = [{ id: 'user-1', role: 'admin' }]
+ state.adminCount = 2
+ const { db } = await import('@/lib/db')
+
+ const result = await betterAuthProvider.deleteUser!('user-1')
+
+ expect(result).toEqual({ success: true })
+ expect(db.delete).toHaveBeenCalled()
+ })
+
+ it('deletes the last remaining account even when it is the only admin', async () => {
+ state.accounts = [{ id: 'user-1', role: 'admin' }]
+ state.adminCount = 1
+ state.userCount = 1
+ const { db } = await import('@/lib/db')
+
+ const result = await betterAuthProvider.deleteUser!('user-1')
+
+ expect(result).toEqual({ success: true })
+ expect(db.delete).toHaveBeenCalled()
+ })
+
+ it('deletes through a caller-supplied transaction without re-guarding', async () => {
+ // The caller (deleteAccount) already validated the guard under this
+ // transaction's locks; deleteUser must not refuse here even though
+ // the state alone (last admin with members) would.
+ state.accounts = [{ id: 'user-1', role: 'admin' }]
+ state.adminCount = 1
+ state.userCount = 2
+ const { db } = await import('@/lib/db')
+
+ const result = await betterAuthProvider.deleteUser!('user-1', db as never)
+
+ expect(result).toEqual({ success: true })
+ expect(db.delete).toHaveBeenCalled()
+ })
+ })
+
+ describe('validateDeletion', () => {
+ it('refuses the last admin while members remain and reports wasAdmin', async () => {
+ state.accounts = [{ id: 'user-1', role: 'admin' }]
+ state.adminCount = 1
+ state.userCount = 2
+ const { db } = await import('@/lib/db')
+
+ await expect(
+ betterAuthProvider.validateDeletion!('user-1', db as never)
+ ).resolves.toEqual({
+ error: expect.stringMatching(/only admin/i),
+ wasAdmin: true
+ })
+ })
+
+ it('allows the sole account of a single-user instance', async () => {
+ state.accounts = [{ id: 'user-1', role: 'admin' }]
+ state.adminCount = 1
+ state.userCount = 1
+ const { db } = await import('@/lib/db')
+
+ await expect(
+ betterAuthProvider.validateDeletion!('user-1', db as never)
+ ).resolves.toEqual({ error: null, wasAdmin: true })
+ })
+
+ it('reports wasAdmin false for regular members', async () => {
+ state.accounts = [{ id: 'user-1', role: 'user' }]
+ const { db } = await import('@/lib/db')
+
+ await expect(
+ betterAuthProvider.validateDeletion!('user-1', db as never)
+ ).resolves.toEqual({ error: null, wasAdmin: false })
+ })
+
+ it('locks the target row before classifying its role', async () => {
+ // A concurrent promotion must not slip a soon-to-be-admin past
+ // the last-admin guard mid-deletion, so the role read happens
+ // under a row lock when the guard runs in a transaction.
+ state.accounts = [{ id: 'user-1', role: 'user' }]
+ const { db } = await import('@/lib/db')
+
+ await betterAuthProvider.validateDeletion!('user-1', db as never)
+
+ expect(state.targetLocked).toBe(true)
+ })
+ })
+
+ describe('postDeletion', () => {
+ it('re-runs the bootstrap election when the deleted account was admin', async () => {
+ await betterAuthProvider.postDeletion!(true)
+
+ expect(reElectBootstrapAdmin).toHaveBeenCalledTimes(1)
+ })
+
+ it('is a no-op for member deletions', async () => {
+ await betterAuthProvider.postDeletion!(false)
+
+ expect(reElectBootstrapAdmin).not.toHaveBeenCalled()
+ })
+ })
+})
diff --git a/lib/auth/__tests__/none-provider.test.ts b/lib/auth/__tests__/none-provider.test.ts
index 87b02028..05946c43 100644
--- a/lib/auth/__tests__/none-provider.test.ts
+++ b/lib/auth/__tests__/none-provider.test.ts
@@ -89,7 +89,10 @@ describe('none auth provider (anonymous mode)', () => {
expect(noneAuthProvider.capabilities).toEqual({
signUp: false,
passwordReset: false,
- deleteUser: false
+ deleteUser: false,
+ oauth: false,
+ emailVerification: false,
+ share: false
})
})
})
diff --git a/lib/auth/__tests__/provider.test.ts b/lib/auth/__tests__/provider.test.ts
index c2293098..cf56a62e 100644
--- a/lib/auth/__tests__/provider.test.ts
+++ b/lib/auth/__tests__/provider.test.ts
@@ -3,7 +3,8 @@ import { afterEach, beforeEach, describe, expect, it } from 'vitest'
import {
getAuthProvider,
isAnonymousMode,
- resolveAuthProviderName
+ resolveAuthProviderName,
+ withShareOptIn
} from '@/lib/auth/provider'
const AUTH_ENV_KEYS = [
@@ -70,12 +71,10 @@ describe('auth provider dispatch', () => {
)
})
- it('accepts better-auth as a name but reports it unavailable in this version', () => {
+ it('resolves better-auth to the better-auth provider', () => {
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.'
- )
+ expect(getAuthProvider().name).toBe('better-auth')
})
})
@@ -191,3 +190,78 @@ describe('supabase provider without configuration', () => {
expect(response.headers.get('location')).toBeNull()
})
})
+
+describe('withShareOptIn', () => {
+ const base = {
+ signUp: true,
+ passwordReset: true,
+ deleteUser: true,
+ oauth: false,
+ emailVerification: false,
+ share: true
+ }
+
+ it('keeps sharing only when an opt-in flag is true (better-auth)', () => {
+ const originalPublic = process.env.NEXT_PUBLIC_ENABLE_SHARE
+ const originalRuntime = process.env.ENABLE_SHARE
+ try {
+ delete process.env.NEXT_PUBLIC_ENABLE_SHARE
+ delete process.env.ENABLE_SHARE
+ expect(withShareOptIn(base, 'better-auth').share).toBe(false)
+
+ // The runtime flag is the one that works in prebuilt images, where
+ // the public flag was inlined at build time.
+ process.env.ENABLE_SHARE = 'true'
+ expect(withShareOptIn(base, 'better-auth').share).toBe(true)
+ process.env.ENABLE_SHARE = 'false'
+ expect(withShareOptIn(base, 'better-auth').share).toBe(false)
+
+ process.env.NEXT_PUBLIC_ENABLE_SHARE = 'true'
+ expect(withShareOptIn(base, 'better-auth').share).toBe(true)
+
+ process.env.NEXT_PUBLIC_ENABLE_SHARE = 'false'
+ expect(withShareOptIn(base, 'better-auth').share).toBe(false)
+ } finally {
+ if (originalPublic === undefined) {
+ delete process.env.NEXT_PUBLIC_ENABLE_SHARE
+ } else {
+ process.env.NEXT_PUBLIC_ENABLE_SHARE = originalPublic
+ }
+ if (originalRuntime === undefined) {
+ delete process.env.ENABLE_SHARE
+ } else {
+ process.env.ENABLE_SHARE = originalRuntime
+ }
+ }
+ })
+
+ it('leaves supabase sharing untouched by the opt-in flag', () => {
+ // The default Supabase path must behave as it always has: sharing
+ // with no env var configured.
+ const originalPublic = process.env.NEXT_PUBLIC_ENABLE_SHARE
+ const originalRuntime = process.env.ENABLE_SHARE
+ try {
+ delete process.env.NEXT_PUBLIC_ENABLE_SHARE
+ delete process.env.ENABLE_SHARE
+ expect(withShareOptIn(base, 'supabase').share).toBe(true)
+ } finally {
+ if (originalPublic === undefined) {
+ delete process.env.NEXT_PUBLIC_ENABLE_SHARE
+ } else {
+ process.env.NEXT_PUBLIC_ENABLE_SHARE = originalPublic
+ }
+ if (originalRuntime === undefined) {
+ delete process.env.ENABLE_SHARE
+ } else {
+ process.env.ENABLE_SHARE = originalRuntime
+ }
+ }
+ })
+
+ it('never enables sharing for a provider without the capability', () => {
+ process.env.NEXT_PUBLIC_ENABLE_SHARE = 'true'
+ expect(withShareOptIn({ ...base, share: false }, 'better-auth').share).toBe(
+ false
+ )
+ })
+})
diff --git a/lib/auth/__tests__/rate-limit.test.ts b/lib/auth/__tests__/rate-limit.test.ts
new file mode 100644
index 00000000..15da14b2
--- /dev/null
+++ b/lib/auth/__tests__/rate-limit.test.ts
@@ -0,0 +1,44 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+
+import { checkRateLimit, resetRateLimits } from '../rate-limit'
+
+describe('checkRateLimit', () => {
+ beforeEach(() => {
+ resetRateLimits()
+ vi.useFakeTimers()
+ })
+
+ afterEach(() => {
+ vi.useRealTimers()
+ })
+
+ it('allows ten attempts and blocks the eleventh within a window', () => {
+ for (let attempt = 0; attempt < 10; attempt++) {
+ expect(checkRateLimit('sign-in:1.2.3.4:[email protected]')).toBe(true)
+ }
+ expect(checkRateLimit('sign-in:1.2.3.4:[email protected]')).toBe(false)
+ })
+
+ it('allows again once the window passes', () => {
+ for (let attempt = 0; attempt < 12; attempt++) {
+ checkRateLimit('sign-in:1.2.3.4:[email protected]')
+ }
+ expect(checkRateLimit('sign-in:1.2.3.4:[email protected]')).toBe(false)
+
+ vi.advanceTimersByTime(60_001)
+
+ expect(checkRateLimit('sign-in:1.2.3.4:[email protected]')).toBe(true)
+ })
+
+ it('tracks keys independently', () => {
+ for (let attempt = 0; attempt < 12; attempt++) {
+ checkRateLimit('sign-in:1.2.3.4:[email protected]')
+ }
+
+ // A different account from the same IP, or the same account from a
+ // different IP, keeps its own budget.
+ expect(checkRateLimit('sign-in:1.2.3.4:[email protected]')).toBe(true)
+ expect(checkRateLimit('sign-in:5.6.7.8:[email protected]')).toBe(true)
+ expect(checkRateLimit('sign-up:1.2.3.4:[email protected]')).toBe(true)
+ })
+})
diff --git a/lib/auth/__tests__/redirect-target.test.ts b/lib/auth/__tests__/redirect-target.test.ts
new file mode 100644
index 00000000..f3f668e3
--- /dev/null
+++ b/lib/auth/__tests__/redirect-target.test.ts
@@ -0,0 +1,34 @@
+import { describe, expect, it } from 'vitest'
+
+import { safeRedirectPath } from '@/lib/auth/redirect-target'
+
+describe('safeRedirectPath', () => {
+ it('keeps plain same-origin paths', () => {
+ expect(safeRedirectPath('/search/abc123')).toBe('/search/abc123')
+ expect(safeRedirectPath('/search/abc?x=1#top')).toBe('/search/abc?x=1#top')
+ })
+
+ it('falls back to the root when absent', () => {
+ expect(safeRedirectPath(undefined)).toBe('/')
+ expect(safeRedirectPath('')).toBe('/')
+ })
+
+ it('rejects protocol-relative and absolute destinations', () => {
+ expect(safeRedirectPath('//evil.example.com')).toBe('/')
+ expect(safeRedirectPath('http://evil.example.com')).toBe('/')
+ expect(safeRedirectPath('https://evil.example.com/path')).toBe('/')
+ })
+
+ it('rejects backslash-normalized destinations', () => {
+ // Browsers normalize backslashes to slashes when resolving URLs, so
+ // /\evil.example.com would navigate off-site after navigation.
+ expect(safeRedirectPath('/\\evil.example.com')).toBe('/')
+ })
+
+ it('rejects non-HTTP schemes and credentials', () => {
+ expect(safeRedirectPath('javascript:alert(1)')).toBe('/')
+ expect(safeRedirectPath('http://user:[email protected]/')).toBe(
+ '/'
+ )
+ })
+})
diff --git a/lib/auth/better-auth/__tests__/config.test.ts b/lib/auth/better-auth/__tests__/config.test.ts
new file mode 100644
index 00000000..1ab394d3
--- /dev/null
+++ b/lib/auth/better-auth/__tests__/config.test.ts
@@ -0,0 +1,517 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+
+import {
+ applyBootstrapAdminGate,
+ claimBootstrapAdmin,
+ getAuth,
+ getSignUpMode,
+ isBootstrapAccount,
+ isBootstrapWindowOpen,
+ reElectBootstrapAdmin,
+ resetAuthInstance
+} from '@/lib/auth/better-auth/config'
+import { sendSmtpMail } from '@/lib/auth/better-auth/mailer'
+import { db } from '@/lib/db'
+
+vi.mock('@/lib/auth/better-auth/mailer', async importOriginal => ({
+ ...(await importOriginal<typeof import('@/lib/auth/better-auth/mailer')>()),
+ sendSmtpMail: vi.fn()
+}))
+
+vi.mock('@/lib/db', () => ({
+ db: {
+ select: vi.fn(() => ({
+ from: vi.fn()
+ })),
+ transaction: vi.fn()
+ }
+}))
+
+function mockUserCount(total: number) {
+ vi.mocked(db.select).mockReturnValue({
+ from: vi.fn().mockResolvedValue([{ total }])
+ } as never)
+}
+
+function mockClaim(opts: {
+ admins?: Array<{ id: string }>
+ earliest?: string
+}) {
+ const set = vi.fn(() => ({ where: vi.fn() }))
+ const update = vi.fn(() => ({ set }))
+ const tx = {
+ execute: vi.fn(),
+ select: vi.fn(() => ({
+ from: vi.fn(() => ({
+ where: vi.fn(() => ({
+ limit: vi.fn().mockResolvedValue(opts.admins ?? [])
+ })),
+ orderBy: vi.fn(() => ({
+ limit: vi
+ .fn()
+ .mockResolvedValue(opts.earliest ? [{ id: opts.earliest }] : [])
+ }))
+ }))
+ })),
+ update
+ }
+ vi.mocked(db.transaction).mockImplementation(
+ async callback => (callback as (tx: unknown) => Promise<void>)(tx) as never
+ )
+ return { tx, update, set }
+}
+
+describe('bootstrap admin gate', () => {
+ const originalEnv: Record<string, string | undefined> = {}
+
+ beforeEach(() => {
+ for (const key of ['BOOTSTRAP_ADMIN_EMAIL', 'NODE_ENV']) {
+ originalEnv[key] = process.env[key]
+ }
+ delete process.env.BOOTSTRAP_ADMIN_EMAIL
+ vi.clearAllMocks()
+ })
+
+ afterEach(() => {
+ for (const [key, value] of Object.entries(originalEnv)) {
+ if (value === undefined) {
+ delete process.env[key]
+ } else {
+ process.env[key] = value
+ }
+ }
+ })
+
+ it('allows any email through while no gate is configured', async () => {
+ mockUserCount(0)
+
+ await expect(
+ applyBootstrapAdminGate({ email: '[email protected]' })
+ ).resolves.toBeUndefined()
+ })
+
+ it('leaves later sign-ups untouched once the window closed', async () => {
+ mockUserCount(1)
+
+ await expect(
+ applyBootstrapAdminGate({ email: '[email protected]' })
+ ).resolves.toBeUndefined()
+ })
+
+ it('rejects other emails while BOOTSTRAP_ADMIN_EMAIL is set', async () => {
+ process.env.BOOTSTRAP_ADMIN_EMAIL = '[email protected]'
+ mockUserCount(0)
+
+ await expect(
+ applyBootstrapAdminGate({ email: '[email protected]' })
+ ).rejects.toThrow(/BOOTSTRAP_ADMIN_EMAIL/)
+ })
+
+ it('accepts the gated email case-insensitively', async () => {
+ process.env.BOOTSTRAP_ADMIN_EMAIL = '[email protected]'
+ mockUserCount(0)
+
+ await expect(
+ applyBootstrapAdminGate({ email: '[email protected]' })
+ ).resolves.toBeUndefined()
+ })
+
+ it('does not gate sign-ups after the window closed even with a gate set', async () => {
+ process.env.BOOTSTRAP_ADMIN_EMAIL = '[email protected]'
+ mockUserCount(3)
+
+ await expect(
+ applyBootstrapAdminGate({ email: '[email protected]' })
+ ).resolves.toBeUndefined()
+ })
+})
+
+describe('claimBootstrapAdmin', () => {
+ it('grants the admin role to the first account', async () => {
+ const { tx, update, set } = mockClaim({ earliest: 'user-1' })
+
+ await claimBootstrapAdmin('user-1')
+
+ expect(tx.execute).toHaveBeenCalled()
+ expect(update).toHaveBeenCalled()
+ expect(set).toHaveBeenCalledWith({ role: 'admin' })
+ })
+
+ it('does nothing when an admin already exists', async () => {
+ const { update } = mockClaim({
+ admins: [{ id: 'existing-admin' }],
+ earliest: 'user-1'
+ })
+
+ await claimBootstrapAdmin('user-1')
+
+ expect(update).not.toHaveBeenCalled()
+ })
+
+ it('does nothing when other users remain (no re-bootstrap after the first account)', async () => {
+ // Sole admin deleted their account while members remained: the next
+ // registrant is neither an admin nor the earliest account, so it must
+ // not inherit the role.
+ const { update } = mockClaim({ earliest: 'older-user' })
+
+ await claimBootstrapAdmin('user-1')
+
+ expect(update).not.toHaveBeenCalled()
+ })
+
+ it('elects exactly one admin when concurrent first sign-ups both observe each other', async () => {
+ // Alice and Bob commit before either after-hook claims; each claim sees
+ // both rows. Only the earliest account may claim, so exactly one wins
+ // regardless of interleaving.
+ const claims: string[] = []
+ for (const userId of ['alice', 'bob']) {
+ const { update } = mockClaim({ earliest: 'alice' })
+ await claimBootstrapAdmin(userId)
+ if (update.mock.calls.length > 0) {
+ claims.push(userId)
+ }
+ }
+
+ expect(claims).toEqual(['alice'])
+ })
+
+ it('retries serialization failures and completes the claim when no admin materialized', async () => {
+ // A 40001 abort does not prove a concurrent claimant committed:
+ // both claimants can abort. The retry must re-run the election
+ // instead of giving up and stranding the instance admin-less.
+ const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => {})
+ const { update } = mockClaim({ earliest: 'user-1' })
+ vi.mocked(db.transaction).mockRejectedValueOnce(
+ Object.assign(new Error('could not serialize access'), {
+ code: '40001'
+ })
+ )
+
+ await expect(claimBootstrapAdmin('user-1')).resolves.toBeUndefined()
+
+ expect(update).toHaveBeenCalled()
+ expect(errorSpy).not.toHaveBeenCalled()
+
+ errorSpy.mockRestore()
+ })
+
+ it('logs unexpected claim failures', async () => {
+ const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => {})
+ vi.mocked(db.transaction).mockRejectedValue(new Error('connection lost'))
+
+ await expect(claimBootstrapAdmin('user-1')).resolves.toBeUndefined()
+ expect(errorSpy).toHaveBeenCalledWith(
+ expect.stringContaining('Bootstrap admin claim failed'),
+ expect.any(Error)
+ )
+ // Exhaustion must read as a repair-needed condition with the
+ // remediation, not a silent success.
+ expect(errorSpy.mock.calls[0][0]).toContain('repair needed')
+ expect(errorSpy.mock.calls[0][0]).toContain("SET role = 'admin'")
+
+ errorSpy.mockRestore()
+ })
+
+ it('retries a transient claim failure until it succeeds', async () => {
+ // The user insert is already committed at this point and the
+ // earliest-account guard means no later sign-up can take the claim
+ // over, so a transient blip must be retried rather than logged away.
+ const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => {})
+ const { update } = mockClaim({ earliest: 'user-1' })
+ vi.mocked(db.transaction).mockRejectedValueOnce(
+ Object.assign(new Error('connection lost'), { code: '08006' })
+ )
+
+ await expect(claimBootstrapAdmin('user-1')).resolves.toBeUndefined()
+
+ expect(update).toHaveBeenCalled()
+ expect(errorSpy).not.toHaveBeenCalled()
+
+ errorSpy.mockRestore()
+ })
+})
+
+describe('reElectBootstrapAdmin', () => {
+ it('promotes the earliest account when the deletion left no admin', async () => {
+ // A sign-up raced the sole admin's deletion: its own claim declined
+ // because the admin row still existed. The re-election completes the
+ // election for the earliest remaining account.
+ const { update, set } = mockClaim({ earliest: 'raced-signup' })
+
+ await reElectBootstrapAdmin()
+
+ expect(update).toHaveBeenCalled()
+ expect(set).toHaveBeenCalledWith({ role: 'admin' })
+ })
+
+ it('does nothing when an admin exists', async () => {
+ const { update } = mockClaim({
+ admins: [{ id: 'existing-admin' }],
+ earliest: 'user-1'
+ })
+
+ await reElectBootstrapAdmin()
+
+ expect(update).not.toHaveBeenCalled()
+ })
+
+ it('does nothing on an empty table', async () => {
+ const { update } = mockClaim({})
+
+ await reElectBootstrapAdmin()
+
+ expect(update).not.toHaveBeenCalled()
+ })
+
+ it('retries serialization failures and logs after exhausting attempts', async () => {
+ const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => {})
+ const { update } = mockClaim({ earliest: 'raced-signup' })
+ vi.mocked(db.transaction).mockRejectedValueOnce(
+ Object.assign(new Error('could not serialize'), { code: '40001' })
+ )
+ await expect(reElectBootstrapAdmin()).resolves.toBeUndefined()
+ expect(update).toHaveBeenCalled()
+ expect(errorSpy).not.toHaveBeenCalled()
+
+ vi.mocked(db.transaction).mockRejectedValue(new Error('boom'))
+ await expect(reElectBootstrapAdmin()).resolves.toBeUndefined()
+ expect(errorSpy).toHaveBeenCalledWith(
+ expect.stringContaining('Bootstrap admin re-election failed'),
+ expect.any(Error)
+ )
+
+ errorSpy.mockRestore()
+ })
+})
+
+describe('getSignUpMode', () => {
+ const original = process.env.AUTH_SIGNUP_MODE
+
+ afterEach(() => {
+ if (original === undefined) {
+ delete process.env.AUTH_SIGNUP_MODE
+ } else {
+ process.env.AUTH_SIGNUP_MODE = original
+ }
+ })
+
+ it('defaults to open when unset', () => {
+ delete process.env.AUTH_SIGNUP_MODE
+ expect(getSignUpMode()).toBe('open')
+ })
+
+ it('accepts open and invite (case-insensitive, trimmed)', () => {
+ process.env.AUTH_SIGNUP_MODE = ' invite '
+ expect(getSignUpMode()).toBe('invite')
+ process.env.AUTH_SIGNUP_MODE = 'Open'
+ expect(getSignUpMode()).toBe('open')
+ })
+
+ it('throws on an unsupported value instead of silently opening sign-ups', () => {
+ process.env.AUTH_SIGNUP_MODE = 'invte'
+ expect(() => getSignUpMode()).toThrow(/Invalid AUTH_SIGNUP_MODE/)
+ })
+})
+
+describe('isBootstrapAccount', () => {
+ const original = process.env.BOOTSTRAP_ADMIN_EMAIL
+
+ afterEach(() => {
+ if (original === undefined) {
+ delete process.env.BOOTSTRAP_ADMIN_EMAIL
+ } else {
+ process.env.BOOTSTRAP_ADMIN_EMAIL = original
+ }
+ })
+
+ it('is false when no gate is configured', async () => {
+ delete process.env.BOOTSTRAP_ADMIN_EMAIL
+ mockUserCount(0)
+ await expect(isBootstrapAccount('[email protected]')).resolves.toBe(false)
+ })
+
+ it('accepts the gated address while the table is empty', async () => {
+ process.env.BOOTSTRAP_ADMIN_EMAIL = '[email protected]'
+ mockUserCount(0)
+ await expect(isBootstrapAccount('[email protected]')).resolves.toBe(true)
+ })
+
+ it('matches the gate case-insensitively and trimmed', async () => {
+ process.env.BOOTSTRAP_ADMIN_EMAIL = ' [email protected] '
+ mockUserCount(0)
+ await expect(isBootstrapAccount('[email protected]')).resolves.toBe(true)
+ })
+
+ it('rejects other addresses', async () => {
+ process.env.BOOTSTRAP_ADMIN_EMAIL = '[email protected]'
+ mockUserCount(0)
+ await expect(isBootstrapAccount('[email protected]')).resolves.toBe(
+ false
+ )
+ })
+
+ it('is false once the bootstrap window closed', async () => {
+ process.env.BOOTSTRAP_ADMIN_EMAIL = '[email protected]'
+ mockUserCount(1)
+ await expect(isBootstrapAccount('[email protected]')).resolves.toBe(false)
+ })
+})
+
+describe('isBootstrapWindowOpen', () => {
+ const original = process.env.BOOTSTRAP_ADMIN_EMAIL
+
+ afterEach(() => {
+ if (original === undefined) {
+ delete process.env.BOOTSTRAP_ADMIN_EMAIL
+ } else {
+ process.env.BOOTSTRAP_ADMIN_EMAIL = original
+ }
+ })
+
+ it('is false when no gate is configured', async () => {
+ delete process.env.BOOTSTRAP_ADMIN_EMAIL
+ mockUserCount(0)
+ await expect(isBootstrapWindowOpen()).resolves.toBe(false)
+ })
+
+ it('is true while the gate is set and the table is empty', async () => {
+ process.env.BOOTSTRAP_ADMIN_EMAIL = '[email protected]'
+ mockUserCount(0)
+ await expect(isBootstrapWindowOpen()).resolves.toBe(true)
+ })
+
+ it('is false once the first account exists', async () => {
+ process.env.BOOTSTRAP_ADMIN_EMAIL = '[email protected]'
+ mockUserCount(1)
+ await expect(isBootstrapWindowOpen()).resolves.toBe(false)
+ })
+})
+
+describe('reset password mailer wiring', () => {
+ const original: Record<string, string | undefined> = {}
+
+ beforeEach(() => {
+ resetAuthInstance()
+ for (const key of [
+ 'SMTP_HOST',
+ 'SMTP_USER',
+ 'SMTP_PASSWORD',
+ 'BETTER_AUTH_URL'
+ ]) {
+ original[key] = process.env[key]
+ delete process.env[key]
+ }
+ })
+
+ afterEach(() => {
+ resetAuthInstance()
+ for (const [key, value] of Object.entries(original)) {
+ if (value === undefined) {
+ delete process.env[key]
+ } else {
+ process.env[key] = value
+ }
+ }
+ })
+
+ it('wires the reset mailer through the shared SMTP transport', () => {
+ process.env.SMTP_HOST = 'smtp.example.com'
+ process.env.SMTP_USER = 'user'
+ process.env.SMTP_PASSWORD = 'pass'
+
+ const auth = getAuth()
+
+ expect(typeof auth.options.emailAndPassword?.sendResetPassword).toBe(
+ 'function'
+ )
+ })
+
+ it('omits the reset mailer when SMTP is not configured', () => {
+ const auth = getAuth()
+
+ expect(auth.options.emailAndPassword?.sendResetPassword).toBeUndefined()
+ })
+
+ it('refuses to send a reset email without a canonical origin', async () => {
+ // Without BETTER_AUTH_URL the link could only be built from
+ // caller-controlled headers: the mailer must fail instead of
+ // delivering a live credential to a spoofed host.
+ process.env.SMTP_HOST = 'smtp.example.com'
+ process.env.SMTP_USER = 'user'
+ process.env.SMTP_PASSWORD = 'pass'
+
+ const auth = getAuth()
+ const sendResetPassword = auth.options.emailAndPassword?.sendResetPassword
+ expect(sendResetPassword).toBeDefined()
+
+ await expect(
+ sendResetPassword!({
+ user: { email: '[email protected]' },
+ url: 'http://localhost:3000/api/auth/reset-password/tok',
+ token: 'tok'
+ } as never)
+ ).rejects.toThrow('BETTER_AUTH_URL')
+ expect(sendSmtpMail).not.toHaveBeenCalled()
+ })
+
+ it('links the in-app reset page instead of better-auth unmounted endpoint', async () => {
+ // better-auth's own /api/auth/reset-password/:token handler is not
+ // mounted, so its generated url would 404; the email must carry the
+ // raw token to the in-app page instead.
+ process.env.SMTP_HOST = 'smtp.example.com'
+ process.env.SMTP_USER = 'user'
+ process.env.SMTP_PASSWORD = 'pass'
+ process.env.BETTER_AUTH_URL = 'http://localhost:3000/'
+
+ const auth = getAuth()
+ const sendResetPassword = auth.options.emailAndPassword?.sendResetPassword
+ expect(sendResetPassword).toBeDefined()
+
+ await sendResetPassword!({
+ user: { email: '[email protected]' },
+ url: 'http://localhost:3000/api/auth/reset-password/tok?callbackURL=x',
+ token: 'tok'
+ } as never)
+
+ expect(sendSmtpMail).toHaveBeenCalledWith(
+ expect.objectContaining({
+ text: expect.stringContaining(
+ 'http://localhost:3000/auth/update-password?token=tok'
+ )
+ })
+ )
+ })
+})
+
+describe('auth secret', () => {
+ beforeEach(() => {
+ resetAuthInstance()
+ })
+
+ afterEach(() => {
+ resetAuthInstance()
+ vi.unstubAllEnvs()
+ })
+
+ it('throws in production when BETTER_AUTH_SECRET is missing', () => {
+ vi.stubEnv('NODE_ENV', 'production')
+ vi.stubEnv('BETTER_AUTH_SECRET', undefined)
+
+ expect(() => getAuth()).toThrow(/BETTER_AUTH_SECRET/)
+ })
+
+ it('uses the configured secret in production', () => {
+ vi.stubEnv('NODE_ENV', 'production')
+ vi.stubEnv('BETTER_AUTH_SECRET', 'a'.repeat(32))
+
+ expect(() => getAuth()).not.toThrow()
+ })
+
+ it('falls back to the development secret outside production', () => {
+ vi.stubEnv('NODE_ENV', 'test')
+ vi.stubEnv('BETTER_AUTH_SECRET', undefined)
+
+ expect(() => getAuth()).not.toThrow()
+ })
+})
diff --git a/lib/auth/better-auth/__tests__/invitations.test.ts b/lib/auth/better-auth/__tests__/invitations.test.ts
new file mode 100644
index 00000000..f6ab6148
--- /dev/null
+++ b/lib/auth/better-auth/__tests__/invitations.test.ts
@@ -0,0 +1,169 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest'
+
+import {
+ consumeInvitation,
+ createInvitation,
+ hashInvitationToken,
+ hasRecentBootstrapInvitation,
+ releaseInvitation,
+ revokeInvitation,
+ validateInvitation
+} from '@/lib/auth/better-auth/invitations'
+import { db } from '@/lib/db'
+
+const { state } = vi.hoisted(() => ({
+ state: { rows: [] as unknown[] }
+}))
+
+vi.mock('@/lib/db', () => ({
+ db: {
+ select: vi.fn(() => ({
+ from: vi.fn(() => ({
+ where: vi.fn(() => Promise.resolve(state.rows))
+ }))
+ })),
+ insert: vi.fn(() => ({
+ values: vi.fn(() => ({
+ returning: vi.fn(() => Promise.resolve(state.rows))
+ }))
+ })),
+ update: vi.fn(() => ({
+ set: vi.fn(() => ({
+ where: vi.fn(() => ({
+ returning: vi.fn(() => Promise.resolve(state.rows))
+ }))
+ }))
+ }))
+ }
+}))
+
+function activeInvitation(overrides: Record<string, unknown> = {}) {
+ return {
+ id: 'inv-1',
+ email: '[email protected]',
+ token: 'tok',
+ invitedBy: 'admin-1',
+ revokedAt: null,
+ usedAt: null,
+ expiresAt: new Date(Date.now() + 60_000),
+ createdAt: new Date(),
+ ...overrides
+ }
+}
+
+describe('invitations', () => {
+ beforeEach(() => {
+ state.rows = []
+ vi.clearAllMocks()
+ })
+
+ describe('validateInvitation', () => {
+ it('returns null for a missing token', async () => {
+ await expect(validateInvitation(undefined)).resolves.toBeNull()
+ await expect(validateInvitation('')).resolves.toBeNull()
+ expect(db.select).not.toHaveBeenCalled()
+ })
+
+ it('returns null when no active row matches (missing or revoked)', async () => {
+ // Revoked tokens are filtered out by the query (isNull(revokedAt))
+ state.rows = []
+
+ await expect(validateInvitation('revoked-or-missing')).resolves.toBeNull()
+ })
+
+ it('returns the invitation when valid', async () => {
+ state.rows = [activeInvitation()]
+
+ const invitation = await validateInvitation('tok')
+
+ expect(invitation).toMatchObject({ id: 'inv-1', token: 'tok' })
+ })
+
+ it('returns null for an expired invitation', async () => {
+ state.rows = [
+ activeInvitation({ expiresAt: new Date(Date.now() - 1000) })
+ ]
+
+ await expect(validateInvitation('tok')).resolves.toBeNull()
+ })
+
+ it('returns null for an already used invitation', async () => {
+ state.rows = [activeInvitation({ usedAt: new Date() })]
+
+ await expect(validateInvitation('tok')).resolves.toBeNull()
+ })
+ })
+
+ describe('hashInvitationToken', () => {
+ it('returns the SHA-256 hex digest of the token', () => {
+ expect(hashInvitationToken('')).toBe(
+ 'e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855'
+ )
+ })
+ })
+
+ describe('createInvitation', () => {
+ it('inserts a hashed token and returns the plaintext once', async () => {
+ state.rows = [activeInvitation()]
+
+ const { invitation, token } = await createInvitation({
+ invitedBy: 'admin-1',
+ })
+
+ expect(invitation.id).toBe('inv-1')
+ expect(token).toMatch(/^[0-9a-f]{48}$/)
+ expect(db.insert).toHaveBeenCalled()
+ })
+ })
+
+ describe('revokeInvitation', () => {
+ it('reports success when a row was revoked', async () => {
+ state.rows = [{ id: 'inv-1' }]
+ await expect(revokeInvitation('inv-1')).resolves.toBe(true)
+ })
+
+ it('reports failure when nothing matched', async () => {
+ state.rows = []
+ await expect(revokeInvitation('missing')).resolves.toBe(false)
+ })
+ })
+
+ describe('consumeInvitation', () => {
+ it('consumes an unconsumed invitation', async () => {
+ state.rows = [{ id: 'inv-1' }]
+ await expect(consumeInvitation('inv-1')).resolves.toBe(true)
+ })
+
+ it('fails when already consumed', async () => {
+ state.rows = []
+ await expect(consumeInvitation('inv-1')).resolves.toBe(false)
+ })
+ })
+
+ describe('releaseInvitation', () => {
+ it('clears the used marker so the same link can be retried', async () => {
+ state.rows = [{ id: 'inv-1' }]
+ await expect(releaseInvitation('inv-1')).resolves.toBeUndefined()
+ expect(db.update).toHaveBeenCalled()
+ })
+ })
+})
+
+describe('hasRecentBootstrapInvitation', () => {
+ it('is true when a live bootstrap invitation row exists', async () => {
+ state.rows = [{ id: 'inv-1' }]
+
+ await expect(
+ hasRecentBootstrapInvitation('[email protected]', 15 * 60 * 1000)
+ ).resolves.toBe(true)
+ })
+
+ it('is false when no row matches', async () => {
+ state.rows = []
+
+ await expect(
+ hasRecentBootstrapInvitation('[email protected]', 15 * 60 * 1000)
+ ).resolves.toBe(false)
+ })
+})
diff --git a/lib/auth/better-auth/config.ts b/lib/auth/better-auth/config.ts
new file mode 100644
index 00000000..69ee9461
--- /dev/null
+++ b/lib/auth/better-auth/config.ts
@@ -0,0 +1,327 @@
+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 { asc, count, eq, sql } from 'drizzle-orm'
+
+import { db } from '@/lib/db'
+
+import { isSmtpConfigured, sendSmtpMail } from './mailer'
+import * as authSchema from './schema'
+
+export type SignUpMode = 'open' | 'invite'
+
+/**
+ * Password reset and invitation emails require SMTP. The `passwordReset`
+ * capability of the better-auth provider is gated on this at runtime.
+ */
+export function isBetterAuthSmtpConfigured(): boolean {
+ return isSmtpConfigured()
+}
+
+/**
+ * Canonical origin for absolute links delivered by email. Never derived
+ * from request headers: `Origin` and `x-forwarded-host` are caller-
+ * controlled, and a spoofed value would deliver a valid one-time
+ * credential to an attacker domain (host-header injection). Deployments
+ * that deliver email must set `BETTER_AUTH_URL`.
+ */
+export function getEmailLinkOrigin(): string {
+ return (process.env.BETTER_AUTH_URL ?? '').trim().replace(/\/+$/, '')
+}
+
+export function getSignUpMode(): SignUpMode {
+ const raw = process.env.AUTH_SIGNUP_MODE?.trim().toLowerCase()
+ if (!raw) {
+ return 'open' // documented default
+ }
+ if (raw === 'open' || raw === 'invite') {
+ return raw
+ }
+ // A typo must not silently open an invite-only instance to the internet:
+ // fail loudly instead of guessing (same policy as BETTER_AUTH_SECRET).
+ throw new Error(
+ `Invalid AUTH_SIGNUP_MODE "${process.env.AUTH_SIGNUP_MODE}". ` +
+ 'Expected "open" or "invite".'
+ )
+}
+
+function getSecret(): string {
+ const secret = process.env.BETTER_AUTH_SECRET?.trim()
+ if (secret) {
+ return secret
+ }
+ if (process.env.NODE_ENV === 'production') {
+ // Never fall back to a publicly known secret in production: better-auth
+ // must fail fast instead of silently signing with a shared default.
+ throw new Error(
+ 'BETTER_AUTH_SECRET must be set when running AUTH_PROVIDER=better-auth.'
+ )
+ }
+ if (process.env.NODE_ENV !== 'test') {
+ console.warn(
+ '⚠️ BETTER_AUTH_SECRET is not set. Using an insecure development ' +
+ 'secret. Set BETTER_AUTH_SECRET to a stable random value.'
+ )
+ }
+ return 'morphic-better-auth-development-secret'
+}
+
+/**
+ * Sign-up gate for the bootstrap window: while the user table is empty and
+ * `BOOTSTRAP_ADMIN_EMAIL` is set, only that address may sign up. The admin
+ * role itself is granted by `claimBootstrapAdmin` once the row exists.
+ */
+export async function applyBootstrapAdminGate(data: {
+ email?: string
+}): Promise<void> {
+ const [existing] = await db.select({ total: count() }).from(authSchema.user)
+
+ if ((existing?.total ?? 0) > 0) {
+ return // Bootstrap window is closed
+ }
+
+ const gate = process.env.BOOTSTRAP_ADMIN_EMAIL?.trim().toLowerCase()
+ if (gate && data.email?.trim().toLowerCase() !== gate) {
+ throw new APIError('FORBIDDEN', {
+ message:
+ 'Sign-up is restricted to the configured BOOTSTRAP_ADMIN_EMAIL address.'
+ })
+ }
+}
+
+/**
+ * True while the bootstrap window is open: `BOOTSTRAP_ADMIN_EMAIL` is set
+ * and the user table is still empty. The sign-up page uses this to render
+ * the form (without a token) on a fresh invite-only instance; the address
+ * itself is enforced by `applyBootstrapAdminGate` at creation time.
+ */
+export async function isBootstrapWindowOpen(): Promise<boolean> {
+ if (!process.env.BOOTSTRAP_ADMIN_EMAIL?.trim()) {
+ return false
+ }
+ const [existing] = await db.select({ total: count() }).from(authSchema.user)
+ return (existing?.total ?? 0) === 0
+}
+
+/**
+ * True when the email is the seed administrator of a fresh instance:
+ * `BOOTSTRAP_ADMIN_EMAIL` is set, the address matches, and the user table
+ * is still empty. Invite-only instances use this to let the first admin
+ * sign up without an invitation — creating invitations requires an admin,
+ * so the instance would otherwise have no way to bootstrap.
+ */
+export async function isBootstrapAccount(email: string): Promise<boolean> {
+ const gate = process.env.BOOTSTRAP_ADMIN_EMAIL?.trim().toLowerCase()
+ if (!gate || email.trim().toLowerCase() !== gate) {
+ return false
+ }
+ return isBootstrapWindowOpen()
+}
+
+/**
+ * Runs an admin-election transaction with retries. A serialization
+ * failure (SQLSTATE 40001) does not by itself prove a concurrent
+ * claimant committed: both transactions can abort. Retry it like any
+ * other transient failure — a real winner shows up as an existing admin
+ * on the next attempt, and if nobody won the retry completes the
+ * election instead of stranding the instance without an admin.
+ */
+async function withElectionRetry(
+ label: string,
+ run: () => Promise<void>
+): Promise<void> {
+ // Bounded on purpose: the hook runs inside the sign-up (or deletion)
+ // request after the account work already committed, so retrying
+ // forever would hang the response indefinitely. The window is short
+ // but covers transient blips; exhaustion is a repair-needed condition
+ // logged loudly — the election is deterministic, so a single manual
+ // promotion restores the invariant.
+ const maxAttempts = 6
+ for (let attempt = 1; ; attempt++) {
+ try {
+ await run()
+ return
+ } catch (error) {
+ if (attempt >= maxAttempts) {
+ console.error(
+ `${label} failed after ${maxAttempts} attempts — repair needed. ` +
+ 'If the instance is now without an admin, promote the intended ' +
+ `account directly: UPDATE "user" SET role = 'admin' ` +
+ "WHERE id = '<account id>'. Later sign-ups cannot take the " +
+ 'claim because the election requires the earliest account.',
+ error
+ )
+ return
+ }
+ await new Promise(resolve =>
+ setTimeout(resolve, Math.min(100 * 2 ** (attempt - 1), 500))
+ )
+ }
+ }
+}
+
+/**
+ * Grant the admin role to the very first account.
+ *
+ * The after-create hook runs in its own transaction once the sign-up has
+ * committed, so two concurrent first sign-ups can each observe the other's
+ * committed row: a "no other user exists" condition would make both decline
+ * and leave the instance without any admin. The claim is therefore a
+ * deterministic election — the role goes to the earliest account (createdAt,
+ * tie-broken by id) whenever no admin exists. Exactly one of any set of
+ * concurrent sign-ups can be the earliest, so exactly one account claims the
+ * role regardless of interleaving.
+ *
+ * "No admin exists" alone would allow escalation: if the sole admin later
+ * deletes their account while regular members remain, the next registrant
+ * must not inherit the role — and it cannot be the earliest account, so the
+ * election declines it. Re-bootstrapping then requires removing every
+ * account (the bootstrap window reopens with an empty table) or promoting a
+ * successor directly in the database.
+ */
+export async function claimBootstrapAdmin(userId: string): Promise<void> {
+ // A transient failure here (e.g. the connection drops after the user
+ // insert already committed) must not strand the instance without an
+ // admin: the earliest-account guard means no later sign-up can take the
+ // claim over, so retry before giving up.
+ await withElectionRetry('Bootstrap admin claim', () =>
+ db.transaction(async tx => {
+ await tx.execute(sql`set transaction isolation level serializable`)
+ const [admin] = await tx
+ .select({ id: authSchema.user.id })
+ .from(authSchema.user)
+ .where(eq(authSchema.user.role, 'admin'))
+ .limit(1)
+ if (admin) {
+ return // An admin exists: the bootstrap window is closed
+ }
+ const [earliest] = await tx
+ .select({ id: authSchema.user.id })
+ .from(authSchema.user)
+ .orderBy(asc(authSchema.user.createdAt), asc(authSchema.user.id))
+ .limit(1)
+ if (earliest?.id !== userId) {
+ return // Not the earliest account: another sign-up owns the claim
+ }
+ await tx
+ .update(authSchema.user)
+ .set({ role: 'admin' })
+ .where(eq(authSchema.user.id, userId))
+ })
+ )
+}
+
+/**
+ * Completes the bootstrap election after the last admin account is
+ * deleted. A sign-up that commits while the deletion is in flight sees
+ * the admin row in its own claim and declines; the deletion's locked
+ * count in turn cannot see the uncommitted insert. Running the election
+ * again after the deletion commits closes the window: the sign-up's
+ * claim runs after its insert commits and the re-election runs after
+ * the deletion commits, so neither can miss the other without a
+ * timestamp cycle — at least one of them observes both states and the
+ * earliest account takes the role.
+ */
+export async function reElectBootstrapAdmin(): Promise<void> {
+ await withElectionRetry('Bootstrap admin re-election', () =>
+ db.transaction(async tx => {
+ await tx.execute(sql`set transaction isolation level serializable`)
+ const [admin] = await tx
+ .select({ id: authSchema.user.id })
+ .from(authSchema.user)
+ .where(eq(authSchema.user.role, 'admin'))
+ .limit(1)
+ if (admin) {
+ return // An admin exists: nothing to re-elect
+ }
+ const [earliest] = await tx
+ .select({ id: authSchema.user.id })
+ .from(authSchema.user)
+ .orderBy(asc(authSchema.user.createdAt), asc(authSchema.user.id))
+ .limit(1)
+ if (!earliest) {
+ return // Empty table: the bootstrap window is the recovery path
+ }
+ await tx
+ .update(authSchema.user)
+ .set({ role: 'admin' })
+ .where(eq(authSchema.user.id, earliest.id))
+ })
+ )
+}
+
+function createAuth() {
+ const smtpConfigured = isBetterAuthSmtpConfigured()
+
+ return betterAuth({
+ appName: 'Morphic',
+ secret: getSecret(),
+ database: drizzleAdapter(db, { provider: 'pg', schema: authSchema }),
+ emailAndPassword: {
+ enabled: true,
+ // better-auth 1.7 removed the built-in nodemailer transport: without
+ // this callback, requestPasswordReset fails with RESET_PASSWORD_DISABLED
+ // even when the SMTP variables are present. Morphic does not use email
+ // verification, so this is the only email better-auth delivers;
+ // invitation mail goes through lib/actions/admin.ts.
+ sendResetPassword: smtpConfigured
+ ? 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.
+ // Link the in-app page directly with the raw token instead; it
+ // resets the password through the provider's server action.
+ const origin = getEmailLinkOrigin()
+ if (!origin) {
+ // Without a canonical origin the link could only be built
+ // from caller-controlled headers: fail loudly rather than
+ // deliver a live credential to the wrong host.
+ throw new Error(
+ 'BETTER_AUTH_URL must be set to deliver password reset emails'
+ )
+ }
+ const link = `${origin}/auth/update-password?token=${token}`
+ await sendSmtpMail({
+ to: user.email,
+ subject: 'Reset your Morphic password',
+ text: `Use this link to reset your password (valid for one hour): ${link}`,
+ html: `<p>Use this link to reset your password (valid for one hour):</p><p><a href="${link}">Reset password</a></p>`
+ })
+ }
+ : 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()],
+ databaseHooks: {
+ user: {
+ create: {
+ before: async user => applyBootstrapAdminGate(user),
+ after: async user => {
+ await claimBootstrapAdmin(user.id)
+ }
+ }
+ }
+ }
+ })
+}
+
+export type BetterAuth = ReturnType<typeof createAuth>
+
+let authInstance: BetterAuth | null = null
+
+/** Lazily create the shared Better Auth instance. */
+export function getAuth(): BetterAuth {
+ if (!authInstance) {
+ authInstance = createAuth()
+ }
+ return authInstance
+}
+
+/** Test seam: reset the memoized instance after changing env vars. */
+export function resetAuthInstance(): void {
+ authInstance = null
+}
diff --git a/lib/auth/better-auth/invitations.ts b/lib/auth/better-auth/invitations.ts
new file mode 100644
index 00000000..66896cf7
--- /dev/null
+++ b/lib/auth/better-auth/invitations.ts
@@ -0,0 +1,176 @@
+import { createHash, randomBytes } from 'crypto'
+import { and, desc, eq, gt, isNull } from 'drizzle-orm'
+
+import { db } from '@/lib/db'
+
+import { invitations } from './schema'
+
+/** Invitation tokens are valid for one week by default. */
+export const INVITATION_TTL_MS = 7 * 24 * 60 * 60 * 1000
+
+export interface InvitationRecord {
+ id: string
+ email: string | null
+ token: string
+ invitedBy: string
+ revokedAt: Date | null
+ usedAt: Date | null
+ expiresAt: Date
+ createdAt: Date
+}
+
+function toDate(value: Date | string | null): Date | null {
+ if (value === null || value === undefined) return null
+ return value instanceof Date ? value : new Date(value)
+}
+
+function toRecord(row: typeof invitations.$inferSelect): InvitationRecord {
+ return {
+ ...row,
+ revokedAt: toDate(row.revokedAt),
+ usedAt: toDate(row.usedAt),
+ expiresAt: toDate(row.expiresAt)!,
+ createdAt: toDate(row.createdAt)!
+ }
+}
+
+export function generateInvitationToken(): string {
+ return randomBytes(24).toString('hex')
+}
+
+/**
+ * Invitation tokens are stored as SHA-256 hashes. The plaintext token only
+ * exists in the link handed to the admin at creation time, so a database
+ * leak cannot be replayed as valid invitations.
+ */
+export function hashInvitationToken(token: string): string {
+ return createHash('sha256').update(token).digest('hex')
+}
+
+export async function createInvitation(params: {
+ invitedBy: string
+ email: string
+ ttlMs?: number
+}): Promise<{ invitation: InvitationRecord; token: string }> {
+ const token = generateInvitationToken()
+ const [row] = await db
+ .insert(invitations)
+ .values({
+ token: hashInvitationToken(token),
+ email: params.email,
+ invitedBy: params.invitedBy,
+ expiresAt: new Date(Date.now() + (params.ttlMs ?? INVITATION_TTL_MS))
+ })
+ .returning()
+
+ return { invitation: toRecord(row), token }
+}
+
+export async function listInvitations(): Promise<InvitationRecord[]> {
+ const rows = await db
+ .select()
+ .from(invitations)
+ .orderBy(desc(invitations.createdAt))
+
+ return rows.map(toRecord)
+}
+
+/**
+ * True when a live bootstrap invitation for the address was created within
+ * the cooldown window. The bootstrap branch runs before better-auth's rate
+ * limiter, so without this a caller who knows the gated address could loop
+ * the sign-up action to flood the mailbox and the table with admin links.
+ */
+export async function hasRecentBootstrapInvitation(
+ email: string,
+ cooldownMs: number
+): Promise<boolean> {
+ const [existing] = await db
+ .select({ id: invitations.id })
+ .from(invitations)
+ .where(
+ and(
+ eq(invitations.email, email),
+ eq(invitations.invitedBy, 'bootstrap'),
+ isNull(invitations.usedAt),
+ isNull(invitations.revokedAt),
+ gt(invitations.expiresAt, new Date()),
+ gt(invitations.createdAt, new Date(Date.now() - cooldownMs))
+ )
+ )
+
+ return Boolean(existing)
+}
+
+/**
+ * Resolve an invitation token. Returns the invitation only when it exists,
+ * is not revoked, not already used, and not expired.
+ */
+export async function validateInvitation(
+ token: string | null | undefined
+): Promise<InvitationRecord | null> {
+ if (!token) {
+ return null
+ }
+
+ const [row] = await db
+ .select()
+ .from(invitations)
+ .where(
+ and(
+ eq(invitations.token, hashInvitationToken(token)),
+ isNull(invitations.revokedAt)
+ )
+ )
+
+ if (!row) {
+ return null
+ }
+
+ const invitation = toRecord(row)
+ if (invitation.usedAt || invitation.expiresAt.getTime() <= Date.now()) {
+ return null
+ }
+
+ return invitation
+}
+
+export async function revokeInvitation(id: string): Promise<boolean> {
+ const [row] = await db
+ .update(invitations)
+ .set({ revokedAt: new Date() })
+ .where(and(eq(invitations.id, id), isNull(invitations.revokedAt)))
+ .returning({ id: invitations.id })
+
+ return Boolean(row)
+}
+
+/** Marks an invitation as consumed. Returns false if already consumed. */
+export async function consumeInvitation(id: string): Promise<boolean> {
+ const [row] = await db
+ .update(invitations)
+ .set({ usedAt: new Date() })
+ .where(
+ and(
+ eq(invitations.id, id),
+ isNull(invitations.usedAt),
+ isNull(invitations.revokedAt)
+ )
+ )
+ .returning({ id: invitations.id })
+
+ return Boolean(row)
+}
+
+/**
+ * Undoes a consumption so the same link can be redeemed again. Used when the
+ * sign-up the claim enabled failed before creating the account (e.g. the
+ * password was rejected), so a corrected retry does not need a fresh link.
+ * The address binding and expiry still apply.
+ */
+export async function releaseInvitation(id: string): Promise<void> {
+ await db
+ .update(invitations)
+ .set({ usedAt: null })
+ .where(and(eq(invitations.id, id), isNull(invitations.revokedAt)))
+}
diff --git a/lib/auth/better-auth/mailer.ts b/lib/auth/better-auth/mailer.ts
new file mode 100644
index 00000000..d6102a60
--- /dev/null
+++ b/lib/auth/better-auth/mailer.ts
@@ -0,0 +1,36 @@
+import nodemailer from 'nodemailer'
+
+/**
+ * Shared SMTP plumbing for every email Morphic's better-auth provider
+ * delivers (password resets, invitation emails). better-auth 1.7 removed
+ * its built-in nodemailer transport, so the `email.server` option no
+ * longer sends anything; delivery goes through the callbacks in
+ * lib/auth/better-auth/config.ts, which call into here.
+ */
+export function isSmtpConfigured(): boolean {
+ return Boolean(
+ process.env.SMTP_HOST && process.env.SMTP_USER && process.env.SMTP_PASSWORD
+ )
+}
+
+export async function sendSmtpMail(message: {
+ to: string
+ subject: string
+ text: string
+ html?: string
+}): Promise<void> {
+ const transporter = nodemailer.createTransport({
+ host: process.env.SMTP_HOST,
+ port: Number(process.env.SMTP_PORT ?? 587),
+ secure: process.env.SMTP_SECURE === 'true',
+ auth: {
+ user: process.env.SMTP_USER,
+ pass: process.env.SMTP_PASSWORD
+ }
+ })
+
+ await transporter.sendMail({
+ from: process.env.EMAIL_FROM ?? 'Morphic <[email protected]>',
+ ...message
+ })
+}
diff --git a/lib/auth/better-auth/members.ts b/lib/auth/better-auth/members.ts
new file mode 100644
index 00000000..b370b29e
--- /dev/null
+++ b/lib/auth/better-auth/members.ts
@@ -0,0 +1,31 @@
+import { asc } from 'drizzle-orm'
+
+import { db } from '@/lib/db'
+
+import { user } from './schema'
+
+export interface MemberSummary {
+ id: string
+ email: string
+ name: string | null
+ role: string | null
+}
+
+export async function listMembers(): Promise<MemberSummary[]> {
+ const rows = await db
+ .select({
+ id: user.id,
+ email: user.email,
+ name: user.name,
+ role: user.role
+ })
+ .from(user)
+ .orderBy(asc(user.createdAt))
+
+ return rows.map(row => ({
+ id: row.id,
+ email: row.email,
+ name: row.name ?? null,
+ role: row.role ?? null
+ }))
+}
diff --git a/lib/auth/better-auth/schema.ts b/lib/auth/better-auth/schema.ts
new file mode 100644
index 00000000..783af8fc
--- /dev/null
+++ b/lib/auth/better-auth/schema.ts
@@ -0,0 +1,82 @@
+import { createId } from '@paralleldrive/cuid2'
+import { boolean, pgTable, text, timestamp } from 'drizzle-orm/pg-core'
+
+/**
+ * Better Auth core tables (`user`, `session`, `account`, `verification`)
+ * stored in the application's own Postgres via Better Auth's Drizzle adapter.
+ * Column names follow Better Auth's canonical Postgres schema; the admin
+ * plugin adds `role`, `banned`, `banReason`, and `banExpires` to `user`.
+ */
+export const user = pgTable('user', {
+ id: text('id').primaryKey(),
+ name: text('name').notNull(),
+ email: text('email').notNull().unique(),
+ emailVerified: boolean('email_verified').default(false).notNull(),
+ image: text('image'),
+ role: text('role').default('user'),
+ banned: boolean('banned').default(false),
+ banReason: text('ban_reason'),
+ banExpires: timestamp('ban_expires'),
+ createdAt: timestamp('created_at').defaultNow().notNull(),
+ updatedAt: timestamp('updated_at').defaultNow().notNull()
+})
+
+export const session = pgTable('session', {
+ id: text('id').primaryKey(),
+ expiresAt: timestamp('expires_at').notNull(),
+ token: text('token').notNull().unique(),
+ createdAt: timestamp('created_at').notNull(),
+ updatedAt: timestamp('updated_at').notNull(),
+ ipAddress: text('ip_address'),
+ userAgent: text('user_agent'),
+ impersonatedBy: text('impersonated_by'),
+ userId: text('user_id')
+ .notNull()
+ .references(() => user.id, { onDelete: 'cascade' })
+})
+
+export const account = pgTable('account', {
+ id: text('id').primaryKey(),
+ accountId: text('account_id').notNull(),
+ providerId: text('provider_id').notNull(),
+ userId: text('user_id')
+ .notNull()
+ .references(() => user.id, { onDelete: 'cascade' }),
+ accessToken: text('access_token'),
+ refreshToken: text('refresh_token'),
+ idToken: text('id_token'),
+ accessTokenExpiresAt: timestamp('access_token_expires_at'),
+ refreshTokenExpiresAt: timestamp('refresh_token_expires_at'),
+ scope: text('scope'),
+ password: text('password'),
+ createdAt: timestamp('created_at').notNull(),
+ updatedAt: timestamp('updated_at').notNull()
+})
+
+export const verification = pgTable('verification', {
+ id: text('id').primaryKey(),
+ identifier: text('identifier').notNull(),
+ value: text('value').notNull(),
+ expiresAt: timestamp('expires_at').notNull(),
+ createdAt: timestamp('created_at'),
+ updatedAt: timestamp('updated_at')
+})
+
+/**
+ * Invitation tokens used when `AUTH_SIGNUP_MODE=invite`. An invitation is
+ * redeemable when it is neither revoked, expired, nor already used.
+ */
+export const invitations = pgTable('invitations', {
+ id: text('id')
+ .primaryKey()
+ .$defaultFn(() => createId()),
+ email: text('email'),
+ // SHA-256 hash of the invitation token; the plaintext only exists in the
+ // link returned to the admin at creation time.
+ token: text('token').notNull().unique(),
+ invitedBy: text('invited_by').notNull(),
+ revokedAt: timestamp('revoked_at'),
+ usedAt: timestamp('used_at'),
+ expiresAt: timestamp('expires_at').notNull(),
+ createdAt: timestamp('created_at').defaultNow().notNull()
+})
diff --git a/lib/auth/provider.ts b/lib/auth/provider.ts
index 47356591..de9a7b00 100644
--- a/lib/auth/provider.ts
+++ b/lib/auth/provider.ts
@@ -1,6 +1,11 @@
+import { betterAuthProvider } from '@/lib/auth/providers/better-auth'
import { noneAuthProvider } from '@/lib/auth/providers/none'
import { supabaseAuthProvider } from '@/lib/auth/providers/supabase'
-import type { AuthProvider, AuthProviderName } from '@/lib/auth/types'
+import type {
+ AuthCapabilities,
+ AuthProvider,
+ AuthProviderName
+} from '@/lib/auth/types'
const AUTH_PROVIDER_NAMES: AuthProviderName[] = [
'supabase',
@@ -8,10 +13,10 @@ const AUTH_PROVIDER_NAMES: AuthProviderName[] = [
'none'
]
-// Providers register here as they ship. `better-auth` is an accepted
-// configuration value reserved for a follow-up release.
+// Providers register here as they ship.
const providerRegistry: Partial<Record<AuthProviderName, AuthProvider>> = {
supabase: supabaseAuthProvider,
+ 'better-auth': betterAuthProvider,
none: noneAuthProvider
}
@@ -33,6 +38,43 @@ function enforceCloudDeploymentGuard(
)
}
+/**
+ * Whether sharing is enabled. ENABLE_SHARE is the runtime (non-public)
+ * flag and works in prebuilt images; NEXT_PUBLIC_ENABLE_SHARE is kept for
+ * source builds, but Next inlines NEXT_PUBLIC_* at build time even in
+ * server bundles, so it cannot be flipped at runtime in a published
+ * image. shareChat enforces the same helper server-side.
+ */
+export function isShareEnabled(): boolean {
+ return (
+ process.env.ENABLE_SHARE === 'true' ||
+ process.env.NEXT_PUBLIC_ENABLE_SHARE === 'true'
+ )
+}
+
+/**
+ * Fold the sharing opt-in flag into a provider's capabilities. Must be
+ * evaluated on the server: client components inline NEXT_PUBLIC_* values
+ * at build time, which would freeze the setting in prebuilt images.
+ * shareChat enforces the same rule server-side.
+ *
+ * The opt-in applies to Better Auth only: Supabase deployments have
+ * always shared without an env var, and anonymous mode has no sharing
+ * capability to fold into.
+ */
+export function withShareOptIn(
+ capabilities: AuthCapabilities,
+ providerName: AuthProviderName
+): AuthCapabilities {
+ if (providerName !== 'better-auth') {
+ return capabilities
+ }
+ return {
+ ...capabilities,
+ share: capabilities.share && isShareEnabled()
+ }
+}
+
/**
* Resolve the active auth provider name from configuration.
*
diff --git a/lib/auth/providers/better-auth.ts b/lib/auth/providers/better-auth.ts
new file mode 100644
index 00000000..bd2f0153
--- /dev/null
+++ b/lib/auth/providers/better-auth.ts
@@ -0,0 +1,617 @@
+import { headers } from 'next/headers'
+import { type NextRequest, NextResponse } from 'next/server'
+
+import { count, eq } from 'drizzle-orm'
+
+import {
+ getAuth,
+ getEmailLinkOrigin,
+ getSignUpMode,
+ isBetterAuthSmtpConfigured,
+ isBootstrapAccount,
+ reElectBootstrapAdmin
+} from '@/lib/auth/better-auth/config'
+import {
+ consumeInvitation,
+ createInvitation,
+ hasRecentBootstrapInvitation,
+ releaseInvitation,
+ revokeInvitation,
+ validateInvitation
+} from '@/lib/auth/better-auth/invitations'
+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 { getRequestOrigin } from '@/lib/auth/request'
+import type {
+ AppUser,
+ AuthActionResult,
+ AuthProvider,
+ AuthTransaction,
+ DeletionGuardResult
+} from '@/lib/auth/types'
+import { db } from '@/lib/db'
+
+/**
+ * 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
+ * committed the user) may safely release the invitation claim.
+ */
+async function accountExists(email: string): Promise<boolean> {
+ try {
+ const [row] = await db
+ .select({ id: authUser.id })
+ .from(authUser)
+ .where(eq(authUser.email, email))
+ .limit(1)
+ return Boolean(row)
+ } catch {
+ // Uncertain: prefer leaving the claim consumed over re-enabling a link
+ // that may already have been redeemed.
+ return true
+ }
+}
+
+const LAST_ADMIN_ERROR =
+ 'You are the only admin. Promote another member to admin before deleting this account.'
+
+/**
+ * The last-admin invariant, evaluated against db (unlocked UX gate) or a
+ * transaction (authoritative check). When lock is set the admin listing
+ * uses SELECT ... FOR UPDATE, so concurrent deletions serialize on the
+ * admin rows until the owning transaction commits. A concurrent sign-up
+ * inserts a new row, which does not conflict with the admin-row locks,
+ * so its insert can commit just after the user count below; the
+ * post-commit re-election (postDeletion) covers that case.
+ */
+async function deletionGuard(
+ q: Pick<typeof db, 'select' | 'delete'>,
+ userId: string,
+ lock: boolean
+): Promise<DeletionGuardResult> {
+ // The admin listing is locked first, before the target is classified:
+ // locking each own target first would let two concurrent admin
+ // deletions each hold the row the other needs, deadlocking. When
+ // every guard requests the shared admin set as its first lock, the
+ // second deletion simply waits for the first scan to commit.
+ const adminsQuery = q
+ .select({ id: authUser.id })
+ .from(authUser)
+ .where(eq(authUser.role, 'admin'))
+ const admins = lock ? await adminsQuery.for('update') : await adminsQuery
+
+ // The target row is then locked before its role is read: a concurrent
+ // promotion must not let a soon-to-be-admin slip past the last-admin
+ // guard while its own deletion is already in flight.
+ const targetQuery = q
+ .select({ role: authUser.role })
+ .from(authUser)
+ .where(eq(authUser.id, userId))
+ .limit(1)
+ const [target] = lock ? await targetQuery.for('update') : await targetQuery
+ const wasAdmin = target?.role === 'admin'
+ if (!wasAdmin) {
+ return { error: null, wasAdmin: false }
+ }
+ if (admins.length > 1) {
+ return { error: null, wasAdmin }
+ }
+ // Last admin: deletion is only refused while other users remain.
+ // Members left without an admin have no in-product path back, but an
+ // empty user table is the documented re-bootstrap state, so the sole
+ // account of a single-user instance must be able to delete itself.
+ const [userCount] = await q.select({ n: count() }).from(authUser)
+ if ((userCount?.n ?? 0) <= 1) {
+ return { error: null, wasAdmin }
+ }
+ return { error: LAST_ADMIN_ERROR, wasAdmin }
+}
+
+/**
+ * Minimum gap between bootstrap invitation emails for the same address.
+ * The action-level rate limiter bounds attempts per IP+email, but a
+ * patient caller can still space requests a minute apart; this cooldown
+ * is what keeps the mailbox quiet while the bootstrap token is being
+ * chased down.
+ */
+const BOOTSTRAP_INVITE_COOLDOWN_MS = 15 * 60 * 1000
+
+/**
+ * Serializes the bootstrap cooldown check + invitation creation + send per
+ * address. The check and the insert are separate queries, so concurrent
+ * tokenless sign-ups for the gated address could all pass the check before
+ * the first insert landed and each mail a live admin link. Morphic runs as
+ * a single instance, so an in-process chain per address is sufficient.
+ */
+const bootstrapSendLocks = new Map<string, Promise<unknown>>()
+
+async function withBootstrapSendLock<T>(
+ emailKey: string,
+ fn: () => Promise<T>
+): Promise<T> {
+ const previous = bootstrapSendLocks.get(emailKey) ?? Promise.resolve()
+ let release!: () => void
+ const gate = new Promise<void>(resolve => {
+ release = resolve
+ })
+ const entry = previous.then(
+ () => gate,
+ () => gate
+ )
+ bootstrapSendLocks.set(emailKey, entry)
+ await previous.catch(() => {})
+ try {
+ return await fn()
+ } finally {
+ release()
+ if (bootstrapSendLocks.get(emailKey) === entry) {
+ bootstrapSendLocks.delete(emailKey)
+ }
+ }
+}
+
+function errorMessage(error: unknown, fallback: string): string {
+ if (error instanceof Error && error.message) {
+ return error.message
+ }
+ return fallback
+}
+
+const TOO_MANY_REQUESTS = 'Too many attempts. Please try again in a minute.'
+
+async function clientIp(): Promise<string> {
+ const requestHeaders = await headers()
+ const forwarded = requestHeaders.get('x-forwarded-for')
+ return (
+ forwarded?.split(',')[0]?.trim() ||
+ requestHeaders.get('x-real-ip') ||
+ 'local'
+ )
+}
+
+/**
+ * Bounds repeated auth attempts per IP+email. better-auth's own rate
+ * limiter only runs in its HTTP handler, which Morphic does not mount,
+ * so the direct auth.api.* actions need their own throttle.
+ */
+async function attemptAllowed(action: string, email: string): Promise<boolean> {
+ const ip = await clientIp()
+ return checkRateLimit(`${action}:${ip}:${email.trim().toLowerCase()}`)
+}
+
+interface BetterAuthSessionUser {
+ id: string
+ email: string
+ name: string | null
+ image: string | null
+ createdAt: Date
+ role?: string | null
+}
+
+function toAppUser(user: BetterAuthSessionUser): AppUser {
+ return {
+ id: user.id,
+ email: user.email ?? null,
+ name: user.name ?? null,
+ image: user.image ?? null,
+ createdAt: user.createdAt ?? null,
+ role: user.role ?? null
+ }
+}
+
+export const betterAuthProvider: AuthProvider = {
+ name: 'better-auth',
+
+ get capabilities() {
+ return {
+ signUp: true,
+ passwordReset:
+ isBetterAuthSmtpConfigured() && getEmailLinkOrigin() !== '',
+ deleteUser: true,
+ // Email/password only: no OAuth provider is wired into the local
+ // instance, and accounts are usable immediately without email
+ // confirmation.
+ oauth: false,
+ emailVerification: false,
+ share: true
+ }
+ },
+
+ async getCurrentUser(): Promise<AppUser | null> {
+ const session = await getAuth().api.getSession({
+ headers: await headers()
+ })
+ if (!session) {
+ return null
+ }
+ return toAppUser(session.user as BetterAuthSessionUser)
+ },
+
+ async handleSession(request: NextRequest): Promise<NextResponse> {
+ const { response: session, headers: responseHeaders } =
+ await getAuth().api.getSession({
+ headers: request.headers,
+ returnHeaders: true
+ })
+
+ // Public paths that do not require a session (mirrors the supabase
+ // middleware). /relay is the PostHog reverse proxy: analytics requests
+ // from the login and sign-up pages must not bounce to /auth/login.
+ // /search hosts the shared-chat pages: app/search/[id]/page.tsx decides
+ // visibility (public chats are viewable logged out, private ones are
+ // rejected there), so the proxy must not pre-empt that check.
+ const publicPaths = ['/auth', '/share', '/api', '/relay', '/search']
+ const pathname = request.nextUrl.pathname
+
+ if (
+ !session &&
+ pathname !== '/' &&
+ !publicPaths.some(path => pathname.startsWith(path))
+ ) {
+ const url = request.nextUrl.clone()
+ url.pathname = '/auth/login'
+ // Drop the original query from the login URL itself; it travels
+ // inside `next` (including its query string) instead. The login
+ // form validates it with safeRedirectPath before following it.
+ url.search = ''
+ url.searchParams.set('next', pathname + request.nextUrl.search)
+ return NextResponse.redirect(url)
+ }
+
+ const response = NextResponse.next({ request })
+ // better-auth refreshes the session cookie once a session passes half
+ // its lifetime (updateAge). Forward the refreshed cookie so active
+ // sessions do not expire at the original expiry time.
+ if (responseHeaders) {
+ for (const raw of responseHeaders.getSetCookie()) {
+ response.headers.append('set-cookie', raw)
+ }
+ }
+ return response
+ },
+
+ async signIn({
+ email,
+ password
+ }: {
+ email: string
+ password: string
+ }): Promise<AuthActionResult> {
+ if (!(await attemptAllowed('sign-in', email))) {
+ return { success: false, error: TOO_MANY_REQUESTS }
+ }
+ try {
+ await getAuth().api.signInEmail({
+ body: { email, password },
+ headers: await headers()
+ })
+ // The nextCookies plugin stores the session cookie through
+ // next/headers; no manual set-cookie copy is needed (and a manual
+ // cookies().set of the raw header would double-encode the signed
+ // value, breaking the signature check on read).
+ return { success: true }
+ } catch (error) {
+ return {
+ success: false,
+ error: errorMessage(error, 'Invalid email or password')
+ }
+ }
+ },
+
+ async signUp({
+ email,
+ password,
+ token
+ }: {
+ email: string
+ password: string
+ token?: string
+ }): Promise<AuthActionResult> {
+ if (!(await attemptAllowed('sign-up', email))) {
+ return { success: false, error: TOO_MANY_REQUESTS }
+ }
+ // The bootstrap account is the seed admin of a fresh instance:
+ // invitations can only be created by an existing admin, so the gated
+ // address must be able to sign up without a token.
+ // Set when an invitation claim succeeded, so a failed account creation
+ // can release the claim and let the same link be retried.
+ let consumedInvitationId: string | undefined
+ const bootstrapAccount = await isBootstrapAccount(email)
+ if (bootstrapAccount && isBetterAuthSmtpConfigured()) {
+ const origin = getEmailLinkOrigin()
+ if (!origin) {
+ // Fail closed: without a canonical origin the confirmation link
+ // cannot be delivered safely, and silently falling back to
+ // first-come sign-up would let anyone who guesses the address
+ // claim admin while the operator believes mailbox proof is active.
+ return {
+ success: false,
+ error:
+ 'Bootstrap sign-up requires BETTER_AUTH_URL to deliver its confirmation email. Set it, or unset SMTP to accept the first sign-up directly.'
+ }
+ }
+ // The bootstrap gate only compares caller-supplied email text, so on
+ // an instance reachable by others anyone who guesses the operator's
+ // address could claim the admin role. When SMTP is available, require
+ // proof of mailbox control instead: without a token, send a one-time
+ // invitation bound to the address; with one, it must be that very
+ // invitation. Validated in every sign-up mode — open mode otherwise
+ // ignores tokens, which would let any non-empty token skip the proof.
+ if (!token) {
+ const emailKey = email.trim().toLowerCase()
+ return withBootstrapSendLock(emailKey, async () => {
+ try {
+ if (
+ await hasRecentBootstrapInvitation(
+ emailKey,
+ BOOTSTRAP_INVITE_COOLDOWN_MS
+ )
+ ) {
+ // A live link is already on its way: the per-address
+ // cooldown keeps the mailbox quiet while the operator
+ // chases down the first link.
+ return {
+ success: true,
+ notice: `A bootstrap link was sent to ${email}. Open it to finish creating the admin account.`
+ }
+ }
+ const { invitation, token: inviteToken } = await createInvitation({
+ invitedBy: 'bootstrap',
+ email: emailKey
+ })
+ try {
+ await sendSmtpMail({
+ to: email,
+ subject: 'Finish creating your Morphic admin account',
+ text: `Use this link to finish creating the admin account for ${email} (valid for one week): ${origin}/auth/sign-up?token=${inviteToken}`,
+ html: `<p>Use this link to finish creating the admin account for ${email} (valid for one week):</p><p><a href="${origin}/auth/sign-up?token=${inviteToken}">Complete sign-up</a></p>`
+ })
+ } catch (error) {
+ // Delivery failed: release the invitation so a retry can send
+ // a fresh link instead of being locked out by the cooldown.
+ await revokeInvitation(invitation.id).catch(() => {})
+ throw error
+ }
+ return {
+ success: true,
+ notice: `A bootstrap link was sent to ${email}. Open it to finish creating the admin account.`
+ }
+ } catch (error) {
+ return {
+ success: false,
+ error: errorMessage(error, 'Could not send the bootstrap email.')
+ }
+ }
+ })
+ }
+ const invitation = await validateInvitation(token)
+ if (
+ !invitation ||
+ // An ordinary invitation (invitedBy = the inviting admin) for
+ // the same address must not claim admin: only the invitation
+ // this branch mailed itself (invitedBy = 'bootstrap') proves
+ // mailbox control of the gated address.
+ invitation.invitedBy !== 'bootstrap' ||
+ !invitation.email ||
+ invitation.email.trim().toLowerCase() !== email.trim().toLowerCase()
+ ) {
+ return {
+ success: false,
+ error:
+ 'Bootstrap sign-up requires the link sent to your email address.'
+ }
+ }
+ const claimed = await consumeInvitation(invitation.id)
+ if (!claimed) {
+ return {
+ success: false,
+ error: 'This bootstrap link has already been used.'
+ }
+ }
+ consumedInvitationId = invitation.id
+ } else if (getSignUpMode() === 'invite' && !bootstrapAccount) {
+ const invitation = await validateInvitation(token)
+ if (!invitation) {
+ return {
+ success: false,
+ error: 'Sign-up requires a valid invitation token.'
+ }
+ }
+ // Invitations issued for a specific address can only be redeemed by
+ // that address, so a forwarded link is useless to anyone else. The
+ // admin action always requires an email, so the truthy check is
+ // defense-in-depth for rows that predate that requirement.
+ // Checked before the claim so a mismatched attempt does not burn the
+ // invitation for its intended recipient.
+ if (
+ invitation.email &&
+ invitation.email.trim().toLowerCase() !== email.trim().toLowerCase()
+ ) {
+ return {
+ success: false,
+ error: 'This invitation was issued for a different email address.'
+ }
+ }
+ // Claim the invitation before creating the account so concurrent
+ // submissions of the same link cannot both pass validation. If the
+ // sign-up then fails before the account exists, the claim is released
+ // below so the same link can be retried with a corrected password.
+ const claimed = await consumeInvitation(invitation.id)
+ if (!claimed) {
+ return {
+ success: false,
+ error: 'Sign-up requires a valid invitation token.'
+ }
+ }
+ consumedInvitationId = invitation.id
+ }
+
+ try {
+ const response = await getAuth().api.signUpEmail({
+ body: { name: email, email, password },
+ headers: await headers()
+ })
+
+ // signUpEmail resolves to `{ token, user }` — there is no `session`
+ // field. The token is the session token the nextCookies plugin
+ // delivers to the browser, so its presence is the success signal.
+ if (!response || !(response as { token?: unknown }).token) {
+ // A structured rejection: no account was created, so the claim is
+ // released and the same link can be retried (e.g. with a password
+ // that passes better-auth's rules).
+ if (consumedInvitationId) {
+ await releaseInvitation(consumedInvitationId).catch(() => {})
+ }
+ return {
+ success: false,
+ error: 'Sign-up failed. The account may already exist.'
+ }
+ }
+
+ return { success: true }
+ } catch (error) {
+ // Uncertain outcome: better-auth may have committed the user before
+ // the connection failed. Only release the claim when no account
+ // exists for the address.
+ if (consumedInvitationId && !(await accountExists(email))) {
+ await releaseInvitation(consumedInvitationId).catch(() => {})
+ }
+ return {
+ success: false,
+ error: errorMessage(error, 'An error occurred')
+ }
+ }
+ },
+
+ async signOut(): Promise<AuthActionResult> {
+ try {
+ await getAuth().api.signOut({
+ headers: await headers()
+ })
+ // The nextCookies plugin clears the session cookie through
+ // next/headers; no manual set-cookie copy is needed.
+ return { success: true }
+ } catch (error) {
+ return {
+ success: false,
+ error: errorMessage(error, 'Failed to sign out')
+ }
+ }
+ },
+
+ async requestPasswordReset(email: string): Promise<AuthActionResult> {
+ if (!isBetterAuthSmtpConfigured()) {
+ return {
+ success: false,
+ error: 'Password reset is not configured on this instance.'
+ }
+ }
+ if (!(await attemptAllowed('password-reset', email))) {
+ return { success: false, error: TOO_MANY_REQUESTS }
+ }
+
+ try {
+ const origin = await getRequestOrigin()
+ await getAuth().api.requestPasswordReset({
+ body: {
+ email,
+ redirectTo: `${origin}/auth/update-password`
+ },
+ headers: await headers()
+ })
+ return { success: true }
+ } catch (error) {
+ return {
+ success: false,
+ error: errorMessage(error, 'Failed to send reset email')
+ }
+ }
+ },
+
+ async updatePassword(
+ password: string,
+ token?: string
+ ): Promise<AuthActionResult> {
+ try {
+ await getAuth().api.resetPassword({
+ body: {
+ newPassword: password,
+ ...(token ? { token } : {})
+ },
+ headers: await headers()
+ })
+ // A token reset changes the credential only: no session cookie is
+ // issued, so send the user to sign in with the new password instead
+ // of landing logged-out on the app root.
+ return token
+ ? { success: true, redirectTo: '/auth/login' }
+ : { success: true }
+ } catch (error) {
+ return {
+ success: false,
+ error: errorMessage(error, 'Failed to update password')
+ }
+ }
+ },
+
+ validateDeleteUserConfig(): string | null {
+ return null
+ },
+
+ async canDeleteUser(userId: string): Promise<string | null> {
+ // Best-effort UX gate: callers run this before destructive side
+ // effects. validateDeletion is the authoritative locked check.
+ const { error } = await deletionGuard(db, userId, false)
+ return error
+ },
+
+ async validateDeletion(
+ userId: string,
+ tx: AuthTransaction
+ ): Promise<DeletionGuardResult> {
+ // Runs inside the caller's transaction: FOR UPDATE on the admin rows
+ // serializes concurrent admin deletions until that transaction
+ // commits, so the answer cannot flip before the identity delete that
+ // consumes this result.
+ return deletionGuard(tx, userId, true)
+ },
+
+ async postDeletion(wasAdmin: boolean): Promise<void> {
+ if (wasAdmin) {
+ // Completes the bootstrap election for a sign-up whose own claim
+ // declined because the admin row still existed when it ran (see
+ // reElectBootstrapAdmin).
+ await reElectBootstrapAdmin()
+ }
+ },
+
+ async deleteUser(
+ userId: string,
+ tx?: AuthTransaction
+ ): Promise<AuthActionResult> {
+ try {
+ if (tx) {
+ // Runs inside the caller's transaction; the caller validated the
+ // guard under this transaction's locks before any cleanup.
+ await tx.delete(authUser).where(eq(authUser.id, userId))
+ return { success: true }
+ }
+ // Self-contained path: guard and delete share one locked
+ // transaction so concurrent deletions serialize.
+ return await db.transaction(async innerTx => {
+ const guard = await deletionGuard(innerTx, userId, true)
+ if (guard.error) {
+ return { success: false, error: guard.error }
+ }
+ // Cascades remove sessions and accounts via foreign keys
+ await innerTx.delete(authUser).where(eq(authUser.id, userId))
+ return { success: true }
+ })
+ } catch (error) {
+ return {
+ success: false,
+ error: errorMessage(error, 'Failed to delete user')
+ }
+ }
+ }
+}
diff --git a/lib/auth/providers/none.ts b/lib/auth/providers/none.ts
index b1f7c27d..d515550f 100644
--- a/lib/auth/providers/none.ts
+++ b/lib/auth/providers/none.ts
@@ -14,7 +14,10 @@ export const noneAuthProvider: AuthProvider = {
capabilities: {
signUp: false,
passwordReset: false,
- deleteUser: false
+ deleteUser: false,
+ oauth: false,
+ emailVerification: false,
+ share: false
},
async getCurrentUser(): Promise<AppUser | null> {
diff --git a/lib/auth/providers/supabase.ts b/lib/auth/providers/supabase.ts
index d9bcff66..744f9842 100644
--- a/lib/auth/providers/supabase.ts
+++ b/lib/auth/providers/supabase.ts
@@ -1,8 +1,8 @@
-import { headers } from 'next/headers'
import { type NextRequest, NextResponse } from 'next/server'
import type { User as SupabaseUser } from '@supabase/supabase-js'
+import { getRequestOrigin } from '@/lib/auth/request'
import type { AppUser, AuthActionResult, AuthProvider } from '@/lib/auth/types'
import { createAdminClient } from '@/lib/supabase/admin'
import { hasSupabasePublicConfig } from '@/lib/supabase/keys'
@@ -33,23 +33,15 @@ function toAppUser(user: SupabaseUser): AppUser {
}
}
-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
+ deleteUser: true,
+ oauth: true,
+ emailVerification: true,
+ share: true
},
async getCurrentUser(): Promise<AppUser | null> {
@@ -91,10 +83,14 @@ export const supabaseAuthProvider: AuthProvider = {
async signInWithOAuth(provider: string): Promise<AuthActionResult> {
const supabase = await createClient()
- const origin = await getOrigin()
+ const origin = await getRequestOrigin()
const { data, error } = await supabase.auth.signInWithOAuth({
provider: provider as 'google',
options: {
+ // Fixed callback URL: Supabase's redirect allowlist matches the
+ // configured Redirect URLs exactly, so a ?next= query here would
+ // fall out of the allowlist and break the exchange. The login form
+ // carries the destination in a short-lived cookie instead.
redirectTo: `${origin}/auth/oauth`
}
})
@@ -112,7 +108,7 @@ export const supabaseAuthProvider: AuthProvider = {
password: string
}): Promise<AuthActionResult> {
const supabase = await createClient()
- const origin = await getOrigin()
+ const origin = await getRequestOrigin()
const { error } = await supabase.auth.signUp({
email,
password,
@@ -131,7 +127,7 @@ export const supabaseAuthProvider: AuthProvider = {
async requestPasswordReset(email: string): Promise<AuthActionResult> {
const supabase = await createClient()
- const origin = await getOrigin()
+ const origin = await getRequestOrigin()
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.
diff --git a/lib/auth/rate-limit.ts b/lib/auth/rate-limit.ts
new file mode 100644
index 00000000..f53460a7
--- /dev/null
+++ b/lib/auth/rate-limit.ts
@@ -0,0 +1,44 @@
+/**
+ * Fixed-window in-process rate limiter for the auth actions that call
+ * `auth.api.*` directly. Better Auth's own rate limiter runs only in
+ * its HTTP handler, which Morphic does not mount, so without this the
+ * sign-in, sign-up, and password-reset actions would be unthrottled.
+ * Keys combine the client IP with the (caller-supplied) email, so both
+ * credential stuffing across accounts and targeted guessing against
+ * one account are bounded. Morphic runs as a single instance (see
+ * bootstrapSendLocks in the better-auth provider), so an in-process
+ * map is sufficient; a multi-instance deployment would need a shared
+ * store.
+ */
+const WINDOW_MS = 60_000
+const MAX_ATTEMPTS = 10
+const MAX_KEYS = 10_000
+
+const buckets = new Map<string, { windowStart: number; count: number }>()
+
+/**
+ * Returns true when the attempt is allowed. Every call — including the
+ * first of a window — counts as an attempt.
+ */
+export function checkRateLimit(key: string): boolean {
+ const now = Date.now()
+ if (buckets.size > MAX_KEYS) {
+ for (const [existing, bucket] of buckets) {
+ if (now - bucket.windowStart >= WINDOW_MS) {
+ buckets.delete(existing)
+ }
+ }
+ }
+ const bucket = buckets.get(key)
+ if (!bucket || now - bucket.windowStart >= WINDOW_MS) {
+ buckets.set(key, { windowStart: now, count: 1 })
+ return true
+ }
+ bucket.count++
+ return bucket.count <= MAX_ATTEMPTS
+}
+
+/** Test hook: clears all windows. */
+export function resetRateLimits(): void {
+ buckets.clear()
+}
diff --git a/lib/auth/redirect-target.ts b/lib/auth/redirect-target.ts
new file mode 100644
index 00000000..6b4921ac
--- /dev/null
+++ b/lib/auth/redirect-target.ts
@@ -0,0 +1,27 @@
+/**
+ * Validates a post-login redirect target. Only same-origin relative paths
+ * are accepted: a crafted ?next= (protocol-relative URL, backslash or
+ * stripped-whitespace tricks, absolute URL) must not bounce a signed-in
+ * user off-site. Anything else falls back to the app root.
+ */
+export function safeRedirectPath(next: string | undefined): string {
+ if (!next) {
+ return '/'
+ }
+ try {
+ // The base origin is arbitrary: anything that resolves away from it
+ // (protocol-relative URLs, backslash-normalized paths, absolute URLs,
+ // non-HTTP schemes) is rejected.
+ const url = new URL(next, 'http://redirect-target.invalid')
+ if (
+ url.origin !== 'http://redirect-target.invalid' ||
+ url.username ||
+ url.password
+ ) {
+ return '/'
+ }
+ return url.pathname + url.search + url.hash
+ } catch {
+ return '/'
+ }
+}
diff --git a/lib/auth/request.ts b/lib/auth/request.ts
new file mode 100644
index 00000000..97f2ae72
--- /dev/null
+++ b/lib/auth/request.ts
@@ -0,0 +1,16 @@
+import { headers } from 'next/headers'
+
+/**
+ * Best-effort origin of the current request, usable from server actions and
+ * route handlers for building absolute redirect URLs.
+ */
+export async function getRequestOrigin(): 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}` : ''
+}
diff --git a/lib/auth/types.ts b/lib/auth/types.ts
index 1d29ab16..bf554561 100644
--- a/lib/auth/types.ts
+++ b/lib/auth/types.ts
@@ -1,5 +1,7 @@
import type { NextRequest, NextResponse } from 'next/server'
+import type { db } from '@/lib/db'
+
export type AuthProviderName = 'supabase' | 'better-auth' | 'none'
/**
@@ -12,6 +14,8 @@ export interface AppUser {
name?: string | null
image?: string | null
createdAt?: Date | string | null
+ /** Provider role when the provider has one (e.g. `admin` | `user`). */
+ role?: string | null
}
/**
@@ -22,6 +26,12 @@ export interface AuthCapabilities {
signUp: boolean
passwordReset: boolean
deleteUser: boolean
+ /** Provider implements `signInWithOAuth` (e.g. a Google button can work). */
+ oauth: boolean
+ /** 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). */
+ share: boolean
}
export interface AuthActionResult {
@@ -32,6 +42,12 @@ export interface AuthActionResult {
* (e.g. an OAuth redirect to the identity provider).
*/
redirectTo?: string
+ /**
+ * Present when the action did not complete sign-in but the client should
+ * display this message instead of redirecting (e.g. a bootstrap link was
+ * emailed and sign-up continues from the mail).
+ */
+ notice?: string
}
/**
@@ -62,14 +78,53 @@ export interface AuthProvider {
signUp?(credentials: {
email: string
password: string
+ token?: string
}): Promise<AuthActionResult>
signOut?(): Promise<AuthActionResult>
requestPasswordReset?(email: string): Promise<AuthActionResult>
- updatePassword?(password: string): Promise<AuthActionResult>
- deleteUser?(userId: string): Promise<AuthActionResult>
+ updatePassword?(password: string, token?: string): Promise<AuthActionResult>
+ deleteUser?(userId: string, tx?: AuthTransaction): Promise<AuthActionResult>
/**
* Returns an error message when the provider is not configured to delete
* users, or null when deletion is available.
*/
validateDeleteUserConfig?(): string | null
+ /**
+ * Returns an error message when this specific account must not be deleted
+ * (e.g. the last remaining admin), or null when deletion may proceed.
+ * Best-effort UX gate: callers run it before destructive side effects,
+ * but it does not lock; validateDeletion is the authoritative check.
+ */
+ canDeleteUser?(userId: string): Promise<string | null>
+ /**
+ * Authoritative deletion guard, run inside the caller's transaction so
+ * the provider's locks are held until the identity deletion that uses
+ * this result commits. Providers without concurrency-sensitive invariants
+ * omit it.
+ */
+ validateDeletion?(
+ userId: string,
+ tx: AuthTransaction
+ ): Promise<DeletionGuardResult>
+ /**
+ * Runs after a deletion that reported wasAdmin has committed. Used to
+ * complete role elections that a concurrent sign-up could not finish
+ * while the deleted admin row still existed.
+ */
+ postDeletion?(wasAdmin: boolean): Promise<void>
+}
+
+/**
+ * A database transaction handed to provider methods that must share their
+ * locks with the caller's surrounding transaction.
+ */
+export type AuthTransaction = Parameters<
+ Parameters<typeof db.transaction>[0]
+>[0]
+
+export interface DeletionGuardResult {
+ /** Error message when the account must not be deleted, otherwise null. */
+ error: string | null
+ /** Whether the target account held the admin role. */
+ wasAdmin: boolean
}
diff --git a/lib/contexts/app-user-context.tsx b/lib/contexts/app-user-context.tsx
index 31061475..82c7eed3 100644
--- a/lib/contexts/app-user-context.tsx
+++ b/lib/contexts/app-user-context.tsx
@@ -12,7 +12,10 @@ interface AppUserContextValue {
const NO_CAPABILITIES: AuthCapabilities = {
signUp: false,
passwordReset: false,
- deleteUser: false
+ deleteUser: false,
+ oauth: false,
+ emailVerification: false,
+ share: false
}
const AppUserContext = createContext<AppUserContextValue>({
diff --git a/lib/db/schema.ts b/lib/db/schema.ts
index 7ad997d6..ce1282fa 100644
--- a/lib/db/schema.ts
+++ b/lib/db/schema.ts
@@ -507,3 +507,9 @@ export const additionalUsageInterest = pgTable(
export type AdditionalUsageInterest = InferSelectModel<
typeof additionalUsageInterest
>
+
+// Better Auth tables (user, session, account, verification, invitations)
+// are defined in lib/auth/better-auth/schema.ts and re-exported here so the
+// canonical schema module — and drizzle-kit generation anchored on it —
+// covers every table in the database.
+export * from '../auth/better-auth/schema'
diff --git a/next.config.mjs b/next.config.mjs
index 88d8229e..623af753 100644
--- a/next.config.mjs
+++ b/next.config.mjs
@@ -1,20 +1,22 @@
/** @type {import('next').NextConfig} */
const nextConfig = {
- // Reverse proxy for PostHog to reduce tracking-blocker interception.
skipTrailingSlashRedirect: true,
- async rewrites() {
+ async headers() {
return [
{
- source: '/relay/static/:path*',
- destination: 'https://us-assets.i.posthog.com/static/:path*'
- },
- {
- source: '/relay/array/:path*',
- destination: 'https://us-assets.i.posthog.com/array/:path*'
- },
- {
- source: '/relay/:path*',
- destination: 'https://us.i.posthog.com/:path*'
+ // Only the auth pages carry one-time credentials in ?token=
+ // (invitations, password resets, bootstrap). no-referrer on those
+ // pages keeps the token-bearing URL out of Referer headers on
+ // outbound and same-origin requests — including requests the
+ // /relay PostHog proxy route makes upstream — while the rest of
+ // the site keeps normal referrer data for analytics.
+ source: '/auth/:path*',
+ headers: [
+ {
+ key: 'Referrer-Policy',
+ value: 'no-referrer'
+ }
+ ]
}
]
},
diff --git a/package.json b/package.json
index 6c9c462a..9e834886 100644
--- a/package.json
+++ b/package.json
@@ -70,6 +70,7 @@
"@vercel/otel": "^2.1.3",
"ai": "^7.0.66",
"ai-sdk-ollama": "^4.1.0",
+ "better-auth": "^1.7.7",
"class-variance-authority": "^0.7.1",
"clsx": "^2.1.0",
"cmdk": "1.0.0",
@@ -83,6 +84,7 @@
"katex": "^0.16.10",
"next": "^16.2.6",
"node-html-parser": "^6.1.13",
+ "nodemailer": "^10.0.15",
"postgres": "^3.4.5",
"posthog-js": "^1.382.0",
"posthog-node": "^5.36.4",