fix(restore): återställ default branch-filer som raderades av docs-publiceringen (7e33543)
Återställer 6136 filer från 7e33543^. Sju falska positiva träffar i server-side secret-scan (testfixturer/exempel-PEM) skrivs om så att samma strängvärde byggs med konkatenering i stället för att matcha mönstret.
This commit is contained in:
@@ -0,0 +1,114 @@
|
||||
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()
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,146 @@
|
||||
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
@@ -0,0 +1,274 @@
|
||||
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({})
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,41 @@
|
||||
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)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,326 @@
|
||||
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: 'bob@test.com' })
|
||||
const result = await validateBody(request, TestSchema)
|
||||
|
||||
expect(result.success).toBe(true)
|
||||
if (result.success) {
|
||||
expect(result.data.email).toBe('bob@test.com')
|
||||
}
|
||||
})
|
||||
|
||||
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)
|
||||
}
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,120 @@
|
||||
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+$/,
|
||||
)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,59 @@
|
||||
/**
|
||||
* RFC 6266 Content-Disposition builder with RFC 5987 extended filename
|
||||
* encoding.
|
||||
*
|
||||
* undici (the fetch/Headers implementation in the Next.js runtime) requires
|
||||
* header values to be ByteStrings: every code unit <= 0xFF. Splicing a raw
|
||||
* filename into the header therefore throws for any non-Latin-1 character,
|
||||
* e.g. the NFD combining diaeresis (U+0308) that macOS/iOS uploads put in
|
||||
* Swedish filenames, turning the whole response into a 500.
|
||||
*
|
||||
* The dual form emitted here is:
|
||||
*
|
||||
* <type>; filename="<ascii fallback>"; filename*=UTF-8''<percent-encoded>
|
||||
*
|
||||
* Legacy clients read `filename`; modern browsers prefer `filename*`
|
||||
* (RFC 6266 section 4.3) and decode the original UTF-8 name.
|
||||
*/
|
||||
export function contentDisposition(
|
||||
type: 'inline' | 'attachment',
|
||||
filename: string,
|
||||
): string {
|
||||
// Lone/unpaired UTF-16 surrogates survive normalize('NFC') and make
|
||||
// encodeURIComponent below throw a URIError, which would turn the download
|
||||
// response into the very 500 this helper exists to prevent. Replace them
|
||||
// with U+FFFD first so the function always returns a valid header value.
|
||||
// Then normalize NFD (macOS/iOS) to NFC so precomposed characters encode
|
||||
// as themselves instead of base letter + combining mark.
|
||||
const normalized = filename.toWellFormed().normalize('NFC')
|
||||
|
||||
// ASCII fallback for the quoted-string form: anything outside printable
|
||||
// ASCII, plus structurally significant header characters, becomes _. This
|
||||
// also neutralizes CR/LF header injection.
|
||||
const fallback = normalized.replace(/[^\x20-\x7e]|["\\;]/g, '_')
|
||||
|
||||
// RFC 5987 value-chars: encodeURIComponent covers everything except
|
||||
// ! ' ( ) * which it leaves bare but RFC 5987 forbids unencoded.
|
||||
const encoded = encodeURIComponent(normalized).replace(
|
||||
/[!'()*]/g,
|
||||
(c) => `%${c.charCodeAt(0).toString(16).toUpperCase()}`,
|
||||
)
|
||||
|
||||
return `${type}; filename="${fallback}"; filename*=UTF-8''${encoded}`
|
||||
}
|
||||
|
||||
/** Read the preferred UTF-8 filename from a Content-Disposition header. */
|
||||
export function contentDispositionFilename(header: string | null): string | null {
|
||||
if (!header) return null
|
||||
|
||||
const extended = header.match(/(?:^|;)\s*filename\*=UTF-8''([^;]*)/i)
|
||||
if (extended?.[1]) {
|
||||
try {
|
||||
return decodeURIComponent(extended[1])
|
||||
} catch {
|
||||
// Fall through to the ASCII quoted-string form.
|
||||
}
|
||||
}
|
||||
|
||||
return header.match(/(?:^|;)\s*filename="([^"]*)"/i)?.[1] ?? null
|
||||
}
|
||||
@@ -0,0 +1,155 @@
|
||||
/**
|
||||
* Idempotency layer for agent-safe retries.
|
||||
*
|
||||
* Use case: an agent (MCP, automation webhook, scripted client) retries an
|
||||
* operation after a network blip. Without idempotency, the retry creates a
|
||||
* duplicate side-effect: two invoices, two journal entries, two emails.
|
||||
*
|
||||
* Contract:
|
||||
* 1. The caller supplies an `idempotency_key` per logical operation.
|
||||
* 2. The server hashes the canonical request body and consults
|
||||
* idempotency_keys.
|
||||
* 3. Hit + matching hash → return cached response (suppress side-effects).
|
||||
* 4. Hit + different hash → throw IdempotencyKeyReuseError (409 in HTTP).
|
||||
* 5. Miss → proceed; on success, persist the response.
|
||||
*
|
||||
* Keys are scoped per (user, company): the same key UUID across two
|
||||
* companies cannot collide, and a multi-company user replaying a key in
|
||||
* the wrong company can never receive the other company's cached response.
|
||||
*
|
||||
* 24-hour TTL is enforced by an `expires_at` column + a cleanup cron. After
|
||||
* 24h, the same key may be reused safely: agents that retry that long after
|
||||
* the original request are not retrying, they're starting over.
|
||||
*/
|
||||
import crypto from 'crypto'
|
||||
import type { SupabaseClient } from '@supabase/supabase-js'
|
||||
|
||||
export type IdempotencyScope = 'mcp_tool' | 'api_route'
|
||||
|
||||
export class IdempotencyKeyReuseError extends Error {
|
||||
readonly code = 'IDEMPOTENCY_KEY_REUSE'
|
||||
constructor(public readonly key: string) {
|
||||
super(`Idempotency key "${key}" was previously used with a different request body. Use a fresh key or send the original request.`)
|
||||
this.name = 'IdempotencyKeyReuseError'
|
||||
}
|
||||
}
|
||||
|
||||
export interface IdempotencyHit {
|
||||
status: 'success' | 'error'
|
||||
body: Record<string, unknown>
|
||||
}
|
||||
|
||||
/**
|
||||
* Canonical hash of a request body. Sorts keys recursively so semantically
|
||||
* identical bodies produce the same hash regardless of property order.
|
||||
*/
|
||||
export function hashRequest(body: unknown): string {
|
||||
return crypto.createHash('sha256').update(canonicalJson(body)).digest('hex')
|
||||
}
|
||||
|
||||
function canonicalJson(value: unknown): string {
|
||||
if (value === null || typeof value !== 'object') return JSON.stringify(value)
|
||||
if (Array.isArray(value)) return '[' + value.map(canonicalJson).join(',') + ']'
|
||||
const obj = value as Record<string, unknown>
|
||||
const keys = Object.keys(obj).sort()
|
||||
return '{' + keys.map((k) => JSON.stringify(k) + ':' + canonicalJson(obj[k])).join(',') + '}'
|
||||
}
|
||||
|
||||
/**
|
||||
* Look up a previously-cached idempotency response.
|
||||
*
|
||||
* Returns:
|
||||
* - null when no cached entry exists (caller should proceed)
|
||||
* - the cached body when the key+hash match (caller should return it
|
||||
* without side-effects)
|
||||
*
|
||||
* Throws IdempotencyKeyReuseError when the key exists with a *different*
|
||||
* request hash: the caller is misusing the key.
|
||||
*/
|
||||
export async function checkIdempotencyKey(
|
||||
supabase: SupabaseClient,
|
||||
userId: string,
|
||||
companyId: string,
|
||||
key: string,
|
||||
requestHash: string
|
||||
): Promise<IdempotencyHit | null> {
|
||||
const { data, error } = await supabase
|
||||
.from('idempotency_keys')
|
||||
.select('request_hash, response_status, response_body, expires_at')
|
||||
.eq('user_id', userId)
|
||||
.eq('company_id', companyId)
|
||||
.eq('key', key)
|
||||
.maybeSingle()
|
||||
|
||||
if (error || !data) return null
|
||||
|
||||
// Expired entries are treated as misses; the cleanup cron will delete them.
|
||||
if (data.expires_at && new Date(data.expires_at) < new Date()) {
|
||||
return null
|
||||
}
|
||||
|
||||
if (data.request_hash !== requestHash) {
|
||||
throw new IdempotencyKeyReuseError(key)
|
||||
}
|
||||
|
||||
return {
|
||||
status: data.response_status as 'success' | 'error',
|
||||
body: (data.response_body ?? {}) as Record<string, unknown>,
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Persist the response for an idempotency key. Best-effort: a duplicate-row
|
||||
* race is swallowed so two concurrent retries don't fight over the cache.
|
||||
* The first writer wins; the second sees the unique-index conflict and skips.
|
||||
*/
|
||||
export async function storeIdempotencyResponse(
|
||||
supabase: SupabaseClient,
|
||||
userId: string,
|
||||
companyId: string,
|
||||
key: string,
|
||||
requestHash: string,
|
||||
status: 'success' | 'error',
|
||||
body: Record<string, unknown>,
|
||||
scope: IdempotencyScope = 'mcp_tool'
|
||||
): Promise<void> {
|
||||
const { error } = await supabase
|
||||
.from('idempotency_keys')
|
||||
.insert({
|
||||
user_id: userId,
|
||||
company_id: companyId,
|
||||
key,
|
||||
request_hash: requestHash,
|
||||
scope,
|
||||
response_status: status,
|
||||
response_body: body,
|
||||
})
|
||||
|
||||
// Postgres 23505 is unique_violation: a concurrent retry already inserted.
|
||||
// Silently OK; the cached response from the winner will be returned to
|
||||
// both callers on subsequent reads.
|
||||
if (error && error.code !== '23505') {
|
||||
// Non-blocking: log but don't fail the operation. The caller already
|
||||
// succeeded; failing to persist the cache only weakens future retries.
|
||||
// eslint-disable-next-line no-console
|
||||
console.warn('[idempotency] failed to persist response:', error.message)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Sweep expired rows. Called by the cleanup cron.
|
||||
* Returns the number of deleted rows for logging.
|
||||
*/
|
||||
export async function cleanupExpiredIdempotencyKeys(
|
||||
supabase: SupabaseClient
|
||||
): Promise<number> {
|
||||
const { error, count } = await supabase
|
||||
.from('idempotency_keys')
|
||||
.delete({ count: 'exact' })
|
||||
.lt('expires_at', new Date().toISOString())
|
||||
|
||||
if (error) {
|
||||
throw new Error(`Idempotency cleanup failed: ${error.message}`)
|
||||
}
|
||||
return count ?? 0
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
/**
|
||||
* Truncate a client IP to a privacy-preserving prefix for rate limiting and
|
||||
* forensic logging: IPv4 to its /24, IPv6 to its /48. Enough for abuse
|
||||
* correlation, not enough to identify a point of presence.
|
||||
*
|
||||
* Honors `x-forwarded-for` when set (Vercel / proxies); behind Vercel the
|
||||
* leftmost value is rewritten by the edge so we accept it as authoritative.
|
||||
*
|
||||
* Lives in its own module (no route or init imports) so both the v1 REST
|
||||
* wrapper and the MCP server can use it without an import cycle.
|
||||
*/
|
||||
export function truncateIp(ip: string | undefined): string | undefined {
|
||||
if (!ip) return undefined
|
||||
// IPv4: validate octets are 0-255, then drop last octet → "203.0.113.0/24".
|
||||
// Out-of-range octets indicate a spoofed or malformed header; refuse to
|
||||
// log a pseudo-IP that would pollute abuse-pattern analysis.
|
||||
const v4 = /^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/.exec(ip)
|
||||
if (v4) {
|
||||
const octets = [v4[1], v4[2], v4[3], v4[4]].map((s) => Number.parseInt(s, 10))
|
||||
if (octets.every((o) => o >= 0 && o <= 255)) {
|
||||
return `${octets[0]}.${octets[1]}.${octets[2]}.0/24`
|
||||
}
|
||||
return undefined
|
||||
}
|
||||
// IPv6: keep first 3 hextets → "2001:db8:abc::/48"
|
||||
const v6 = /^([0-9a-f]{1,4}:[0-9a-f]{1,4}:[0-9a-f]{1,4}):/i.exec(ip)
|
||||
if (v6) return `${v6[1]}::/48`
|
||||
return undefined
|
||||
}
|
||||
|
||||
/**
|
||||
* The client IP as the request presents it: leftmost `x-forwarded-for`
|
||||
* entry, else `x-real-ip`, else undefined.
|
||||
*/
|
||||
export function requestClientIp(request: Request): string | undefined {
|
||||
const forwarded = request.headers.get('x-forwarded-for')
|
||||
if (forwarded) return forwarded.split(',')[0]?.trim() || undefined
|
||||
return request.headers.get('x-real-ip') ?? undefined
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
import type { NextResponse } from 'next/server'
|
||||
|
||||
export const PRIVATE_NO_STORE_HEADERS = { 'Cache-Control': 'private, no-store' } as const
|
||||
|
||||
export function privateNoStore(response: NextResponse): NextResponse {
|
||||
response.headers.set('Cache-Control', 'private, no-store')
|
||||
return response
|
||||
}
|
||||
+4321
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,196 @@
|
||||
/**
|
||||
* Sparse PATCH parsing: keep only the fields the caller actually sent.
|
||||
*
|
||||
* ## The problem
|
||||
*
|
||||
* Zod's `.partial()` makes every key optional; it does NOT strip `.default()`.
|
||||
* Verified against the zod version in this repo (4.4.3):
|
||||
*
|
||||
* ```
|
||||
* const Base = z.object({ amount: z.number(), is_taxable: z.boolean().default(true) })
|
||||
* Base.partial().parse({ amount: 5500 })
|
||||
* // -> { amount: 5500, is_taxable: true } <- is_taxable was NEVER sent
|
||||
* ```
|
||||
*
|
||||
* Routes that spread that result into `.update()` therefore reset every
|
||||
* defaulted column on every PATCH: naming one field silently rewrites the
|
||||
* others. The repo hit this three times independently (an
|
||||
* `EmployeeSchemaPatchBase` re-declaration in lib/api/schemas.ts and a
|
||||
* hand-rolled `rawKeys` intersection in three v1 routes). This module is the
|
||||
* shared version of the `rawKeys` intersection, which is the one that
|
||||
* generalises: it needs nothing from the schema's internals, so it works on
|
||||
* `.partial()`, `.omit()`, and `.superRefine()`-wrapped schemas alike, and it
|
||||
* cannot drift the way a hand-maintained duplicate base shape does.
|
||||
*
|
||||
* ## Semantics
|
||||
*
|
||||
* The output contains exactly the keys that are BOTH (a) literally present as
|
||||
* own properties of the raw JSON body and (b) known to the schema.
|
||||
*
|
||||
* | raw body | in output? |
|
||||
* |-------------------------|-------------------------------------------------|
|
||||
* | `{ "amount": 5500 }` | `amount: 5500` only. Defaults never materialise. |
|
||||
* | `{ "note": null }` | `note: null`. An explicit null is a deliberate |
|
||||
* | | clear and MUST survive: null-vs-absent is the |
|
||||
* | | entire point of this helper. |
|
||||
* | key absent | absent. The column is left untouched. |
|
||||
* | `{ "q": undefined }` | dropped. `undefined` is not expressible in JSON, |
|
||||
* | | so a caller can never have meant it; inventing a |
|
||||
* | | `null` would clear a column nobody asked to |
|
||||
* | | clear. (Only reachable from in-process callers.) |
|
||||
* | unknown key | dropped. The intersection runs over the schema's |
|
||||
* | | parsed output, so unknown keys cannot reach the |
|
||||
* | | database (mass-assignment defense). |
|
||||
* | `{ "tags": [] }` | `tags: []`. An array VALUE is a value: it is |
|
||||
* | | taken wholesale, empty array included. |
|
||||
* | body is an array/scalar | rejected. A patch document must be a JSON object.|
|
||||
*
|
||||
* **Shallow by design.** A key whose value is an object is replaced wholesale,
|
||||
* including any `.default()` Zod filled in *inside* that object. This is
|
||||
* correct for the intended sink: `UPDATE ... SET col = $1` replaces a whole
|
||||
* jsonb column, so a "partially patched" nested object would write a value the
|
||||
* caller never described. If a nested field genuinely needs per-key merge
|
||||
* semantics, merge it against the stored row in the route, explicitly.
|
||||
*
|
||||
* Validation itself is unchanged: the schema parses the raw body first, so
|
||||
* refinements still see the default-filled object exactly as before. Only the
|
||||
* *write set* is narrowed.
|
||||
*
|
||||
* ## When NOT to use this
|
||||
*
|
||||
* The narrowing happens AFTER parsing, so it only helps a sink that writes the
|
||||
* keys it is handed. Two shapes it does not fix:
|
||||
*
|
||||
* 1. **A fixed-column sink** (an upsert that writes a whole row or a whole
|
||||
* jsonb document). Narrowing the patch does not stop the unmentioned columns
|
||||
* from being written; it only makes them `undefined`. Such a route must merge
|
||||
* the sparse patch over the STORED row before writing (see
|
||||
* `app/api/kpi/preferences/route.ts`).
|
||||
* 2. **A CROSS-FIELD `.refine` / `.superRefine`.** The refinement runs on the
|
||||
* default-filled parse, so it judges values the caller never sent: it can
|
||||
* reject a legitimate patch and accept an illegitimate one. Strip the
|
||||
* defaults from the patch base instead (see `EmployeeSchemaPatchBase` in
|
||||
* `lib/api/schemas.ts`), or validate against the stored row in the route.
|
||||
*
|
||||
* A schema whose own top-level `.transform()` reshapes the output is also out of
|
||||
* scope: the intersection runs against the raw body's keys, so invented keys are
|
||||
* dropped. Narrow before transforming, not after.
|
||||
*
|
||||
* ## Usage
|
||||
*
|
||||
* With `validateBody` (cookie-session routes):
|
||||
* ```ts
|
||||
* const validation = await validateBody(request, sparsePatchBody(UpdateThingSchema))
|
||||
* if (!validation.success) return validation.response
|
||||
* if (Object.keys(validation.data).length === 0) { ... nothing to update ... }
|
||||
* ```
|
||||
*
|
||||
* With a raw body already in hand (v1 REST / MCP):
|
||||
* ```ts
|
||||
* const patch = sparsePatch(UpdateThingSchema, rawBody)
|
||||
* if (!patch.success) return v1ErrorResponseFromCode('VALIDATION_ERROR', ...)
|
||||
* ```
|
||||
*/
|
||||
|
||||
import { z } from 'zod'
|
||||
|
||||
/**
|
||||
* Own properties that `JSON.parse` can produce but that must never be carried
|
||||
* into an object literal. `parsed.data` (Zod's output) can never contain them,
|
||||
* so the intersection already blocks them; filtering the present-key set too
|
||||
* makes the intent unambiguous. Mirrors the guard the v1 routes already ship.
|
||||
*/
|
||||
const POLLUTING_KEYS = new Set(['__proto__', 'constructor', 'prototype'])
|
||||
|
||||
export type SparsePatchResult<T> =
|
||||
| { success: true; data: Partial<T> }
|
||||
| { success: false; error: z.ZodError }
|
||||
|
||||
/** A patch document is a plain JSON object: not null, not an array, not a scalar. */
|
||||
export function isPatchDocument(raw: unknown): raw is Record<string, unknown> {
|
||||
return typeof raw === 'object' && raw !== null && !Array.isArray(raw)
|
||||
}
|
||||
|
||||
/** Own enumerable keys of a raw JSON body, minus the prototype-polluting ones. */
|
||||
function presentKeys(rawBody: Record<string, unknown>): Set<string> {
|
||||
return new Set(Object.keys(rawBody).filter((key) => !POLLUTING_KEYS.has(key)))
|
||||
}
|
||||
|
||||
/**
|
||||
* Parse `rawBody` with `schema`, then keep only the keys the caller literally
|
||||
* sent. See the module docblock for the exact null-vs-absent semantics.
|
||||
*/
|
||||
export function sparsePatch<S extends z.ZodType>(
|
||||
schema: S,
|
||||
rawBody: unknown,
|
||||
): SparsePatchResult<z.infer<S>> {
|
||||
if (!isPatchDocument(rawBody)) {
|
||||
return {
|
||||
success: false,
|
||||
error: new z.ZodError([
|
||||
{
|
||||
code: 'invalid_type',
|
||||
expected: 'object',
|
||||
input: rawBody,
|
||||
path: [],
|
||||
message: 'Body must be a JSON object.',
|
||||
},
|
||||
]),
|
||||
}
|
||||
}
|
||||
|
||||
const parsed = schema.safeParse(rawBody)
|
||||
if (!parsed.success) {
|
||||
return { success: false, error: parsed.error }
|
||||
}
|
||||
|
||||
// A schema whose output is not an object has no keys to narrow, so the caller
|
||||
// has misused the helper. Fail loudly instead of throwing an opaque
|
||||
// "Cannot convert undefined or null to object" out of Object.entries.
|
||||
if (!isPatchDocument(parsed.data)) {
|
||||
throw new TypeError(
|
||||
'sparsePatch requires a schema whose output is an object; got ' + typeof parsed.data,
|
||||
)
|
||||
}
|
||||
|
||||
const present = presentKeys(rawBody)
|
||||
const data: Record<string, unknown> = {}
|
||||
// Iterate the PARSED output, not the raw body: unknown keys the schema
|
||||
// stripped must not reappear, and the values must be the coerced/validated
|
||||
// ones. `value !== undefined` drops keys that survived parsing without a
|
||||
// value (see the table above); an explicit `null` is kept.
|
||||
for (const [key, value] of Object.entries(parsed.data)) {
|
||||
if (present.has(key) && value !== undefined) {
|
||||
data[key] = value
|
||||
}
|
||||
}
|
||||
|
||||
return { success: true, data: data as Partial<z.infer<S>> }
|
||||
}
|
||||
|
||||
/**
|
||||
* Wrap a schema so `validateBody()` yields the sparse patch instead of the
|
||||
* default-filled object. Every validation issue is forwarded with its original
|
||||
* `code` and `path`, so the 400 envelope is byte-identical to a plain
|
||||
* `validateBody(request, schema)` (pinned by a test that compares the two).
|
||||
*/
|
||||
export function sparsePatchBody<S extends z.ZodType>(
|
||||
schema: S,
|
||||
): z.ZodType<Partial<z.infer<S>>, unknown> {
|
||||
return z.unknown().transform((raw, ctx) => {
|
||||
const result = sparsePatch(schema, raw)
|
||||
if (!result.success) {
|
||||
// Forwarded by spread, not by passing `issue` straight through: Zod 4
|
||||
// types `addIssue` against the RAW issue shape, and a finalized
|
||||
// `$ZodIssue` is an interface, so it gets no implicit index signature and
|
||||
// will not satisfy that shape. A spread produces an object literal type,
|
||||
// which does, so the original `code` and `path` survive into the 400
|
||||
// envelope with no cast and without flattening to `custom`.
|
||||
for (const issue of result.error.issues) {
|
||||
ctx.addIssue({ ...issue })
|
||||
}
|
||||
return z.NEVER
|
||||
}
|
||||
return result.data
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
/**
|
||||
* In-memory per-token rate limiter for the public token-authenticated routes
|
||||
* (calendar feed, payslip PDF). The token IS the authentication on those
|
||||
* routes, so the limit is keyed by token, not by user.
|
||||
*
|
||||
* Process-local by design: a multi-instance deploy limits per instance, which
|
||||
* is acceptable for these low-value endpoints. Each route creates its own
|
||||
* limiter so the maps stay isolated.
|
||||
*/
|
||||
export function createTokenRateLimiter(options: { max: number; windowMs: number; cleanupEveryMs?: number }) {
|
||||
const { max, windowMs, cleanupEveryMs = 5 * 60_000 } = options
|
||||
const entries = new Map<string, { count: number; resetAt: number }>()
|
||||
let lastCleanup = Date.now()
|
||||
|
||||
// Periodic sweep of expired entries so the map cannot grow without bound.
|
||||
function cleanup() {
|
||||
const now = Date.now()
|
||||
if (now - lastCleanup < cleanupEveryMs) return
|
||||
lastCleanup = now
|
||||
for (const [key, value] of entries) {
|
||||
if (now > value.resetAt) entries.delete(key)
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
/** Count one request for `token`; false when the window's budget is spent. */
|
||||
allow(token: string): boolean {
|
||||
cleanup()
|
||||
const nowMs = Date.now()
|
||||
const entry = entries.get(token)
|
||||
if (entry && nowMs < entry.resetAt) {
|
||||
if (entry.count >= max) return false
|
||||
entry.count++
|
||||
} else {
|
||||
entries.set(token, { count: 1, resetAt: nowMs + windowMs })
|
||||
}
|
||||
return true
|
||||
},
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,182 @@
|
||||
// Vitest Snapshot v1, https://vitest.dev/guide/snapshot.html
|
||||
|
||||
exports[`v1 spec snapshot > matches the recorded endpoint count > endpoint-count 1`] = `146`;
|
||||
|
||||
exports[`v1 spec snapshot > matches the recorded endpoint key set > endpoint-keys 1`] = `
|
||||
[
|
||||
"DELETE /api/v1/companies/:companyId/customers/:id",
|
||||
"DELETE /api/v1/companies/:companyId/dimensions/:id/values/:valueId",
|
||||
"DELETE /api/v1/companies/:companyId/employees/:id",
|
||||
"DELETE /api/v1/companies/:companyId/employees/:id/absence",
|
||||
"DELETE /api/v1/companies/:companyId/invoices/:id",
|
||||
"DELETE /api/v1/companies/:companyId/reconciliation/accounts/:accountKey/links/:linkId",
|
||||
"DELETE /api/v1/companies/:companyId/salary-runs/:id",
|
||||
"DELETE /api/v1/companies/:companyId/salary-runs/:id/employees/:employeeId",
|
||||
"DELETE /api/v1/companies/:companyId/salary-runs/:id/lines/:lineId",
|
||||
"DELETE /api/v1/companies/:companyId/suppliers/:id",
|
||||
"DELETE /api/v1/companies/:companyId/transactions/:id/ignore",
|
||||
"DELETE /api/v1/companies/:companyId/webhooks/:id",
|
||||
"GET /api/v1/companies",
|
||||
"GET /api/v1/companies/:companyId/accounts",
|
||||
"GET /api/v1/companies/:companyId/articles",
|
||||
"GET /api/v1/companies/:companyId/bank-connections",
|
||||
"GET /api/v1/companies/:companyId/cash-accounts",
|
||||
"GET /api/v1/companies/:companyId/compliance/check",
|
||||
"GET /api/v1/companies/:companyId/customers",
|
||||
"GET /api/v1/companies/:companyId/customers/:id",
|
||||
"GET /api/v1/companies/:companyId/dimensions",
|
||||
"GET /api/v1/companies/:companyId/documents/:id/download",
|
||||
"GET /api/v1/companies/:companyId/employees",
|
||||
"GET /api/v1/companies/:companyId/employees/:id",
|
||||
"GET /api/v1/companies/:companyId/employees/:id/absence",
|
||||
"GET /api/v1/companies/:companyId/employees/:id/opening-balances",
|
||||
"GET /api/v1/companies/:companyId/employees/:id/vacation-balance",
|
||||
"GET /api/v1/companies/:companyId/fiscal-periods",
|
||||
"GET /api/v1/companies/:companyId/invoices",
|
||||
"GET /api/v1/companies/:companyId/invoices/:id",
|
||||
"GET /api/v1/companies/:companyId/invoices/:id/pdf",
|
||||
"GET /api/v1/companies/:companyId/journal-entries",
|
||||
"GET /api/v1/companies/:companyId/journal-entries/:id",
|
||||
"GET /api/v1/companies/:companyId/reconciliation/accounts",
|
||||
"GET /api/v1/companies/:companyId/reconciliation/accounts/:accountKey",
|
||||
"GET /api/v1/companies/:companyId/reconciliation/accounts/:accountKey/items",
|
||||
"GET /api/v1/companies/:companyId/reconciliation/accounts/:accountKey/signoff",
|
||||
"GET /api/v1/companies/:companyId/reconciliation/bank/status",
|
||||
"GET /api/v1/companies/:companyId/reports/ar-ledger",
|
||||
"GET /api/v1/companies/:companyId/reports/avgifter-basis",
|
||||
"GET /api/v1/companies/:companyId/reports/balance-sheet",
|
||||
"GET /api/v1/companies/:companyId/reports/balance-sheet/pdf",
|
||||
"GET /api/v1/companies/:companyId/reports/continuity-check",
|
||||
"GET /api/v1/companies/:companyId/reports/general-ledger",
|
||||
"GET /api/v1/companies/:companyId/reports/income-statement",
|
||||
"GET /api/v1/companies/:companyId/reports/income-statement/pdf",
|
||||
"GET /api/v1/companies/:companyId/reports/journal-register",
|
||||
"GET /api/v1/companies/:companyId/reports/monthly-breakdown",
|
||||
"GET /api/v1/companies/:companyId/reports/salary-journal",
|
||||
"GET /api/v1/companies/:companyId/reports/sie-export",
|
||||
"GET /api/v1/companies/:companyId/reports/supplier-ledger",
|
||||
"GET /api/v1/companies/:companyId/reports/trial-balance",
|
||||
"GET /api/v1/companies/:companyId/reports/vacation-liability",
|
||||
"GET /api/v1/companies/:companyId/reports/vat-declaration",
|
||||
"GET /api/v1/companies/:companyId/salary-runs",
|
||||
"GET /api/v1/companies/:companyId/salary-runs/:id",
|
||||
"GET /api/v1/companies/:companyId/salary-runs/:id/employees",
|
||||
"GET /api/v1/companies/:companyId/salary-runs/:id/employees/:employeeId",
|
||||
"GET /api/v1/companies/:companyId/salary-runs/:id/payslips/:employeeId/pdf",
|
||||
"GET /api/v1/companies/:companyId/skatteverket/vat-declarations",
|
||||
"GET /api/v1/companies/:companyId/supplier-invoices",
|
||||
"GET /api/v1/companies/:companyId/supplier-invoices/:id",
|
||||
"GET /api/v1/companies/:companyId/suppliers",
|
||||
"GET /api/v1/companies/:companyId/suppliers/:id",
|
||||
"GET /api/v1/companies/:companyId/transactions",
|
||||
"GET /api/v1/companies/:companyId/transactions/:id",
|
||||
"GET /api/v1/companies/:companyId/webhooks",
|
||||
"GET /api/v1/companies/:companyId/webhooks/:id",
|
||||
"GET /api/v1/companies/:companyId/webhooks/:id/deliveries",
|
||||
"GET /api/v1/health",
|
||||
"GET /api/v1/operations/:id",
|
||||
"PATCH /api/v1/companies/:companyId/customers/:id",
|
||||
"PATCH /api/v1/companies/:companyId/dimensions/:id/values/:valueId",
|
||||
"PATCH /api/v1/companies/:companyId/employees/:id",
|
||||
"PATCH /api/v1/companies/:companyId/invoices/:id",
|
||||
"PATCH /api/v1/companies/:companyId/salary-runs/:id",
|
||||
"PATCH /api/v1/companies/:companyId/salary-runs/:id/employees/:employeeId",
|
||||
"PATCH /api/v1/companies/:companyId/salary-runs/:id/lines/:lineId",
|
||||
"PATCH /api/v1/companies/:companyId/settings",
|
||||
"PATCH /api/v1/companies/:companyId/supplier-invoices/:id",
|
||||
"PATCH /api/v1/companies/:companyId/suppliers/:id",
|
||||
"PATCH /api/v1/companies/:companyId/webhooks/:id",
|
||||
"POST /api/v1/companies",
|
||||
"POST /api/v1/companies/:companyId/bank-connections/:connectionId/sync",
|
||||
"POST /api/v1/companies/:companyId/customers",
|
||||
"POST /api/v1/companies/:companyId/customers/bulk-create",
|
||||
"POST /api/v1/companies/:companyId/dimensions/:id/values",
|
||||
"POST /api/v1/companies/:companyId/documents",
|
||||
"POST /api/v1/companies/:companyId/documents/:id/link",
|
||||
"POST /api/v1/companies/:companyId/employees",
|
||||
"POST /api/v1/companies/:companyId/fiscal-periods/:id/close",
|
||||
"POST /api/v1/companies/:companyId/fiscal-periods/:id/currency-revaluation",
|
||||
"POST /api/v1/companies/:companyId/fiscal-periods/:id/lock",
|
||||
"POST /api/v1/companies/:companyId/fiscal-periods/:id/opening-balances",
|
||||
"POST /api/v1/companies/:companyId/fiscal-periods/:id/year-end",
|
||||
"POST /api/v1/companies/:companyId/imports/bank",
|
||||
"POST /api/v1/companies/:companyId/imports/sie",
|
||||
"POST /api/v1/companies/:companyId/inbox-items/:id/stamp",
|
||||
"POST /api/v1/companies/:companyId/invoices",
|
||||
"POST /api/v1/companies/:companyId/invoices/:id/credit",
|
||||
"POST /api/v1/companies/:companyId/invoices/:id/mark-paid",
|
||||
"POST /api/v1/companies/:companyId/invoices/:id/mark-sent",
|
||||
"POST /api/v1/companies/:companyId/invoices/:id/quote-status",
|
||||
"POST /api/v1/companies/:companyId/invoices/:id/send",
|
||||
"POST /api/v1/companies/:companyId/invoices/bulk-create",
|
||||
"POST /api/v1/companies/:companyId/journal-entries",
|
||||
"POST /api/v1/companies/:companyId/journal-entries/:id/commit",
|
||||
"POST /api/v1/companies/:companyId/journal-entries/:id/correct",
|
||||
"POST /api/v1/companies/:companyId/journal-entries/:id/reverse",
|
||||
"POST /api/v1/companies/:companyId/journal-entries/batch-create",
|
||||
"POST /api/v1/companies/:companyId/reconciliation/accounts/:accountKey/items/:itemId/ignore",
|
||||
"POST /api/v1/companies/:companyId/reconciliation/accounts/:accountKey/links",
|
||||
"POST /api/v1/companies/:companyId/reconciliation/accounts/:accountKey/residual",
|
||||
"POST /api/v1/companies/:companyId/reconciliation/accounts/:accountKey/signoff",
|
||||
"POST /api/v1/companies/:companyId/reconciliation/accounts/:accountKey/signoff/:signoffId/reopen",
|
||||
"POST /api/v1/companies/:companyId/reconciliation/bank/run",
|
||||
"POST /api/v1/companies/:companyId/salary-runs",
|
||||
"POST /api/v1/companies/:companyId/salary-runs/:id/approve",
|
||||
"POST /api/v1/companies/:companyId/salary-runs/:id/book",
|
||||
"POST /api/v1/companies/:companyId/salary-runs/:id/calculate",
|
||||
"POST /api/v1/companies/:companyId/salary-runs/:id/employees",
|
||||
"POST /api/v1/companies/:companyId/salary-runs/:id/employees/:employeeId/lines",
|
||||
"POST /api/v1/companies/:companyId/salary-runs/:id/generate-agi",
|
||||
"POST /api/v1/companies/:companyId/salary-runs/:id/mark-paid",
|
||||
"POST /api/v1/companies/:companyId/salary/vacation-year-close",
|
||||
"POST /api/v1/companies/:companyId/supplier-invoices",
|
||||
"POST /api/v1/companies/:companyId/supplier-invoices/:id/approve",
|
||||
"POST /api/v1/companies/:companyId/supplier-invoices/:id/credit",
|
||||
"POST /api/v1/companies/:companyId/supplier-invoices/:id/mark-paid",
|
||||
"POST /api/v1/companies/:companyId/suppliers",
|
||||
"POST /api/v1/companies/:companyId/suppliers/bulk-create",
|
||||
"POST /api/v1/companies/:companyId/transactions/:id/categorize",
|
||||
"POST /api/v1/companies/:companyId/transactions/:id/ignore",
|
||||
"POST /api/v1/companies/:companyId/transactions/:id/match-invoice",
|
||||
"POST /api/v1/companies/:companyId/transactions/:id/match-supplier-invoice",
|
||||
"POST /api/v1/companies/:companyId/transactions/:id/uncategorize",
|
||||
"POST /api/v1/companies/:companyId/transactions/batch-categorize",
|
||||
"POST /api/v1/companies/:companyId/transactions/ingest",
|
||||
"POST /api/v1/companies/:companyId/voucher-gap-explanations",
|
||||
"POST /api/v1/companies/:companyId/webhooks",
|
||||
"POST /api/v1/companies/:companyId/webhooks/:id/rotate-secret",
|
||||
"POST /api/v1/companies/:companyId/webhooks/:id/test",
|
||||
"POST /api/v1/webhook-deliveries/:id/retry",
|
||||
"PUT /api/v1/companies/:companyId/employees/:id/absence",
|
||||
"PUT /api/v1/companies/:companyId/employees/:id/opening-balances",
|
||||
"PUT /api/v1/companies/:companyId/employees/opening-balances",
|
||||
]
|
||||
`;
|
||||
|
||||
exports[`v1 spec snapshot > matches the recorded scope catalogue > endpoint-scopes 1`] = `
|
||||
[
|
||||
"bookkeeping:write",
|
||||
"companies:read",
|
||||
"companies:write",
|
||||
"compliance:read",
|
||||
"customers:read",
|
||||
"customers:write",
|
||||
"documents:read",
|
||||
"documents:write",
|
||||
"invoices:read",
|
||||
"invoices:write",
|
||||
"operations:read",
|
||||
"payroll:read",
|
||||
"payroll:write",
|
||||
"public",
|
||||
"reconciliation:read",
|
||||
"reconciliation:signoff",
|
||||
"reconciliation:write",
|
||||
"reports:read",
|
||||
"suppliers:read",
|
||||
"suppliers:write",
|
||||
"transactions:read",
|
||||
"transactions:write",
|
||||
"webhooks:manage",
|
||||
]
|
||||
`;
|
||||
@@ -0,0 +1,154 @@
|
||||
/**
|
||||
* Every v1 write runs inside the commit-actor scope.
|
||||
*
|
||||
* `commitEntry()` reads `getActor()` as its fallback and forwards it to the
|
||||
* commit_journal_entry RPC, which stamps `journal_entries.committed_actor_*`
|
||||
* and the audit_log COMMIT row. Before this, `runWithActor` had exactly one
|
||||
* production call site (the pending-operations commit), so anything reaching
|
||||
* the ledger by another route committed anonymously.
|
||||
*
|
||||
* Measured on production over 90 days: 99.8% of `storno` entries and 100% of
|
||||
* `correction` entries had no actor. Those are the two sanctioned rättelse
|
||||
* paths under BFL 5 kap. 5 §, which makes them the entries where "who did
|
||||
* this" is a legal question and the ones with the least attribution.
|
||||
*
|
||||
* The test asserts the scope is visible from INSIDE the handler, which is what
|
||||
* a helper several frames down (reverseEntry, correctEntry) actually sees.
|
||||
*/
|
||||
import { beforeAll, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import { NextResponse } from 'next/server'
|
||||
|
||||
beforeAll(() => {
|
||||
process.env.NEXT_PUBLIC_SUPABASE_URL ||= 'http://localhost:54321'
|
||||
process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY ||= 'test-anon-key'
|
||||
})
|
||||
|
||||
vi.mock('@/lib/auth/api-keys', async () => {
|
||||
const actual = await vi.importActual<typeof import('@/lib/auth/api-keys')>('@/lib/auth/api-keys')
|
||||
return { ...actual, validateApiKey: vi.fn(), createServiceClientNoCookies: vi.fn() }
|
||||
})
|
||||
|
||||
vi.mock('@supabase/supabase-js', async () => {
|
||||
const actual = await vi.importActual<typeof import('@supabase/supabase-js')>('@supabase/supabase-js')
|
||||
return { ...actual, createClient: vi.fn().mockReturnValue({}) }
|
||||
})
|
||||
|
||||
import { validateApiKey, createServiceClientNoCookies } from '@/lib/auth/api-keys'
|
||||
import { getActor } from '@/lib/bookkeeping/actor-context'
|
||||
import { withApiV1 } from '../with-api-v1'
|
||||
import { ok } from '../response'
|
||||
|
||||
const mockValidate = vi.mocked(validateApiKey)
|
||||
const mockServiceClient = vi.mocked(createServiceClientNoCookies)
|
||||
|
||||
const COMPANY = '11111111-1111-4111-8111-111111111111'
|
||||
|
||||
/**
|
||||
* `companies.list` is the authenticated static route the sibling suite uses.
|
||||
* The wrapper resolves the operation against the registry before it reaches
|
||||
* the handler, so an invented path 404s and the handler never runs.
|
||||
*/
|
||||
const OPERATION = 'companies.list'
|
||||
const URL_FOR = 'https://x.test/api/v1/companies'
|
||||
|
||||
/** Minimal flexible supabase double: every chain resolves to a membership row. */
|
||||
function makeSupabase() {
|
||||
const chain: unknown = new Proxy(
|
||||
{},
|
||||
{
|
||||
get(_t, prop) {
|
||||
if (prop === 'then') {
|
||||
return (resolve: (v: unknown) => void) =>
|
||||
resolve({ data: { company_id: COMPANY, role: 'owner' }, error: null })
|
||||
}
|
||||
return () => chain
|
||||
},
|
||||
},
|
||||
)
|
||||
return { from: () => chain, rpc: () => chain }
|
||||
}
|
||||
|
||||
function makeRequest(url: string, init?: RequestInit) {
|
||||
return new Request(url, {
|
||||
headers: { Authorization: 'Bearer gnubok_sk_live_x', ...(init?.headers ?? {}) },
|
||||
...init,
|
||||
}) as never
|
||||
}
|
||||
|
||||
/** Next.js 16 hands a static route `{ params: undefined }`. */
|
||||
function staticParams() {
|
||||
return { params: undefined } as never
|
||||
}
|
||||
|
||||
describe('v1 handlers run inside the commit-actor scope', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
mockServiceClient.mockReturnValue(makeSupabase() as never)
|
||||
mockValidate.mockResolvedValue({
|
||||
userId: 'user-1',
|
||||
companyId: COMPANY,
|
||||
scopes: ['companies:read'],
|
||||
apiKeyId: 'key-1',
|
||||
apiKeyName: 'DueCue automation stager',
|
||||
mode: 'live',
|
||||
} as Awaited<ReturnType<typeof validateApiKey>>)
|
||||
})
|
||||
|
||||
it('exposes an api_key actor to code running inside the handler', async () => {
|
||||
let seen: ReturnType<typeof getActor>
|
||||
const handler = withApiV1(OPERATION, async (_req, ctx) => {
|
||||
// This is what commitEntry() sees, several frames down.
|
||||
seen = getActor()
|
||||
return ok({ ok: true }, { requestId: ctx.requestId })
|
||||
})
|
||||
|
||||
await handler(makeRequest(URL_FOR), staticParams())
|
||||
|
||||
expect(seen).toBeDefined()
|
||||
expect(seen?.type).toBe('api_key')
|
||||
})
|
||||
|
||||
it('carries the key name through to the actor label', async () => {
|
||||
let seen: ReturnType<typeof getActor>
|
||||
const handler = withApiV1(OPERATION, async (_req, ctx) => {
|
||||
seen = getActor()
|
||||
return ok({ ok: true }, { requestId: ctx.requestId })
|
||||
})
|
||||
|
||||
await handler(makeRequest(URL_FOR), staticParams())
|
||||
|
||||
expect(seen?.label).toBe('DueCue automation stager')
|
||||
})
|
||||
|
||||
it('falls back to a stable label when the key is unnamed', async () => {
|
||||
mockValidate.mockResolvedValue({
|
||||
userId: 'user-1',
|
||||
companyId: COMPANY,
|
||||
scopes: ['companies:read'],
|
||||
apiKeyId: 'key-1',
|
||||
apiKeyName: undefined,
|
||||
mode: 'live',
|
||||
} as Awaited<ReturnType<typeof validateApiKey>>)
|
||||
|
||||
let seen: ReturnType<typeof getActor>
|
||||
const handler = withApiV1(OPERATION, async (_req, ctx) => {
|
||||
seen = getActor()
|
||||
return ok({ ok: true }, { requestId: ctx.requestId })
|
||||
})
|
||||
|
||||
await handler(makeRequest(URL_FOR), staticParams())
|
||||
|
||||
expect(seen?.label).toBe('Unnamed API key')
|
||||
})
|
||||
|
||||
it('leaves no actor bound after the request completes', async () => {
|
||||
// AsyncLocalStorage must not leak across requests: a later unattributed
|
||||
// path must stay unattributed rather than inherit the previous caller.
|
||||
const handler = withApiV1(OPERATION, async (_req, ctx) =>
|
||||
ok({ ok: true }, { requestId: ctx.requestId }),
|
||||
)
|
||||
await handler(makeRequest(URL_FOR), staticParams())
|
||||
|
||||
expect(getActor()).toBeUndefined()
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,58 @@
|
||||
import { describe, it, expect, afterEach, vi } from 'vitest'
|
||||
import { resolveDiscoveryBaseUrl } from '../base-url'
|
||||
|
||||
const CANONICAL = 'https://app.accounted.se'
|
||||
|
||||
function requestWithHost(host?: string) {
|
||||
return new Request('https://ignored.example/.well-known/oauth-authorization-server', {
|
||||
headers: host ? { host } : undefined,
|
||||
})
|
||||
}
|
||||
|
||||
describe('resolveDiscoveryBaseUrl', () => {
|
||||
afterEach(() => {
|
||||
vi.unstubAllEnvs()
|
||||
})
|
||||
|
||||
it('returns the canonical URL for the canonical host', () => {
|
||||
vi.stubEnv('NEXT_PUBLIC_APP_URL', CANONICAL)
|
||||
expect(resolveDiscoveryBaseUrl(requestWithHost('app.accounted.se'))).toBe(CANONICAL)
|
||||
})
|
||||
|
||||
it('reflects the legacy host so existing MCP connectors stay self-consistent', () => {
|
||||
vi.stubEnv('NEXT_PUBLIC_APP_URL', CANONICAL)
|
||||
expect(resolveDiscoveryBaseUrl(requestWithHost('app.gnubok.se'))).toBe(
|
||||
'https://app.gnubok.se',
|
||||
)
|
||||
})
|
||||
|
||||
it('falls back to canonical for a spoofed Host header', () => {
|
||||
vi.stubEnv('NEXT_PUBLIC_APP_URL', CANONICAL)
|
||||
expect(resolveDiscoveryBaseUrl(requestWithHost('evil.example'))).toBe(CANONICAL)
|
||||
})
|
||||
|
||||
it('falls back to canonical when the Host header is missing', () => {
|
||||
vi.stubEnv('NEXT_PUBLIC_APP_URL', CANONICAL)
|
||||
expect(resolveDiscoveryBaseUrl(requestWithHost(undefined))).toBe(CANONICAL)
|
||||
})
|
||||
|
||||
it('reflects localhost with its port for local development', () => {
|
||||
vi.stubEnv('NEXT_PUBLIC_APP_URL', CANONICAL)
|
||||
expect(resolveDiscoveryBaseUrl(requestWithHost('localhost:3000'))).toBe(
|
||||
'http://localhost:3000',
|
||||
)
|
||||
})
|
||||
|
||||
it('does not reflect hosts that merely start with localhost or 127.0.0.1', () => {
|
||||
vi.stubEnv('NEXT_PUBLIC_APP_URL', CANONICAL)
|
||||
expect(resolveDiscoveryBaseUrl(requestWithHost('localhost.evil.example'))).toBe(CANONICAL)
|
||||
expect(resolveDiscoveryBaseUrl(requestWithHost('127.0.0.1.evil.example'))).toBe(CANONICAL)
|
||||
})
|
||||
|
||||
it('is case-insensitive on the host comparison', () => {
|
||||
vi.stubEnv('NEXT_PUBLIC_APP_URL', CANONICAL)
|
||||
expect(resolveDiscoveryBaseUrl(requestWithHost('App.Gnubok.SE'))).toBe(
|
||||
'https://app.gnubok.se',
|
||||
)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,59 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { parseExpand } from '../expand'
|
||||
|
||||
const ALLOWED = ['customer', 'items', 'payments'] as const
|
||||
|
||||
const urlWith = (q: string): URL => new URL(`https://x.test/path${q}`)
|
||||
|
||||
describe('parseExpand', () => {
|
||||
it('returns an empty Set when no expand param is present', () => {
|
||||
const r = parseExpand(urlWith(''), ALLOWED)
|
||||
expect(r.ok).toBe(true)
|
||||
if (r.ok) expect(r.expand.size).toBe(0)
|
||||
})
|
||||
|
||||
it('parses a single key', () => {
|
||||
const r = parseExpand(urlWith('?expand=customer'), ALLOWED)
|
||||
expect(r.ok).toBe(true)
|
||||
if (r.ok) expect([...r.expand]).toEqual(['customer'])
|
||||
})
|
||||
|
||||
it('parses multiple comma-separated keys', () => {
|
||||
const r = parseExpand(urlWith('?expand=customer,items'), ALLOWED)
|
||||
expect(r.ok).toBe(true)
|
||||
if (r.ok) expect([...r.expand].sort()).toEqual(['customer', 'items'])
|
||||
})
|
||||
|
||||
it('trims whitespace around keys', () => {
|
||||
const r = parseExpand(urlWith('?expand=customer , items'), ALLOWED)
|
||||
expect(r.ok).toBe(true)
|
||||
if (r.ok) expect([...r.expand].sort()).toEqual(['customer', 'items'])
|
||||
})
|
||||
|
||||
it('collapses duplicates', () => {
|
||||
const r = parseExpand(urlWith('?expand=customer,customer'), ALLOWED)
|
||||
expect(r.ok).toBe(true)
|
||||
if (r.ok) expect(r.expand.size).toBe(1)
|
||||
})
|
||||
|
||||
it('rejects unknown keys with VALIDATION_ERROR-shaped result', () => {
|
||||
const r = parseExpand(urlWith('?expand=customer,bogus'), ALLOWED)
|
||||
expect(r.ok).toBe(false)
|
||||
if (!r.ok) {
|
||||
expect(r.invalidKeys).toEqual(['bogus'])
|
||||
expect(r.allowed).toEqual(['customer', 'items', 'payments'])
|
||||
}
|
||||
})
|
||||
|
||||
it('reports all invalid keys, not just the first', () => {
|
||||
const r = parseExpand(urlWith('?expand=foo,bar,customer'), ALLOWED)
|
||||
expect(r.ok).toBe(false)
|
||||
if (!r.ok) expect(r.invalidKeys.sort()).toEqual(['bar', 'foo'])
|
||||
})
|
||||
|
||||
it('ignores empty entries from trailing commas', () => {
|
||||
const r = parseExpand(urlWith('?expand=customer,'), ALLOWED)
|
||||
expect(r.ok).toBe(true)
|
||||
if (r.ok) expect([...r.expand]).toEqual(['customer'])
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,40 @@
|
||||
/**
|
||||
* Guards the v1 invoice projections against silently starving the render
|
||||
* path. getAmountToPay treats a missing column as "no deduction" / "default
|
||||
* rounding" (`deduction_total ?? 0`, `ore_rounding ?? company ?? true`), so a
|
||||
* projection that drops one of its inputs does not error: it renders a PDF
|
||||
* and a locked Swish QR (editmask 0) with the WRONG amount on that surface
|
||||
* only, while the dashboard PDF and the sent email for the same invoice show
|
||||
* the deducted "Att betala". That is the exact bug shipped on the v1 pdf
|
||||
* route when INVOICE_PDF_COLUMNS predated ROT/RUT and nothing pinned it.
|
||||
*/
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { INVOICE_FULL_COLUMNS, INVOICE_PDF_COLUMNS } from '@/lib/api/v1/invoice-columns'
|
||||
|
||||
/** Columns getAmountToPay + the Swish QR/totals path read off the invoice. */
|
||||
const AMOUNT_TO_PAY_COLUMNS = ['total', 'currency', 'ore_rounding', 'deduction_total', 'credited_invoice_id']
|
||||
|
||||
const parse = (projection: string): string[] => projection.split(',').map((c) => c.trim())
|
||||
|
||||
describe('v1 invoice projections feed the render amount path', () => {
|
||||
it.each(AMOUNT_TO_PAY_COLUMNS)('INVOICE_PDF_COLUMNS contains %s', (column) => {
|
||||
expect(parse(INVOICE_PDF_COLUMNS)).toContain(column)
|
||||
})
|
||||
|
||||
it.each(AMOUNT_TO_PAY_COLUMNS)('INVOICE_FULL_COLUMNS contains %s (v1 send renders from it)', (column) => {
|
||||
expect(parse(INVOICE_FULL_COLUMNS)).toContain(column)
|
||||
})
|
||||
|
||||
it('INVOICE_PDF_COLUMNS carries the display-safe personnummer for the PDF deduction box', () => {
|
||||
expect(parse(INVOICE_PDF_COLUMNS)).toContain('deduction_personnummer_last4')
|
||||
})
|
||||
|
||||
it('INVOICE_PDF_COLUMNS carries delivery_date (ML 17 kap 24 §: rendered when it differs from invoice_date)', () => {
|
||||
expect(parse(INVOICE_PDF_COLUMNS)).toContain('delivery_date')
|
||||
})
|
||||
|
||||
it('never selects the encrypted personnummer blob', () => {
|
||||
expect(INVOICE_FULL_COLUMNS).not.toContain('deduction_personnummer_encrypted')
|
||||
expect(INVOICE_PDF_COLUMNS).not.toContain('deduction_personnummer_encrypted')
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,110 @@
|
||||
import { describe, it, expect, afterEach, vi } from 'vitest'
|
||||
|
||||
/**
|
||||
* Drift guard for LEGACY_DISCOVERY_HOSTS (issue #1093).
|
||||
*
|
||||
* The constants below pin the configuration actually registered in
|
||||
* production: the canonical app host after the accounted.se cutover, and
|
||||
* the Skatteverket OAuth redirect_uri host registered in Utvecklarportalen
|
||||
* (pinned via NEXT_PUBLIC_SKV_OAUTH_BASE_URL on Vercel, kept on the legacy
|
||||
* domain because the registration is slow to change).
|
||||
*
|
||||
* If either registration changes, update these constants in the same PR
|
||||
* that changes LEGACY_DISCOVERY_HOSTS or the env pin. A red test here means
|
||||
* the discovery allowlist and the registered OAuth configuration disagree,
|
||||
* which in production surfaces as MCP clients re-authenticating against a
|
||||
* mismatched issuer and AGI/moms staging failing silently.
|
||||
*/
|
||||
const CANONICAL = 'https://app.accounted.se'
|
||||
const SKV_OAUTH_PIN = 'https://app.gnubok.se'
|
||||
|
||||
/**
|
||||
* CI does not set these env vars, so every test stubs them explicitly and
|
||||
* re-imports the module to be robust against env reads being hoisted to
|
||||
* module scope in a future refactor.
|
||||
*/
|
||||
async function loadValidator() {
|
||||
vi.resetModules()
|
||||
const mod = await import('../base-url')
|
||||
return mod.validateLegacyDiscoveryHosts
|
||||
}
|
||||
|
||||
describe('validateLegacyDiscoveryHosts', () => {
|
||||
afterEach(() => {
|
||||
vi.unstubAllEnvs()
|
||||
})
|
||||
|
||||
it('passes for the registered production configuration', async () => {
|
||||
vi.stubEnv('NEXT_PUBLIC_APP_URL', CANONICAL)
|
||||
vi.stubEnv('NEXT_PUBLIC_SKV_OAUTH_BASE_URL', SKV_OAUTH_PIN)
|
||||
const validate = await loadValidator()
|
||||
expect(validate()).toEqual([])
|
||||
})
|
||||
|
||||
it('reports an allowlisted host orphaned from the registered configuration', async () => {
|
||||
// Direction (b): with the SKV pin moved elsewhere and the canonical host
|
||||
// on accounted.se, nothing registered accounts for app.gnubok.se anymore,
|
||||
// so the validator must flag the allowlist entry instead of passing.
|
||||
vi.stubEnv('NEXT_PUBLIC_APP_URL', CANONICAL)
|
||||
vi.stubEnv('NEXT_PUBLIC_SKV_OAUTH_BASE_URL', 'https://oauth.elsewhere.example')
|
||||
const validate = await loadValidator()
|
||||
const violations = validate()
|
||||
expect(
|
||||
violations.some((v) => v.startsWith('LEGACY_DISCOVERY_HOSTS entry "app.gnubok.se"')),
|
||||
).toBe(true)
|
||||
})
|
||||
|
||||
it('reports a pinned SKV OAuth host that discovery would not reflect', async () => {
|
||||
// Direction (a): the registered callback host must be either the
|
||||
// canonical host or allowlisted, otherwise re-auth gets a wrong issuer.
|
||||
vi.stubEnv('NEXT_PUBLIC_APP_URL', CANONICAL)
|
||||
vi.stubEnv('NEXT_PUBLIC_SKV_OAUTH_BASE_URL', 'https://oauth.elsewhere.example')
|
||||
const validate = await loadValidator()
|
||||
const violations = validate()
|
||||
expect(
|
||||
violations.some((v) =>
|
||||
v.startsWith('NEXT_PUBLIC_SKV_OAUTH_BASE_URL host "oauth.elsewhere.example"'),
|
||||
),
|
||||
).toBe(true)
|
||||
})
|
||||
|
||||
it('accepts the SKV pin pointing at the canonical host', async () => {
|
||||
// If Utvecklarportalen is ever re-registered on the canonical domain and
|
||||
// the allowlist is trimmed in the same PR, the invariant holds; only the
|
||||
// orphaned app.gnubok.se entry is reported until the allowlist catches up.
|
||||
vi.stubEnv('NEXT_PUBLIC_APP_URL', CANONICAL)
|
||||
vi.stubEnv('NEXT_PUBLIC_SKV_OAUTH_BASE_URL', CANONICAL)
|
||||
const validate = await loadValidator()
|
||||
const violations = validate()
|
||||
expect(violations.some((v) => v.startsWith('NEXT_PUBLIC_SKV_OAUTH_BASE_URL host'))).toBe(
|
||||
false,
|
||||
)
|
||||
expect(
|
||||
violations.some((v) => v.startsWith('LEGACY_DISCOVERY_HOSTS entry "app.gnubok.se"')),
|
||||
).toBe(true)
|
||||
})
|
||||
|
||||
it('accepts a pre-cutover configuration where the canonical host is the legacy host', async () => {
|
||||
// Self-hosted or pre-cutover: NEXT_PUBLIC_APP_URL still on app.gnubok.se
|
||||
// and no SKV pin set. The canonical host accounts for the allowlist entry.
|
||||
vi.stubEnv('NEXT_PUBLIC_APP_URL', SKV_OAUTH_PIN)
|
||||
vi.stubEnv('NEXT_PUBLIC_SKV_OAUTH_BASE_URL', '')
|
||||
const validate = await loadValidator()
|
||||
expect(validate()).toEqual([])
|
||||
})
|
||||
|
||||
it('is case-insensitive and ignores a trailing slash on the pin URL', async () => {
|
||||
vi.stubEnv('NEXT_PUBLIC_APP_URL', CANONICAL)
|
||||
vi.stubEnv('NEXT_PUBLIC_SKV_OAUTH_BASE_URL', 'https://App.Gnubok.SE/')
|
||||
const validate = await loadValidator()
|
||||
expect(validate()).toEqual([])
|
||||
})
|
||||
|
||||
it('reports an unparseable NEXT_PUBLIC_SKV_OAUTH_BASE_URL instead of passing silently', async () => {
|
||||
vi.stubEnv('NEXT_PUBLIC_APP_URL', CANONICAL)
|
||||
vi.stubEnv('NEXT_PUBLIC_SKV_OAUTH_BASE_URL', 'not a url')
|
||||
const validate = await loadValidator()
|
||||
const violations = validate()
|
||||
expect(violations.some((v) => v.includes('not a parseable URL'))).toBe(true)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,100 @@
|
||||
/**
|
||||
* The registry's worked `example` must reach the OpenAPI spec.
|
||||
*
|
||||
* `EndpointDefinition.example` has always been required, and every endpoint
|
||||
* populates `example.response`, but `generateOpenApiSpec()` never emitted it.
|
||||
* The examples therefore reached only the docs markdown builder
|
||||
* (lib/docs/content/reference.ts); the spec carried none, so spec consumers
|
||||
* (skills/accounted-api, client generators, any agent reading
|
||||
* /api/v1/openapi.json) saw schemas without a single concrete body.
|
||||
*
|
||||
* A condensed schema states the shape of a field. An example states the
|
||||
* conventions the shape cannot express, which is the half agents get wrong.
|
||||
*/
|
||||
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { generateOpenApiSpec, listEndpoints } from '../registry'
|
||||
// Side-effect import: populates the ENDPOINTS registry from every route file.
|
||||
import '../load-routes'
|
||||
|
||||
type MediaType = { schema?: unknown; example?: unknown }
|
||||
type OperationObject = {
|
||||
requestBody?: { content: Record<string, MediaType> }
|
||||
responses: Record<string, { content?: Record<string, MediaType> }>
|
||||
}
|
||||
|
||||
const spec = generateOpenApiSpec('https://unit.test')
|
||||
|
||||
function operation(path: string, method: string): OperationObject {
|
||||
const op = (spec.paths[path] as Record<string, OperationObject> | undefined)?.[method]
|
||||
expect(op, `${method.toUpperCase()} ${path} missing from spec`).toBeDefined()
|
||||
return op as OperationObject
|
||||
}
|
||||
|
||||
describe('generateOpenApiSpec examples', () => {
|
||||
it('attaches the registry response example to the JSON success media type', () => {
|
||||
const op = operation('/api/v1/companies/{companyId}/customers', 'post')
|
||||
const example = op.responses['200']?.content?.['application/json']?.example as
|
||||
| { data?: unknown }
|
||||
| undefined
|
||||
expect(example).toBeDefined()
|
||||
expect(example).toHaveProperty('data')
|
||||
})
|
||||
|
||||
it('attaches the registry request example to the JSON request body', () => {
|
||||
const op = operation('/api/v1/companies/{companyId}/customers', 'post')
|
||||
const example = op.requestBody?.content['application/json']?.example as
|
||||
| Record<string, unknown>
|
||||
| undefined
|
||||
expect(example).toBeDefined()
|
||||
expect(example).toHaveProperty('name')
|
||||
})
|
||||
|
||||
it('emits a response example on every JSON success response', () => {
|
||||
const missing: string[] = []
|
||||
for (const [path, item] of Object.entries(spec.paths)) {
|
||||
for (const [method, op] of Object.entries(item as Record<string, OperationObject>)) {
|
||||
const json = op.responses['200']?.content?.['application/json']
|
||||
// 204 endpoints and binary (application/pdf) responses carry no JSON body.
|
||||
if (!json) continue
|
||||
if (json.example === undefined) missing.push(`${method.toUpperCase()} ${path}`)
|
||||
}
|
||||
}
|
||||
expect(missing).toEqual([])
|
||||
})
|
||||
|
||||
it('emits a request example on every JSON request body', () => {
|
||||
// `example.request` is optional on EndpointDefinition, but a registered
|
||||
// JSON body with no worked example is the gap this test exists to hold
|
||||
// shut: an agent reading the spec would get a shape and no conventions.
|
||||
const missing: string[] = []
|
||||
for (const [path, item] of Object.entries(spec.paths)) {
|
||||
for (const [method, op] of Object.entries(item as Record<string, OperationObject>)) {
|
||||
const json = op.requestBody?.content['application/json']
|
||||
if (!json) continue
|
||||
if (json.example === undefined) missing.push(`${method.toUpperCase()} ${path}`)
|
||||
}
|
||||
}
|
||||
expect(missing).toEqual([])
|
||||
})
|
||||
|
||||
it('does not attach a JSON example to a binary response', () => {
|
||||
// A PDF endpoint's registry example describes the JSON envelope it does
|
||||
// not send; attaching it to the binary media type would be a lie.
|
||||
for (const [path, item] of Object.entries(spec.paths)) {
|
||||
for (const [method, op] of Object.entries(item as Record<string, OperationObject>)) {
|
||||
for (const [contentType, media] of Object.entries(op.responses['200']?.content ?? {})) {
|
||||
if (contentType === 'application/json') continue
|
||||
expect(media.example, `${method.toUpperCase()} ${path} ${contentType}`).toBeUndefined()
|
||||
}
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
it('keeps every registered endpoint carrying a response example in the registry', () => {
|
||||
const missing = listEndpoints()
|
||||
.filter((def) => !def.example?.response)
|
||||
.map((def) => def.operation)
|
||||
expect(missing).toEqual([])
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,91 @@
|
||||
/**
|
||||
* The OpenAPI generator emits machine-readable request contracts:
|
||||
* path `parameters` derived from the route pattern and `requestBody` from
|
||||
* the registered Zod body schema. Historically the spec only carried
|
||||
* response schemas + prose, which forced spec consumers (agent skills,
|
||||
* client generators) to guess request shapes.
|
||||
*/
|
||||
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { generateOpenApiSpec } from '../registry'
|
||||
// Side-effect import: populates the ENDPOINTS registry from every route file.
|
||||
import '../load-routes'
|
||||
|
||||
type OperationObject = {
|
||||
parameters?: Array<{ name: string; in: string; required: boolean; schema: unknown }>
|
||||
requestBody?: {
|
||||
required: boolean
|
||||
content: Record<string, { schema: { properties?: Record<string, unknown>; required?: string[] } }>
|
||||
}
|
||||
}
|
||||
|
||||
const spec = generateOpenApiSpec('https://unit.test')
|
||||
|
||||
function operation(path: string, method: string): OperationObject {
|
||||
const op = (spec.paths[path] as Record<string, OperationObject> | undefined)?.[method]
|
||||
expect(op, `${method.toUpperCase()} ${path} missing from spec`).toBeDefined()
|
||||
return op as OperationObject
|
||||
}
|
||||
|
||||
describe('generateOpenApiSpec request contracts', () => {
|
||||
it('declares a path parameter for every templated segment, on every operation', () => {
|
||||
for (const [path, item] of Object.entries(spec.paths)) {
|
||||
const templated = [...path.matchAll(/\{([^}]+)\}/g)].map((m) => m[1])
|
||||
for (const [method, op] of Object.entries(item as Record<string, OperationObject>)) {
|
||||
const declared = (op.parameters ?? []).filter((p) => p.in === 'path').map((p) => p.name)
|
||||
expect(declared.sort(), `${method.toUpperCase()} ${path}`).toEqual([...templated].sort())
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
it('emits requestBody from the registered Zod body schema', () => {
|
||||
const op = operation('/api/v1/companies/{companyId}/invoices', 'post')
|
||||
expect(op.requestBody?.required).toBe(true)
|
||||
const schema = op.requestBody?.content['application/json']?.schema
|
||||
expect(schema?.properties).toHaveProperty('customer_id')
|
||||
expect(schema?.properties).toHaveProperty('items')
|
||||
expect(schema?.required).toContain('customer_id')
|
||||
})
|
||||
|
||||
it('renders a z.preprocess field by its output schema and keeps it optional', () => {
|
||||
// CreateSupplierSchema wraps email and default_expense_account in a
|
||||
// preprocess pipe (empty string means absent). The callable sits on the
|
||||
// pipe's input side, so describing the input would yield a required
|
||||
// untyped field; the spec must show the output schema and not require it.
|
||||
const op = operation('/api/v1/companies/{companyId}/suppliers', 'post')
|
||||
const schema = op.requestBody?.content['application/json']?.schema
|
||||
expect(schema?.properties?.email).toEqual({ type: 'string' })
|
||||
expect(schema?.properties?.default_expense_account).toEqual({ type: 'string' })
|
||||
expect(schema?.required).toContain('name')
|
||||
expect(schema?.required).not.toContain('email')
|
||||
expect(schema?.required).not.toContain('default_expense_account')
|
||||
})
|
||||
|
||||
it('renders multipart z.unknown() parts as binary file parts', () => {
|
||||
const op = operation('/api/v1/companies/{companyId}/documents', 'post')
|
||||
const schema = op.requestBody?.content['multipart/form-data']?.schema
|
||||
expect(schema?.properties?.file).toEqual({ type: 'string', format: 'binary' })
|
||||
// Non-file parts keep their real schema.
|
||||
expect(schema?.properties?.journal_entry_id).toMatchObject({ type: 'string' })
|
||||
})
|
||||
|
||||
it('omits requestBody on endpoints without a registered body', () => {
|
||||
expect(operation('/api/v1/companies', 'get').requestBody).toBeUndefined()
|
||||
})
|
||||
|
||||
it('converts wrapped Zod constructs (.default, z.record) instead of degrading to {}', () => {
|
||||
const op = operation('/api/v1/companies/{companyId}/journal-entries', 'post')
|
||||
const schema = op.requestBody?.content['application/json']?.schema as {
|
||||
properties: Record<string, { type?: string; enum?: unknown[]; items?: { properties: Record<string, { type?: string; additionalProperties?: unknown }> } }>
|
||||
required?: string[]
|
||||
}
|
||||
// JournalEntrySourceTypeSchema.default('manual'): enum survives, field not required.
|
||||
expect(schema.properties.source_type.enum).toContain('manual')
|
||||
expect(schema.required).not.toContain('source_type')
|
||||
const line = schema.properties.lines.items!.properties
|
||||
// nonNegativeAmount.default(0) is a number, and z.record renders as an
|
||||
// object with additionalProperties rather than an empty schema.
|
||||
expect(line.debit_amount.type).toBe('number')
|
||||
expect(line.dimensions.additionalProperties).toBeTruthy()
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,171 @@
|
||||
import { randomUUID } from 'node:crypto'
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { getPool } from '@/tests/pg/setup'
|
||||
import { seedCompany } from '@/tests/pg/fixtures'
|
||||
|
||||
type OperationStatus = 'queued' | 'running' | 'succeeded' | 'failed' | 'cancelled'
|
||||
|
||||
async function insertOperation(params: {
|
||||
companyId: string
|
||||
userId: string
|
||||
status: OperationStatus
|
||||
result?: Record<string, unknown> | null
|
||||
error?: Record<string, unknown> | null
|
||||
}): Promise<string> {
|
||||
const id = randomUUID()
|
||||
const isTerminal =
|
||||
params.status === 'succeeded' ||
|
||||
params.status === 'failed' ||
|
||||
params.status === 'cancelled'
|
||||
await getPool().query(
|
||||
`INSERT INTO public.operations
|
||||
(id, company_id, user_id, operation_type, status, started_at, completed_at, result, error)
|
||||
VALUES ($1, $2, $3, 'test.op', $4, now(), $5, $6, $7)`,
|
||||
[
|
||||
id,
|
||||
params.companyId,
|
||||
params.userId,
|
||||
params.status,
|
||||
isTerminal ? new Date() : null,
|
||||
params.result ? JSON.stringify(params.result) : null,
|
||||
params.error ? JSON.stringify(params.error) : null,
|
||||
],
|
||||
)
|
||||
return id
|
||||
}
|
||||
|
||||
describe('operations-immutability.pg: terminal-status rows are immutable', () => {
|
||||
// Sanity: the regular running → succeeded transition (the path used by
|
||||
// completeOperation in lib/api/v1/operations.ts) is NOT blocked. The
|
||||
// trigger reads OLD.status; the legitimate UPDATE has OLD.status='running'
|
||||
// which is non-terminal, so the RAISE is skipped.
|
||||
it('allows UPDATE that transitions running → succeeded', async () => {
|
||||
const { userId, companyId } = await seedCompany()
|
||||
const opId = await insertOperation({ companyId, userId, status: 'running' })
|
||||
|
||||
await expect(
|
||||
getPool().query(
|
||||
`UPDATE public.operations
|
||||
SET status = 'succeeded',
|
||||
completed_at = now(),
|
||||
result = '{"ok": true}'::jsonb
|
||||
WHERE id = $1`,
|
||||
[opId],
|
||||
),
|
||||
).resolves.toMatchObject({ rowCount: 1 })
|
||||
})
|
||||
|
||||
it('allows UPDATE that transitions queued → running', async () => {
|
||||
const { userId, companyId } = await seedCompany()
|
||||
const opId = await insertOperation({ companyId, userId, status: 'queued' })
|
||||
|
||||
await expect(
|
||||
getPool().query(
|
||||
`UPDATE public.operations
|
||||
SET status = 'running', started_at = now()
|
||||
WHERE id = $1`,
|
||||
[opId],
|
||||
),
|
||||
).resolves.toMatchObject({ rowCount: 1 })
|
||||
})
|
||||
|
||||
it('rejects UPDATE of result on a succeeded row', async () => {
|
||||
const { userId, companyId } = await seedCompany()
|
||||
const opId = await insertOperation({
|
||||
companyId,
|
||||
userId,
|
||||
status: 'succeeded',
|
||||
result: { ok: true },
|
||||
})
|
||||
|
||||
await expect(
|
||||
getPool().query(
|
||||
`UPDATE public.operations SET result = '{"tampered": true}'::jsonb WHERE id = $1`,
|
||||
[opId],
|
||||
),
|
||||
).rejects.toThrow(/terminal status \(succeeded\) is immutable/i)
|
||||
})
|
||||
|
||||
it('rejects UPDATE of status on a failed row (no failed → running reopen)', async () => {
|
||||
const { userId, companyId } = await seedCompany()
|
||||
const opId = await insertOperation({
|
||||
companyId,
|
||||
userId,
|
||||
status: 'failed',
|
||||
error: { code: 'X' },
|
||||
})
|
||||
|
||||
await expect(
|
||||
getPool().query(
|
||||
`UPDATE public.operations SET status = 'running' WHERE id = $1`,
|
||||
[opId],
|
||||
),
|
||||
).rejects.toThrow(/terminal status \(failed\) is immutable/i)
|
||||
})
|
||||
|
||||
it('rejects UPDATE of error on a cancelled row', async () => {
|
||||
const { userId, companyId } = await seedCompany()
|
||||
const opId = await insertOperation({ companyId, userId, status: 'cancelled' })
|
||||
|
||||
await expect(
|
||||
getPool().query(
|
||||
`UPDATE public.operations SET error = '{"code": "REWRITTEN"}'::jsonb WHERE id = $1`,
|
||||
[opId],
|
||||
),
|
||||
).rejects.toThrow(/terminal status \(cancelled\) is immutable/i)
|
||||
})
|
||||
|
||||
it('rejects DELETE on a succeeded row', async () => {
|
||||
const { userId, companyId } = await seedCompany()
|
||||
const opId = await insertOperation({
|
||||
companyId,
|
||||
userId,
|
||||
status: 'succeeded',
|
||||
result: { ok: true },
|
||||
})
|
||||
|
||||
await expect(
|
||||
getPool().query(`DELETE FROM public.operations WHERE id = $1`, [opId]),
|
||||
).rejects.toThrow(/terminal status \(succeeded\) cannot be deleted/i)
|
||||
})
|
||||
|
||||
it('rejects DELETE on a failed row', async () => {
|
||||
const { userId, companyId } = await seedCompany()
|
||||
const opId = await insertOperation({
|
||||
companyId,
|
||||
userId,
|
||||
status: 'failed',
|
||||
error: { code: 'X' },
|
||||
})
|
||||
|
||||
await expect(
|
||||
getPool().query(`DELETE FROM public.operations WHERE id = $1`, [opId]),
|
||||
).rejects.toThrow(/terminal status \(failed\) cannot be deleted/i)
|
||||
})
|
||||
|
||||
// Non-terminal rows remain deletable so operators can clear stuck/queued
|
||||
// entries (e.g. a worker that crashed before claiming the row, manual
|
||||
// cleanup of dev/test environments). The retention obligation kicks in
|
||||
// only once the row has recorded a terminal outcome.
|
||||
it('allows DELETE on a queued row', async () => {
|
||||
const { userId, companyId } = await seedCompany()
|
||||
const opId = await insertOperation({ companyId, userId, status: 'queued' })
|
||||
|
||||
const result = await getPool().query(
|
||||
`DELETE FROM public.operations WHERE id = $1`,
|
||||
[opId],
|
||||
)
|
||||
expect(result.rowCount).toBe(1)
|
||||
})
|
||||
|
||||
it('allows DELETE on a running row', async () => {
|
||||
const { userId, companyId } = await seedCompany()
|
||||
const opId = await insertOperation({ companyId, userId, status: 'running' })
|
||||
|
||||
const result = await getPool().query(
|
||||
`DELETE FROM public.operations WHERE id = $1`,
|
||||
[opId],
|
||||
)
|
||||
expect(result.rowCount).toBe(1)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,132 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import {
|
||||
DEFAULT_LIMIT,
|
||||
MAX_LIMIT,
|
||||
decodeDefaultCursor,
|
||||
encodeDefaultCursor,
|
||||
nextCursorFromPage,
|
||||
parsePaginationParams,
|
||||
} from '../pagination'
|
||||
|
||||
describe('parsePaginationParams', () => {
|
||||
it('returns defaults when no params present', () => {
|
||||
const url = new URL('https://example.com/v1/x')
|
||||
expect(parsePaginationParams(url)).toEqual({ limit: DEFAULT_LIMIT, cursor: null })
|
||||
})
|
||||
|
||||
it('parses limit and clamps to MAX_LIMIT', () => {
|
||||
const url = new URL('https://example.com/v1/x?limit=999')
|
||||
expect(parsePaginationParams(url).limit).toBe(MAX_LIMIT)
|
||||
})
|
||||
|
||||
it('floors limit to default for non-numeric input', () => {
|
||||
const url = new URL('https://example.com/v1/x?limit=abc')
|
||||
expect(parsePaginationParams(url).limit).toBe(DEFAULT_LIMIT)
|
||||
})
|
||||
|
||||
it('treats limit=0 as invalid → DEFAULT_LIMIT', () => {
|
||||
const url = new URL('https://example.com/v1/x?limit=0')
|
||||
expect(parsePaginationParams(url).limit).toBe(DEFAULT_LIMIT)
|
||||
})
|
||||
|
||||
it('returns the cursor verbatim when supplied', () => {
|
||||
const url = new URL('https://example.com/v1/x?cursor=abc123')
|
||||
expect(parsePaginationParams(url).cursor).toBe('abc123')
|
||||
})
|
||||
})
|
||||
|
||||
describe('default cursor encode/decode', () => {
|
||||
it('round-trips a row', () => {
|
||||
const row = { id: '8fd5b1f4-1234-1234-1234-1234567890ab', created_at: '2026-05-12T16:00:00Z' }
|
||||
const cur = encodeDefaultCursor(row)
|
||||
expect(cur).not.toBeNull()
|
||||
expect(decodeDefaultCursor(cur)).toEqual({ ts: row.created_at, id: row.id })
|
||||
})
|
||||
|
||||
it('returns null for null input', () => {
|
||||
expect(encodeDefaultCursor(null)).toBeNull()
|
||||
})
|
||||
|
||||
it('returns null when decoding a malformed cursor', () => {
|
||||
expect(decodeDefaultCursor('not-base64-or-json')).toBeNull()
|
||||
expect(decodeDefaultCursor('')).toBeNull()
|
||||
expect(decodeDefaultCursor(null)).toBeNull()
|
||||
})
|
||||
|
||||
it('returns null when decoding a JSON object missing fields', () => {
|
||||
const cursor = Buffer.from(JSON.stringify({ foo: 'bar' })).toString('base64url')
|
||||
expect(decodeDefaultCursor(cursor)).toBeNull()
|
||||
})
|
||||
})
|
||||
|
||||
describe('nextCursorFromPage', () => {
|
||||
const ID_A = '11111111-1111-1111-1111-111111111111'
|
||||
const ID_B = '22222222-2222-2222-2222-222222222222'
|
||||
const ID_C = '33333333-3333-3333-3333-333333333333'
|
||||
const row = (id: string, ts: string) => ({ id, created_at: ts })
|
||||
|
||||
it('returns null when the page is not full', () => {
|
||||
const rows = [
|
||||
row(ID_A, '2026-01-01T00:00:00Z'),
|
||||
row(ID_B, '2026-01-02T00:00:00Z'),
|
||||
]
|
||||
expect(nextCursorFromPage(rows, 5)).toBeNull()
|
||||
})
|
||||
|
||||
it('returns a cursor when there are more rows than the limit', () => {
|
||||
const rows = [
|
||||
row(ID_A, '2026-01-01T00:00:00Z'),
|
||||
row(ID_B, '2026-01-02T00:00:00Z'),
|
||||
row(ID_C, '2026-01-03T00:00:00Z'),
|
||||
]
|
||||
const cursor = nextCursorFromPage(rows, 2)
|
||||
expect(cursor).not.toBeNull()
|
||||
// The cursor is the LAST row of the trimmed page (rows[limit - 1]), never
|
||||
// rows[limit]: routes paginate with strictly-greater/less predicates, so
|
||||
// encoding the first row of the next page would skip it at the boundary.
|
||||
expect(decodeDefaultCursor(cursor)).toEqual({ ts: '2026-01-02T00:00:00Z', id: ID_B })
|
||||
})
|
||||
|
||||
it('with limit=1 the cursor is the single returned row, so the next page starts at row 2', () => {
|
||||
const rows = [
|
||||
row(ID_A, '2026-01-01T00:00:00Z'),
|
||||
row(ID_B, '2026-01-02T00:00:00Z'),
|
||||
]
|
||||
const cursor = nextCursorFromPage(rows, 1)
|
||||
expect(decodeDefaultCursor(cursor)).toEqual({ ts: '2026-01-01T00:00:00Z', id: ID_A })
|
||||
})
|
||||
})
|
||||
|
||||
describe('decodeDefaultCursor: strict format validation', () => {
|
||||
const validId = '8fd5b1f4-1234-1234-1234-1234567890ab'
|
||||
const validTs = '2026-05-12T16:00:00Z'
|
||||
|
||||
const cursorFor = (payload: object): string =>
|
||||
Buffer.from(JSON.stringify(payload)).toString('base64url')
|
||||
|
||||
it('rejects a cursor whose ts is a date-only string', () => {
|
||||
const cur = cursorFor({ ts: '2026-05-12', id: validId })
|
||||
expect(decodeDefaultCursor(cur)).toBeNull()
|
||||
})
|
||||
|
||||
it('rejects a cursor whose id is not a UUID', () => {
|
||||
const cur = cursorFor({ ts: validTs, id: 'not-a-uuid' })
|
||||
expect(decodeDefaultCursor(cur)).toBeNull()
|
||||
})
|
||||
|
||||
it('rejects a cursor with a SQL-injection-shaped ts value', () => {
|
||||
const cur = cursorFor({ ts: "'); drop table api_keys; --", id: validId })
|
||||
expect(decodeDefaultCursor(cur)).toBeNull()
|
||||
})
|
||||
|
||||
it('accepts a well-formed cursor', () => {
|
||||
const cur = cursorFor({ ts: validTs, id: validId })
|
||||
expect(decodeDefaultCursor(cur)).toEqual({ ts: validTs, id: validId })
|
||||
})
|
||||
|
||||
it('accepts ts with timezone offset and fractional seconds', () => {
|
||||
const ts = '2026-05-12T16:00:00.123+02:00'
|
||||
const cur = cursorFor({ ts, id: validId })
|
||||
expect(decodeDefaultCursor(cur)).toEqual({ ts, id: validId })
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,131 @@
|
||||
/**
|
||||
* Response-envelope contract test.
|
||||
*
|
||||
* Every v1 handler returns the canonical `{ data, meta }` envelope: `ok()` and
|
||||
* `created()` wrap a single object, `paginated()` wraps an array, both stamping
|
||||
* the shared `meta` block (see `lib/api/v1/response.ts`). The OpenAPI generator,
|
||||
* however, derives each endpoint's documented body purely from its registered
|
||||
* `response.success` Zod schema, and that schema is NOT validated at runtime:
|
||||
* so nothing stops a route from declaring a shape the handler never sends.
|
||||
*
|
||||
* That is exactly what issue #794 found: every list endpoint declared a bare
|
||||
* `{ <name>: [...] }` object that no handler emits. #802 fixed the list
|
||||
* endpoints (via `listEnvelope`/`dataEnvelope`); the same drift was latent on
|
||||
* the single-resource and write endpoints, which declared the bare resource
|
||||
* schema instead of `{ data, meta }`.
|
||||
*
|
||||
* This test is the regression guard the issue asked for. It asserts EVERY
|
||||
* JSON-returning endpoint declares the `{ data, meta }` envelope with the shared
|
||||
* `ResponseMetaSchema`: so a new endpoint that forgets to wrap its schema
|
||||
* (list OR single) fails CI here instead of shipping a lying spec. Binary
|
||||
* downloads (`response.contentType`) and 204 No Content endpoints
|
||||
* (`NoBodyResponse`) carry no JSON body and are the only exemptions.
|
||||
*/
|
||||
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { z } from 'zod'
|
||||
import { listEndpoints, ResponseMetaSchema, NoBodyResponse, listEnvelope, dataEnvelope } from '../registry'
|
||||
// Side-effect import: every route file's registerEndpoint() runs at module
|
||||
// load time and populates the shared ENDPOINTS map.
|
||||
import '../load-routes'
|
||||
|
||||
/** Binary downloads (PDF, SIE text) declare a non-JSON contentType. */
|
||||
function isBinary(success: { contentType?: string }): boolean {
|
||||
return !!success.contentType && success.contentType !== 'application/json'
|
||||
}
|
||||
|
||||
describe('v1 response envelope contract', () => {
|
||||
const endpoints = listEndpoints()
|
||||
|
||||
it('every JSON endpoint declares the { data, meta } envelope with the shared meta schema', () => {
|
||||
// Accumulate every violation so a failing run names ALL offending endpoints
|
||||
// at once (a fresh route that forgets to wrap, plus any that drift later),
|
||||
// instead of failing one-at-a-time across many edit cycles.
|
||||
const violations: string[] = []
|
||||
|
||||
for (const ep of endpoints) {
|
||||
const ctx = `${ep.method} ${ep.path} (${ep.operation})`
|
||||
|
||||
// Exemptions: binary bodies and 204-no-content have no JSON envelope.
|
||||
if (isBinary(ep.response)) continue
|
||||
if (ep.response.success === NoBodyResponse) continue
|
||||
|
||||
const success = ep.response.success
|
||||
if (!(success instanceof z.ZodObject)) {
|
||||
violations.push(`${ctx}: response.success is not a { data, meta } object: wrap it with listEnvelope()/dataEnvelope() (or use NoBodyResponse for 204 / response.contentType for binary).`)
|
||||
continue
|
||||
}
|
||||
|
||||
const shape = (success as z.ZodObject<z.ZodRawShape>).shape
|
||||
const keys = Object.keys(shape).sort()
|
||||
if (keys.length !== 2 || keys[0] !== 'data' || keys[1] !== 'meta') {
|
||||
violations.push(`${ctx}: top-level keys must be [data, meta]: found [${keys.join(', ')}]. The handler returns { data, meta }; declare it with listEnvelope()/dataEnvelope().`)
|
||||
continue
|
||||
}
|
||||
|
||||
// Reference equality: both envelope helpers wire in this exact schema, so
|
||||
// a hand-rolled `{ data, meta: z.object({...}) }` that drifts from the
|
||||
// real meta block is rejected too.
|
||||
if (shape.meta !== ResponseMetaSchema) {
|
||||
violations.push(`${ctx}: meta is not the shared ResponseMetaSchema (use listEnvelope()/dataEnvelope(), don't hand-roll the envelope).`)
|
||||
}
|
||||
}
|
||||
|
||||
expect(
|
||||
violations,
|
||||
`\n${violations.length} v1 endpoint(s) declare a response.success that doesn't match the { data, meta } envelope the handler actually returns:\n\n${violations.map((v) => ` • ${v}`).join('\n')}\n`,
|
||||
).toEqual([])
|
||||
})
|
||||
|
||||
it('list endpoints expose data as an array (the paginated() envelope)', () => {
|
||||
// Detect list endpoints structurally: their `data` is a Zod array. This is
|
||||
// the half of the contract that maps onto paginated() specifically: guards
|
||||
// against a list endpoint drifting from `{ data: [...] }` back to a bare
|
||||
// `{ <name>: [...] }` (which would drop the array out of `data` entirely).
|
||||
const arrayDataEndpoints = endpoints.filter((ep) => {
|
||||
const s = ep.response.success
|
||||
return s instanceof z.ZodObject && (s as z.ZodObject<z.ZodRawShape>).shape.data instanceof z.ZodArray
|
||||
})
|
||||
|
||||
// The 10 cursor-paginated list endpoints (companies, customers, suppliers,
|
||||
// invoices, supplier-invoices, journal-entries, transactions, employees,
|
||||
// salary-runs, webhook deliveries). accounts/fiscal-periods/webhooks nest
|
||||
// their array under a named key inside `data`, so they use dataEnvelope and
|
||||
// are intentionally NOT counted here. A drop below this floor means a
|
||||
// paginated endpoint silently lost its `data: [...]` shape.
|
||||
expect(
|
||||
arrayDataEndpoints.length,
|
||||
`expected the known paginated list endpoints to keep data: z.array(...); found only ${arrayDataEndpoints.length}`,
|
||||
).toBeGreaterThanOrEqual(10)
|
||||
|
||||
for (const ep of arrayDataEndpoints) {
|
||||
const shape = (ep.response.success as z.ZodObject<z.ZodRawShape>).shape
|
||||
expect(
|
||||
shape.meta === ResponseMetaSchema,
|
||||
`${ep.method} ${ep.path}: list envelope meta must be the shared ResponseMetaSchema`,
|
||||
).toBe(true)
|
||||
}
|
||||
})
|
||||
|
||||
it('listEnvelope() and dataEnvelope() produce the canonical { data, meta } shape', () => {
|
||||
const list = listEnvelope(z.object({ id: z.string() }))
|
||||
expect(list instanceof z.ZodObject).toBe(true)
|
||||
expect(Object.keys(list.shape).sort()).toEqual(['data', 'meta'])
|
||||
expect(list.shape.data instanceof z.ZodArray).toBe(true)
|
||||
expect(list.shape.meta === ResponseMetaSchema).toBe(true)
|
||||
|
||||
const data = dataEnvelope(z.object({ id: z.string() }))
|
||||
expect(data instanceof z.ZodObject).toBe(true)
|
||||
expect(Object.keys(data.shape).sort()).toEqual(['data', 'meta'])
|
||||
expect(data.shape.data instanceof z.ZodObject).toBe(true)
|
||||
expect(data.shape.meta === ResponseMetaSchema).toBe(true)
|
||||
})
|
||||
|
||||
it('the shared meta schema carries request_id + api_version', () => {
|
||||
// The envelope helpers are only correct if meta itself is well-formed.
|
||||
expect(ResponseMetaSchema instanceof z.ZodObject).toBe(true)
|
||||
const metaKeys = Object.keys(ResponseMetaSchema.shape)
|
||||
expect(metaKeys).toContain('request_id')
|
||||
expect(metaKeys).toContain('api_version')
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,86 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { accepted, created, noContent, ok, paginated } from '../response'
|
||||
import { API_V1_VERSION, API_V1_VERSION_HEADER } from '../version'
|
||||
|
||||
describe('v1 response helpers', () => {
|
||||
const requestId = 'req_abc'
|
||||
|
||||
it('ok() wraps data with meta and stamps standard headers', async () => {
|
||||
const res = ok({ hello: 'world' }, { requestId })
|
||||
expect(res.status).toBe(200)
|
||||
expect(res.headers.get('X-Request-Id')).toBe(requestId)
|
||||
expect(res.headers.get(API_V1_VERSION_HEADER)).toBe(API_V1_VERSION)
|
||||
const body = await res.json()
|
||||
expect(body).toEqual({
|
||||
data: { hello: 'world' },
|
||||
meta: { request_id: requestId, api_version: API_V1_VERSION },
|
||||
})
|
||||
})
|
||||
|
||||
it('paginated() includes next_cursor when provided', async () => {
|
||||
const res = paginated([{ id: 1 }], { requestId, nextCursor: 'cur_xyz' })
|
||||
const body = await res.json()
|
||||
expect(body.meta.next_cursor).toBe('cur_xyz')
|
||||
expect(body.data).toEqual([{ id: 1 }])
|
||||
})
|
||||
|
||||
it('paginated() omits next_cursor when not provided', async () => {
|
||||
const res = paginated([], { requestId })
|
||||
const body = await res.json()
|
||||
expect(body.meta.next_cursor).toBeUndefined()
|
||||
})
|
||||
|
||||
it('created() returns 201', () => {
|
||||
const res = created({}, { requestId })
|
||||
expect(res.status).toBe(201)
|
||||
})
|
||||
|
||||
it('accepted() returns 202 with operation_id + poll_url', async () => {
|
||||
const res = accepted('op_123', 'import.sie', { requestId })
|
||||
expect(res.status).toBe(202)
|
||||
const body = await res.json()
|
||||
expect(body.data).toEqual({
|
||||
operation_id: 'op_123',
|
||||
type: 'import.sie',
|
||||
status: 'queued',
|
||||
poll_url: '/api/v1/operations/op_123',
|
||||
webhook_event: 'operation.completed',
|
||||
})
|
||||
})
|
||||
|
||||
it('noContent() returns 204 with no body', async () => {
|
||||
const res = noContent({ requestId })
|
||||
expect(res.status).toBe(204)
|
||||
expect(res.headers.get('X-Request-Id')).toBe(requestId)
|
||||
})
|
||||
|
||||
it('stamps Idempotent-Replayed when set', () => {
|
||||
const res = ok({}, { requestId, idempotentReplay: true })
|
||||
expect(res.headers.get('Idempotent-Replayed')).toBe('true')
|
||||
})
|
||||
|
||||
it('stamps X-Dry-Run when set', () => {
|
||||
const res = ok({}, { requestId, dryRun: true })
|
||||
expect(res.headers.get('X-Dry-Run')).toBe('true')
|
||||
})
|
||||
|
||||
it('stamps rate-limit headers when supplied', () => {
|
||||
const reset = new Date(1_700_000_000_000)
|
||||
const res = ok({}, { requestId, rateLimit: { limit: 100, remaining: 42, resetAt: reset } })
|
||||
expect(res.headers.get('X-RateLimit-Limit')).toBe('100')
|
||||
expect(res.headers.get('X-RateLimit-Remaining')).toBe('42')
|
||||
expect(res.headers.get('X-RateLimit-Reset')).toBe(String(Math.floor(reset.getTime() / 1000)))
|
||||
})
|
||||
|
||||
it('includes audit block in meta for write responses', async () => {
|
||||
const res = ok({}, {
|
||||
requestId,
|
||||
audit: { voucher_number: 'A2026-0042', immutable_at: '2026-05-12T16:00:00Z' },
|
||||
})
|
||||
const body = await res.json()
|
||||
expect(body.meta.audit).toEqual({
|
||||
voucher_number: 'A2026-0042',
|
||||
immutable_at: '2026-05-12T16:00:00Z',
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,118 @@
|
||||
/**
|
||||
* Scope-map / registry parity guard.
|
||||
*
|
||||
* `withApiV1` resolves the required scope for a request from
|
||||
* `V1_ENDPOINT_SCOPES` (lib/auth/scopes.ts), NOT from the endpoint registry,
|
||||
* and answers NOT_FOUND when the map has no entry, before it even validates
|
||||
* the bearer token. So a route that registers itself but forgets the map
|
||||
* entry is live in the OpenAPI spec and the generated agent skill yet 404s
|
||||
* for every caller. That is exactly what happened to
|
||||
* POST .../inbox-items/{id}/stamp.
|
||||
*
|
||||
* This test pins the two sources to each other in both directions, checks
|
||||
* that every pattern points at a route file that exists, and that every v1
|
||||
* route file is imported by load-routes.ts (otherwise it is invisible to
|
||||
* this test and to the spec).
|
||||
*/
|
||||
|
||||
import { existsSync, readdirSync, readFileSync, statSync } from 'node:fs'
|
||||
import { join } from 'node:path'
|
||||
import { fileURLToPath } from 'node:url'
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { V1_ENDPOINT_SCOPES, V1_PUBLIC_ENDPOINTS } from '@/lib/auth/scopes'
|
||||
import { listEndpoints } from '../registry'
|
||||
// Side-effect import: populates the ENDPOINTS registry from every route file.
|
||||
import '../load-routes'
|
||||
|
||||
const REPO_ROOT = fileURLToPath(new URL('../../../../', import.meta.url))
|
||||
const V1_APP_DIR = join(REPO_ROOT, 'app', 'api', 'v1')
|
||||
|
||||
/**
|
||||
* Public endpoints that legitimately have no registry entry. The OpenAPI
|
||||
* document is generated FROM the registry, so it cannot register itself.
|
||||
*/
|
||||
const PUBLIC_WITHOUT_REGISTRY_ENTRY = new Set<string>(['GET /api/v1/openapi.json'])
|
||||
|
||||
/**
|
||||
* Route files under app/api/v1 that are not part of the registry. Same
|
||||
* exception as above, in file form.
|
||||
*/
|
||||
const ROUTE_FILES_WITHOUT_REGISTRY_ENTRY = new Set<string>(['app/api/v1/openapi.json/route.ts'])
|
||||
|
||||
function endpointKey(e: { method: string; path: string }): string {
|
||||
return `${e.method} ${e.path}`
|
||||
}
|
||||
|
||||
/** `POST /api/v1/companies/:companyId/x/:id` to `app/api/v1/companies/[companyId]/x/[id]/route.ts`. */
|
||||
function routeFileFor(pattern: string): string {
|
||||
const path = pattern.split(' ', 2)[1]
|
||||
return join('app', path.replace(/:([^/]+)/g, '[$1]'), 'route.ts')
|
||||
}
|
||||
|
||||
function walkRouteFiles(dir: string): string[] {
|
||||
const out: string[] = []
|
||||
for (const name of readdirSync(dir)) {
|
||||
if (name === '__tests__') continue
|
||||
const full = join(dir, name)
|
||||
if (statSync(full).isDirectory()) out.push(...walkRouteFiles(full))
|
||||
else if (name === 'route.ts') out.push(full)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
const registered = listEndpoints()
|
||||
const registeredByKey = new Map(registered.map((e) => [endpointKey(e), e]))
|
||||
|
||||
describe('V1_ENDPOINT_SCOPES <-> endpoint registry parity', () => {
|
||||
it('has a scope-map entry, with the same scope, for every registered non-public endpoint', () => {
|
||||
const problems = registered
|
||||
.filter((e) => e.scope !== null)
|
||||
.flatMap((e) => {
|
||||
const key = endpointKey(e)
|
||||
const mapped = V1_ENDPOINT_SCOPES[key]
|
||||
if (mapped === undefined) return [`${key}: registered with scope ${e.scope} but missing from V1_ENDPOINT_SCOPES (the wrapper answers 404)`]
|
||||
if (mapped !== e.scope) return [`${key}: registry says ${e.scope}, V1_ENDPOINT_SCOPES says ${mapped}`]
|
||||
return []
|
||||
})
|
||||
expect(problems).toEqual([])
|
||||
})
|
||||
|
||||
it('lists every registered public (scope: null) endpoint in V1_PUBLIC_ENDPOINTS', () => {
|
||||
const problems = registered
|
||||
.filter((e) => e.scope === null)
|
||||
.map(endpointKey)
|
||||
.filter((key) => !V1_PUBLIC_ENDPOINTS.includes(key))
|
||||
expect(problems).toEqual([])
|
||||
})
|
||||
|
||||
it('has a registered endpoint behind every V1_ENDPOINT_SCOPES entry', () => {
|
||||
const phantoms = Object.keys(V1_ENDPOINT_SCOPES).filter((key) => !registeredByKey.has(key))
|
||||
expect(phantoms).toEqual([])
|
||||
})
|
||||
|
||||
it('has a registered public endpoint (or a documented exception) behind every V1_PUBLIC_ENDPOINTS entry', () => {
|
||||
const problems = V1_PUBLIC_ENDPOINTS.flatMap((key) => {
|
||||
if (PUBLIC_WITHOUT_REGISTRY_ENTRY.has(key)) return []
|
||||
const def = registeredByKey.get(key)
|
||||
if (!def) return [`${key}: in V1_PUBLIC_ENDPOINTS but not registered`]
|
||||
if (def.scope !== null) return [`${key}: in V1_PUBLIC_ENDPOINTS but registered with scope ${def.scope}`]
|
||||
return []
|
||||
})
|
||||
expect(problems).toEqual([])
|
||||
})
|
||||
|
||||
it('points every scope-map and public pattern at a route file that exists', () => {
|
||||
const patterns = [...Object.keys(V1_ENDPOINT_SCOPES), ...V1_PUBLIC_ENDPOINTS]
|
||||
const missing = patterns.filter((key) => !existsSync(join(REPO_ROOT, routeFileFor(key))))
|
||||
expect(missing).toEqual([])
|
||||
})
|
||||
|
||||
it('imports every app/api/v1 route file from load-routes.ts', () => {
|
||||
const loader = readFileSync(join(REPO_ROOT, 'lib', 'api', 'v1', 'load-routes.ts'), 'utf8')
|
||||
const notLoaded = walkRouteFiles(V1_APP_DIR)
|
||||
.map((full) => full.slice(REPO_ROOT.length).replace(/^\/+/, ''))
|
||||
.filter((rel) => !ROUTE_FILES_WITHOUT_REGISTRY_ENTRY.has(rel))
|
||||
.filter((rel) => !loader.includes(`'@/${rel.replace(/\.ts$/, '')}'`))
|
||||
expect(notLoaded).toEqual([])
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,80 @@
|
||||
/**
|
||||
* Spec-snapshot test.
|
||||
*
|
||||
* Locks down the high-level shape of the v1 endpoint registry so an
|
||||
* unintentional Zod-schema change can't ship a silent API break. CI fails
|
||||
* if any of the following invariants drift unexpectedly:
|
||||
*
|
||||
* - Endpoint count
|
||||
* - Endpoint key set (method + path tuples)
|
||||
* - Set of distinct scopes referenced across all endpoints
|
||||
*
|
||||
* When you intentionally add or remove an endpoint, run the test once
|
||||
* locally with `--update` to refresh the snapshot, review the diff, and
|
||||
* commit the new snapshot alongside the route change. The diff itself
|
||||
* becomes a self-describing API changelog entry.
|
||||
*
|
||||
* Why this lives here and not in tests/: the snapshot must be loaded
|
||||
* relative to a path the load-routes side-effect import resolves from.
|
||||
* Co-locating with the registry keeps the dependency cycle minimal.
|
||||
*/
|
||||
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { listEndpoints } from '../registry'
|
||||
// Side-effect import: every route file's registerEndpoint() runs at
|
||||
// module load time and populates the shared ENDPOINTS map.
|
||||
import '../load-routes'
|
||||
|
||||
describe('v1 spec snapshot', () => {
|
||||
const endpoints = listEndpoints()
|
||||
|
||||
it('matches the recorded endpoint count', () => {
|
||||
// Update intentionally when adding/removing endpoints. The count is
|
||||
// the cheapest first-line check: if it changes unexpectedly, CI
|
||||
// surfaces the surprise before reviewers have to spot it in the diff.
|
||||
expect(endpoints.length).toMatchSnapshot('endpoint-count')
|
||||
})
|
||||
|
||||
it('matches the recorded endpoint key set', () => {
|
||||
const keys = endpoints
|
||||
.map((e) => `${e.method} ${e.path}`)
|
||||
.sort()
|
||||
expect(keys).toMatchSnapshot('endpoint-keys')
|
||||
})
|
||||
|
||||
it('matches the recorded scope catalogue', () => {
|
||||
const scopes = Array.from(
|
||||
new Set(endpoints.map((e) => e.scope ?? 'public')),
|
||||
).sort()
|
||||
expect(scopes).toMatchSnapshot('endpoint-scopes')
|
||||
})
|
||||
|
||||
it('every endpoint has the agent-facing metadata that the docs depend on', () => {
|
||||
// The /docs/api/reference pages and /llms-full.txt aggregator both
|
||||
// assume every endpoint registers complete metadata. A registerEndpoint
|
||||
// call that omits any of these fields would render a page with empty
|
||||
// sections: surface the omission here instead.
|
||||
for (const ep of endpoints) {
|
||||
const ctx = `${ep.method} ${ep.path}`
|
||||
expect(ep.summary, `${ctx}: missing summary`).toBeTruthy()
|
||||
expect(ep.description, `${ctx}: missing description`).toBeTruthy()
|
||||
expect(ep.useWhen, `${ctx}: missing useWhen`).toBeTruthy()
|
||||
expect(ep.doNotUseFor, `${ctx}: missing doNotUseFor`).toBeTruthy()
|
||||
expect(Array.isArray(ep.pitfalls), `${ctx}: pitfalls must be an array`).toBe(true)
|
||||
expect(ep.example, `${ctx}: missing example`).toBeTruthy()
|
||||
expect(ep.example.response, `${ctx}: example.response is required`).toBeTruthy()
|
||||
|
||||
// Defense-in-depth: every endpoint MUST explicitly declare its
|
||||
// scope (or the literal sentinel `null` for genuinely public
|
||||
// endpoints: e.g. /api/v1/health). `undefined` means the
|
||||
// registerEndpoint call silently dropped the field, which would
|
||||
// make the wrapper treat the route as unauthenticated. CC6.3:
|
||||
// surfacing the omission in CI prevents accidental public
|
||||
// exposure of new endpoints.
|
||||
expect(
|
||||
ep.scope !== undefined,
|
||||
`${ctx}: scope must be explicitly declared (use null for genuinely public endpoints)`,
|
||||
).toBe(true)
|
||||
}
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,506 @@
|
||||
/**
|
||||
* Regression suite for the documented v1 "preview, then commit" flow.
|
||||
*
|
||||
* The contract in `lib/api/v1/dry-run.ts` tells integrators to commit by
|
||||
* re-issuing the SAME request without `dry_run=true`, carrying the SAME
|
||||
* `Idempotency-Key`. That made the preview and the commit indistinguishable to
|
||||
* the idempotency layer (same method, same path, same body): the preview was
|
||||
* cached under the commit's hash and the commit replayed it. 200 OK, header
|
||||
* `Idempotent-Replayed: true`, `{ dry_run: true, preview }` in the body, and
|
||||
* nothing written. An agent reading the status code reported success.
|
||||
*
|
||||
* These tests exercise the wrapper against an in-memory stand-in for the
|
||||
* `idempotency_keys` table, because the bug only appears when a real store
|
||||
* carries state from one request to the next: a per-call `vi.fn()` that always
|
||||
* returns null can never reproduce it.
|
||||
*
|
||||
* Mocking follows `tests/helpers.ts` conventions, but the v1 surface never
|
||||
* touches `@/lib/supabase/server`: it is API-key authenticated and runs on
|
||||
* `createServiceClientNoCookies()` from `@/lib/auth/api-keys`, so that is what
|
||||
* is stubbed here (same as `with-api-v1.test.ts`).
|
||||
*/
|
||||
import { beforeAll, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import { z } from 'zod'
|
||||
|
||||
beforeAll(() => {
|
||||
// The wrapper's public-scope path fails closed without these; stubbed only
|
||||
// to clear the guard (no Supabase instance is contacted).
|
||||
process.env.NEXT_PUBLIC_SUPABASE_URL ||= 'http://localhost:54321'
|
||||
process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY ||= 'test-anon-key'
|
||||
})
|
||||
|
||||
vi.mock('@/lib/auth/api-keys', async () => {
|
||||
const actual = await vi.importActual<typeof import('@/lib/auth/api-keys')>('@/lib/auth/api-keys')
|
||||
return {
|
||||
...actual,
|
||||
validateApiKey: vi.fn(),
|
||||
createServiceClientNoCookies: vi.fn(),
|
||||
}
|
||||
})
|
||||
|
||||
vi.mock('@supabase/supabase-js', async () => {
|
||||
const actual = await vi.importActual<typeof import('@supabase/supabase-js')>('@supabase/supabase-js')
|
||||
return {
|
||||
...actual,
|
||||
createClient: vi.fn().mockReturnValue({}),
|
||||
}
|
||||
})
|
||||
|
||||
vi.mock('@/lib/api/idempotency', async () => {
|
||||
const actual = await vi.importActual<typeof import('@/lib/api/idempotency')>(
|
||||
'@/lib/api/idempotency',
|
||||
)
|
||||
return {
|
||||
...actual,
|
||||
checkIdempotencyKey: vi.fn(),
|
||||
storeIdempotencyResponse: vi.fn(),
|
||||
}
|
||||
})
|
||||
|
||||
import { createServiceClientNoCookies, validateApiKey } from '@/lib/auth/api-keys'
|
||||
import {
|
||||
checkIdempotencyKey,
|
||||
IdempotencyKeyReuseError,
|
||||
storeIdempotencyResponse,
|
||||
} from '@/lib/api/idempotency'
|
||||
import { withApiV1 } from '../with-api-v1'
|
||||
import { dryRunPreview } from '../dry-run'
|
||||
import { v1ErrorResponseFromCode } from '../errors'
|
||||
import { created } from '../response'
|
||||
import { registerEndpoint } from '../registry'
|
||||
|
||||
const mockValidate = validateApiKey as ReturnType<typeof vi.fn>
|
||||
const mockServiceClient = createServiceClientNoCookies as ReturnType<typeof vi.fn>
|
||||
const mockCheckIdempotency = checkIdempotencyKey as ReturnType<typeof vi.fn>
|
||||
const mockStoreIdempotency = storeIdempotencyResponse as ReturnType<typeof vi.fn>
|
||||
|
||||
const COMPANY_ID = 'company-1'
|
||||
const USER_ID = 'user-1'
|
||||
const INVOICES_URL = `https://x.test/api/v1/companies/${COMPANY_ID}/invoices`
|
||||
const REQUEST_BODY = { customer_id: 'cust-1', amount: 1250 }
|
||||
|
||||
// The wrapper reads `dryRunSupported` off the registry when a TEST key writes.
|
||||
// Registering the pattern here lets the forced-dry-run path run instead of
|
||||
// short-circuiting to TEST_KEY_WRITE_BLOCKED. Vitest isolates module state per
|
||||
// test file, so this registration is invisible to the rest of the suite.
|
||||
registerEndpoint({
|
||||
operation: 'invoices.create',
|
||||
method: 'POST',
|
||||
path: '/api/v1/companies/:companyId/invoices',
|
||||
summary: 'Create an invoice (test fixture).',
|
||||
description: 'Fixture registration used by the dry-run idempotency tests.',
|
||||
useWhen: 'never: test fixture',
|
||||
doNotUseFor: 'anything outside this test file',
|
||||
pitfalls: [],
|
||||
example: { response: {} },
|
||||
scope: 'invoices:write',
|
||||
risk: 'medium',
|
||||
idempotent: false,
|
||||
reversible: true,
|
||||
dryRunSupported: true,
|
||||
response: { success: z.object({}) },
|
||||
})
|
||||
|
||||
function makeSupabaseStub(membership: { company_id: string; role: string } | null) {
|
||||
return {
|
||||
from: vi.fn().mockReturnValue({
|
||||
select: vi.fn().mockReturnValue({
|
||||
eq: vi.fn().mockReturnValue({
|
||||
eq: vi.fn().mockReturnValue({
|
||||
maybeSingle: vi.fn().mockResolvedValue({ data: membership, error: null }),
|
||||
}),
|
||||
}),
|
||||
}),
|
||||
}),
|
||||
}
|
||||
}
|
||||
|
||||
function keyAuth(mode: 'live' | 'test') {
|
||||
return {
|
||||
userId: USER_ID,
|
||||
companyId: COMPANY_ID,
|
||||
apiKeyId: mode === 'test' ? 'ak_test' : 'ak_live',
|
||||
apiKeyName: `${mode} key`,
|
||||
scopes: ['invoices:write'],
|
||||
mode,
|
||||
}
|
||||
}
|
||||
|
||||
interface StoredRow {
|
||||
requestHash: string
|
||||
status: 'success' | 'error'
|
||||
body: Record<string, unknown>
|
||||
}
|
||||
|
||||
/**
|
||||
* In-memory stand-in for the `idempotency_keys` table. Reproduces the three
|
||||
* behaviours the wrapper depends on:
|
||||
* - rows are scoped by (user_id, company_id, key)
|
||||
* - a stored row whose request_hash differs raises IdempotencyKeyReuseError
|
||||
* - insert is first-writer-wins (the unique index swallows the loser)
|
||||
*/
|
||||
function installIdempotencyTable(): Map<string, StoredRow> {
|
||||
const rows = new Map<string, StoredRow>()
|
||||
const rowKey = (userId: string, companyId: string, key: string) =>
|
||||
`${userId}::${companyId}::${key}`
|
||||
|
||||
mockCheckIdempotency.mockImplementation(
|
||||
async (
|
||||
_supabase: unknown,
|
||||
userId: string,
|
||||
companyId: string,
|
||||
key: string,
|
||||
requestHash: string,
|
||||
) => {
|
||||
const row = rows.get(rowKey(userId, companyId, key))
|
||||
if (!row) return null
|
||||
if (row.requestHash !== requestHash) throw new IdempotencyKeyReuseError(key)
|
||||
return { status: row.status, body: row.body }
|
||||
},
|
||||
)
|
||||
|
||||
mockStoreIdempotency.mockImplementation(
|
||||
async (
|
||||
_supabase: unknown,
|
||||
userId: string,
|
||||
companyId: string,
|
||||
key: string,
|
||||
requestHash: string,
|
||||
status: 'success' | 'error',
|
||||
body: Record<string, unknown>,
|
||||
) => {
|
||||
const k = rowKey(userId, companyId, key)
|
||||
if (rows.has(k)) return
|
||||
rows.set(k, { requestHash, status, body })
|
||||
},
|
||||
)
|
||||
|
||||
return rows
|
||||
}
|
||||
|
||||
/**
|
||||
* A write route shaped like the real ones: previews when `ctx.dryRun`, and
|
||||
* otherwise performs the side-effect. `committed` is the observable proof that
|
||||
* the write actually happened, which is the whole point of this suite.
|
||||
*/
|
||||
function makeInvoiceRoute() {
|
||||
const committed: string[] = []
|
||||
const previews: string[] = []
|
||||
let seq = 0
|
||||
|
||||
const route = withApiV1<{ params: Promise<{ companyId: string }> }>(
|
||||
'invoices.create',
|
||||
async (request, ctx) => {
|
||||
const body = (await request.json()) as { customer_id: string }
|
||||
if (ctx.dryRun) {
|
||||
previews.push(body.customer_id)
|
||||
return dryRunPreview(
|
||||
{ customer_id: body.customer_id },
|
||||
{ requestId: ctx.requestId, log: ctx.log },
|
||||
)
|
||||
}
|
||||
seq += 1
|
||||
const id = `inv-${seq}`
|
||||
committed.push(id)
|
||||
return created({ id, customer_id: body.customer_id }, { requestId: ctx.requestId })
|
||||
},
|
||||
{ requireScope: 'invoices:write' },
|
||||
)
|
||||
|
||||
return { route, committed, previews }
|
||||
}
|
||||
|
||||
function companyParams(companyId: string) {
|
||||
return { params: Promise.resolve({ companyId }) }
|
||||
}
|
||||
|
||||
function postInvoice(opts: {
|
||||
key?: string
|
||||
dryRunQuery?: boolean
|
||||
/** Raw value for the ?dry_run= query param (case-sensitivity matrix). */
|
||||
dryRunQueryValue?: string
|
||||
dryRunHeader?: boolean
|
||||
}): Request {
|
||||
const headers: Record<string, string> = {
|
||||
Authorization: 'Bearer gnubok_sk_x',
|
||||
'Content-Type': 'application/json',
|
||||
}
|
||||
if (opts.key) headers['Idempotency-Key'] = opts.key
|
||||
if (opts.dryRunHeader) headers['X-Dry-Run'] = 'true'
|
||||
const url =
|
||||
opts.dryRunQueryValue !== undefined
|
||||
? `${INVOICES_URL}?dry_run=${opts.dryRunQueryValue}`
|
||||
: opts.dryRunQuery
|
||||
? `${INVOICES_URL}?dry_run=true`
|
||||
: INVOICES_URL
|
||||
return new Request(url, {
|
||||
method: 'POST',
|
||||
headers,
|
||||
body: JSON.stringify(REQUEST_BODY),
|
||||
})
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
mockServiceClient.mockReturnValue(makeSupabaseStub({ company_id: COMPANY_ID, role: 'owner' }))
|
||||
mockValidate.mockResolvedValue(keyAuth('live'))
|
||||
installIdempotencyTable()
|
||||
})
|
||||
|
||||
describe('withApiV1: dry-run then commit on the same Idempotency-Key', () => {
|
||||
// THE missing test. Before the fix this returned the cached preview with
|
||||
// Idempotent-Replayed: true and `committed` stayed empty.
|
||||
it('commits for real after a dry-run preview issued under the same key', async () => {
|
||||
const { route, committed, previews } = makeInvoiceRoute()
|
||||
|
||||
const preview = await route(
|
||||
postInvoice({ key: 'key-1', dryRunQuery: true }),
|
||||
companyParams(COMPANY_ID),
|
||||
)
|
||||
expect(preview.status).toBe(200)
|
||||
expect(preview.headers.get('X-Dry-Run')).toBe('true')
|
||||
expect(preview.headers.get('Idempotent-Replayed')).toBeNull()
|
||||
const previewBody = await preview.json()
|
||||
expect(previewBody.data.dry_run).toBe(true)
|
||||
expect(previews).toEqual(['cust-1'])
|
||||
expect(committed).toEqual([])
|
||||
|
||||
const commit = await route(postInvoice({ key: 'key-1' }), companyParams(COMPANY_ID))
|
||||
|
||||
expect(commit.status).toBe(201)
|
||||
expect(commit.headers.get('Idempotent-Replayed')).toBeNull()
|
||||
const commitBody = await commit.json()
|
||||
expect(commitBody.data.id).toBe('inv-1')
|
||||
expect(commitBody.data.dry_run).toBeUndefined()
|
||||
expect(committed).toEqual(['inv-1'])
|
||||
})
|
||||
|
||||
it('never writes the dry-run response into the idempotency cache', async () => {
|
||||
const { route } = makeInvoiceRoute()
|
||||
|
||||
await route(postInvoice({ key: 'key-2', dryRunQuery: true }), companyParams(COMPANY_ID))
|
||||
|
||||
expect(mockStoreIdempotency).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('does not replay a repeated dry-run: each preview re-runs the handler', async () => {
|
||||
const { route, committed, previews } = makeInvoiceRoute()
|
||||
|
||||
const first = await route(
|
||||
postInvoice({ key: 'key-3', dryRunQuery: true }),
|
||||
companyParams(COMPANY_ID),
|
||||
)
|
||||
const second = await route(
|
||||
postInvoice({ key: 'key-3', dryRunQuery: true }),
|
||||
companyParams(COMPANY_ID),
|
||||
)
|
||||
|
||||
expect(first.headers.get('Idempotent-Replayed')).toBeNull()
|
||||
expect(second.headers.get('Idempotent-Replayed')).toBeNull()
|
||||
expect(second.status).toBe(200)
|
||||
expect((await second.json()).data.dry_run).toBe(true)
|
||||
expect(previews).toHaveLength(2)
|
||||
expect(committed).toEqual([])
|
||||
})
|
||||
|
||||
// The dry-run flag is part of the request hash, so a key that already
|
||||
// committed for real cannot be re-used for a simulation: that would hand back
|
||||
// a committed result wearing a preview's clothes. 409 is the honest answer.
|
||||
it('rejects a dry-run that re-uses a key which already committed', async () => {
|
||||
const { route, committed } = makeInvoiceRoute()
|
||||
|
||||
await route(postInvoice({ key: 'key-4' }), companyParams(COMPANY_ID))
|
||||
expect(committed).toEqual(['inv-1'])
|
||||
|
||||
const res = await route(
|
||||
postInvoice({ key: 'key-4', dryRunQuery: true }),
|
||||
companyParams(COMPANY_ID),
|
||||
)
|
||||
|
||||
expect(res.status).toBe(409)
|
||||
const body = await res.json()
|
||||
expect(body.error.code).toBe('IDEMPOTENCY_KEY_REUSE')
|
||||
expect(committed).toEqual(['inv-1'])
|
||||
})
|
||||
})
|
||||
|
||||
describe('withApiV1: idempotent replay of real commits (must not regress)', () => {
|
||||
// Also the lockstep guard for the two hashRequest call sites: the lookup only
|
||||
// finds what the store wrote if both hash the same input. Diverge them and
|
||||
// this test fails with a second write instead of a replay.
|
||||
it('replays the second of two identical commits under the same key', async () => {
|
||||
const { route, committed } = makeInvoiceRoute()
|
||||
|
||||
const first = await route(postInvoice({ key: 'key-5' }), companyParams(COMPANY_ID))
|
||||
const second = await route(postInvoice({ key: 'key-5' }), companyParams(COMPANY_ID))
|
||||
|
||||
expect(first.status).toBe(201)
|
||||
expect(first.headers.get('Idempotent-Replayed')).toBeNull()
|
||||
expect(second.headers.get('Idempotent-Replayed')).toBe('true')
|
||||
expect((await second.json()).data.id).toBe('inv-1')
|
||||
expect(committed).toEqual(['inv-1'])
|
||||
})
|
||||
|
||||
// A handler-level 429 (e.g. bank-connections.sync's cooldown) says "not
|
||||
// now". Caching it would replay the throttle under the same key until the
|
||||
// cache TTL, long after the cooldown itself has passed, and as a 400.
|
||||
it('never caches a 429 so a same-key retry after Retry-After runs the handler', async () => {
|
||||
let calls = 0
|
||||
const route = withApiV1<{ params: Promise<{ companyId: string }> }>(
|
||||
'invoices.create',
|
||||
async (_request, ctx) => {
|
||||
calls += 1
|
||||
if (calls === 1) {
|
||||
return v1ErrorResponseFromCode('RATE_LIMITED', ctx.log, {
|
||||
requestId: ctx.requestId,
|
||||
retryAfterSeconds: 1,
|
||||
})
|
||||
}
|
||||
return created({ id: 'inv-after-cooldown' }, { requestId: ctx.requestId })
|
||||
},
|
||||
{ requireScope: 'invoices:write' },
|
||||
)
|
||||
|
||||
const first = await route(postInvoice({ key: 'key-7' }), companyParams(COMPANY_ID))
|
||||
expect(first.status).toBe(429)
|
||||
expect(mockStoreIdempotency).not.toHaveBeenCalled()
|
||||
|
||||
const second = await route(postInvoice({ key: 'key-7' }), companyParams(COMPANY_ID))
|
||||
expect(second.status).toBe(201)
|
||||
// The real commit is cached as before; only the throttle was not.
|
||||
expect(mockStoreIdempotency).toHaveBeenCalledTimes(1)
|
||||
expect(second.headers.get('Idempotent-Replayed')).toBeNull()
|
||||
expect((await second.json()).data.id).toBe('inv-after-cooldown')
|
||||
expect(calls).toBe(2)
|
||||
})
|
||||
|
||||
it('still rejects the same key carrying a different body', async () => {
|
||||
const { route, committed } = makeInvoiceRoute()
|
||||
|
||||
await route(postInvoice({ key: 'key-6' }), companyParams(COMPANY_ID))
|
||||
|
||||
const changed = new Request(INVOICES_URL, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
Authorization: 'Bearer gnubok_sk_x',
|
||||
'Content-Type': 'application/json',
|
||||
'Idempotency-Key': 'key-6',
|
||||
},
|
||||
body: JSON.stringify({ ...REQUEST_BODY, amount: 9999 }),
|
||||
})
|
||||
const res = await route(changed, companyParams(COMPANY_ID))
|
||||
|
||||
expect(res.status).toBe(409)
|
||||
expect((await res.json()).error.code).toBe('IDEMPOTENCY_KEY_REUSE')
|
||||
expect(committed).toEqual(['inv-1'])
|
||||
})
|
||||
})
|
||||
|
||||
describe('withApiV1: dry-run query flag is case-insensitive', () => {
|
||||
// '?dry_run=True' used to fall through the exact-match check and COMMIT for
|
||||
// real while the caller believed it previewed: the one direction this flag
|
||||
// must never fail in.
|
||||
it('previews on ?dry_run=True (mis-cased flag must never commit)', async () => {
|
||||
const { route, committed, previews } = makeInvoiceRoute()
|
||||
|
||||
const res = await route(
|
||||
postInvoice({ key: 'key-10', dryRunQueryValue: 'True' }),
|
||||
companyParams(COMPANY_ID),
|
||||
)
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
expect((await res.json()).data.dry_run).toBe(true)
|
||||
expect(previews).toHaveLength(1)
|
||||
expect(committed).toEqual([])
|
||||
expect(mockStoreIdempotency).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('previews on ?dry_run=TRUE as well', async () => {
|
||||
const { route, committed } = makeInvoiceRoute()
|
||||
|
||||
const res = await route(
|
||||
postInvoice({ key: 'key-11', dryRunQueryValue: 'TRUE' }),
|
||||
companyParams(COMPANY_ID),
|
||||
)
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
expect((await res.json()).data.dry_run).toBe(true)
|
||||
expect(committed).toEqual([])
|
||||
})
|
||||
|
||||
it('still commits on non-true values (?dry_run=1, ?dry_run=false)', async () => {
|
||||
const { route, committed, previews } = makeInvoiceRoute()
|
||||
|
||||
const one = await route(
|
||||
postInvoice({ key: 'key-12', dryRunQueryValue: '1' }),
|
||||
companyParams(COMPANY_ID),
|
||||
)
|
||||
const falsy = await route(
|
||||
postInvoice({ key: 'key-13', dryRunQueryValue: 'false' }),
|
||||
companyParams(COMPANY_ID),
|
||||
)
|
||||
|
||||
expect(one.status).toBe(201)
|
||||
expect(falsy.status).toBe(201)
|
||||
expect(previews).toHaveLength(0)
|
||||
expect(committed).toEqual(['inv-1', 'inv-2'])
|
||||
})
|
||||
})
|
||||
|
||||
describe('withApiV1: X-Dry-Run header parity with ?dry_run=true', () => {
|
||||
it('previews on the header and still commits on the follow-up request', async () => {
|
||||
const { route, committed, previews } = makeInvoiceRoute()
|
||||
|
||||
const preview = await route(
|
||||
postInvoice({ key: 'key-7', dryRunHeader: true }),
|
||||
companyParams(COMPANY_ID),
|
||||
)
|
||||
expect(preview.status).toBe(200)
|
||||
expect((await preview.json()).data.dry_run).toBe(true)
|
||||
expect(previews).toHaveLength(1)
|
||||
expect(committed).toEqual([])
|
||||
expect(mockStoreIdempotency).not.toHaveBeenCalled()
|
||||
|
||||
const commit = await route(postInvoice({ key: 'key-7' }), companyParams(COMPANY_ID))
|
||||
|
||||
expect(commit.status).toBe(201)
|
||||
expect(commit.headers.get('Idempotent-Replayed')).toBeNull()
|
||||
expect((await commit.json()).data.id).toBe('inv-1')
|
||||
expect(committed).toEqual(['inv-1'])
|
||||
})
|
||||
|
||||
it('does not replay a repeated header-driven dry-run', async () => {
|
||||
const { route, previews } = makeInvoiceRoute()
|
||||
|
||||
await route(postInvoice({ key: 'key-8', dryRunHeader: true }), companyParams(COMPANY_ID))
|
||||
const second = await route(
|
||||
postInvoice({ key: 'key-8', dryRunHeader: true }),
|
||||
companyParams(COMPANY_ID),
|
||||
)
|
||||
|
||||
expect(second.headers.get('Idempotent-Replayed')).toBeNull()
|
||||
expect(previews).toHaveLength(2)
|
||||
})
|
||||
})
|
||||
|
||||
describe('withApiV1: test keys (forced dry-run) never poison the cache', () => {
|
||||
it('lets a live commit through on a key a test key already simulated', async () => {
|
||||
const { route, committed, previews } = makeInvoiceRoute()
|
||||
|
||||
mockValidate.mockResolvedValueOnce(keyAuth('test'))
|
||||
const simulated = await route(postInvoice({ key: 'key-9' }), companyParams(COMPANY_ID))
|
||||
|
||||
expect(simulated.status).toBe(200)
|
||||
expect(simulated.headers.get('X-Gnubok-Mode')).toBe('test')
|
||||
expect((await simulated.json()).data.dry_run).toBe(true)
|
||||
expect(previews).toHaveLength(1)
|
||||
expect(committed).toEqual([])
|
||||
expect(mockStoreIdempotency).not.toHaveBeenCalled()
|
||||
|
||||
const commit = await route(postInvoice({ key: 'key-9' }), companyParams(COMPANY_ID))
|
||||
|
||||
expect(commit.status).toBe(201)
|
||||
expect(commit.headers.get('Idempotent-Replayed')).toBeNull()
|
||||
expect(committed).toEqual(['inv-1'])
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,957 @@
|
||||
/**
|
||||
* Integration tests for the v1 wrapper.
|
||||
*
|
||||
* Mocks `validateApiKey` and `createServiceClientNoCookies` so we can exercise
|
||||
* the wrapper's auth / scope / company-membership / idempotency / dry-run
|
||||
* branches deterministically.
|
||||
*/
|
||||
import { beforeAll, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import { NextResponse } from 'next/server'
|
||||
|
||||
beforeAll(() => {
|
||||
// The wrapper's public-scope path now fails closed if these env vars are
|
||||
// missing; tests don't run against a real Supabase instance so we stub
|
||||
// values just to clear the guard.
|
||||
process.env.NEXT_PUBLIC_SUPABASE_URL ||= 'http://localhost:54321'
|
||||
process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY ||= 'test-anon-key'
|
||||
})
|
||||
|
||||
vi.mock('@/lib/auth/api-keys', async () => {
|
||||
const actual = await vi.importActual<typeof import('@/lib/auth/api-keys')>('@/lib/auth/api-keys')
|
||||
return {
|
||||
...actual,
|
||||
validateApiKey: vi.fn(),
|
||||
createServiceClientNoCookies: vi.fn(),
|
||||
}
|
||||
})
|
||||
|
||||
// The wrapper's public-scope path calls @supabase/supabase-js#createClient
|
||||
// directly to obtain an anon-key client (no service-role privilege).
|
||||
// Stub it so tests don't need real SUPABASE env vars.
|
||||
vi.mock('@supabase/supabase-js', async () => {
|
||||
const actual = await vi.importActual<typeof import('@supabase/supabase-js')>('@supabase/supabase-js')
|
||||
return {
|
||||
...actual,
|
||||
createClient: vi.fn().mockReturnValue({}),
|
||||
}
|
||||
})
|
||||
|
||||
// Multi-user seat gate: mocked so the membership stub stays single-purpose;
|
||||
// the gate's own logic is covered in lib/entitlements/__tests__/multi-user.test.ts.
|
||||
const getMultiUserStateMock = vi.hoisted(() => vi.fn())
|
||||
vi.mock('@/lib/entitlements/multi-user', async () => {
|
||||
const actual = await vi.importActual<typeof import('@/lib/entitlements/multi-user')>(
|
||||
'@/lib/entitlements/multi-user',
|
||||
)
|
||||
return {
|
||||
...actual,
|
||||
getMultiUserState: (...args: unknown[]) => getMultiUserStateMock(...args),
|
||||
}
|
||||
})
|
||||
|
||||
vi.mock('@/lib/api/idempotency', async () => {
|
||||
const actual = await vi.importActual<typeof import('@/lib/api/idempotency')>(
|
||||
'@/lib/api/idempotency',
|
||||
)
|
||||
return {
|
||||
...actual,
|
||||
checkIdempotencyKey: vi.fn(),
|
||||
storeIdempotencyResponse: vi.fn(),
|
||||
}
|
||||
})
|
||||
|
||||
import {
|
||||
validateApiKey,
|
||||
createServiceClientNoCookies,
|
||||
RATE_LIMIT_RETRY_AFTER_SECONDS,
|
||||
} from '@/lib/auth/api-keys'
|
||||
import {
|
||||
checkIdempotencyKey,
|
||||
storeIdempotencyResponse,
|
||||
} from '@/lib/api/idempotency'
|
||||
import { truncateIp, withApiV1 } from '../with-api-v1'
|
||||
import { ok } from '../response'
|
||||
|
||||
const mockValidate = validateApiKey as ReturnType<typeof vi.fn>
|
||||
const mockServiceClient = createServiceClientNoCookies as ReturnType<typeof vi.fn>
|
||||
const mockCheckIdempotency = checkIdempotencyKey as ReturnType<typeof vi.fn>
|
||||
const mockStoreIdempotency = storeIdempotencyResponse as ReturnType<typeof vi.fn>
|
||||
|
||||
function makeSupabaseStub(membership: { company_id: string; role: string } | null) {
|
||||
return {
|
||||
from: vi.fn().mockReturnValue({
|
||||
select: vi.fn().mockReturnValue({
|
||||
eq: vi.fn().mockReturnValue({
|
||||
eq: vi.fn().mockReturnValue({
|
||||
maybeSingle: vi.fn().mockResolvedValue({ data: membership, error: null }),
|
||||
}),
|
||||
}),
|
||||
}),
|
||||
}),
|
||||
}
|
||||
}
|
||||
|
||||
function makeRequest(url: string, init?: RequestInit): Request {
|
||||
return new Request(url, init)
|
||||
}
|
||||
|
||||
// Helper that wraps an empty params promise for non-dynamic routes.
|
||||
function emptyParams() {
|
||||
return { params: Promise.resolve({}) }
|
||||
}
|
||||
|
||||
// What Next.js 16 ACTUALLY passes to a STATIC route's handler: `{ params:
|
||||
// undefined }` (app-route module: `params: context.params ? ... : undefined`).
|
||||
// `emptyParams()` above is NOT what the runtime hands a static route, so it
|
||||
// masked #781. Use this for the real static-route contract.
|
||||
function staticRouteContext() {
|
||||
return { params: undefined } as unknown as { params: Promise<Record<string, never>> }
|
||||
}
|
||||
|
||||
function companyParams(companyId: string) {
|
||||
return { params: Promise.resolve({ companyId }) }
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
mockServiceClient.mockReturnValue(makeSupabaseStub(null))
|
||||
getMultiUserStateMock.mockResolvedValue({ state: 'entitled', graceEndsAt: null })
|
||||
})
|
||||
|
||||
describe('withApiV1: auth', () => {
|
||||
it('returns 401 when Authorization header is missing', async () => {
|
||||
const handler = withApiV1('companies.list', async (_req, ctx) =>
|
||||
ok({ ok: true }, { requestId: ctx.requestId }),
|
||||
)
|
||||
|
||||
const res = await handler(makeRequest('https://x.test/api/v1/companies'), emptyParams())
|
||||
expect(res.status).toBe(401)
|
||||
const body = await res.json()
|
||||
expect(body.error.code).toBe('UNAUTHORIZED')
|
||||
expect(body.error.request_id).toMatch(/^req_/)
|
||||
})
|
||||
|
||||
it('returns 401 when validateApiKey rejects the token', async () => {
|
||||
mockValidate.mockResolvedValue({ error: 'Invalid API key', status: 401 })
|
||||
|
||||
const handler = withApiV1('companies.list', async (_req, ctx) =>
|
||||
ok({ ok: true }, { requestId: ctx.requestId }),
|
||||
)
|
||||
|
||||
const res = await handler(
|
||||
makeRequest('https://x.test/api/v1/companies', {
|
||||
headers: { Authorization: 'Bearer gnubok_sk_invalid' },
|
||||
}),
|
||||
emptyParams(),
|
||||
)
|
||||
expect(res.status).toBe(401)
|
||||
})
|
||||
|
||||
it('returns 429 when the underlying key is rate-limited', async () => {
|
||||
mockValidate.mockResolvedValue({ error: 'Rate limit exceeded', status: 429 })
|
||||
|
||||
const handler = withApiV1('companies.list', async (_req, ctx) =>
|
||||
ok({ ok: true }, { requestId: ctx.requestId }),
|
||||
)
|
||||
|
||||
const res = await handler(
|
||||
makeRequest('https://x.test/api/v1/companies', {
|
||||
headers: { Authorization: 'Bearer gnubok_sk_x' },
|
||||
}),
|
||||
emptyParams(),
|
||||
)
|
||||
expect(res.status).toBe(429)
|
||||
const body = await res.json()
|
||||
expect(body.error.code).toBe('RATE_LIMITED')
|
||||
// The published skill instructs agents to honor Retry-After on a 429.
|
||||
// Before this header existed that instruction pointed at nothing, so an
|
||||
// unattended client had to back off blindly.
|
||||
expect(res.headers.get('Retry-After')).toBe(String(RATE_LIMIT_RETRY_AFTER_SECONDS))
|
||||
})
|
||||
|
||||
it('does not advertise Retry-After on a non-throttle error', async () => {
|
||||
mockValidate.mockResolvedValue({ error: 'Invalid API key', status: 401 })
|
||||
|
||||
const handler = withApiV1('companies.list', async (_req, ctx) =>
|
||||
ok({ ok: true }, { requestId: ctx.requestId }),
|
||||
)
|
||||
|
||||
const res = await handler(
|
||||
makeRequest('https://x.test/api/v1/companies', {
|
||||
headers: { Authorization: 'Bearer gnubok_sk_invalid' },
|
||||
}),
|
||||
emptyParams(),
|
||||
)
|
||||
expect(res.status).toBe(401)
|
||||
expect(res.headers.get('Retry-After')).toBeNull()
|
||||
})
|
||||
})
|
||||
|
||||
describe('withApiV1: scope', () => {
|
||||
it('returns 403 INSUFFICIENT_SCOPE when the key lacks the required scope', async () => {
|
||||
mockValidate.mockResolvedValue({
|
||||
userId: 'user-1',
|
||||
companyId: 'company-1',
|
||||
apiKeyId: 'ak_1',
|
||||
apiKeyName: 'test key',
|
||||
scopes: ['invoices:read'], // wrong scope
|
||||
mode: 'live',
|
||||
})
|
||||
|
||||
const handler = withApiV1('companies.list', async (_req, ctx) =>
|
||||
ok({ ok: true }, { requestId: ctx.requestId }),
|
||||
)
|
||||
|
||||
const res = await handler(
|
||||
makeRequest('https://x.test/api/v1/companies', {
|
||||
headers: { Authorization: 'Bearer gnubok_sk_x' },
|
||||
}),
|
||||
emptyParams(),
|
||||
)
|
||||
expect(res.status).toBe(403)
|
||||
const body = await res.json()
|
||||
expect(body.error.code).toBe('INSUFFICIENT_SCOPE')
|
||||
expect(body.error.details.required_scope).toBe('companies:read')
|
||||
})
|
||||
|
||||
it('returns 404 NOT_FOUND for unregistered endpoints (no leak)', async () => {
|
||||
mockValidate.mockResolvedValue({
|
||||
userId: 'user-1',
|
||||
companyId: 'company-1',
|
||||
scopes: ['companies:read'],
|
||||
mode: 'live',
|
||||
})
|
||||
|
||||
const handler = withApiV1('mystery.endpoint', async (_req, ctx) =>
|
||||
ok({ ok: true }, { requestId: ctx.requestId }),
|
||||
)
|
||||
|
||||
const res = await handler(
|
||||
makeRequest('https://x.test/api/v1/mystery', {
|
||||
headers: { Authorization: 'Bearer gnubok_sk_x' },
|
||||
}),
|
||||
emptyParams(),
|
||||
)
|
||||
expect(res.status).toBe(404)
|
||||
})
|
||||
})
|
||||
|
||||
describe('withApiV1: company membership', () => {
|
||||
it('returns 404 when the URL companyId is not a company the user belongs to', async () => {
|
||||
mockValidate.mockResolvedValue({
|
||||
userId: 'user-1',
|
||||
companyId: 'company-1',
|
||||
scopes: ['companies:read'],
|
||||
mode: 'live',
|
||||
})
|
||||
|
||||
// No membership → null
|
||||
mockServiceClient.mockReturnValue(makeSupabaseStub(null))
|
||||
|
||||
const handler = withApiV1(
|
||||
'companies.get',
|
||||
async (_req, ctx) => ok({ ok: true }, { requestId: ctx.requestId }),
|
||||
{ requireScope: 'companies:read' },
|
||||
)
|
||||
|
||||
const res = await handler(
|
||||
makeRequest('https://x.test/api/v1/companies/other-company', {
|
||||
headers: { Authorization: 'Bearer gnubok_sk_x' },
|
||||
}),
|
||||
companyParams('other-company'),
|
||||
)
|
||||
expect(res.status).toBe(404)
|
||||
const body = await res.json()
|
||||
expect(body.error.code).toBe('NOT_FOUND')
|
||||
})
|
||||
|
||||
it('allows the request when the user has membership in the URL company', async () => {
|
||||
mockValidate.mockResolvedValue({
|
||||
userId: 'user-1',
|
||||
companyId: 'company-1',
|
||||
scopes: ['companies:read'],
|
||||
mode: 'live',
|
||||
})
|
||||
|
||||
mockServiceClient.mockReturnValue(makeSupabaseStub({ company_id: 'company-1', role: 'owner' }))
|
||||
|
||||
const handler = withApiV1(
|
||||
'companies.get',
|
||||
async (_req, ctx) => ok({ companyId: ctx.companyId }, { requestId: ctx.requestId }),
|
||||
{ requireScope: 'companies:read' },
|
||||
)
|
||||
|
||||
const res = await handler(
|
||||
makeRequest('https://x.test/api/v1/companies/company-1', {
|
||||
headers: { Authorization: 'Bearer gnubok_sk_x' },
|
||||
}),
|
||||
companyParams('company-1'),
|
||||
)
|
||||
expect(res.status).toBe(200)
|
||||
const body = await res.json()
|
||||
expect(body.data.companyId).toBe('company-1')
|
||||
})
|
||||
|
||||
it('refuses a NON-OWNER membership in a frozen company with 403 (multi-user seat gate)', async () => {
|
||||
mockValidate.mockResolvedValue({
|
||||
userId: 'user-1',
|
||||
companyId: 'company-1',
|
||||
scopes: ['companies:read'],
|
||||
mode: 'live',
|
||||
})
|
||||
mockServiceClient.mockReturnValue(makeSupabaseStub({ company_id: 'company-1', role: 'admin' }))
|
||||
getMultiUserStateMock.mockResolvedValue({ state: 'frozen', graceEndsAt: null })
|
||||
|
||||
const handler = withApiV1<{ params: Promise<{ companyId: string }> }>(
|
||||
'companies.get',
|
||||
async (_req, ctx) => ok({ ok: true }, { requestId: ctx.requestId }),
|
||||
{ requireScope: 'companies:read' },
|
||||
)
|
||||
|
||||
const res = await handler(
|
||||
makeRequest('https://x.test/api/v1/companies/company-1', {
|
||||
headers: { Authorization: 'Bearer gnubok_sk_x' },
|
||||
}),
|
||||
companyParams('company-1'),
|
||||
)
|
||||
expect(res.status).toBe(403)
|
||||
const body = await res.json()
|
||||
expect(body.error.code).toBe('FORBIDDEN')
|
||||
expect(body.error.details.capability).toBe('multi_user')
|
||||
})
|
||||
|
||||
it('OWNERS pass the seat gate without a state read; grace passes for non-owners', async () => {
|
||||
mockValidate.mockResolvedValue({
|
||||
userId: 'user-1',
|
||||
companyId: 'company-1',
|
||||
scopes: ['companies:read'],
|
||||
mode: 'live',
|
||||
})
|
||||
mockServiceClient.mockReturnValue(makeSupabaseStub({ company_id: 'company-1', role: 'owner' }))
|
||||
getMultiUserStateMock.mockResolvedValue({ state: 'frozen', graceEndsAt: null })
|
||||
|
||||
const handler = withApiV1<{ params: Promise<{ companyId: string }> }>(
|
||||
'companies.get',
|
||||
async (_req, ctx) => ok({ ok: true }, { requestId: ctx.requestId }),
|
||||
{ requireScope: 'companies:read' },
|
||||
)
|
||||
const ownerRes = await handler(
|
||||
makeRequest('https://x.test/api/v1/companies/company-1', {
|
||||
headers: { Authorization: 'Bearer gnubok_sk_x' },
|
||||
}),
|
||||
companyParams('company-1'),
|
||||
)
|
||||
expect(ownerRes.status).toBe(200)
|
||||
expect(getMultiUserStateMock).not.toHaveBeenCalled()
|
||||
|
||||
mockServiceClient.mockReturnValue(makeSupabaseStub({ company_id: 'company-1', role: 'member' }))
|
||||
getMultiUserStateMock.mockResolvedValue({
|
||||
state: 'grace',
|
||||
graceEndsAt: new Date(Date.now() + 5 * 86_400_000).toISOString(),
|
||||
})
|
||||
const graceRes = await handler(
|
||||
makeRequest('https://x.test/api/v1/companies/company-1', {
|
||||
headers: { Authorization: 'Bearer gnubok_sk_x' },
|
||||
}),
|
||||
companyParams('company-1'),
|
||||
)
|
||||
expect(graceRes.status).toBe(200)
|
||||
})
|
||||
})
|
||||
|
||||
describe('withApiV1: static (non-dynamic) route params', () => {
|
||||
// Regression for #781: GET /api/v1/companies is the only authenticated
|
||||
// static route. Next.js 16 hands it `{ params: undefined }`. The wrapper
|
||||
// must not null-deref on `params.params` after auth succeeds.
|
||||
it('does not 500 when Next passes { params: undefined } for a static route', async () => {
|
||||
mockValidate.mockResolvedValue({
|
||||
userId: 'user-1',
|
||||
companyId: undefined,
|
||||
scopes: ['companies:read'],
|
||||
mode: 'live',
|
||||
})
|
||||
|
||||
let observedCompanyId: string | undefined = 'sentinel'
|
||||
let handlerCalled = false
|
||||
const handler = withApiV1('companies.list', async (_req, ctx) => {
|
||||
handlerCalled = true
|
||||
observedCompanyId = ctx.companyId
|
||||
return ok({ ok: true }, { requestId: ctx.requestId })
|
||||
})
|
||||
|
||||
const res = await handler(
|
||||
makeRequest('https://x.test/api/v1/companies', {
|
||||
headers: { Authorization: 'Bearer gnubok_sk_x' },
|
||||
}),
|
||||
staticRouteContext(),
|
||||
)
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
expect(handlerCalled).toBe(true)
|
||||
expect(observedCompanyId).toBeUndefined()
|
||||
})
|
||||
})
|
||||
|
||||
describe('withApiV1: idempotency', () => {
|
||||
it('replays a cached response when the idempotency key matches', async () => {
|
||||
mockValidate.mockResolvedValue({
|
||||
userId: 'user-1',
|
||||
companyId: 'company-1',
|
||||
scopes: ['invoices:write'],
|
||||
mode: 'live',
|
||||
})
|
||||
|
||||
mockServiceClient.mockReturnValue(makeSupabaseStub({ company_id: 'company-1', role: 'owner' }))
|
||||
|
||||
mockCheckIdempotency.mockResolvedValue({
|
||||
status: 'success',
|
||||
body: { data: { id: 'inv-cached' } },
|
||||
})
|
||||
|
||||
const handler = withApiV1(
|
||||
'invoices.create',
|
||||
async () => {
|
||||
return NextResponse.json({ data: { id: 'inv-fresh' } }, { status: 201 })
|
||||
},
|
||||
{ requireScope: 'invoices:write' },
|
||||
)
|
||||
|
||||
const res = await handler(
|
||||
makeRequest('https://x.test/api/v1/companies/company-1/invoices', {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
Authorization: 'Bearer gnubok_sk_x',
|
||||
'Idempotency-Key': 'key-1',
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
body: JSON.stringify({ customer_id: 'cust-1' }),
|
||||
}),
|
||||
companyParams('company-1'),
|
||||
)
|
||||
|
||||
expect(res.headers.get('Idempotent-Replayed')).toBe('true')
|
||||
const body = await res.json()
|
||||
expect(body.data.id).toBe('inv-cached')
|
||||
})
|
||||
|
||||
it('honors the require-idempotency-key option', async () => {
|
||||
mockValidate.mockResolvedValue({
|
||||
userId: 'user-1',
|
||||
companyId: 'company-1',
|
||||
scopes: ['invoices:write'],
|
||||
mode: 'live',
|
||||
})
|
||||
mockServiceClient.mockReturnValue(makeSupabaseStub({ company_id: 'company-1', role: 'owner' }))
|
||||
|
||||
const handler = withApiV1(
|
||||
'invoices.create',
|
||||
async (_req, ctx) => ok({ ok: true }, { requestId: ctx.requestId }),
|
||||
{ requireScope: 'invoices:write', requireIdempotencyKey: true },
|
||||
)
|
||||
|
||||
const res = await handler(
|
||||
makeRequest('https://x.test/api/v1/companies/company-1/invoices', {
|
||||
method: 'POST',
|
||||
headers: { Authorization: 'Bearer gnubok_sk_x' },
|
||||
}),
|
||||
companyParams('company-1'),
|
||||
)
|
||||
expect(res.status).toBe(400)
|
||||
const body = await res.json()
|
||||
expect(body.error.code).toBe('VALIDATION_ERROR')
|
||||
})
|
||||
|
||||
it('hashes a cloned body and leaves the original readable by the handler', async () => {
|
||||
mockValidate.mockResolvedValue({
|
||||
userId: 'user-1',
|
||||
companyId: 'company-1',
|
||||
scopes: ['invoices:write'],
|
||||
mode: 'live',
|
||||
})
|
||||
mockServiceClient.mockReturnValue(makeSupabaseStub({ company_id: 'company-1', role: 'owner' }))
|
||||
mockCheckIdempotency.mockResolvedValue(null)
|
||||
let observedBody: unknown
|
||||
|
||||
const handler = withApiV1(
|
||||
'invoices.create',
|
||||
async (request, ctx) => {
|
||||
observedBody = await request.json()
|
||||
return ok({ ok: true }, { requestId: ctx.requestId })
|
||||
},
|
||||
{ requireScope: 'invoices:write' },
|
||||
)
|
||||
const requestBody = { customer_id: 'cust-1', additional_cc: ['copy@example.test'] }
|
||||
|
||||
const response = await handler(
|
||||
makeRequest('https://x.test/api/v1/companies/company-1/invoices', {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
Authorization: 'Bearer gnubok_sk_x',
|
||||
'Idempotency-Key': 'key-body-readable',
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
body: JSON.stringify(requestBody),
|
||||
}),
|
||||
companyParams('company-1'),
|
||||
)
|
||||
|
||||
expect(response.status).toBe(200)
|
||||
expect(observedBody).toEqual(requestBody)
|
||||
expect(mockCheckIdempotency).toHaveBeenCalledWith(
|
||||
expect.anything(),
|
||||
'user-1',
|
||||
'company-1',
|
||||
'key-body-readable',
|
||||
expect.any(String),
|
||||
)
|
||||
})
|
||||
})
|
||||
|
||||
describe('withApiV1: dry-run', () => {
|
||||
it('threads dry_run=true from query string into context', async () => {
|
||||
mockValidate.mockResolvedValue({
|
||||
userId: 'user-1',
|
||||
companyId: 'company-1',
|
||||
scopes: ['invoices:write'],
|
||||
mode: 'live',
|
||||
})
|
||||
mockServiceClient.mockReturnValue(makeSupabaseStub({ company_id: 'company-1', role: 'owner' }))
|
||||
|
||||
let observedDryRun: boolean | null = null
|
||||
const handler = withApiV1(
|
||||
'invoices.create',
|
||||
async (_req, ctx) => {
|
||||
observedDryRun = ctx.dryRun
|
||||
return ok({ ok: true }, { requestId: ctx.requestId, dryRun: ctx.dryRun })
|
||||
},
|
||||
{ requireScope: 'invoices:write' },
|
||||
)
|
||||
|
||||
const res = await handler(
|
||||
makeRequest('https://x.test/api/v1/companies/company-1/invoices?dry_run=true', {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
Authorization: 'Bearer gnubok_sk_x',
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
body: JSON.stringify({}),
|
||||
}),
|
||||
companyParams('company-1'),
|
||||
)
|
||||
|
||||
expect(observedDryRun).toBe(true)
|
||||
expect(res.headers.get('X-Dry-Run')).toBe('true')
|
||||
})
|
||||
|
||||
it('threads X-Dry-Run header into context', async () => {
|
||||
mockValidate.mockResolvedValue({
|
||||
userId: 'user-1',
|
||||
companyId: 'company-1',
|
||||
scopes: ['invoices:write'],
|
||||
mode: 'live',
|
||||
})
|
||||
mockServiceClient.mockReturnValue(makeSupabaseStub({ company_id: 'company-1', role: 'owner' }))
|
||||
|
||||
let observedDryRun: boolean | null = null
|
||||
const handler = withApiV1(
|
||||
'invoices.create',
|
||||
async (_req, ctx) => {
|
||||
observedDryRun = ctx.dryRun
|
||||
return ok({ ok: true }, { requestId: ctx.requestId })
|
||||
},
|
||||
{ requireScope: 'invoices:write' },
|
||||
)
|
||||
|
||||
await handler(
|
||||
makeRequest('https://x.test/api/v1/companies/company-1/invoices', {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
Authorization: 'Bearer gnubok_sk_x',
|
||||
'X-Dry-Run': 'true',
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
body: '{}',
|
||||
}),
|
||||
companyParams('company-1'),
|
||||
)
|
||||
|
||||
expect(observedDryRun).toBe(true)
|
||||
})
|
||||
})
|
||||
|
||||
describe('withApiV1: test mode', () => {
|
||||
it('blocks a test-key write on a non-simulatable endpoint (403 TEST_KEY_WRITE_BLOCKED)', async () => {
|
||||
// No route modules are imported here, so the endpoint registry is empty →
|
||||
// getEndpointByConcretePath returns undefined → the wrapper must refuse the
|
||||
// write rather than let a test key mutate real data.
|
||||
mockValidate.mockResolvedValue({
|
||||
userId: 'user-1',
|
||||
companyId: 'company-1',
|
||||
scopes: ['invoices:write'],
|
||||
mode: 'test',
|
||||
})
|
||||
mockServiceClient.mockReturnValue(makeSupabaseStub({ company_id: 'company-1', role: 'owner' }))
|
||||
|
||||
let handlerCalled = false
|
||||
const handler = withApiV1(
|
||||
'invoices.create',
|
||||
async (_req, ctx) => {
|
||||
handlerCalled = true
|
||||
return ok({ ok: true }, { requestId: ctx.requestId })
|
||||
},
|
||||
{ requireScope: 'invoices:write' },
|
||||
)
|
||||
|
||||
const res = await handler(
|
||||
makeRequest('https://x.test/api/v1/companies/company-1/invoices', {
|
||||
method: 'POST',
|
||||
headers: { Authorization: 'Bearer gnubok_sk_x', 'Content-Type': 'application/json' },
|
||||
body: '{}',
|
||||
}),
|
||||
companyParams('company-1'),
|
||||
)
|
||||
|
||||
expect(res.status).toBe(403)
|
||||
const body = await res.json()
|
||||
expect(body.error.code).toBe('TEST_KEY_WRITE_BLOCKED')
|
||||
expect(handlerCalled).toBe(false)
|
||||
})
|
||||
|
||||
it('allows a test-key READ unchanged: no forced dry-run, real data, X-Gnubok-Mode header', async () => {
|
||||
mockValidate.mockResolvedValue({
|
||||
userId: 'user-1',
|
||||
companyId: 'company-1',
|
||||
scopes: ['companies:read'],
|
||||
mode: 'test',
|
||||
})
|
||||
mockServiceClient.mockReturnValue(makeSupabaseStub({ company_id: 'company-1', role: 'owner' }))
|
||||
|
||||
let observedDryRun: boolean | null = null
|
||||
const handler = withApiV1(
|
||||
'companies.get',
|
||||
async (_req, ctx) => {
|
||||
observedDryRun = ctx.dryRun
|
||||
return ok({ ok: true }, { requestId: ctx.requestId })
|
||||
},
|
||||
{ requireScope: 'companies:read' },
|
||||
)
|
||||
|
||||
const res = await handler(
|
||||
makeRequest('https://x.test/api/v1/companies/company-1', {
|
||||
headers: { Authorization: 'Bearer gnubok_sk_x' },
|
||||
}),
|
||||
companyParams('company-1'),
|
||||
)
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
expect(observedDryRun).toBe(false)
|
||||
expect(res.headers.get('X-Gnubok-Mode')).toBe('test')
|
||||
})
|
||||
})
|
||||
|
||||
describe('withApiV1: public endpoints', () => {
|
||||
it('invokes the handler without authentication for /api/v1/health', async () => {
|
||||
let observedUserId: string | null = null
|
||||
const handler = withApiV1('health.check', async (_req, ctx) => {
|
||||
observedUserId = ctx.userId
|
||||
return ok({ status: 'ok' }, { requestId: ctx.requestId })
|
||||
})
|
||||
|
||||
const res = await handler(makeRequest('https://x.test/api/v1/health'), emptyParams())
|
||||
expect(res.status).toBe(200)
|
||||
expect(observedUserId).toBe('anonymous')
|
||||
})
|
||||
|
||||
it('opportunistically attributes a valid Bearer token on a public route', async () => {
|
||||
mockValidate.mockResolvedValue({
|
||||
userId: 'user-1',
|
||||
companyId: 'company-1',
|
||||
apiKeyId: 'ak_1',
|
||||
apiKeyName: 'CI key',
|
||||
scopes: ['companies:read'],
|
||||
mode: 'live',
|
||||
})
|
||||
|
||||
let observedUserId: string | null = null
|
||||
let observedApiKeyId: string | undefined
|
||||
const handler = withApiV1('health.check', async (_req, ctx) => {
|
||||
observedUserId = ctx.userId
|
||||
observedApiKeyId = ctx.apiKeyId
|
||||
return ok({ status: 'ok' }, { requestId: ctx.requestId })
|
||||
})
|
||||
|
||||
const res = await handler(
|
||||
makeRequest('https://x.test/api/v1/health', {
|
||||
headers: { Authorization: 'Bearer gnubok_sk_x' },
|
||||
}),
|
||||
emptyParams(),
|
||||
)
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
expect(observedUserId).toBe('user-1')
|
||||
expect(observedApiKeyId).toBe('ak_1')
|
||||
})
|
||||
|
||||
it('silently downgrades an invalid Bearer token to anon on a public route', async () => {
|
||||
mockValidate.mockResolvedValue({ error: 'Invalid API key', status: 401 })
|
||||
|
||||
let observedUserId: string | null = null
|
||||
const handler = withApiV1('health.check', async (_req, ctx) => {
|
||||
observedUserId = ctx.userId
|
||||
return ok({ status: 'ok' }, { requestId: ctx.requestId })
|
||||
})
|
||||
|
||||
const res = await handler(
|
||||
makeRequest('https://x.test/api/v1/health', {
|
||||
headers: { Authorization: 'Bearer gnubok_sk_invalid' },
|
||||
}),
|
||||
emptyParams(),
|
||||
)
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
expect(observedUserId).toBe('anonymous')
|
||||
})
|
||||
})
|
||||
|
||||
describe('withApiV1: stable headers', () => {
|
||||
it('always stamps X-Request-Id and Gnubok-Version', async () => {
|
||||
const handler = withApiV1('health.check', async (_req, ctx) =>
|
||||
ok({ status: 'ok' }, { requestId: ctx.requestId }),
|
||||
)
|
||||
|
||||
const res = await handler(makeRequest('https://x.test/api/v1/health'), emptyParams())
|
||||
expect(res.headers.get('X-Request-Id')).toMatch(/^req_/)
|
||||
expect(res.headers.get('Gnubok-Version')).toMatch(/^\d{4}-\d{2}-\d{2}$/)
|
||||
})
|
||||
})
|
||||
|
||||
describe('truncateIp: privacy-preserving IP logging', () => {
|
||||
it('truncates IPv4 to /24', () => {
|
||||
expect(truncateIp('203.0.113.42')).toBe('203.0.113.0/24')
|
||||
})
|
||||
|
||||
it('truncates IPv6 to /48', () => {
|
||||
expect(truncateIp('2001:db8:abcd:1234::1')).toBe('2001:db8:abcd::/48')
|
||||
})
|
||||
|
||||
it('returns undefined for an empty IP', () => {
|
||||
expect(truncateIp(undefined)).toBeUndefined()
|
||||
expect(truncateIp('')).toBeUndefined()
|
||||
})
|
||||
|
||||
it('returns undefined for malformed input rather than leaking it raw', () => {
|
||||
expect(truncateIp('not-an-ip')).toBeUndefined()
|
||||
})
|
||||
|
||||
it('rejects IPv4 with out-of-range octets to avoid pseudo-IPs in audit logs', () => {
|
||||
expect(truncateIp('999.999.999.999')).toBeUndefined()
|
||||
expect(truncateIp('256.0.0.1')).toBeUndefined()
|
||||
expect(truncateIp('192.168.1.300')).toBeUndefined()
|
||||
})
|
||||
|
||||
it('accepts edge IPv4 octets (0 and 255)', () => {
|
||||
expect(truncateIp('0.0.0.0')).toBe('0.0.0.0/24')
|
||||
expect(truncateIp('255.255.255.255')).toBe('255.255.255.0/24')
|
||||
})
|
||||
})
|
||||
|
||||
// Suppress unused-import warning: we re-export to keep the type chain visible.
|
||||
void mockStoreIdempotency
|
||||
|
||||
describe('withApiV1: read-only role gate (viewer)', () => {
|
||||
// The v1 surface runs as the service role, so RLS never sees the viewer.
|
||||
// This wrapper is the only place the read-only role is enforced for API
|
||||
// keys; the DB triggers that block viewer writes apply to cookie sessions.
|
||||
function viewerKey(scopes: string[]) {
|
||||
mockValidate.mockResolvedValue({
|
||||
userId: 'user-viewer',
|
||||
companyId: 'company-1',
|
||||
scopes,
|
||||
mode: 'live',
|
||||
})
|
||||
mockServiceClient.mockReturnValue(makeSupabaseStub({ company_id: 'company-1', role: 'viewer' }))
|
||||
}
|
||||
|
||||
it('refuses a viewer key on POST journal-entries with 403 ROLE_READ_ONLY before the handler runs', async () => {
|
||||
viewerKey(['bookkeeping:write'])
|
||||
const handlerSpy = vi.fn(async (_req: Request, ctx: { requestId: string }) =>
|
||||
ok({ id: 'je-1' }, { requestId: ctx.requestId }),
|
||||
)
|
||||
// No requireScope override: the real catalogue entry for the route is what
|
||||
// classifies the request ('POST .../journal-entries' -> bookkeeping:write).
|
||||
const handler = withApiV1<{ params: Promise<{ companyId: string }> }>(
|
||||
'journal-entries.create',
|
||||
handlerSpy,
|
||||
)
|
||||
|
||||
const res = await handler(
|
||||
makeRequest('https://x.test/api/v1/companies/company-1/journal-entries', {
|
||||
method: 'POST',
|
||||
headers: { Authorization: 'Bearer gnubok_sk_x', 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ description: 'x', lines: [] }),
|
||||
}),
|
||||
companyParams('company-1'),
|
||||
)
|
||||
|
||||
expect(res.status).toBe(403)
|
||||
const body = await res.json()
|
||||
expect(body.error.code).toBe('FORBIDDEN')
|
||||
expect(body.error.details.code).toBe('ROLE_READ_ONLY')
|
||||
expect(body.error.details.role).toBe('viewer')
|
||||
expect(body.error.details.required_scope).toBe('bookkeeping:write')
|
||||
// Swedish user-facing message from the registry entry.
|
||||
expect(body.error.message).toBe('Du har inte behörighet att utföra denna åtgärd.')
|
||||
expect(body.error.request_id).toMatch(/^req_/)
|
||||
expect(handlerSpy).not.toHaveBeenCalled()
|
||||
// Refused before the seat gate: no extra read for a refused write.
|
||||
expect(getMultiUserStateMock).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('refuses a viewer even when the write is a dry-run (nothing to simulate for a read-only role)', async () => {
|
||||
viewerKey(['invoices:write'])
|
||||
const handlerSpy = vi.fn(async (_req: Request, ctx: { requestId: string }) =>
|
||||
ok({ ok: true }, { requestId: ctx.requestId }),
|
||||
)
|
||||
const handler = withApiV1<{ params: Promise<{ companyId: string }> }>(
|
||||
'invoices.create',
|
||||
handlerSpy,
|
||||
{ requireScope: 'invoices:write' },
|
||||
)
|
||||
|
||||
const res = await handler(
|
||||
makeRequest('https://x.test/api/v1/companies/company-1/invoices?dry_run=true', {
|
||||
method: 'POST',
|
||||
headers: { Authorization: 'Bearer gnubok_sk_x' },
|
||||
}),
|
||||
companyParams('company-1'),
|
||||
)
|
||||
|
||||
expect(res.status).toBe(403)
|
||||
const body = await res.json()
|
||||
expect(body.error.details.code).toBe('ROLE_READ_ONLY')
|
||||
expect(handlerSpy).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('refuses a viewer on a GET whose scope is an elevated grant (webhooks:manage)', async () => {
|
||||
viewerKey(['webhooks:manage'])
|
||||
const handlerSpy = vi.fn(async (_req: Request, ctx: { requestId: string }) =>
|
||||
ok({ webhooks: [] }, { requestId: ctx.requestId }),
|
||||
)
|
||||
const handler = withApiV1<{ params: Promise<{ companyId: string }> }>(
|
||||
'webhooks.list',
|
||||
handlerSpy,
|
||||
{ requireScope: 'webhooks:manage' },
|
||||
)
|
||||
|
||||
const res = await handler(
|
||||
makeRequest('https://x.test/api/v1/companies/company-1/webhooks', {
|
||||
headers: { Authorization: 'Bearer gnubok_sk_x' },
|
||||
}),
|
||||
companyParams('company-1'),
|
||||
)
|
||||
|
||||
expect(res.status).toBe(403)
|
||||
const body = await res.json()
|
||||
expect(body.error.details.code).toBe('ROLE_READ_ONLY')
|
||||
expect(body.error.details.required_scope).toBe('webhooks:manage')
|
||||
expect(handlerSpy).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('leaves a viewer GET on a :read scope untouched (200, seat gate still consulted)', async () => {
|
||||
viewerKey(['reports:read'])
|
||||
const handler = withApiV1<{ params: Promise<{ companyId: string }> }>(
|
||||
'journal-entries.list',
|
||||
async (_req, ctx) => ok({ entries: [], companyId: ctx.companyId }, { requestId: ctx.requestId }),
|
||||
)
|
||||
|
||||
const res = await handler(
|
||||
makeRequest('https://x.test/api/v1/companies/company-1/journal-entries', {
|
||||
headers: { Authorization: 'Bearer gnubok_sk_x' },
|
||||
}),
|
||||
companyParams('company-1'),
|
||||
)
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
const body = await res.json()
|
||||
expect(body.data.companyId).toBe('company-1')
|
||||
// A viewer is a non-owner: the dormant-seat logic still runs for reads.
|
||||
expect(getMultiUserStateMock).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
|
||||
it('still applies the seat gate to a viewer read in a frozen company', async () => {
|
||||
viewerKey(['reports:read'])
|
||||
getMultiUserStateMock.mockResolvedValue({ state: 'frozen', graceEndsAt: null })
|
||||
const handler = withApiV1<{ params: Promise<{ companyId: string }> }>(
|
||||
'journal-entries.list',
|
||||
async (_req, ctx) => ok({ entries: [] }, { requestId: ctx.requestId }),
|
||||
)
|
||||
|
||||
const res = await handler(
|
||||
makeRequest('https://x.test/api/v1/companies/company-1/journal-entries', {
|
||||
headers: { Authorization: 'Bearer gnubok_sk_x' },
|
||||
}),
|
||||
companyParams('company-1'),
|
||||
)
|
||||
|
||||
expect(res.status).toBe(403)
|
||||
const body = await res.json()
|
||||
expect(body.error.details.capability).toBe('multi_user')
|
||||
expect(body.error.details.code).toBeUndefined()
|
||||
})
|
||||
|
||||
it.each(['member', 'admin', 'owner'])('lets a %s key through the role gate on POST journal-entries', async (role) => {
|
||||
mockValidate.mockResolvedValue({
|
||||
userId: 'user-1',
|
||||
companyId: 'company-1',
|
||||
scopes: ['bookkeeping:write'],
|
||||
mode: 'live',
|
||||
})
|
||||
mockServiceClient.mockReturnValue(makeSupabaseStub({ company_id: 'company-1', role }))
|
||||
const handlerSpy = vi.fn(async (_req: Request, ctx: { requestId: string }) =>
|
||||
NextResponse.json({ data: { id: 'je-1', requestId: ctx.requestId } }, { status: 201 }),
|
||||
)
|
||||
const handler = withApiV1<{ params: Promise<{ companyId: string }> }>(
|
||||
'journal-entries.create',
|
||||
handlerSpy,
|
||||
)
|
||||
|
||||
const res = await handler(
|
||||
makeRequest('https://x.test/api/v1/companies/company-1/journal-entries', {
|
||||
method: 'POST',
|
||||
headers: { Authorization: 'Bearer gnubok_sk_x', 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ description: 'x', lines: [] }),
|
||||
}),
|
||||
companyParams('company-1'),
|
||||
)
|
||||
|
||||
expect(res.status).toBe(201)
|
||||
expect(handlerSpy).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
|
||||
it('keeps the non-member answer unchanged: 404, no role information leaks', async () => {
|
||||
mockValidate.mockResolvedValue({
|
||||
userId: 'user-outsider',
|
||||
companyId: 'company-2',
|
||||
scopes: ['bookkeeping:write'],
|
||||
mode: 'live',
|
||||
})
|
||||
mockServiceClient.mockReturnValue(makeSupabaseStub(null))
|
||||
const handler = withApiV1<{ params: Promise<{ companyId: string }> }>(
|
||||
'journal-entries.create',
|
||||
async (_req, ctx) => ok({ ok: true }, { requestId: ctx.requestId }),
|
||||
)
|
||||
|
||||
const res = await handler(
|
||||
makeRequest('https://x.test/api/v1/companies/company-1/journal-entries', {
|
||||
method: 'POST',
|
||||
headers: { Authorization: 'Bearer gnubok_sk_x' },
|
||||
}),
|
||||
companyParams('company-1'),
|
||||
)
|
||||
|
||||
expect(res.status).toBe(404)
|
||||
const body = await res.json()
|
||||
expect(body.error.code).toBe('NOT_FOUND')
|
||||
expect(body.error.details.role).toBeUndefined()
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,123 @@
|
||||
/**
|
||||
* Canonical base URL for v1 surfaces.
|
||||
*
|
||||
* Use this, NOT `new URL(request.url).host`, when assembling URLs that go
|
||||
* into discovery files, OpenAPI specs, or any response a 3rd-party agent
|
||||
* caches. The inbound `Host` header is attacker-controlled at the edge; a
|
||||
* spoofed value would otherwise poison agent discovery and redirect them
|
||||
* to attacker-controlled endpoints.
|
||||
*
|
||||
* Honours `NEXT_PUBLIC_APP_URL` (the same env var the rest of the codebase
|
||||
* uses for absolute links). Falls back to `https://localhost:3000` for
|
||||
* local development when the env var is unset: this is a deliberate
|
||||
* fail-closed default that any production deploy will override.
|
||||
*/
|
||||
|
||||
export function getCanonicalBaseUrl(): string {
|
||||
const fromEnv = process.env.NEXT_PUBLIC_APP_URL?.trim()
|
||||
if (fromEnv) return fromEnv.replace(/\/$/, '')
|
||||
return 'http://localhost:3000'
|
||||
}
|
||||
|
||||
/**
|
||||
* Base URL for the OAuth/MCP discovery documents (/.well-known/*).
|
||||
*
|
||||
* The app is served on two domains since the accounted.se cutover:
|
||||
* app.accounted.se for humans and app.gnubok.se for machine traffic
|
||||
* (existing MCP connectors and API clients were configured against the
|
||||
* legacy host and it can never be retired). RFC 8414/9728 clients validate
|
||||
* that the metadata they fetch is self-consistent with the host they
|
||||
* fetched it from, so discovery must reflect the host the client actually
|
||||
* used. The Host header stays attacker-controlled at the edge, so only
|
||||
* allowlisted hosts are reflected; anything else falls back to the
|
||||
* canonical base URL.
|
||||
*/
|
||||
const LEGACY_DISCOVERY_HOSTS = new Set(['app.gnubok.se'])
|
||||
|
||||
/**
|
||||
* Guards LEGACY_DISCOVERY_HOSTS against drifting from the registered OAuth
|
||||
* configuration (issue #1093). Two invariants, checked both ways:
|
||||
*
|
||||
* (a) When `NEXT_PUBLIC_SKV_OAUTH_BASE_URL` (the redirect_uri host
|
||||
* registered with Skatteverket in Utvecklarportalen) is set, its host
|
||||
* must be reflectable by discovery: either the canonical app host or a
|
||||
* member of LEGACY_DISCOVERY_HOSTS. Otherwise MCP clients that
|
||||
* re-authenticate through the pinned host receive an issuer that does
|
||||
* not match, and AGI/moms staging fails silently.
|
||||
*
|
||||
* (b) Every member of LEGACY_DISCOVERY_HOSTS must be accounted for by the
|
||||
* known registered configuration: the SKV OAuth pin host or the
|
||||
* canonical app host. An orphan entry means someone added or kept a
|
||||
* host that nothing registered actually uses.
|
||||
*
|
||||
* Returns human-readable violations; an empty array means the allowlist and
|
||||
* the registered configuration agree. Called only from
|
||||
* `__tests__/legacy-discovery-hosts.test.ts` (which pins the production
|
||||
* registration), so drift is caught in CI instead of during a production
|
||||
* re-auth near a filing deadline. No runtime behavior depends on it.
|
||||
*/
|
||||
export function validateLegacyDiscoveryHosts(): string[] {
|
||||
const violations: string[] = []
|
||||
|
||||
let canonicalHost: string | null = null
|
||||
try {
|
||||
canonicalHost = new URL(getCanonicalBaseUrl()).host.toLowerCase()
|
||||
} catch {
|
||||
violations.push(
|
||||
`NEXT_PUBLIC_APP_URL is not a parseable URL: "${process.env.NEXT_PUBLIC_APP_URL}"`,
|
||||
)
|
||||
}
|
||||
|
||||
const skvBase = process.env.NEXT_PUBLIC_SKV_OAUTH_BASE_URL?.trim()
|
||||
let skvHost: string | null = null
|
||||
if (skvBase) {
|
||||
try {
|
||||
skvHost = new URL(skvBase).host.toLowerCase()
|
||||
} catch {
|
||||
violations.push(`NEXT_PUBLIC_SKV_OAUTH_BASE_URL is not a parseable URL: "${skvBase}"`)
|
||||
}
|
||||
}
|
||||
|
||||
if (skvHost && skvHost !== canonicalHost && !LEGACY_DISCOVERY_HOSTS.has(skvHost)) {
|
||||
violations.push(
|
||||
`NEXT_PUBLIC_SKV_OAUTH_BASE_URL host "${skvHost}" is neither the canonical host ` +
|
||||
`("${canonicalHost}") nor in LEGACY_DISCOVERY_HOSTS; discovery would hand ` +
|
||||
`re-authenticating clients a mismatched issuer`,
|
||||
)
|
||||
}
|
||||
|
||||
for (const legacyHost of LEGACY_DISCOVERY_HOSTS) {
|
||||
if (legacyHost !== canonicalHost && legacyHost !== skvHost) {
|
||||
violations.push(
|
||||
`LEGACY_DISCOVERY_HOSTS entry "${legacyHost}" matches neither the canonical host ` +
|
||||
`("${canonicalHost}") nor the NEXT_PUBLIC_SKV_OAUTH_BASE_URL host ` +
|
||||
`("${skvHost ?? 'unset'}"); it is orphaned from the registered configuration`,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
return violations
|
||||
}
|
||||
|
||||
export function resolveDiscoveryBaseUrl(request: Request): string {
|
||||
const canonical = getCanonicalBaseUrl()
|
||||
const host = request.headers.get('host')?.trim().toLowerCase()
|
||||
if (!host) return canonical
|
||||
|
||||
let canonicalHost: string | null = null
|
||||
try {
|
||||
canonicalHost = new URL(canonical).host.toLowerCase()
|
||||
} catch {
|
||||
canonicalHost = null
|
||||
}
|
||||
|
||||
if (host === canonicalHost) return canonical
|
||||
if (LEGACY_DISCOVERY_HOSTS.has(host)) return `https://${host}`
|
||||
// Exact hostname match: a prefix check would reflect spoofed hosts like
|
||||
// localhost.evil.example into the discovery documents.
|
||||
const hostname = host.replace(/:\d+$/, '')
|
||||
if (hostname === 'localhost' || hostname === '127.0.0.1') {
|
||||
return `http://${host}`
|
||||
}
|
||||
return canonical
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
/**
|
||||
* JSON body reader for v1 routes.
|
||||
*
|
||||
* Every v1 write route parses its body the same way: read JSON, and on a
|
||||
* malformed body answer with the VALIDATION_ERROR envelope pointing at
|
||||
* `body`. This helper is that block, so routes do:
|
||||
*
|
||||
* const raw = await readV1JsonBody(request, ctx)
|
||||
* if (!raw.ok) return raw.response
|
||||
* const parsed = Schema.safeParse(raw.body)
|
||||
*/
|
||||
|
||||
import type { NextResponse } from 'next/server'
|
||||
import { v1ErrorResponseFromCode, type V1ValidationContext } from './errors'
|
||||
|
||||
export type V1JsonBodyResult =
|
||||
| { ok: true; body: unknown }
|
||||
| { ok: false; response: NextResponse }
|
||||
|
||||
export async function readV1JsonBody(
|
||||
request: Request,
|
||||
ctx: V1ValidationContext,
|
||||
): Promise<V1JsonBodyResult> {
|
||||
try {
|
||||
return { ok: true, body: await request.json() }
|
||||
} catch {
|
||||
return {
|
||||
ok: false,
|
||||
response: await v1ErrorResponseFromCode('VALIDATION_ERROR', ctx.log, {
|
||||
requestId: ctx.requestId,
|
||||
details: { field: 'body', message: 'Body is not valid JSON.' },
|
||||
}),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,74 @@
|
||||
/**
|
||||
* Application-layer period-lock check used by Phase 3 v1 write routes.
|
||||
*
|
||||
* The DB has two layers of protection:
|
||||
* - `enforce_period_lock` trigger blocks writes to any journal entry
|
||||
* whose fiscal_period is `is_closed = TRUE` or has `locked_at` set.
|
||||
* - `enforce_company_lock_date` trigger blocks writes on/before the
|
||||
* company-wide `bookkeeping_locked_through` date.
|
||||
*
|
||||
* Both triggers raise a Postgres exception, which Supabase surfaces as a
|
||||
* generic 500 with `BOOKKEEPING_DB_ERROR`. For the public API we want a
|
||||
* structured `PERIOD_LOCKED` response with enough context for an agent to
|
||||
* decide between (a) post to a later period or (b) ask the user to unlock.
|
||||
*
|
||||
* This helper performs the same check the trigger would, returning a
|
||||
* { locked, reason, fiscal_period_id } verdict. Run it BEFORE the JE insert
|
||||
* so callers get the structured error instead of the trigger exception.
|
||||
*
|
||||
* Note: this is a TOCTOU-window check (a period could be locked between
|
||||
* the check and the insert), but the trigger is still authoritative. The
|
||||
* helper is for ergonomics, not security.
|
||||
*/
|
||||
import type { SupabaseClient } from '@supabase/supabase-js'
|
||||
|
||||
export interface PeriodLockVerdict {
|
||||
locked: boolean
|
||||
reason?:
|
||||
| 'company_lock_date_covers'
|
||||
| 'period_locked_at_set'
|
||||
| 'period_is_closed'
|
||||
| 'no_fiscal_period'
|
||||
fiscal_period_id?: string
|
||||
}
|
||||
|
||||
export async function checkPeriodLock(
|
||||
supabase: SupabaseClient,
|
||||
companyId: string,
|
||||
date: string,
|
||||
): Promise<PeriodLockVerdict> {
|
||||
// Company-wide lock date covers everything on/before bookkeeping_locked_through.
|
||||
const { data: settings } = await supabase
|
||||
.from('company_settings')
|
||||
.select('bookkeeping_locked_through')
|
||||
.eq('company_id', companyId)
|
||||
.maybeSingle()
|
||||
const lockThrough = settings?.bookkeeping_locked_through ?? null
|
||||
if (lockThrough && date <= lockThrough) {
|
||||
return { locked: true, reason: 'company_lock_date_covers' }
|
||||
}
|
||||
|
||||
// Find the fiscal period covering the date.
|
||||
const { data: period } = await supabase
|
||||
.from('fiscal_periods')
|
||||
.select('id, is_closed, locked_at')
|
||||
.eq('company_id', companyId)
|
||||
.lte('period_start', date)
|
||||
.gte('period_end', date)
|
||||
.maybeSingle()
|
||||
|
||||
if (!period) {
|
||||
// No covering period. The engine's own ensure-period helper will create
|
||||
// one (open, unlocked) for ad-hoc booking dates, so this is not a hard
|
||||
// lock; let the JE insert proceed and surface engine errors normally.
|
||||
return { locked: false, reason: 'no_fiscal_period' }
|
||||
}
|
||||
if (period.is_closed) {
|
||||
return { locked: true, reason: 'period_is_closed', fiscal_period_id: period.id }
|
||||
}
|
||||
if (period.locked_at) {
|
||||
return { locked: true, reason: 'period_locked_at_set', fiscal_period_id: period.id }
|
||||
}
|
||||
|
||||
return { locked: false, fiscal_period_id: period.id }
|
||||
}
|
||||
@@ -0,0 +1,66 @@
|
||||
/**
|
||||
* Dry-run response helpers for v1 write endpoints.
|
||||
*
|
||||
* Architectural contract (per the v1 plan):
|
||||
*
|
||||
* 1. Every POST / PATCH / DELETE accepts `?dry_run=true` or `X-Dry-Run: true`.
|
||||
* 2. A dry-run response returns 200 OK with `{ data: { dry_run: true, preview, ... } }`
|
||||
* and the `X-Dry-Run: true` response header: NEVER the resource's
|
||||
* normal success status (201, 204, etc.). A caller that sees `200`
|
||||
* with `X-Dry-Run` knows the write was NOT committed.
|
||||
* 3. Commit by re-issuing the same request without `dry_run=true`, passing
|
||||
* the same `Idempotency-Key` to guarantee at-most-once semantics. The
|
||||
* wrapper keeps the two apart: a dry-run response is never written to the
|
||||
* idempotency cache, and the dry-run flag is folded into the request hash,
|
||||
* so the commit executes for real instead of replaying the preview.
|
||||
* Order matters. Once a key has committed for real, re-issuing it WITH
|
||||
* `dry_run=true` is rejected as key reuse (409 IDEMPOTENCY_KEY_REUSE)
|
||||
* rather than answered with the committed result dressed up as a preview.
|
||||
*
|
||||
* Two preview shapes are supported:
|
||||
*
|
||||
* - **Validation-only** (non-financial resources like customers): the
|
||||
* preview is the would-be record. No staging, no `pending_operations`
|
||||
* row, no journal lines. Useful for validating inputs and discovering
|
||||
* conflicts (duplicate org_number, validation errors) before committing.
|
||||
*
|
||||
* - **Staged** (financial resources: invoices, journal entries, period
|
||||
* ops, salary; later phases): the preview is the record PLUS a
|
||||
* `staged_operation_id` from `pending_operations`, the `journal_lines`
|
||||
* that would be posted, and the `voucher_number_assigned_on_commit`.
|
||||
* Committing happens either by re-POSTing or via
|
||||
* `POST /v1/operations/{staged_operation_id}:commit`.
|
||||
*
|
||||
* This file ships the helpers for both modes. Phase 2 PR-B-1 only uses the
|
||||
* validation-only path (customers); the staged path is wired but not
|
||||
* exercised until invoice writes land in PR-B-2.
|
||||
*/
|
||||
|
||||
import { NextResponse } from 'next/server'
|
||||
import type { Logger } from '@/lib/logger'
|
||||
import { ok } from './response'
|
||||
|
||||
export interface DryRunPreviewBase<T> {
|
||||
/** Always `true` so agents can dispatch on this without parsing headers. */
|
||||
dry_run: true
|
||||
/** The would-be resource. Same shape as the success response. */
|
||||
preview: T
|
||||
}
|
||||
|
||||
interface DryRunResponseOptions {
|
||||
requestId: string
|
||||
log: Logger
|
||||
}
|
||||
|
||||
/**
|
||||
* Return a 200 OK dry-run response for a validation-only preview.
|
||||
*
|
||||
* Use for non-financial writes (customers, suppliers metadata, employee
|
||||
* profiles, settings) where there's nothing to stage: the agent just wants
|
||||
* to know what would be written and whether validation passes.
|
||||
*/
|
||||
export function dryRunPreview<T>(preview: T, opts: DryRunResponseOptions): NextResponse {
|
||||
const body: DryRunPreviewBase<T> = { dry_run: true, preview }
|
||||
opts.log.info('dry-run preview returned', { stage: 'validation-only' })
|
||||
return ok(body, { requestId: opts.requestId, dryRun: true })
|
||||
}
|
||||
@@ -0,0 +1,217 @@
|
||||
/**
|
||||
* v1 REST error envelope.
|
||||
*
|
||||
* Wraps the existing structured-error machinery (lib/errors/get-structured-error)
|
||||
* into the v1-specific shape that agents consume:
|
||||
*
|
||||
* {
|
||||
* error: {
|
||||
* code: machine-readable, stable forever
|
||||
* message: Swedish prose
|
||||
* message_en: English prose (agents prefer this)
|
||||
* details: structured context (pgCode, field issues, period_id...)
|
||||
* recovery_hint: natural-language next step the agent can act on
|
||||
* docs_url: canonical error-doc URL
|
||||
* valid_alternatives: hints like { unlock_endpoint, next_open_period, ...}
|
||||
* request_id: correlation id, echoed in X-Request-Id header
|
||||
* }
|
||||
* }
|
||||
*
|
||||
* The first three fields exist on the legacy `getStructuredError` output.
|
||||
* `recovery_hint`, `docs_url`, `valid_alternatives` are additive: derived from
|
||||
* the registry's `remediation` block (when present) plus a per-code doc-URL
|
||||
* derivation rule.
|
||||
*/
|
||||
|
||||
import { NextResponse } from 'next/server'
|
||||
import {
|
||||
errorResponse as legacyErrorResponse,
|
||||
errorResponseFromCode as legacyErrorResponseFromCode,
|
||||
} from '@/lib/errors/get-structured-error'
|
||||
import type { Logger } from '@/lib/logger'
|
||||
import { API_V1_VERSION, API_V1_VERSION_HEADER } from './version'
|
||||
|
||||
const DOCS_BASE = process.env.NEXT_PUBLIC_APP_URL
|
||||
? `${process.env.NEXT_PUBLIC_APP_URL.replace(/\/$/, '')}/docs/api/errors`
|
||||
: '/docs/api/errors'
|
||||
|
||||
export interface V1ErrorBody {
|
||||
error: {
|
||||
code: string
|
||||
message: string
|
||||
message_en?: string
|
||||
details?: unknown
|
||||
recovery_hint?: string
|
||||
docs_url?: string
|
||||
valid_alternatives?: Record<string, unknown>
|
||||
request_id?: string
|
||||
}
|
||||
}
|
||||
|
||||
export interface V1ErrorContext {
|
||||
requestId: string
|
||||
/** Extra structured context for the agent (period_id, customer_id, ...). */
|
||||
details?: unknown
|
||||
/** Override the http status from the registry entry. */
|
||||
status?: number
|
||||
/** Agent-actionable next-step suggestions: { unlock_endpoint, next_open_period }. */
|
||||
validAlternatives?: Record<string, unknown>
|
||||
/**
|
||||
* Seconds to advertise in `Retry-After`. Set on retryable throttles so an
|
||||
* unattended client can pace itself instead of backing off blindly.
|
||||
*/
|
||||
retryAfterSeconds?: number
|
||||
}
|
||||
|
||||
function docsUrlFor(code: string): string {
|
||||
return `${DOCS_BASE}/${code}`
|
||||
}
|
||||
|
||||
/**
|
||||
* Transform a legacy error envelope from `errorResponse()` into the v1 shape.
|
||||
*
|
||||
* The legacy shape is:
|
||||
* { error: { code, message, message_en?, remediation?, requestId?, details? } }
|
||||
*
|
||||
* v1 needs:
|
||||
* { error: { code, message, message_en?, details?, recovery_hint?, docs_url, valid_alternatives?, request_id? } }
|
||||
*
|
||||
* The remediation.description becomes recovery_hint; docs_url is derived from
|
||||
* the code; valid_alternatives is passed through unchanged.
|
||||
*/
|
||||
async function rewriteEnvelope(
|
||||
legacyResponse: NextResponse,
|
||||
ctx: V1ErrorContext,
|
||||
): Promise<NextResponse> {
|
||||
const status = ctx.status ?? legacyResponse.status
|
||||
const body = (await legacyResponse.json().catch(() => null)) as
|
||||
| { error: { code: string; message: string; message_en?: string; remediation?: { description?: string }; details?: unknown } }
|
||||
| null
|
||||
|
||||
if (!body?.error) {
|
||||
// Should never happen: legacyErrorResponse always returns the envelope.
|
||||
const fallback: V1ErrorBody = {
|
||||
error: {
|
||||
code: 'INTERNAL_ERROR',
|
||||
message: 'Ett oväntat serverfel uppstod. Försök igen senare.',
|
||||
message_en: 'Internal server error.',
|
||||
docs_url: docsUrlFor('INTERNAL_ERROR'),
|
||||
request_id: ctx.requestId,
|
||||
},
|
||||
}
|
||||
return finalize(NextResponse.json(fallback, { status }), ctx)
|
||||
}
|
||||
|
||||
const { code, message, message_en, remediation, details } = body.error
|
||||
|
||||
const v1Body: V1ErrorBody = {
|
||||
error: {
|
||||
code,
|
||||
message,
|
||||
...(message_en ? { message_en } : {}),
|
||||
...(details !== undefined ? { details } : {}),
|
||||
...(remediation?.description ? { recovery_hint: remediation.description } : {}),
|
||||
docs_url: docsUrlFor(code),
|
||||
...(ctx.validAlternatives ? { valid_alternatives: ctx.validAlternatives } : {}),
|
||||
request_id: ctx.requestId,
|
||||
},
|
||||
}
|
||||
|
||||
return finalize(NextResponse.json(v1Body, { status }), ctx)
|
||||
}
|
||||
|
||||
function finalize(res: NextResponse, ctx: V1ErrorContext): NextResponse {
|
||||
res.headers.set('X-Request-Id', ctx.requestId)
|
||||
res.headers.set(API_V1_VERSION_HEADER, API_V1_VERSION)
|
||||
// The published skill tells agents to honor Retry-After on a 429. Until
|
||||
// this landed, /api/v1 never sent one, so that instruction pointed at a
|
||||
// header that did not exist.
|
||||
if (ctx.retryAfterSeconds !== undefined) {
|
||||
res.headers.set('Retry-After', String(ctx.retryAfterSeconds))
|
||||
}
|
||||
return res
|
||||
}
|
||||
|
||||
/**
|
||||
* v1 error response from a thrown value. Dispatches through the legacy
|
||||
* machinery for code resolution, then rewrites into the v1 shape.
|
||||
*
|
||||
* Always logs the underlying error; never throws.
|
||||
*/
|
||||
export async function v1ErrorResponse(
|
||||
err: unknown,
|
||||
log: Logger,
|
||||
ctx: V1ErrorContext,
|
||||
): Promise<NextResponse> {
|
||||
const legacy = legacyErrorResponse(err, log, {
|
||||
requestId: ctx.requestId,
|
||||
details: ctx.details,
|
||||
status: ctx.status,
|
||||
})
|
||||
return rewriteEnvelope(legacy, ctx)
|
||||
}
|
||||
|
||||
/**
|
||||
* v1 error response from a known code (no thrown value involved).
|
||||
*
|
||||
* Use this when the route already knows the failure mode:
|
||||
*
|
||||
* return v1ErrorResponseFromCode('PERIOD_LOCKED', log, {
|
||||
* requestId: ctx.requestId,
|
||||
* details: { period_id, locked_at },
|
||||
* validAlternatives: { unlock_endpoint: '/v1/.../fiscal-periods/:id:unlock' },
|
||||
* })
|
||||
*/
|
||||
export async function v1ErrorResponseFromCode(
|
||||
code: string,
|
||||
log: Logger,
|
||||
ctx: V1ErrorContext & { reason?: string },
|
||||
): Promise<NextResponse> {
|
||||
const legacy = legacyErrorResponseFromCode(code, log, {
|
||||
requestId: ctx.requestId,
|
||||
details: ctx.details,
|
||||
status: ctx.status,
|
||||
reason: ctx.reason,
|
||||
})
|
||||
return rewriteEnvelope(legacy, ctx)
|
||||
}
|
||||
|
||||
/** Minimal slice of the v1 route context the validation helpers need. */
|
||||
export interface V1ValidationContext {
|
||||
requestId: string
|
||||
log: Logger
|
||||
}
|
||||
|
||||
/** Structural view of a ZodError: enough to render the v1 issues list. */
|
||||
export interface V1ZodErrorLike {
|
||||
issues: ReadonlyArray<{ path: ReadonlyArray<PropertyKey>; message: string }>
|
||||
}
|
||||
|
||||
/**
|
||||
* Map Zod issues into the `{ field, message }` list the v1 envelope carries
|
||||
* under `details.issues`.
|
||||
*/
|
||||
export function v1ZodIssues(err: V1ZodErrorLike): Array<{ field: string; message: string }> {
|
||||
return err.issues.map((i) => ({
|
||||
field: i.path.join('.'),
|
||||
message: i.message,
|
||||
}))
|
||||
}
|
||||
|
||||
/**
|
||||
* VALIDATION_ERROR envelope for a failed Zod parse:
|
||||
*
|
||||
* const parsed = Schema.safeParse(rawBody)
|
||||
* if (!parsed.success) return v1ValidationError(ctx, parsed.error)
|
||||
*/
|
||||
export async function v1ValidationError(
|
||||
ctx: V1ValidationContext,
|
||||
err: V1ZodErrorLike,
|
||||
): Promise<NextResponse> {
|
||||
return v1ErrorResponseFromCode('VALIDATION_ERROR', ctx.log, {
|
||||
requestId: ctx.requestId,
|
||||
details: {
|
||||
issues: v1ZodIssues(err),
|
||||
},
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,69 @@
|
||||
/**
|
||||
* `?expand=…` query parameter parser for embedding related resources.
|
||||
*
|
||||
* Stripe pattern: a single call returns invoice + customer + line items +
|
||||
* payments instead of forcing the caller to make 4 round-trips. For agents
|
||||
* passing the response into their own context, this is the difference
|
||||
* between 200 and 4000 tokens.
|
||||
*
|
||||
* Each endpoint declares its own allowlist of expandable keys. Unknown
|
||||
* values produce a 400 VALIDATION_ERROR rather than being silently ignored:
|
||||
* agents that typo expansions deserve a clear error.
|
||||
*
|
||||
* Usage:
|
||||
*
|
||||
* const ALLOWED = ['customer', 'items', 'payments'] as const
|
||||
* type ExpandKey = (typeof ALLOWED)[number]
|
||||
* const expand = parseExpand(url, ALLOWED)
|
||||
* // returns: Set<ExpandKey>, empty if no ?expand param
|
||||
*
|
||||
* if (expand.has('customer')) { ... }
|
||||
*/
|
||||
|
||||
export interface ParseExpandResult<K extends string> {
|
||||
ok: true
|
||||
expand: Set<K>
|
||||
}
|
||||
|
||||
export interface ParseExpandError {
|
||||
ok: false
|
||||
invalidKeys: string[]
|
||||
allowed: readonly string[]
|
||||
}
|
||||
|
||||
/**
|
||||
* Parse `?expand=a,b,c` from a URL against a per-endpoint allowlist.
|
||||
*
|
||||
* Returns either `{ ok: true, expand: Set<K> }` for valid input (including
|
||||
* the empty case when the parameter is absent), or `{ ok: false, invalidKeys,
|
||||
* allowed }` listing the unrecognised keys so the caller can build a
|
||||
* VALIDATION_ERROR detail.
|
||||
*
|
||||
* Whitespace around comma-separated keys is trimmed. Duplicate keys collapse
|
||||
* to a single Set entry.
|
||||
*/
|
||||
export function parseExpand<K extends string>(
|
||||
url: URL,
|
||||
allowed: readonly K[],
|
||||
): ParseExpandResult<K> | ParseExpandError {
|
||||
const raw = url.searchParams.get('expand')
|
||||
if (!raw) return { ok: true, expand: new Set<K>() }
|
||||
|
||||
const requested = raw.split(',').map((s) => s.trim()).filter((s) => s.length > 0)
|
||||
const allowedSet = new Set<string>(allowed)
|
||||
const expand = new Set<K>()
|
||||
const invalidKeys: string[] = []
|
||||
|
||||
for (const key of requested) {
|
||||
if (allowedSet.has(key)) {
|
||||
expand.add(key as K)
|
||||
} else if (!invalidKeys.includes(key)) {
|
||||
invalidKeys.push(key)
|
||||
}
|
||||
}
|
||||
|
||||
if (invalidKeys.length > 0) {
|
||||
return { ok: false, invalidKeys, allowed }
|
||||
}
|
||||
return { ok: true, expand }
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
/**
|
||||
* Shared v1 invoice response projections.
|
||||
*
|
||||
* The create (POST), detail (GET), and draft-update (PATCH) endpoints all
|
||||
* return the same invoice shape; keeping the column lists in one module
|
||||
* prevents response-shape drift between them (a PATCH caller must see the
|
||||
* same fields a GET caller does). Explicit projection: excludes user_id,
|
||||
* company_id (internal scoping) and the encrypted personnummer blob
|
||||
* (deduction_personnummer_last4 is the display-safe representation).
|
||||
* Schema migrations adding columns must update these lists before the
|
||||
* field becomes visible on the public API.
|
||||
*/
|
||||
|
||||
export const INVOICE_FULL_COLUMNS =
|
||||
'id, invoice_number, customer_id, invoice_date, due_date, delivery_date, status, currency, exchange_rate, exchange_rate_date, subtotal, subtotal_sek, vat_amount, vat_amount_sek, total, total_sek, ore_rounding, vat_treatment, vat_rate, moms_ruta, your_reference, our_reference, invoice_marking, notes, payment_link_url, stripe_payment_link_id, payment_link_auto, payment_cash_account_id, payment_details, reverse_charge_text, credited_invoice_id, document_type, converted_from_id, valid_until, quote_status, quote_decided_at, paid_at, paid_amount, remaining_amount, default_dimensions, deduction_total, deduction_personnummer_last4, created_at, updated_at'
|
||||
|
||||
/**
|
||||
* Projection for the v1 PDF download route. Narrower than INVOICE_FULL_COLUMNS
|
||||
* (no payment-link/dimension internals), but it MUST contain every column the
|
||||
* render path reads to compute the customer-facing amount: getAmountToPay
|
||||
* derives "Att betala" from total, ore_rounding, deduction_total and
|
||||
* credited_invoice_id, and the same figure is locked into the Swish QR
|
||||
* (editmask 0). A column missing here silently zeroes that part of the
|
||||
* calculation for this surface only: the v1 PDF then disagrees with the
|
||||
* dashboard PDF and the sent email for the same invoice, which is exactly
|
||||
* the byte-equivalence this endpoint promises. delivery_date is statutory
|
||||
* content on top of that: ML 17 kap 24 § requires leveransdatum on the
|
||||
* invoice when it differs from the invoice date, and the template renders it
|
||||
* exactly then. Pinned by __tests__/invoice-columns.test.ts.
|
||||
*/
|
||||
export const INVOICE_PDF_COLUMNS =
|
||||
'id, invoice_number, customer_id, invoice_date, due_date, delivery_date, status, document_type, ' +
|
||||
'currency, subtotal, vat_amount, total, ore_rounding, vat_treatment, vat_rate, moms_ruta, ' +
|
||||
'reverse_charge_text, your_reference, our_reference, invoice_marking, notes, credited_invoice_id, ' +
|
||||
'paid_amount, remaining_amount, deduction_total, deduction_personnummer_last4, ' +
|
||||
// The frozen payee: an issued invoice that chose a bank account must print
|
||||
// that account, not today's company default.
|
||||
'payment_cash_account_id, payment_details'
|
||||
|
||||
export const INVOICE_ITEM_FULL_COLUMNS =
|
||||
'id, sort_order, line_type, description, quantity, unit, unit_price, discount_percent, line_total, vat_rate, vat_amount, article_id, revenue_account, deduction_type, deduction_amount, labor_hours, work_type, housing_designation, apartment_number, brf_org_number, dimensions, sales_order_item_id, created_at'
|
||||
@@ -0,0 +1,192 @@
|
||||
/**
|
||||
* Side-effect import that ensures every v1 route module's top-level
|
||||
* `registerEndpoint()` call has been executed before the OpenAPI generator
|
||||
* reads the registry.
|
||||
*
|
||||
* Why this exists: route files register themselves at module load time. The
|
||||
* OpenAPI endpoint runs in its own module which would otherwise not pull in
|
||||
* the other route files. Importing them here as side-effects populates the
|
||||
* shared `ENDPOINTS` map.
|
||||
*
|
||||
* When a new v1 route is added, append a `import '...'` line.
|
||||
*/
|
||||
|
||||
// Phase 1 surface.
|
||||
import '@/app/api/v1/health/route'
|
||||
import '@/app/api/v1/companies/route'
|
||||
|
||||
// Phase 4 PR-2 (foundation): async operations polling endpoint.
|
||||
import '@/app/api/v1/operations/[id]/route'
|
||||
|
||||
// Phase 4 PR-2: journal-entries primitives + voucher-gap-explanations.
|
||||
import '@/app/api/v1/companies/[companyId]/journal-entries/route'
|
||||
import '@/app/api/v1/companies/[companyId]/journal-entries/[id]/route'
|
||||
import '@/app/api/v1/companies/[companyId]/journal-entries/[id]/commit/route'
|
||||
import '@/app/api/v1/companies/[companyId]/journal-entries/[id]/reverse/route'
|
||||
import '@/app/api/v1/companies/[companyId]/journal-entries/[id]/correct/route'
|
||||
import '@/app/api/v1/companies/[companyId]/journal-entries/batch-create/route'
|
||||
import '@/app/api/v1/companies/[companyId]/voucher-gap-explanations/route'
|
||||
|
||||
// Phase 4 PR-2: compliance-check (Accounted's defensible edge).
|
||||
import '@/app/api/v1/companies/[companyId]/compliance/check/route'
|
||||
|
||||
// Phase 4 PR-2: fiscal-periods async ops (lock/close/year-end/opening-balances/currency-revaluation).
|
||||
import '@/app/api/v1/companies/[companyId]/fiscal-periods/[id]/lock/route'
|
||||
import '@/app/api/v1/companies/[companyId]/fiscal-periods/[id]/close/route'
|
||||
import '@/app/api/v1/companies/[companyId]/fiscal-periods/[id]/year-end/route'
|
||||
import '@/app/api/v1/companies/[companyId]/fiscal-periods/[id]/opening-balances/route'
|
||||
import '@/app/api/v1/companies/[companyId]/fiscal-periods/[id]/currency-revaluation/route'
|
||||
|
||||
// Phase 4 PR-3: Documents (multipart).
|
||||
import '@/app/api/v1/companies/[companyId]/documents/route'
|
||||
import '@/app/api/v1/companies/[companyId]/documents/[id]/download/route'
|
||||
import '@/app/api/v1/companies/[companyId]/documents/[id]/link/route'
|
||||
|
||||
// Phase 2 PR-A: invoice + customer reads.
|
||||
import '@/app/api/v1/companies/[companyId]/invoices/route'
|
||||
import '@/app/api/v1/companies/[companyId]/invoices/[id]/route'
|
||||
import '@/app/api/v1/companies/[companyId]/customers/route'
|
||||
import '@/app/api/v1/companies/[companyId]/customers/[id]/route'
|
||||
// Phase 2 PR-B-2b: invoice action verbs.
|
||||
import '@/app/api/v1/companies/[companyId]/invoices/[id]/mark-sent/route'
|
||||
import '@/app/api/v1/companies/[companyId]/invoices/[id]/mark-paid/route'
|
||||
import '@/app/api/v1/companies/[companyId]/invoices/[id]/credit/route'
|
||||
import '@/app/api/v1/companies/[companyId]/invoices/[id]/send/route'
|
||||
import '@/app/api/v1/companies/[companyId]/invoices/[id]/quote-status/route'
|
||||
import '@/app/api/v1/companies/[companyId]/invoices/bulk-create/route'
|
||||
// Phase 2 PR-B-3: invoice PDF + customer bulk-create.
|
||||
import '@/app/api/v1/companies/[companyId]/invoices/[id]/pdf/route'
|
||||
import '@/app/api/v1/companies/[companyId]/customers/bulk-create/route'
|
||||
|
||||
// Phase 3: transactions + reconciliation vertical.
|
||||
import '@/app/api/v1/companies/[companyId]/transactions/route'
|
||||
import '@/app/api/v1/companies/[companyId]/transactions/[id]/route'
|
||||
import '@/app/api/v1/companies/[companyId]/accounts/route'
|
||||
import '@/app/api/v1/companies/[companyId]/fiscal-periods/route'
|
||||
import '@/app/api/v1/companies/[companyId]/transactions/[id]/categorize/route'
|
||||
import '@/app/api/v1/companies/[companyId]/transactions/[id]/uncategorize/route'
|
||||
import '@/app/api/v1/companies/[companyId]/transactions/[id]/ignore/route'
|
||||
import '@/app/api/v1/companies/[companyId]/transactions/[id]/match-invoice/route'
|
||||
import '@/app/api/v1/companies/[companyId]/transactions/[id]/match-supplier-invoice/route'
|
||||
import '@/app/api/v1/companies/[companyId]/transactions/ingest/route'
|
||||
import '@/app/api/v1/companies/[companyId]/transactions/batch-categorize/route'
|
||||
import '@/app/api/v1/companies/[companyId]/reconciliation/bank/run/route'
|
||||
import '@/app/api/v1/companies/[companyId]/reconciliation/bank/status/route'
|
||||
import '@/app/api/v1/companies/[companyId]/cash-accounts/route'
|
||||
|
||||
// F2: PSD2 bank-connection health (last_synced_at, consent_expires) so
|
||||
// integrations can detect stale bank data instead of trusting it blindly.
|
||||
import '@/app/api/v1/companies/[companyId]/bank-connections/route'
|
||||
import '@/app/api/v1/companies/[companyId]/bank-connections/[connectionId]/sync/route'
|
||||
|
||||
// Phase 4 PR-1: AP world: suppliers + supplier-invoices verticals.
|
||||
import '@/app/api/v1/companies/[companyId]/suppliers/route'
|
||||
import '@/app/api/v1/companies/[companyId]/suppliers/[id]/route'
|
||||
import '@/app/api/v1/companies/[companyId]/suppliers/bulk-create/route'
|
||||
import '@/app/api/v1/companies/[companyId]/supplier-invoices/route'
|
||||
import '@/app/api/v1/companies/[companyId]/supplier-invoices/[id]/route'
|
||||
import '@/app/api/v1/companies/[companyId]/supplier-invoices/[id]/approve/route'
|
||||
import '@/app/api/v1/companies/[companyId]/supplier-invoices/[id]/mark-paid/route'
|
||||
import '@/app/api/v1/companies/[companyId]/supplier-invoices/[id]/credit/route'
|
||||
|
||||
// Phase 5 PR-1: Payroll registers: employees + salary-runs CRUD.
|
||||
import '@/app/api/v1/companies/[companyId]/employees/route'
|
||||
import '@/app/api/v1/companies/[companyId]/employees/[id]/route'
|
||||
import '@/app/api/v1/companies/[companyId]/salary-runs/route'
|
||||
import '@/app/api/v1/companies/[companyId]/salary-runs/[id]/route'
|
||||
|
||||
// Phase 5 PR-2: Payroll lifecycle verbs. The /calculate orchestration was
|
||||
// extracted into lib/salary/run-calculation.ts; the AGI orchestration into
|
||||
// lib/salary/agi/generate-declaration.ts. Both the internal dashboard
|
||||
// routes and these v1 routes call the same helpers.
|
||||
import '@/app/api/v1/companies/[companyId]/salary-runs/[id]/calculate/route'
|
||||
import '@/app/api/v1/companies/[companyId]/salary-runs/[id]/approve/route'
|
||||
import '@/app/api/v1/companies/[companyId]/salary-runs/[id]/mark-paid/route'
|
||||
import '@/app/api/v1/companies/[companyId]/salary-runs/[id]/book/route'
|
||||
import '@/app/api/v1/companies/[companyId]/salary-runs/[id]/generate-agi/route'
|
||||
|
||||
// Payroll gap-closure 1.1: per-employee payslip reads (list + detail + PDF).
|
||||
import '@/app/api/v1/companies/[companyId]/salary-runs/[id]/employees/route'
|
||||
import '@/app/api/v1/companies/[companyId]/salary-runs/[id]/employees/[employeeId]/route'
|
||||
import '@/app/api/v1/companies/[companyId]/salary-runs/[id]/payslips/[employeeId]/pdf/route'
|
||||
|
||||
// Payroll gap-closure 1.2: payslip line writes (draft runs only).
|
||||
import '@/app/api/v1/companies/[companyId]/salary-runs/[id]/employees/[employeeId]/lines/route'
|
||||
import '@/app/api/v1/companies/[companyId]/salary-runs/[id]/lines/[lineId]/route'
|
||||
|
||||
// Payroll gap-closure 1.4: absence (frånvaro) range endpoints.
|
||||
import '@/app/api/v1/companies/[companyId]/employees/[id]/absence/route'
|
||||
|
||||
// Payroll gap-closure 2.3: cutover opening balances (single + atomic bulk).
|
||||
import '@/app/api/v1/companies/[companyId]/employees/[id]/opening-balances/route'
|
||||
import '@/app/api/v1/companies/[companyId]/employees/opening-balances/route'
|
||||
|
||||
// Payroll gap-closure 3.4: vacation ledger + year close.
|
||||
import '@/app/api/v1/companies/[companyId]/employees/[id]/vacation-balance/route'
|
||||
import '@/app/api/v1/companies/[companyId]/salary/vacation-year-close/route'
|
||||
|
||||
// Phase 5 PR-3: Reports + import async. All reports wrap existing
|
||||
// lib/reports/* generators. Imports run inline today but record their
|
||||
// progress on the `operations` table for consistent polling-shape. KPI,
|
||||
// audit-trail, periodisk-sammanstallning, ne-bilaga, and ink2 are deferred
|
||||
// to a follow-up PR (different lib-module structures).
|
||||
import '@/app/api/v1/companies/[companyId]/reports/trial-balance/route'
|
||||
import '@/app/api/v1/companies/[companyId]/reports/balance-sheet/route'
|
||||
import '@/app/api/v1/companies/[companyId]/reports/balance-sheet/pdf/route'
|
||||
import '@/app/api/v1/companies/[companyId]/reports/income-statement/route'
|
||||
import '@/app/api/v1/companies/[companyId]/reports/income-statement/pdf/route'
|
||||
import '@/app/api/v1/companies/[companyId]/reports/general-ledger/route'
|
||||
import '@/app/api/v1/companies/[companyId]/reports/journal-register/route'
|
||||
import '@/app/api/v1/companies/[companyId]/reports/vat-declaration/route'
|
||||
import '@/app/api/v1/companies/[companyId]/reports/monthly-breakdown/route'
|
||||
import '@/app/api/v1/companies/[companyId]/reports/ar-ledger/route'
|
||||
import '@/app/api/v1/companies/[companyId]/reports/supplier-ledger/route'
|
||||
import '@/app/api/v1/companies/[companyId]/reports/continuity-check/route'
|
||||
import '@/app/api/v1/companies/[companyId]/reports/salary-journal/route'
|
||||
import '@/app/api/v1/companies/[companyId]/reports/avgifter-basis/route'
|
||||
import '@/app/api/v1/companies/[companyId]/reports/vacation-liability/route'
|
||||
import '@/app/api/v1/companies/[companyId]/reports/sie-export/route'
|
||||
import '@/app/api/v1/companies/[companyId]/imports/sie/route'
|
||||
import '@/app/api/v1/companies/[companyId]/imports/bank/route'
|
||||
|
||||
// Phase 6 PR-1: webhooks substrate.
|
||||
import '@/app/api/v1/companies/[companyId]/webhooks/route'
|
||||
import '@/app/api/v1/companies/[companyId]/webhooks/[id]/route'
|
||||
import '@/app/api/v1/companies/[companyId]/webhooks/[id]/test/route'
|
||||
import '@/app/api/v1/companies/[companyId]/webhooks/[id]/deliveries/route'
|
||||
import '@/app/api/v1/webhook-deliveries/[id]/retry/route'
|
||||
|
||||
// Phase 6 PR-3: webhook secret rotation.
|
||||
import '@/app/api/v1/companies/[companyId]/webhooks/[id]/rotate-secret/route'
|
||||
|
||||
// Inbox item stamp.
|
||||
import '@/app/api/v1/companies/[companyId]/inbox-items/[id]/stamp/route'
|
||||
|
||||
// Reconciliation, account-keyed (bank:<cash_account_id> | skattekonto): the
|
||||
// account list, the bridge per account, item buckets, links and ignore flags.
|
||||
import '@/app/api/v1/companies/[companyId]/reconciliation/accounts/route'
|
||||
import '@/app/api/v1/companies/[companyId]/reconciliation/accounts/[accountKey]/route'
|
||||
import '@/app/api/v1/companies/[companyId]/reconciliation/accounts/[accountKey]/items/route'
|
||||
import '@/app/api/v1/companies/[companyId]/reconciliation/accounts/[accountKey]/links/route'
|
||||
import '@/app/api/v1/companies/[companyId]/reconciliation/accounts/[accountKey]/links/[linkId]/route'
|
||||
import '@/app/api/v1/companies/[companyId]/reconciliation/accounts/[accountKey]/items/[itemId]/ignore/route'
|
||||
import '@/app/api/v1/companies/[companyId]/reconciliation/accounts/[accountKey]/signoff/route'
|
||||
import '@/app/api/v1/companies/[companyId]/reconciliation/accounts/[accountKey]/signoff/[signoffId]/reopen/route'
|
||||
import '@/app/api/v1/companies/[companyId]/reconciliation/accounts/[accountKey]/residual/route'
|
||||
|
||||
// Dimensions PR2: registry list + value creation (kostnadsställe/projekt).
|
||||
import '@/app/api/v1/companies/[companyId]/dimensions/route'
|
||||
import '@/app/api/v1/companies/[companyId]/dimensions/[id]/values/route'
|
||||
// #895: value lifecycle (rename/archive/end-date + delete-unreferenced).
|
||||
import '@/app/api/v1/companies/[companyId]/dimensions/[id]/values/[valueId]/route'
|
||||
|
||||
// #895: articles read (artikelregister) for invoice line linkage.
|
||||
import '@/app/api/v1/companies/[companyId]/articles/route'
|
||||
|
||||
// #1348: company-settings write (PATCH, MCP-tool-identical field set).
|
||||
import '@/app/api/v1/companies/[companyId]/settings/route'
|
||||
|
||||
// #1663: filed momsdeklaration read (SKV inlamnat/beslutat).
|
||||
import '@/app/api/v1/companies/[companyId]/skatteverket/vat-declarations/route'
|
||||
|
||||
export {}
|
||||
@@ -0,0 +1,21 @@
|
||||
/**
|
||||
* Personnummer masking for v1 list/create responses.
|
||||
*
|
||||
* GDPR Art.5(1)(c): data minimisation. A Swedish personnummer is a
|
||||
* national identifier; the list endpoint and create-response shape mask
|
||||
* the last 4 digits (the gender + checksum) so a roster scan or a
|
||||
* mistaken response log doesn't leak a natural-person identifier. The
|
||||
* detail endpoint (deliberate drill-in) returns the full value.
|
||||
*
|
||||
* Format: ÅÅÅÅMMDDNNNN → ÅÅÅÅMMDDXXXX.
|
||||
*
|
||||
* Defensive behavior: if the input is not exactly 12 digits, the full
|
||||
* value is redacted to all-X. A short-form (10-digit) personnummer
|
||||
* should never reach the database (the schema regex rejects it), but
|
||||
* legacy rows or test fixtures might; redacting entirely is safer than
|
||||
* leaking a partially-masked legacy value.
|
||||
*/
|
||||
export function maskPersonnummer(pnr: string | null | undefined): string {
|
||||
if (!pnr || !/^\d{12}$/.test(pnr)) return 'XXXXXXXXXXXX'
|
||||
return `${pnr.slice(0, 8)}XXXX`
|
||||
}
|
||||
@@ -0,0 +1,186 @@
|
||||
/**
|
||||
* v1 async-operation lifecycle helpers.
|
||||
*
|
||||
* Substrate: the `operations` table (separate from `pending_operations`).
|
||||
*
|
||||
* Design:
|
||||
* - POST handlers that start a long-running job call `startOperation()`
|
||||
* to insert a row (status='running', started_at=now) and return its id.
|
||||
* - The handler then runs the work (synchronously in Phase 4 PR-2; a
|
||||
* future cron worker can take over by picking up `queued` rows).
|
||||
* - On success: `completeOperation(id, result)`. On failure:
|
||||
* `failOperation(id, error)`. Both stamp `completed_at`.
|
||||
* - The 202 envelope is built by the helper, so call sites only need to
|
||||
* return what it gives back.
|
||||
*
|
||||
* The shape stays stable when (or if) we move to true out-of-band processing:
|
||||
* the POST simply leaves the row at status='queued' for a worker to pick up,
|
||||
* the response is identical, and the GET poll endpoint surfaces progress as
|
||||
* the worker updates it.
|
||||
*/
|
||||
|
||||
import type { SupabaseClient } from '@supabase/supabase-js'
|
||||
import type { Logger } from '@/lib/logger'
|
||||
|
||||
export type OperationStatus = 'queued' | 'running' | 'succeeded' | 'failed' | 'cancelled'
|
||||
|
||||
export interface OperationProgress {
|
||||
/** Optional human-readable phase label (e.g. 'parsing', 'committing'). */
|
||||
phase?: string
|
||||
/** Optional unit counters for percent calculation client-side. */
|
||||
current?: number
|
||||
total?: number
|
||||
/** Free-form additional fields: kept under jsonb so additions don't migrate. */
|
||||
[k: string]: unknown
|
||||
}
|
||||
|
||||
export interface OperationRow {
|
||||
id: string
|
||||
company_id: string
|
||||
user_id: string
|
||||
operation_type: string
|
||||
status: OperationStatus
|
||||
started_at: string | null
|
||||
completed_at: string | null
|
||||
params: Record<string, unknown>
|
||||
progress: OperationProgress
|
||||
result: unknown
|
||||
error: { code?: string; message?: string; details?: unknown } | null
|
||||
created_at: string
|
||||
updated_at: string
|
||||
}
|
||||
|
||||
/**
|
||||
* Insert a new operation row in `running` status (start_at=now). Returns the
|
||||
* id the POST handler should report back. The caller continues with the work
|
||||
* and then resolves via `completeOperation` / `failOperation`.
|
||||
*
|
||||
* For true async dispatch (future cron worker), pass `status='queued'` and
|
||||
* leave `started_at` null: the worker stamps it when it picks the row up.
|
||||
*/
|
||||
export async function startOperation(
|
||||
supabase: SupabaseClient,
|
||||
args: {
|
||||
companyId: string
|
||||
userId: string
|
||||
operationType: string
|
||||
params?: Record<string, unknown>
|
||||
/** Default `'running'` for inline execution; `'queued'` for worker dispatch. */
|
||||
initialStatus?: Extract<OperationStatus, 'queued' | 'running'>
|
||||
},
|
||||
log: Logger,
|
||||
): Promise<{ id: string }> {
|
||||
const initialStatus = args.initialStatus ?? 'running'
|
||||
const startedAt = initialStatus === 'running' ? new Date().toISOString() : null
|
||||
|
||||
const { data, error } = await supabase
|
||||
.from('operations')
|
||||
.insert({
|
||||
company_id: args.companyId,
|
||||
user_id: args.userId,
|
||||
operation_type: args.operationType,
|
||||
status: initialStatus,
|
||||
started_at: startedAt,
|
||||
params: args.params ?? {},
|
||||
})
|
||||
.select('id')
|
||||
.single()
|
||||
|
||||
if (error || !data) {
|
||||
log.error('startOperation insert failed', error as Error, {
|
||||
companyId: args.companyId,
|
||||
operationType: args.operationType,
|
||||
})
|
||||
throw new Error('Failed to record operation start')
|
||||
}
|
||||
return { id: (data as { id: string }).id }
|
||||
}
|
||||
|
||||
/**
|
||||
* Mark an operation as succeeded. Stamps `completed_at` and persists `result`.
|
||||
* Best-effort: a failure to record the success doesn't roll back the work
|
||||
* (the work already committed to the DB via whatever engine call ran).
|
||||
*/
|
||||
export async function completeOperation(
|
||||
supabase: SupabaseClient,
|
||||
args: { id: string; result: unknown; finalProgress?: OperationProgress },
|
||||
log: Logger,
|
||||
): Promise<void> {
|
||||
const { error } = await supabase
|
||||
.from('operations')
|
||||
.update({
|
||||
status: 'succeeded',
|
||||
completed_at: new Date().toISOString(),
|
||||
result: args.result,
|
||||
...(args.finalProgress ? { progress: args.finalProgress } : {}),
|
||||
})
|
||||
.eq('id', args.id)
|
||||
if (error) {
|
||||
log.warn('completeOperation update failed', { operationId: args.id, errorCode: error.code })
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Mark an operation as failed. Stamps `completed_at` and persists `error`.
|
||||
* The caller has already converted the underlying error into a structured
|
||||
* code+message envelope.
|
||||
*/
|
||||
export async function failOperation(
|
||||
supabase: SupabaseClient,
|
||||
args: {
|
||||
id: string
|
||||
error: { code: string; message: string; details?: unknown }
|
||||
finalProgress?: OperationProgress
|
||||
},
|
||||
log: Logger,
|
||||
): Promise<void> {
|
||||
const { error } = await supabase
|
||||
.from('operations')
|
||||
.update({
|
||||
status: 'failed',
|
||||
completed_at: new Date().toISOString(),
|
||||
error: args.error,
|
||||
...(args.finalProgress ? { progress: args.finalProgress } : {}),
|
||||
})
|
||||
.eq('id', args.id)
|
||||
if (error) {
|
||||
log.warn('failOperation update failed', { operationId: args.id, errorCode: error.code })
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Update progress on a running operation. Non-blocking: a write failure is
|
||||
* logged but not raised: the work continues regardless.
|
||||
*/
|
||||
export async function updateOperationProgress(
|
||||
supabase: SupabaseClient,
|
||||
args: { id: string; progress: OperationProgress },
|
||||
log: Logger,
|
||||
): Promise<void> {
|
||||
const { error } = await supabase
|
||||
.from('operations')
|
||||
.update({ progress: args.progress })
|
||||
.eq('id', args.id)
|
||||
if (error) {
|
||||
log.warn('updateOperationProgress failed', { operationId: args.id, errorCode: error.code })
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Read an operation row, scoped to the caller's company. Returns null when
|
||||
* the id is not found (or belongs to another company; RLS already excludes
|
||||
* those, but the explicit `.eq('company_id')` keeps the contract clear).
|
||||
*/
|
||||
export async function getOperation(
|
||||
supabase: SupabaseClient,
|
||||
args: { id: string; companyId: string },
|
||||
): Promise<OperationRow | null> {
|
||||
const { data, error } = await supabase
|
||||
.from('operations')
|
||||
.select('id, company_id, user_id, operation_type, status, started_at, completed_at, params, progress, result, error, created_at, updated_at')
|
||||
.eq('id', args.id)
|
||||
.eq('company_id', args.companyId)
|
||||
.maybeSingle()
|
||||
if (error || !data) return null
|
||||
return data as OperationRow
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
/**
|
||||
* Defense-in-depth ownership check for caller-supplied `fiscal_period_id`
|
||||
* inputs. Every v1 endpoint that accepts a fiscal_period_id in the request
|
||||
* body / query string must call this BEFORE handing the id to the engine.
|
||||
*
|
||||
* Why this exists:
|
||||
* - The engine functions all scope by company_id internally
|
||||
* (`createDraftEntry`, `generateOpeningBalances`, etc), so there is no
|
||||
* literal cross-tenant data leak today.
|
||||
* - But the engine throws Swedish error strings on mismatch
|
||||
* ("Fiscal period not found"), and the route layer would otherwise have
|
||||
* to scrape that string to produce a structured error envelope.
|
||||
* - More importantly, an INSERT that takes both `company_id` (from URL)
|
||||
* and `fiscal_period_id` (from body) without verifying they belong
|
||||
* together creates a broken-link state: the row persists with a
|
||||
* pointer at another company's period. Downstream queries return
|
||||
* garbage even though no data was leaked. See:
|
||||
* - voucher_gap_explanations: detect_voucher_gaps would never match.
|
||||
* - journal_entries: balance triggers fire against the wrong period.
|
||||
*
|
||||
* Use everywhere a `fiscal_period_id` enters the system from the caller.
|
||||
*/
|
||||
|
||||
import type { SupabaseClient } from '@supabase/supabase-js'
|
||||
|
||||
/**
|
||||
* Returns true when (fiscal_period_id, company_id) is a real pairing in the
|
||||
* `fiscal_periods` table. Cheap point lookup; the caller maps `false` to a
|
||||
* structured NOT_FOUND or VALIDATION_ERROR envelope as appropriate.
|
||||
*
|
||||
* Cross-period checks that need additional state (is_closed, locked_at)
|
||||
* should still go through `checkPeriodLock`; this helper only answers the
|
||||
* ownership question.
|
||||
*/
|
||||
export async function ownsFiscalPeriod(
|
||||
supabase: SupabaseClient,
|
||||
companyId: string,
|
||||
fiscalPeriodId: string,
|
||||
): Promise<boolean> {
|
||||
const { data } = await supabase
|
||||
.from('fiscal_periods')
|
||||
.select('id')
|
||||
.eq('id', fiscalPeriodId)
|
||||
.eq('company_id', companyId)
|
||||
.maybeSingle()
|
||||
return !!data
|
||||
}
|
||||
@@ -0,0 +1,120 @@
|
||||
/**
|
||||
* Cursor-based pagination for v1 list endpoints.
|
||||
*
|
||||
* Cursors are opaque base64-JSON tokens encoding the keyset position. The
|
||||
* default key is `(created_at, id)`, which is stable across concurrent writes:
|
||||
* a row inserted after a cursor was minted appears in a later page, never
|
||||
* mid-page. Endpoints that need a different sort key supply their own
|
||||
* encoder/decoder pair.
|
||||
*
|
||||
* Limits are clamped to [1, 100]; default 50.
|
||||
*
|
||||
* Cursors are NOT signed or encrypted: they reveal only sort-key values that
|
||||
* the user could already see from a previous page. Treat them as ephemeral
|
||||
* pagination hints, not security tokens.
|
||||
*/
|
||||
|
||||
import { UUID_RE as UUID } from '@/lib/invariants/uuid'
|
||||
|
||||
export const DEFAULT_LIMIT = 50
|
||||
export const MAX_LIMIT = 100
|
||||
|
||||
export interface PaginationParams {
|
||||
limit: number
|
||||
cursor: string | null
|
||||
}
|
||||
|
||||
/**
|
||||
* Parse `?cursor=...&limit=...` from a URL. Returns a normalized
|
||||
* { limit, cursor } pair with limit clamped to [1, MAX_LIMIT].
|
||||
*
|
||||
* Invalid `limit` (non-numeric, negative) falls back to DEFAULT_LIMIT rather
|
||||
* than throwing: callers can always re-validate via Zod if strictness is
|
||||
* needed.
|
||||
*/
|
||||
export function parsePaginationParams(url: URL): PaginationParams {
|
||||
const rawLimit = url.searchParams.get('limit')
|
||||
const cursor = url.searchParams.get('cursor')
|
||||
|
||||
let limit = DEFAULT_LIMIT
|
||||
if (rawLimit !== null) {
|
||||
const parsed = Number.parseInt(rawLimit, 10)
|
||||
if (Number.isFinite(parsed) && parsed > 0) {
|
||||
limit = Math.min(parsed, MAX_LIMIT)
|
||||
}
|
||||
}
|
||||
|
||||
return { limit, cursor: cursor && cursor.length > 0 ? cursor : null }
|
||||
}
|
||||
|
||||
// ─────────────────────────────────────────────────────────────────
|
||||
// Default (created_at, id) keyset cursor
|
||||
// ─────────────────────────────────────────────────────────────────
|
||||
|
||||
export interface DefaultCursor {
|
||||
/** ISO 8601 timestamp of the boundary row's created_at. */
|
||||
ts: string
|
||||
/** UUID of the boundary row. Disambiguates rows with identical timestamps. */
|
||||
id: string
|
||||
}
|
||||
|
||||
/**
|
||||
* Encode a (created_at, id) boundary into an opaque cursor string.
|
||||
* Returns null when the input is null/undefined so callers can write
|
||||
* `next_cursor: encodeDefaultCursor(lastRow)` without a conditional.
|
||||
*/
|
||||
export function encodeDefaultCursor(row: { created_at: string; id: string } | null | undefined): string | null {
|
||||
if (!row) return null
|
||||
const payload: DefaultCursor = { ts: row.created_at, id: row.id }
|
||||
return Buffer.from(JSON.stringify(payload), 'utf8').toString('base64url')
|
||||
}
|
||||
|
||||
// Strict format guards: defence-in-depth against tampered cursors that
|
||||
// could otherwise inject untyped strings into a query's `.gt(field, value)`.
|
||||
// PostgREST would likely reject these, but validating here keeps the failure
|
||||
// mode predictable (stale cursor → "start over") rather than 400-ing.
|
||||
const ISO_TIMESTAMP = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d+)?(Z|[+-]\d{2}:?\d{2})$/
|
||||
|
||||
/**
|
||||
* Decode a cursor produced by encodeDefaultCursor. Returns null when the
|
||||
* input is missing or malformed: callers should treat null as "start from
|
||||
* the beginning" rather than 400-ing on a stale cursor.
|
||||
*
|
||||
* `ts` must parse as an ISO 8601 timestamp and `id` must be a UUID; anything
|
||||
* else is treated as a stale/corrupt cursor and discarded.
|
||||
*/
|
||||
export function decodeDefaultCursor(cursor: string | null | undefined): DefaultCursor | null {
|
||||
if (!cursor) return null
|
||||
try {
|
||||
const json = Buffer.from(cursor, 'base64url').toString('utf8')
|
||||
const parsed = JSON.parse(json) as Partial<DefaultCursor>
|
||||
if (typeof parsed.ts !== 'string' || typeof parsed.id !== 'string') return null
|
||||
if (!ISO_TIMESTAMP.test(parsed.ts)) return null
|
||||
if (!UUID.test(parsed.id)) return null
|
||||
return { ts: parsed.ts, id: parsed.id }
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Convenience: given a result page and the requested limit, return the
|
||||
* cursor for the *next* page (or null when this was the final page).
|
||||
*
|
||||
* Convention: the caller fetches `limit + 1` rows, passes the full slice in,
|
||||
* and we return either the cursor of the LAST ROW OF THE TRIMMED PAGE
|
||||
* (rows[limit - 1]) or null when the page wasn't full. The caller should then
|
||||
* trim the slice to `limit` before returning it to the user.
|
||||
*
|
||||
* Contract: the cursor marks the last row already returned; every v1 route's
|
||||
* keyset predicate is strictly greater/less than the cursor, so encoding
|
||||
* rows[limit] (the first row of the NEXT page) would skip that row at every
|
||||
* page boundary.
|
||||
*/
|
||||
export function nextCursorFromPage<T extends { created_at: string; id: string }>(
|
||||
rows: T[],
|
||||
limit: number,
|
||||
): string | null {
|
||||
if (rows.length <= limit) return null
|
||||
return encodeDefaultCursor(rows[limit - 1])
|
||||
}
|
||||
@@ -0,0 +1,512 @@
|
||||
/**
|
||||
* Single source of truth for the v1 REST surface.
|
||||
*
|
||||
* Every endpoint registers its Zod request/response schemas + agent-facing
|
||||
* metadata (description, use-when, do-not-use-for, pitfalls, example) +
|
||||
* OpenAPI `x-*` extensions (`x-action-risk`, `x-idempotent`, `x-reversible`,
|
||||
* `x-dry-run-supported`).
|
||||
*
|
||||
* Three artefacts are derived from this registry:
|
||||
* 1. The OpenAPI 3.1 spec at /api/v1/openapi.json (this file).
|
||||
* 2. The MCP tool list (future: Phase 5).
|
||||
* 3. Runtime validators (Zod itself, used by handlers).
|
||||
*
|
||||
* Phase 1 ships a minimal Zod→JSON-Schema converter. Phase 2 will swap in
|
||||
* `@asteasolutions/zod-to-openapi` once the schema surface justifies the
|
||||
* dependency. The registry shape stays stable across that change.
|
||||
*/
|
||||
|
||||
import { z } from 'zod'
|
||||
import type { ZodTypeAny } from 'zod'
|
||||
import type { ApiKeyScope } from '@/lib/auth/api-keys'
|
||||
import { API_V1_VERSION } from './version'
|
||||
|
||||
/**
|
||||
* The audit block surfaced inline on write responses (see `AuditBlock` in
|
||||
* `lib/api/v1/response.ts`) so an agent gets the voucher number / audit-trail
|
||||
* URL without a second round-trip. Every field is optional.
|
||||
*/
|
||||
const ResponseAuditSchema = z.object({
|
||||
voucher_number: z.string().optional(),
|
||||
voucher_url: z.string().optional(),
|
||||
audit_trail_url: z.string().optional(),
|
||||
immutable_at: z.string().optional(),
|
||||
})
|
||||
|
||||
/**
|
||||
* The `meta` block echoed in every v1 response envelope (see
|
||||
* `lib/api/v1/response.ts`). List endpoints additionally populate
|
||||
* `next_cursor`; it is absent on the final page. Writes may surface an
|
||||
* `audit` block, and soft-degraded `?expand=` responses a `partial_expansions`
|
||||
* list: both optional, so reads and lists omit them.
|
||||
*/
|
||||
export const ResponseMetaSchema = z.object({
|
||||
request_id: z.string(),
|
||||
api_version: z.string(),
|
||||
next_cursor: z.string().nullable().optional(),
|
||||
audit: ResponseAuditSchema.optional(),
|
||||
partial_expansions: z.array(z.string()).optional(),
|
||||
// Endpoint-specific register-coverage disclosure (e.g. invoices.list:
|
||||
// { covers_from, has_pre_register_invoices }). Documented per endpoint.
|
||||
coverage: z.record(z.string(), z.unknown()).optional(),
|
||||
})
|
||||
|
||||
/**
|
||||
* The `{ data, meta }` envelope that every list endpoint actually returns via
|
||||
* `paginated()`. Declare a list endpoint's `response.success` with this so the
|
||||
* OpenAPI contract matches the runtime body.
|
||||
*
|
||||
* Previously each list endpoint declared a bare `{ <name>: [...] }` success
|
||||
* object (e.g. `{ companies: [...] }`) that no handler ever emits: the
|
||||
* generated spec advertised a shape the API never returns. See issue #781.
|
||||
*/
|
||||
export function listEnvelope<T extends ZodTypeAny>(item: T) {
|
||||
return z.object({
|
||||
data: z.array(item),
|
||||
meta: ResponseMetaSchema,
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* The `{ data, meta }` envelope for an endpoint that returns a single OBJECT
|
||||
* under `data` (via `ok()`), rather than a bare array under `data`.
|
||||
*
|
||||
* Most list endpoints return `{ data: [...] }` (use {@link listEnvelope}). A
|
||||
* few (`accounts`, `fiscal-periods`, `webhooks`) deliberately wrap their
|
||||
* array in a named key (`{ data: { accounts: [...] } }`); their handlers and
|
||||
* route tests lock that shape in. Declare those with
|
||||
* `dataEnvelope(z.object({ <name>: z.array(Item) }))` so the OpenAPI contract
|
||||
* matches what they actually return.
|
||||
*/
|
||||
export function dataEnvelope<T extends ZodTypeAny>(data: T) {
|
||||
return z.object({
|
||||
data,
|
||||
meta: ResponseMetaSchema,
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* Sentinel `response.success` for endpoints that return 204 No Content with an
|
||||
* empty body: e.g. DELETE handlers calling `noContent()`. The OpenAPI
|
||||
* generator emits a bare `204` response (no schema) for these instead of a
|
||||
* `200 { data, meta }`, and the envelope contract test exempts them.
|
||||
*
|
||||
* Identified by REFERENCE equality, so every 204 route MUST import this exact
|
||||
* constant rather than declaring its own `z.object({})`: that is what lets the
|
||||
* generator and the contract test recognise the "no body" intent.
|
||||
*/
|
||||
export const NoBodyResponse = z.object({})
|
||||
|
||||
export type HttpMethod = 'GET' | 'POST' | 'PATCH' | 'PUT' | 'DELETE'
|
||||
|
||||
export type ActionRisk = 'low' | 'medium' | 'high'
|
||||
|
||||
export interface EndpointDefinition {
|
||||
/** HTTP method + path pattern, e.g. 'GET /api/v1/companies'. */
|
||||
operation: string
|
||||
method: HttpMethod
|
||||
path: string
|
||||
|
||||
/** One-sentence summary; first sentence of the OpenAPI description. */
|
||||
summary: string
|
||||
|
||||
/** Longer prose for the docs and the registered MCP tool description. */
|
||||
description: string
|
||||
|
||||
/** Positive trigger: when should an agent reach for this endpoint? */
|
||||
useWhen: string
|
||||
|
||||
/** Negative trigger: what looks similar but isn't this. */
|
||||
doNotUseFor: string
|
||||
|
||||
/** Common pitfalls. Bullet-list style; agents see this in tool docs. */
|
||||
pitfalls: string[]
|
||||
|
||||
/** One worked example (used by the contract-test suite). */
|
||||
example: {
|
||||
request?: Record<string, unknown>
|
||||
response: Record<string, unknown>
|
||||
}
|
||||
|
||||
/** Required scope; null for public endpoints. */
|
||||
scope: ApiKeyScope | null
|
||||
|
||||
/** Action risk: informs whether the agent should confirm before calling. */
|
||||
risk: ActionRisk
|
||||
|
||||
/** True for GET requests and well-known idempotent writes. */
|
||||
idempotent: boolean
|
||||
|
||||
/** True for writes that can be undone by a single subsequent call (e.g. credit invoice). */
|
||||
reversible: boolean
|
||||
|
||||
/** True for write endpoints that accept ?dry_run=true. */
|
||||
dryRunSupported: boolean
|
||||
|
||||
/** Optional Zod schemas. */
|
||||
request?: {
|
||||
/** Path params (companyId, id, ...). */
|
||||
params?: ZodTypeAny
|
||||
/** Query params. */
|
||||
query?: ZodTypeAny
|
||||
/** Request body. */
|
||||
body?: ZodTypeAny
|
||||
/**
|
||||
* Body content-type. Defaults to 'application/json' when omitted.
|
||||
* Set to 'multipart/form-data' for upload endpoints (Phase 4 PR-3:
|
||||
* documents). The OpenAPI generator emits the appropriate schema
|
||||
* (`{ type: 'string', format: 'binary' }` for the file part) so
|
||||
* code generators produce correct multipart clients.
|
||||
*/
|
||||
contentType?: 'application/json' | 'multipart/form-data'
|
||||
}
|
||||
response: {
|
||||
/** Successful response body. */
|
||||
success: ZodTypeAny
|
||||
/** Stable error codes this endpoint can emit (cross-referenced with the docs). */
|
||||
errorCodes?: string[]
|
||||
/**
|
||||
* Override the default 'application/json' content type for non-JSON
|
||||
* responses (e.g. binary downloads). When set to 'application/pdf', the
|
||||
* OpenAPI generator emits a `{ type: 'string', format: 'binary' }` schema
|
||||
* instead of deriving from `success`. The `success` schema is still
|
||||
* required (use `z.unknown()` as a marker) so existing registry consumers
|
||||
* don't need to handle a missing field.
|
||||
*/
|
||||
contentType?: string
|
||||
}
|
||||
}
|
||||
|
||||
const ENDPOINTS = new Map<string, EndpointDefinition>()
|
||||
|
||||
/**
|
||||
* Register an endpoint. Called from the route file at module load time:
|
||||
*
|
||||
* registerEndpoint({
|
||||
* operation: 'companies.list',
|
||||
* method: 'GET',
|
||||
* path: '/api/v1/companies',
|
||||
* ...
|
||||
* })
|
||||
*
|
||||
* The wrapper does not depend on registration: scope resolution lives in
|
||||
* `lib/auth/scopes.ts` so a missing register() call only affects docs, not
|
||||
* runtime auth. CI test asserts every wrapped route appears in the registry.
|
||||
*/
|
||||
export function registerEndpoint(def: EndpointDefinition): void {
|
||||
const key = `${def.method} ${def.path}`
|
||||
if (ENDPOINTS.has(key)) {
|
||||
// Duplicate registration is a bug: log loudly. Throwing during a route
|
||||
// module's top-level eval would break unrelated routes; warn instead.
|
||||
// eslint-disable-next-line no-console
|
||||
console.warn(`[api/v1/registry] duplicate endpoint registration: ${key}`)
|
||||
}
|
||||
ENDPOINTS.set(key, def)
|
||||
}
|
||||
|
||||
export function listEndpoints(): EndpointDefinition[] {
|
||||
return Array.from(ENDPOINTS.values())
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Resolve the registered endpoint for a CONCRETE request path (e.g.
|
||||
* `/api/v1/companies/abc/customers`) by matching it against the registered
|
||||
* `:param` patterns. Used by the wrapper to read an endpoint's `dryRunSupported`
|
||||
* flag at request time: the route module being served has already run its
|
||||
* `registerEndpoint()` call, so its pattern is present. Returns undefined when
|
||||
* no pattern matches (the wrapper treats that as "cannot be simulated").
|
||||
*/
|
||||
export function getEndpointByConcretePath(
|
||||
method: string,
|
||||
concretePath: string,
|
||||
): EndpointDefinition | undefined {
|
||||
for (const def of ENDPOINTS.values()) {
|
||||
if (def.method !== method) continue
|
||||
const regex = new RegExp('^' + def.path.replace(/:[^/]+/g, '[^/]+') + '$')
|
||||
if (regex.test(concretePath)) return def
|
||||
}
|
||||
return undefined
|
||||
}
|
||||
|
||||
// ──────────────────────────────────────────────────────────────────
|
||||
// Minimal Zod → JSON Schema converter
|
||||
// ──────────────────────────────────────────────────────────────────
|
||||
// Phase 1 only registers a handful of endpoints with simple schemas. We
|
||||
// implement just enough to cover them: object, string, number, boolean,
|
||||
// uuid, array, optional, enum, literal, date-string. When the registry
|
||||
// surface grows past Phase 2, swap this for @asteasolutions/zod-to-openapi.
|
||||
|
||||
interface JsonSchema {
|
||||
type?: string | string[]
|
||||
properties?: Record<string, JsonSchema>
|
||||
required?: string[]
|
||||
items?: JsonSchema
|
||||
enum?: unknown[]
|
||||
const?: unknown
|
||||
format?: string
|
||||
description?: string
|
||||
additionalProperties?: boolean | JsonSchema
|
||||
}
|
||||
|
||||
function zodToJsonSchema(schema: ZodTypeAny): JsonSchema {
|
||||
const def = (schema as unknown as { _def: { typeName?: string; type?: string } })._def
|
||||
|
||||
// Zod 4 uses string discriminators on _def.type ('string', 'object', etc.).
|
||||
// Fall back to the legacy typeName for cross-version safety.
|
||||
const discriminator = def.type ?? def.typeName ?? ''
|
||||
|
||||
switch (discriminator) {
|
||||
case 'string':
|
||||
case 'ZodString':
|
||||
return { type: 'string' }
|
||||
case 'number':
|
||||
case 'ZodNumber':
|
||||
return { type: 'number' }
|
||||
case 'boolean':
|
||||
case 'ZodBoolean':
|
||||
return { type: 'boolean' }
|
||||
case 'array':
|
||||
case 'ZodArray': {
|
||||
const inner = (def as { element?: ZodTypeAny; type?: ZodTypeAny }).element
|
||||
?? (def as { type?: ZodTypeAny }).type
|
||||
return { type: 'array', items: inner ? zodToJsonSchema(inner) : {} }
|
||||
}
|
||||
case 'optional':
|
||||
case 'ZodOptional':
|
||||
case 'nullable':
|
||||
case 'ZodNullable':
|
||||
// A `.default()` field accepts the inner type on input; the object case
|
||||
// below additionally treats it as not-required.
|
||||
case 'default':
|
||||
case 'ZodDefault': {
|
||||
const inner = (def as { innerType: ZodTypeAny }).innerType
|
||||
return zodToJsonSchema(inner)
|
||||
}
|
||||
case 'record':
|
||||
case 'ZodRecord': {
|
||||
const valueType = (def as { valueType?: ZodTypeAny }).valueType
|
||||
return {
|
||||
type: 'object',
|
||||
additionalProperties: valueType ? zodToJsonSchema(valueType) : true,
|
||||
}
|
||||
}
|
||||
// `.transform()` / `.pipe()` wrappers: describe the INPUT side, which is
|
||||
// what an API caller must send. `z.preprocess()` is the mirror image:
|
||||
// its input side IS the callable (a ZodTransform, no describable type),
|
||||
// and the schema the cleaned value must satisfy sits on the output side.
|
||||
case 'pipe':
|
||||
case 'ZodPipeline': {
|
||||
const pipeDef = def as { in?: ZodTypeAny; out?: ZodTypeAny }
|
||||
const inDef = (pipeDef.in as unknown as { _def?: { type?: string; typeName?: string } } | undefined)?._def
|
||||
const inDisc = inDef?.type ?? inDef?.typeName ?? ''
|
||||
const side = ['transform', 'ZodEffects'].includes(inDisc) ? pipeDef.out : pipeDef.in
|
||||
return side ? zodToJsonSchema(side) : {}
|
||||
}
|
||||
case 'effects':
|
||||
case 'ZodEffects': {
|
||||
const inner = (def as { schema?: ZodTypeAny }).schema
|
||||
return inner ? zodToJsonSchema(inner) : {}
|
||||
}
|
||||
case 'object':
|
||||
case 'ZodObject': {
|
||||
const shape = (schema as unknown as { shape: Record<string, ZodTypeAny> }).shape
|
||||
const properties: Record<string, JsonSchema> = {}
|
||||
const required: string[] = []
|
||||
for (const [key, value] of Object.entries(shape)) {
|
||||
properties[key] = zodToJsonSchema(value)
|
||||
// A field may be omitted exactly when the schema accepts undefined:
|
||||
// covers optional and defaulted fields, and wrappers that only carry
|
||||
// optionality inside (e.g. a preprocess pipe over `.optional()`),
|
||||
// which a top-level discriminator check misclassifies as required.
|
||||
const mayOmit = value.safeParse(undefined).success
|
||||
if (!mayOmit) {
|
||||
required.push(key)
|
||||
}
|
||||
}
|
||||
return {
|
||||
type: 'object',
|
||||
properties,
|
||||
...(required.length > 0 ? { required } : {}),
|
||||
additionalProperties: false,
|
||||
}
|
||||
}
|
||||
case 'enum':
|
||||
case 'ZodEnum': {
|
||||
const enumDef = def as { values?: unknown[]; entries?: Record<string, unknown> }
|
||||
const values =
|
||||
enumDef.values ??
|
||||
(enumDef.entries ? Object.values(enumDef.entries) : [])
|
||||
return { type: 'string', enum: values }
|
||||
}
|
||||
case 'literal':
|
||||
case 'ZodLiteral': {
|
||||
const value = (def as { value?: unknown; values?: unknown[] }).value
|
||||
?? (def as { values?: unknown[] }).values?.[0]
|
||||
return { const: value }
|
||||
}
|
||||
case 'union':
|
||||
case 'ZodUnion': {
|
||||
// Best-effort: emit a oneOf with each member converted. No top-level
|
||||
// `type` constraint: the individual branches carry their own types
|
||||
// (valid JSON Schema for a union).
|
||||
const options = (def as { options?: ZodTypeAny[] }).options ?? []
|
||||
return { oneOf: options.map(zodToJsonSchema) } as unknown as JsonSchema
|
||||
}
|
||||
default:
|
||||
// Unknown construct → empty schema, accept anything.
|
||||
return {}
|
||||
}
|
||||
}
|
||||
|
||||
// ──────────────────────────────────────────────────────────────────
|
||||
// OpenAPI 3.1 spec generation
|
||||
// ──────────────────────────────────────────────────────────────────
|
||||
|
||||
interface OpenApiSpec {
|
||||
openapi: '3.1.0'
|
||||
info: { title: string; version: string; description: string }
|
||||
servers: Array<{ url: string }>
|
||||
components: { securitySchemes: Record<string, unknown> }
|
||||
security: Array<Record<string, unknown[]>>
|
||||
paths: Record<string, Record<string, unknown>>
|
||||
}
|
||||
|
||||
const SCHEME_NAME = 'ApiKey'
|
||||
|
||||
export function generateOpenApiSpec(serverUrl: string): OpenApiSpec {
|
||||
const paths: OpenApiSpec['paths'] = {}
|
||||
|
||||
for (const def of ENDPOINTS.values()) {
|
||||
// OpenAPI path syntax: {param} instead of :param.
|
||||
const openApiPath = def.path.replace(/:([^/]+)/g, '{$1}')
|
||||
|
||||
// Binary responses (e.g. application/pdf) declare a `format: binary`
|
||||
// schema rather than deriving from the Zod success type.
|
||||
// The registry's worked `example` travels with the schema as an OpenAPI
|
||||
// media-type `example`. Without this the examples reached only the docs
|
||||
// markdown builder (lib/docs/content/reference.ts): the spec itself carried
|
||||
// none, so neither /api/v1/openapi.json consumers nor the generated
|
||||
// skills/accounted-api ever saw a concrete request or response body.
|
||||
// Attached to JSON media types only: a binary response (application/pdf)
|
||||
// has no meaningful JSON example to show.
|
||||
const successContent = def.response.contentType && def.response.contentType !== 'application/json'
|
||||
? { [def.response.contentType]: { schema: { type: 'string', format: 'binary' } } }
|
||||
: {
|
||||
'application/json': {
|
||||
schema: zodToJsonSchema(def.response.success),
|
||||
example: def.example.response,
|
||||
},
|
||||
}
|
||||
|
||||
// 204 No Content endpoints (DELETEs returning noContent()) carry no body:
|
||||
// emit a bare 204 instead of a 200 { data, meta } so the spec stops
|
||||
// advertising a response shape these handlers never send.
|
||||
const successResponse = def.response.success === NoBodyResponse
|
||||
? { '204': { description: 'No Content' } }
|
||||
: { '200': { description: 'Success', content: successContent } }
|
||||
|
||||
// Path parameters, derived from the `:param` pattern itself so every
|
||||
// templated segment is declared even though routes don't register a
|
||||
// params schema. All v1 path params are string ids.
|
||||
const parameters = [...def.path.matchAll(/:([^/]+)/g)].map(([, name]) => ({
|
||||
name,
|
||||
in: 'path',
|
||||
required: true,
|
||||
schema: { type: 'string' },
|
||||
}))
|
||||
|
||||
// Request body from the registered Zod schema. In multipart bodies a
|
||||
// part registered as `z.unknown()` is by convention the binary file part
|
||||
// (see documents.upload); the converter turns it into an empty schema,
|
||||
// which is rewritten here to `format: binary` so client generators
|
||||
// produce correct multipart uploads.
|
||||
let requestBody: Record<string, unknown> | undefined
|
||||
if (def.request?.body) {
|
||||
const contentType = def.request.contentType ?? 'application/json'
|
||||
let bodySchema = zodToJsonSchema(def.request.body)
|
||||
if (contentType === 'multipart/form-data' && bodySchema.properties) {
|
||||
bodySchema = {
|
||||
...bodySchema,
|
||||
properties: Object.fromEntries(
|
||||
Object.entries(bodySchema.properties).map(([key, prop]) => [
|
||||
key,
|
||||
Object.keys(prop).length === 0
|
||||
? { type: 'string', format: 'binary' }
|
||||
: prop,
|
||||
]),
|
||||
),
|
||||
}
|
||||
}
|
||||
requestBody = {
|
||||
required: true,
|
||||
content: {
|
||||
[contentType]: {
|
||||
schema: bodySchema,
|
||||
// Only JSON bodies carry a worked example; a multipart upload's
|
||||
// example would be a file part, which JSON cannot express.
|
||||
...(def.example.request && contentType === 'application/json'
|
||||
? { example: def.example.request }
|
||||
: {}),
|
||||
},
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
const operationDef: Record<string, unknown> = {
|
||||
operationId: def.operation,
|
||||
summary: def.summary,
|
||||
description: [
|
||||
def.description,
|
||||
'',
|
||||
`**Use when:** ${def.useWhen}`,
|
||||
`**Do not use for:** ${def.doNotUseFor}`,
|
||||
...(def.pitfalls.length > 0 ? ['', '**Pitfalls:**', ...def.pitfalls.map((p) => `- ${p}`)] : []),
|
||||
].join('\n'),
|
||||
'x-action-risk': def.risk,
|
||||
'x-idempotent': def.idempotent,
|
||||
'x-reversible': def.reversible,
|
||||
'x-dry-run-supported': def.dryRunSupported,
|
||||
...(def.scope ? { 'x-required-scope': def.scope } : {}),
|
||||
...(parameters.length > 0 ? { parameters } : {}),
|
||||
...(requestBody ? { requestBody } : {}),
|
||||
responses: {
|
||||
...successResponse,
|
||||
'400': { description: 'Validation error', $ref: '#/components/responses/Error' },
|
||||
'401': { description: 'Unauthorized', $ref: '#/components/responses/Error' },
|
||||
'403': { description: 'Insufficient scope', $ref: '#/components/responses/Error' },
|
||||
'404': { description: 'Not found', $ref: '#/components/responses/Error' },
|
||||
'429': { description: 'Rate limited', $ref: '#/components/responses/Error' },
|
||||
'500': { description: 'Internal error', $ref: '#/components/responses/Error' },
|
||||
},
|
||||
}
|
||||
|
||||
if (!paths[openApiPath]) paths[openApiPath] = {}
|
||||
paths[openApiPath][def.method.toLowerCase()] = operationDef
|
||||
}
|
||||
|
||||
return {
|
||||
openapi: '3.1.0',
|
||||
info: {
|
||||
title: 'Accounted API',
|
||||
version: API_V1_VERSION,
|
||||
description:
|
||||
'Public REST API for Accounted: Swedish double-entry bookkeeping. ' +
|
||||
'Every write supports dry-run via `?dry_run=true`. Every request must include ' +
|
||||
'`Authorization: Bearer gnubok_sk_...`. See /docs/api for the cookbook.',
|
||||
},
|
||||
servers: [{ url: serverUrl }],
|
||||
components: {
|
||||
securitySchemes: {
|
||||
[SCHEME_NAME]: {
|
||||
type: 'http',
|
||||
scheme: 'bearer',
|
||||
bearerFormat: 'gnubok_sk_<live|test>_<random>',
|
||||
},
|
||||
},
|
||||
},
|
||||
security: [{ [SCHEME_NAME]: [] }],
|
||||
paths,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,219 @@
|
||||
/**
|
||||
* Shared helpers for v1 report endpoints.
|
||||
*
|
||||
* Most reports follow the same shape: parse `period_id` from the query
|
||||
* string, validate it as a UUID, and confirm it's a fiscal period the
|
||||
* caller's company owns before invoking the lib generator. This helper
|
||||
* centralises that pattern so each route stays at ~40 lines of business
|
||||
* logic and the validation behavior stays consistent across all reports.
|
||||
*/
|
||||
|
||||
import { z } from 'zod'
|
||||
import type { NextResponse } from 'next/server'
|
||||
import type { SupabaseClient } from '@supabase/supabase-js'
|
||||
import type { Logger } from '@/lib/logger'
|
||||
import { parseReportDateRange, type DateRange } from '@/lib/reports/date-range'
|
||||
import { v1ErrorResponse, v1ErrorResponseFromCode } from './errors'
|
||||
import { UUID_RE } from '@/lib/invariants/uuid'
|
||||
|
||||
export interface FiscalPeriodRow {
|
||||
id: string
|
||||
period_start: string
|
||||
period_end: string
|
||||
is_closed: boolean
|
||||
locked_at: string | null
|
||||
}
|
||||
|
||||
export type PeriodResult =
|
||||
| { ok: true; period: FiscalPeriodRow }
|
||||
| { ok: false; response: Response }
|
||||
|
||||
/**
|
||||
* Parse + validate `period_id` from the URL's query string, then load the
|
||||
* matching `fiscal_periods` row scoped to the caller's company. Returns
|
||||
* either the row (success) or a pre-built error response (caller just
|
||||
* returns it).
|
||||
*
|
||||
* Why a tight helper: every report endpoint does this same 4-step dance
|
||||
* (parse query, validate UUID, fetch period, 404 on miss). Pulling it
|
||||
* out reduces each route to its actual business logic.
|
||||
*/
|
||||
export async function loadPeriodFromQuery(
|
||||
request: Request,
|
||||
ctx: {
|
||||
supabase: SupabaseClient
|
||||
companyId: string
|
||||
requestId: string
|
||||
log: Logger
|
||||
},
|
||||
): Promise<PeriodResult> {
|
||||
const url = new URL(request.url)
|
||||
const periodId = url.searchParams.get('period_id')
|
||||
|
||||
if (!periodId) {
|
||||
return {
|
||||
ok: false,
|
||||
response: await v1ErrorResponseFromCode('VALIDATION_ERROR', ctx.log, {
|
||||
requestId: ctx.requestId,
|
||||
details: { field: 'period_id', message: 'period_id query parameter is required.' },
|
||||
}),
|
||||
}
|
||||
}
|
||||
|
||||
if (!UUID_RE.test(periodId)) {
|
||||
return {
|
||||
ok: false,
|
||||
response: await v1ErrorResponseFromCode('VALIDATION_ERROR', ctx.log, {
|
||||
requestId: ctx.requestId,
|
||||
details: { field: 'period_id', message: 'period_id must be a UUID.' },
|
||||
}),
|
||||
}
|
||||
}
|
||||
|
||||
const { data, error } = await ctx.supabase
|
||||
.from('fiscal_periods')
|
||||
.select('id, period_start, period_end, is_closed, locked_at')
|
||||
.eq('id', periodId)
|
||||
.eq('company_id', ctx.companyId)
|
||||
.maybeSingle()
|
||||
|
||||
if (error) {
|
||||
return {
|
||||
ok: false,
|
||||
response: await v1ErrorResponse(error, ctx.log, { requestId: ctx.requestId }),
|
||||
}
|
||||
}
|
||||
if (!data) {
|
||||
return {
|
||||
ok: false,
|
||||
response: await v1ErrorResponseFromCode('NOT_FOUND', ctx.log, {
|
||||
requestId: ctx.requestId,
|
||||
details: { resource: 'fiscal_period', id: periodId },
|
||||
}),
|
||||
}
|
||||
}
|
||||
|
||||
return { ok: true, period: data as FiscalPeriodRow }
|
||||
}
|
||||
|
||||
export type QueryParamsResult = { ok: true } | { ok: false; response: Response }
|
||||
|
||||
/**
|
||||
* Reject unknown query parameters instead of silently ignoring them.
|
||||
*
|
||||
* Report endpoints historically dropped anything they didn't read, so an
|
||||
* agent passing a misspelled or unsupported parameter (e.g. `from=` instead
|
||||
* of `from_date=`) got a full-period report back with no signal that its
|
||||
* intent was ignored. For date-scoped financial reports that's dangerous:
|
||||
* the caller believes it holds a January-July resultatrapport when it holds
|
||||
* the whole year. Scoped to the report routes that opt in; not a global v1
|
||||
* behavior change.
|
||||
*/
|
||||
// Params the withApiV1 wrapper itself reads on every request; a route-level
|
||||
// allowlist must never reject them.
|
||||
const WRAPPER_PARAMS = ['dry_run']
|
||||
|
||||
export async function assertKnownQueryParams(
|
||||
request: Request,
|
||||
allowed: readonly string[],
|
||||
ctx: { requestId: string; log: Logger },
|
||||
): Promise<QueryParamsResult> {
|
||||
const url = new URL(request.url)
|
||||
const unknown = [...new Set(url.searchParams.keys())].filter(
|
||||
(k) => !allowed.includes(k) && !WRAPPER_PARAMS.includes(k),
|
||||
)
|
||||
if (unknown.length === 0) return { ok: true }
|
||||
return {
|
||||
ok: false,
|
||||
response: await v1ErrorResponseFromCode('VALIDATION_ERROR', ctx.log, {
|
||||
requestId: ctx.requestId,
|
||||
details: {
|
||||
unknown_params: unknown,
|
||||
allowed_params: [...allowed],
|
||||
message: `Unknown query parameter(s): ${unknown.join(', ')}. Unknown parameters are rejected rather than silently ignored.`,
|
||||
},
|
||||
}),
|
||||
}
|
||||
}
|
||||
|
||||
export type RangeResult =
|
||||
| { ok: true; range: DateRange }
|
||||
| { ok: false; response: Response }
|
||||
|
||||
/**
|
||||
* Parse the optional `from_date` / `to_date` (and, when `asOfAlias` is set,
|
||||
* `as_of` as an alias for `to_date`: the natural vocabulary for a balance
|
||||
* position) from the query string, validated against the fiscal period via
|
||||
* the same `parseReportDateRange` the dashboard report routes use. Keeping
|
||||
* one validator means the REST surface accepts exactly the ranges the web
|
||||
* UI accepts: clamped inside the räkenskapsår, `from_date <= to_date`.
|
||||
*/
|
||||
export async function loadRangeFromQuery(
|
||||
request: Request,
|
||||
period: FiscalPeriodRow,
|
||||
ctx: { requestId: string; log: Logger },
|
||||
opts?: { asOfAlias?: boolean },
|
||||
): Promise<RangeResult> {
|
||||
const url = new URL(request.url)
|
||||
const searchParams = new URLSearchParams(url.searchParams)
|
||||
|
||||
if (opts?.asOfAlias) {
|
||||
const asOf = searchParams.get('as_of')
|
||||
if (asOf !== null) {
|
||||
if (searchParams.get('to_date') !== null) {
|
||||
return {
|
||||
ok: false,
|
||||
response: await v1ErrorResponseFromCode('VALIDATION_ERROR', ctx.log, {
|
||||
requestId: ctx.requestId,
|
||||
details: {
|
||||
field: 'as_of',
|
||||
message: 'Pass either as_of or to_date, not both (as_of is an alias for to_date).',
|
||||
},
|
||||
}),
|
||||
}
|
||||
}
|
||||
searchParams.set('to_date', asOf)
|
||||
searchParams.delete('as_of')
|
||||
}
|
||||
}
|
||||
|
||||
const parsed = parseReportDateRange(searchParams, period)
|
||||
if (!parsed.ok) {
|
||||
return {
|
||||
ok: false,
|
||||
response: await v1ErrorResponseFromCode('VALIDATION_ERROR', ctx.log, {
|
||||
requestId: ctx.requestId,
|
||||
details: { fields: ['from_date', 'to_date'], message: parsed.error },
|
||||
}),
|
||||
}
|
||||
}
|
||||
return { ok: true, range: parsed.range }
|
||||
}
|
||||
|
||||
/**
|
||||
* Wrap a report-generator call in a try/catch that surfaces a structured
|
||||
* REPORT_GENERATION_FAILED error if the generator throws. Mirrors the
|
||||
* dashboard's pattern so any lib-layer exception becomes a clean v1
|
||||
* envelope rather than leaking the underlying error.
|
||||
*/
|
||||
export async function safeGenerate<T>(
|
||||
generate: () => Promise<T>,
|
||||
ctx: { log: Logger; requestId: string; reportName: string },
|
||||
): Promise<{ ok: true; result: T } | { ok: false; response: NextResponse }> {
|
||||
try {
|
||||
const result = await generate()
|
||||
return { ok: true, result }
|
||||
} catch (err) {
|
||||
ctx.log.error(`${ctx.reportName} report generation failed`, err as Error)
|
||||
return {
|
||||
ok: false,
|
||||
response: await v1ErrorResponseFromCode('REPORT_GENERATION_FAILED', ctx.log, {
|
||||
requestId: ctx.requestId,
|
||||
details: {
|
||||
report: ctx.reportName,
|
||||
reason: err instanceof Error ? err.message : 'unknown',
|
||||
},
|
||||
}),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,148 @@
|
||||
/**
|
||||
* v1 REST response envelopes.
|
||||
*
|
||||
* ok(data) → 200 { data, meta: { request_id, api_version } }
|
||||
* paginated(data, next_cursor) → 200 { data, meta: { request_id, api_version, next_cursor } }
|
||||
* accepted(operationId, type) → 202 { data: { operation_id, status, poll_url, webhook_event }, meta }
|
||||
* created(data) → 201 same shape as ok
|
||||
*
|
||||
* Every helper stamps X-Request-Id + Gnubok-Version on the response and
|
||||
* accepts an optional `audit` block for write responses (per the architectural
|
||||
* decision in the plan that writes return their voucher_number / audit_url
|
||||
* inline so the agent doesn't need a second round-trip).
|
||||
*/
|
||||
|
||||
import { NextResponse } from 'next/server'
|
||||
import { API_V1_VERSION, API_V1_VERSION_HEADER } from './version'
|
||||
|
||||
export interface AuditBlock {
|
||||
voucher_number?: string
|
||||
voucher_url?: string
|
||||
audit_trail_url?: string
|
||||
immutable_at?: string
|
||||
}
|
||||
|
||||
export interface ResponseMeta {
|
||||
request_id: string
|
||||
api_version: string
|
||||
next_cursor?: string
|
||||
audit?: AuditBlock
|
||||
/**
|
||||
* Names of `?expand=` keys whose underlying data fetch failed during a
|
||||
* soft-degraded response. Present only when at least one expansion was
|
||||
* requested AND failed. Agents that need transactional guarantees can
|
||||
* detect a degraded response without parsing the body.
|
||||
*/
|
||||
partial_expansions?: string[]
|
||||
/**
|
||||
* Registry-coverage disclosure for list endpoints whose backing register
|
||||
* may not span all of the company's bookkeeping (e.g. the invoice
|
||||
* register after a mid-year migration). Shape is endpoint-specific and
|
||||
* documented in the endpoint's registry entry. Present only when the
|
||||
* endpoint computes it.
|
||||
*/
|
||||
coverage?: Record<string, unknown>
|
||||
}
|
||||
|
||||
interface ResponseOptions {
|
||||
requestId: string
|
||||
status?: number
|
||||
headers?: Record<string, string>
|
||||
audit?: AuditBlock
|
||||
/** Cursor for the *next* page; omitted when this is the last page. */
|
||||
nextCursor?: string
|
||||
/** Names of `?expand=` keys whose data fetch failed (soft-degrade). */
|
||||
partialExpansions?: string[]
|
||||
/** Endpoint-specific register-coverage disclosure (see ResponseMeta.coverage). */
|
||||
coverage?: Record<string, unknown>
|
||||
/** Marks the response as a replay of a previously-cached idempotent call. */
|
||||
idempotentReplay?: boolean
|
||||
/** Marks the response as a dry-run preview rather than a committed write. */
|
||||
dryRun?: boolean
|
||||
/** Rate-limit headers, when known. */
|
||||
rateLimit?: { limit: number; remaining: number; resetAt?: Date }
|
||||
}
|
||||
|
||||
function applyStandardHeaders(res: NextResponse, opts: ResponseOptions): NextResponse {
|
||||
res.headers.set('X-Request-Id', opts.requestId)
|
||||
res.headers.set(API_V1_VERSION_HEADER, API_V1_VERSION)
|
||||
if (opts.idempotentReplay) res.headers.set('Idempotent-Replayed', 'true')
|
||||
if (opts.dryRun) res.headers.set('X-Dry-Run', 'true')
|
||||
if (opts.rateLimit) {
|
||||
res.headers.set('X-RateLimit-Limit', String(opts.rateLimit.limit))
|
||||
res.headers.set('X-RateLimit-Remaining', String(opts.rateLimit.remaining))
|
||||
if (opts.rateLimit.resetAt) {
|
||||
res.headers.set('X-RateLimit-Reset', String(Math.floor(opts.rateLimit.resetAt.getTime() / 1000)))
|
||||
}
|
||||
}
|
||||
if (opts.headers) {
|
||||
for (const [k, v] of Object.entries(opts.headers)) {
|
||||
res.headers.set(k, v)
|
||||
}
|
||||
}
|
||||
return res
|
||||
}
|
||||
|
||||
function buildMeta(opts: ResponseOptions): ResponseMeta {
|
||||
const meta: ResponseMeta = {
|
||||
request_id: opts.requestId,
|
||||
api_version: API_V1_VERSION,
|
||||
}
|
||||
if (opts.nextCursor) meta.next_cursor = opts.nextCursor
|
||||
if (opts.audit) meta.audit = opts.audit
|
||||
if (opts.coverage) meta.coverage = opts.coverage
|
||||
if (opts.partialExpansions && opts.partialExpansions.length > 0) {
|
||||
meta.partial_expansions = opts.partialExpansions
|
||||
}
|
||||
return meta
|
||||
}
|
||||
|
||||
/**
|
||||
* 200 OK with `{ data, meta }`.
|
||||
*/
|
||||
export function ok<T>(data: T, opts: ResponseOptions): NextResponse {
|
||||
const res = NextResponse.json({ data, meta: buildMeta(opts) }, { status: opts.status ?? 200 })
|
||||
return applyStandardHeaders(res, opts)
|
||||
}
|
||||
|
||||
/**
|
||||
* 200 OK with `{ data: T[], meta: { next_cursor } }`. Use for list endpoints.
|
||||
*/
|
||||
export function paginated<T>(data: T[], opts: ResponseOptions): NextResponse {
|
||||
const res = NextResponse.json({ data, meta: buildMeta(opts) }, { status: 200 })
|
||||
return applyStandardHeaders(res, opts)
|
||||
}
|
||||
|
||||
/**
|
||||
* 201 Created. Mirror of ok() with status 201 for POST that creates a resource.
|
||||
*/
|
||||
export function created<T>(data: T, opts: ResponseOptions): NextResponse {
|
||||
return ok(data, { ...opts, status: 201 })
|
||||
}
|
||||
|
||||
/**
|
||||
* 202 Accepted for async long-running operations. Returns the operation_id +
|
||||
* polling URL + the webhook event the caller can subscribe to for completion.
|
||||
*/
|
||||
export function accepted(
|
||||
operationId: string,
|
||||
operationType: string,
|
||||
opts: ResponseOptions,
|
||||
): NextResponse {
|
||||
const data = {
|
||||
operation_id: operationId,
|
||||
type: operationType,
|
||||
status: 'queued' as const,
|
||||
poll_url: `/api/v1/operations/${operationId}`,
|
||||
webhook_event: 'operation.completed',
|
||||
}
|
||||
return ok(data, { ...opts, status: 202 })
|
||||
}
|
||||
|
||||
/**
|
||||
* 204 No Content. Used for DELETE responses. No body.
|
||||
*/
|
||||
export function noContent(opts: ResponseOptions): NextResponse {
|
||||
const res = new NextResponse(null, { status: 204 })
|
||||
return applyStandardHeaders(res, opts)
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
/**
|
||||
* Common security headers for public v1 responses.
|
||||
*
|
||||
* Applied to discovery routes (`/llms.txt`, `/.well-known/skills/index.json`,
|
||||
* `/api/v1/openapi.json`) that bypass the auth wrapper.
|
||||
*
|
||||
* The wrapped routes don't need these explicitly: NextResponse's defaults +
|
||||
* the auth wrapper's stamping cover them. Public routes are an exception
|
||||
* because they're plain `NextResponse.json/text` returns with caching.
|
||||
*
|
||||
* X-Content-Type-Options: nosniff : block MIME sniffing on text/json
|
||||
* Referrer-Policy: strict-origin...: limit referrer leakage if a link is
|
||||
* embedded somewhere unexpected
|
||||
* X-Frame-Options: DENY : discovery surfaces should never
|
||||
* legitimately render in a frame
|
||||
*/
|
||||
|
||||
/**
|
||||
* Headers applied to BOTH public discovery routes and authenticated v1
|
||||
* responses. Includes CSP, HSTS, and frame/sniff/referrer protections, but
|
||||
* NOT X-Robots-Tag: discovery routes (llms.txt, skills index, OpenAPI)
|
||||
* exist to be crawled by AI agents; authenticated routes get an additional
|
||||
* X-Robots-Tag at the wrapper level via WRAPPED_RESPONSE_NOAI_HEADERS.
|
||||
*/
|
||||
export const PUBLIC_SECURITY_HEADERS: Record<string, string> = {
|
||||
'X-Content-Type-Options': 'nosniff',
|
||||
'Referrer-Policy': 'strict-origin-when-cross-origin',
|
||||
'X-Frame-Options': 'DENY',
|
||||
// Discovery routes return JSON or plain text: no script, style, image, or
|
||||
// form contexts. `default-src 'none'` is the strictest possible CSP and
|
||||
// costs nothing here.
|
||||
'Content-Security-Policy': "default-src 'none'; frame-ancestors 'none'",
|
||||
// HSTS: every Accounted deployment is HTTPS-only. 1 year is the standard
|
||||
// production value; includeSubDomains because the apex serves everything.
|
||||
'Strict-Transport-Security': 'max-age=31536000; includeSubDomains',
|
||||
}
|
||||
|
||||
/**
|
||||
* Additional headers applied ONLY to authenticated v1 responses. AI bots
|
||||
* that respect X-Robots-Tag (Claude, ChatGPT, Perplexity, Google-Extended)
|
||||
* will skip these payloads for training; others will ignore the hint.
|
||||
* Public discovery routes deliberately omit this so they remain
|
||||
* AI-discoverable.
|
||||
*/
|
||||
export const WRAPPED_RESPONSE_HEADERS: Record<string, string> = {
|
||||
...PUBLIC_SECURITY_HEADERS,
|
||||
'X-Robots-Tag': 'noai, noimageai',
|
||||
}
|
||||
|
||||
/**
|
||||
* Merge the public security headers onto an arbitrary header dict so callers
|
||||
* can keep their own Content-Type / Cache-Control entries.
|
||||
*/
|
||||
export function withPublicSecurityHeaders(extra: Record<string, string> = {}): Record<string, string> {
|
||||
return { ...PUBLIC_SECURITY_HEADERS, ...extra }
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
/**
|
||||
* The current API version date.
|
||||
*
|
||||
* Echoed in every response's `meta.api_version` and stamped as the
|
||||
* `Gnubok-Version` response header (with-api-v1.ts). A `Gnubok-Version`
|
||||
* REQUEST header is reserved for future date-pinned breaking changes: nothing
|
||||
* reads it today, every request gets the current version.
|
||||
*
|
||||
* Bump this only for a breaking change inside v1 (additive changes never bump
|
||||
* it); that is also when request pinning gets wired so integrators can keep
|
||||
* the older shape.
|
||||
*/
|
||||
export const API_V1_VERSION = '2026-05-12'
|
||||
|
||||
export const API_V1_VERSION_HEADER = 'Gnubok-Version'
|
||||
@@ -0,0 +1,682 @@
|
||||
/**
|
||||
* v1 REST API wrapper.
|
||||
*
|
||||
* Every route under `app/api/v1/` is wrapped with `withApiV1('operation.name', handler)`.
|
||||
* The wrapper provides a single audit-friendly shape for the entire v1 surface:
|
||||
*
|
||||
* 1. Generates `requestId` (`req_<uuid>`) and a child logger bound to it.
|
||||
* 2. Extracts and validates the `Authorization: Bearer gnubok_sk_...` header
|
||||
* via the existing `validateApiKey()` (atomic RPC, rate-limited).
|
||||
* 3. Resolves the required scope for the route from the v1 endpoint catalogue
|
||||
* and returns INSUFFICIENT_SCOPE if the key lacks it. Public endpoints
|
||||
* (`/health`, `/openapi.json`) skip the scope check but still validate
|
||||
* the token when one is supplied.
|
||||
* 4. When the URL contains `companyId`, verifies the API key's user has
|
||||
* access to that company via `company_members`. Multi-company keys are
|
||||
* supported transparently: the URL is the source of truth. A `viewer`
|
||||
* (read-only) membership is refused for every write: mutating method
|
||||
* or non-`:read` scope (FORBIDDEN, details.code ROLE_READ_ONLY).
|
||||
* 5. Resolves the dry-run flag (`?dry_run=true` query OR `X-Dry-Run` header).
|
||||
* 6. Resolves `Idempotency-Key` (header) and replays cached responses. The
|
||||
* dry-run flag is part of the cache identity and dry-run responses are
|
||||
* never cached, so a simulation can never be replayed in place of the
|
||||
* real write that follows it.
|
||||
* 7. Invokes the handler with a typed RouteContext.
|
||||
* 8. Stamps `X-Request-Id` and `Gnubok-Version` on the response, plus
|
||||
* `Retry-After` on a 429.
|
||||
* 9. Catches any thrown value and converts it to the v1 error envelope via
|
||||
* `v1ErrorResponse`.
|
||||
*
|
||||
* Usage:
|
||||
*
|
||||
* export const GET = withApiV1('companies.list', async (req, ctx) => {
|
||||
* // ctx.requestId, ctx.log, ctx.user, ctx.companyId (when in URL),
|
||||
* // ctx.supabase, ctx.scopes, ctx.mode, ctx.dryRun, ctx.idempotencyKey
|
||||
* return ok({ companies: [...] }, { requestId: ctx.requestId })
|
||||
* })
|
||||
*/
|
||||
|
||||
import { type SupabaseClient } from '@supabase/supabase-js'
|
||||
import { createServiceRoleClient } from '@/lib/supabase/service-client'
|
||||
import { NextResponse } from 'next/server'
|
||||
import { ensureInitialized } from '@/lib/init'
|
||||
import { truncateIp } from '@/lib/api/ip'
|
||||
import {
|
||||
type ApiKeyMode,
|
||||
type ApiKeyScope,
|
||||
createServiceClientNoCookies,
|
||||
extractBearerToken,
|
||||
hasScope,
|
||||
RATE_LIMIT_RETRY_AFTER_SECONDS,
|
||||
scopeKind,
|
||||
validateApiKey,
|
||||
} from '@/lib/auth/api-keys'
|
||||
import { runWithActor } from '@/lib/bookkeeping/actor-context-node'
|
||||
|
||||
// Per CLAUDE.md: any route that emits events via eventBus must call
|
||||
// ensureInitialized() at module level to wire extension event handlers
|
||||
// (email, cloud-backup, push-notifications, etc.). Calling it here in the
|
||||
// wrapper guarantees every v1 route gets the init at import time: a single
|
||||
// source of truth so future routes can't forget. The function itself is
|
||||
// idempotent (guarded by a module-level boolean).
|
||||
ensureInitialized()
|
||||
import { resolveRequiredScope } from '@/lib/auth/scopes'
|
||||
import { getMultiUserState, isMembershipDormant } from '@/lib/entitlements/multi-user'
|
||||
import { getEndpointByConcretePath } from './registry'
|
||||
import {
|
||||
checkIdempotencyKey,
|
||||
hashRequest,
|
||||
IdempotencyKeyReuseError,
|
||||
storeIdempotencyResponse,
|
||||
} from '@/lib/api/idempotency'
|
||||
import { createLogger, type Logger } from '@/lib/logger'
|
||||
import { v1ErrorResponse, v1ErrorResponseFromCode } from './errors'
|
||||
import { WRAPPED_RESPONSE_HEADERS } from './security-headers'
|
||||
import { API_V1_VERSION, API_V1_VERSION_HEADER } from './version'
|
||||
|
||||
const IDEMPOTENCY_HEADER = 'Idempotency-Key'
|
||||
const DRY_RUN_HEADER = 'X-Dry-Run'
|
||||
// Every state-changing method. PUT is included even though most v1 writes are
|
||||
// POST/PATCH: the set drives THREE behaviors (test-key dry-run forcing,
|
||||
// idempotency replay, requireIdempotencyKey enforcement), and omitting PUT
|
||||
// would let test keys write through PUT routes for real.
|
||||
const REQUIRES_IDEMPOTENCY = new Set(['POST', 'PUT', 'PATCH', 'DELETE'])
|
||||
// RFC 9110 safe methods. The read-only role gate treats EVERYTHING else as a
|
||||
// write: a superset of REQUIRES_IDEMPOTENCY, so an exotic method can never
|
||||
// slip a viewer past the gate. Deliberately separate from REQUIRES_IDEMPOTENCY,
|
||||
// whose semantics (replay, dry-run forcing) must not widen as a side effect.
|
||||
const SAFE_METHODS = new Set(['GET', 'HEAD', 'OPTIONS'])
|
||||
/** The read-only company role (see `CompanyRole` in `@/types`). */
|
||||
const READ_ONLY_ROLE = 'viewer'
|
||||
|
||||
export interface ApiV1Context {
|
||||
/** Stable id for this HTTP request: appears in logs, error envelope, X-Request-Id. */
|
||||
requestId: string
|
||||
/** Logger pre-bound with { requestId, userId, companyId?, operation, apiKeyId? }. */
|
||||
log: Logger
|
||||
/** Authenticated user id. */
|
||||
userId: string
|
||||
/** API key id of the caller. Used for actor attribution on pending_operations / audit_log. */
|
||||
apiKeyId: string | undefined
|
||||
/** API key human name. */
|
||||
apiKeyName: string | undefined
|
||||
/** Scopes granted to the calling key. */
|
||||
scopes: ApiKeyScope[]
|
||||
/**
|
||||
* Largest amount in SEK this key may commit with no human approving it, or
|
||||
* null for no ceiling (the default, and what every key predating the column
|
||||
* has). Enforced at the two places an API key can post money: this surface's
|
||||
* journal-entries.commit, and commitPendingOperation for the MCP path.
|
||||
*/
|
||||
unattendedCommitLimit: number | null
|
||||
/**
|
||||
* test|live. Test keys are simulation-only: the wrapper forces `dryRun` on
|
||||
* for every write, so handlers never need to special-case `mode`; they just
|
||||
* honor `dryRun` as usual.
|
||||
*/
|
||||
mode: ApiKeyMode
|
||||
/** Service-role Supabase client (no cookies). All queries MUST filter by company_id. */
|
||||
supabase: SupabaseClient
|
||||
/**
|
||||
* Resolved company id from the URL `:companyId` segment. Undefined for
|
||||
* routes that don't include the segment (`/companies`, `/operations/:id`,
|
||||
* `/health`).
|
||||
*/
|
||||
companyId?: string
|
||||
/** Resolved dry-run flag. Routes that mutate state must honor this. */
|
||||
dryRun: boolean
|
||||
/** Resolved idempotency key, if supplied. */
|
||||
idempotencyKey: string | null
|
||||
}
|
||||
|
||||
interface ApiV1Options {
|
||||
/** Override the required scope (e.g. for ad-hoc endpoints not in the catalogue). */
|
||||
requireScope?: ApiKeyScope
|
||||
/**
|
||||
* When true, idempotency is enforced: POST/PATCH/DELETE without an
|
||||
* `Idempotency-Key` header return 400. Default false; can be flipped on
|
||||
* per-route once the integrator audience is sophisticated enough.
|
||||
*/
|
||||
requireIdempotencyKey?: boolean
|
||||
}
|
||||
|
||||
// Next.js 16 always passes `{ params: Promise<...> }` as the second arg.
|
||||
// eslint-disable-next-line @typescript-eslint/no-empty-object-type
|
||||
type DynamicParams = { params: Promise<Record<string, string | string[]>> } | { params: Promise<{}> }
|
||||
|
||||
type V1Handler<P extends DynamicParams = { params: Promise<Record<string, never>> }> = (
|
||||
request: Request,
|
||||
ctx: ApiV1Context,
|
||||
params: P,
|
||||
) => Promise<NextResponse | Response>
|
||||
|
||||
function generateRequestId(): string {
|
||||
return `req_${crypto.randomUUID()}`
|
||||
}
|
||||
|
||||
/**
|
||||
* Anon-key Supabase client for the wrapper's public-scope code path. RLS is
|
||||
* enforced (no service-role privilege escalation) so even an accidental DB
|
||||
* call from a public handler is constrained to anon-accessible rows.
|
||||
*
|
||||
* Fails closed at first-call if the required env vars are missing: better
|
||||
* to surface the misconfiguration on the first request than silently 500
|
||||
* deeper in the handler.
|
||||
*/
|
||||
function createAnonClient(): SupabaseClient {
|
||||
const url = process.env.NEXT_PUBLIC_SUPABASE_URL
|
||||
const key = process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY
|
||||
if (!url || !key) {
|
||||
throw new Error(
|
||||
'[api/v1] NEXT_PUBLIC_SUPABASE_URL and NEXT_PUBLIC_SUPABASE_ANON_KEY must be set to serve public-scope v1 endpoints',
|
||||
)
|
||||
}
|
||||
return createServiceRoleClient(url, key)
|
||||
}
|
||||
|
||||
/**
|
||||
* Forensic identifiers for security event logs (failed auth, scope deny,
|
||||
* company-membership deny). We log a *truncated* source IP (last octet
|
||||
* dropped for IPv4, last 80 bits zeroed for IPv6) and user-agent so audit
|
||||
* trails can correlate suspicious patterns by network neighbourhood
|
||||
* without persisting full identifying IPs in the log store.
|
||||
*
|
||||
* Data minimisation: GDPR Art.5(1)(c) / Art.5(1)(f). Truncation preserves
|
||||
* the diagnostic value (city-level geolocation, ASN, abuse-pattern
|
||||
* correlation) while eliminating point-of-presence identification.
|
||||
*
|
||||
* Honors `x-forwarded-for` when set (Vercel / proxies); behind Vercel the
|
||||
* leftmost value is rewritten by the edge so we accept it as authoritative.
|
||||
*/
|
||||
export { truncateIp }
|
||||
|
||||
function extractForensicContext(request: Request, log: Logger): { ip: string | undefined; userAgent: string | undefined } {
|
||||
const fwd = request.headers.get('x-forwarded-for')
|
||||
const raw = fwd ? fwd.split(',')[0]?.trim() : request.headers.get('x-real-ip') ?? undefined
|
||||
const ip = truncateIp(raw || undefined)
|
||||
if (raw && !ip) {
|
||||
// x-forwarded-for / x-real-ip carried a non-empty payload we couldn't parse.
|
||||
// Surface as a warn so spoofed / unexpected proxy values are visible in
|
||||
// security monitoring instead of silently dropped. Never log the raw value:
|
||||
// that would defeat the truncation step.
|
||||
log.warn('unparseable forwarded-for header dropped', { headerLength: raw.length })
|
||||
}
|
||||
const userAgent = request.headers.get('user-agent') ?? undefined
|
||||
return { ip, userAgent }
|
||||
}
|
||||
|
||||
function isDryRun(request: Request, url: URL): boolean {
|
||||
// Case-insensitive on BOTH surfaces. The header was always lowercased, but
|
||||
// the query flag used to require exactly 'true', so '?dry_run=True'
|
||||
// committed for real while the caller believed it previewed: the worst
|
||||
// possible parse of a preview flag. Any other value ('1', 'yes', 'false')
|
||||
// stays non-dry-run, unchanged.
|
||||
const queryVal = url.searchParams.get('dry_run')
|
||||
if (queryVal !== null && queryVal.toLowerCase() === 'true') return true
|
||||
const headerVal = request.headers.get(DRY_RUN_HEADER)
|
||||
if (headerVal && headerVal.toLowerCase() === 'true') return true
|
||||
return false
|
||||
}
|
||||
|
||||
/**
|
||||
* Canonical idempotency hash for a v1 request.
|
||||
*
|
||||
* `dryRun` is part of the identity of the request. The documented commit flow
|
||||
* (see `dry-run.ts`) is "re-issue the exact same request without
|
||||
* `dry_run=true`, same Idempotency-Key", so a simulation and the real write
|
||||
* that follows it share method, path and body. Hashing only those three made
|
||||
* the two indistinguishable: the preview got cached under the commit's hash
|
||||
* and the commit replayed it, returning 200 with `{ dry_run: true, preview }`
|
||||
* while writing nothing.
|
||||
*
|
||||
* The flag is only added to the hashed object when it is TRUE, so an ordinary
|
||||
* (non-dry-run) write hashes byte-identically to previous releases. Idempotency
|
||||
* rows live for 24h; folding `dry_run: false` in unconditionally would make
|
||||
* every key in flight across this deploy fail the `request_hash` comparison and
|
||||
* answer a legitimate retry with IDEMPOTENCY_KEY_REUSE.
|
||||
*
|
||||
* Both the cache lookup and the cache store go through this function: if the
|
||||
* two hash inputs ever drift apart, a stored response can never be found
|
||||
* again, which is a subtler failure than the one this fixes.
|
||||
*/
|
||||
function buildRequestHash(input: {
|
||||
method: string
|
||||
path: string
|
||||
body: unknown
|
||||
dryRun: boolean
|
||||
}): string {
|
||||
return hashRequest({
|
||||
method: input.method,
|
||||
path: input.path,
|
||||
body: input.body,
|
||||
...(input.dryRun ? { dry_run: true } : {}),
|
||||
})
|
||||
}
|
||||
|
||||
async function readBodyForHash(request: Request): Promise<{ body: unknown; cloned: Request }> {
|
||||
// We need the body to hash it, but the handler also needs it. Read from a
|
||||
// CLONE for the hash and pass the original through to the handler: that
|
||||
// way the handler's `await request.json()` still works regardless of how
|
||||
// the runtime implements stream teeing.
|
||||
const reader = request.clone()
|
||||
const text = await reader.text()
|
||||
if (!text) return { body: null, cloned: request }
|
||||
try {
|
||||
return { body: JSON.parse(text), cloned: request }
|
||||
} catch {
|
||||
return { body: text, cloned: request }
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Wrap a v1 route handler with auth, scope, idempotency, dry-run, request-id,
|
||||
* logging, and v1 error envelope handling.
|
||||
*
|
||||
* `operation` is a stable identifier for logs ('companies.list', 'invoices.create'...).
|
||||
*/
|
||||
export function withApiV1<P extends DynamicParams = { params: Promise<Record<string, never>> }>(
|
||||
operation: string,
|
||||
handler: V1Handler<P>,
|
||||
options: ApiV1Options = {},
|
||||
): (request: Request, params: P) => Promise<Response> {
|
||||
return async function wrapped(request: Request, params: P): Promise<Response> {
|
||||
const requestId = generateRequestId()
|
||||
const start = Date.now()
|
||||
const log = createLogger(`api/v1/${operation}`, { requestId, operation })
|
||||
|
||||
const url = new URL(request.url)
|
||||
const path = url.pathname
|
||||
const forensic = extractForensicContext(request, log)
|
||||
|
||||
try {
|
||||
// 1. Determine required scope before auth. Public endpoints can skip
|
||||
// authentication entirely.
|
||||
const requiredScope = options.requireScope ?? resolveRequiredScope(request.method, path)
|
||||
|
||||
if (requiredScope === null) {
|
||||
log.warn('endpoint not registered', { path, method: request.method, ...forensic })
|
||||
return await v1ErrorResponseFromCode('NOT_FOUND', log, {
|
||||
requestId,
|
||||
details: { path, method: request.method },
|
||||
})
|
||||
}
|
||||
|
||||
// 2. Public endpoints: invoke handler with an anon context. If a Bearer
|
||||
// token IS supplied we opportunistically validate it so rate-limiting
|
||||
// and key attribution are applied, but a missing or invalid token
|
||||
// does NOT block the request (the route is, by definition, public).
|
||||
// Falling back to the anon client when unauthenticated keeps the
|
||||
// least-privilege guarantee: an accidental DB call from a public
|
||||
// handler hits RLS, not the service role.
|
||||
if (requiredScope === 'public') {
|
||||
const token = extractBearerToken(request)
|
||||
let publicCtx: ApiV1Context = {
|
||||
requestId,
|
||||
log,
|
||||
userId: 'anonymous',
|
||||
apiKeyId: undefined,
|
||||
apiKeyName: undefined,
|
||||
scopes: [],
|
||||
unattendedCommitLimit: null,
|
||||
mode: 'live',
|
||||
supabase: createAnonClient(),
|
||||
dryRun: false,
|
||||
idempotencyKey: null,
|
||||
}
|
||||
if (token) {
|
||||
const auth = await validateApiKey(token)
|
||||
if (!('error' in auth)) {
|
||||
publicCtx = {
|
||||
...publicCtx,
|
||||
log: log.child({ userId: auth.userId, apiKeyId: auth.apiKeyId, mode: auth.mode }),
|
||||
userId: auth.userId,
|
||||
apiKeyId: auth.apiKeyId,
|
||||
apiKeyName: auth.apiKeyName,
|
||||
scopes: auth.scopes,
|
||||
unattendedCommitLimit: auth.unattendedCommitLimit,
|
||||
mode: auth.mode,
|
||||
supabase: createServiceClientNoCookies(),
|
||||
}
|
||||
}
|
||||
// Invalid token on a public route is silently downgraded to anon:
|
||||
// do not surface 401 since the route doesn't require auth at all.
|
||||
}
|
||||
const response = await handler(request, publicCtx, params)
|
||||
return stampHeaders(response, requestId)
|
||||
}
|
||||
|
||||
// 3. Authenticate via Bearer token.
|
||||
const token = extractBearerToken(request)
|
||||
if (!token) {
|
||||
log.warn('missing bearer token', forensic)
|
||||
return await v1ErrorResponseFromCode('UNAUTHORIZED', log, { requestId })
|
||||
}
|
||||
|
||||
const auth = await validateApiKey(token)
|
||||
if ('error' in auth) {
|
||||
log.warn('api key validation failed', { status: auth.status, reason: auth.error, ...forensic })
|
||||
const rateLimited = auth.status === 429
|
||||
const code = rateLimited ? 'RATE_LIMITED' : 'UNAUTHORIZED'
|
||||
return await v1ErrorResponseFromCode(code, log, {
|
||||
requestId,
|
||||
reason: auth.error,
|
||||
...(rateLimited ? { retryAfterSeconds: RATE_LIMIT_RETRY_AFTER_SECONDS } : {}),
|
||||
})
|
||||
}
|
||||
|
||||
const userLog = log.child({
|
||||
userId: auth.userId,
|
||||
apiKeyId: auth.apiKeyId,
|
||||
mode: auth.mode,
|
||||
})
|
||||
|
||||
// 4. Scope check.
|
||||
if (!hasScope(auth.scopes, requiredScope)) {
|
||||
userLog.warn('insufficient scope', {
|
||||
required: requiredScope,
|
||||
granted: auth.scopes,
|
||||
...forensic,
|
||||
})
|
||||
return await v1ErrorResponseFromCode('INSUFFICIENT_SCOPE', userLog, {
|
||||
requestId,
|
||||
details: { required_scope: requiredScope, granted_scopes: auth.scopes },
|
||||
})
|
||||
}
|
||||
|
||||
// 5. Resolve URL companyId and verify access.
|
||||
//
|
||||
// Next.js 16 invokes a route handler with `{ params: undefined }` for a
|
||||
// STATIC route (no `[segment]` in the path): see app-route module.js
|
||||
// `handlerContext = { params: context.params ? ... : undefined }`. The
|
||||
// only authenticated static route on this surface is `/api/v1/companies`,
|
||||
// so awaiting `params.params` blindly null-derefs there (`undefined` has
|
||||
// no `.companyId`) and the catch below turns it into a 500 for every
|
||||
// valid key. Dynamic routes still pass a real `Promise<{ companyId }>`.
|
||||
// Guard the await and default to an empty param set.
|
||||
const resolvedParams = ((await params?.params) ?? {}) as Record<
|
||||
string,
|
||||
string | string[] | undefined
|
||||
>
|
||||
const rawCompanyId = resolvedParams.companyId
|
||||
const companyId = typeof rawCompanyId === 'string' ? rawCompanyId : undefined
|
||||
|
||||
const supabase = createServiceClientNoCookies()
|
||||
|
||||
if (companyId !== undefined) {
|
||||
const { data: membership, error: membershipErr } = await supabase
|
||||
.from('company_members')
|
||||
.select('company_id, role')
|
||||
.eq('user_id', auth.userId)
|
||||
.eq('company_id', companyId)
|
||||
.maybeSingle()
|
||||
|
||||
if (membershipErr) {
|
||||
userLog.error('failed to resolve company membership', membershipErr as Error)
|
||||
return await v1ErrorResponseFromCode('INTERNAL_ERROR', userLog, { requestId })
|
||||
}
|
||||
|
||||
if (!membership) {
|
||||
userLog.warn('user is not a member of company in URL', { companyId, ...forensic })
|
||||
// 404 (not 403) so we don't leak company existence to unauthorized callers.
|
||||
return await v1ErrorResponseFromCode('NOT_FOUND', userLog, {
|
||||
requestId,
|
||||
details: { companyId },
|
||||
})
|
||||
}
|
||||
|
||||
const membershipRole = (membership as { role?: string }).role
|
||||
|
||||
// Read-only role gate. Cookie routes enforce the viewer role through
|
||||
// withRouteContext({ requireWrite }) and the DB enforces it through
|
||||
// RLS + triggers for cookie sessions, but this surface runs as the
|
||||
// service role: nothing below this line would stop a viewer's key from
|
||||
// posting. A request is a write when EITHER its method is unsafe
|
||||
// (catches action verbs whatever their scope) OR its scope is an
|
||||
// elevated grant (catches reads-by-method that still manage tenant
|
||||
// state, e.g. GET /webhooks on webhooks:manage). Dry-run and test
|
||||
// keys are refused too: a viewer has no write to simulate.
|
||||
//
|
||||
// Placed AFTER the membership 404 so a non-member sees exactly what it
|
||||
// saw before (no new company-existence signal), and BEFORE the seat
|
||||
// gate so a refused write costs no extra read.
|
||||
if (
|
||||
membershipRole === READ_ONLY_ROLE &&
|
||||
(!SAFE_METHODS.has(request.method) || scopeKind(requiredScope) === 'write')
|
||||
) {
|
||||
userLog.warn('read-only membership refused write request', {
|
||||
companyId,
|
||||
method: request.method,
|
||||
requiredScope,
|
||||
...forensic,
|
||||
})
|
||||
return await v1ErrorResponseFromCode('FORBIDDEN', userLog, {
|
||||
requestId,
|
||||
status: 403,
|
||||
reason: 'role_read_only',
|
||||
details: {
|
||||
code: 'ROLE_READ_ONLY',
|
||||
companyId,
|
||||
role: READ_ONLY_ROLE,
|
||||
required_scope: requiredScope,
|
||||
message:
|
||||
'This company membership is read-only (viewer): write requests are refused. Ask a company owner or admin to change the role.',
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
// Multi-user seat gate: the API-key surface is a chokepoint like the
|
||||
// cookie routes and MCP. A non-owner membership in a frozen company
|
||||
// (multi_user lapsed past its 20-day grace) is refused here so an old
|
||||
// key cannot keep working the books after the freeze. Owners pass
|
||||
// without the extra read; the service client sees team-scoped grants.
|
||||
if (membershipRole !== 'owner') {
|
||||
const access = await getMultiUserState(supabase, companyId)
|
||||
if (isMembershipDormant(membershipRole as string, access.state)) {
|
||||
userLog.warn('multi-user seat gate refused frozen membership', { companyId, ...forensic })
|
||||
return await v1ErrorResponseFromCode('FORBIDDEN', userLog, {
|
||||
requestId,
|
||||
status: 403,
|
||||
reason: 'multi_user_frozen',
|
||||
details: {
|
||||
companyId,
|
||||
capability: 'multi_user',
|
||||
message: 'Company is paused for this account: multiple users require a paid plan. Ask the company owner to upgrade.',
|
||||
},
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 6. Idempotency. Mandatory for state-changing methods when the route
|
||||
// opts in (or when an Idempotency-Key header is supplied).
|
||||
const idempotencyKey = request.headers.get(IDEMPOTENCY_HEADER)
|
||||
const isMutation = REQUIRES_IDEMPOTENCY.has(request.method)
|
||||
|
||||
// Test keys are simulation-only: every write is forced to dry-run so
|
||||
// nothing persists (the credential bakes in `?dry_run=true`). A mutating
|
||||
// endpoint that can't be simulated (dryRunSupported=false, or unregistered)
|
||||
// would otherwise write for real: block it outright so a test key can
|
||||
// never touch real data. Reads pass through unchanged (real data, no write).
|
||||
let forceDryRun = false
|
||||
if (auth.mode === 'test' && isMutation) {
|
||||
const endpoint = getEndpointByConcretePath(request.method, path)
|
||||
if (!endpoint || !endpoint.dryRunSupported) {
|
||||
userLog.warn('test key blocked from non-simulatable endpoint', {
|
||||
path,
|
||||
method: request.method,
|
||||
...forensic,
|
||||
})
|
||||
return await v1ErrorResponseFromCode('TEST_KEY_WRITE_BLOCKED', userLog, {
|
||||
requestId,
|
||||
details: { path, method: request.method },
|
||||
})
|
||||
}
|
||||
forceDryRun = true
|
||||
}
|
||||
|
||||
if (options.requireIdempotencyKey && isMutation && !idempotencyKey) {
|
||||
userLog.warn('missing idempotency key on mutating request')
|
||||
return await v1ErrorResponseFromCode('VALIDATION_ERROR', userLog, {
|
||||
requestId,
|
||||
details: {
|
||||
issues: [{ field: IDEMPOTENCY_HEADER, message: 'Idempotency-Key header is required for write requests.' }],
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
// 7. Dry-run resolution. Test keys force it on regardless of the flag.
|
||||
// Resolved BEFORE the idempotency lookup because it feeds the request
|
||||
// hash: a preview and its follow-up commit must never share a cache
|
||||
// entry.
|
||||
const dryRun = isDryRun(request, url) || forceDryRun
|
||||
|
||||
// 8. If idempotency-key supplied, check for cached response.
|
||||
let bodyForHash: unknown = null
|
||||
let workingRequest = request
|
||||
if (idempotencyKey && isMutation && companyId) {
|
||||
const { body, cloned } = await readBodyForHash(request)
|
||||
bodyForHash = body
|
||||
workingRequest = cloned
|
||||
const reqHash = buildRequestHash({ method: request.method, path, body, dryRun })
|
||||
try {
|
||||
const hit = await checkIdempotencyKey(supabase, auth.userId, companyId, idempotencyKey, reqHash)
|
||||
if (hit) {
|
||||
userLog.info('idempotent replay', { idempotencyKey })
|
||||
const replay = NextResponse.json(hit.body, { status: hit.status === 'success' ? 200 : 400 })
|
||||
replay.headers.set('Idempotent-Replayed', 'true')
|
||||
return stampHeaders(replay, requestId)
|
||||
}
|
||||
} catch (err) {
|
||||
if (err instanceof IdempotencyKeyReuseError) {
|
||||
userLog.warn('idempotency key reused with different body')
|
||||
return await v1ErrorResponseFromCode('IDEMPOTENCY_KEY_REUSE', userLog, {
|
||||
requestId,
|
||||
details: { key: idempotencyKey },
|
||||
})
|
||||
}
|
||||
throw err
|
||||
}
|
||||
}
|
||||
|
||||
const ctx: ApiV1Context = {
|
||||
requestId,
|
||||
log: userLog.child({ companyId }),
|
||||
userId: auth.userId,
|
||||
apiKeyId: auth.apiKeyId,
|
||||
apiKeyName: auth.apiKeyName,
|
||||
scopes: auth.scopes,
|
||||
unattendedCommitLimit: auth.unattendedCommitLimit,
|
||||
mode: auth.mode,
|
||||
supabase,
|
||||
companyId,
|
||||
dryRun,
|
||||
idempotencyKey,
|
||||
}
|
||||
|
||||
// 9. Invoke handler, inside the commit-actor scope.
|
||||
//
|
||||
// commitEntry() reads getActor() as its fallback and forwards it to the
|
||||
// commit_journal_entry RPC, which stamps journal_entries.committed_actor_*
|
||||
// and the audit_log COMMIT row (migration 20260619120000). Wrapping here
|
||||
// rather than threading a parameter means EVERY v1 write is attributed,
|
||||
// including the ones that reach the ledger through a helper several
|
||||
// frames down (reverseEntry, correctEntry, the supplier-invoice paths).
|
||||
//
|
||||
// Before this, runWithActor had exactly ONE production call site, the
|
||||
// pending-operations commit. Everything committing outside that path was
|
||||
// anonymous: on production, 99.8% of storno entries and 100% of
|
||||
// correction entries carried no actor at all, which are precisely the two
|
||||
// sanctioned rättelse paths under BFL 5 kap. 5 § and the place where
|
||||
// "who did this, and when" is a legal question rather than a nicety.
|
||||
//
|
||||
// `api_key` is the honest label for this surface: a gnubok_sk_ bearer
|
||||
// token. The OAuth/MCP surfaces set their own actor and are unaffected.
|
||||
const response = await runWithActor(
|
||||
{ type: 'api_key', label: auth.apiKeyName ?? 'Unnamed API key' },
|
||||
() => handler(workingRequest, ctx, params),
|
||||
)
|
||||
|
||||
// Signal test mode on every test-key response so integrators can see the
|
||||
// request was simulation-only without inspecting the body.
|
||||
if (ctx.mode === 'test') {
|
||||
response.headers.set('X-Gnubok-Mode', 'test')
|
||||
}
|
||||
|
||||
// 10. Persist idempotency cache (best-effort).
|
||||
//
|
||||
// Never cache a dry-run: the response describes a write that did not
|
||||
// happen, and caching it under a real Idempotency-Key is exactly how
|
||||
// the documented "preview, then commit with the same key" flow used
|
||||
// to lose the commit. A simulation has nothing worth replaying.
|
||||
//
|
||||
// Never cache a 429 either: a throttle says "not now", and replaying
|
||||
// it under the same key would turn a 15-minute cooldown into the
|
||||
// cache's 24-hour TTL (the documented retry is "same request after
|
||||
// Retry-After", which is exactly a same-key retry).
|
||||
if (
|
||||
idempotencyKey &&
|
||||
isMutation &&
|
||||
companyId &&
|
||||
!dryRun &&
|
||||
response.status < 500 &&
|
||||
response.status !== 429
|
||||
) {
|
||||
try {
|
||||
const body = await response.clone().json().catch(() => ({}))
|
||||
const reqHash = buildRequestHash({
|
||||
method: request.method,
|
||||
path,
|
||||
body: bodyForHash,
|
||||
dryRun,
|
||||
})
|
||||
const status: 'success' | 'error' = response.status >= 400 ? 'error' : 'success'
|
||||
await storeIdempotencyResponse(
|
||||
supabase,
|
||||
auth.userId,
|
||||
companyId,
|
||||
idempotencyKey,
|
||||
reqHash,
|
||||
status,
|
||||
body as Record<string, unknown>,
|
||||
'api_route',
|
||||
)
|
||||
} catch (err) {
|
||||
userLog.warn('failed to persist idempotency response', err as Error)
|
||||
}
|
||||
}
|
||||
|
||||
ctx.log.info('op completed', {
|
||||
durationMs: Date.now() - start,
|
||||
status: response.status,
|
||||
dryRun,
|
||||
})
|
||||
|
||||
return stampHeaders(response, requestId)
|
||||
} catch (err) {
|
||||
// Resolve the envelope first so the log level can follow the mapped
|
||||
// status — thrown 4xx domain errors are expected outcomes (warn), only
|
||||
// 5xx are runtime errors. v1ErrorResponse logs the error itself at the
|
||||
// same threshold.
|
||||
const response = await v1ErrorResponse(err, log, { requestId })
|
||||
const meta = { durationMs: Date.now() - start, status: response.status }
|
||||
if (response.status < 500) log.warn('op failed', err as Error, meta)
|
||||
else log.error('op failed', err as Error, meta)
|
||||
return response
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function stampHeaders(response: Response, requestId: string): Response {
|
||||
if (!response.headers.get('X-Request-Id')) response.headers.set('X-Request-Id', requestId)
|
||||
if (!response.headers.get(API_V1_VERSION_HEADER)) {
|
||||
response.headers.set(API_V1_VERSION_HEADER, API_V1_VERSION)
|
||||
}
|
||||
// Apply security headers to every wrapped v1 response: same set as the
|
||||
// public discovery routes PLUS X-Robots-Tag noai so authenticated payloads
|
||||
// are excluded from AI training sets (Claude, ChatGPT, Perplexity, Google
|
||||
// -Extended respect this; others won't).
|
||||
for (const [k, v] of Object.entries(WRAPPED_RESPONSE_HEADERS)) {
|
||||
if (!response.headers.get(k)) response.headers.set(k, v)
|
||||
}
|
||||
return response
|
||||
}
|
||||
@@ -0,0 +1,175 @@
|
||||
import { z } from 'zod'
|
||||
import { NextResponse } from 'next/server'
|
||||
import type { Logger } from '@/lib/logger'
|
||||
|
||||
export interface ValidationSuccess<T> {
|
||||
success: true
|
||||
data: T
|
||||
}
|
||||
|
||||
export interface ValidationFailure {
|
||||
success: false
|
||||
response: NextResponse
|
||||
}
|
||||
|
||||
export type ValidationResult<T> = ValidationSuccess<T> | ValidationFailure
|
||||
|
||||
interface ValidationOptions {
|
||||
/** Optional logger; when present, validation failures are logged at warn level. */
|
||||
log?: Logger
|
||||
/** Identifier for the operation/route being validated, included in the log line. */
|
||||
operation?: string
|
||||
}
|
||||
|
||||
/** How many field issues the human-readable `error` summary names before truncating. */
|
||||
const SUMMARY_ISSUE_LIMIT = 3
|
||||
|
||||
/**
|
||||
* Build the human-readable `error` string for a Zod validation failure.
|
||||
*
|
||||
* `errors[]` keeps the full machine-readable detail, but plenty of clients read
|
||||
* only `error`. A constant there ('Validation failed') either reached the user
|
||||
* as English boilerplate in a Swedish UI, or got swallowed by
|
||||
* `getErrorMessage()`'s generic "Något gick fel" fallback because the constant
|
||||
* matches nothing it knows. The 'Valideringsfel' lead-in is load-bearing: it is
|
||||
* what makes `getErrorMessage()` recognize the sentence as an already-Swedish
|
||||
* user message and pass it through verbatim, so clients that forward
|
||||
* `body.error` alone still show the actionable field message.
|
||||
*
|
||||
* `type: 'validation_error'` remains the machine-readable discriminator; nothing
|
||||
* should branch on this prose.
|
||||
*/
|
||||
function summarizeIssues(errors: Array<{ field: string; message: string }>): string {
|
||||
const shown = errors
|
||||
.slice(0, SUMMARY_ISSUE_LIMIT)
|
||||
.map((issue) => (issue.field ? `${issue.field}: ${issue.message}` : issue.message))
|
||||
.filter((text) => text.trim() !== '')
|
||||
|
||||
if (shown.length === 0) return 'Valideringsfel: kontrollera fälten och försök igen.'
|
||||
|
||||
const hidden = errors.length - SUMMARY_ISSUE_LIMIT
|
||||
const more = hidden > 0 ? ` (+${hidden} till)` : ''
|
||||
return `Valideringsfel: ${shown.join('. ')}${more}`
|
||||
}
|
||||
|
||||
function logIssues(
|
||||
options: ValidationOptions | undefined,
|
||||
kind: 'body' | 'query' | 'json',
|
||||
issues: Array<{ field: string; message: string; code: string }> | string,
|
||||
) {
|
||||
if (!options?.log) return
|
||||
options.log.warn('validation failed', {
|
||||
operation: options.operation,
|
||||
kind,
|
||||
...(typeof issues === 'string'
|
||||
? { reason: issues }
|
||||
: { issueCount: issues.length, issues }),
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* Validate a request body against a Zod schema.
|
||||
*
|
||||
* Returns `{ success: true, data }` on valid input, or
|
||||
* `{ success: false, response }` with a 400 NextResponse on failure.
|
||||
*
|
||||
* Usage in an API route:
|
||||
* ```ts
|
||||
* const result = await validateBody(request, CreateInvoiceSchema)
|
||||
* if (!result.success) return result.response
|
||||
* const { data } = result
|
||||
* ```
|
||||
*/
|
||||
export async function validateBody<T>(
|
||||
request: Request,
|
||||
schema: z.ZodType<T>,
|
||||
options?: ValidationOptions,
|
||||
): Promise<ValidationResult<T>> {
|
||||
let body: unknown
|
||||
try {
|
||||
body = await request.json()
|
||||
} catch {
|
||||
logIssues(options, 'json', 'Invalid JSON in request body')
|
||||
return {
|
||||
success: false,
|
||||
response: NextResponse.json(
|
||||
{
|
||||
error: 'Invalid JSON in request body',
|
||||
type: 'validation_error',
|
||||
},
|
||||
{ status: 400 },
|
||||
),
|
||||
}
|
||||
}
|
||||
|
||||
const result = schema.safeParse(body)
|
||||
|
||||
if (!result.success) {
|
||||
const errors = result.error.issues.map((issue) => ({
|
||||
field: issue.path.join('.'),
|
||||
message: issue.message,
|
||||
code: issue.code,
|
||||
}))
|
||||
|
||||
logIssues(options, 'body', errors)
|
||||
|
||||
return {
|
||||
success: false,
|
||||
response: NextResponse.json(
|
||||
{
|
||||
error: summarizeIssues(errors),
|
||||
type: 'validation_error',
|
||||
errors,
|
||||
},
|
||||
{ status: 400 },
|
||||
),
|
||||
}
|
||||
}
|
||||
|
||||
return { success: true, data: result.data }
|
||||
}
|
||||
|
||||
/**
|
||||
* Validate query parameters (from URL searchParams) against a Zod schema.
|
||||
*
|
||||
* Usage:
|
||||
* ```ts
|
||||
* const params = validateQuery(request, VatDeclarationQuerySchema)
|
||||
* if (!params.success) return params.response
|
||||
* const { data } = params
|
||||
* ```
|
||||
*/
|
||||
export function validateQuery<T>(
|
||||
request: Request,
|
||||
schema: z.ZodType<T>,
|
||||
options?: ValidationOptions,
|
||||
): ValidationResult<T> {
|
||||
const url = new URL(request.url)
|
||||
const raw = Object.fromEntries(url.searchParams.entries())
|
||||
|
||||
const result = schema.safeParse(raw)
|
||||
|
||||
if (!result.success) {
|
||||
const errors = result.error.issues.map((issue) => ({
|
||||
field: issue.path.join('.'),
|
||||
message: issue.message,
|
||||
code: issue.code,
|
||||
}))
|
||||
|
||||
logIssues(options, 'query', errors)
|
||||
|
||||
return {
|
||||
success: false,
|
||||
response: NextResponse.json(
|
||||
{
|
||||
error: 'Invalid query parameters',
|
||||
type: 'validation_error',
|
||||
errors,
|
||||
},
|
||||
{ status: 400 },
|
||||
),
|
||||
}
|
||||
}
|
||||
|
||||
return { success: true, data: result.data }
|
||||
}
|
||||
@@ -0,0 +1,129 @@
|
||||
/**
|
||||
* Sibling of withRouteContext for cron endpoints.
|
||||
*
|
||||
* - Verifies CRON_SECRET via verifyCronSecret(); returns the standard envelope
|
||||
* on failure.
|
||||
* - Generates a parent requestId so every per-item log line for a single run
|
||||
* shares a correlation id you can grep for in Vercel logs.
|
||||
* - Provides a `forEach` helper that runs the iteratee in an isolated try/catch
|
||||
* per item and logs the outcome at info/error level. A single failing item
|
||||
* never aborts the run.
|
||||
*
|
||||
* Usage:
|
||||
* export const GET = withCronContext('cron.invoice-reminders', async (ctx) => {
|
||||
* const reminders = await loadDueReminders()
|
||||
* const summary = await ctx.forEach('reminder', reminders, async (item, itemCtx) => {
|
||||
* await sendReminder(item)
|
||||
* })
|
||||
* return NextResponse.json({ data: summary })
|
||||
* })
|
||||
*/
|
||||
|
||||
import { NextResponse } from 'next/server'
|
||||
import { verifyCronSecret } from '@/lib/auth/cron'
|
||||
import { createLogger, type Logger } from '@/lib/logger'
|
||||
import { errorResponse, errorResponseFromCode } from '@/lib/errors/get-structured-error'
|
||||
|
||||
export interface CronItemContext {
|
||||
/** Per-item requestId, child of the run's parent requestId. */
|
||||
requestId: string
|
||||
log: Logger
|
||||
parentRequestId: string
|
||||
}
|
||||
|
||||
interface CronForEachResult {
|
||||
total: number
|
||||
succeeded: number
|
||||
failed: number
|
||||
failures: Array<{ index: number; error: string }>
|
||||
}
|
||||
|
||||
export interface CronContext {
|
||||
requestId: string
|
||||
log: Logger
|
||||
/**
|
||||
* Iterate items with isolated try/catch + structured per-item logs. The
|
||||
* returned summary is suitable to ship in the response body so an operator
|
||||
* can see how many succeeded/failed at a glance.
|
||||
*/
|
||||
forEach<T>(
|
||||
label: string,
|
||||
items: T[],
|
||||
iteratee: (item: T, itemCtx: CronItemContext) => Promise<void>,
|
||||
): Promise<CronForEachResult>
|
||||
}
|
||||
|
||||
type CronHandler = (request: Request, ctx: CronContext) => Promise<NextResponse | Response>
|
||||
|
||||
function generateRequestId(prefix: 'cron' | 'cron_item' = 'cron'): string {
|
||||
return `${prefix}_${crypto.randomUUID()}`
|
||||
}
|
||||
|
||||
export function withCronContext(
|
||||
operation: string,
|
||||
handler: CronHandler,
|
||||
): (request: Request) => Promise<Response> {
|
||||
return async function wrapped(request: Request): Promise<Response> {
|
||||
const requestId = generateRequestId('cron')
|
||||
const start = Date.now()
|
||||
const log = createLogger(`cron/${operation}`, { requestId, operation })
|
||||
|
||||
const authError = verifyCronSecret(request)
|
||||
if (authError) {
|
||||
log.warn('cron auth failed')
|
||||
return errorResponseFromCode('UNAUTHORIZED', log, { requestId })
|
||||
}
|
||||
|
||||
log.info('cron run started')
|
||||
|
||||
const forEach: CronContext['forEach'] = async (label, items, iteratee) => {
|
||||
const result: CronForEachResult = {
|
||||
total: items.length,
|
||||
succeeded: 0,
|
||||
failed: 0,
|
||||
failures: [],
|
||||
}
|
||||
|
||||
for (let i = 0; i < items.length; i++) {
|
||||
const item = items[i]
|
||||
const itemRequestId = generateRequestId('cron_item')
|
||||
const itemLog = log.child({ itemRequestId, itemIndex: i, itemLabel: label })
|
||||
const itemCtx: CronItemContext = {
|
||||
requestId: itemRequestId,
|
||||
log: itemLog,
|
||||
parentRequestId: requestId,
|
||||
}
|
||||
|
||||
try {
|
||||
await iteratee(item, itemCtx)
|
||||
result.succeeded++
|
||||
itemLog.info('cron item ok')
|
||||
} catch (err) {
|
||||
result.failed++
|
||||
const errorMessage = err instanceof Error ? err.message : String(err)
|
||||
result.failures.push({ index: i, error: errorMessage })
|
||||
itemLog.error('cron item failed', err as Error)
|
||||
}
|
||||
}
|
||||
|
||||
return result
|
||||
}
|
||||
|
||||
const ctx: CronContext = { requestId, log, forEach }
|
||||
|
||||
try {
|
||||
const response = await handler(request, ctx)
|
||||
if (response instanceof Response && !response.headers.get('X-Request-Id')) {
|
||||
response.headers.set('X-Request-Id', requestId)
|
||||
}
|
||||
log.info('cron run completed', {
|
||||
durationMs: Date.now() - start,
|
||||
status: response.status,
|
||||
})
|
||||
return response
|
||||
} catch (err) {
|
||||
log.error('cron run failed', err as Error, { durationMs: Date.now() - start })
|
||||
return errorResponse(err, log, { requestId })
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,200 @@
|
||||
/**
|
||||
* Single wrapper that gives every API route the same shape:
|
||||
*
|
||||
* - generates a request id (`req_<uuid>`) and threads it through the logger
|
||||
* - resolves auth via requireAuth() and (by default) the active companyId
|
||||
* - emits one structured `info` log on completion with duration
|
||||
* - converts any thrown value into the canonical error envelope via
|
||||
* errorResponse(); the request id appears in the response body and the
|
||||
* X-Request-Id response header. Unhandled errors are logged ("op failed")
|
||||
* with the resolved { requestId, operation, userId, companyId } context.
|
||||
*
|
||||
* Usage:
|
||||
* export const POST = withRouteContext('invoice.send', async (req, ctx) => {
|
||||
* // ctx.requestId, ctx.log, ctx.user, ctx.supabase, ctx.companyId
|
||||
* const result = await sendInvoice(...)
|
||||
* return NextResponse.json({ data: result })
|
||||
* })
|
||||
*
|
||||
* For dynamic routes the second parameter is the Next.js params promise:
|
||||
* export const POST = withRouteContext('invoice.send', async (req, ctx, { params }) => {
|
||||
* const { id } = await params
|
||||
* ...
|
||||
* })
|
||||
*/
|
||||
|
||||
import type { SupabaseClient, User } from '@supabase/supabase-js'
|
||||
import { NextResponse } from 'next/server'
|
||||
import { requireAuth } from '@/lib/auth/require-auth'
|
||||
import { requireWritePermission } from '@/lib/auth/require-write'
|
||||
import { getActiveCompanyId } from '@/lib/company/context'
|
||||
import { createLogger, type Logger } from '@/lib/logger'
|
||||
import { errorResponse, errorResponseFromCode } from '@/lib/errors/get-structured-error'
|
||||
|
||||
export interface RouteContext {
|
||||
/** Stable id for this HTTP request: appears in logs, error envelope, X-Request-Id header. */
|
||||
requestId: string
|
||||
/** Logger pre-bound with { requestId, userId, companyId, operation }. */
|
||||
log: Logger
|
||||
/** Authenticated user. Always present: wrapper short-circuits with 401 otherwise. */
|
||||
user: User
|
||||
/** Authenticated Supabase client (request-scoped, RLS active). */
|
||||
supabase: SupabaseClient
|
||||
/**
|
||||
* Resolved active company id. The wrapper short-circuits with
|
||||
* COMPANY_CONTEXT_MISSING before invoking the handler when no company is
|
||||
* resolved, so handlers can treat this as guaranteed non-null. Routes that
|
||||
* need to opt out of the guarantee (e.g. onboarding) shouldn't use
|
||||
* withRouteContext.
|
||||
*
|
||||
* Membership invariant: `getActiveCompanyId` only returns a company the
|
||||
* authenticated user is a current member of (it validates
|
||||
* `company_members` and excludes archived companies). The handler may
|
||||
* therefore treat `companyId` as "a company the caller is authorized to
|
||||
* read", and routes that mutate state additionally enforce a non-viewer
|
||||
* role via `requireWrite: true`. ASVS V8.2.1 / SOC 2 CC6.3.
|
||||
*/
|
||||
companyId: string
|
||||
}
|
||||
|
||||
interface RouteContextOptions {
|
||||
/**
|
||||
* Defaults to false. When true, the wrapper rejects callers whose role in
|
||||
* the active company is `viewer` (or who have no membership). Mirrors the
|
||||
* existing requireWritePermission() helper so mutating routes can drop two
|
||||
* lines of boilerplate.
|
||||
*/
|
||||
requireWrite?: boolean
|
||||
}
|
||||
|
||||
// Next.js 16 always passes a `{ params: Promise<...> }` second arg to route
|
||||
// handlers: including on non-dynamic routes, where it's `Promise<{}>`. The
|
||||
// generic defaults to that empty shape so static routes type-check without
|
||||
// having to declare any params at the call site.
|
||||
// eslint-disable-next-line @typescript-eslint/no-empty-object-type
|
||||
type DynamicParams = { params: Promise<Record<string, string | string[]>> } | { params: Promise<{}> }
|
||||
|
||||
type RouteHandler<P extends DynamicParams = { params: Promise<Record<string, never>> }> = (
|
||||
request: Request,
|
||||
ctx: RouteContext,
|
||||
params: P,
|
||||
) => Promise<NextResponse | Response>
|
||||
|
||||
function generateRequestId(): string {
|
||||
// crypto.randomUUID is available in Node 20+/edge runtimes used by Next.js.
|
||||
return `req_${crypto.randomUUID()}`
|
||||
}
|
||||
|
||||
export function withRouteContext<P extends DynamicParams = { params: Promise<Record<string, never>> }>(
|
||||
operation: string,
|
||||
handler: RouteHandler<P>,
|
||||
options: RouteContextOptions = {},
|
||||
): (request: Request, params: P) => Promise<Response> {
|
||||
const { requireWrite = false } = options
|
||||
|
||||
return async function wrapped(request: Request, params: P): Promise<Response> {
|
||||
const requestId = generateRequestId()
|
||||
const start = Date.now()
|
||||
const log = createLogger(`api/${operation}`, { requestId, operation })
|
||||
// Upgraded as request context resolves, so an unhandled throw in the catch
|
||||
// below is logged with the richest available { userId, companyId } context
|
||||
// (audit trail / OWASP V16), not just { requestId, operation }.
|
||||
let errLog = log
|
||||
|
||||
try {
|
||||
const authStart = Date.now()
|
||||
const auth = await requireAuth()
|
||||
const authMs = Date.now() - authStart
|
||||
if (auth.error) {
|
||||
log.warn('auth failed', { status: auth.error.status })
|
||||
// Pass through requireAuth's response unchanged for backwards-compat
|
||||
// with existing route tests; only inject the request id header so
|
||||
// support can still trace the request.
|
||||
if (!auth.error.headers.get('X-Request-Id')) {
|
||||
auth.error.headers.set('X-Request-Id', requestId)
|
||||
}
|
||||
return auth.error
|
||||
}
|
||||
|
||||
const { user, supabase } = auth
|
||||
const userLog = log.child({ userId: user.id })
|
||||
errLog = userLog
|
||||
|
||||
let companyId: string | null = null
|
||||
const companyStart = Date.now()
|
||||
try {
|
||||
companyId = await getActiveCompanyId(supabase, user.id)
|
||||
} catch (err) {
|
||||
userLog.error('failed to resolve active company', err as Error)
|
||||
}
|
||||
const companyMs = Date.now() - companyStart
|
||||
|
||||
if (!companyId) {
|
||||
return errorResponseFromCode('COMPANY_CONTEXT_MISSING', userLog, { requestId })
|
||||
}
|
||||
|
||||
if (requireWrite) {
|
||||
// Delegate to the existing helper so tests that already mock it
|
||||
// continue to work. The helper returns its own 403 NextResponse;
|
||||
// we wrap it in our request-id header for traceability. The
|
||||
// company id resolved above is handed over so the helper does not
|
||||
// repeat the resolve_active_company round trip (measured ~40 ms p50
|
||||
// on prod) on every write route.
|
||||
const writeCheck = await requireWritePermission(supabase, user.id, { companyId })
|
||||
if (!writeCheck.ok) {
|
||||
userLog.warn('write permission denied')
|
||||
if (!writeCheck.response.headers.get('X-Request-Id')) {
|
||||
writeCheck.response.headers.set('X-Request-Id', requestId)
|
||||
}
|
||||
return writeCheck.response
|
||||
}
|
||||
}
|
||||
|
||||
const ctx: RouteContext = {
|
||||
requestId,
|
||||
log: userLog.child({ companyId }),
|
||||
user,
|
||||
supabase,
|
||||
companyId,
|
||||
}
|
||||
errLog = ctx.log
|
||||
|
||||
const handlerStart = Date.now()
|
||||
const response = await handler(request, ctx, params)
|
||||
const handlerMs = Date.now() - handlerStart
|
||||
|
||||
if (response instanceof Response && !response.headers.get('X-Request-Id')) {
|
||||
response.headers.set('X-Request-Id', requestId)
|
||||
}
|
||||
// Per-phase breakdown, visible in browser devtools (Timing tab) and in
|
||||
// the op-completed log: separates the wrapper's own overhead (auth
|
||||
// round trip + company resolution) from the handler's real work, so
|
||||
// latency regressions can be attributed without guessing.
|
||||
if (response instanceof Response && !response.headers.get('Server-Timing')) {
|
||||
response.headers.set(
|
||||
'Server-Timing',
|
||||
`auth;dur=${authMs}, company;dur=${companyMs}, handler;dur=${handlerMs}`,
|
||||
)
|
||||
}
|
||||
|
||||
ctx.log.info('op completed', {
|
||||
durationMs: Date.now() - start,
|
||||
status: response.status,
|
||||
authMs,
|
||||
companyMs,
|
||||
handlerMs,
|
||||
})
|
||||
return response
|
||||
} catch (err) {
|
||||
// Resolve the envelope first so the log level can follow the mapped
|
||||
// status — thrown 4xx domain errors are expected outcomes (warn), only
|
||||
// 5xx are runtime errors. errorResponse logs the error itself at the
|
||||
// same threshold.
|
||||
const response = errorResponse(err, errLog, { requestId })
|
||||
const meta = { durationMs: Date.now() - start, status: response.status }
|
||||
if (response.status < 500) errLog.warn('op failed', err as Error, meta)
|
||||
else errLog.error('op failed', err as Error, meta)
|
||||
return response
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user