docs(production): standardiserad produktionsberedskap och gap-analys

Lägger docs/production-readiness.md och siax/production-gaps.json enligt SIAX Master Definition of Done. Underlag: git-, kod- och live-evidens 2026-11-11. Nivån är evidensbaserad, inte ett leveransgodkännande.
This commit is contained in:
2026-11-10 09:15:21 +01:00
parent 0fda8cae48
commit 2bee8eb778
6135 changed files with 4 additions and 1718997 deletions
@@ -1,499 +0,0 @@
import { randomUUID } from 'node:crypto'
import { describe, expect, it } from 'vitest'
import { getPool, withUserContext } from '@/tests/pg/setup'
import {
insertAuthUser,
insertBalancedLines,
insertCompany,
insertCompanyMember,
insertDraftJournalEntry,
seedCompany,
} from '@/tests/pg/fixtures'
// BFL retention is enforced by two independent triggers on document_attachments:
// * enforce_document_journal_entry_immutability (20260506130000): blocks
// any change to journal_entry_id once it has been set, regardless of the
// linked entry's status. Honors gnubok.allow_delete (20260506140000).
// * enforce_document_metadata_immutability (extended in 20260506120000):
// blocks metadata changes and journal_entry_line_id changes when the
// linked entry is posted/reversed. Also honors gnubok.allow_delete.
//
// Both wordings: "BFL 5 kap" (entry trigger) and "BFL 7 kap" (metadata
// trigger): are accepted; which one fires first depends on what column the
// UPDATE touches.
const BFL_RETENTION_ERROR = /BFL [57] kap/i
async function insertDocument(params: {
userId: string
companyId: string
journalEntryId: string | null
journalEntryLineId?: string | null
}): Promise<string> {
const id = randomUUID()
await getPool().query(
`INSERT INTO public.document_attachments
(id, user_id, company_id, storage_path, file_name, file_size_bytes,
mime_type, sha256_hash, journal_entry_id, journal_entry_line_id)
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10)`,
[
id,
params.userId,
params.companyId,
`documents/${params.userId}/${id}.pdf`,
'underlag.pdf',
1024,
'application/pdf',
'a'.repeat(64),
params.journalEntryId,
params.journalEntryLineId ?? null,
],
)
return id
}
// Insert a draft, balance it, and walk through the legal state-machine
// transitions to land on the requested status. enforce_journal_entry_immutability
// only allows draft→posted and posted→reversed, so the path matters.
async function insertEntryAtStatus(params: {
userId: string
companyId: string
fiscalPeriodId: string
voucherNumber: number
status?: 'posted' | 'reversed'
}): Promise<string> {
const entryId = await insertDraftJournalEntry({
userId: params.userId,
companyId: params.companyId,
fiscalPeriodId: params.fiscalPeriodId,
voucherNumber: params.voucherNumber,
})
await insertBalancedLines(entryId)
await getPool().query(
`UPDATE public.journal_entries SET status = 'posted' WHERE id = $1`,
[entryId],
)
if (params.status === 'reversed') {
await getPool().query(
`UPDATE public.journal_entries SET status = 'reversed' WHERE id = $1`,
[entryId],
)
}
return entryId
}
describe('document-immutability.pg: BFL retention bypass guards', () => {
it('rejects unlinking (journal_entry_id → NULL) on a doc linked to a posted entry', async () => {
const { userId, companyId, fiscalPeriodId } = await seedCompany()
const entryId = await insertEntryAtStatus({
userId, companyId, fiscalPeriodId, voucherNumber: 1,
})
const docId = await insertDocument({ userId, companyId, journalEntryId: entryId })
await expect(
getPool().query(
`UPDATE public.document_attachments SET journal_entry_id = NULL WHERE id = $1`,
[docId],
),
).rejects.toThrow(BFL_RETENTION_ERROR)
})
it('rejects unlinking on a doc linked to a reversed entry', async () => {
const { userId, companyId, fiscalPeriodId } = await seedCompany()
const entryId = await insertEntryAtStatus({
userId, companyId, fiscalPeriodId, voucherNumber: 1, status: 'reversed',
})
const docId = await insertDocument({ userId, companyId, journalEntryId: entryId })
await expect(
getPool().query(
`UPDATE public.document_attachments SET journal_entry_id = NULL WHERE id = $1`,
[docId],
),
).rejects.toThrow(BFL_RETENTION_ERROR)
})
it('rejects unlinking on a doc linked to a draft entry: link is durable from first set', async () => {
// The entry-level trigger does not consult journal_entries.status; once
// journal_entry_id is set on a document, it cannot be cleared. This is
// stricter than the original branch design and matches main's intent
// that the verifikation→underlag link be durable from first set.
const { userId, companyId, fiscalPeriodId } = await seedCompany()
const draftId = await insertDraftJournalEntry({
userId, companyId, fiscalPeriodId, voucherNumber: 0,
})
const docId = await insertDocument({ userId, companyId, journalEntryId: draftId })
await expect(
getPool().query(
`UPDATE public.document_attachments SET journal_entry_id = NULL WHERE id = $1`,
[docId],
),
).rejects.toThrow(BFL_RETENTION_ERROR)
})
it('rejects re-pointing journal_entry_id to a different posted entry', async () => {
const { userId, companyId, fiscalPeriodId } = await seedCompany()
const entryA = await insertEntryAtStatus({
userId, companyId, fiscalPeriodId, voucherNumber: 1,
})
const entryB = await insertEntryAtStatus({
userId, companyId, fiscalPeriodId, voucherNumber: 2,
})
const docId = await insertDocument({ userId, companyId, journalEntryId: entryA })
await expect(
getPool().query(
`UPDATE public.document_attachments SET journal_entry_id = $1 WHERE id = $2`,
[entryB, docId],
),
).rejects.toThrow(BFL_RETENTION_ERROR)
})
it('allows first-time linking (NULL → UUID): legitimate linkToJournalEntry path', async () => {
const { userId, companyId, fiscalPeriodId } = await seedCompany()
const entryId = await insertEntryAtStatus({
userId, companyId, fiscalPeriodId, voucherNumber: 1,
})
const docId = await insertDocument({ userId, companyId, journalEntryId: null })
await getPool().query(
`UPDATE public.document_attachments SET journal_entry_id = $1 WHERE id = $2`,
[entryId, docId],
)
const after = await getPool().query<{ journal_entry_id: string | null }>(
`SELECT journal_entry_id FROM public.document_attachments WHERE id = $1`,
[docId],
)
expect(after.rows[0]!.journal_entry_id).toBe(entryId)
})
it('rejects unlinking journal_entry_line_id on a doc linked to a posted entry', async () => {
const { userId, companyId, fiscalPeriodId } = await seedCompany()
const entryId = await insertEntryAtStatus({
userId, companyId, fiscalPeriodId, voucherNumber: 1,
})
const lineRow = await getPool().query<{ id: string }>(
`SELECT id FROM public.journal_entry_lines WHERE journal_entry_id = $1 LIMIT 1`,
[entryId],
)
const lineId = lineRow.rows[0]!.id
const docId = await insertDocument({
userId, companyId, journalEntryId: entryId, journalEntryLineId: lineId,
})
await expect(
getPool().query(
`UPDATE public.document_attachments SET journal_entry_line_id = NULL WHERE id = $1`,
[docId],
),
).rejects.toThrow(BFL_RETENTION_ERROR)
})
it('end-to-end: unlink-then-delete attack is blocked at the unlink step', async () => {
const { userId, companyId, fiscalPeriodId } = await seedCompany()
const entryId = await insertEntryAtStatus({
userId, companyId, fiscalPeriodId, voucherNumber: 1,
})
const docId = await insertDocument({ userId, companyId, journalEntryId: entryId })
await expect(
getPool().query(
`UPDATE public.document_attachments SET journal_entry_id = NULL WHERE id = $1`,
[docId],
),
).rejects.toThrow(BFL_RETENTION_ERROR)
await expect(
getPool().query(`DELETE FROM public.document_attachments WHERE id = $1`, [docId]),
).rejects.toThrow(/Bokföringslagen/i)
})
it('respects gnubok.allow_delete bypass: delete_last_voucher RPC keeps working', async () => {
const { userId, companyId, fiscalPeriodId } = await seedCompany()
const entryId = await insertEntryAtStatus({
userId, companyId, fiscalPeriodId, voucherNumber: 1,
})
const docId = await insertDocument({ userId, companyId, journalEntryId: entryId })
const client = await getPool().connect()
try {
await client.query('BEGIN')
await client.query(`SELECT set_config('gnubok.allow_delete', 'true', true)`)
await client.query(
`UPDATE public.document_attachments SET journal_entry_id = NULL WHERE id = $1`,
[docId],
)
const after = await client.query<{ journal_entry_id: string | null }>(
`SELECT journal_entry_id FROM public.document_attachments WHERE id = $1`,
[docId],
)
expect(after.rows[0]!.journal_entry_id).toBeNull()
await client.query('ROLLBACK')
} finally {
client.release()
}
})
})
// The supersession flow needs to flip the OLD row from is_current_version=true
// to false. The metadata-immutability trigger blocks that change for docs
// linked to posted entries unless the gnubok.allow_supersede GUC is set:
// which create_document_version sets before its UPDATE. Without this, users
// have no way to replace a corrupt underlag (e.g. a bad PDF uploaded via the
// MCP server before magic-byte validation).
describe('document-immutability.pg: version supersession on posted entries', () => {
it('allows create_document_version on a doc linked to a posted entry', async () => {
const { userId, companyId, fiscalPeriodId } = await seedCompany()
const entryId = await insertEntryAtStatus({
userId, companyId, fiscalPeriodId, voucherNumber: 1,
})
const docId = await insertDocument({ userId, companyId, journalEntryId: entryId })
// create_document_version is SECURITY DEFINER but enforces auth.uid()
// matches p_user_id and that the caller is a company member, so the
// call must run under withUserContext(userId).
const newId = await withUserContext(userId, async (client) => {
const result = await client.query<{ new_id: string }>(
`SELECT public.create_document_version(
$1::uuid, $2::uuid, $3::text, $4::text, $5::bigint, $6::text, $7::text
) AS new_id`,
[
userId,
docId,
`documents/${userId}/replacement.pdf`,
'replacement.pdf',
2048,
'application/pdf',
'b'.repeat(64),
],
)
const id = result.rows[0]!.new_id
// The transaction is rolled back by withUserContext, so we have to
// assert state from within the same client/transaction.
const oldRow = await client.query<{
is_current_version: boolean
superseded_by_id: string | null
journal_entry_id: string | null
}>(
`SELECT is_current_version, superseded_by_id, journal_entry_id
FROM public.document_attachments WHERE id = $1`,
[docId],
)
expect(oldRow.rows[0]!.is_current_version).toBe(false)
expect(oldRow.rows[0]!.superseded_by_id).toBe(id)
expect(oldRow.rows[0]!.journal_entry_id).toBe(entryId)
const newRow = await client.query<{
is_current_version: boolean
version: number
journal_entry_id: string | null
prev_version_hash: string | null
}>(
`SELECT is_current_version, version, journal_entry_id, prev_version_hash
FROM public.document_attachments WHERE id = $1`,
[id],
)
expect(newRow.rows[0]!.is_current_version).toBe(true)
expect(newRow.rows[0]!.version).toBe(2)
expect(newRow.rows[0]!.journal_entry_id).toBe(entryId)
expect(newRow.rows[0]!.prev_version_hash).toBe('a'.repeat(64))
return id
})
expect(newId).toBeDefined()
})
it('allows create_document_version on a doc linked to a reversed entry', async () => {
const { userId, companyId, fiscalPeriodId } = await seedCompany()
const entryId = await insertEntryAtStatus({
userId, companyId, fiscalPeriodId, voucherNumber: 1, status: 'reversed',
})
const docId = await insertDocument({ userId, companyId, journalEntryId: entryId })
await withUserContext(userId, async (client) => {
const result = await client.query(
`SELECT public.create_document_version(
$1::uuid, $2::uuid, $3::text, $4::text, $5::bigint, $6::text, $7::text
)`,
[
userId, docId,
`documents/${userId}/replacement.pdf`,
'replacement.pdf', 2048, 'application/pdf', 'c'.repeat(64),
],
)
expect(result.rows).toHaveLength(1)
})
})
// Cross-tenant attack: a member of company A calls create_document_version
// with a document id that belongs to company B. Before the auth+membership
// check landed, the SECURITY DEFINER function would happily mutate the
// foreign company's row because the GUC bypass disarmed the immutability
// trigger. The membership guard inside the function is the only line of
// defence: PostgREST exposes the RPC to all authenticated users.
it('rejects create_document_version when caller is not a member of the document company', async () => {
const { userId: aliceId, companyId: aliceCompanyId, fiscalPeriodId: aliceFp } =
await seedCompany()
const entryId = await insertEntryAtStatus({
userId: aliceId,
companyId: aliceCompanyId,
fiscalPeriodId: aliceFp,
voucherNumber: 1,
})
const docId = await insertDocument({
userId: aliceId,
companyId: aliceCompanyId,
journalEntryId: entryId,
})
// Bob has his own company; he is NOT a member of Alice's company.
const bobId = await insertAuthUser()
const bobCompany = await insertCompany({ createdBy: bobId })
await insertCompanyMember({ companyId: bobCompany, userId: bobId, role: 'owner' })
await withUserContext(bobId, async (client) => {
await expect(
client.query(
`SELECT public.create_document_version(
$1::uuid, $2::uuid, $3::text, $4::text, $5::bigint, $6::text, $7::text
)`,
[
bobId, docId,
`documents/${bobId}/exfil.pdf`,
'exfil.pdf', 2048, 'application/pdf', 'd'.repeat(64),
],
),
).rejects.toThrow(/not a member/i)
})
})
// Identity-spoofing attack: caller passes p_user_id ≠ auth.uid(). Allowing
// this would let any authenticated user manufacture supersession events
// attributed to a different user: useful for audit-log forgery even when
// the supersession itself is legitimate.
it('rejects create_document_version when p_user_id does not match auth.uid()', async () => {
const { userId: aliceId, companyId, fiscalPeriodId } = await seedCompany()
const entryId = await insertEntryAtStatus({
userId: aliceId, companyId, fiscalPeriodId, voucherNumber: 1,
})
const docId = await insertDocument({
userId: aliceId, companyId, journalEntryId: entryId,
})
// Mallory is also a member of the company: so the membership check
// alone would not catch a spoofed p_user_id.
const malloryId = await insertAuthUser()
await insertCompanyMember({ companyId, userId: malloryId, role: 'member' })
await withUserContext(malloryId, async (client) => {
await expect(
client.query(
`SELECT public.create_document_version(
$1::uuid, $2::uuid, $3::text, $4::text, $5::bigint, $6::text, $7::text
)`,
[
// Spoofing aliceId as the actor while auth.uid() is malloryId.
aliceId, docId,
`documents/${aliceId}/spoofed.pdf`,
'spoofed.pdf', 2048, 'application/pdf', 'e'.repeat(64),
],
),
).rejects.toThrow(/does not match authenticated user/i)
})
})
// The narrowed bypass: even with allow_supersede set, a direct UPDATE that
// tries to change sha256_hash, journal_entry_id, or any other audit field
// must still be blocked. Before the narrowing the GUC was a blanket
// bypass that disarmed the entire trigger.
it('keeps blocking sha256_hash mutation even when allow_supersede is set', async () => {
const { userId, companyId, fiscalPeriodId } = await seedCompany()
const entryId = await insertEntryAtStatus({
userId, companyId, fiscalPeriodId, voucherNumber: 1,
})
const docId = await insertDocument({ userId, companyId, journalEntryId: entryId })
const client = await getPool().connect()
try {
await client.query('BEGIN')
await client.query(`SELECT set_config('gnubok.allow_supersede', 'true', true)`)
await expect(
client.query(
`UPDATE public.document_attachments SET sha256_hash = $2 WHERE id = $1`,
[docId, 'f'.repeat(64)],
),
).rejects.toThrow(BFL_RETENTION_ERROR)
await client.query('ROLLBACK')
} finally {
client.release()
}
})
it('keeps blocking journal_entry_id mutation even when allow_supersede is set', async () => {
const { userId, companyId, fiscalPeriodId } = await seedCompany()
const entryA = await insertEntryAtStatus({
userId, companyId, fiscalPeriodId, voucherNumber: 1,
})
const entryB = await insertEntryAtStatus({
userId, companyId, fiscalPeriodId, voucherNumber: 2,
})
const docId = await insertDocument({ userId, companyId, journalEntryId: entryA })
const client = await getPool().connect()
try {
await client.query('BEGIN')
await client.query(`SELECT set_config('gnubok.allow_supersede', 'true', true)`)
await expect(
client.query(
`UPDATE public.document_attachments SET journal_entry_id = $1 WHERE id = $2`,
[entryB, docId],
),
).rejects.toThrow(BFL_RETENTION_ERROR)
await client.query('ROLLBACK')
} finally {
client.release()
}
})
it('rejects direct UPDATE flipping is_current_version without the GUC', async () => {
const { userId, companyId, fiscalPeriodId } = await seedCompany()
const entryId = await insertEntryAtStatus({
userId, companyId, fiscalPeriodId, voucherNumber: 1,
})
const docId = await insertDocument({ userId, companyId, journalEntryId: entryId })
await expect(
getPool().query(
`UPDATE public.document_attachments SET is_current_version = false WHERE id = $1`,
[docId],
),
).rejects.toThrow(BFL_RETENTION_ERROR)
})
it('respects gnubok.allow_supersede bypass on direct UPDATE', async () => {
const { userId, companyId, fiscalPeriodId } = await seedCompany()
const entryId = await insertEntryAtStatus({
userId, companyId, fiscalPeriodId, voucherNumber: 1,
})
const docId = await insertDocument({ userId, companyId, journalEntryId: entryId })
const client = await getPool().connect()
try {
await client.query('BEGIN')
await client.query(`SELECT set_config('gnubok.allow_supersede', 'true', true)`)
await client.query(
`UPDATE public.document_attachments SET is_current_version = false WHERE id = $1`,
[docId],
)
const after = await client.query<{ is_current_version: boolean }>(
`SELECT is_current_version FROM public.document_attachments WHERE id = $1`,
[docId],
)
expect(after.rows[0]!.is_current_version).toBe(false)
await client.query('ROLLBACK')
} finally {
client.release()
}
})
})
File diff suppressed because it is too large Load Diff
@@ -1,190 +0,0 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import {
readBodyWithCap,
resolveUpstreamStorageUrl,
toSameOriginStorageUrl,
} from '../storage-proxy'
const SUPABASE = 'https://pwxtzglxptnnvjrpixpg.supabase.co'
const APP = 'https://app.accounted.se'
const UPLOAD_URL = `${SUPABASE}/storage/v1/object/upload/sign/documents/co-1/user-1/pending/up-1/faktura%20maj.pdf?token=eyJ.sig`
const DOWNLOAD_URL = `${SUPABASE}/storage/v1/object/sign/documents/co-1/user-1/kvitto.pdf?token=eyJ.sig&download=`
beforeEach(() => {
vi.stubEnv('NEXT_PUBLIC_SUPABASE_URL', SUPABASE)
vi.stubEnv('NEXT_PUBLIC_APP_URL', APP)
})
afterEach(() => {
vi.unstubAllEnvs()
})
describe('toSameOriginStorageUrl', () => {
it('moves a signed upload URL onto the app origin, keeping path encoding and the token', () => {
expect(toSameOriginStorageUrl(UPLOAD_URL)).toBe(
`${APP}/api/storage/upload/sign/documents/co-1/user-1/pending/up-1/faktura%20maj.pdf?token=eyJ.sig`,
)
})
it('moves a signed download URL onto the app origin with every query parameter', () => {
expect(toSameOriginStorageUrl(DOWNLOAD_URL)).toBe(
`${APP}/api/storage/sign/documents/co-1/user-1/kvitto.pdf?token=eyJ.sig&download=`,
)
})
it('tolerates a trailing slash on the app URL', () => {
expect(toSameOriginStorageUrl(DOWNLOAD_URL, `${APP}/`)).toMatch(
new RegExp(`^${APP}/api/storage/sign/`),
)
})
it('leaves the URL alone when the app has no public URL (self-host without NEXT_PUBLIC_APP_URL)', () => {
vi.stubEnv('NEXT_PUBLIC_APP_URL', '')
expect(toSameOriginStorageUrl(UPLOAD_URL)).toBe(UPLOAD_URL)
expect(toSameOriginStorageUrl(UPLOAD_URL, undefined)).toBe(UPLOAD_URL)
})
it('leaves URLs on other hosts, other buckets, unsigned paths and token-less links alone', () => {
expect(toSameOriginStorageUrl('https://storage.example/upload?token=signed')).toBe(
'https://storage.example/upload?token=signed',
)
const otherBucket = `${SUPABASE}/storage/v1/object/sign/avatars/a.png?token=t`
expect(toSameOriginStorageUrl(otherBucket)).toBe(otherBucket)
const publicObject = `${SUPABASE}/storage/v1/object/public/documents/a.pdf`
expect(toSameOriginStorageUrl(publicObject)).toBe(publicObject)
const noToken = `${SUPABASE}/storage/v1/object/sign/documents/a.pdf`
expect(toSameOriginStorageUrl(noToken)).toBe(noToken)
expect(toSameOriginStorageUrl('not a url')).toBe('not a url')
})
})
describe('resolveUpstreamStorageUrl', () => {
it('rebuilds the upstream signed URL for upload and download paths', () => {
expect(
resolveUpstreamStorageUrl(
'upload/sign/documents/co-1/user-1/pending/up-1/faktura%20maj.pdf',
new URLSearchParams('token=eyJ.sig'),
),
).toEqual({
ok: true,
url: `${SUPABASE}/storage/v1/object/upload/sign/documents/co-1/user-1/pending/up-1/faktura%20maj.pdf?token=eyJ.sig`,
})
expect(
resolveUpstreamStorageUrl(
'sign/documents/co-1/user-1/kvitto.pdf',
new URLSearchParams('token=eyJ.sig&download='),
),
).toEqual({
ok: true,
url: `${SUPABASE}/storage/v1/object/sign/documents/co-1/user-1/kvitto.pdf?token=eyJ.sig&download=`,
})
})
it('fails closed on anything that is not a signed documents-bucket object path', () => {
const token = new URLSearchParams('token=t')
expect(resolveUpstreamStorageUrl('public/documents/a.pdf', token)).toEqual({
ok: false,
reason: 'unsupported_path',
})
expect(resolveUpstreamStorageUrl('sign/avatars/a.png', token)).toEqual({
ok: false,
reason: 'unsupported_path',
})
expect(resolveUpstreamStorageUrl('sign/documents/', token)).toEqual({
ok: false,
reason: 'unsupported_path',
})
expect(resolveUpstreamStorageUrl('sign/documents/../bucket/x', token)).toEqual({
ok: false,
reason: 'unsupported_path',
})
expect(resolveUpstreamStorageUrl('list/documents', token)).toEqual({
ok: false,
reason: 'unsupported_path',
})
})
it('rejects dot segments in every spelling the URL parser would normalise away', () => {
const token = new URLSearchParams('token=t')
for (const evil of [
'sign/documents/%2e%2e/avatars/x',
'sign/documents/.%2e/avatars/x',
'sign/documents/%2e./avatars/x',
'sign/documents/%2E%2E/avatars/x',
'sign/documents/a/../../avatars/x',
'sign/documents/./x',
'sign/documents/a//x',
'sign/documents/a%5c..%5cavatars/x',
'sign/documents/a\\..\\avatars/x',
'sign/documents/a%2f..%2favatars/x',
'sign/documents/%zz/x',
'upload/sign/documents/%2e%2e/avatars/x',
]) {
expect(resolveUpstreamStorageUrl(evil, token), evil).toEqual({
ok: false,
reason: 'unsupported_path',
})
}
})
it('still accepts real keys with spaces, non-ASCII and dots inside names', () => {
const token = new URLSearchParams('token=t')
const resolved = resolveUpstreamStorageUrl(
'sign/documents/co-1/user-1/faktura%20maj%20%C3%A5r.2026.pdf',
token,
)
expect(resolved.ok).toBe(true)
})
it('requires the signed token', () => {
expect(resolveUpstreamStorageUrl('sign/documents/a.pdf', new URLSearchParams())).toEqual({
ok: false,
reason: 'missing_token',
})
})
it('reports an unconfigured Storage host instead of guessing', () => {
vi.stubEnv('NEXT_PUBLIC_SUPABASE_URL', '')
expect(
resolveUpstreamStorageUrl('sign/documents/a.pdf', new URLSearchParams('token=t')),
).toEqual({ ok: false, reason: 'storage_unconfigured' })
})
})
describe('readBodyWithCap', () => {
function stream(chunks: Uint8Array[]): ReadableStream<Uint8Array> {
return new ReadableStream({
start(controller) {
for (const chunk of chunks) controller.enqueue(chunk)
controller.close()
},
})
}
it('concatenates a body under the cap', async () => {
const out = await readBodyWithCap(
stream([new TextEncoder().encode('%PDF'), new TextEncoder().encode('-1.4')]),
100,
)
expect(out && new TextDecoder().decode(out)).toBe('%PDF-1.4')
})
it('returns null as soon as the running total passes the cap, without draining the rest', async () => {
let pulled = 0
const endless = new ReadableStream<Uint8Array>({
pull(controller) {
pulled++
controller.enqueue(new Uint8Array(1024))
},
})
const out = await readBodyWithCap(endless, 4096)
expect(out).toBeNull()
expect(pulled).toBeLessThan(10)
})
it('treats a missing body as empty', async () => {
expect((await readBodyWithCap(null, 10))?.byteLength).toBe(0)
})
})
@@ -1,463 +0,0 @@
import { describe, it, expect, vi, beforeEach } from 'vitest'
import type { SupabaseClient } from '@supabase/supabase-js'
import { createQueuedMockSupabase } from '@/tests/helpers'
import {
anchorSupplierInvoiceDocument,
reanchorOrphanedSupplierInvoiceDocuments,
sweepFloatingSupplierInvoiceDocuments,
} from '../supplier-invoice-underlag'
/**
* anchorSupplierInvoiceDocument issues its queries in a fixed `.from()` order,
* and the queued mock consumes one enqueued result per `.from()` call:
* 1. supplier_invoices (the invoice + its FK verifikat)
* 2. document_attachments (the retained document, anchor check)
* 3. supplier_invoice_payments (partial-payment verifikat candidates)
* 4. journal_entries (status + period of every candidate)
* 5. document_attachments (the anchoring UPDATE)
* Steps 3-5 are skipped when the document needs no anchoring.
*/
describe('anchorSupplierInvoiceDocument', () => {
beforeEach(() => {
vi.clearAllMocks()
})
const openPeriod = { is_closed: false, locked_at: null }
it('anchors a floating document to the payment verifikat when registration was reversed', async () => {
// The reported case: the invoice PDF was orphaned when the rättelse it had
// been relinked onto was deleted, leaving the posted payment verifikat
// warning "Underlag saknas" while the verifikat view showed the PDF.
const { supabase, enqueueMany } = createQueuedMockSupabase()
enqueueMany([
{
data: {
id: 'si-1',
document_id: 'doc-1',
registration_journal_entry_id: 'je-reg',
payment_journal_entry_id: 'je-pay',
},
},
{ data: { id: 'doc-1', journal_entry_id: null, is_current_version: true } },
{ data: [] },
{
data: [
{ id: 'je-reg', status: 'reversed', fiscal_period: openPeriod },
{ id: 'je-pay', status: 'posted', fiscal_period: openPeriod },
],
},
{ data: [{ id: 'doc-1' }] },
])
const anchored = await anchorSupplierInvoiceDocument(
supabase as unknown as SupabaseClient,
'company-1',
'si-1',
)
expect(anchored).toBe('je-pay')
expect(supabase.from).toHaveBeenCalledTimes(5)
})
it('prefers the registration verifikat: it is the primary booking', async () => {
const { supabase, enqueueMany } = createQueuedMockSupabase()
enqueueMany([
{
data: {
id: 'si-1',
document_id: 'doc-1',
registration_journal_entry_id: 'je-reg',
payment_journal_entry_id: 'je-pay',
},
},
{ data: { id: 'doc-1', journal_entry_id: null, is_current_version: true } },
{ data: [] },
{
data: [
{ id: 'je-reg', status: 'posted', fiscal_period: openPeriod },
{ id: 'je-pay', status: 'posted', fiscal_period: openPeriod },
],
},
{ data: [{ id: 'doc-1' }] },
])
expect(
await anchorSupplierInvoiceDocument(
supabase as unknown as SupabaseClient,
'company-1',
'si-1',
),
).toBe('je-reg')
})
it('falls back to a partial-payment verifikat, oldest first', async () => {
const { supabase, enqueueMany } = createQueuedMockSupabase()
enqueueMany([
{
data: {
id: 'si-1',
document_id: 'doc-1',
registration_journal_entry_id: null,
payment_journal_entry_id: null,
},
},
{ data: { id: 'doc-1', journal_entry_id: null, is_current_version: true } },
{ data: [{ journal_entry_id: 'je-p1' }, { journal_entry_id: 'je-p2' }] },
{
data: [
{ id: 'je-p1', status: 'posted', fiscal_period: openPeriod },
{ id: 'je-p2', status: 'posted', fiscal_period: openPeriod },
],
},
{ data: [{ id: 'doc-1' }] },
])
expect(
await anchorSupplierInvoiceDocument(
supabase as unknown as SupabaseClient,
'company-1',
'si-1',
),
).toBe('je-p1')
})
it('never moves a document that is already anchored', async () => {
const { supabase, enqueueMany } = createQueuedMockSupabase()
enqueueMany([
{
data: {
id: 'si-1',
document_id: 'doc-1',
registration_journal_entry_id: 'je-reg',
payment_journal_entry_id: 'je-pay',
},
},
{ data: { id: 'doc-1', journal_entry_id: 'je-reg', is_current_version: true } },
])
expect(
await anchorSupplierInvoiceDocument(
supabase as unknown as SupabaseClient,
'company-1',
'si-1',
),
).toBeNull()
// Stopped before the candidate lookup: no UPDATE was attempted.
expect(supabase.from).toHaveBeenCalledTimes(2)
})
it('leaves a superseded document alone', async () => {
const { supabase, enqueueMany } = createQueuedMockSupabase()
enqueueMany([
{
data: {
id: 'si-1',
document_id: 'doc-1',
registration_journal_entry_id: 'je-reg',
payment_journal_entry_id: null,
},
},
{ data: { id: 'doc-1', journal_entry_id: null, is_current_version: false } },
])
expect(
await anchorSupplierInvoiceDocument(
supabase as unknown as SupabaseClient,
'company-1',
'si-1',
),
).toBeNull()
expect(supabase.from).toHaveBeenCalledTimes(2)
})
it('skips a candidate whose period is locked (the trigger would reject the write)', async () => {
const { supabase, enqueueMany } = createQueuedMockSupabase()
enqueueMany([
{
data: {
id: 'si-1',
document_id: 'doc-1',
registration_journal_entry_id: 'je-reg',
payment_journal_entry_id: null,
},
},
{ data: { id: 'doc-1', journal_entry_id: null, is_current_version: true } },
{ data: [] },
{
data: [
{
id: 'je-reg',
status: 'posted',
fiscal_period: { is_closed: false, locked_at: '2026-07-01T00:00:00Z' },
},
],
},
])
expect(
await anchorSupplierInvoiceDocument(
supabase as unknown as SupabaseClient,
'company-1',
'si-1',
),
).toBeNull()
// Candidates were resolved, but no UPDATE followed.
expect(supabase.from).toHaveBeenCalledTimes(4)
})
it('does nothing when the invoice has no retained document', async () => {
const { supabase, enqueueMany } = createQueuedMockSupabase()
enqueueMany([
{
data: {
id: 'si-1',
document_id: null,
registration_journal_entry_id: 'je-reg',
payment_journal_entry_id: null,
},
},
])
expect(
await anchorSupplierInvoiceDocument(
supabase as unknown as SupabaseClient,
'company-1',
'si-1',
),
).toBeNull()
expect(supabase.from).toHaveBeenCalledTimes(1)
})
it('reports a zero-row update as null: a write that never happened is not an anchor', async () => {
// Prod case 2026-08-28 (faktura 118776): every static condition passed yet
// the document stayed floating. The guarded update can match nothing (a
// concurrent writer, or RLS filtering the row); claiming success then hides
// the miss from both callers and the reconcile cron.
const { supabase, enqueueMany } = createQueuedMockSupabase()
enqueueMany([
{
data: {
id: 'si-1',
document_id: 'doc-1',
registration_journal_entry_id: null,
payment_journal_entry_id: 'je-pay',
},
},
{ data: { id: 'doc-1', journal_entry_id: null, is_current_version: true } },
{ data: [] },
{ data: [{ id: 'je-pay', status: 'posted', fiscal_period: openPeriod }] },
{ data: [] }, // UPDATE matched no rows
])
await expect(
anchorSupplierInvoiceDocument(supabase as unknown as SupabaseClient, 'company-1', 'si-1'),
).resolves.toBeNull()
})
it('names the foreign key in the fiscal_periods embed', async () => {
// fiscal_periods points back at journal_entries twice (closing_entry_id,
// opening_balance_entry_id), so the bare embed is ambiguous and PostgREST
// answers PGRST201. The bare form shipped 2026-07-27 and this helper
// anchored nothing in production until 2026-09-01. A mocked client resolves
// no relationship, so asserting the string is the only thing a unit test
// can do here; scripts/checks/ambiguous-embed.mjs is the repo-wide guard.
const { supabase, enqueueMany, findCall } = createQueuedMockSupabase()
enqueueMany([
{
data: {
id: 'si-1',
document_id: 'doc-1',
registration_journal_entry_id: 'je-reg',
payment_journal_entry_id: null,
},
},
{ data: { id: 'doc-1', journal_entry_id: null, is_current_version: true } },
{ data: [] },
{ data: [{ id: 'je-reg', status: 'posted', fiscal_period: openPeriod }] },
{ data: [{ id: 'doc-1' }] },
])
await anchorSupplierInvoiceDocument(supabase as unknown as SupabaseClient, 'company-1', 'si-1')
expect(findCall('journal_entries', 'select')?.[0]).toContain(
'fiscal_periods!journal_entries_fiscal_period_id_fkey',
)
})
it('logs the reason when the period lock state cannot be read, and anchors nothing', async () => {
// Failing closed is right: never anchor on a lock state we could not read.
// Failing SILENTLY is what let the PGRST201 above sit dead for five weeks,
// with the caller's "no verifikat can anchor it" warning as the only
// signal, naming a cause that had nothing to do with it.
const consoleError = vi.spyOn(console, 'error').mockImplementation(() => {})
const { supabase, enqueueMany } = createQueuedMockSupabase()
enqueueMany([
{
data: {
id: 'si-1',
document_id: 'doc-1',
registration_journal_entry_id: 'je-reg',
payment_journal_entry_id: null,
},
},
{ data: { id: 'doc-1', journal_entry_id: null, is_current_version: true } },
{ data: [] },
{
error: {
message:
"Could not embed because more than one relationship was found for 'journal_entries' and 'fiscal_periods'",
},
},
])
await expect(
anchorSupplierInvoiceDocument(supabase as unknown as SupabaseClient, 'company-1', 'si-1'),
).resolves.toBeNull()
// Stopped at the failed read: no UPDATE was attempted.
expect(supabase.from).toHaveBeenCalledTimes(4)
const logged = consoleError.mock.calls.flat().join(' ')
expect(logged).toContain('failed to resolve period lock state for supplier invoice anchoring')
expect(logged).toContain('more than one relationship')
consoleError.mockRestore()
})
it('reports failure as null instead of throwing at the caller', async () => {
const { supabase, enqueueMany } = createQueuedMockSupabase()
enqueueMany([
{
data: {
id: 'si-1',
document_id: 'doc-1',
registration_journal_entry_id: 'je-reg',
payment_journal_entry_id: null,
},
},
{ data: { id: 'doc-1', journal_entry_id: null, is_current_version: true } },
{ data: [] },
{ data: [{ id: 'je-reg', status: 'posted', fiscal_period: openPeriod }] },
{ error: { message: 'period locked' } },
])
await expect(
anchorSupplierInvoiceDocument(supabase as unknown as SupabaseClient, 'company-1', 'si-1'),
).resolves.toBeNull()
})
})
describe('sweepFloatingSupplierInvoiceDocuments', () => {
beforeEach(() => {
vi.clearAllMocks()
})
const openPeriod = { is_closed: false, locked_at: null }
it('anchors every floating retained document it finds, across companies', async () => {
const { supabase, enqueueMany } = createQueuedMockSupabase()
enqueueMany([
// Candidate scan: two invoices with floating current-version documents.
{
data: [
{ id: 'si-1', company_id: 'company-1', document: { id: 'doc-1', journal_entry_id: null, is_current_version: true } },
{ id: 'si-2', company_id: 'company-2', document: { id: 'doc-2', journal_entry_id: null, is_current_version: true } },
],
},
// anchorSupplierInvoiceDocument for si-1 (5 queries)
{ data: { id: 'si-1', document_id: 'doc-1', registration_journal_entry_id: null, payment_journal_entry_id: 'je-1' } },
{ data: { id: 'doc-1', journal_entry_id: null, is_current_version: true } },
{ data: [] },
{ data: [{ id: 'je-1', status: 'posted', fiscal_period: openPeriod }] },
{ data: [{ id: 'doc-1' }] },
// anchorSupplierInvoiceDocument for si-2: its only verifikat is locked.
{ data: { id: 'si-2', document_id: 'doc-2', registration_journal_entry_id: null, payment_journal_entry_id: 'je-2' } },
{ data: { id: 'doc-2', journal_entry_id: null, is_current_version: true } },
{ data: [] },
{ data: [{ id: 'je-2', status: 'posted', fiscal_period: { is_closed: true, locked_at: null } }] },
])
const result = await sweepFloatingSupplierInvoiceDocuments(
supabase as unknown as SupabaseClient,
)
expect(result).toEqual({ candidates: 2, anchored: 1 })
})
it('returns zeros and touches nothing when no document is floating', async () => {
const { supabase, enqueueMany } = createQueuedMockSupabase()
enqueueMany([{ data: [] }])
const result = await sweepFloatingSupplierInvoiceDocuments(
supabase as unknown as SupabaseClient,
)
expect(result).toEqual({ candidates: 0, anchored: 0 })
expect(supabase.from).toHaveBeenCalledTimes(1)
})
it('survives a failed candidate scan without throwing', async () => {
const { supabase, enqueueMany } = createQueuedMockSupabase()
enqueueMany([{ error: { message: 'relation walk failed' } }])
await expect(
sweepFloatingSupplierInvoiceDocuments(supabase as unknown as SupabaseClient),
).resolves.toEqual({ candidates: 0, anchored: 0 })
})
})
describe('reanchorOrphanedSupplierInvoiceDocuments', () => {
beforeEach(() => {
vi.clearAllMocks()
})
it('re-anchors the supplier invoice whose document a deleted voucher orphaned', async () => {
const { supabase, enqueueMany } = createQueuedMockSupabase()
enqueueMany([
{ data: [{ id: 'si-1' }] }, // supplier_invoices by document_id
{
data: {
id: 'si-1',
document_id: 'doc-1',
registration_journal_entry_id: null,
payment_journal_entry_id: 'je-pay',
},
},
{ data: { id: 'doc-1', journal_entry_id: null, is_current_version: true } },
{ data: [] },
{
data: [{ id: 'je-pay', status: 'posted', fiscal_period: { is_closed: false, locked_at: null } }],
},
{ data: [{ id: 'doc-1' }] },
])
expect(
await reanchorOrphanedSupplierInvoiceDocuments(
supabase as unknown as SupabaseClient,
'company-1',
['doc-1'],
),
).toBe(1)
})
it('leaves a plain receipt floating so it returns to the unlinked pool', async () => {
const { supabase, enqueueMany } = createQueuedMockSupabase()
enqueueMany([{ data: [] }]) // no supplier invoice owns this document
expect(
await reanchorOrphanedSupplierInvoiceDocuments(
supabase as unknown as SupabaseClient,
'company-1',
['doc-9'],
),
).toBe(0)
})
it('short-circuits when the deleted voucher had no documents', async () => {
const { supabase } = createQueuedMockSupabase()
expect(
await reanchorOrphanedSupplierInvoiceDocuments(
supabase as unknown as SupabaseClient,
'company-1',
[],
),
).toBe(0)
expect(supabase.from).not.toHaveBeenCalled()
})
})
File diff suppressed because it is too large Load Diff
-238
View File
@@ -1,238 +0,0 @@
/**
* Same-origin proxy for Supabase Storage signed URLs.
*
* Agent sandboxes (Claude Desktop's code execution, some MCP clients) only
* allow network egress to the host the MCP server lives on. Our signed
* Storage URLs point at <project>.supabase.co, so a model-free upload or a
* document download from such a sandbox was refused before it left the box
* (user report 2026-08-21). These helpers rewrite a signed URL onto this
* app's own origin (`/api/storage/...`) and resolve it back to the upstream
* Storage URL inside the proxy route.
*
* The signed token travels unchanged and is the only credential on both
* sides: the proxy grants nothing the public Storage host did not already
* grant, and it refuses every path that is not a signed object path on the
* documents bucket. Without NEXT_PUBLIC_APP_URL (a self-host that never set
* it) the rewrite is a no-op rather than a broken localhost link.
*/
export const STORAGE_PROXY_ROUTE = '/api/storage'
/**
* Content types a browser renders natively without a script context: PDF
* and the raster image formats the document archive accepts. These are the
* only types either document-serving route (the inline preview proxy and the
* signed-URL proxy below) hands to the browser as-is. Everything else that
* can reach the archive (text/html mail bodies, application/xhtml+xml
* iXBRL, Peppol application/xml and text/xml, image/svg+xml, application/json,
* unknown or legacy types) is active content when it lands on our origin:
* an uploader-controlled <script> inside it would run with the app origin's
* authority (stored XSS). Those types are served under OPAQUE_DOCUMENT_CSP.
*/
export const INLINE_SAFE_MIME_TYPES: ReadonlySet<string> = new Set([
'application/pdf',
'image/jpeg',
'image/png',
'image/webp',
'image/gif',
'image/heic',
'image/heif',
])
/**
* Policy for every served document that is not natively inline-safe.
* `sandbox` (no tokens) makes the rendered document opaque-origin and
* script-free wherever it is opened, iframe or direct tab. The source
* directives block outbound requests on top of that: sandbox alone still
* loads remote images, so a tracking pixel in a mail body would notify the
* sender when the preview is opened. Inline styles and embedded data:/blob:
* images keep working, so HTML mail previews and XML views still render.
*/
export const OPAQUE_DOCUMENT_CSP =
"sandbox; default-src 'none'; style-src 'unsafe-inline'; img-src data: blob:"
/**
* Canonical (lower-case, parameter-free) form of `mimeType` when it is one
* of INLINE_SAFE_MIME_TYPES, else null. Legacy rows hold client-declared
* strings, so parameters and case are tolerated on the way in but never
* echoed back out.
*/
export function inlineSafeMimeType(mimeType: string | null | undefined): string | null {
if (!mimeType) return null
const essence = mimeType.split(';')[0]?.trim().toLowerCase() ?? ''
return INLINE_SAFE_MIME_TYPES.has(essence) ? essence : null
}
/**
* The documents-bucket object key behind a proxied download path
* (`sign/documents/<key>`, still percent-encoded), decoded so it can be
* matched against `document_attachments.storage_path`. Null for upload paths
* and anything else.
*/
export function documentKeyFromProxyPath(objectPath: string): string | null {
const prefix = 'sign/documents/'
if (!objectPath.startsWith(prefix)) return null
try {
return decodeURIComponent(objectPath.slice(prefix.length))
} catch {
return null
}
}
/** Upstream prefix under the Storage API that every signed object URL shares. */
const UPSTREAM_OBJECT_PREFIX = '/storage/v1/object/'
/**
* Only token-authenticated object paths on the documents bucket: signed
* downloads (`sign/documents/...`) and signed uploads
* (`upload/sign/documents/...`). Anything else (public objects, bucket
* admin, other buckets) is not this proxy's business.
*/
const ALLOWED_OBJECT_PATH_RE = /^(sign|upload\/sign)\/documents\/[^/]+/
export type StorageProxyResolution =
| { ok: true; url: string }
| { ok: false; reason: 'unsupported_path' | 'missing_token' | 'storage_unconfigured' }
/**
* True when every segment of the (still percent-encoded) object path is a
* plain name: no empty segment, no `.`/`..` in raw or percent-encoded form
* (`%2e%2e`, `.%2e`, `%2e.`: the WHATWG URL parser normalises those away,
* which would let `sign/documents/%2e%2e/other/x` leave the documents
* bucket), no backslash (a path separator for https URLs), no malformed
* escapes.
*/
function hasOnlyPlainSegments(objectPath: string): boolean {
for (const segment of objectPath.split('/')) {
if (segment === '') return false
let decoded: string
try {
decoded = decodeURIComponent(segment)
} catch {
return false
}
if (decoded === '.' || decoded === '..') return false
if (decoded.includes('\\') || decoded.includes('/')) return false
}
return true
}
function trimTrailingSlash(value: string): string {
return value.replace(/\/+$/, '')
}
function upstreamStorageOrigin(): string | null {
const raw = process.env.NEXT_PUBLIC_SUPABASE_URL?.trim()
if (!raw) return null
try {
return new URL(raw).origin
} catch {
return null
}
}
/**
* Rewrite a Supabase signed Storage URL onto this app's origin. Returns the
* input unchanged when it is not a signed documents-bucket URL on our Storage
* host, or when the app has no public URL configured.
*/
export function toSameOriginStorageUrl(
signedUrl: string,
appBaseUrl: string | undefined = process.env.NEXT_PUBLIC_APP_URL,
): string {
const base = appBaseUrl?.trim()
const upstream = upstreamStorageOrigin()
if (!base || !upstream) return signedUrl
let url: URL
try {
url = new URL(signedUrl)
} catch {
return signedUrl
}
if (url.origin !== upstream) return signedUrl
if (!url.pathname.startsWith(UPSTREAM_OBJECT_PREFIX)) return signedUrl
// Keep the pathname exactly as Storage encoded it: object keys may hold
// spaces and non-ASCII, and the token was signed over the real key.
const objectPath = url.pathname.slice(UPSTREAM_OBJECT_PREFIX.length)
if (!ALLOWED_OBJECT_PATH_RE.test(objectPath)) return signedUrl
if (!url.searchParams.has('token')) return signedUrl
return `${trimTrailingSlash(base)}${STORAGE_PROXY_ROUTE}/${objectPath}${url.search}`
}
/**
* Resolve the proxied path (everything after `/api/storage/`, still
* percent-encoded as received) plus its query back to the upstream Storage
* URL. Fails closed on anything outside the signed documents-bucket paths.
*/
export function resolveUpstreamStorageUrl(
objectPath: string,
search: URLSearchParams,
): StorageProxyResolution {
const upstream = upstreamStorageOrigin()
if (!upstream) return { ok: false, reason: 'storage_unconfigured' }
if (!ALLOWED_OBJECT_PATH_RE.test(objectPath) || !hasOnlyPlainSegments(objectPath)) {
return { ok: false, reason: 'unsupported_path' }
}
if (!search.get('token')) return { ok: false, reason: 'missing_token' }
const query = search.toString()
const url = `${upstream}${UPSTREAM_OBJECT_PREFIX}${objectPath}${query ? `?${query}` : ''}`
// Belt and braces: whatever fetch() will actually request, after URL
// normalisation, must still sit inside the allowlist.
let normalisedPath: string
try {
normalisedPath = new URL(url).pathname
} catch {
return { ok: false, reason: 'unsupported_path' }
}
if (
!normalisedPath.startsWith(UPSTREAM_OBJECT_PREFIX) ||
!ALLOWED_OBJECT_PATH_RE.test(normalisedPath.slice(UPSTREAM_OBJECT_PREFIX.length))
) {
return { ok: false, reason: 'unsupported_path' }
}
return { ok: true, url }
}
/**
* Read a request body into memory, aborting as soon as it exceeds `maxBytes`
* instead of buffering an unbounded payload first and measuring afterwards
* (the proxy is unauthenticated until Storage checks the token, so a
* self-host without a platform body limit must not be forced to hold an
* arbitrary upload in RAM). Returns null when the cap is exceeded.
*/
export async function readBodyWithCap(
body: ReadableStream<Uint8Array> | null,
maxBytes: number,
): Promise<ArrayBuffer | null> {
if (!body) return new ArrayBuffer(0)
const reader = body.getReader()
const chunks: Uint8Array[] = []
let total = 0
try {
for (;;) {
const { done, value } = await reader.read()
if (done) break
if (!value) continue
total += value.byteLength
if (total > maxBytes) {
await reader.cancel()
return null
}
chunks.push(value)
}
} finally {
reader.releaseLock()
}
const out = new Uint8Array(total)
let offset = 0
for (const chunk of chunks) {
out.set(chunk, offset)
offset += chunk.byteLength
}
return out.buffer
}
@@ -1,329 +0,0 @@
import type { SupabaseClient } from '@supabase/supabase-js'
import { createLogger } from '@/lib/logger'
const log = createLogger('supplier-invoice-underlag')
/**
* Re-anchor a supplier invoice's retained source document to one of the
* invoice's own posted verifikat when the document is currently floating
* (document_attachments.journal_entry_id IS NULL).
*
* Why this exists (support case 2026-07-27): every missing-underlag surface
* (verifikat_without_documents / transactions_without_documents RPCs,
* /api/documents/counts, the transactions list) only accepts a referenced
* supplier-invoice document as underlag when it is ANCHORED to a journal
* entry, because only anchored docs sit behind the WORM deletion guards
* (block_document_deletion keys on journal_entry_id). A floating document
* therefore keeps "Underlag saknas" alive on a verifikat that plainly shows
* the invoice PDF, and the user has no way to resolve it: the nag is supposed
* to get the document anchored, but nothing anchored it.
*
* Documents end up floating two ways, both seen in production:
* 1. delete_last_voucher clears journal_entry_id on every document hanging
* on the deleted voucher (it has to: the FK is ON DELETE RESTRICT). When
* that voucher was a rättelse the invoice's PDF had been relinked onto,
* the invoice is left holding an unanchored document while its payment
* verifikat is still posted.
* 2. Payment/cash verifikat booked for an invoice whose document was never
* anchored at registration (attached after the fact, or booked through a
* path that did not link it).
*
* Anchoring is strictly an improvement: it puts the document behind the
* deletion guard and makes the hänvisning (BFL 5 kap 7 §) legally solid, and
* the immutability triggers explicitly allow NULL -> uuid
* (enforce_document_journal_entry_immutability returns early when
* OLD.journal_entry_id IS NULL). An already-anchored document is never moved.
*
* Returns the journal entry id the document was anchored to, or null when
* nothing needed doing (no document, already anchored, no eligible verifikat).
* Never throws: every caller runs after a committed, immutable booking, so a
* failure here must be logged, not surfaced.
*/
export async function anchorSupplierInvoiceDocument(
supabase: SupabaseClient,
companyId: string,
supplierInvoiceId: string,
): Promise<string | null> {
try {
const { data: invoice } = await supabase
.from('supplier_invoices')
.select('id, document_id, registration_journal_entry_id, payment_journal_entry_id')
.eq('id', supplierInvoiceId)
.eq('company_id', companyId)
.maybeSingle()
const documentId = (invoice as { document_id?: string | null } | null)?.document_id
if (!documentId) return null
const { data: document } = await supabase
.from('document_attachments')
.select('id, journal_entry_id, is_current_version')
.eq('id', documentId)
.eq('company_id', companyId)
.maybeSingle()
const doc = document as
| { id: string; journal_entry_id: string | null; is_current_version: boolean }
| null
// Already anchored (the normal case), superseded, or gone: leave it alone.
// Moving an anchored doc is blocked by the immutability trigger anyway.
if (!doc || doc.journal_entry_id || doc.is_current_version !== true) return null
const entryId = await pickAnchorEntry(
supabase,
companyId,
supplierInvoiceId,
invoice as {
registration_journal_entry_id: string | null
payment_journal_entry_id: string | null
},
)
if (!entryId) {
// The invoice HAS a floating retained document but no verifikat that can
// take it. In the payment routes (which call this right after posting)
// that is an anomaly worth a log line: prod case 2026-08-28 (Anders,
// faktura 118776) stayed "Underlag saknas" through exactly this kind of
// silent bail, and nothing recorded which branch gave up.
log.warn('supplier invoice document is floating but no verifikat can anchor it', {
companyId,
supplierInvoiceId,
documentId: doc.id,
})
return null
}
const { data: updatedRows, error } = await supabase
.from('document_attachments')
.update({ journal_entry_id: entryId })
.eq('id', doc.id)
.eq('company_id', companyId)
// Concurrency guard: a parallel booking may have anchored it since the
// read above. Never steal a document that already serves a verifikat.
.is('journal_entry_id', null)
.eq('is_current_version', true)
.select('id')
if (error) {
log.warn('failed to anchor supplier invoice document to verifikat', {
companyId,
supplierInvoiceId,
documentId: doc.id,
journalEntryId: entryId,
reason: error.message,
})
return null
}
// The guarded update can match zero rows (a concurrent writer got there
// first, or RLS filtered the row). That is NOT a successful anchor: report
// null so callers and the reconcile cron treat the document as still
// floating instead of trusting a write that never happened.
if (!updatedRows || updatedRows.length === 0) {
log.warn('anchor update matched no rows; document left floating', {
companyId,
supplierInvoiceId,
documentId: doc.id,
journalEntryId: entryId,
})
return null
}
return entryId
} catch (err) {
log.warn('anchorSupplierInvoiceDocument threw', {
companyId,
supplierInvoiceId,
reason: err instanceof Error ? err.message : String(err),
})
return null
}
}
/**
* The invoice's own verifikat, in the order BFL wants the underlag to hang:
* the registration booking is the primary booking of the affärshändelse, the
* payment booking is the fallback (and the only booking under kontantmetoden),
* then any partial-payment verifikat, oldest first.
*
* Only posted entries in open, unlocked periods qualify: a reversed entry is
* no longer a live booking, and enforce_period_lock_documents rejects the
* write outright once the period is closed or locked.
*/
async function pickAnchorEntry(
supabase: SupabaseClient,
companyId: string,
supplierInvoiceId: string,
invoice: {
registration_journal_entry_id: string | null
payment_journal_entry_id: string | null
},
): Promise<string | null> {
const candidates: string[] = []
const push = (id: string | null | undefined) => {
if (id && !candidates.includes(id)) candidates.push(id)
}
push(invoice.registration_journal_entry_id)
push(invoice.payment_journal_entry_id)
const { data: paymentRows } = await supabase
.from('supplier_invoice_payments')
.select('journal_entry_id, payment_date')
.eq('company_id', companyId)
.eq('supplier_invoice_id', supplierInvoiceId)
.not('journal_entry_id', 'is', null)
.order('payment_date', { ascending: true })
for (const row of (paymentRows ?? []) as { journal_entry_id: string | null }[]) {
push(row.journal_entry_id)
}
if (candidates.length === 0) return null
const { data: entries, error } = await supabase
.from('journal_entries')
// fiscal_periods also points back at journal_entries (closing_entry_id,
// opening_balance_entry_id), so PostgREST refuses the bare embed as
// ambiguous; name the FK explicitly.
.select(
'id, status, fiscal_period:fiscal_periods!journal_entries_fiscal_period_id_fkey(is_closed, locked_at)',
)
.eq('company_id', companyId)
.in('id', candidates)
if (error) {
// Fail closed: never anchor on a lock state we could not read. But say so.
// The bare embed above returned PGRST201 on every call from 2026-07-27
// onwards and the result was dropped on the floor, so the caller's "no
// verifikat can anchor it" warning was the only signal, and it named the
// wrong cause.
log.error('failed to resolve period lock state for supplier invoice anchoring', {
companyId,
supplierInvoiceId,
reason: error.message,
})
return null
}
type EntryRow = {
id: string
status: string
fiscal_period:
| { is_closed: boolean | null; locked_at: string | null }
| { is_closed: boolean | null; locked_at: string | null }[]
| null
}
const byId = new Map<string, EntryRow>(
((entries ?? []) as unknown as EntryRow[]).map((entry) => [entry.id, entry]),
)
for (const id of candidates) {
const entry = byId.get(id)
if (!entry || entry.status !== 'posted') continue
// PostgREST returns an embedded to-one either as an object or, depending
// on how it resolves the relationship, as a single-element array.
const period = Array.isArray(entry.fiscal_period) ? entry.fiscal_period[0] : entry.fiscal_period
if (period?.is_closed || period?.locked_at) continue
return id
}
return null
}
/**
* Re-anchor the supplier-invoice documents that a just-deleted voucher left
* floating. Takes the document ids that hung on the voucher before it was torn
* down (delete_last_voucher nulls their journal_entry_id), and re-points those
* that are a supplier invoice's retained source document at another posted
* verifikat of the same invoice.
*
* Documents that belong to no supplier invoice are left floating on purpose:
* a receipt uploaded straight to the deleted voucher SHOULD return to the
* unlinked pool so the user can attach it to the replacement booking.
*
* Returns the number of documents re-anchored.
*/
export interface FloatingDocumentSweepResult {
/** Invoices whose floating retained document was examined. */
candidates: number
/** Documents actually anchored to a verifikat this run. */
anchored: number
}
/**
* Prod-wide self-heal for retained supplier-invoice documents that stayed
* floating although the invoice has a posted verifikat: the inline anchoring
* in the payment routes is best-effort by design (never throws, the booking is
* already committed), so a transient failure there strands the document until
* something retries. Historically that "something" was a hand-written repair
* migration (20260727180000, 20260824150000); this makes the retry a standing
* daily cron instead. Prod case 2026-08-28 (Anders, faktura 118776): payment
* verifikat posted, invoice document eligible on every static condition, yet
* the inline anchor did nothing and no log recorded why, so the verifikat
* showed "Underlag saknas" until the user re-uploaded the PDF by hand.
*
* Anchoring an already-shown-but-floating document is strictly an improvement
* (it puts the file behind the WORM deletion guard and satisfies BFL 5 kap
* 7 §), and anchorSupplierInvoiceDocument never moves an anchored document,
* so re-running this sweep is idempotent. Locked/closed periods are skipped by
* pickAnchorEntry, matching the repair migrations.
*
* Meant to run under the service-role client from a cron: RLS would otherwise
* scope the candidate scan to one user's companies.
*/
export async function sweepFloatingSupplierInvoiceDocuments(
supabase: SupabaseClient,
opts: { limit?: number } = {},
): Promise<FloatingDocumentSweepResult> {
const limit = Math.min(Math.max(opts.limit ?? 200, 1), 1000)
// FK named explicitly: with an ambiguous relationship PostgREST rejects the
// embed and the sweep would silently see zero candidates (the #2022 lesson).
const { data, error } = await supabase
.from('supplier_invoices')
.select(
'id, company_id, document:document_attachments!supplier_invoices_document_id_fkey!inner(id, journal_entry_id, is_current_version)',
)
.not('document_id', 'is', null)
.or('payment_journal_entry_id.not.is.null,registration_journal_entry_id.not.is.null')
.is('document.journal_entry_id', null)
.eq('document.is_current_version', true)
.limit(limit)
if (error) {
log.warn('floating-document sweep query failed', { reason: error.message })
return { candidates: 0, anchored: 0 }
}
const rows = (data ?? []) as unknown as Array<{ id: string; company_id: string }>
let anchored = 0
for (const row of rows) {
if (await anchorSupplierInvoiceDocument(supabase, row.company_id, row.id)) anchored++
}
if (rows.length > 0) {
log.info('floating-document sweep complete', { candidates: rows.length, anchored })
}
return { candidates: rows.length, anchored }
}
export async function reanchorOrphanedSupplierInvoiceDocuments(
supabase: SupabaseClient,
companyId: string,
documentIds: string[],
): Promise<number> {
if (documentIds.length === 0) return 0
try {
const { data: invoices } = await supabase
.from('supplier_invoices')
.select('id')
.eq('company_id', companyId)
.in('document_id', documentIds)
let anchored = 0
for (const invoice of ((invoices ?? []) as { id: string }[])) {
if (await anchorSupplierInvoiceDocument(supabase, companyId, invoice.id)) anchored++
}
return anchored
} catch (err) {
log.warn('reanchorOrphanedSupplierInvoiceDocuments threw', {
companyId,
reason: err instanceof Error ? err.message : String(err),
})
return 0
}
}