Files
MattssonandClaude Fable 5.1 d29a5bda14 fix(auth): resolve auth-link hosts from the brands table, drop NEXT_PUBLIC_WHITELABEL_DOMAINS (#2376)
* fix(auth): resolve auth-link hosts from the brands table, drop NEXT_PUBLIC_WHITELABEL_DOMAINS

Password reset, invite, email change and signup links now resolve the
request host against brands.domain server-side. The env var was a second
copy of that registry compiled into the browser; every new brand needed
the row, the env var, the GoTrue allowlist and a redeploy, and two
partners shipped with the env var stale, so their reset mails went out
canonical-branded to the canonical host.

- New POST /api/auth/password-reset: the login page no longer calls
  GoTrue directly, so the browser carries no domain list.
- lib/domains/trusted-app-origin.ts is async and registry-backed; it
  also trusts this deployment's own VERCEL_URL / VERCEL_BRANCH_URL so
  previews keep sending links to themselves.
- Signup shares the same resolver instead of following the raw host.
- Docs and .env.example describe the single registry; GoTrue keeps the
  redirect allowlist as backstop (hosted: *.accounted.se wildcard).

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01NUNB7qjua8EUaJmZgfFscx

* fix(auth): await the async origin resolver in the billing routes merged from main

PR #2370 added resolveRequestAppOrigin callers in billing/checkout and
billing/portal after this branch made the resolver async. Await them and
move their tests from the removed env var to the brands mock; update the
login source-assert test to the server-routed reset.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01NUNB7qjua8EUaJmZgfFscx

* fix(auth): refuse auth links on a failed brand lookup, keep local dev hosts, correct GoTrue allowlist docs

Skeptic and CI findings on #2376, one pass:

- A failed brands lookup now throws BrandLookupFailedError (TRANSIENT_ERROR,
  503, retryable) instead of falling back to the canonical origin: a
  canonical link is the wrong-brand mail this PR removes. Password reset
  and email change answer 503 themselves; withRouteContext routes map the
  code.
- A local canonical (dev) trusts other local hosts and ports on the same
  scheme, so lane servers on 3001-3003 confirm signups on themselves.
- GoTrue matches the full redirect_to including the query and `*` stops
  at `.` and `/`: docs and decision line now prescribe
  https://*.accounted.se/auth/callback** and https://*.accounted.se/invite/**.
- The Turnstile contract test asserts the server-routed reset forwards
  the captcha token (it still asserted the removed browser call).

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01NUNB7qjua8EUaJmZgfFscx

---------

Co-authored-by: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-07 15:12:22 +02:00

142 lines
5.7 KiB
TypeScript

import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { readFileSync } from 'node:fs'
import path from 'node:path'
import { eventBus } from '@/lib/events/bus'
import {
captchaTokenOptions,
getTurnstileRolloutState,
isTurnstileSubmissionBlocked,
resolveTurnstileSiteKey,
} from '../turnstile'
const readRepoFile = (file: string) =>
readFileSync(path.join(process.cwd(), file), 'utf8')
beforeEach(() => {
vi.clearAllMocks()
eventBus.clear()
})
afterEach(() => {
vi.unstubAllEnvs()
})
describe('Turnstile rollout state', () => {
it('keeps Auth available while the public site key is absent', () => {
expect(resolveTurnstileSiteKey(undefined)).toBeNull()
expect(resolveTurnstileSiteKey('')).toBeNull()
expect(resolveTurnstileSiteKey(' ')).toBeNull()
expect(getTurnstileRolloutState(undefined)).toBe('disabled')
expect(isTurnstileSubmissionBlocked(null, undefined)).toBe(false)
})
it('treats an unsubstituted Docker sentinel as disabled', () => {
const sentinel = '__NEXT_PUBLIC_TURNSTILE_SITE_KEY__'
expect(resolveTurnstileSiteKey(sentinel)).toBeNull()
expect(getTurnstileRolloutState(sentinel)).toBe('disabled')
expect(isTurnstileSubmissionBlocked(null, sentinel)).toBe(false)
})
it('fails closed after the client site key is configured', () => {
const siteKey = ' public-site-key '
expect(resolveTurnstileSiteKey(siteKey)).toBe('public-site-key')
expect(getTurnstileRolloutState(siteKey)).toBe('client-enabled')
expect(isTurnstileSubmissionBlocked(null, siteKey)).toBe(true)
expect(isTurnstileSubmissionBlocked('', siteKey)).toBe(true)
expect(isTurnstileSubmissionBlocked('verified-token', siteKey)).toBe(false)
})
it('reads the runtime-substituted environment value at call time', () => {
vi.stubEnv('NEXT_PUBLIC_TURNSTILE_SITE_KEY', '')
expect(getTurnstileRolloutState()).toBe('disabled')
vi.stubEnv('NEXT_PUBLIC_TURNSTILE_SITE_KEY', 'runtime-site-key')
expect(getTurnstileRolloutState()).toBe('client-enabled')
})
it('forwards only a non-empty token to Supabase Auth', () => {
expect(captchaTokenOptions(null)).toEqual({})
expect(captchaTokenOptions(undefined)).toEqual({})
expect(captchaTokenOptions(' ')).toEqual({})
expect(captchaTokenOptions(' token-value ')).toEqual({
captchaToken: 'token-value',
})
})
})
describe('Turnstile integration contract', () => {
it('protects every public Supabase Auth flow in scope', () => {
const login = readRepoFile('app/(auth)/login/login-client.tsx')
const register = readRepoFile('app/(auth)/register/register-client.tsx')
const sandbox = readRepoFile('app/sandbox/page.tsx')
expect(login).toMatch(
/signInWithPassword\([\s\S]*?options: captchaTokenOptions\(passwordCaptchaToken\)/,
)
// The reset flow moved server-side (brands-table host resolution,
// 2026-09-07): the captcha token must travel to
// POST /api/auth/password-reset, and that route must forward it into
// the GoTrue resetPasswordForEmail call.
expect(login).toMatch(
/fetch\('\/api\/auth\/password-reset'[\s\S]*?captchaTokenOptions\(resetCaptchaToken\)/,
)
const resetRoute = readRepoFile('app/api/auth/password-reset/route.ts')
expect(resetRoute).toMatch(/resetPasswordForEmail\([\s\S]*?captchaToken/)
expect(login).toContain('action="accounted_login"')
expect(login).toContain('action="accounted_password_reset"')
// The register page's email flow moved server-side (invite-only brand
// domain gate, 2026-08-27): the captcha token must travel to
// POST /api/auth/signup, and that route must forward it into the GoTrue
// signUp call, so the CAPTCHA still guards the flow end to end.
expect(register).toMatch(
/fetch\('\/api\/auth\/signup'[\s\S]*?captchaTokenOptions\(captchaToken\)/,
)
expect(register).toContain('action="accounted_signup"')
const signupRoute = readRepoFile('app/api/auth/signup/route.ts')
expect(signupRoute).toMatch(/signUp\(\{[\s\S]*?captchaToken/)
expect(sandbox).toMatch(
/signInAnonymously\([\s\S]*?captchaTokenOptions\(captchaToken\)/,
)
expect(sandbox).toContain('action="accounted_sandbox"')
})
it('keeps the public key, CSP, and Docker runtime contract in sync', () => {
const envExample = readRepoFile('.env.example')
const dockerEnvExample = readRepoFile('.env.docker.example')
const dockerfile = readRepoFile('Dockerfile')
const entrypoint = readRepoFile('docker-entrypoint.sh')
const nextConfig = readRepoFile('next.config.ts')
expect(envExample).toContain('NEXT_PUBLIC_TURNSTILE_SITE_KEY=')
expect(dockerEnvExample).toContain('NEXT_PUBLIC_TURNSTILE_SITE_KEY=')
expect(dockerfile).toContain(
'NEXT_PUBLIC_TURNSTILE_SITE_KEY=__NEXT_PUBLIC_TURNSTILE_SITE_KEY__',
)
expect(entrypoint).toContain('__NEXT_PUBLIC_TURNSTILE_SITE_KEY__')
expect(nextConfig).toContain('https://challenges.cloudflare.com')
expect(nextConfig).toMatch(/script-src[\s\S]*?turnstileOrigin/)
expect(nextConfig).toMatch(/frame-src[\s\S]*?turnstileOrigin/)
expect(envExample).not.toContain('TURNSTILE_SECRET_KEY')
expect(dockerEnvExample).not.toContain('TURNSTILE_SECRET_KEY')
})
it('ships matching Swedish and English challenge messages', () => {
const swedish = JSON.parse(readRepoFile('messages/sv.json')).auth
const english = JSON.parse(readRepoFile('messages/en.json')).auth
const keys = [
'turnstile_checking',
'turnstile_required',
'turnstile_error',
]
for (const key of keys) {
expect(swedish[key]).toBeTypeOf('string')
expect(swedish[key]).not.toBe('')
expect(english[key]).toBeTypeOf('string')
expect(english[key]).not.toBe('')
}
})
})