docs(production): standardiserad produktionsberedskap och gap-analys
Lägger docs/production-readiness.md och siax/production-gaps.json enligt SIAX Master Definition of Done. Underlag: git-, kod- och live-evidens 2026-11-11. Nivån är evidensbaserad, inte ett leveransgodkännande.
This commit is contained in:
@@ -1,360 +0,0 @@
|
||||
/**
|
||||
* Tests for POST /api/auth/email-hook (Supabase Send Email hook).
|
||||
*
|
||||
* Unauthenticated by design: the guard is the Standard Webhooks signature.
|
||||
* Signature material is computed with node:crypto exactly like Supabase does.
|
||||
*/
|
||||
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'
|
||||
import { createHmac, randomBytes } from 'node:crypto'
|
||||
import type { Brand } from '@/lib/branding/resolve'
|
||||
|
||||
vi.mock('@/lib/init', () => ({ ensureInitialized: vi.fn() }))
|
||||
|
||||
const resolveBrandResultByHostMock = vi.hoisted(() => vi.fn())
|
||||
vi.mock('@/lib/branding/resolve', () => ({
|
||||
resolveBrandByHost: vi.fn(),
|
||||
// The one registry read: the trusted-origin resolver classifies the
|
||||
// redirect_to host through it, and the hook reads the sender brand from it.
|
||||
resolveBrandResultByHost: (...args: unknown[]) => resolveBrandResultByHostMock(...args),
|
||||
// Imported by lib/email/brand-sender (not called on the hook path).
|
||||
resolveBrandForCompany: vi.fn(),
|
||||
}))
|
||||
|
||||
const CANONICAL = 'https://app.gnubok.se'
|
||||
/** The one registered brand host in these tests; everything else is unknown. */
|
||||
const BRAND_HOST = 'app.siffra.se'
|
||||
|
||||
vi.mock('@/lib/branding/service', () => ({
|
||||
getBranding: () => ({ appName: 'Accounted', appUrl: 'https://app.gnubok.se' }),
|
||||
}))
|
||||
|
||||
const sendEmailMock = vi.hoisted(() => vi.fn())
|
||||
vi.mock('@/lib/email/service', () => ({
|
||||
getEmailService: () => ({ sendEmail: sendEmailMock, isConfigured: () => true }),
|
||||
}))
|
||||
|
||||
import { POST } from '../route'
|
||||
|
||||
const KEY = randomBytes(24)
|
||||
const SECRET = `v1,whsec_${KEY.toString('base64')}`
|
||||
|
||||
function makeBrand(overrides: Partial<Brand> = {}): Brand {
|
||||
return {
|
||||
id: 'brand-1',
|
||||
teamId: 'team-1',
|
||||
domain: 'app.siffra.se',
|
||||
appName: 'Siffra',
|
||||
logoUrl: null,
|
||||
brandColor: '#123456',
|
||||
chromeColor: null,
|
||||
fontKey: 'default',
|
||||
supportEmail: '[email protected]',
|
||||
authEmailFrom: '[email protected]',
|
||||
senderDomain: 'post.siffra.se',
|
||||
senderDomainStatus: 'verified',
|
||||
resendDomainId: 'rd-1',
|
||||
signupMode: 'open',
|
||||
...overrides,
|
||||
}
|
||||
}
|
||||
|
||||
function signedRequest(rawBody: string, opts?: { badSignature?: boolean; headers?: Record<string, string> }): Request {
|
||||
const id = 'msg_1'
|
||||
const timestamp = String(Math.floor(Date.now() / 1000))
|
||||
const signature = createHmac('sha256', KEY)
|
||||
.update(`${id}.${timestamp}.${rawBody}`)
|
||||
.digest('base64')
|
||||
return new Request('http://localhost:3000/api/auth/email-hook', {
|
||||
method: 'POST',
|
||||
body: rawBody,
|
||||
headers: {
|
||||
'content-type': 'application/json',
|
||||
'webhook-id': id,
|
||||
'webhook-timestamp': timestamp,
|
||||
'webhook-signature': opts?.badSignature ? 'v1,AAAA' : `v1,${signature}`,
|
||||
...opts?.headers,
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
function hookPayload(overrides?: {
|
||||
user?: Record<string, unknown>
|
||||
email_data?: Record<string, unknown>
|
||||
}): string {
|
||||
return JSON.stringify({
|
||||
user: { email: '[email protected]', ...overrides?.user },
|
||||
email_data: {
|
||||
token: '123456',
|
||||
token_hash: 'hash-1',
|
||||
redirect_to: 'https://app.gnubok.se/auth/callback?next=/reset-password',
|
||||
email_action_type: 'recovery',
|
||||
site_url: 'https://app.gnubok.se',
|
||||
...overrides?.email_data,
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
const ORIGINAL_APP_URL = process.env.NEXT_PUBLIC_APP_URL
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
process.env.SUPABASE_SEND_EMAIL_HOOK_SECRET = SECRET
|
||||
process.env.NEXT_PUBLIC_APP_URL = CANONICAL
|
||||
resolveBrandResultByHostMock.mockImplementation(async (host: string) => ({
|
||||
brand: host === BRAND_HOST ? makeBrand() : null,
|
||||
lookupFailed: false,
|
||||
}))
|
||||
sendEmailMock.mockResolvedValue({ success: true, messageId: 'msg-1' })
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
delete process.env.SUPABASE_SEND_EMAIL_HOOK_SECRET
|
||||
if (ORIGINAL_APP_URL === undefined) delete process.env.NEXT_PUBLIC_APP_URL
|
||||
else process.env.NEXT_PUBLIC_APP_URL = ORIGINAL_APP_URL
|
||||
})
|
||||
|
||||
describe('POST /api/auth/email-hook', () => {
|
||||
it('returns 500 when the hook secret is not configured', async () => {
|
||||
delete process.env.SUPABASE_SEND_EMAIL_HOOK_SECRET
|
||||
const res = await POST(signedRequest(hookPayload()))
|
||||
expect(res.status).toBe(500)
|
||||
expect(sendEmailMock).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('returns 401 for an invalid signature', async () => {
|
||||
const res = await POST(signedRequest(hookPayload(), { badSignature: true }))
|
||||
expect(res.status).toBe(401)
|
||||
expect(sendEmailMock).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('returns 400 for a signed but malformed payload', async () => {
|
||||
const res = await POST(signedRequest('not-json'))
|
||||
expect(res.status).toBe(400)
|
||||
expect(sendEmailMock).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('sends canonical recovery mail linking to the originating host (no brand)', async () => {
|
||||
const res = await POST(signedRequest(hookPayload()))
|
||||
expect(res.status).toBe(200)
|
||||
await expect(res.json()).resolves.toEqual({})
|
||||
|
||||
expect(sendEmailMock).toHaveBeenCalledTimes(1)
|
||||
const options = sendEmailMock.mock.calls[0][0]
|
||||
expect(options.to).toBe('[email protected]')
|
||||
expect(options.subject).toBe('Återställ ditt lösenord')
|
||||
expect(options.fromName).toBeUndefined()
|
||||
expect(options.fromAddress).toBeUndefined()
|
||||
expect(options.replyTo).toBeUndefined()
|
||||
// token_hash + verifyOtp pattern on the originating host, preserving the
|
||||
// existing next=/reset-password query.
|
||||
expect(options.text).toContain('https://app.gnubok.se/auth/callback?next=%2Freset-password')
|
||||
expect(options.text).toContain('token_hash=hash-1')
|
||||
expect(options.text).toContain('type=recovery')
|
||||
})
|
||||
|
||||
it('brands the mail from the redirect_to host and rides the verified brand sender', async () => {
|
||||
const res = await POST(
|
||||
signedRequest(
|
||||
hookPayload({
|
||||
email_data: {
|
||||
email_action_type: 'signup',
|
||||
redirect_to: 'https://app.siffra.se/auth/callback',
|
||||
},
|
||||
}),
|
||||
),
|
||||
)
|
||||
expect(res.status).toBe(200)
|
||||
expect(resolveBrandResultByHostMock).toHaveBeenCalledWith('app.siffra.se')
|
||||
|
||||
const options = sendEmailMock.mock.calls[0][0]
|
||||
expect(options.fromName).toBe('Siffra')
|
||||
expect(options.fromAddress).toBe('[email protected]')
|
||||
expect(options.replyTo).toBe('[email protected]')
|
||||
expect(options.html).toContain('Siffra')
|
||||
expect(options.html).not.toMatch(/accounted/i)
|
||||
expect(options.text).toContain('https://app.siffra.se/auth/callback?token_hash=hash-1')
|
||||
expect(options.text).toContain('type=signup')
|
||||
})
|
||||
|
||||
it('uses the via-fallback for a brand without a verified sender domain', async () => {
|
||||
resolveBrandResultByHostMock.mockResolvedValue({
|
||||
brand: makeBrand({ senderDomainStatus: 'pending' }),
|
||||
lookupFailed: false,
|
||||
})
|
||||
await POST(
|
||||
signedRequest(
|
||||
hookPayload({
|
||||
email_data: {
|
||||
email_action_type: 'magiclink',
|
||||
redirect_to: 'https://app.siffra.se/auth/callback',
|
||||
},
|
||||
}),
|
||||
),
|
||||
)
|
||||
const options = sendEmailMock.mock.calls[0][0]
|
||||
expect(options.fromName).toBe('Siffra')
|
||||
expect(options.fromAddress).toBeUndefined()
|
||||
})
|
||||
|
||||
it('sends two mails for a secure email change', async () => {
|
||||
await POST(
|
||||
signedRequest(
|
||||
hookPayload({
|
||||
user: { email: '[email protected]', new_email: '[email protected]' },
|
||||
email_data: {
|
||||
email_action_type: 'email_change',
|
||||
token_hash: 'hash-new-address',
|
||||
token_hash_new: 'hash-current-address',
|
||||
redirect_to: 'https://app.gnubok.se/auth/callback',
|
||||
},
|
||||
}),
|
||||
),
|
||||
)
|
||||
expect(sendEmailMock).toHaveBeenCalledTimes(2)
|
||||
const first = sendEmailMock.mock.calls[0][0]
|
||||
const second = sendEmailMock.mock.calls[1][0]
|
||||
// token_hash confirms at the NEW address, token_hash_new at the current.
|
||||
expect(first.to).toBe('[email protected]')
|
||||
expect(first.text).toContain('token_hash=hash-new-address')
|
||||
expect(second.to).toBe('[email protected]')
|
||||
expect(second.text).toContain('token_hash=hash-current-address')
|
||||
})
|
||||
|
||||
it('sends the OTP code for reauthentication without a link', async () => {
|
||||
await POST(
|
||||
signedRequest(
|
||||
hookPayload({
|
||||
email_data: { email_action_type: 'reauthentication', token: '424242' },
|
||||
}),
|
||||
),
|
||||
)
|
||||
const options = sendEmailMock.mock.calls[0][0]
|
||||
expect(options.subject).toBe('Din verifieringskod')
|
||||
expect(options.text).toContain('424242')
|
||||
expect(options.text).not.toContain('token_hash=')
|
||||
})
|
||||
|
||||
it('builds the callback URL when redirect_to points at a plain path', async () => {
|
||||
await POST(
|
||||
signedRequest(
|
||||
hookPayload({
|
||||
email_data: {
|
||||
email_action_type: 'magiclink',
|
||||
redirect_to: 'https://app.gnubok.se/settings/account',
|
||||
},
|
||||
}),
|
||||
),
|
||||
)
|
||||
const options = sendEmailMock.mock.calls[0][0]
|
||||
expect(options.text).toContain('https://app.gnubok.se/auth/callback?next=%2Fsettings%2Faccount')
|
||||
expect(options.text).toContain('type=magiclink')
|
||||
})
|
||||
|
||||
it('returns 500 when the email provider fails, so Supabase retries', async () => {
|
||||
sendEmailMock.mockResolvedValue({ success: false, error: 'provider down' })
|
||||
const res = await POST(signedRequest(hookPayload()))
|
||||
expect(res.status).toBe(500)
|
||||
})
|
||||
|
||||
describe('redirect_to destinations (signature proves the sender, not the destination)', () => {
|
||||
it.each([
|
||||
['an unknown host', 'https://evil.example/auth/callback?next=/reset-password'],
|
||||
['a lookalike of a registered host', 'https://app.siffra.se.evil.example/auth/callback'],
|
||||
['a registered host on a non-default port', 'https://app.siffra.se:8443/auth/callback'],
|
||||
['a credential-bearing URL', 'https://[email protected]/auth/callback'],
|
||||
// URL.origin drops userinfo: the host alone would pass as trusted.
|
||||
['credentials on a registered host', 'https://[email protected]/auth/callback?next=/x'],
|
||||
['credentials on the canonical host', 'https://user:[email protected]/auth/callback?next=/x'],
|
||||
['a malformed value', 'not a url'],
|
||||
])('links %s to the canonical callback without the requested path', async (_label, redirectTo) => {
|
||||
const res = await POST(
|
||||
signedRequest(hookPayload({ email_data: { redirect_to: redirectTo } })),
|
||||
)
|
||||
expect(res.status).toBe(200)
|
||||
|
||||
const options = sendEmailMock.mock.calls[0][0]
|
||||
expect(options.text).toContain(
|
||||
'https://app.gnubok.se/auth/callback?token_hash=hash-1&type=recovery',
|
||||
)
|
||||
expect(options.text).not.toContain('evil.example')
|
||||
expect(options.text).not.toContain(':8443')
|
||||
expect(options.text).not.toContain('next=')
|
||||
// Canonical link means canonical sender: brand and destination agree.
|
||||
expect(options.fromName).toBeUndefined()
|
||||
expect(options.fromAddress).toBeUndefined()
|
||||
})
|
||||
|
||||
it('upgrades http on a registered brand host to https and drops the requested path', async () => {
|
||||
await POST(
|
||||
signedRequest(
|
||||
hookPayload({
|
||||
email_data: { redirect_to: 'http://app.siffra.se/auth/callback?next=/settings' },
|
||||
}),
|
||||
),
|
||||
)
|
||||
const options = sendEmailMock.mock.calls[0][0]
|
||||
expect(options.text).toContain(
|
||||
'https://app.siffra.se/auth/callback?token_hash=hash-1&type=recovery',
|
||||
)
|
||||
expect(options.text).not.toContain('http://')
|
||||
expect(options.text).not.toContain('next=')
|
||||
expect(options.fromName).toBe('Siffra')
|
||||
})
|
||||
|
||||
it('keeps the requested path on a registered brand host', async () => {
|
||||
await POST(
|
||||
signedRequest(
|
||||
hookPayload({
|
||||
email_data: { redirect_to: 'https://app.siffra.se/auth/callback?next=%2Freset-password' },
|
||||
}),
|
||||
),
|
||||
)
|
||||
const options = sendEmailMock.mock.calls[0][0]
|
||||
expect(options.text).toContain(
|
||||
'https://app.siffra.se/auth/callback?next=%2Freset-password&token_hash=hash-1',
|
||||
)
|
||||
expect(options.fromName).toBe('Siffra')
|
||||
})
|
||||
|
||||
it('falls back to the canonical callback when redirect_to is missing', async () => {
|
||||
await POST(signedRequest(hookPayload({ email_data: { redirect_to: undefined } })))
|
||||
const options = sendEmailMock.mock.calls[0][0]
|
||||
expect(options.text).toContain('https://app.gnubok.se/auth/callback?token_hash=hash-1')
|
||||
})
|
||||
|
||||
it('returns 500 without sending when the brand read fails after the origin resolved', async () => {
|
||||
// First read (origin classification) succeeds, second (sender) fails:
|
||||
// never platform-branded mail carrying a brand link.
|
||||
resolveBrandResultByHostMock
|
||||
.mockResolvedValueOnce({ brand: makeBrand(), lookupFailed: false })
|
||||
.mockResolvedValueOnce({ brand: null, lookupFailed: true })
|
||||
const res = await POST(
|
||||
signedRequest(
|
||||
hookPayload({ email_data: { redirect_to: 'https://app.siffra.se/auth/callback' } }),
|
||||
),
|
||||
)
|
||||
expect(res.status).toBe(500)
|
||||
expect(sendEmailMock).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('still sends canonical mail when the brand read fails on the canonical origin', async () => {
|
||||
resolveBrandResultByHostMock.mockResolvedValue({ brand: null, lookupFailed: true })
|
||||
const res = await POST(signedRequest(hookPayload()))
|
||||
expect(res.status).toBe(200)
|
||||
const options = sendEmailMock.mock.calls[0][0]
|
||||
expect(options.text).toContain('https://app.gnubok.se/auth/callback?next=%2Freset-password')
|
||||
expect(options.fromName).toBeUndefined()
|
||||
})
|
||||
|
||||
it('returns 500 without sending when the brand registry cannot be read', async () => {
|
||||
resolveBrandResultByHostMock.mockResolvedValue({ brand: null, lookupFailed: true })
|
||||
const res = await POST(
|
||||
signedRequest(
|
||||
hookPayload({ email_data: { redirect_to: 'https://app.siffra.se/auth/callback' } }),
|
||||
),
|
||||
)
|
||||
expect(res.status).toBe(500)
|
||||
expect(sendEmailMock).not.toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -1,280 +0,0 @@
|
||||
import { NextResponse } from 'next/server'
|
||||
import { ensureInitialized } from '@/lib/init'
|
||||
import { createLogger } from '@/lib/logger'
|
||||
import { getEmailService } from '@/lib/email/service'
|
||||
import { getBranding } from '@/lib/branding/service'
|
||||
import { resolveBrandResultByHost } from '@/lib/branding/resolve'
|
||||
import { getSenderForBrand } from '@/lib/email/brand-sender'
|
||||
import { buildAuthEmail } from '@/lib/email/auth-templates'
|
||||
import { verifyStandardWebhookSignature } from '@/lib/email/standard-webhook'
|
||||
import {
|
||||
BrandLookupFailedError,
|
||||
getCanonicalAppOrigin,
|
||||
resolveTrustedAppOrigin,
|
||||
} from '@/lib/domains/trusted-app-origin'
|
||||
|
||||
// Loads the email extension so getEmailService() returns the Resend
|
||||
// implementation instead of the noop default.
|
||||
ensureInitialized()
|
||||
|
||||
const log = createLogger('auth-email-hook')
|
||||
|
||||
/**
|
||||
* POST /api/auth/email-hook: Supabase Auth "Send Email" hook (WL-05, WL-13).
|
||||
*
|
||||
* When enabled in Supabase (Auth > Hooks > Send Email, pointing at this URL
|
||||
* with the shared secret in SUPABASE_SEND_EMAIL_HOOK_SECRET), Supabase stops
|
||||
* sending auth mail itself and this endpoint sends every auth mail (signup
|
||||
* confirmation, recovery, magic link, invite, email change, reauthentication)
|
||||
* through the platform email service, branded per the requesting host: the
|
||||
* brand is resolved from the trusted redirect_to origin, so a
|
||||
* reset requested on app.partner.se is sent in the partner's brand and links
|
||||
* back to app.partner.se. Unknown hosts get canonical platform mail.
|
||||
*
|
||||
* Unauthenticated by design (server-to-server): authenticity comes from the
|
||||
* Standard Webhooks signature, not a session, exactly like the Stripe and
|
||||
* Resend webhook routes. The raw body is verified byte-for-byte before
|
||||
* parsing. The signature proves WHO sent the payload, not that every
|
||||
* destination in it should be followed: redirect_to is GoTrue's already
|
||||
* allowlisted referrer, but that allowlist is a glob configured by hand, so
|
||||
* the origin is resolved here again through lib/domains/trusted-app-origin
|
||||
* (canonical, this deployment's own Vercel hosts, or a registered brand
|
||||
* domain). Anything else gets a canonical link, and the token never rides
|
||||
* to a host this deployment does not serve. This endpoint is
|
||||
* availability-critical once the hook is enabled:
|
||||
* any internal failure returns 500 so Supabase retries (up to 3 times within
|
||||
* a 5 second budget); success returns 200 {} fast.
|
||||
*
|
||||
* Until the hook is switched on in Supabase this route is dormant and auth
|
||||
* mail keeps flowing from Supabase unchanged.
|
||||
*/
|
||||
|
||||
// verifyOtp types our /auth/callback confirm route accepts. Unknown action
|
||||
// types fall back to the generic 'email' type rather than dropping the mail.
|
||||
const VERIFY_TYPES = new Set([
|
||||
'signup',
|
||||
'recovery',
|
||||
'magiclink',
|
||||
'invite',
|
||||
'email_change',
|
||||
'email',
|
||||
])
|
||||
|
||||
interface SendEmailHookPayload {
|
||||
user?: {
|
||||
email?: string | null
|
||||
new_email?: string | null
|
||||
email_new?: string | null
|
||||
} | null
|
||||
email_data?: {
|
||||
token?: string
|
||||
token_hash?: string
|
||||
token_new?: string
|
||||
token_hash_new?: string
|
||||
redirect_to?: string
|
||||
email_action_type?: string
|
||||
site_url?: string
|
||||
} | null
|
||||
}
|
||||
|
||||
/**
|
||||
* Build the verify URL on the ORIGINATING host using the token_hash +
|
||||
* verifyOtp pattern (browser- and host-independent, per the WL-05 research):
|
||||
* /auth/callback consumes token_hash + type server-side and then honors the
|
||||
* `next` path. If redirect_to already points at /auth/callback (our client
|
||||
* flows do), its query (e.g. next=/reset-password) is preserved.
|
||||
*
|
||||
* `origin` is the already-trusted application origin; `redirectUrl` is the
|
||||
* requested redirect_to only when it sits on that origin, else null (the
|
||||
* link then lands on the origin's /auth/callback with no `next`).
|
||||
*/
|
||||
function buildActionUrl(
|
||||
origin: string,
|
||||
redirectUrl: URL | null,
|
||||
tokenHash: string,
|
||||
actionType: string,
|
||||
): string {
|
||||
const verifyType = VERIFY_TYPES.has(actionType) ? actionType : 'email'
|
||||
let url: URL
|
||||
if (redirectUrl && redirectUrl.pathname === '/auth/callback') {
|
||||
url = new URL(redirectUrl.toString())
|
||||
} else {
|
||||
url = new URL('/auth/callback', origin)
|
||||
if (redirectUrl) {
|
||||
const next = redirectUrl.pathname + redirectUrl.search
|
||||
if (next && next !== '/') url.searchParams.set('next', next)
|
||||
}
|
||||
}
|
||||
url.searchParams.set('token_hash', tokenHash)
|
||||
url.searchParams.set('type', verifyType)
|
||||
return url.toString()
|
||||
}
|
||||
|
||||
/**
|
||||
* The requested redirect_to, kept only when its origin is one this
|
||||
* deployment serves. The comparison is on the resolved origin, so an http
|
||||
* link to a hosted domain, a lookalike host, a non-default port or a
|
||||
* credential-bearing URL all collapse to the canonical /auth/callback.
|
||||
* Throws BrandLookupFailedError when the brands table cannot be read.
|
||||
*/
|
||||
async function resolveRedirect(
|
||||
requested: string | undefined,
|
||||
): Promise<{ origin: string; redirectUrl: URL | null }> {
|
||||
let requestedUrl: URL | null = null
|
||||
if (requested) {
|
||||
try {
|
||||
requestedUrl = new URL(requested)
|
||||
} catch {
|
||||
requestedUrl = null
|
||||
}
|
||||
}
|
||||
// URL.origin drops userinfo, so a credential-bearing redirect on a served
|
||||
// host would pass the origin comparison and be cloned into the link with
|
||||
// the credentials still in it. No flow of ours ever sends one: treat it as
|
||||
// untrusted outright (canonical link, no next), never as a served host.
|
||||
if (requestedUrl && (requestedUrl.username || requestedUrl.password)) {
|
||||
log.warn('redirect_to carries credentials; linking to the canonical origin', {
|
||||
host: requestedUrl.hostname,
|
||||
})
|
||||
requestedUrl = null
|
||||
}
|
||||
const origin = await resolveTrustedAppOrigin(requestedUrl?.origin ?? null)
|
||||
if (requestedUrl && requestedUrl.origin === origin) {
|
||||
return { origin, redirectUrl: requestedUrl }
|
||||
}
|
||||
if (requestedUrl) {
|
||||
// Hostname only: the URL may carry a query, never log the token side.
|
||||
log.warn('redirect_to origin is not a served host; linking to the canonical origin', {
|
||||
host: requestedUrl.hostname,
|
||||
})
|
||||
}
|
||||
return { origin, redirectUrl: null }
|
||||
}
|
||||
|
||||
export async function POST(request: Request) {
|
||||
const secret = process.env.SUPABASE_SEND_EMAIL_HOOK_SECRET
|
||||
if (!secret) {
|
||||
log.error('SUPABASE_SEND_EMAIL_HOOK_SECRET is not configured', undefined)
|
||||
return NextResponse.json({ error: 'Hook not configured' }, { status: 500 })
|
||||
}
|
||||
|
||||
const rawBody = await request.text()
|
||||
const verified = verifyStandardWebhookSignature({
|
||||
secret,
|
||||
payload: rawBody,
|
||||
id: request.headers.get('webhook-id'),
|
||||
timestamp: request.headers.get('webhook-timestamp'),
|
||||
signature: request.headers.get('webhook-signature'),
|
||||
})
|
||||
if (!verified) {
|
||||
return NextResponse.json({ error: 'Invalid signature' }, { status: 401 })
|
||||
}
|
||||
|
||||
let payload: SendEmailHookPayload
|
||||
try {
|
||||
payload = JSON.parse(rawBody) as SendEmailHookPayload
|
||||
} catch {
|
||||
return NextResponse.json({ error: 'Invalid payload' }, { status: 400 })
|
||||
}
|
||||
|
||||
const emailData = payload.email_data ?? {}
|
||||
const actionType = emailData.email_action_type || ''
|
||||
const recipient = payload.user?.email || null
|
||||
if (!recipient) {
|
||||
return NextResponse.json({ error: 'Missing recipient' }, { status: 400 })
|
||||
}
|
||||
|
||||
// Brand from the RESOLVED host: redirect_to carries the tenant origin, and
|
||||
// the sender identity must match the host the link lands on. A lookup
|
||||
// failure is a 500 so Supabase retries rather than sending a mail whose
|
||||
// link would land on the wrong domain.
|
||||
let resolved: Awaited<ReturnType<typeof resolveRedirect>>
|
||||
try {
|
||||
resolved = await resolveRedirect(emailData.redirect_to)
|
||||
} catch (err) {
|
||||
if (!(err instanceof BrandLookupFailedError)) throw err
|
||||
log.error('brand lookup failed while resolving redirect_to', err, { host: err.host })
|
||||
return NextResponse.json({ error: 'Origin lookup failed' }, { status: 500 })
|
||||
}
|
||||
const { origin, redirectUrl } = resolved
|
||||
// A brand host whose row cannot be read right now (a second registry read
|
||||
// can fail after the first succeeded) must not get platform-branded mail
|
||||
// carrying a brand link: 500, Supabase retries. On the canonical origin a
|
||||
// failed read is the platform sender either way, so it does not block.
|
||||
const brandResult = await resolveBrandResultByHost(new URL(origin).hostname)
|
||||
if (brandResult.lookupFailed && origin !== getCanonicalAppOrigin()) {
|
||||
log.error('brand lookup failed for the resolved origin', undefined, { origin })
|
||||
return NextResponse.json({ error: 'Origin lookup failed' }, { status: 500 })
|
||||
}
|
||||
const brand = brandResult.brand
|
||||
const sender = getSenderForBrand(brand)
|
||||
const appName = brand?.appName ?? getBranding().appName
|
||||
|
||||
// Compose the mail(s) for this hook invocation.
|
||||
const mails: Array<{ to: string; actionType: string; actionUrl?: string; otpCode?: string }> = []
|
||||
|
||||
if (actionType === 'reauthentication') {
|
||||
if (!emailData.token) {
|
||||
return NextResponse.json({ error: 'Missing token' }, { status: 400 })
|
||||
}
|
||||
mails.push({ to: recipient, actionType, otpCode: emailData.token })
|
||||
} else if (actionType === 'email_change') {
|
||||
// Secure email change sends TWO mails from one invocation. Documented
|
||||
// reversal: token_hash confirms at the NEW address, token_hash_new at
|
||||
// the CURRENT one.
|
||||
if (!emailData.token_hash) {
|
||||
return NextResponse.json({ error: 'Missing token_hash' }, { status: 400 })
|
||||
}
|
||||
const newEmail = payload.user?.new_email || payload.user?.email_new || recipient
|
||||
mails.push({
|
||||
to: newEmail,
|
||||
actionType: 'email_change',
|
||||
actionUrl: buildActionUrl(origin, redirectUrl, emailData.token_hash, 'email_change'),
|
||||
})
|
||||
if (emailData.token_hash_new) {
|
||||
mails.push({
|
||||
to: recipient,
|
||||
actionType: 'email_change_current',
|
||||
actionUrl: buildActionUrl(origin, redirectUrl, emailData.token_hash_new, 'email_change'),
|
||||
})
|
||||
}
|
||||
} else {
|
||||
if (!emailData.token_hash) {
|
||||
return NextResponse.json({ error: 'Missing token_hash' }, { status: 400 })
|
||||
}
|
||||
mails.push({
|
||||
to: recipient,
|
||||
actionType,
|
||||
actionUrl: buildActionUrl(origin, redirectUrl, emailData.token_hash, actionType),
|
||||
})
|
||||
}
|
||||
|
||||
const emailService = getEmailService()
|
||||
for (const mail of mails) {
|
||||
const built = buildAuthEmail({
|
||||
actionType: mail.actionType,
|
||||
appName,
|
||||
actionUrl: mail.actionUrl,
|
||||
otpCode: mail.otpCode,
|
||||
})
|
||||
const result = await emailService.sendEmail({
|
||||
to: mail.to,
|
||||
subject: built.subject,
|
||||
html: built.html,
|
||||
text: built.text,
|
||||
fromName: sender.fromName ?? undefined,
|
||||
fromAddress: sender.fromAddress ?? undefined,
|
||||
replyTo: sender.replyTo ?? undefined,
|
||||
})
|
||||
if (!result.success) {
|
||||
// Non-2xx makes Supabase retry, which is the recovery we want: auth
|
||||
// mail must not be silently dropped.
|
||||
log.error('auth mail send failed', new Error(result.error ?? 'unknown'), {
|
||||
actionType: mail.actionType,
|
||||
})
|
||||
return NextResponse.json({ error: 'Send failed' }, { status: 500 })
|
||||
}
|
||||
}
|
||||
|
||||
return NextResponse.json({})
|
||||
}
|
||||
@@ -1,217 +0,0 @@
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import { NextResponse } from 'next/server'
|
||||
import {
|
||||
createSessionTimeoutState,
|
||||
signSessionTimeoutState,
|
||||
verifySessionTimeoutState,
|
||||
} from '@/lib/auth/session-timeout'
|
||||
import { SESSION_TIMEOUT_COOKIE } from '@/lib/auth/session-timeout-shared'
|
||||
|
||||
const mocks = vi.hoisted(() => ({
|
||||
requireAuth: vi.fn(),
|
||||
cookieValue: undefined as string | undefined,
|
||||
}))
|
||||
|
||||
vi.mock('@/lib/auth/require-auth', () => ({
|
||||
requireAuth: mocks.requireAuth,
|
||||
}))
|
||||
|
||||
vi.mock('next/headers', () => ({
|
||||
cookies: vi.fn(async () => ({
|
||||
get: (name: string) => name === SESSION_TIMEOUT_COOKIE && mocks.cookieValue
|
||||
? { name, value: mocks.cookieValue }
|
||||
: undefined,
|
||||
})),
|
||||
}))
|
||||
|
||||
import { GET, POST } from '../route'
|
||||
|
||||
const preference = { autoLogout: false, error: null as unknown }
|
||||
|
||||
const supabase = {
|
||||
auth: {
|
||||
getClaims: vi.fn(async () => ({
|
||||
data: { claims: { session_id: 'session-1' } },
|
||||
})),
|
||||
},
|
||||
from: vi.fn(() => ({
|
||||
select: vi.fn(() => ({
|
||||
eq: vi.fn(() => ({
|
||||
maybeSingle: vi.fn(async () => ({
|
||||
data: preference.error ? null : { auto_logout: preference.autoLogout },
|
||||
error: preference.error,
|
||||
})),
|
||||
})),
|
||||
})),
|
||||
})),
|
||||
}
|
||||
|
||||
describe('session heartbeat route', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
process.env.SESSION_TIMEOUT_SECRET = 'heartbeat-test-secret'
|
||||
process.env.NEXT_PUBLIC_SESSION_IDLE_TIMEOUT_MS = '30000'
|
||||
process.env.NEXT_PUBLIC_SESSION_ABSOLUTE_TIMEOUT_MS = '60000'
|
||||
process.env.NEXT_PUBLIC_SESSION_WARNING_MS = '10000'
|
||||
mocks.requireAuth.mockResolvedValue({
|
||||
user: { id: 'user-1' },
|
||||
supabase,
|
||||
error: null,
|
||||
})
|
||||
mocks.cookieValue = undefined
|
||||
preference.autoLogout = false
|
||||
preference.error = null
|
||||
})
|
||||
|
||||
async function setState(args?: {
|
||||
startedAt?: number
|
||||
lastActivityAt?: number
|
||||
sessionId?: string
|
||||
autoLogout?: boolean
|
||||
}) {
|
||||
const state = {
|
||||
...createSessionTimeoutState({
|
||||
userId: 'user-1',
|
||||
sessionId: args?.sessionId ?? 'session-1',
|
||||
method: 'password',
|
||||
// Default the opt-in to true: most cases here exercise enforcement.
|
||||
autoLogout: args?.autoLogout ?? true,
|
||||
now: args?.startedAt ?? Date.now(),
|
||||
}),
|
||||
...(args?.lastActivityAt === undefined
|
||||
? {}
|
||||
: { lastActivityAt: args.lastActivityAt }),
|
||||
}
|
||||
mocks.cookieValue = (await signSessionTimeoutState(state)) ?? undefined
|
||||
return state
|
||||
}
|
||||
|
||||
it('returns the server-authoritative timeout state without extending it on GET', async () => {
|
||||
const state = await setState()
|
||||
|
||||
const response = await GET()
|
||||
|
||||
expect(response.status).toBe(200)
|
||||
await expect(response.json()).resolves.toMatchObject({
|
||||
data: {
|
||||
enabled: true,
|
||||
startedAt: state.startedAt,
|
||||
lastActivityAt: state.lastActivityAt,
|
||||
},
|
||||
})
|
||||
expect(response.cookies.get(SESSION_TIMEOUT_COOKIE)).toBeUndefined()
|
||||
})
|
||||
|
||||
it('advances activity and rotates the signed cookie on POST', async () => {
|
||||
const state = await setState({ startedAt: Date.now() - 1000 })
|
||||
|
||||
const response = await POST()
|
||||
|
||||
expect(response.status).toBe(200)
|
||||
const rotated = response.cookies.get(SESSION_TIMEOUT_COOKIE)?.value
|
||||
expect(rotated).toBeTruthy()
|
||||
await expect(verifySessionTimeoutState(rotated)).resolves.toMatchObject({
|
||||
startedAt: state.startedAt,
|
||||
lastActivityAt: expect.any(Number),
|
||||
})
|
||||
})
|
||||
|
||||
it('rejects an expired state', async () => {
|
||||
const now = Date.now()
|
||||
await setState({ startedAt: now - 60_000, lastActivityAt: now - 1 })
|
||||
const expired = await GET()
|
||||
expect(expired.status).toBe(401)
|
||||
expect(expired.headers.get('x-session-timeout-reason')).toBe('absolute')
|
||||
})
|
||||
|
||||
it('initializes fresh state for a missing or mismatched cookie like middleware', async () => {
|
||||
const missing = await GET()
|
||||
expect(missing.status).toBe(200)
|
||||
const initialized = missing.cookies.get(SESSION_TIMEOUT_COOKIE)?.value
|
||||
expect(initialized).toBeTruthy()
|
||||
await expect(verifySessionTimeoutState(initialized)).resolves.toMatchObject({
|
||||
userId: 'user-1',
|
||||
sessionId: 'session-1',
|
||||
})
|
||||
|
||||
await setState({ sessionId: 'another-session' })
|
||||
const mismatch = await GET()
|
||||
expect(mismatch.status).toBe(200)
|
||||
const reminted = mismatch.cookies.get(SESSION_TIMEOUT_COOKIE)?.value
|
||||
expect(reminted).toBeTruthy()
|
||||
await expect(verifySessionTimeoutState(reminted)).resolves.toMatchObject({
|
||||
sessionId: 'session-1',
|
||||
})
|
||||
})
|
||||
|
||||
it('reports enabled: false and never expires an opted-out session', async () => {
|
||||
const now = Date.now()
|
||||
// Times that would be long expired if enforcement applied.
|
||||
await setState({
|
||||
startedAt: now - 120_000,
|
||||
lastActivityAt: now - 120_000,
|
||||
autoLogout: false,
|
||||
})
|
||||
|
||||
const response = await GET()
|
||||
|
||||
expect(response.status).toBe(200)
|
||||
await expect(response.json()).resolves.toMatchObject({
|
||||
data: { enabled: false },
|
||||
})
|
||||
})
|
||||
|
||||
it('upgrades a pre-toggle cookie in place, keeping its timers', async () => {
|
||||
preference.autoLogout = true
|
||||
const startedAt = Date.now() - 5_000
|
||||
const legacy: Record<string, unknown> = {
|
||||
...createSessionTimeoutState({
|
||||
userId: 'user-1',
|
||||
sessionId: 'session-1',
|
||||
method: 'password',
|
||||
autoLogout: true,
|
||||
now: startedAt,
|
||||
}),
|
||||
}
|
||||
delete legacy.autoLogout
|
||||
mocks.cookieValue =
|
||||
(await signSessionTimeoutState(
|
||||
legacy as Parameters<typeof signSessionTimeoutState>[0],
|
||||
)) ?? undefined
|
||||
|
||||
const response = await GET()
|
||||
|
||||
expect(response.status).toBe(200)
|
||||
const upgraded = response.cookies.get(SESSION_TIMEOUT_COOKIE)?.value
|
||||
expect(upgraded).toBeTruthy()
|
||||
await expect(verifySessionTimeoutState(upgraded)).resolves.toMatchObject({
|
||||
startedAt,
|
||||
autoLogout: true,
|
||||
})
|
||||
})
|
||||
|
||||
it('answers without persisting a snapshot when the preference read fails', async () => {
|
||||
preference.error = { message: 'connection reset' }
|
||||
const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => {})
|
||||
|
||||
const response = await GET()
|
||||
|
||||
expect(response.status).toBe(200)
|
||||
await expect(response.json()).resolves.toMatchObject({
|
||||
data: { enabled: false },
|
||||
})
|
||||
// No cookie: the unknown preference must not be baked into a snapshot.
|
||||
expect(response.cookies.get(SESSION_TIMEOUT_COOKIE)).toBeUndefined()
|
||||
errorSpy.mockRestore()
|
||||
})
|
||||
|
||||
it('passes through the existing authentication error', async () => {
|
||||
mocks.requireAuth.mockResolvedValue({
|
||||
user: null,
|
||||
supabase,
|
||||
error: NextResponse.json({ error: 'Unauthorized' }, { status: 401 }),
|
||||
})
|
||||
|
||||
expect((await GET()).status).toBe(401)
|
||||
})
|
||||
})
|
||||
@@ -1,145 +0,0 @@
|
||||
import { cookies } from 'next/headers'
|
||||
import { NextResponse } from 'next/server'
|
||||
import type { SupabaseClient } from '@supabase/supabase-js'
|
||||
import { requireAuth } from '@/lib/auth/require-auth'
|
||||
import {
|
||||
createSessionTimeoutState,
|
||||
evaluateSessionTimeout,
|
||||
fetchAutoLogoutPreference,
|
||||
getSessionTimeoutConfig,
|
||||
sessionStateMatchesUser,
|
||||
sessionStateNeedsRemint,
|
||||
sessionTimeoutCookieOptions,
|
||||
signSessionTimeoutState,
|
||||
toSessionTimeoutClientState,
|
||||
verifySessionTimeoutState,
|
||||
} from '@/lib/auth/session-timeout'
|
||||
import {
|
||||
SESSION_AUTH_METHOD_HINT_COOKIE,
|
||||
SESSION_TIMEOUT_COOKIE,
|
||||
isSessionAuthMethod,
|
||||
type SessionTimeoutReason,
|
||||
} from '@/lib/auth/session-timeout-shared'
|
||||
|
||||
export const dynamic = 'force-dynamic'
|
||||
|
||||
async function getSessionId(supabase: SupabaseClient): Promise<string | null> {
|
||||
if (typeof supabase.auth.getClaims !== 'function') return null
|
||||
|
||||
try {
|
||||
const { data } = await supabase.auth.getClaims()
|
||||
return typeof data?.claims?.session_id === 'string'
|
||||
? data.claims.session_id
|
||||
: null
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
function expiredResponse(reason: SessionTimeoutReason): NextResponse {
|
||||
const response = NextResponse.json(
|
||||
{ error: { code: 'SESSION_EXPIRED', reason } },
|
||||
{ status: 401 },
|
||||
)
|
||||
response.headers.set('X-Session-Timeout-Reason', reason)
|
||||
response.headers.set('Cache-Control', 'no-store')
|
||||
return response
|
||||
}
|
||||
|
||||
async function heartbeat(updateActivity: boolean): Promise<NextResponse> {
|
||||
const auth = await requireAuth()
|
||||
if (auth.error) return auth.error
|
||||
|
||||
const config = getSessionTimeoutConfig()
|
||||
const now = Date.now()
|
||||
|
||||
if (!config.enabled) {
|
||||
return NextResponse.json({
|
||||
data: {
|
||||
enabled: false,
|
||||
idleTimeoutMs: 0,
|
||||
absoluteTimeoutMs: 0,
|
||||
warningMs: 0,
|
||||
serverNow: now,
|
||||
startedAt: now,
|
||||
lastActivityAt: now,
|
||||
method: 'password',
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
const cookieStore = await cookies()
|
||||
const encodedState = cookieStore.get(SESSION_TIMEOUT_COOKIE)?.value
|
||||
const state = await verifySessionTimeoutState(encodedState)
|
||||
const sessionId = await getSessionId(auth.supabase)
|
||||
|
||||
const stateMatches =
|
||||
state !== null && sessionStateMatchesUser(state, auth.user.id, sessionId)
|
||||
|
||||
if (!state || !stateMatches || sessionStateNeedsRemint(state)) {
|
||||
// Mirror middleware initialization: a missing, session-mismatched, or
|
||||
// pre-toggle cookie means the timeout state has not been established
|
||||
// for this session yet, not that the session expired.
|
||||
const hintedMethod = cookieStore.get(SESSION_AUTH_METHOD_HINT_COOKIE)?.value
|
||||
const autoLogout = await fetchAutoLogoutPreference(auth.supabase, auth.user.id)
|
||||
const freshState = state && stateMatches
|
||||
? { ...state, autoLogout: autoLogout ?? false }
|
||||
: createSessionTimeoutState({
|
||||
userId: auth.user.id,
|
||||
sessionId,
|
||||
method: isSessionAuthMethod(hintedMethod) ? hintedMethod : 'password',
|
||||
autoLogout: autoLogout ?? false,
|
||||
now,
|
||||
})
|
||||
const response = NextResponse.json({
|
||||
data: toSessionTimeoutClientState(freshState, config, now),
|
||||
})
|
||||
response.headers.set('Cache-Control', 'no-store')
|
||||
// Unknown preference (failed read): answer this poll without persisting
|
||||
// a fail-open snapshot; the next resync retries the read (mirrors the
|
||||
// middleware).
|
||||
if (autoLogout !== null) {
|
||||
const signedFresh = await signSessionTimeoutState(freshState)
|
||||
if (signedFresh) {
|
||||
response.cookies.set(
|
||||
SESSION_TIMEOUT_COOKIE,
|
||||
signedFresh,
|
||||
sessionTimeoutCookieOptions(),
|
||||
)
|
||||
}
|
||||
}
|
||||
return response
|
||||
}
|
||||
|
||||
const reason = evaluateSessionTimeout(state, config, now)
|
||||
if (reason) return expiredResponse(reason)
|
||||
|
||||
const nextState = updateActivity
|
||||
? { ...state, lastActivityAt: now }
|
||||
: state
|
||||
const response = NextResponse.json({
|
||||
data: toSessionTimeoutClientState(nextState, config, now),
|
||||
})
|
||||
response.headers.set('Cache-Control', 'no-store')
|
||||
|
||||
if (updateActivity) {
|
||||
const signedNext = await signSessionTimeoutState(nextState)
|
||||
if (signedNext) {
|
||||
response.cookies.set(
|
||||
SESSION_TIMEOUT_COOKIE,
|
||||
signedNext,
|
||||
sessionTimeoutCookieOptions(),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
return response
|
||||
}
|
||||
|
||||
export async function GET(): Promise<NextResponse> {
|
||||
return heartbeat(false)
|
||||
}
|
||||
|
||||
export async function POST(): Promise<NextResponse> {
|
||||
return heartbeat(true)
|
||||
}
|
||||
@@ -1,101 +0,0 @@
|
||||
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'
|
||||
import { parseJsonResponse } from '@/tests/helpers'
|
||||
|
||||
const resetPasswordForEmailMock = vi.hoisted(() => vi.fn())
|
||||
vi.mock('@/lib/supabase/server', () => ({
|
||||
createClient: vi.fn(async () => ({
|
||||
auth: { resetPasswordForEmail: resetPasswordForEmailMock },
|
||||
})),
|
||||
}))
|
||||
|
||||
const resolveBrandResultByHostMock = vi.hoisted(() => vi.fn())
|
||||
vi.mock('@/lib/branding/resolve', () => ({
|
||||
resolveBrandResultByHost: (...args: unknown[]) => resolveBrandResultByHostMock(...args),
|
||||
}))
|
||||
|
||||
import { POST } from '../route'
|
||||
|
||||
function makeRequest(body: unknown, headers: Record<string, string> = {}): Request {
|
||||
return new Request('https://internal/api/auth/password-reset', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json', ...headers },
|
||||
body: JSON.stringify(body),
|
||||
})
|
||||
}
|
||||
|
||||
const ORIGINAL_APP_URL = process.env.NEXT_PUBLIC_APP_URL
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
process.env.NEXT_PUBLIC_APP_URL = 'https://app.accounted.test'
|
||||
resetPasswordForEmailMock.mockResolvedValue({ data: {}, error: null })
|
||||
resolveBrandResultByHostMock.mockImplementation(async (host: string) => ({
|
||||
brand: host === 'app.testbrand.example' ? { domain: host } : null,
|
||||
lookupFailed: false,
|
||||
}))
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
if (ORIGINAL_APP_URL === undefined) delete process.env.NEXT_PUBLIC_APP_URL
|
||||
else process.env.NEXT_PUBLIC_APP_URL = ORIGINAL_APP_URL
|
||||
})
|
||||
|
||||
describe('POST /api/auth/password-reset', () => {
|
||||
it('400s on invalid body', async () => {
|
||||
const res = await POST(makeRequest({ email: 'not-an-email' }))
|
||||
expect(res.status).toBe(400)
|
||||
expect(resetPasswordForEmailMock).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('sends the recovery callback on a registered brand host', async () => {
|
||||
const res = await POST(
|
||||
makeRequest(
|
||||
{ email: ' [email protected] ', captchaToken: 'tok' },
|
||||
{ host: 'internal', 'x-forwarded-host': 'app.testbrand.example' },
|
||||
),
|
||||
)
|
||||
const { body: json } = await parseJsonResponse<{ data: { status: string } }>(res)
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
expect(json.data.status).toBe('sent')
|
||||
expect(resetPasswordForEmailMock).toHaveBeenCalledWith('[email protected]', {
|
||||
redirectTo: 'https://app.testbrand.example/auth/callback?next=/reset-password',
|
||||
captchaToken: 'tok',
|
||||
})
|
||||
})
|
||||
|
||||
it('falls back to the canonical callback for an unregistered host', async () => {
|
||||
await POST(makeRequest({ email: '[email protected]' }, { host: 'attacker.test' }))
|
||||
|
||||
expect(resetPasswordForEmailMock).toHaveBeenCalledWith('[email protected]', {
|
||||
redirectTo: 'https://app.accounted.test/auth/callback?next=/reset-password',
|
||||
})
|
||||
})
|
||||
|
||||
it('503s (fail safe) when the brand lookup errors, without calling GoTrue', async () => {
|
||||
resolveBrandResultByHostMock.mockResolvedValue({ brand: null, lookupFailed: true })
|
||||
|
||||
const res = await POST(
|
||||
makeRequest({ email: '[email protected]' }, { host: 'app.testbrand.example' }),
|
||||
)
|
||||
const { body: json } = await parseJsonResponse<{ error: { code: string } }>(res)
|
||||
|
||||
expect(res.status).toBe(503)
|
||||
expect(json.error.code).toBe('brand_lookup_failed')
|
||||
expect(resetPasswordForEmailMock).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('maps a GoTrue error to the canonical envelope with its status', async () => {
|
||||
resetPasswordForEmailMock.mockResolvedValue({
|
||||
data: null,
|
||||
error: { code: 'over_email_send_rate_limit', message: 'rate limit', status: 429 },
|
||||
})
|
||||
|
||||
const res = await POST(makeRequest({ email: '[email protected]' }, { host: 'app.accounted.test' }))
|
||||
const { body: json } = await parseJsonResponse<{ error: { code: string; message: string } }>(res)
|
||||
|
||||
expect(res.status).toBe(429)
|
||||
expect(json.error.code).toBe('over_email_send_rate_limit')
|
||||
expect(json.error.message).toBeTruthy()
|
||||
})
|
||||
})
|
||||
@@ -1,93 +0,0 @@
|
||||
import { NextResponse } from 'next/server'
|
||||
import { z } from 'zod'
|
||||
import { createClient } from '@/lib/supabase/server'
|
||||
import { validateBody } from '@/lib/api/validate'
|
||||
import {
|
||||
BrandLookupFailedError,
|
||||
buildPasswordResetRedirectTo,
|
||||
requestHost,
|
||||
} from '@/lib/domains/trusted-app-origin'
|
||||
import { getErrorMessage } from '@/lib/errors/get-error-message'
|
||||
import { createLogger } from '@/lib/logger'
|
||||
|
||||
const log = createLogger('auth-password-reset')
|
||||
|
||||
/**
|
||||
* POST /api/auth/password-reset: request a password recovery mail.
|
||||
*
|
||||
* Moved server-side so the recovery callback is resolved against the brands
|
||||
* table (lib/domains/trusted-app-origin.ts) instead of a domain list compiled
|
||||
* into the browser bundle. The login page used to call
|
||||
* supabase.auth.resetPasswordForEmail directly with a redirectTo it validated
|
||||
* against NEXT_PUBLIC_WHITELABEL_DOMAINS; every new brand then needed that
|
||||
* env var updated and a redeploy, and when that was forgotten the mail went
|
||||
* out canonical-branded to the canonical host. Here the request host decides:
|
||||
* a registered brand host gets its own callback (and, through the Send Email
|
||||
* hook, its own brand), everything else gets the canonical one.
|
||||
*
|
||||
* Anonymous by design: a user asking for a reset has no session, so no
|
||||
* withRouteContext / requireAuth. Abuse is bounded exactly as the direct
|
||||
* GoTrue call was: the forwarded Turnstile token (verified by GoTrue) plus
|
||||
* GoTrue's own recovery rate limits. A signed-in user may also call this
|
||||
* (the login page is reachable while signed in); the cookie-backed client
|
||||
* carries their session and GoTrue behaves the same either way.
|
||||
*
|
||||
* The response never says whether the address exists: GoTrue answers 200 for
|
||||
* unknown addresses and this route passes that through unchanged.
|
||||
*/
|
||||
|
||||
const PasswordResetSchema = z.object({
|
||||
email: z.string().trim().toLowerCase().max(320).pipe(z.string().email()),
|
||||
captchaToken: z.string().max(4096).nullish(),
|
||||
})
|
||||
|
||||
export async function POST(request: Request) {
|
||||
const validation = await validateBody(request, PasswordResetSchema)
|
||||
if (!validation.success) return validation.response
|
||||
const { email, captchaToken } = validation.data
|
||||
|
||||
let redirectTo: string
|
||||
try {
|
||||
redirectTo = await buildPasswordResetRedirectTo(requestHost(request))
|
||||
} catch (err) {
|
||||
if (!(err instanceof BrandLookupFailedError)) throw err
|
||||
// Transient brands-table error: fail safe like /api/auth/signup. A
|
||||
// canonical fallback here would mail a white-label user a wrong-brand
|
||||
// link; 503 tells the client to retry instead.
|
||||
return NextResponse.json(
|
||||
{
|
||||
error: {
|
||||
code: 'brand_lookup_failed',
|
||||
message: 'Tillfälligt fel. Försök igen om en stund.',
|
||||
message_en: 'Temporary error. Please try again shortly.',
|
||||
},
|
||||
},
|
||||
{ status: 503 },
|
||||
)
|
||||
}
|
||||
|
||||
const supabase = await createClient()
|
||||
const { error } = await supabase.auth.resetPasswordForEmail(email, {
|
||||
redirectTo,
|
||||
...(captchaToken ? { captchaToken } : {}),
|
||||
})
|
||||
|
||||
if (error) {
|
||||
log.warn('resetPasswordForEmail rejected', { status: error.status, code: error.code })
|
||||
// Same envelope as /api/auth/signup: the login page feeds it to
|
||||
// classifyAuthError (keyed on code and HTTP status) and localizes the
|
||||
// display message through getErrorMessage.
|
||||
return NextResponse.json(
|
||||
{
|
||||
error: {
|
||||
code: error.code ?? 'auth_error',
|
||||
message: getErrorMessage(error, { context: 'auth', locale: 'sv' }),
|
||||
message_en: getErrorMessage(error, { context: 'auth', locale: 'en' }),
|
||||
},
|
||||
},
|
||||
{ status: error.status && error.status >= 400 ? error.status : 400 },
|
||||
)
|
||||
}
|
||||
|
||||
return NextResponse.json({ data: { status: 'sent' } })
|
||||
}
|
||||
@@ -1,191 +0,0 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import { parseJsonResponse } from '@/tests/helpers'
|
||||
|
||||
const signUpMock = vi.hoisted(() => vi.fn())
|
||||
vi.mock('@/lib/supabase/server', () => ({
|
||||
createClient: vi.fn(async () => ({ auth: { signUp: signUpMock } })),
|
||||
}))
|
||||
|
||||
const gateMock = vi.hoisted(() => vi.fn())
|
||||
vi.mock('@/lib/auth/brand-signup-gate', async (importOriginal) => {
|
||||
const actual =
|
||||
await importOriginal<typeof import('@/lib/auth/brand-signup-gate')>()
|
||||
return {
|
||||
...actual,
|
||||
evaluateBrandSignupGate: (...args: unknown[]) => gateMock(...args),
|
||||
}
|
||||
})
|
||||
|
||||
const resolveBrandResultByHostMock = vi.hoisted(() => vi.fn())
|
||||
vi.mock('@/lib/branding/resolve', () => ({
|
||||
resolveBrandResultByHost: (...args: unknown[]) => resolveBrandResultByHostMock(...args),
|
||||
}))
|
||||
|
||||
import { POST } from '../route'
|
||||
|
||||
function makeRequest(
|
||||
body: unknown,
|
||||
headers: Record<string, string> = {},
|
||||
): Request {
|
||||
return new Request('https://internal/api/auth/signup', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json', ...headers },
|
||||
body: JSON.stringify(body),
|
||||
})
|
||||
}
|
||||
|
||||
const validBody = { email: '[email protected]', password: 'Str0ng!Pass' }
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
process.env.NEXT_PUBLIC_APP_URL = 'https://app.accounted.se'
|
||||
// app.testbrand.example is a registered brand host; app.accounted.se is
|
||||
// the canonical host and never consults the registry.
|
||||
resolveBrandResultByHostMock.mockImplementation(async (host: string) => ({
|
||||
brand: host === 'app.testbrand.example' ? { domain: host } : null,
|
||||
lookupFailed: false,
|
||||
}))
|
||||
gateMock.mockResolvedValue({ allowed: true, brand: null, via: 'no_brand' })
|
||||
signUpMock.mockResolvedValue({
|
||||
data: { user: { identities: [{ id: 'i1' }] }, session: null },
|
||||
error: null,
|
||||
})
|
||||
})
|
||||
|
||||
describe('POST /api/auth/signup', () => {
|
||||
it('400s on invalid body', async () => {
|
||||
const res = await POST(makeRequest({ email: 'not-an-email', password: 'x' }))
|
||||
expect(res.status).toBe(400)
|
||||
expect(signUpMock).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('403s with signup_not_allowed when the gate blocks', async () => {
|
||||
gateMock.mockResolvedValue({ allowed: false, brand: { id: 'brand-1' } })
|
||||
|
||||
const res = await POST(
|
||||
makeRequest(validBody, { host: 'app.testbrand.example' }),
|
||||
)
|
||||
const { body: json } = await parseJsonResponse<{ error: { code: string } }>(res)
|
||||
|
||||
expect(res.status).toBe(403)
|
||||
expect(json.error.code).toBe('signup_not_allowed')
|
||||
expect(signUpMock).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('503s (fail safe) when the brand lookup errors, without creating an account', async () => {
|
||||
gateMock.mockResolvedValue({ allowed: false, brand: null, lookupFailed: true })
|
||||
|
||||
const res = await POST(
|
||||
makeRequest(validBody, { host: 'app.testbrand.example' }),
|
||||
)
|
||||
const { body: json } = await parseJsonResponse<{ error: { code: string } }>(res)
|
||||
|
||||
expect(res.status).toBe(503)
|
||||
expect(json.error.code).toBe('brand_lookup_failed')
|
||||
expect(signUpMock).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('feeds the gate the forwarded host, normalized email and invite cookie', async () => {
|
||||
await POST(
|
||||
makeRequest(
|
||||
{ ...validBody, email: ' [email protected] ' },
|
||||
{
|
||||
host: 'internal',
|
||||
'x-forwarded-host': 'app.testbrand.example',
|
||||
cookie: 'gnubok-invite-token=gnubok_inv_x',
|
||||
},
|
||||
),
|
||||
)
|
||||
|
||||
expect(gateMock).toHaveBeenCalledWith({
|
||||
host: 'app.testbrand.example',
|
||||
email: '[email protected]',
|
||||
inviteToken: 'gnubok_inv_x',
|
||||
})
|
||||
})
|
||||
|
||||
it('signs up with a confirmation callback on the originating host', async () => {
|
||||
const res = await POST(
|
||||
makeRequest(validBody, {
|
||||
'x-forwarded-host': 'app.testbrand.example',
|
||||
'x-forwarded-proto': 'https',
|
||||
}),
|
||||
)
|
||||
const { body: json } = await parseJsonResponse<{ data: { status: string } }>(res)
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
expect(json.data.status).toBe('confirmation_sent')
|
||||
expect(signUpMock).toHaveBeenCalledWith({
|
||||
email: '[email protected]',
|
||||
password: 'Str0ng!Pass',
|
||||
options: {
|
||||
emailRedirectTo: 'https://app.testbrand.example/auth/callback',
|
||||
},
|
||||
})
|
||||
})
|
||||
|
||||
it('forwards the captcha token and a safe next path', async () => {
|
||||
await POST(
|
||||
makeRequest(
|
||||
{ ...validBody, captchaToken: 'tok', next: '/api/mcp-oauth/authorize?x=1' },
|
||||
{ host: 'app.accounted.se' },
|
||||
),
|
||||
)
|
||||
|
||||
const call = signUpMock.mock.calls[0][0]
|
||||
expect(call.options.captchaToken).toBe('tok')
|
||||
expect(call.options.emailRedirectTo).toBe(
|
||||
'https://app.accounted.se/auth/callback?next=%2Fapi%2Fmcp-oauth%2Fauthorize%3Fx%3D1',
|
||||
)
|
||||
})
|
||||
|
||||
it('drops an unsafe next path instead of forwarding it', async () => {
|
||||
await POST(
|
||||
makeRequest(
|
||||
{ ...validBody, next: 'https://evil.example.com/phish' },
|
||||
{ host: 'app.accounted.se' },
|
||||
),
|
||||
)
|
||||
const call = signUpMock.mock.calls[0][0]
|
||||
expect(call.options.emailRedirectTo).toBe(
|
||||
'https://app.accounted.se/auth/callback',
|
||||
)
|
||||
})
|
||||
|
||||
it('maps a GoTrue error to the canonical envelope', async () => {
|
||||
signUpMock.mockResolvedValue({
|
||||
data: { user: null, session: null },
|
||||
error: { code: 'weak_password', message: 'Password is too weak', status: 422 },
|
||||
})
|
||||
|
||||
const res = await POST(makeRequest(validBody, { host: 'app.accounted.se' }))
|
||||
const { body: json } = await parseJsonResponse<{ error: { code: string; message: string } }>(res)
|
||||
|
||||
expect(res.status).toBe(422)
|
||||
expect(json.error.code).toBe('weak_password')
|
||||
})
|
||||
|
||||
it('reports duplicate for the obfuscated existing-account response', async () => {
|
||||
signUpMock.mockResolvedValue({
|
||||
data: { user: { identities: [] }, session: null },
|
||||
error: null,
|
||||
})
|
||||
|
||||
const res = await POST(makeRequest(validBody, { host: 'app.accounted.se' }))
|
||||
const { body: json } = await parseJsonResponse<{ data: { status: string } }>(res)
|
||||
|
||||
expect(json.data.status).toBe('duplicate')
|
||||
})
|
||||
|
||||
it('reports session for auto-confirmed signups', async () => {
|
||||
signUpMock.mockResolvedValue({
|
||||
data: { user: { identities: [{ id: 'i1' }] }, session: { access_token: 'x' } },
|
||||
error: null,
|
||||
})
|
||||
|
||||
const res = await POST(makeRequest(validBody, { host: 'app.accounted.se' }))
|
||||
const { body: json } = await parseJsonResponse<{ data: { status: string } }>(res)
|
||||
|
||||
expect(json.data.status).toBe('session')
|
||||
})
|
||||
})
|
||||
@@ -1,135 +0,0 @@
|
||||
import { NextResponse } from 'next/server'
|
||||
import { z } from 'zod'
|
||||
import { createClient } from '@/lib/supabase/server'
|
||||
import { validateBody } from '@/lib/api/validate'
|
||||
import {
|
||||
evaluateBrandSignupGate,
|
||||
readInviteTokenFromCookieHeader,
|
||||
} from '@/lib/auth/brand-signup-gate'
|
||||
import { safeReturnTo } from '@/lib/auth/safe-return-to'
|
||||
import { resolveTrustedAppOrigin } from '@/lib/domains/trusted-app-origin'
|
||||
import { getErrorMessage } from '@/lib/errors/get-error-message'
|
||||
import { createLogger } from '@/lib/logger'
|
||||
|
||||
const log = createLogger('auth-signup')
|
||||
|
||||
/**
|
||||
* POST /api/auth/signup: email+password signup, moved server-side so the
|
||||
* invite-only brand-domain gate (lib/auth/brand-signup-gate.ts) cannot be
|
||||
* bypassed. The register page used to call supabase.auth.signUp straight
|
||||
* from the browser; that call never touched Next.js, so any host-based
|
||||
* gating there would have been cosmetic. This route is now the only
|
||||
* email-signup path on every host: on canonical and open-brand hosts the
|
||||
* behavior is byte-identical to the old direct call (same GoTrue request,
|
||||
* same captcha, same emailRedirectTo shape), on invite-only brand hosts it
|
||||
* refuses with signup_not_allowed unless the email is allowlisted or a
|
||||
* valid invite cookie rides along.
|
||||
*
|
||||
* Anonymous by design: there is no session to authenticate at signup time,
|
||||
* so no withRouteContext / requireAuth. Abuse is bounded the same way the
|
||||
* direct GoTrue call was: the forwarded Turnstile token (verified by
|
||||
* GoTrue) plus GoTrue's own signup rate limits.
|
||||
*/
|
||||
|
||||
const SignupSchema = z.object({
|
||||
email: z.string().trim().toLowerCase().max(320).pipe(z.string().email()),
|
||||
password: z.string().min(8).max(256),
|
||||
captchaToken: z.string().max(4096).nullish(),
|
||||
/** Post-signup resume path (MCP OAuth consent); same-origin enforced. */
|
||||
next: z.string().max(2048).nullish(),
|
||||
})
|
||||
|
||||
export async function POST(request: Request) {
|
||||
const validation = await validateBody(request, SignupSchema)
|
||||
if (!validation.success) return validation.response
|
||||
const { email, password, captchaToken } = validation.data
|
||||
|
||||
const host =
|
||||
request.headers.get('x-forwarded-host') ?? request.headers.get('host') ?? ''
|
||||
|
||||
// The invite cookie is set by /invite/[token] before it redirects to
|
||||
// /register, so an invitee's signup carries it automatically.
|
||||
const inviteToken = readInviteTokenFromCookieHeader(request.headers.get('cookie'))
|
||||
|
||||
const gate = await evaluateBrandSignupGate({ host, email, inviteToken })
|
||||
if (!gate.allowed && 'lookupFailed' in gate) {
|
||||
// Transient brands-table error: fail safe, do not create the account.
|
||||
// 503 tells the client to retry rather than the misleading "not allowed".
|
||||
return NextResponse.json(
|
||||
{
|
||||
error: {
|
||||
code: 'brand_lookup_failed',
|
||||
message: 'Tillfälligt fel. Försök igen om en stund.',
|
||||
message_en: 'Temporary error. Please try again shortly.',
|
||||
},
|
||||
},
|
||||
{ status: 503 },
|
||||
)
|
||||
}
|
||||
if (!gate.allowed) {
|
||||
return NextResponse.json(
|
||||
{
|
||||
error: {
|
||||
code: 'signup_not_allowed',
|
||||
// Brand-neutral copy: the interstitial on the register page owns
|
||||
// the user-facing story; this message is the API-level fallback.
|
||||
message: 'Registrering på den här domänen kräver inbjudan.',
|
||||
message_en: 'Signing up on this domain requires an invitation.',
|
||||
},
|
||||
},
|
||||
{ status: 403 },
|
||||
)
|
||||
}
|
||||
|
||||
// Confirmation links must land back on the ORIGINATING host (WL-05 brand
|
||||
// mail resolves its brand from this URL). The host is resolved through the
|
||||
// same registry as every other auth link (canonical, this deployment's
|
||||
// own Vercel hosts, or a registered brand domain); anything else falls
|
||||
// back to the canonical origin rather than following the raw header.
|
||||
const confirmationCallback = new URL(
|
||||
'/auth/callback',
|
||||
await resolveTrustedAppOrigin(host),
|
||||
)
|
||||
const nextPath = safeReturnTo(validation.data.next ?? null, '/')
|
||||
if (nextPath !== '/') confirmationCallback.searchParams.set('next', nextPath)
|
||||
|
||||
const supabase = await createClient()
|
||||
const { data, error } = await supabase.auth.signUp({
|
||||
email,
|
||||
password,
|
||||
options: {
|
||||
emailRedirectTo: confirmationCallback.toString(),
|
||||
...(captchaToken ? { captchaToken } : {}),
|
||||
},
|
||||
})
|
||||
|
||||
if (error) {
|
||||
log.warn('signUp rejected', { status: error.status, code: error.code })
|
||||
// The register page feeds this envelope to classifyAuthError, which
|
||||
// keys on the GoTrue code (and the HTTP status); the display message is
|
||||
// localized through getErrorMessage like every other auth surface.
|
||||
return NextResponse.json(
|
||||
{
|
||||
error: {
|
||||
code: error.code ?? 'auth_error',
|
||||
message: getErrorMessage(error, { context: 'auth', locale: 'sv' }),
|
||||
message_en: getErrorMessage(error, { context: 'auth', locale: 'en' }),
|
||||
},
|
||||
},
|
||||
{ status: error.status && error.status >= 400 ? error.status : 400 },
|
||||
)
|
||||
}
|
||||
|
||||
// Supabase obfuscates duplicate signups (anti-enumeration): a confirmed
|
||||
// existing email returns a user with identities: [] and sends no mail.
|
||||
// Surface that as a distinct status so the page can skip the misleading
|
||||
// "check your email" screen; the information is the same the browser call
|
||||
// exposed, so nothing new leaks.
|
||||
const status = data.session
|
||||
? 'session'
|
||||
: data.user && (data.user.identities?.length ?? 0) === 0
|
||||
? 'duplicate'
|
||||
: 'confirmation_sent'
|
||||
|
||||
return NextResponse.json({ data: { status } })
|
||||
}
|
||||
Reference in New Issue
Block a user