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:
2026-11-10 09:15:21 +01:00
parent 0fda8cae48
commit 2bee8eb778
6135 changed files with 4 additions and 1718997 deletions
@@ -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()
})
})
-93
View File
@@ -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' } })
}