docs(production): standardiserad produktionsberedskap och gap-analys

Lägger docs/production-readiness.md och siax/production-gaps.json enligt SIAX Master Definition of Done. Underlag: git-, kod- och live-evidens 2026-11-11. Nivån är evidensbaserad, inte ett leveransgodkännande.
This commit is contained in:
2026-11-10 09:15:21 +01:00
parent 0fda8cae48
commit 2bee8eb778
6135 changed files with 4 additions and 1718997 deletions
@@ -1,182 +0,0 @@
// 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",
]
`;
@@ -1,154 +0,0 @@
/**
* 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()
})
})
@@ -1,58 +0,0 @@
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',
)
})
})
-59
View File
@@ -1,59 +0,0 @@
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'])
})
})
@@ -1,40 +0,0 @@
/**
* 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')
})
})
@@ -1,110 +0,0 @@
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)
})
})
@@ -1,100 +0,0 @@
/**
* 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([])
})
})
@@ -1,91 +0,0 @@
/**
* 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()
})
})
@@ -1,171 +0,0 @@
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)
})
})
-132
View File
@@ -1,132 +0,0 @@
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 })
})
})
@@ -1,131 +0,0 @@
/**
* 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')
})
})
-86
View File
@@ -1,86 +0,0 @@
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',
})
})
})
@@ -1,118 +0,0 @@
/**
* 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([])
})
})
@@ -1,80 +0,0 @@
/**
* 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)
}
})
})
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff