Fix/attributes config (#926)

* fix(git): pin LF on generated extension registry and vitest snapshots

setup:extensions and vitest write these files with LF; with
core.autocrlf=true git expects CRLF and flags them as phantom
modifications on every dev/build run.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* fix(security): enforce MFA on mcp-oauth consent and gate viewer storno route

mcp-oauth/authorize renders an HTML consent page and issues 303 redirects that withRouteContext cannot express, so it kept raw getUser() and thereby skipped the AAL2 gate: a password-only (AAL1) session could approve consent that mints a long-lived, MFA-bypassing API key. Add a route-local requireAal2() step-up on GET and POST; AAL1 sessions redirect to /mfa/verify, BankID users are exempt.

Separately, POST /api/reports/vat-declaration/rc-basis-gaps/fix calls correctEntry() (storno of a posted entry) but lacked requireWrite, so viewer-role members could trigger it. Add { requireWrite: true }.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* fix(api): route transactions endpoints through withRouteContext

Migrate the transactions routes off hand-rolled supabase.auth.getUser() onto the MFA-enforcing withRouteContext wrapper; add requireWrite on mutating handlers (book, uncategorize, attach-document, ignore, batch-match, create-from-document). Behavior and response shapes preserved; tests updated to the wrapper mock pattern.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* fix(api): route SIE import and bank reconciliation through withRouteContext

Migrate import/sie and reconciliation/bank routes onto the MFA-enforcing wrapper; requireWrite on mutations (import execute, create-accounts, mappings write verbs, link/unlink/run/mark-opening-balance). Reads (status, unmatched-entries) stay ungated. Response shapes preserved; tests added/updated to the wrapper mock pattern.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* fix(api): route salary endpoints through withRouteContext

Migrate salary employees and runs routes (plus ku, payroll-config, tax-tables) onto the MFA-enforcing wrapper; requireWrite on mutations. Personnummer masking/encryption untouched; file downloads (AGI XML, payslip PDF, payment files) keep their headers. Two payment-file GETs retain requireWrite because they stamp *_file_generated_at and previously gated viewers. Tests added/updated to the wrapper mock pattern.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* fix(api): route report endpoints through withRouteContext

Migrate the read-only report routes (trial balance, balansrapport, resultatrapport, income statement, ledgers, KPI, VAT declaration, salary journal, monthly breakdown, journal register, continuity check, full archive, etc.) onto the MFA-enforcing wrapper. All read-only, no requireWrite. JSON/XLSX/PDF/ZIP response bodies and headers preserved byte-for-byte; tests updated to the wrapper mock pattern.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* fix(api): route invoices, skatteverket, agent and extension endpoints through withRouteContext

Migrate invoices, supplier-invoices, skatteverket tax-payments, and dynamic extension routes onto the MFA-enforcing wrapper with requireWrite on mutations. The two NDJSON streaming agent routes (invoke, onboarding/stream) use requireAuth() directly (the wrapper can't wrap a streaming response) so MFA is still enforced. skatteverket payment-file GET keeps requireWrite (stamps a generated-at field). Response shapes and file headers preserved; tests added/updated.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* fix(api): route documents, events, team and account endpoints through withRouteContext

Migrate documents, events, kpi/preferences, vat/validate, support/contact onto the MFA-enforcing wrapper with requireWrite on mutations. account/password, team/accept and team/members use requireAuth() directly (user-level or pre-membership flows with no active company context) so MFA is still enforced. events keeps its dual API-key-or-session auth. Document retention guard untouched; tests added/updated.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* fix(api): route settings and pending-operations endpoints through withRouteContext

Migrate settings (api-keys, oauth-clients, booking-templates, counterparty-templates, logo, company settings) and pending-operations (commit, bulk-commit, reject, edit-before-approve) onto the MFA-enforcing wrapper with requireWrite on mutations. Credential-guarding routes keep their per-user ownership filters. Response shapes preserved; tests added/updated to the wrapper mock pattern.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* chore(guards): ratchet raw-route-auth baseline 119->1 after A1 migration

Lock in the withRouteContext migration so the count cannot regress. The single remaining entry, mcp-oauth/authorize, is a documented exception (HTML consent + redirects, MFA enforced via route-local step-up). Record the campaign and requireWrite decisions in DECISIONS.md.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* feat(vat): add eSKD momsdeklaration file export for "Deklarera via fil"

Generate the Skatteverket eSKDUpload v6.0 XML file so users can file VAT by
upload instead of typing every ruta into the form. Extract buildFiledAmounts()
as the shared whole-krona source of truth (öre truncated per SFL 22 kap 1 §) so
the XML file and the manual-filing PDF can never disagree. Adds the /eskd API
route, an XML option in the report export menu, and the upload button on the
manual-filing card. Strings in sv + en.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* feat(vat): add 'vat_settlement' source type and update related components

* fix(booking): adjust search input layout and enable autofocus

* fix(vat): support 12-digit org numbers and adjust emission order for eSKD file

* fix(migration): add 'vat_settlement' to journal_entries.source_type CHECK

---------

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
Mattsson
2026-07-08 09:54:46 +02:00
committed by GitHub
co-authored by Claude Opus 4.8
parent 63e05c4eec
commit abe9ac9d8c
204 changed files with 9841 additions and 6362 deletions
@@ -1,9 +1,12 @@
import { describe, it, expect, vi, beforeEach } from 'vitest'
import { NextResponse } from 'next/server'
import { parseJsonResponse, createQueuedMockSupabase } from '@/tests/helpers'
const { supabase: mockSupabase, enqueue, reset } = createQueuedMockSupabase()
vi.mock('@/lib/supabase/server', () => ({
createClient: () => Promise.resolve(mockSupabase),
const requireAuthMock = vi.fn()
vi.mock('@/lib/auth/require-auth', () => ({
requireAuth: (...args: unknown[]) => requireAuthMock(...args),
}))
vi.mock('@/lib/company/context', () => ({
@@ -11,8 +14,9 @@ vi.mock('@/lib/company/context', () => ({
getActiveCompanyId: vi.fn().mockResolvedValue('company-1'),
}))
const requireWriteMock = vi.fn()
vi.mock('@/lib/auth/require-write', () => ({
requireWritePermission: vi.fn().mockResolvedValue({ ok: true }),
requireWritePermission: (...args: unknown[]) => requireWriteMock(...args),
}))
vi.mock('@/lib/init', () => ({
@@ -26,11 +30,14 @@ const mockUser = { id: 'user-1', email: 'test@test.se' }
beforeEach(() => {
vi.clearAllMocks()
reset()
mockSupabase.auth.getUser.mockResolvedValue({ data: { user: mockUser } })
requireAuthMock.mockResolvedValue({ user: mockUser, supabase: mockSupabase })
requireWriteMock.mockResolvedValue({ ok: true })
})
const VALID_UUID = '11111111-1111-4111-8111-111111111111'
const routeParams = { params: Promise.resolve({}) }
function makeReq(body: unknown) {
return new Request('http://localhost/api/transactions/create-from-document', {
method: 'POST',
@@ -56,28 +63,43 @@ function validBody(overrides: Partial<{
describe('POST /api/transactions/create-from-document', () => {
it('returns 401 when not authenticated', async () => {
mockSupabase.auth.getUser.mockResolvedValue({ data: { user: null } })
const res = await POST(makeReq(validBody()))
requireAuthMock.mockResolvedValue({
user: null,
supabase: mockSupabase,
error: NextResponse.json({ error: 'Unauthorized' }, { status: 401 }),
})
const res = await POST(makeReq(validBody()), routeParams)
const { status, body } = await parseJsonResponse(res)
expect(status).toBe(401)
expect(body).toEqual({ error: 'Unauthorized' })
})
it('returns 403 when the caller is a viewer', async () => {
requireWriteMock.mockResolvedValue({
ok: false,
response: NextResponse.json({ error: 'Forbidden' }, { status: 403 }),
})
const res = await POST(makeReq(validBody()), routeParams)
const { status, body } = await parseJsonResponse(res)
expect(status).toBe(403)
expect(body).toEqual({ error: 'Forbidden' })
})
it('returns 400 when the body is invalid', async () => {
const res = await POST(makeReq({ inbox_item_id: 'not-a-uuid', amount: 0 }))
const res = await POST(makeReq({ inbox_item_id: 'not-a-uuid', amount: 0 }), routeParams)
const { status } = await parseJsonResponse(res)
expect(status).toBe(400)
})
it('returns 400 when amount is zero (schema refine)', async () => {
const res = await POST(makeReq(validBody({ amount: 0 })))
const res = await POST(makeReq(validBody({ amount: 0 })), routeParams)
const { status } = await parseJsonResponse(res)
expect(status).toBe(400)
})
it('returns 404 when the inbox item is not in the user company', async () => {
enqueue({ data: null, error: null }) // inbox item lookup misses
const res = await POST(makeReq(validBody()))
const res = await POST(makeReq(validBody()), routeParams)
const { status, body } = await parseJsonResponse<{ error: string }>(res)
expect(status).toBe(404)
expect(body.error).toBe('Inbox item not found')
@@ -94,7 +116,7 @@ describe('POST /api/transactions/create-from-document', () => {
},
error: null,
})
const res = await POST(makeReq(validBody()))
const res = await POST(makeReq(validBody()), routeParams)
const { status, body } = await parseJsonResponse<{ error: string }>(res)
expect(status).toBe(409)
expect(body.error).toMatch(/redan kopplad/)
@@ -111,7 +133,7 @@ describe('POST /api/transactions/create-from-document', () => {
},
error: null,
})
const res = await POST(makeReq(validBody()))
const res = await POST(makeReq(validBody()), routeParams)
const { status, body } = await parseJsonResponse<{ error: string }>(res)
expect(status).toBe(409)
expect(body.error).toMatch(/redan bokförd/)
@@ -131,7 +153,7 @@ describe('POST /api/transactions/create-from-document', () => {
enqueue({ data: { id: 'new-tx-1' }, error: null }) // insert
enqueue({ data: [{ id: VALID_UUID }], error: null }) // inbox update: one row affected
const res = await POST(makeReq(validBody()))
const res = await POST(makeReq(validBody()), routeParams)
const { status, body } = await parseJsonResponse<{
data: { transaction_id: string; inbox_item_id: string; document_id: string }
}>(res)
@@ -159,7 +181,7 @@ describe('POST /api/transactions/create-from-document', () => {
enqueue({ data: [], error: null }) // inbox update affects zero rows: lost the race
enqueue({ data: null, error: null }) // rollback delete of the orphan
const res = await POST(makeReq(validBody()))
const res = await POST(makeReq(validBody()), routeParams)
const { status, body } = await parseJsonResponse<{ error: string }>(res)
expect(status).toBe(409)
expect(body.error).toMatch(/parallell begäran/)
@@ -182,7 +204,7 @@ describe('POST /api/transactions/create-from-document', () => {
enqueue({ data: { id: 'new-tx-3' }, error: null })
enqueue({ data: [{ id: VALID_UUID }], error: null })
const res = await POST(makeReq(validBody()))
const res = await POST(makeReq(validBody()), routeParams)
const { status } = await parseJsonResponse(res)
expect(status).toBe(200)
})
@@ -201,7 +223,7 @@ describe('POST /api/transactions/create-from-document', () => {
enqueue({ data: null, error: { message: 'db down' } }) // insert fails
// Silence the console.error
const spy = vi.spyOn(console, 'error').mockImplementation(() => {})
const res = await POST(makeReq(validBody()))
const res = await POST(makeReq(validBody()), routeParams)
const { status, body } = await parseJsonResponse<{ error: string }>(res)
expect(status).toBe(500)
expect(body.error).toMatch(/Kunde inte skapa transaktion/)
@@ -222,7 +244,7 @@ describe('POST /api/transactions/create-from-document', () => {
enqueue({ data: { id: 'new-tx-2' }, error: null }) // insert ok
enqueue({ data: null, error: { message: 'rls' } }) // link update fails
const spy = vi.spyOn(console, 'error').mockImplementation(() => {})
const res = await POST(makeReq(validBody()))
const res = await POST(makeReq(validBody()), routeParams)
const { status, body } = await parseJsonResponse<{
data: { transaction_id: string; inbox_link_failed?: boolean }
}>(res)
+101 -109
View File
@@ -1,10 +1,8 @@
import { createClient } from '@/lib/supabase/server'
import { NextResponse } from 'next/server'
import { ensureInitialized } from '@/lib/init'
import { withRouteContext } from '@/lib/api/with-route-context'
import { validateBody } from '@/lib/api/validate'
import { CreateTransactionFromDocumentSchema } from '@/lib/api/schemas'
import { requireCompanyId } from '@/lib/company/context'
import { requireWritePermission } from '@/lib/auth/require-write'
ensureInitialized()
@@ -20,120 +18,114 @@ ensureInitialized()
* Use case: receipt in the inbox has no matching bank transaction
* (cash purchase, personal-card expense, missed sync).
*/
export async function POST(request: Request) {
const supabase = await createClient()
export const POST = withRouteContext(
'transaction.create_from_document',
async (request, { supabase, user, companyId }) => {
const validation = await validateBody(request, CreateTransactionFromDocumentSchema)
if (!validation.success) return validation.response
const { inbox_item_id, amount, transaction_date, description } = validation.data
const { data: { user } } = await supabase.auth.getUser()
if (!user) return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
const { data: item, error: itemError } = await supabase
.from('invoice_inbox_items')
.select('id, document_id, matched_transaction_id, created_supplier_invoice_id, extracted_data')
.eq('id', inbox_item_id)
.eq('company_id', companyId)
.maybeSingle()
const writeCheck = await requireWritePermission(supabase, user.id)
if (!writeCheck.ok) return writeCheck.response
if (itemError || !item) {
return NextResponse.json({ error: 'Inbox item not found' }, { status: 404 })
}
if (item.matched_transaction_id) {
return NextResponse.json(
{ error: 'Inkorgsposten är redan kopplad till en transaktion.' },
{ status: 409 },
)
}
if (item.created_supplier_invoice_id) {
return NextResponse.json(
{ error: 'Inkorgsposten är redan bokförd som leverantörsfaktura.' },
{ status: 409 },
)
}
const companyId = await requireCompanyId(supabase, user.id)
// Allowlist the currency: extracted_data.invoice.currency comes from the
// (deterministic, but still untrusted) PDF extractor, so an arbitrary
// string like "XYZ" or '"SEK\'"' could otherwise be persisted directly to
// the transactions table and break later formatCurrency / journal-entry
// bookings (BFL 5 kap 6 §). Coerce anything outside the supported set
// to SEK; the user can change it manually on the transaction.
const ALLOWED_CURRENCIES = new Set(['SEK', 'EUR', 'USD', 'GBP', 'NOK', 'DKK'])
const extractedCurrency = (
item.extracted_data as { invoice?: { currency?: string } } | null
)?.invoice?.currency
const currency =
extractedCurrency && ALLOWED_CURRENCIES.has(extractedCurrency)
? extractedCurrency
: 'SEK'
const validation = await validateBody(request, CreateTransactionFromDocumentSchema)
if (!validation.success) return validation.response
const { inbox_item_id, amount, transaction_date, description } = validation.data
const { data: newTx, error: insertError } = await supabase
.from('transactions')
.insert({
company_id: companyId,
user_id: user.id,
date: transaction_date,
description,
amount,
currency,
category: 'uncategorized',
is_business: null,
import_source: 'manual',
document_id: item.document_id,
})
.select('id')
.single()
const { data: item, error: itemError } = await supabase
.from('invoice_inbox_items')
.select('id, document_id, matched_transaction_id, created_supplier_invoice_id, extracted_data')
.eq('id', inbox_item_id)
.eq('company_id', companyId)
.maybeSingle()
if (insertError || !newTx) {
console.error('[create-from-document] Failed to insert transaction:', insertError)
return NextResponse.json({ error: 'Kunde inte skapa transaktion.' }, { status: 500 })
}
if (itemError || !item) {
return NextResponse.json({ error: 'Inbox item not found' }, { status: 404 })
}
if (item.matched_transaction_id) {
return NextResponse.json(
{ error: 'Inkorgsposten är redan kopplad till en transaktion.' },
{ status: 409 },
)
}
if (item.created_supplier_invoice_id) {
return NextResponse.json(
{ error: 'Inkorgsposten är redan bokförd som leverantörsfaktura.' },
{ status: 409 },
)
}
// Concurrency guard: the .is('matched_transaction_id', null) predicate +
// the rows-affected check turn this into an optimistic-lock release. If
// two requests with the same inbox_item_id race past the earlier
// matched_transaction_id check, only the first UPDATE will match a row
// here. The loser's transaction insert is then an orphan we proactively
// delete so the user doesn't get a duplicate uncategorized row.
const { data: linked, error: linkError } = await supabase
.from('invoice_inbox_items')
.update({ matched_transaction_id: newTx.id })
.eq('id', inbox_item_id)
.eq('company_id', companyId)
.is('matched_transaction_id', null)
.select('id')
// Allowlist the currency: extracted_data.invoice.currency comes from the
// (deterministic, but still untrusted) PDF extractor, so an arbitrary
// string like "XYZ" or '"SEK\'"' could otherwise be persisted directly to
// the transactions table and break later formatCurrency / journal-entry
// bookings (BFL 5 kap 6 §). Coerce anything outside the supported set
// to SEK; the user can change it manually on the transaction.
const ALLOWED_CURRENCIES = new Set(['SEK', 'EUR', 'USD', 'GBP', 'NOK', 'DKK'])
const extractedCurrency = (
item.extracted_data as { invoice?: { currency?: string } } | null
)?.invoice?.currency
const currency =
extractedCurrency && ALLOWED_CURRENCIES.has(extractedCurrency)
? extractedCurrency
: 'SEK'
if (linkError) {
console.error('[create-from-document] Failed to link inbox item:', linkError)
// Transaction was created; surface a 200 with a warning so the user can
// still find it under Transaktioner: the inbox-link orphan is recoverable.
return NextResponse.json({
data: { transaction_id: newTx.id, inbox_link_failed: true },
})
}
const { data: newTx, error: insertError } = await supabase
.from('transactions')
.insert({
company_id: companyId,
user_id: user.id,
date: transaction_date,
description,
amount,
currency,
category: 'uncategorized',
is_business: null,
import_source: 'manual',
document_id: item.document_id,
})
.select('id')
.single()
if (!linked || linked.length === 0) {
// Lost a race: another concurrent request linked the inbox item first.
// Roll back our newly-created transaction (only safe because we own it
// and it has no journal_entry_id yet) and return 409 so the client can
// refetch and reuse the winning transaction instead of creating a dupe.
// Re-assert company_id on the delete (defence in depth: newTx.id is a
// fresh UUID from a company-scoped insert above, but scoping the rollback
// makes the invariant explicit).
await supabase.from('transactions').delete().eq('id', newTx.id).eq('company_id', companyId)
return NextResponse.json(
{ error: 'Inkorgsposten kopplades av en parallell begäran. Försök igen.' },
{ status: 409 },
)
}
if (insertError || !newTx) {
console.error('[create-from-document] Failed to insert transaction:', insertError)
return NextResponse.json({ error: 'Kunde inte skapa transaktion.' }, { status: 500 })
}
// Concurrency guard: the .is('matched_transaction_id', null) predicate +
// the rows-affected check turn this into an optimistic-lock release. If
// two requests with the same inbox_item_id race past the earlier
// matched_transaction_id check, only the first UPDATE will match a row
// here. The loser's transaction insert is then an orphan we proactively
// delete so the user doesn't get a duplicate uncategorized row.
const { data: linked, error: linkError } = await supabase
.from('invoice_inbox_items')
.update({ matched_transaction_id: newTx.id })
.eq('id', inbox_item_id)
.eq('company_id', companyId)
.is('matched_transaction_id', null)
.select('id')
if (linkError) {
console.error('[create-from-document] Failed to link inbox item:', linkError)
// Transaction was created; surface a 200 with a warning so the user can
// still find it under Transaktioner: the inbox-link orphan is recoverable.
return NextResponse.json({
data: { transaction_id: newTx.id, inbox_link_failed: true },
data: { transaction_id: newTx.id, inbox_item_id, document_id: item.document_id },
})
}
if (!linked || linked.length === 0) {
// Lost a race: another concurrent request linked the inbox item first.
// Roll back our newly-created transaction (only safe because we own it
// and it has no journal_entry_id yet) and return 409 so the client can
// refetch and reuse the winning transaction instead of creating a dupe.
// Re-assert company_id on the delete (defence in depth: newTx.id is a
// fresh UUID from a company-scoped insert above, but scoping the rollback
// makes the invariant explicit).
await supabase.from('transactions').delete().eq('id', newTx.id).eq('company_id', companyId)
return NextResponse.json(
{ error: 'Inkorgsposten kopplades av en parallell begäran. Försök igen.' },
{ status: 409 },
)
}
return NextResponse.json({
data: { transaction_id: newTx.id, inbox_item_id, document_id: item.document_id },
})
}
},
{ requireWrite: true },
)