Skip to content

An AI-powered search engine with a generative UI

fix(auth): forward visitor IPs to Supabase Auth from server actions (#1073)

Yoshiki Miuraa7d7a4dfb8d1
diff --git a/.env.local.example b/.env.local.example
index 32f2e698..998ef057 100644
--- a/.env.local.example
+++ b/.env.local.example
@@ -103,6 +103,9 @@ ANONYMOUS_USER_ID=anonymous-user
# NEXT_PUBLIC_SUPABASE_PUBLISHABLE_KEY=[YOUR_SUPABASE_PUBLISHABLE_KEY]
# Required for account deletion. Never expose this key to the browser.
# SUPABASE_SECRET_KEY=[YOUR_SUPABASE_SECRET_KEY]
+# Forward visitor IPs to Supabase Auth rate limits (automatic on Vercel deployments).
+# Only enable behind a proxy that overwrites X-Forwarded-For.
+# SUPABASE_FORWARD_CLIENT_IP=true
# Local multi-user accounts in Morphic's own Postgres (no Supabase needed).
# See the "Better Auth" section in docs/CONFIGURATION.md for the full walkthrough.
diff --git a/docs/CONFIGURATION.md b/docs/CONFIGURATION.md
index e44eeccd..5dafccf5 100644
--- a/docs/CONFIGURATION.md
+++ b/docs/CONFIGURATION.md
@@ -336,6 +336,16 @@ SUPABASE_SECRET_KEY=[YOUR_SUPABASE_SECRET_KEY]
not allowlisted, Supabase silently falls back to the project Site URL and
the recovery code can never be exchanged for a session.
+5. Optional: keep Supabase's per-IP rate limits per visitor. Sign-up,
+ password sign-in, and password reset run as server actions, so Supabase
+ sees the server's address unless Morphic forwards the visitor's. To
+ forward it, use an `sb_secret_...` key for `SUPABASE_SECRET_KEY` and turn
+ on **Authentication → Rate Limits → IP Address Forwarding**. On Vercel
+ production and preview deployments this is automatic. Elsewhere,
+ including `vercel dev`, set `SUPABASE_FORWARD_CLIENT_IP=true` only when a
+ reverse proxy in front of Morphic overwrites `X-Forwarded-For`; otherwise
+ visitors can spoof it to dodge the limits.
+
## Guest Mode
Guest mode allows users to try Morphic without creating an account. Guest sessions are ephemeral — no chat history is stored.
diff --git a/lib/auth/__tests__/supabase-provider.test.ts b/lib/auth/__tests__/supabase-provider.test.ts
index 45acab76..6bce5b74 100644
--- a/lib/auth/__tests__/supabase-provider.test.ts
+++ b/lib/auth/__tests__/supabase-provider.test.ts
@@ -3,9 +3,12 @@ import { NextRequest, NextResponse } from 'next/server'
import { beforeEach, describe, expect, it, vi } from 'vitest'
import { supabaseAuthProvider } from '@/lib/auth/providers/supabase'
-import { createClient } from '@/lib/supabase/server'
+import { createAuthActionClient } from '@/lib/supabase/server'
-vi.mock('@/lib/supabase/server', () => ({ createClient: vi.fn() }))
+vi.mock('@/lib/supabase/server', () => ({
+ createClient: vi.fn(),
+ createAuthActionClient: vi.fn()
+}))
vi.mock('@/lib/supabase/middleware', () => ({
updateSession: vi.fn(),
exchangeRecoveryCode: vi.fn()
@@ -28,7 +31,7 @@ describe('supabase provider', () => {
beforeEach(() => {
vi.clearAllMocks()
- vi.mocked(createClient).mockResolvedValue({
+ vi.mocked(createAuthActionClient).mockResolvedValue({
auth: { resetPasswordForEmail }
} as never)
vi.mocked(headers).mockResolvedValue(
diff --git a/lib/auth/providers/supabase.ts b/lib/auth/providers/supabase.ts
index 744f9842..7ac7dfcd 100644
--- a/lib/auth/providers/supabase.ts
+++ b/lib/auth/providers/supabase.ts
@@ -7,7 +7,7 @@ import type { AppUser, AuthActionResult, AuthProvider } from '@/lib/auth/types'
import { createAdminClient } from '@/lib/supabase/admin'
import { hasSupabasePublicConfig } from '@/lib/supabase/keys'
import { exchangeRecoveryCode, updateSession } from '@/lib/supabase/middleware'
-import { createClient } from '@/lib/supabase/server'
+import { createAuthActionClient, createClient } from '@/lib/supabase/server'
function metaString(
metadata: Record<string, unknown>,
@@ -73,7 +73,7 @@ export const supabaseAuthProvider: AuthProvider = {
email: string
password: string
}): Promise<AuthActionResult> {
- const supabase = await createClient()
+ const supabase = await createAuthActionClient()
const { error } = await supabase.auth.signInWithPassword({
email,
password
@@ -107,7 +107,7 @@ export const supabaseAuthProvider: AuthProvider = {
email: string
password: string
}): Promise<AuthActionResult> {
- const supabase = await createClient()
+ const supabase = await createAuthActionClient()
const origin = await getRequestOrigin()
const { error } = await supabase.auth.signUp({
email,
@@ -126,7 +126,7 @@ export const supabaseAuthProvider: AuthProvider = {
},
async requestPasswordReset(email: string): Promise<AuthActionResult> {
- const supabase = await createClient()
+ const supabase = await createAuthActionClient()
const origin = await getRequestOrigin()
const { error } = await supabase.auth.resetPasswordForEmail(email, {
// Keep the pre-refactor destination: deployments that already allowlist
diff --git a/lib/supabase/__tests__/server.test.ts b/lib/supabase/__tests__/server.test.ts
new file mode 100644
index 00000000..78f2d96d
--- /dev/null
+++ b/lib/supabase/__tests__/server.test.ts
@@ -0,0 +1,122 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+
+vi.mock('@supabase/ssr', () => ({ createServerClient: vi.fn(() => ({})) }))
+vi.mock('@/lib/supabase/keys', () => ({
+ getSupabasePublishableKey: vi.fn(() => 'sb_publishable_test')
+}))
+vi.mock('next/headers', () => ({
+ cookies: vi.fn(async () => ({ getAll: () => [], set: vi.fn() })),
+ headers: vi.fn()
+}))
+
+import { headers } from 'next/headers'
+
+import { createServerClient } from '@supabase/ssr'
+
+import { createAuthActionClient } from '../server'
+
+const ENV_KEYS = [
+ 'NEXT_PUBLIC_SUPABASE_URL',
+ 'SUPABASE_SECRET_KEY',
+ 'SUPABASE_FORWARD_CLIENT_IP',
+ 'VERCEL',
+ 'VERCEL_ENV'
+] as const
+
+function lastClientArgs() {
+ const calls = vi.mocked(createServerClient).mock.calls
+ return calls[calls.length - 1] as unknown as [
+ string,
+ string,
+ { global?: { headers?: Record<string, string> } }
+ ]
+}
+
+describe('createAuthActionClient', () => {
+ const saved: Record<string, string | undefined> = {}
+
+ beforeEach(() => {
+ vi.clearAllMocks()
+ for (const key of ENV_KEYS) saved[key] = process.env[key]
+ process.env.NEXT_PUBLIC_SUPABASE_URL = 'https://example.supabase.co'
+ process.env.SUPABASE_SECRET_KEY = 'sb_secret_test'
+ delete process.env.SUPABASE_FORWARD_CLIENT_IP
+ process.env.VERCEL = '1'
+ process.env.VERCEL_ENV = 'production'
+ vi.mocked(headers).mockResolvedValue(
+ new Headers({ 'x-forwarded-for': '203.0.113.7, 10.0.0.1' }) as never
+ )
+ })
+
+ afterEach(() => {
+ for (const key of ENV_KEYS) {
+ if (saved[key] === undefined) delete process.env[key]
+ else process.env[key] = saved[key]
+ }
+ })
+
+ it('forwards the first x-forwarded-for address with the secret key on Vercel', async () => {
+ await createAuthActionClient()
+
+ const [, key, options] = lastClientArgs()
+ expect(key).toBe('sb_secret_test')
+ expect(options.global?.headers).toEqual({
+ 'sb-forwarded-for': '203.0.113.7'
+ })
+ })
+
+ it('does not trust x-forwarded-for outside Vercel unless opted in', async () => {
+ delete process.env.VERCEL
+
+ await createAuthActionClient()
+
+ const [, key, options] = lastClientArgs()
+ expect(key).toBe('sb_publishable_test')
+ expect(options.global).toBeUndefined()
+ })
+
+ it('does not trust x-forwarded-for under vercel dev', async () => {
+ process.env.VERCEL_ENV = 'development'
+
+ await createAuthActionClient()
+
+ expect(lastClientArgs()[1]).toBe('sb_publishable_test')
+ })
+
+ it('forwards outside Vercel when SUPABASE_FORWARD_CLIENT_IP=true', async () => {
+ delete process.env.VERCEL
+ process.env.SUPABASE_FORWARD_CLIENT_IP = 'true'
+
+ await createAuthActionClient()
+
+ expect(lastClientArgs()[2].global?.headers).toEqual({
+ 'sb-forwarded-for': '203.0.113.7'
+ })
+ })
+
+ it('can be turned off on Vercel with SUPABASE_FORWARD_CLIENT_IP=false', async () => {
+ process.env.SUPABASE_FORWARD_CLIENT_IP = 'false'
+
+ await createAuthActionClient()
+
+ expect(lastClientArgs()[1]).toBe('sb_publishable_test')
+ })
+
+ it('falls back to the publishable key for legacy service_role keys', async () => {
+ process.env.SUPABASE_SECRET_KEY = 'eyJhbGciOiJIUzI1NiJ9.legacy'
+
+ await createAuthActionClient()
+
+ expect(lastClientArgs()[1]).toBe('sb_publishable_test')
+ })
+
+ it('falls back when the forwarded address is not an IP', async () => {
+ vi.mocked(headers).mockResolvedValue(
+ new Headers({ 'x-forwarded-for': 'unknown' }) as never
+ )
+
+ await createAuthActionClient()
+
+ expect(lastClientArgs()[1]).toBe('sb_publishable_test')
+ })
+})
diff --git a/lib/supabase/server.ts b/lib/supabase/server.ts
index a9f90f12..965cce91 100644
--- a/lib/supabase/server.ts
+++ b/lib/supabase/server.ts
@@ -1,9 +1,37 @@
-import { cookies } from 'next/headers'
+import { cookies, headers } from 'next/headers'
import { createServerClient } from '@supabase/ssr'
+import { isIP } from 'node:net'
import { getSupabasePublishableKey } from './keys'
+type CookieStore = Awaited<ReturnType<typeof cookies>>
+
+function cookieAdapter(cookieStore: CookieStore) {
+ return {
+ getAll() {
+ return cookieStore.getAll()
+ },
+ setAll(
+ cookiesToSet: Array<{
+ name: string
+ value: string
+ options?: Parameters<CookieStore['set']>[2]
+ }>
+ ) {
+ try {
+ cookiesToSet.forEach(({ name, value, options }) =>
+ cookieStore.set(name, value, options)
+ )
+ } catch {
+ // The `setAll` method was called from a Server Component.
+ // This can be ignored if you have middleware refreshing
+ // user sessions.
+ }
+ }
+ }
+}
+
export async function createClient() {
const cookieStore = await cookies()
const supabaseKey = getSupabasePublishableKey()
@@ -11,23 +39,41 @@ export async function createClient() {
return createServerClient(
process.env.NEXT_PUBLIC_SUPABASE_URL!,
supabaseKey!,
- {
- cookies: {
- getAll() {
- return cookieStore.getAll()
- },
- setAll(cookiesToSet) {
- try {
- cookiesToSet.forEach(({ name, value, options }) =>
- cookieStore.set(name, value, options)
- )
- } catch {
- // The `setAll` method was called from a Server Component.
- // This can be ignored if you have middleware refreshing
- // user sessions.
- }
- }
- }
- }
+ { cookies: cookieAdapter(cookieStore) }
+ )
+}
+
+// Only Vercel deployments overwrite x-forwarded-for at the edge.
+function trustsForwardedFor(): boolean {
+ const setting = process.env.SUPABASE_FORWARD_CLIENT_IP?.trim()
+ if (setting === 'true') return true
+ if (setting === 'false') return false
+ return (
+ process.env.VERCEL === '1' &&
+ (process.env.VERCEL_ENV === 'production' ||
+ process.env.VERCEL_ENV === 'preview')
)
}
+
+async function forwardableClientIp(): Promise<string | null> {
+ if (!trustsForwardedFor()) return null
+ const requestHeaders = await headers()
+ const ip = requestHeaders.get('x-forwarded-for')?.split(',')[0]?.trim()
+ return ip && isIP(ip) ? ip : null
+}
+
+// Forwards the visitor's IP to Supabase Auth rate limits. The secret key
+// bypasses RLS: use for Auth calls only.
+export async function createAuthActionClient() {
+ const secretKey = process.env.SUPABASE_SECRET_KEY
+ const clientIp = await forwardableClientIp()
+ if (!clientIp || !secretKey?.startsWith('sb_secret_')) {
+ return createClient()
+ }
+
+ const cookieStore = await cookies()
+ return createServerClient(process.env.NEXT_PUBLIC_SUPABASE_URL!, secretKey, {
+ cookies: cookieAdapter(cookieStore),
+ global: { headers: { 'sb-forwarded-for': clientIp } }
+ })
+}