Skip to content

An AI-powered search engine with a generative UI

fix(auth): harden Better Auth rate limiting and token scrubbing (#1069)

Yoshiki Miura158c84a59444
diff --git a/AGENTS.md b/AGENTS.md
index c3616843..39d8614f 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -152,10 +152,6 @@ 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/docs/lessons-learned-review-fixes.md b/docs/lessons-learned-review-fixes.md
deleted file mode 100644
index da1bed03..00000000
--- a/docs/lessons-learned-review-fixes.md
+++ /dev/null
@@ -1,93 +0,0 @@
-# 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/lib/analytics/__tests__/sanitize.test.ts b/lib/analytics/__tests__/sanitize.test.ts
index 4efa6aa1..76acf25c 100644
--- a/lib/analytics/__tests__/sanitize.test.ts
+++ b/lib/analytics/__tests__/sanitize.test.ts
@@ -3,6 +3,8 @@ import { describe, expect, it } from 'vitest'
import { scrubTokenFromEvent } from '../sanitize'
+const AUTH_LINK = 'http://localhost:3000/auth/sign-up'
+
function pageview(currentUrl: unknown): CaptureResult {
return {
event_name: '$pageview',
@@ -48,8 +50,91 @@ describe('scrubTokenFromEvent', () => {
)
})
+ it('strips the token from the initial and session entry urls', () => {
+ const result = scrubTokenFromEvent({
+ event_name: 'chat_started',
+ properties: {
+ $current_url: 'http://localhost:3000/',
+ $initial_current_url: `${AUTH_LINK}?token=abc123`,
+ $initial_referrer: `${AUTH_LINK}?token=abc123`,
+ $session_entry_url: `${AUTH_LINK}?token=abc123`,
+ $session_entry_referrer: `${AUTH_LINK}?token=abc123`
+ }
+ } as unknown as CaptureResult)
+
+ expect(result?.properties).toEqual({
+ $current_url: 'http://localhost:3000/',
+ $initial_current_url: AUTH_LINK,
+ $initial_referrer: AUTH_LINK,
+ $session_entry_url: AUTH_LINK,
+ $session_entry_referrer: AUTH_LINK
+ })
+ })
+
+ it('strips the token from person properties at the event root', () => {
+ const result = scrubTokenFromEvent({
+ event_name: '$pageview',
+ properties: { $current_url: 'http://localhost:3000/' },
+ $set: { $current_url: `${AUTH_LINK}?token=abc123`, plan: 'free' },
+ $set_once: {
+ $initial_current_url: `${AUTH_LINK}?token=abc123`,
+ $initial_referrer: `${AUTH_LINK}?token=abc123`,
+ $current_url: `${AUTH_LINK}?token=abc123`,
+ $referrer: '$direct'
+ }
+ } as unknown as CaptureResult)
+
+ expect(result?.$set).toEqual({ $current_url: AUTH_LINK, plan: 'free' })
+ expect(result?.$set_once).toEqual({
+ $initial_current_url: AUTH_LINK,
+ $initial_referrer: AUTH_LINK,
+ $current_url: AUTH_LINK,
+ $referrer: '$direct'
+ })
+ })
+
+ it('strips the token from person properties nested under properties', () => {
+ const result = scrubTokenFromEvent({
+ event_name: '$set',
+ properties: {
+ $set: { $current_url: `${AUTH_LINK}?token=abc123` },
+ $set_once: {
+ $initial_current_url: `${AUTH_LINK}?token=abc123`,
+ $initial_referrer: `${AUTH_LINK}?token=abc123`
+ }
+ }
+ } as unknown as CaptureResult)
+
+ expect(result?.properties?.$set).toEqual({ $current_url: AUTH_LINK })
+ expect(result?.properties?.$set_once).toEqual({
+ $initial_current_url: AUTH_LINK,
+ $initial_referrer: AUTH_LINK
+ })
+ })
+
+ it('does not mutate the original event', () => {
+ const setOnce = { $initial_current_url: `${AUTH_LINK}?token=abc123` }
+ const event = {
+ event_name: '$pageview',
+ properties: { $current_url: 'http://localhost:3000/' },
+ $set_once: setOnce
+ } as unknown as CaptureResult
+
+ const result = scrubTokenFromEvent(event)
+
+ expect(result).not.toBe(event)
+ expect(setOnce.$initial_current_url).toContain('token=abc123')
+ })
+
it('leaves events without a token untouched', () => {
- const event = pageview('http://localhost:3000/search?q=hello')
+ const event = {
+ event_name: '$pageview',
+ properties: {
+ $current_url: 'http://localhost:3000/search?q=hello',
+ $set_once: { $initial_current_url: 'http://localhost:3000/' }
+ },
+ $set_once: { $initial_referrer: '$direct' }
+ } as unknown as CaptureResult
expect(scrubTokenFromEvent(event)).toBe(event)
})
diff --git a/lib/analytics/sanitize.ts b/lib/analytics/sanitize.ts
index bf1115a4..7839f3f4 100644
--- a/lib/analytics/sanitize.ts
+++ b/lib/analytics/sanitize.ts
@@ -1,14 +1,26 @@
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.
+ * Event properties that carry a full page URL, including the landing URL
+ * that posthog-js replays as initial and session-entry values. 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
+const URL_PROPERTIES = [
+ '$current_url',
+ '$referrer',
+ '$initial_current_url',
+ '$initial_referrer',
+ '$session_entry_url',
+ '$session_entry_referrer'
+] as const
+
+// posthog-js emits person properties at the event root; site apps and
+// manual captures nest them under properties.
+const PERSON_PROPERTY_KEYS = ['$set', '$set_once'] as const
function stripToken(url: string): string | null {
if (!url.includes('token=')) {
@@ -26,23 +38,54 @@ function stripToken(url: string): string | null {
}
}
+function scrubUrls<T extends Record<string, unknown>>(source: T): T {
+ let scrubbed = source
+ for (const key of URL_PROPERTIES) {
+ const value = source[key]
+ if (typeof value !== 'string') {
+ continue
+ }
+ const stripped = stripToken(value)
+ if (stripped !== null) {
+ if (scrubbed === source) {
+ scrubbed = { ...source }
+ }
+ ;(scrubbed as Record<string, unknown>)[key] = stripped
+ }
+ }
+ return scrubbed
+}
+
+function scrubPersonProperties<T extends Record<string, unknown>>(
+ source: T
+): T {
+ let scrubbed = source
+ for (const key of PERSON_PROPERTY_KEYS) {
+ const value = source[key]
+ if (!value || typeof value !== 'object') {
+ continue
+ }
+ const stripped = scrubUrls(value as Record<string, unknown>)
+ if (stripped !== value) {
+ if (scrubbed === source) {
+ scrubbed = { ...source }
+ }
+ ;(scrubbed as Record<string, unknown>)[key] = stripped
+ }
+ }
+ return scrubbed
+}
+
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
+ const scrubbed = scrubPersonProperties(
+ event as unknown as Record<string, unknown>
+ ) as unknown as CaptureResult
+ const source: Record<string, unknown> = event.properties ?? {}
+ const properties = scrubPersonProperties(scrubUrls(source))
+ return properties === source ? scrubbed : { ...scrubbed, properties }
}
diff --git a/lib/auth/__tests__/better-auth-provider.test.ts b/lib/auth/__tests__/better-auth-provider.test.ts
index 8c80bbd0..ff8e31be 100644
--- a/lib/auth/__tests__/better-auth-provider.test.ts
+++ b/lib/auth/__tests__/better-auth-provider.test.ts
@@ -1,3 +1,4 @@
+import { headers } from 'next/headers'
import type { NextRequest } from 'next/server'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
@@ -390,6 +391,42 @@ describe('better-auth provider', () => {
error: expect.stringContaining('Too many attempts')
})
})
+
+ it('blocks repeated attempts for one email across rotating ips', async () => {
+ // x-forwarded-for is caller-supplied, so a fresh value per request
+ // must not buy a fresh budget against the same account.
+ vi.mocked(mockAuth.api.signInEmail).mockResolvedValue({} as never)
+ let attempt = 0
+ vi.mocked(headers).mockImplementation(
+ async () =>
+ new Headers({ 'x-forwarded-for': `10.0.0.${attempt}` }) as never
+ )
+
+ try {
+ for (; attempt < 10; attempt++) {
+ expect(
+ await betterAuthProvider.signIn!({ email: '[email protected]', password: 'x' })
+ ).toEqual({ success: true })
+ }
+
+ expect(
+ await betterAuthProvider.signIn!({ email: '[email protected] ', password: 'x' })
+ ).toEqual({
+ success: false,
+ error: expect.stringContaining('Too many attempts')
+ })
+ expect(
+ await betterAuthProvider.signIn!({
+ email: '[email protected]',
+ password: 'x'
+ })
+ ).toEqual({ success: true })
+ } finally {
+ vi.mocked(headers).mockImplementation(
+ async () => new Headers({ origin: 'http://localhost:3000' }) as never
+ )
+ }
+ })
})
describe('signUp', () => {
diff --git a/lib/auth/__tests__/rate-limit.test.ts b/lib/auth/__tests__/rate-limit.test.ts
index 15da14b2..09f8a98c 100644
--- a/lib/auth/__tests__/rate-limit.test.ts
+++ b/lib/auth/__tests__/rate-limit.test.ts
@@ -1,6 +1,10 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
-import { checkRateLimit, resetRateLimits } from '../rate-limit'
+import {
+ checkRateLimit,
+ rateLimitKeyCount,
+ resetRateLimits
+} from '../rate-limit'
describe('checkRateLimit', () => {
beforeEach(() => {
@@ -41,4 +45,38 @@ describe('checkRateLimit', () => {
expect(checkRateLimit('sign-in:5.6.7.8:[email protected]')).toBe(true)
expect(checkRateLimit('sign-up:1.2.3.4:[email protected]')).toBe(true)
})
+
+ it('evicts the oldest keys when the cap is reached within one window', () => {
+ for (let attempt = 0; attempt < 11; attempt++) {
+ checkRateLimit('sign-in:[email protected]')
+ }
+ expect(checkRateLimit('sign-in:[email protected]')).toBe(false)
+
+ for (let index = 0; index < 20_000; index++) {
+ checkRateLimit(`sign-in:10.0.0.${index}:[email protected]`)
+ }
+
+ expect(rateLimitKeyCount()).toBeLessThanOrEqual(10_000)
+ // The newest key survives with its count; the oldest lost its window.
+ for (let attempt = 0; attempt < 9; attempt++) {
+ expect(checkRateLimit('sign-in:10.0.0.19999:[email protected]')).toBe(true)
+ }
+ expect(checkRateLimit('sign-in:10.0.0.19999:[email protected]')).toBe(false)
+ expect(checkRateLimit('sign-in:[email protected]')).toBe(true)
+ })
+
+ it('drops expired keys before live ones at the cap', () => {
+ for (let index = 0; index < 9_999; index++) {
+ checkRateLimit(`sign-in:stale-${index}`)
+ }
+ vi.advanceTimersByTime(60_001)
+ for (let attempt = 0; attempt < 11; attempt++) {
+ checkRateLimit('sign-in:[email protected]')
+ }
+
+ checkRateLimit('sign-in:[email protected]')
+
+ expect(rateLimitKeyCount()).toBe(2)
+ expect(checkRateLimit('sign-in:[email protected]')).toBe(false)
+ })
})
diff --git a/lib/auth/providers/better-auth.ts b/lib/auth/providers/better-auth.ts
index bd2f0153..85491d32 100644
--- a/lib/auth/providers/better-auth.ts
+++ b/lib/auth/providers/better-auth.ts
@@ -170,13 +170,19 @@ async function clientIp(): Promise<string> {
}
/**
- * 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.
+ * Bounds repeated auth attempts per IP+email and per email alone.
+ * 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. The IP comes from a caller-supplied header, so the
+ * email-only bucket is what bounds guessing against one account when
+ * that header is rotated.
*/
async function attemptAllowed(action: string, email: string): Promise<boolean> {
const ip = await clientIp()
- return checkRateLimit(`${action}:${ip}:${email.trim().toLowerCase()}`)
+ const emailKey = email.trim().toLowerCase()
+ const ipAllowed = checkRateLimit(`${action}:${ip}:${emailKey}`)
+ const emailAllowed = checkRateLimit(`${action}:${emailKey}`)
+ return ipAllowed && emailAllowed
}
interface BetterAuthSessionUser {
diff --git a/lib/auth/rate-limit.ts b/lib/auth/rate-limit.ts
index f53460a7..46e6bc76 100644
--- a/lib/auth/rate-limit.ts
+++ b/lib/auth/rate-limit.ts
@@ -3,9 +3,8 @@
* `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
+ * Callers choose the keys (see attemptAllowed in the better-auth
+ * provider). 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.
@@ -16,21 +15,28 @@ const MAX_KEYS = 10_000
const buckets = new Map<string, { windowStart: number; count: number }>()
+function evict(now: number): void {
+ for (const [existing, bucket] of buckets) {
+ if (now - bucket.windowStart < WINDOW_MS && buckets.size < MAX_KEYS) {
+ break
+ }
+ buckets.delete(existing)
+ }
+}
+
/**
* 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) {
+ // Re-inserting keeps the map ordered by window start, oldest first.
+ buckets.delete(key)
+ if (buckets.size >= MAX_KEYS) {
+ evict(now)
+ }
buckets.set(key, { windowStart: now, count: 1 })
return true
}
@@ -38,6 +44,11 @@ export function checkRateLimit(key: string): boolean {
return bucket.count <= MAX_ATTEMPTS
}
+/** Test hook: number of tracked keys. */
+export function rateLimitKeyCount(): number {
+ return buckets.size
+}
+
/** Test hook: clears all windows. */
export function resetRateLimits(): void {
buckets.clear()