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,114 +0,0 @@
import { describe, it, expect } from 'vitest'
import { contentDisposition, contentDispositionFilename } from '../content-disposition'
describe('contentDisposition', () => {
it('passes a plain ASCII filename through unchanged in both forms', () => {
expect(contentDisposition('inline', 'kvitto.pdf')).toBe(
`inline; filename="kvitto.pdf"; filename*=UTF-8''kvitto.pdf`,
)
})
it('supports the attachment type', () => {
expect(contentDisposition('attachment', 'report.pdf')).toBe(
`attachment; filename="report.pdf"; filename*=UTF-8''report.pdf`,
)
})
it('produces a ByteString-safe value for an NFD Swedish filename', () => {
// macOS/iOS NFD upload: base letter + combining diaeresis U+0308 (776),
// the exact shape that crashed the inline route in prod.
const nfd = 'kvitto fo\u0308rvaring.pdf'
expect(nfd.charCodeAt(9)).toBe(776)
const header = contentDisposition('inline', nfd)
const maxCode = Math.max(...[...header].map((c) => c.charCodeAt(0)))
expect(maxCode).toBeLessThanOrEqual(255)
// The whole header is in fact printable ASCII.
expect(/^[\x20-\x7e]*$/.test(header)).toBe(true)
// filename* carries the NFC-composed UTF-8 percent-encoding of the name.
expect(header).toContain(`filename*=UTF-8''kvitto%20f%C3%B6rvaring.pdf`)
// The quoted fallback replaces the non-ASCII character with _.
expect(header).toContain('filename="kvitto f_rvaring.pdf"')
})
it('is stable across NFD and NFC inputs of the same name', () => {
const nfd = 'lo\u0308n.pdf' // o + combining diaeresis
const nfc = 'l\u00f6n.pdf' // precomposed \u00f6
expect(contentDisposition('inline', nfd)).toBe(contentDisposition('inline', nfc))
})
it('does not throw when used as an undici Headers value', () => {
const nfd = 'lo\u0308nespec_a\u030agren.pdf'
expect(
() => new Headers({ 'Content-Disposition': contentDisposition('inline', nfd) }),
).not.toThrow()
})
it('neutralizes header delimiters and CRLF injection', () => {
const header = contentDisposition('attachment', 'evil";\\\r\nSet-Cookie: x=y.pdf')
expect(header).not.toContain('\r')
expect(header).not.toContain('\n')
expect(header).toContain('filename="evil_____Set-Cookie: x=y.pdf"')
// The extended form percent-encodes them instead of emitting them raw.
expect(header).toContain('%22%3B%5C')
expect(header).toContain('%0D%0A')
})
it('replaces backslash in the quoted fallback', () => {
expect(contentDisposition('inline', 'a\\b.pdf')).toContain('filename="a_b.pdf"')
})
it(`percent-escapes ! ' ( ) * which encodeURIComponent leaves bare`, () => {
const header = contentDisposition('inline', "a!'()*.pdf")
expect(header).toContain(`filename*=UTF-8''a%21%27%28%29%2A.pdf`)
})
it('sanitizes a lone high surrogate instead of throwing', () => {
let header = ''
expect(() => {
header = contentDisposition('attachment', '\uD800')
}).not.toThrow()
// The lone surrogate becomes U+FFFD: _ in the fallback, percent-encoded
// UTF-8 (%EF%BF%BD) in the extended form.
expect(header).toBe(`attachment; filename="_"; filename*=UTF-8''%EF%BF%BD`)
expect(() => new Headers({ 'Content-Disposition': header })).not.toThrow()
})
it('sanitizes an embedded unpaired surrogate and keeps the rest of the name', () => {
let header = ''
expect(() => {
header = contentDisposition('inline', 'a\uD800b')
}).not.toThrow()
expect(header).toBe(`inline; filename="a_b"; filename*=UTF-8''a%EF%BF%BDb`)
expect(() => new Headers({ 'Content-Disposition': header })).not.toThrow()
})
it('keeps a valid surrogate pair (emoji) working unchanged', () => {
const header = contentDisposition('inline', 'r😀.pdf')
expect(header).toBe(`inline; filename="r__.pdf"; filename*=UTF-8''r%F0%9F%98%80.pdf`)
expect(() => new Headers({ 'Content-Disposition': header })).not.toThrow()
})
})
describe('contentDispositionFilename', () => {
it('prefers and decodes the UTF-8 filename', () => {
const header = contentDisposition(
'attachment',
'Företag x Kund AB Faktura nr 2621 20260721.pdf',
)
expect(contentDispositionFilename(header))
.toBe('Företag x Kund AB Faktura nr 2621 20260721.pdf')
})
it('falls back to the quoted ASCII filename', () => {
expect(contentDispositionFilename('attachment; filename="faktura-2621.pdf"'))
.toBe('faktura-2621.pdf')
})
it('returns null for a missing or malformed filename', () => {
expect(contentDispositionFilename(null)).toBeNull()
expect(contentDispositionFilename('attachment')).toBeNull()
})
})
-146
View File
@@ -1,146 +0,0 @@
import { describe, it, expect, vi, beforeEach } from 'vitest'
import {
hashRequest,
checkIdempotencyKey,
storeIdempotencyResponse,
cleanupExpiredIdempotencyKeys,
IdempotencyKeyReuseError,
} from '../idempotency'
describe('hashRequest', () => {
it('produces stable SHA-256 for the same payload', () => {
expect(hashRequest({ a: 1, b: 'x' })).toBe(hashRequest({ a: 1, b: 'x' }))
})
it('is order-independent', () => {
expect(hashRequest({ a: 1, b: 2 })).toBe(hashRequest({ b: 2, a: 1 }))
})
it('detects different values', () => {
expect(hashRequest({ a: 1 })).not.toBe(hashRequest({ a: 2 }))
})
it('handles nested objects deterministically', () => {
const h1 = hashRequest({ outer: { x: 1, y: 2 }, list: [1, 2, 3] })
const h2 = hashRequest({ list: [1, 2, 3], outer: { y: 2, x: 1 } })
expect(h1).toBe(h2)
})
})
function mockClient(maybeSingleResult: { data: Record<string, unknown> | null; error: unknown }) {
const select = vi.fn().mockReturnValue({
eq: vi.fn().mockReturnValue({
eq: vi.fn().mockReturnValue({
eq: vi.fn().mockReturnValue({
maybeSingle: vi.fn().mockResolvedValue(maybeSingleResult),
}),
}),
}),
})
const insert = vi.fn().mockResolvedValue({ error: null })
const deleteFn = vi.fn().mockReturnValue({
lt: vi.fn().mockResolvedValue({ error: null, count: 5 }),
})
return {
client: {
from: vi.fn().mockReturnValue({
select,
insert,
delete: deleteFn,
}),
} as never,
select,
insert,
deleteFn,
}
}
describe('checkIdempotencyKey', () => {
beforeEach(() => vi.clearAllMocks())
it('returns null when no cached row exists', async () => {
const { client } = mockClient({ data: null, error: null })
const result = await checkIdempotencyKey(client, 'user-1', 'company-1', 'key-1', 'hash-1')
expect(result).toBeNull()
})
it('returns cached body when key + hash match', async () => {
const future = new Date(Date.now() + 60_000).toISOString()
const { client } = mockClient({
data: {
request_hash: 'hash-1',
response_status: 'success',
response_body: { foo: 'bar' },
expires_at: future,
},
error: null,
})
const result = await checkIdempotencyKey(client, 'user-1', 'company-1', 'key-1', 'hash-1')
expect(result).toEqual({ status: 'success', body: { foo: 'bar' } })
})
it('throws IdempotencyKeyReuseError on hash mismatch', async () => {
const future = new Date(Date.now() + 60_000).toISOString()
const { client } = mockClient({
data: {
request_hash: 'hash-old',
response_status: 'success',
response_body: { foo: 'old' },
expires_at: future,
},
error: null,
})
await expect(
checkIdempotencyKey(client, 'user-1', 'company-1', 'key-1', 'hash-new')
).rejects.toBeInstanceOf(IdempotencyKeyReuseError)
})
it('treats expired rows as misses', async () => {
const past = new Date(Date.now() - 60_000).toISOString()
const { client } = mockClient({
data: {
request_hash: 'hash-1',
response_status: 'success',
response_body: { foo: 'bar' },
expires_at: past,
},
error: null,
})
const result = await checkIdempotencyKey(client, 'user-1', 'company-1', 'key-1', 'hash-1')
expect(result).toBeNull()
})
})
describe('storeIdempotencyResponse', () => {
beforeEach(() => vi.clearAllMocks())
it('writes the response row', async () => {
const { client, insert } = mockClient({ data: null, error: null })
await storeIdempotencyResponse(client, 'user-1', 'company-1', 'key-1', 'hash-1', 'success', { ok: true })
expect(insert).toHaveBeenCalledWith(expect.objectContaining({
user_id: 'user-1',
company_id: 'company-1',
key: 'key-1',
request_hash: 'hash-1',
response_status: 'success',
response_body: { ok: true },
scope: 'mcp_tool',
}))
})
it('swallows duplicate-row races (23505)', async () => {
const { client, insert } = mockClient({ data: null, error: null })
insert.mockResolvedValueOnce({ error: { code: '23505', message: 'unique_violation' } })
await expect(
storeIdempotencyResponse(client, 'user-1', 'company-1', 'key-1', 'hash-1', 'success', {})
).resolves.toBeUndefined()
})
})
describe('cleanupExpiredIdempotencyKeys', () => {
it('returns delete count', async () => {
const { client } = mockClient({ data: null, error: null })
const count = await cleanupExpiredIdempotencyKeys(client)
expect(count).toBe(5)
})
})
File diff suppressed because it is too large Load Diff
-274
View File
@@ -1,274 +0,0 @@
import { describe, it, expect } from 'vitest'
import { z } from 'zod'
import { sparsePatch, sparsePatchBody, isPatchDocument } from '@/lib/api/sparse-patch'
import { validateBody } from '@/lib/api/validate'
import { createMockRequest } from '@/tests/helpers'
// Mirrors the real hazard shape: a create schema carrying .default() flags,
// turned into a patch schema with .partial().
const CreateLine = z.object({
description: z.string().min(1),
amount: z.number(),
quantity: z.number().optional(),
is_taxable: z.boolean().default(true),
is_net_deduction: z.boolean().default(false),
sort_order: z.number().int().default(0),
account_number: z.string().nullable().optional(),
tags: z.array(z.string()).default([]),
meta: z.object({ source: z.string().default('manual') }).default({ source: 'manual' }),
})
const UpdateLine = CreateLine.partial()
describe('the bug this helper exists for', () => {
it('.partial() does NOT strip .default(): a one-field parse resurrects every default', () => {
// This is the finding, pinned as an executable fact. If a future zod
// upgrade changes it, this test tells you the helper can be retired.
expect(UpdateLine.parse({ amount: 5500 })).toEqual({
amount: 5500,
is_taxable: true,
is_net_deduction: false,
sort_order: 0,
tags: [],
meta: { source: 'manual' },
})
})
})
describe('sparsePatch', () => {
it('a one-field patch does not resurrect defaults', () => {
const result = sparsePatch(UpdateLine, { amount: 5500 })
expect(result.success).toBe(true)
if (!result.success) return
expect(result.data).toEqual({ amount: 5500 })
expect(Object.keys(result.data)).toEqual(['amount'])
})
it('keeps a default-carrying field when the caller DID send it', () => {
const result = sparsePatch(UpdateLine, { is_taxable: false })
expect(result.success).toBe(true)
if (!result.success) return
expect(result.data).toEqual({ is_taxable: false })
})
it('an explicit null survives as a deliberate clear', () => {
const result = sparsePatch(UpdateLine, { account_number: null })
expect(result.success).toBe(true)
if (!result.success) return
expect(result.data).toEqual({ account_number: null })
expect('account_number' in result.data).toBe(true)
})
it('an absent key is untouched (never appears in the output)', () => {
const result = sparsePatch(UpdateLine, { description: 'Bonus' })
expect(result.success).toBe(true)
if (!result.success) return
expect('account_number' in result.data).toBe(false)
expect('is_taxable' in result.data).toBe(false)
expect('sort_order' in result.data).toBe(false)
})
it('null and absent are distinguishable, which is the whole point', () => {
const cleared = sparsePatch(UpdateLine, { account_number: null })
const untouched = sparsePatch(UpdateLine, {})
expect(cleared.success && cleared.data).toEqual({ account_number: null })
expect(untouched.success && untouched.data).toEqual({})
})
it('drops an in-process undefined (not expressible in JSON, never intended)', () => {
const result = sparsePatch(UpdateLine, { amount: 1, quantity: undefined })
expect(result.success).toBe(true)
if (!result.success) return
expect(result.data).toEqual({ amount: 1 })
expect('quantity' in result.data).toBe(false)
})
it('drops unknown keys rather than passing them to the caller', () => {
const result = sparsePatch(UpdateLine, { amount: 1, is_system: true, company_id: 'other' })
expect(result.success).toBe(true)
if (!result.success) return
expect(result.data).toEqual({ amount: 1 })
})
it('drops prototype-polluting own properties from a JSON body', () => {
const rawBody = JSON.parse('{"amount": 1, "__proto__": {"polluted": true}}')
const result = sparsePatch(UpdateLine, rawBody)
expect(result.success).toBe(true)
if (!result.success) return
expect(result.data).toEqual({ amount: 1 })
expect(({} as Record<string, unknown>).polluted).toBeUndefined()
})
describe('nested objects', () => {
it('an absent nested key stays absent (its inner defaults do not materialise)', () => {
const result = sparsePatch(UpdateLine, { amount: 1 })
expect(result.success && 'meta' in result.data).toBe(false)
})
it('a supplied nested key is replaced wholesale, inner defaults included', () => {
// Shallow by design: the sink is `SET col = $1`, which replaces the whole
// jsonb value, so a half-merged object would write something the caller
// never described.
const result = sparsePatch(UpdateLine, { meta: {} })
expect(result.success).toBe(true)
if (!result.success) return
expect(result.data).toEqual({ meta: { source: 'manual' } })
})
it('reports validation errors with their full nested path', () => {
const result = sparsePatch(UpdateLine, { meta: { source: 42 } })
expect(result.success).toBe(false)
if (result.success) return
expect(result.error.issues[0].path).toEqual(['meta', 'source'])
})
})
describe('arrays', () => {
it('an array VALUE is taken wholesale', () => {
const result = sparsePatch(UpdateLine, { tags: ['a', 'b'] })
expect(result.success && result.data).toEqual({ tags: ['a', 'b'] })
})
it('an explicitly empty array is a real value, not an absence', () => {
const result = sparsePatch(UpdateLine, { tags: [] })
expect(result.success).toBe(true)
if (!result.success) return
expect(result.data).toEqual({ tags: [] })
expect('tags' in result.data).toBe(true)
})
it('an array BODY is rejected: a patch document must be a JSON object', () => {
const result = sparsePatch(UpdateLine, [{ amount: 1 }])
expect(result.success).toBe(false)
if (result.success) return
expect(result.error.issues[0].message).toContain('JSON object')
})
})
it.each([
['null', null],
['a scalar', 42],
['a string', 'amount=1'],
])('rejects %s as a body', (_label, body) => {
expect(sparsePatch(UpdateLine, body).success).toBe(false)
})
it('propagates schema validation failures unchanged', () => {
const result = sparsePatch(UpdateLine, { amount: 'not a number' })
expect(result.success).toBe(false)
if (result.success) return
expect(result.error.issues[0].path).toEqual(['amount'])
})
it('throws when the schema output is not an object (there is nothing to narrow)', () => {
const Reshaped = z.object({ a: z.number().optional() }).transform(() => null)
expect(() => sparsePatch(Reshaped, { a: 1 })).toThrow(/output is an object/)
})
it('works on a .superRefine()-wrapped schema (where .shape is unreachable)', () => {
const Refined = CreateLine.partial().superRefine((data, ctx) => {
if (data.amount === 13) {
ctx.addIssue({ code: 'custom', message: 'Olyckstal', path: ['amount'] })
}
})
expect(sparsePatch(Refined, { amount: 1 }).success && sparsePatch(Refined, { amount: 1 })).toMatchObject({
data: { amount: 1 },
})
const bad = sparsePatch(Refined, { amount: 13 })
expect(bad.success).toBe(false)
if (bad.success) return
expect(bad.error.issues[0].path).toEqual(['amount'])
})
})
describe('isPatchDocument', () => {
it.each([
[{}, true],
[{ a: 1 }, true],
[[], false],
[null, false],
[1, false],
['x', false],
[undefined, false],
])('%s -> %s', (input, expected) => {
expect(isPatchDocument(input)).toBe(expected)
})
})
describe('sparsePatchBody + validateBody', () => {
async function patch(body: unknown) {
const request = createMockRequest('/api/thing/1', { method: 'PATCH', body })
return validateBody(request, sparsePatchBody(UpdateLine))
}
it('yields only the sent keys through the validateBody pipeline', async () => {
const result = await patch({ amount: 5500 })
expect(result.success).toBe(true)
if (!result.success) return
expect(result.data).toEqual({ amount: 5500 })
})
it('keeps an explicit null through the validateBody pipeline', async () => {
const result = await patch({ account_number: null })
expect(result.success && result.data).toEqual({ account_number: null })
})
it('returns a 400 with the original field path on a schema failure', async () => {
const result = await patch({ amount: 'x' })
expect(result.success).toBe(false)
if (result.success) return
expect(result.response.status).toBe(400)
const body = await result.response.json()
expect(body.errors[0].field).toBe('amount')
})
// Forwarding through ctx.addIssue must not flatten the issue to `custom`:
// validateBody puts `code` in the 400 envelope and clients branch on it.
it('keeps the original issue CODE, not a flattened `custom`', async () => {
const result = await patch({ amount: 'x' })
expect(result.success).toBe(false)
if (result.success) return
const body = await result.response.json()
expect(body.errors[0].code).toBe('invalid_type')
expect(body.errors[0].code).not.toBe('custom')
})
it('forwards every issue, each with its own nested path and code', async () => {
const result = await patch({ meta: { source: 1 }, description: '' })
expect(result.success).toBe(false)
if (result.success) return
const body = await result.response.json()
expect(body.errors).toEqual(
expect.arrayContaining([
expect.objectContaining({ field: 'meta.source', code: 'invalid_type' }),
expect.objectContaining({ field: 'description', code: 'too_small' }),
]),
)
})
it('produces the same issues a plain validateBody(schema) would', async () => {
const bare = await validateBody(
createMockRequest('/api/thing/1', { method: 'PATCH', body: { amount: 'x' } }),
UpdateLine,
)
const sparse = await patch({ amount: 'x' })
expect(bare.success).toBe(false)
expect(sparse.success).toBe(false)
if (bare.success || sparse.success) return
expect(await sparse.response.json()).toEqual(await bare.response.json())
})
it('returns a 400 when the body is not a JSON object', async () => {
const result = await patch([1, 2])
expect(result.success).toBe(false)
if (result.success) return
expect(result.response.status).toBe(400)
})
it('an empty body parses to an empty patch, not to a pile of defaults', async () => {
const result = await patch({})
expect(result.success).toBe(true)
if (!result.success) return
expect(result.data).toEqual({})
})
})
@@ -1,41 +0,0 @@
import { describe, it, expect, vi, afterEach } from 'vitest'
import { createTokenRateLimiter } from '../token-rate-limit'
describe('createTokenRateLimiter', () => {
afterEach(() => {
vi.useRealTimers()
})
it('allows up to max requests per window, then refuses', () => {
const limiter = createTokenRateLimiter({ max: 3, windowMs: 60_000 })
expect(limiter.allow('a')).toBe(true)
expect(limiter.allow('a')).toBe(true)
expect(limiter.allow('a')).toBe(true)
expect(limiter.allow('a')).toBe(false)
})
it('keys the budget per token', () => {
const limiter = createTokenRateLimiter({ max: 1, windowMs: 60_000 })
expect(limiter.allow('a')).toBe(true)
expect(limiter.allow('b')).toBe(true)
expect(limiter.allow('a')).toBe(false)
})
it('resets the budget once the window has passed', () => {
vi.useFakeTimers()
vi.setSystemTime(new Date('2026-01-01T00:00:00Z'))
const limiter = createTokenRateLimiter({ max: 1, windowMs: 60_000 })
expect(limiter.allow('a')).toBe(true)
expect(limiter.allow('a')).toBe(false)
vi.setSystemTime(new Date('2026-01-01T00:01:00.001Z'))
expect(limiter.allow('a')).toBe(true)
})
it('keeps separate limiters isolated', () => {
const one = createTokenRateLimiter({ max: 1, windowMs: 60_000 })
const two = createTokenRateLimiter({ max: 1, windowMs: 60_000 })
expect(one.allow('a')).toBe(true)
expect(two.allow('a')).toBe(true)
expect(one.allow('a')).toBe(false)
})
})
-326
View File
@@ -1,326 +0,0 @@
import { describe, it, expect } from 'vitest'
import { z } from 'zod'
import { validateBody, validateQuery } from '../validate'
import { getErrorMessage } from '@/lib/errors/get-error-message'
// ============================================================
// Helpers
// ============================================================
function createJsonRequest(body: unknown): Request {
return new Request('http://localhost/api/test', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(body),
})
}
function createMalformedRequest(): Request {
return new Request('http://localhost/api/test', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: 'not valid json {{{',
})
}
function createRequestWithQuery(params: Record<string, string>): Request {
const url = new URL('http://localhost/api/test')
for (const [key, value] of Object.entries(params)) {
url.searchParams.set(key, value)
}
return new Request(url.toString())
}
const TestSchema = z.object({
name: z.string().min(1),
age: z.number().int().positive(),
email: z.string().email().optional(),
})
const QuerySchema = z.object({
page: z.coerce.number().int().positive().default(1),
limit: z.coerce.number().int().min(1).max(100).default(50),
})
// ============================================================
// validateBody
// ============================================================
describe('validateBody', () => {
it('returns success with parsed data on valid input', async () => {
const request = createJsonRequest({ name: 'Alice', age: 30 })
const result = await validateBody(request, TestSchema)
expect(result.success).toBe(true)
if (result.success) {
expect(result.data).toEqual({ name: 'Alice', age: 30 })
}
})
it('returns success with optional fields', async () => {
const request = createJsonRequest({ name: 'Bob', age: 25, email: '[email protected]' })
const result = await validateBody(request, TestSchema)
expect(result.success).toBe(true)
if (result.success) {
expect(result.data.email).toBe('[email protected]')
}
})
it('returns failure response on invalid body', async () => {
const request = createJsonRequest({ name: '', age: -5 })
const result = await validateBody(request, TestSchema)
expect(result.success).toBe(false)
if (!result.success) {
const body = await result.response.json()
expect(result.response.status).toBe(400)
// Inverted on purpose: the old assertion pinned the constant
// 'Validation failed', which is exactly the bug. `error` now carries the
// actionable field message so clients that read only `error` show
// something useful; `errors[]` keeps the full machine-readable detail and
// `type` stays the discriminator.
expect(body.error).not.toBe('Validation failed')
expect(body.error).toMatch(/^Valideringsfel: /)
expect(body.error).toContain('name')
expect(body.error).toContain('age')
expect(body.type).toBe('validation_error')
expect(body.errors).toBeInstanceOf(Array)
expect(body.errors.length).toBeGreaterThan(0)
}
})
it('summarizes at most three issues and counts the rest', async () => {
const WideSchema = z.object({
a: z.string(),
b: z.string(),
c: z.string(),
d: z.string(),
e: z.string(),
})
const request = createJsonRequest({})
const result = await validateBody(request, WideSchema)
expect(result.success).toBe(false)
if (!result.success) {
const body = await result.response.json()
expect(body.errors).toHaveLength(5)
expect(body.error).toContain('(+2 till)')
// Only the first three are named in the prose.
expect(body.error).not.toContain('d:')
expect(body.error).not.toContain('e:')
}
})
it('surfaces the actionable Swedish sentence to a client that reads only body.error', async () => {
// Reproduces the failing UI path: pages like arsredovisning/page.tsx and
// assets/[id]/dispose/page.tsx forward `body.error` (a string) into
// getErrorMessage, which collapsed the constant into "Något gick fel."
const SwedishSchema = z.object({
period_start: z.string({ message: 'Ange periodens startdatum' }),
})
const request = await validateBody(createJsonRequest({}), SwedishSchema)
expect(request.success).toBe(false)
if (!request.success) {
const body = await request.response.json()
const shown = getErrorMessage(body.error, { statusCode: 400 })
expect(shown).toBe(body.error)
expect(shown).toContain('Ange periodens startdatum')
expect(shown).not.toBe('Något gick fel. Försök igen.')
// Clients that forward the whole body keep the existing errors[] path.
expect(getErrorMessage(body, { statusCode: 400 })).toContain(
'Ange periodens startdatum',
)
}
})
it('keeps the machine-readable discriminator and per-field detail intact', async () => {
const request = createJsonRequest({ name: '', age: -5 })
const result = await validateBody(request, TestSchema)
expect(result.success).toBe(false)
if (!result.success) {
const body = await result.response.json()
// A machine consumer branches on `type` / `errors[].code`, never on prose.
// Both are pinned to concrete values here: asserting only `typeof` would
// keep passing if the codes turned into empty strings.
expect(body.type).toBe('validation_error')
for (const issue of body.errors as Array<Record<string, unknown>>) {
expect(typeof issue.field).toBe('string')
expect(typeof issue.message).toBe('string')
expect(typeof issue.code).toBe('string')
}
// Field-keyed lookup, the way a client maps issues onto form inputs.
const byField = new Map(
(body.errors as Array<{ field: string; code: string }>).map((e) => [e.field, e.code]),
)
expect(byField.get('name')).toBe('too_small')
expect(byField.get('age')).toBe('too_small')
}
})
it('returns field paths in error details', async () => {
const request = createJsonRequest({ name: 'Alice', age: 'not-a-number' })
const result = await validateBody(request, TestSchema)
expect(result.success).toBe(false)
if (!result.success) {
const body = await result.response.json()
const ageError = body.errors.find((e: { field: string }) => e.field === 'age')
expect(ageError).toBeDefined()
expect(ageError.code).toBeDefined()
}
})
it('returns error for malformed JSON', async () => {
const request = createMalformedRequest()
const result = await validateBody(request, TestSchema)
expect(result.success).toBe(false)
if (!result.success) {
const body = await result.response.json()
expect(result.response.status).toBe(400)
expect(body.error).toBe('Invalid JSON in request body')
expect(body.type).toBe('validation_error')
}
})
it('reports all validation errors, not just the first', async () => {
// Missing name and age
const request = createJsonRequest({})
const result = await validateBody(request, TestSchema)
expect(result.success).toBe(false)
if (!result.success) {
const body = await result.response.json()
expect(body.errors.length).toBeGreaterThanOrEqual(2)
}
})
it('strips unknown fields (Zod default behavior)', async () => {
const request = createJsonRequest({ name: 'Alice', age: 30, secret: 'hidden' })
const result = await validateBody(request, TestSchema)
expect(result.success).toBe(true)
if (result.success) {
expect((result.data as Record<string, unknown>).secret).toBeUndefined()
}
})
it('rejects invalid email format', async () => {
const request = createJsonRequest({ name: 'Alice', age: 30, email: 'not-email' })
const result = await validateBody(request, TestSchema)
expect(result.success).toBe(false)
})
})
// ============================================================
// validateQuery
// ============================================================
describe('validateQuery', () => {
it('returns success with parsed query params', () => {
const request = createRequestWithQuery({ page: '3', limit: '25' })
const result = validateQuery(request, QuerySchema)
expect(result.success).toBe(true)
if (result.success) {
expect(result.data.page).toBe(3)
expect(result.data.limit).toBe(25)
}
})
it('applies defaults for missing params', () => {
const request = createRequestWithQuery({})
const result = validateQuery(request, QuerySchema)
expect(result.success).toBe(true)
if (result.success) {
expect(result.data.page).toBe(1)
expect(result.data.limit).toBe(50)
}
})
it('coerces string values to numbers', () => {
const request = createRequestWithQuery({ page: '10' })
const result = validateQuery(request, QuerySchema)
expect(result.success).toBe(true)
if (result.success) {
expect(typeof result.data.page).toBe('number')
}
})
it('returns failure for invalid query params', () => {
const request = createRequestWithQuery({ page: '0', limit: '200' })
const result = validateQuery(request, QuerySchema)
expect(result.success).toBe(false)
if (!result.success) {
const body = result.response as unknown as { status: number }
expect(result.response.status).toBe(400)
}
})
it('includes error details in response', () => {
const request = createRequestWithQuery({ limit: 'abc' })
const result = validateQuery(request, QuerySchema)
expect(result.success).toBe(false)
if (!result.success) {
// The response is a NextResponse: we verify it's a 400
expect(result.response.status).toBe(400)
}
})
})
// ============================================================
// Integration: validateBody with domain schemas
// ============================================================
describe('validateBody with domain schemas', () => {
// Demonstrates using validateBody with the actual schemas from schemas.ts
// This pattern is what API routes should use
const InvoiceSchema = z.object({
customer_id: z.string().uuid(),
invoice_date: z.string().regex(/^\d{4}-\d{2}-\d{2}$/),
items: z.array(z.object({
description: z.string().min(1),
amount: z.number().positive(),
})).min(1),
})
it('validates a well-formed invoice request', async () => {
const request = createJsonRequest({
customer_id: '550e8400-e29b-41d4-a716-446655440000',
invoice_date: '2025-03-15',
items: [{ description: 'Service', amount: 1000 }],
})
const result = await validateBody(request, InvoiceSchema)
expect(result.success).toBe(true)
})
it('catches nested array validation errors', async () => {
const request = createJsonRequest({
customer_id: '550e8400-e29b-41d4-a716-446655440000',
invoice_date: '2025-03-15',
items: [{ description: '', amount: -1 }],
})
const result = await validateBody(request, InvoiceSchema)
expect(result.success).toBe(false)
if (!result.success) {
const body = await result.response.json()
// Should catch both description and amount errors
expect(body.errors.length).toBeGreaterThanOrEqual(2)
const fields = body.errors.map((e: { field: string }) => e.field)
expect(fields.some((f: string) => f.includes('items'))).toBe(true)
}
})
})
@@ -1,120 +0,0 @@
import { describe, it, expect, vi, beforeEach } from 'vitest'
import { NextResponse } from 'next/server'
import { createMockSupabase } from '@/tests/helpers'
const authState = vi.hoisted(() => ({
user: { id: 'user-1' } as { id: string } | null,
}))
const requireWriteMock = vi.hoisted(() => vi.fn())
vi.mock('@/lib/auth/require-auth', () => ({
requireAuth: vi.fn(async () => {
if (!authState.user) {
return { error: NextResponse.json({ error: 'unauthorized' }, { status: 401 }) }
}
return { user: authState.user, supabase: supabaseRef.supabase }
}),
}))
vi.mock('@/lib/company/context', () => ({
getActiveCompanyId: vi.fn(),
}))
vi.mock('@/lib/auth/require-write', () => ({
requireWritePermission: (...args: unknown[]) => requireWriteMock(...args),
}))
const supabaseRef = vi.hoisted(() => ({ supabase: null as unknown }))
import { withRouteContext } from '../with-route-context'
import { getActiveCompanyId } from '@/lib/company/context'
const EMPTY_PARAMS = { params: Promise.resolve({}) }
describe('withRouteContext', () => {
beforeEach(() => {
vi.clearAllMocks()
authState.user = { id: 'user-1' }
supabaseRef.supabase = createMockSupabase().supabase
vi.mocked(getActiveCompanyId).mockResolvedValue('company-1')
requireWriteMock.mockResolvedValue({ ok: true })
})
it('resolves the company once and hands it to the write guard on write routes', async () => {
const handler = vi.fn(async () => NextResponse.json({ ok: true }))
const route = withRouteContext('test.write', handler, { requireWrite: true })
const res = await route(new Request('http://localhost/api/test', { method: 'POST' }), EMPTY_PARAMS)
expect(res.status).toBe(200)
expect(getActiveCompanyId).toHaveBeenCalledTimes(1)
expect(requireWriteMock).toHaveBeenCalledTimes(1)
expect(requireWriteMock).toHaveBeenCalledWith(supabaseRef.supabase, 'user-1', {
companyId: 'company-1',
})
expect(handler).toHaveBeenCalledWith(
expect.any(Request),
expect.objectContaining({ companyId: 'company-1', user: { id: 'user-1' } }),
EMPTY_PARAMS,
)
})
it('never invokes the write guard on read routes', async () => {
const route = withRouteContext('test.read', async () => NextResponse.json({ ok: true }))
const res = await route(new Request('http://localhost/api/test'), EMPTY_PARAMS)
expect(res.status).toBe(200)
expect(getActiveCompanyId).toHaveBeenCalledTimes(1)
expect(requireWriteMock).not.toHaveBeenCalled()
})
it('passes the guard 403 through with a request id and skips the handler', async () => {
requireWriteMock.mockResolvedValue({
ok: false,
response: NextResponse.json({ error: 'viewer' }, { status: 403 }),
})
const handler = vi.fn(async () => NextResponse.json({ ok: true }))
const route = withRouteContext('test.write', handler, { requireWrite: true })
const res = await route(new Request('http://localhost/api/test', { method: 'POST' }), EMPTY_PARAMS)
expect(res.status).toBe(403)
expect(res.headers.get('X-Request-Id')).toMatch(/^req_/)
expect(handler).not.toHaveBeenCalled()
})
it('returns COMPANY_CONTEXT_MISSING before the guard when no company resolves', async () => {
vi.mocked(getActiveCompanyId).mockResolvedValue(null)
const route = withRouteContext('test.write', async () => NextResponse.json({ ok: true }), {
requireWrite: true,
})
const res = await route(new Request('http://localhost/api/test', { method: 'POST' }), EMPTY_PARAMS)
expect(res.status).toBe(400)
expect(requireWriteMock).not.toHaveBeenCalled()
})
it('returns 401 from requireAuth untouched except for the request id', async () => {
authState.user = null
const route = withRouteContext('test.read', async () => NextResponse.json({ ok: true }))
const res = await route(new Request('http://localhost/api/test'), EMPTY_PARAMS)
expect(res.status).toBe(401)
expect(res.headers.get('X-Request-Id')).toMatch(/^req_/)
expect(getActiveCompanyId).not.toHaveBeenCalled()
})
it('emits a Server-Timing header with the auth, company and handler phases', async () => {
const route = withRouteContext('test.read', async () => NextResponse.json({ ok: true }))
const res = await route(new Request('http://localhost/api/test'), EMPTY_PARAMS)
expect(res.headers.get('Server-Timing')).toMatch(
/^auth;dur=\d+, company;dur=\d+, handler;dur=\d+$/,
)
})
})