Fix/chrome pdf preview csp (#572)

* feat: add option to exclude year-end closing entries in SIE export and related reports

* delete docs

* fix: allow Chrome's PDF viewer in verifikat document preview

The /api/documents/:id/inline route shipped with
`object-src 'none'` in its CSP, which blocked Chrome's built-in PDF
viewer (it renders inline PDFs via an internal <embed>). Users on
Chrome saw "Det här innehållet har blockerats" when expanding a PDF
attachment in the bookkeeping view; Firefox (PDF.js) and Edge (own
viewer) were unaffected, and JPGs worked because <img> isn't subject
to object-src.

Drops the CSP for this route to the minimum needed for embeddability:
`frame-ancestors 'self'`. X-Content-Type-Options: nosniff plus the
fixed Content-Type from the handler already block MIME confusion;
X-Frame-Options: SAMEORIGIN + frame-ancestors still block clickjacking.

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

* feat(auth): add webmail deep link to email confirmation screens

Mirrors Stripe's signup UX: after asking the user to verify their email,
detect their webmail provider from the domain and show a button that
opens the inbox in a new tab. Gmail gets a from:<sender> search
pre-populated; Outlook/Yahoo/iCloud/Proton open the inbox directly.
Unknown / custom domains fall back to the existing copy.

Sender address is configurable via NEXT_PUBLIC_BRANDING_AUTH_EMAIL_FROM
(default noreply@gnubok.se) so white-label installs can match their
Supabase Auth SMTP config.

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

* fix(auth): unblock first-time password set for BankID users with MFA

Supabase rejects updateUser({password}) and mfa.unenroll with "AAL2 session
is required" whenever a TOTP factor is enrolled. BankID magic-link logins
produce AAL1, and middleware skips MFA enforcement for bankid_linked users,
so they had no path to AAL2 — leaving them unable to set a backup password
or disable MFA without going through the email-recovery escape hatch.

- /api/account/password: branch on app_metadata.has_password. First-time set
  writes via service.auth.admin.updateUserById (no existing credential to
  protect, AAL2 guard does not apply). Change-password keeps the user-session
  updateUser so AAL2 still fires for credential rotation.
- /mfa/verify: accept a safeReturnTo query param and route there after
  successful verify, so step-up flows can land back where they came from.
- SecuritySettings: detect the AAL2 error from both change-password and
  mfa.unenroll and redirect through /mfa/verify?returnTo=/settings/account
  instead of toasting a dead-end error.

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

* Add tests and rounding utility for öre precision in bokslut calculations

- Implemented `roundOre` function for rounding SEK amounts to two decimal places, ensuring consistent monetary calculations.
- Introduced `ORE_TOLERANCE` constant for comparing rounded amounts, facilitating invariant checks in financial entries.
- Created comprehensive tests for `roundOre`, covering typical cases, edge cases, and idempotency.
- Added year-end invariants tests to verify database-level guarantees for closing entries, ensuring they balance to the öre and reject discrepancies.
- Developed end-to-end tests for the dispositions chain, validating the correctness of calculations across various scenarios.

* fix: update PDF rendering to remove Swish QR code generation and set default to disable Swish visibility

* fix: enhance security by rejecting data URIs in safeReturnTo function tests

* fix: improve rounding logic in roundOre function and add customer_type migration

* fix: add customer_type column to customers and enforce CHECK constraint

---------

Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
Mattsson
2026-05-26 22:29:41 +02:00
committed by GitHub
co-authored by Claude Opus 4.7
parent 0087b7be3f
commit 32d9978f1b
207 changed files with 24187 additions and 1052 deletions
@@ -8,9 +8,12 @@ import { seedCompany } from '@/tests/pg/fixtures'
// (added in migration 20260517150000) blocks duplicate (company_id,
// file_hash) rows for active statuses but allows them once a prior row
// is marked 'replaced' or 'failed'.
// 2. The replace_sie_import RPC cancels journal entries with
// source_type='import' while leaving user-created entries
// (source_type='manual', 'bank_transaction', etc.) intact.
// 2. The replace_sie_import RPC hard-deletes journal entries with
// source_type='import' (since 20260526120000), detaches user-attached
// documents from them, clears the fiscal-period opening-balance
// pointer if it came from the import, and resets voucher_sequences
// so the next re-import restarts the series. User-created entries
// (source_type='manual', 'bank_transaction', etc.) are left intact.
async function insertSIEImport(params: {
companyId: string
@@ -53,6 +56,7 @@ async function insertPostedEntry(params: {
fiscalPeriodId: string
sourceType: 'import' | 'manual' | 'bank_transaction'
voucherNumber: number
voucherSeries?: string
entryDate?: string
}): Promise<string> {
const id = randomUUID()
@@ -60,13 +64,14 @@ async function insertPostedEntry(params: {
`INSERT INTO public.journal_entries
(id, user_id, company_id, fiscal_period_id, voucher_number, voucher_series,
entry_date, description, source_type, status)
VALUES ($1, $2, $3, $4, $5, 'A', $6, 'Test entry', $7, 'posted')`,
VALUES ($1, $2, $3, $4, $5, $6, $7, 'Test entry', $8, 'posted')`,
[
id,
params.userId,
params.companyId,
params.fiscalPeriodId,
params.voucherNumber,
params.voucherSeries ?? 'A',
params.entryDate ?? '2026-06-01',
params.sourceType,
],
@@ -81,6 +86,44 @@ async function insertPostedEntry(params: {
return id
}
async function insertVoucherSequence(params: {
companyId: string
userId: string
fiscalPeriodId: string
series: string
lastNumber: number
}): Promise<void> {
await getPool().query(
`INSERT INTO public.voucher_sequences
(company_id, user_id, fiscal_period_id, voucher_series, last_number)
VALUES ($1, $2, $3, $4, $5)`,
[params.companyId, params.userId, params.fiscalPeriodId, params.series, params.lastNumber],
)
}
async function insertDocumentAttachment(params: {
userId: string
companyId: string
journalEntryId: string
}): Promise<string> {
const id = randomUUID()
await getPool().query(
`INSERT INTO public.document_attachments
(id, user_id, company_id, storage_path, file_name, sha256_hash, journal_entry_id, upload_source)
VALUES ($1, $2, $3, $4, $5, $6, $7, 'file_upload')`,
[
id,
params.userId,
params.companyId,
`test/${id}.pdf`,
`test-${id}.pdf`,
`sha256-${id}`,
params.journalEntryId,
],
)
return id
}
describe('sie_imports: partial unique index + replace flow', () => {
it('blocks a second active row with the same (company_id, file_hash)', async () => {
const { companyId, userId, fiscalPeriodId } = await seedCompany()
@@ -134,45 +177,39 @@ describe('sie_imports: partial unique index + replace flow', () => {
expect(newId).toBeTruthy()
})
it('replace_sie_import cancels source_type=import entries and leaves manual/bank_transaction entries posted', async () => {
it('replace_sie_import deletes source_type=import entries, leaves manual/bank_transaction posted, and resets voucher_sequences to MAX of remaining', async () => {
const { companyId, userId, fiscalPeriodId } = await seedCompany()
const obEntry = await insertPostedEntry({
userId,
companyId,
fiscalPeriodId,
sourceType: 'import',
voucherNumber: 1,
userId, companyId, fiscalPeriodId, sourceType: 'import', voucherNumber: 1,
})
const importEntry1 = await insertPostedEntry({
userId,
companyId,
fiscalPeriodId,
sourceType: 'import',
voucherNumber: 2,
userId, companyId, fiscalPeriodId, sourceType: 'import', voucherNumber: 2,
})
const importEntry2 = await insertPostedEntry({
userId,
companyId,
fiscalPeriodId,
sourceType: 'import',
voucherNumber: 3,
userId, companyId, fiscalPeriodId, sourceType: 'import', voucherNumber: 3,
})
const manualEntry = await insertPostedEntry({
userId,
companyId,
fiscalPeriodId,
sourceType: 'manual',
voucherNumber: 4,
userId, companyId, fiscalPeriodId, sourceType: 'manual', voucherNumber: 4,
})
const txnEntry = await insertPostedEntry({
userId,
companyId,
fiscalPeriodId,
sourceType: 'bank_transaction',
voucherNumber: 5,
userId, companyId, fiscalPeriodId, sourceType: 'bank_transaction', voucherNumber: 5,
})
// Voucher_sequences advanced past the imports (5 total inserted in series A)
await insertVoucherSequence({
companyId, userId, fiscalPeriodId, series: 'A', lastNumber: 5,
})
// The fiscal period has its opening_balance_entry_id set to the OB entry,
// matching what a real SIE import would have produced.
await getPool().query(
`UPDATE public.fiscal_periods
SET opening_balance_entry_id = $1, opening_balances_set = true
WHERE id = $2`,
[obEntry, fiscalPeriodId],
)
const importId = await insertSIEImport({
companyId,
userId,
@@ -186,27 +223,172 @@ describe('sie_imports: partial unique index + replace flow', () => {
`SELECT public.replace_sie_import($1::uuid, $2::uuid) AS replace_sie_import`,
[companyId, importId],
)
const cancelled = rows[0]!.replace_sie_import
expect(rows[0]!.replace_sie_import).toBe(3) // OB + 2 import entries
// OB entry + 2 import entries = 3 cancelled. Manual & transaction stay posted.
expect(cancelled).toBe(3)
const statuses = await getPool().query<{ id: string; status: string }>(
// The import entries (and their lines) are gone
const entries = await getPool().query<{ id: string; status: string }>(
`SELECT id, status FROM public.journal_entries WHERE id = ANY($1)`,
[[obEntry, importEntry1, importEntry2, manualEntry, txnEntry]],
)
const statusById = Object.fromEntries(statuses.rows.map(r => [r.id, r.status]))
expect(statusById[obEntry]).toBe('cancelled')
expect(statusById[importEntry1]).toBe('cancelled')
expect(statusById[importEntry2]).toBe('cancelled')
const statusById = Object.fromEntries(entries.rows.map(r => [r.id, r.status]))
expect(statusById[obEntry]).toBeUndefined()
expect(statusById[importEntry1]).toBeUndefined()
expect(statusById[importEntry2]).toBeUndefined()
expect(statusById[manualEntry]).toBe('posted')
expect(statusById[txnEntry]).toBe('posted')
const importRow = await getPool().query<{ status: string; replaced_at: string | null }>(
`SELECT status, replaced_at FROM public.sie_imports WHERE id = $1`,
const lines = await getPool().query<{ count: string }>(
`SELECT count(*)::text FROM public.journal_entry_lines
WHERE journal_entry_id = ANY($1)`,
[[obEntry, importEntry1, importEntry2]],
)
expect(lines.rows[0]!.count).toBe('0')
// voucher_sequences reset to max of remaining entries in series A (5, the bank tx)
const vs = await getPool().query<{ last_number: number }>(
`SELECT last_number FROM public.voucher_sequences
WHERE company_id = $1 AND fiscal_period_id = $2 AND voucher_series = 'A'`,
[companyId, fiscalPeriodId],
)
expect(vs.rows[0]?.last_number).toBe(5)
// fiscal_periods OB pointer cleared
const fp = await getPool().query<{
opening_balance_entry_id: string | null
opening_balances_set: boolean
}>(
`SELECT opening_balance_entry_id, opening_balances_set
FROM public.fiscal_periods WHERE id = $1`,
[fiscalPeriodId],
)
expect(fp.rows[0]?.opening_balance_entry_id).toBeNull()
expect(fp.rows[0]?.opening_balances_set).toBe(false)
// sie_imports OB FK cleared, status replaced
const importRow = await getPool().query<{
status: string
replaced_at: string | null
opening_balance_entry_id: string | null
}>(
`SELECT status, replaced_at, opening_balance_entry_id
FROM public.sie_imports WHERE id = $1`,
[importId],
)
expect(importRow.rows[0]!.status).toBe('replaced')
expect(importRow.rows[0]!.replaced_at).not.toBeNull()
expect(importRow.rows[0]?.status).toBe('replaced')
expect(importRow.rows[0]?.replaced_at).not.toBeNull()
expect(importRow.rows[0]?.opening_balance_entry_id).toBeNull()
})
it('replace_sie_import resets voucher_sequences.last_number to 0 when no entries remain in the series', async () => {
const { companyId, userId, fiscalPeriodId } = await seedCompany()
await insertPostedEntry({
userId, companyId, fiscalPeriodId, sourceType: 'import', voucherNumber: 1,
})
await insertPostedEntry({
userId, companyId, fiscalPeriodId, sourceType: 'import', voucherNumber: 2,
})
await insertVoucherSequence({
companyId, userId, fiscalPeriodId, series: 'A', lastNumber: 2,
})
const importId = await insertSIEImport({
companyId,
userId,
fileHash: `hash-${randomUUID()}`,
status: 'completed',
fiscalPeriodId,
})
await getPool().query(
`SELECT public.replace_sie_import($1::uuid, $2::uuid)`,
[companyId, importId],
)
const vs = await getPool().query<{ last_number: number }>(
`SELECT last_number FROM public.voucher_sequences
WHERE company_id = $1 AND fiscal_period_id = $2 AND voucher_series = 'A'`,
[companyId, fiscalPeriodId],
)
expect(vs.rows[0]?.last_number).toBe(0)
})
it('replace_sie_import detaches documents from deleted entries without losing the document rows', async () => {
const { companyId, userId, fiscalPeriodId } = await seedCompany()
const importEntry = await insertPostedEntry({
userId, companyId, fiscalPeriodId, sourceType: 'import', voucherNumber: 1,
})
const manualEntry = await insertPostedEntry({
userId, companyId, fiscalPeriodId, sourceType: 'manual', voucherNumber: 2,
})
const attachedDoc = await insertDocumentAttachment({
userId, companyId, journalEntryId: importEntry,
})
const manualDoc = await insertDocumentAttachment({
userId, companyId, journalEntryId: manualEntry,
})
const importId = await insertSIEImport({
companyId,
userId,
fileHash: `hash-${randomUUID()}`,
status: 'completed',
fiscalPeriodId,
})
await getPool().query(
`SELECT public.replace_sie_import($1::uuid, $2::uuid)`,
[companyId, importId],
)
// The document attached to the deleted import entry is detached but preserved
const detached = await getPool().query<{
id: string
journal_entry_id: string | null
storage_path: string
file_name: string
}>(
`SELECT id, journal_entry_id, storage_path, file_name
FROM public.document_attachments WHERE id = $1`,
[attachedDoc],
)
expect(detached.rows[0]).toBeTruthy()
expect(detached.rows[0]?.journal_entry_id).toBeNull()
expect(detached.rows[0]?.storage_path).toBeTruthy()
expect(detached.rows[0]?.file_name).toBeTruthy()
// The document attached to the surviving manual entry is left alone
const untouched = await getPool().query<{ journal_entry_id: string | null }>(
`SELECT journal_entry_id FROM public.document_attachments WHERE id = $1`,
[manualDoc],
)
expect(untouched.rows[0]?.journal_entry_id).toBe(manualEntry)
})
it('replace_sie_import on an already-replaced import raises', async () => {
const { companyId, userId, fiscalPeriodId } = await seedCompany()
const importId = await insertSIEImport({
companyId,
userId,
fileHash: `hash-${randomUUID()}`,
status: 'completed',
fiscalPeriodId,
})
await getPool().query(
`SELECT public.replace_sie_import($1::uuid, $2::uuid)`,
[companyId, importId],
)
await expect(
getPool().query(
`SELECT public.replace_sie_import($1::uuid, $2::uuid)`,
[companyId, importId],
),
).rejects.toThrow(/not found or not in completed status/)
})
})
+29 -25
View File
@@ -131,22 +131,28 @@ export async function checkDuplicatePeriodImport(
}
/**
* Replace (cancel) a completed SIE import so the user can re-import corrected
* data for the same fiscal period.
* Replace a completed SIE import so the user can re-import corrected data
* for the same fiscal period.
*
* Per BFL 5 kap 5§ (rättelse), the original entries are preserved with
* status='cancelled'. The import record is marked as 'replaced' with a
* timestamp for audit trail (BFNAR 2013:2 kap 8 behandlingshistorik).
* Nothing is deleted.
* The RPC hard-deletes every source_type='import' entry the original import
* created (plus stragglers from any prior soft-replace), detaches user-
* attached documents from those entries (PDFs stay in storage as unlinked
* documents), clears the fiscal-period opening-balance pointer if it came
* from this import, and resets voucher_sequences so the next re-import
* restarts the series at 1 (or at MAX of remaining non-import entries).
*
* The actual cancellation + status update is atomic via the replace_sie_import
* DB RPC to prevent inconsistent state.
* Audit trail lives in the sie_imports row (status='replaced',
* replaced_at, filename, file_hash, transactions_count, fiscal_year_*)
* plus per-row audit_log entries written by the write_audit_log trigger
* on each journal_entries DELETE (old_state JSONB snapshot).
*
* The whole cleanup is atomic via the replace_sie_import DB RPC.
*/
export async function replaceSIEImport(
supabase: SupabaseClient,
companyId: string,
importId: string
): Promise<{ success: boolean; cancelledEntries: number; error?: string }> {
): Promise<{ success: boolean; deletedEntries: number; error?: string }> {
// 1. Fetch and validate the import record
const { data: importRecord } = await supabase
.from('sie_imports')
@@ -156,11 +162,11 @@ export async function replaceSIEImport(
.single()
if (!importRecord) {
return { success: false, cancelledEntries: 0, error: 'Import hittades inte' }
return { success: false, deletedEntries: 0, error: 'Import hittades inte' }
}
if (importRecord.status !== 'completed') {
return { success: false, cancelledEntries: 0, error: `Kan bara ersätta slutförda importer (status: ${importRecord.status})` }
return { success: false, deletedEntries: 0, error: `Kan bara ersätta slutförda importer (status: ${importRecord.status})` }
}
// 2. Check that the fiscal period is not closed or locked
@@ -173,21 +179,21 @@ export async function replaceSIEImport(
.single()
if (period?.is_closed || period?.locked_at) {
return { success: false, cancelledEntries: 0, error: 'Kan inte ersätta import i ett låst eller stängt räkenskapsår. Öppna perioden först.' }
return { success: false, deletedEntries: 0, error: 'Kan inte ersätta import i ett låst eller stängt räkenskapsår. Öppna perioden först.' }
}
}
// 3. Atomically cancel entries and mark import as replaced via DB RPC
const { data: cancelledCount, error: rpcError } = await supabase.rpc('replace_sie_import', {
// 3. Atomically delete entries and mark import as replaced via DB RPC
const { data: deletedCount, error: rpcError } = await supabase.rpc('replace_sie_import', {
p_company_id: companyId,
p_import_id: importId,
})
if (rpcError) {
return { success: false, cancelledEntries: 0, error: `Kunde inte ersätta import: ${rpcError.message}` }
return { success: false, deletedEntries: 0, error: `Kunde inte ersätta import: ${rpcError.message}` }
}
return { success: true, cancelledEntries: cancelledCount as number }
return { success: true, deletedEntries: deletedCount as number }
}
/**
@@ -1600,17 +1606,15 @@ export async function executeSIEImport(
}
result.replacedPriorImport = {
importId: priorPeriodImport.id,
cancelledEntries: replaceResult.cancelledEntries,
deletedEntries: replaceResult.deletedEntries,
}
// The replace_sie_import RPC cancelled the prior import's opening
// balance entry, but the fiscal_periods row still flags
// opening_balances_set=true and points opening_balance_entry_id at
// the now-cancelled row. Without clearing those, the IB import
// below would skip ("Ingående balanser finns redan...") and the
// new IB would be lost. Only reset when the cleared entry was the
// prior import's IB — if the period's IB came from somewhere else
// (manual entry, year-end carryover), we must not touch it.
// The replace_sie_import RPC clears fiscal_periods
// opening_balance_entry_id and opening_balances_set inside its
// transaction when the prior import had an OB entry. This client-
// side UPDATE is now an idempotent safety net for pre-fix data
// (companies whose prior replace ran against the soft-cancel
// implementation and left the pointer dangling on the row).
if (priorPeriodImport.fiscal_period_id && priorPeriodImport.opening_balance_entry_id) {
await supabase
.from('fiscal_periods')
+2 -2
View File
@@ -299,8 +299,8 @@ export interface ImportResult {
// If this import replaced a prior completed import for the same fiscal year
// (Fortnox re-sync flow), the prior import's id and the count of journal
// entries that were cancelled as a result.
replacedPriorImport?: { importId: string; cancelledEntries: number } | null
// entries that were deleted as a result.
replacedPriorImport?: { importId: string; deletedEntries: number } | null
}
/**