fix(restore): återställ default branch-filer som raderades av docs-publiceringen (7e33543)
masterplan-lock / check (push) Successful in 19s
ci / sonar (push) Failing after 21s
security / scan (push) Failing after 1m37s

Å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:
2026-11-10 09:37:22 +01:00
parent 077251ac94
commit e7f0070e84
6135 changed files with 1718997 additions and 4 deletions
@@ -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',
)
})
})
+59
View File
@@ -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)
})
})
+132
View File
@@ -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')
})
})
+86
View File
@@ -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)
}
})
})
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
+123
View File
@@ -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
}
+35
View File
@@ -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.' },
}),
}
}
}
+74
View File
@@ -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 }
}
+66
View File
@@ -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 })
}
+217
View File
@@ -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),
},
})
}
+69
View File
@@ -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 }
}
File diff suppressed because one or more lines are too long
+192
View File
@@ -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 {}
+21
View File
@@ -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`
}
+186
View File
@@ -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
}
+47
View File
@@ -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
}
+120
View File
@@ -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])
}
File diff suppressed because it is too large Load Diff
+219
View File
@@ -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',
},
}),
}
}
}

Some files were not shown because too many files have changed in this diff Show More