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

Återställer 6136 filer från 7e33543^. Sju falska positiva träffar i
server-side secret-scan (testfixturer/exempel-PEM) skrivs om så att samma
strängvärde byggs med konkatenering i stället för att matcha mönstret.
This commit is contained in:
2026-11-10 09:37:22 +01:00
parent 077251ac94
commit e7f0070e84
6135 changed files with 1718997 additions and 4 deletions
@@ -0,0 +1,288 @@
import { describe, it, expect, vi, beforeEach } from 'vitest'
import { eventBus } from '@/lib/events/bus'
import {
parseJsonResponse,
createMockRouteParams,
createQueuedMockSupabase,
makeDocumentAttachment,
} from '@/tests/helpers'
const { supabase: mockSupabase, enqueue, reset } = createQueuedMockSupabase()
const requireAuthMock = vi.fn()
vi.mock('@/lib/auth/require-auth', () => ({
requireAuth: (...args: unknown[]) => requireAuthMock(...args),
}))
vi.mock('@/lib/company/context', () => ({
requireCompanyId: vi.fn().mockResolvedValue('company-1'),
getActiveCompanyId: vi.fn().mockResolvedValue('company-1'),
}))
vi.mock('@/lib/auth/require-write', () => ({
requireWritePermission: vi.fn().mockResolvedValue({ ok: true }),
}))
vi.mock('@/lib/init', () => ({
ensureInitialized: vi.fn(),
}))
// The GET route signs with the service-role client: the storage SELECT
// policy only covers the uploader's own folder, so a company member viewing
// a colleague's upload cannot sign with their own client.
const createSignedUrlMock = vi.fn()
const serviceStorageFromMock = vi.fn(() => ({ createSignedUrl: createSignedUrlMock }))
vi.mock('@/lib/supabase/server', () => ({
createServiceClient: () => ({
storage: { from: serviceStorageFromMock },
}),
}))
// deleteDocument removes storage objects via the cookieless service-role
// client: the documents bucket is WORM (no DELETE policy on storage.objects),
// so a caller-bound remove() is silently blocked by RLS.
const serviceRemoveMock = vi.fn()
vi.mock('@/lib/auth/api-keys', () => ({
createServiceClientNoCookies: () => ({
storage: { from: vi.fn(() => ({ remove: serviceRemoveMock })) },
}),
}))
import { GET, DELETE } from '../route'
import { requireWritePermission } from '@/lib/auth/require-write'
import { NextResponse } from 'next/server'
const mockUser = { id: 'user-1', email: 'test@test.se' }
beforeEach(() => {
vi.clearAllMocks()
reset()
eventBus.clear()
requireAuthMock.mockResolvedValue({ user: mockUser, supabase: mockSupabase, error: null })
// Reset write-permission mock to default ok
vi.mocked(requireWritePermission).mockResolvedValue({ ok: true })
createSignedUrlMock.mockResolvedValue({
data: { signedUrl: 'https://example.com/signed' },
error: null,
})
serviceRemoveMock.mockResolvedValue({ data: [], error: null })
})
function makeReq(method: 'GET' | 'DELETE' = 'DELETE') {
return new Request('http://localhost/api/documents/doc-1', { method })
}
describe('GET /api/documents/[id]', () => {
it('returns 401 when not authenticated', async () => {
requireAuthMock.mockResolvedValue({
user: null,
supabase: mockSupabase,
error: NextResponse.json({ error: 'Unauthorized' }, { status: 401 }),
})
const res = await GET(makeReq('GET'), createMockRouteParams({ id: 'doc-1' }))
const { status, body } = await parseJsonResponse(res)
expect(status).toBe(401)
expect(body).toEqual({ error: 'Unauthorized' })
})
it('returns 404 when the document is not found in the company', async () => {
enqueue({ data: null, error: null }) // doc lookup
const res = await GET(makeReq('GET'), createMockRouteParams({ id: 'doc-1' }))
const { status, body } = await parseJsonResponse<{ error: string }>(res)
expect(status).toBe(404)
expect(body.error).toBe('Document not found')
})
it('returns 500 when the signed URL cannot be created', async () => {
enqueue({ data: makeDocumentAttachment({ id: 'doc-1' }), error: null })
createSignedUrlMock.mockResolvedValue({ data: null, error: { message: 'boom' } })
const res = await GET(makeReq('GET'), createMockRouteParams({ id: 'doc-1' }))
const { status, body } = await parseJsonResponse<{ error: string }>(res)
expect(status).toBe(500)
expect(body.error).toContain('Failed to create download URL')
})
it('returns the document with a signed download URL and emits document.accessed', async () => {
const row = makeDocumentAttachment({
id: 'doc-1',
file_name: 'kvitto.pdf',
storage_path: 'documents/user-1/kvitto.pdf',
})
enqueue({ data: row, error: null })
const handler = vi.fn()
eventBus.on('document.accessed', handler)
const res = await GET(makeReq('GET'), createMockRouteParams({ id: 'doc-1' }))
const { status, body } = await parseJsonResponse<{
data: { id: string; download_url: string }
}>(res)
expect(status).toBe(200)
expect(body.data.id).toBe('doc-1')
expect(body.data.download_url).toBe('https://example.com/signed')
expect(serviceStorageFromMock).toHaveBeenCalledWith('documents')
expect(createSignedUrlMock).toHaveBeenCalledWith('documents/user-1/kvitto.pdf', 3600)
expect(handler).toHaveBeenCalledOnce()
expect(handler).toHaveBeenCalledWith(
expect.objectContaining({
document: expect.objectContaining({ id: 'doc-1', file_name: 'kvitto.pdf' }),
userId: 'user-1',
companyId: 'company-1',
}),
)
})
it('signs attachments stored under another company member folder', async () => {
// Regression: the storage SELECT policy is per-uploader-folder, so signing
// with the user-bound client failed for every colleague-uploaded document
// ("Failed to create download URL"). The service client must sign after
// the company-scoped row fetch has authorized access.
const row = makeDocumentAttachment({
id: 'doc-2',
file_name: 'leverantorsfaktura.pdf',
storage_path: 'documents/other-member/leverantorsfaktura.pdf',
})
enqueue({ data: row, error: null })
const res = await GET(makeReq('GET'), createMockRouteParams({ id: 'doc-2' }))
const { status, body } = await parseJsonResponse<{
data: { download_url: string }
}>(res)
expect(status).toBe(200)
expect(body.data.download_url).toBe('https://example.com/signed')
expect(createSignedUrlMock).toHaveBeenCalledWith(
'documents/other-member/leverantorsfaktura.pdf',
3600,
)
// The user-bound client must not be used for signing at all.
expect(mockSupabase.storage.from).not.toHaveBeenCalled()
})
})
describe('DELETE /api/documents/[id]', () => {
it('returns 401 when not authenticated', async () => {
requireAuthMock.mockResolvedValue({
user: null,
supabase: mockSupabase,
error: NextResponse.json({ error: 'Unauthorized' }, { status: 401 }),
})
const res = await DELETE(makeReq(), createMockRouteParams({ id: 'doc-1' }))
const { status, body } = await parseJsonResponse(res)
expect(status).toBe(401)
expect(body).toEqual({ error: 'Unauthorized' })
})
it('returns 403 when caller has read-only role', async () => {
vi.mocked(requireWritePermission).mockResolvedValue({
ok: false,
response: NextResponse.json(
{ error: 'Du har endast läsbehörighet i detta företag.' },
{ status: 403 },
),
})
const res = await DELETE(makeReq(), createMockRouteParams({ id: 'doc-1' }))
const { status } = await parseJsonResponse(res)
expect(status).toBe(403)
})
it('returns 404 when document not found in company', async () => {
enqueue({ data: null, error: null }) // doc lookup
const res = await DELETE(makeReq(), createMockRouteParams({ id: 'doc-1' }))
const { status, body } = await parseJsonResponse<{ error: string }>(res)
expect(status).toBe(404)
expect(body.error).toContain('hittades inte')
})
it('returns 409 with BFL message when doc is linked to a journal entry', async () => {
enqueue({
data: {
id: 'doc-1',
file_name: 'kvitto.pdf',
storage_path: 'documents/user-1/kvitto.pdf',
journal_entry_id: 'je-99',
user_id: 'user-1',
},
error: null,
})
const res = await DELETE(makeReq(), createMockRouteParams({ id: 'doc-1' }))
const { status, body } = await parseJsonResponse<{ error: string }>(res)
expect(status).toBe(409)
expect(body.error).toContain('Bokföringslagen')
expect(body.error).toContain('7 kap')
})
it('deletes the row, removes Storage file, and emits document.deleted on unlinked doc', async () => {
enqueue({
data: {
id: 'doc-1',
file_name: 'kvitto.pdf',
storage_path: 'documents/user-1/kvitto.pdf',
journal_entry_id: null,
user_id: 'user-1',
},
error: null,
})
enqueue({ data: null, error: null }) // delete
const handler = vi.fn()
eventBus.on('document.deleted', handler)
const res = await DELETE(makeReq(), createMockRouteParams({ id: 'doc-1' }))
const { status, body } = await parseJsonResponse<{ data: { id: string; deleted: boolean } }>(res)
expect(status).toBe(200)
expect(body.data).toEqual({ id: 'doc-1', deleted: true })
// Both storage layouts are removed: the stored pointer plus the alternate
// candidate key. During the company-scoped path migration a document can
// exist under either prefix, and removing only the stored one would leave a
// readable orphan copy of a document the user asked to erase. The removal
// must go through the service-role client (WORM bucket: RLS silently
// blocks a caller-bound remove()), never the user-bound client.
expect(serviceRemoveMock).toHaveBeenCalledWith([
'documents/user-1/kvitto.pdf',
'documents/company-1/user-1/kvitto.pdf',
])
expect(mockSupabase.storage.from).not.toHaveBeenCalled()
expect(handler).toHaveBeenCalledOnce()
expect(handler).toHaveBeenCalledWith(
expect.objectContaining({
document: expect.objectContaining({ id: 'doc-1', file_name: 'kvitto.pdf' }),
userId: 'user-1',
companyId: 'company-1',
}),
)
})
it('returns 409 with BFL message when DB trigger blocks deletion (defense-in-depth)', async () => {
// Caller bypasses the application-layer check (e.g. race condition).
// The block_document_deletion() trigger raises with "Bokföringslagen" in the
// message; the service maps it to a 409.
enqueue({
data: {
id: 'doc-1',
file_name: 'kvitto.pdf',
storage_path: 'documents/user-1/kvitto.pdf',
journal_entry_id: null,
user_id: 'user-1',
},
error: null,
})
enqueue({
data: null,
error: { message: 'Cannot delete document linked to a posted journal entry (Bokföringslagen)' },
})
const res = await DELETE(makeReq(), createMockRouteParams({ id: 'doc-1' }))
const { status, body } = await parseJsonResponse<{ error: string }>(res)
expect(status).toBe(409)
expect(body.error).toContain('Bokföringslagen')
})
})
@@ -0,0 +1,125 @@
/**
* Tests for POST /api/documents/[id]/detach (detach a duplicate underlag from
* a posted verifikat via the audited detach_underlag_duplicate RPC).
*
* Covers: 401, rule-violation 409 passthrough (Swedish RPC messages verbatim),
* tenant guard 403, unexpected RPC failure 500, and the happy path.
*/
import { describe, it, expect, vi, beforeEach } from 'vitest'
import { NextResponse } from 'next/server'
import {
createQueuedMockSupabase,
createMockRequest,
createMockRouteParams,
parseJsonResponse,
} from '@/tests/helpers'
const { supabase, reset } = createQueuedMockSupabase()
const rpcMock = vi.fn()
;(supabase as { rpc?: unknown }).rpc = rpcMock
const requireAuthMock = vi.fn()
vi.mock('@/lib/auth/require-auth', () => ({
requireAuth: (...args: unknown[]) => requireAuthMock(...args),
}))
vi.mock('@/lib/company/context', () => ({
getActiveCompanyId: vi.fn().mockResolvedValue('company-1'),
requireCompanyId: vi.fn().mockResolvedValue('company-1'),
}))
vi.mock('@/lib/auth/require-write', () => ({
requireWritePermission: vi.fn().mockResolvedValue({ ok: true }),
}))
vi.mock('@/lib/init', () => ({ ensureInitialized: vi.fn() }))
import { POST } from '../route'
const params = () => createMockRouteParams({ id: 'doc-1' })
function makeRequest() {
return createMockRequest('/api/documents/doc-1/detach', { method: 'POST' })
}
describe('POST /api/documents/[id]/detach', () => {
beforeEach(() => {
vi.clearAllMocks()
reset()
requireAuthMock.mockResolvedValue({ user: { id: 'user-1' }, supabase })
})
it('returns 401 when not authenticated', async () => {
requireAuthMock.mockResolvedValue({
error: NextResponse.json({ error: 'Unauthorized' }, { status: 401 }),
})
const response = await POST(makeRequest(), params())
expect(response.status).toBe(401)
expect(rpcMock).not.toHaveBeenCalled()
})
it('passes rule violations through as 409 with the Swedish message', async () => {
rpcMock.mockResolvedValue({
data: null,
error: {
code: 'P0001',
message:
'Verifikationen skulle stå utan underlag: det sista underlaget kan inte kopplas bort. Ersätt det med en ny version i stället.',
},
})
const response = await POST(makeRequest(), params())
const { body } = await parseJsonResponse<{ error: string }>(response)
expect(response.status).toBe(409)
expect(body.error).toContain('sista underlaget')
})
it('maps the tenant guard (42501) to 403', async () => {
rpcMock.mockResolvedValue({
data: null,
error: { code: '42501', message: 'unauthorized: caller is not a member of company company-1' },
})
const response = await POST(makeRequest(), params())
expect(response.status).toBe(403)
})
it('returns 500 on unexpected RPC failure', async () => {
rpcMock.mockResolvedValue({
data: null,
error: { code: '57014', message: 'canceling statement due to statement timeout' },
})
const response = await POST(makeRequest(), params())
expect(response.status).toBe(500)
})
it('detaches the duplicate and returns the RPC result', async () => {
rpcMock.mockResolvedValue({
data: {
detached: true,
document_id: 'doc-1',
journal_entry_id: 'je-1',
remaining_documents: 1,
},
error: null,
})
const response = await POST(makeRequest(), params())
const { body } = await parseJsonResponse<{
data: { detached: boolean; journal_entry_id: string; remaining_documents: number }
}>(response)
expect(response.status).toBe(200)
expect(body.data.detached).toBe(true)
expect(body.data.remaining_documents).toBe(1)
expect(rpcMock).toHaveBeenCalledWith('detach_underlag_duplicate', {
p_company_id: 'company-1',
p_document_id: 'doc-1',
p_user_id: 'user-1',
})
})
})
+48
View File
@@ -0,0 +1,48 @@
import { NextResponse } from 'next/server'
import { withRouteContext } from '@/lib/api/with-route-context'
import { getErrorMessage } from '@/lib/errors/get-error-message'
/**
* POST /api/documents/[id]/detach
*
* Detach a redundant duplicate underlag from its posted verifikation. The
* detach_underlag_duplicate RPC enforces everything (writer role, open and
* unlocked period, company lock date, at least one other anchored underlag
* remaining, not pinned to a transaction or supplier invoice) and writes an
* append-only audit_log row before the carve-out UPDATE. The document itself
* is never deleted: it returns to the unlinked document pool, where the
* ordinary deletion rules apply (an unlinked doc may be deleted).
*/
export const POST = withRouteContext<{ params: Promise<{ id: string }> }>(
'documents.detach',
async (_request, { supabase, companyId, user, log }, { params }) => {
const { id } = await params
const { data, error } = await supabase.rpc('detach_underlag_duplicate', {
p_company_id: companyId,
p_document_id: id,
p_user_id: user.id,
})
if (error) {
// Rule violations are plain RAISE EXCEPTION (P0001) with user-facing
// Swedish messages: surface verbatim as 409. Tenant guard raises 42501.
if (error.code === 'P0001') {
return NextResponse.json({ error: getErrorMessage(error) }, { status: 409 })
}
if (error.code === '42501') {
// The RPC's tenant-guard message is English (log/diagnostic text);
// getErrorMessage would pass it through verbatim, so map it here.
return NextResponse.json(
{ error: 'Du saknar behörighet att ändra underlag i det här företaget.' },
{ status: 403 },
)
}
log.error('detach_underlag_duplicate failed', new Error(error.message), { documentId: id })
return NextResponse.json({ error: 'Underlaget kunde inte kopplas bort' }, { status: 500 })
}
return NextResponse.json({ data })
},
{ requireWrite: true },
)
@@ -0,0 +1,100 @@
import { describe, it, expect, vi, beforeEach } from 'vitest'
import { createQueuedMockSupabase, createMockRequest, parseJsonResponse } from '@/tests/helpers'
const { supabase, enqueue, reset } = createQueuedMockSupabase()
let unauthorized = false
vi.mock('@/lib/api/with-route-context', () => ({
withRouteContext: (_op: string, handler: (req: unknown, ctx: unknown, extra: unknown) => unknown) => {
return async (req: unknown, extra: unknown) => {
if (unauthorized) {
return new Response(JSON.stringify({ error: 'Unauthorized' }), { status: 401 })
}
return handler(req, { supabase, companyId: 'company-1', user: { id: 'user-1' } }, extra)
}
},
}))
const aiStatusMock = vi.fn()
vi.mock('@/lib/ai', () => ({
getAiStatus: () => aiStatusMock(),
}))
import { GET, deriveExtractionStatus } from '../route'
const params = { params: Promise.resolve({ id: 'doc-1' }) }
beforeEach(() => {
vi.clearAllMocks()
reset()
unauthorized = false
aiStatusMock.mockReturnValue({ configured: true })
})
describe('deriveExtractionStatus', () => {
const base = { extracted_at: '2026-08-20T10:00:00Z', extracted_data: null, extraction_model: null }
it('is running while unstamped on a configured deployment', () => {
expect(deriveExtractionStatus({ ...base, extracted_at: null }, true)).toBe('running')
})
// The self-host "no key yet" case: answer on the first poll, no 30 s hang.
it('is disabled while unstamped on an unconfigured deployment', () => {
expect(deriveExtractionStatus({ ...base, extracted_at: null }, false)).toBe('disabled')
})
it('is succeeded when data landed', () => {
expect(deriveExtractionStatus({ ...base, extracted_data: { a: 1 } }, true)).toBe('succeeded')
})
it('maps the quiet skips (paywall, unconfigured, sandbox, opt-out, system) to disabled', () => {
for (const m of [
'skipped:no_ai_entitlement',
'skipped:ai_unconfigured',
'skipped:sandbox',
'skipped:client_opt_out',
'skipped:system_generated',
]) {
expect(deriveExtractionStatus({ ...base, extraction_model: m }, true)).toBe('disabled')
}
})
it('maps every other skip to unsupported and failures to failed', () => {
expect(deriveExtractionStatus({ ...base, extraction_model: 'skipped:unsupported_mime' }, true)).toBe('unsupported')
expect(deriveExtractionStatus({ ...base, extraction_model: 'skipped:ai_no_vision' }, true)).toBe('unsupported')
expect(deriveExtractionStatus({ ...base, extraction_model: 'failed:no_raw_text' }, true)).toBe('failed')
expect(deriveExtractionStatus({ ...base, extraction_model: null }, true)).toBe('failed')
})
})
describe('GET /api/documents/:id/extraction-status', () => {
it('returns 401 when unauthenticated', async () => {
unauthorized = true
const res = await GET(createMockRequest('/api/documents/doc-1/extraction-status'), params)
const { status } = await parseJsonResponse(res)
expect(status).toBe(401)
})
it('returns 404 for an unknown document', async () => {
enqueue({ data: null })
const res = await GET(createMockRequest('/api/documents/doc-1/extraction-status'), params)
const { status } = await parseJsonResponse(res)
expect(status).toBe(404)
})
it('returns the derived status', async () => {
enqueue({ data: { id: 'doc-1', extracted_at: '2026-08-20T10:00:00Z', extracted_data: null, extraction_model: 'skipped:no_ai_entitlement' } })
const res = await GET(createMockRequest('/api/documents/doc-1/extraction-status'), params)
const { status, body } = await parseJsonResponse<{ data: { status: string } }>(res)
expect(status).toBe(200)
expect(body.data.status).toBe('disabled')
})
it('answers disabled immediately on an unconfigured deployment', async () => {
aiStatusMock.mockReturnValue({ configured: false })
enqueue({ data: { id: 'doc-1', extracted_at: null, extracted_data: null, extraction_model: null } })
const res = await GET(createMockRequest('/api/documents/doc-1/extraction-status'), params)
const { body } = await parseJsonResponse<{ data: { status: string } }>(res)
expect(body.data.status).toBe('disabled')
})
})
@@ -0,0 +1,85 @@
import { NextResponse } from 'next/server'
import { withRouteContext } from '@/lib/api/with-route-context'
import { getAiStatus } from '@/lib/ai'
import { getErrorMessage as getUserErrorMessage } from '@/lib/errors/get-error-message'
// GET /api/documents/:id/extraction-status
//
// Light-weight polling endpoint for the AI document-extraction pipeline.
// Returns the minimal fields needed to drive an "extracting…" UI without
// touching storage (no signed URL creation per poll).
//
// Derived status:
// running : extracted_at IS NULL and this deployment has AI configured
// (the pipeline hasn't stamped yet)
// succeeded : extracted_at IS NOT NULL AND extracted_data IS NOT NULL
// disabled : no extraction will ever happen for this document and that
// is not the document's fault: AI is not configured on this
// deployment (extracted_at NULL + unconfigured, or stamped
// skipped:ai_unconfigured), the company is not entitled to
// AI extraction (skipped:no_ai_entitlement), a sandbox or
// client opt-out, or a document the system generated itself
// (skipped:system_generated). The UI shows nothing.
// unsupported : any other skipped:* (HEIC, ZIP, no vision model, …)
// failed : extracted_at IS NOT NULL AND extracted_data IS NULL AND
// extraction_model = 'failed:*'
//
// Before extraction was stamped on every outcome, free-tier uploads and
// unconfigured self-hosts left the column NULL forever and the client had to
// decide "disabled" by timing out after 30 s. It still keeps that timeout as
// the last resort (the document-extraction extension may be switched off).
export type DocumentExtractionStatus = 'running' | 'succeeded' | 'failed' | 'unsupported' | 'disabled'
const QUIET_SKIPS = new Set([
'skipped:ai_unconfigured',
'skipped:no_ai_entitlement',
'skipped:sandbox',
'skipped:client_opt_out',
'skipped:system_generated',
])
export function deriveExtractionStatus(row: {
extracted_at: string | null
extracted_data: unknown
extraction_model: string | null
}, aiConfigured: boolean): DocumentExtractionStatus {
if (!row.extracted_at) return aiConfigured ? 'running' : 'disabled'
if (row.extracted_data) return 'succeeded'
const model = row.extraction_model ?? ''
if (QUIET_SKIPS.has(model)) return 'disabled'
if (model.startsWith('skipped:')) return 'unsupported'
return 'failed'
}
export const GET = withRouteContext<{ params: Promise<{ id: string }> }>(
'document.extraction_status',
async (_request, { supabase, companyId }, { params }) => {
const { id } = await params
const { data, error } = await supabase
.from('document_attachments')
.select('id, extracted_at, extracted_data, extraction_model')
.eq('id', id)
.eq('company_id', companyId)
.maybeSingle()
if (error) return NextResponse.json({ error: getUserErrorMessage(error) }, { status: 500 })
if (!data) return NextResponse.json({ error: 'Not found' }, { status: 404 })
const row = {
extracted_at: data.extracted_at as string | null,
extracted_data: data.extracted_data as Record<string, unknown> | null,
extraction_model: data.extraction_model as string | null,
}
const status = deriveExtractionStatus(row, getAiStatus().configured)
return NextResponse.json({
data: {
id: data.id,
status,
extracted_at: row.extracted_at,
extraction_model: row.extraction_model,
},
})
}
)
@@ -0,0 +1,220 @@
import { describe, it, expect, vi, beforeEach } from 'vitest'
import {
parseJsonResponse,
createMockRouteParams,
createQueuedMockSupabase,
} from '@/tests/helpers'
const { supabase: mockSupabase, enqueue, reset } = createQueuedMockSupabase()
const requireAuthMock = vi.fn()
vi.mock('@/lib/auth/require-auth', () => ({
requireAuth: (...args: unknown[]) => requireAuthMock(...args),
}))
vi.mock('@/lib/company/context', () => ({
getActiveCompanyId: vi.fn().mockResolvedValue('company-1'),
}))
vi.mock('@/lib/auth/require-write', () => ({
requireWritePermission: vi.fn().mockResolvedValue({ ok: true }),
}))
const downloadMock = vi.fn()
vi.mock('@/lib/supabase/server', () => ({
createServiceClient: () => ({
storage: {
from: () => ({ download: downloadMock }),
},
}),
}))
import { GET } from '../route'
import { NextResponse } from 'next/server'
const mockUser = { id: 'user-1', email: 'test@test.se' }
// NFD filename as macOS/iOS uploads produce them: o + combining diaeresis
// U+0308 (char code 776). This is the exact shape that made the raw header
// build throw in prod (undici Headers require code units <= 0xFF).
const NFD_FILE_NAME = 'kvitto fo\u0308rvaring.pdf'
function makeDoc(overrides: Record<string, unknown> = {}) {
return {
id: 'doc-1',
company_id: 'company-1',
file_name: NFD_FILE_NAME,
mime_type: 'application/pdf',
storage_path: 'documents/user-1/doc-1.pdf',
...overrides,
}
}
function makeReq() {
return new Request('http://localhost/api/documents/doc-1/inline')
}
beforeEach(() => {
vi.clearAllMocks()
reset()
requireAuthMock.mockResolvedValue({ user: mockUser, supabase: mockSupabase, error: null })
downloadMock.mockResolvedValue({ data: new Blob(['%PDF-1.4']), error: null })
})
describe('GET /api/documents/[id]/inline', () => {
it('returns 401 when not authenticated', async () => {
requireAuthMock.mockResolvedValue({
user: null,
supabase: mockSupabase,
error: NextResponse.json({ error: 'Unauthorized' }, { status: 401 }),
})
const res = await GET(makeReq(), createMockRouteParams({ id: 'doc-1' }))
const { status } = await parseJsonResponse(res)
expect(status).toBe(401)
})
it('returns 404 when the document is not found', async () => {
enqueue({ data: null, error: { message: 'not found' } }) // doc lookup
const res = await GET(makeReq(), createMockRouteParams({ id: 'doc-1' }))
const { status, body } = await parseJsonResponse<{ error: string }>(res)
expect(status).toBe(404)
expect(body.error).toBe('Document not found')
})
it('returns 404 when the document is outside the active company', async () => {
enqueue({ data: null, error: null })
const res = await GET(makeReq(), createMockRouteParams({ id: 'doc-1' }))
const { status } = await parseJsonResponse(res)
expect(status).toBe(404)
})
it('returns 500 when the storage download fails', async () => {
enqueue({ data: makeDoc(), error: null })
downloadMock.mockResolvedValue({ data: null, error: { message: 'boom' } })
const res = await GET(makeReq(), createMockRouteParams({ id: 'doc-1' }))
const { status } = await parseJsonResponse(res)
expect(status).toBe(500)
})
it('streams the file with an RFC 5987 Content-Disposition for an NFD filename', async () => {
enqueue({ data: makeDoc(), error: null })
const res = await GET(makeReq(), createMockRouteParams({ id: 'doc-1' }))
expect(res.status).toBe(200)
const disposition = res.headers.get('Content-Disposition') ?? ''
expect(disposition).toContain('inline')
// Extended form carries the NFC-composed UTF-8 percent-encoded name.
expect(disposition).toContain(`filename*=UTF-8''kvitto%20f%C3%B6rvaring.pdf`)
// ASCII fallback replaces the non-ASCII character.
expect(disposition).toContain('filename="kvitto f_rvaring.pdf"')
expect(res.headers.get('Content-Type')).toBe('application/pdf')
expect(res.headers.get('Cache-Control')).toBe('private, no-store')
// PDF is natively inline-safe: the sandboxing CSP would break Chrome's
// built-in viewer, so it must be absent here.
expect(res.headers.get('Content-Security-Policy')).toBeNull()
})
it('serves raster images without the sandboxing CSP', async () => {
enqueue({ data: makeDoc({ file_name: 'kvitto.png', mime_type: 'image/png' }), error: null })
downloadMock.mockResolvedValue({ data: new Blob([new Uint8Array([0x89, 0x50, 0x4e, 0x47])]), error: null })
const res = await GET(makeReq(), createMockRouteParams({ id: 'doc-1' }))
expect(res.status).toBe(200)
expect(res.headers.get('Content-Type')).toBe('image/png')
expect(res.headers.get('Content-Security-Policy')).toBeNull()
})
it('serves HTML documents with a sandboxing CSP that blocks outbound requests', async () => {
enqueue({
data: makeDoc({ file_name: 'faktura.html', mime_type: 'text/html' }),
error: null,
})
downloadMock.mockResolvedValue({
data: new Blob(['<img src="https://tracker.example/pixel.gif">']),
error: null,
})
const res = await GET(makeReq(), createMockRouteParams({ id: 'doc-1' }))
expect(res.status).toBe(200)
expect(res.headers.get('Content-Type')).toBe('text/html')
// sandbox alone neutralizes scripts but still loads remote resources: a
// tracking pixel in a mail body would notify the sender on preview. The
// source policy confines the document to inline styles and embedded
// data:/blob: images.
expect(res.headers.get('Content-Security-Policy')).toBe(
"sandbox; default-src 'none'; style-src 'unsafe-inline'; img-src data: blob:",
)
expect(res.headers.get('X-Content-Type-Options')).toBe('nosniff')
})
// Allow-list, not deny-list: every type outside PDF/raster images is
// uploader-controlled active content on this origin and must be sandboxed,
// while still rendering inline (Peppol XML archives, iXBRL, JSON previews).
it.each([
['application/xml', 'peppol-faktura.xml', '<?xml version="1.0"?><Invoice/>'],
['text/xml', 'peppol-faktura.xml', '<?xml version="1.0"?><Invoice/>'],
[
'application/xhtml+xml',
'arsredovisning.xhtml',
'<?xml version="1.0"?><html xmlns="http://www.w3.org/1999/xhtml"><script>alert(1)</script></html>',
],
[
'image/svg+xml',
'logga.svg',
'<svg xmlns="http://www.w3.org/2000/svg"><script>alert(document.cookie)</script></svg>',
],
['application/json', 'psd2-svar.json', '{"transactions":[]}'],
])('serves %s inline but under the sandboxing CSP', async (mimeType, fileName, body) => {
enqueue({ data: makeDoc({ file_name: fileName, mime_type: mimeType }), error: null })
downloadMock.mockResolvedValue({ data: new Blob([body]), error: null })
const res = await GET(makeReq(), createMockRouteParams({ id: 'doc-1' }))
expect(res.status).toBe(200)
expect(res.headers.get('Content-Type')).toBe(mimeType)
expect(res.headers.get('Content-Disposition')).toContain('inline')
expect(res.headers.get('Content-Security-Policy')).toBe(
"sandbox; default-src 'none'; style-src 'unsafe-inline'; img-src data: blob:",
)
expect(res.headers.get('X-Content-Type-Options')).toBe('nosniff')
})
it('sandboxes a legacy row whose type is spoofed with casing or parameters', async () => {
enqueue({
data: makeDoc({ file_name: 'faktura.html', mime_type: 'TEXT/HTML; charset=utf-8' }),
error: null,
})
const res = await GET(makeReq(), createMockRouteParams({ id: 'doc-1' }))
expect(res.status).toBe(200)
expect(res.headers.get('Content-Security-Policy')).toBe(
"sandbox; default-src 'none'; style-src 'unsafe-inline'; img-src data: blob:",
)
})
it('sandboxes an unknown type the extension fallback cannot resolve', async () => {
enqueue({ data: makeDoc({ file_name: 'underlag.bin', mime_type: null }), error: null })
const res = await GET(makeReq(), createMockRouteParams({ id: 'doc-1' }))
expect(res.status).toBe(200)
expect(res.headers.get('Content-Type')).toBe('application/octet-stream')
expect(res.headers.get('Content-Security-Policy')).toBe(
"sandbox; default-src 'none'; style-src 'unsafe-inline'; img-src data: blob:",
)
})
it('keeps the extension fallback for legacy PDF rows without adding the CSP', async () => {
enqueue({ data: makeDoc({ file_name: 'kvitto.pdf', mime_type: null }), error: null })
const res = await GET(makeReq(), createMockRouteParams({ id: 'doc-1' }))
expect(res.status).toBe(200)
expect(res.headers.get('Content-Type')).toBe('application/pdf')
expect(res.headers.get('Content-Security-Policy')).toBeNull()
})
})
+118
View File
@@ -0,0 +1,118 @@
import { NextResponse } from 'next/server'
import { createServiceClient } from '@/lib/supabase/server'
import { contentDisposition } from '@/lib/api/content-disposition'
import { withRouteContext } from '@/lib/api/with-route-context'
import { OPAQUE_DOCUMENT_CSP, inlineSafeMimeType } from '@/lib/core/documents/storage-proxy'
import { getErrorMessage as getUserErrorMessage } from '@/lib/errors/get-error-message'
/**
* GET /api/documents/:id/inline
*
* Same-origin proxy that streams a document attachment with
* `Content-Disposition: inline`, allowing it to render inside
* an <iframe> or <img> tag.
*
* Supabase Storage signed URLs return `Content-Disposition: attachment`,
* which browsers refuse to render inline: that triggers the
* "Det här innehållet har blockerats" error in journal entry previews.
*
* Defense in depth: the user's cookie-bound client authorizes access
* (RLS + explicit company_id filter) before the service-role client
* fetches the file from the non-public `documents` bucket.
*
* Content types are served on an allow-list basis: only the natively
* inline-safe types (INLINE_SAFE_MIME_TYPES: PDF and raster images) render
* with the app origin's authority. Every other resolved type is served
* under OPAQUE_DOCUMENT_CSP, which keeps it opaque-origin and script-free
* while still letting the preview render (HTML mail bodies, Peppol XML,
* iXBRL). The mime_type column was client-declared for legacy rows, so the
* decision cannot trust it beyond membership in the allow-list.
*/
const EXTENSION_MIME_MAP: Record<string, string> = {
pdf: 'application/pdf',
jpg: 'image/jpeg',
jpeg: 'image/jpeg',
png: 'image/png',
webp: 'image/webp',
}
/**
* Resolve the response Content-Type. Some legacy uploads landed with
* `mime_type = null` or `application/octet-stream` (browsers sometimes
* report empty File.type for files dragged from certain sources). Combined
* with the new `X-Content-Type-Options: nosniff` header on this route,
* that broke Chrome's PDF viewer for older rows: the plugin would load
* via <object type="application/pdf"> but refuse to parse a response
* served as octet-stream. Falling back to the file extension covers every
* legacy row without a DB backfill.
*/
function resolveContentType(fileName: string, dbMimeType: string | null): string {
if (dbMimeType && dbMimeType !== 'application/octet-stream') return dbMimeType
const ext = fileName.toLowerCase().split('.').pop() ?? ''
return EXTENSION_MIME_MAP[ext] ?? dbMimeType ?? 'application/octet-stream'
}
export const GET = withRouteContext<{ params: Promise<{ id: string }> }>(
'document.inline',
async (_request, { supabase, companyId }, { params }) => {
const { id } = await params
// Authorize via the auth-bound client and the active tenant. RLS remains
// the second layer, while the explicit company filter prevents a document
// from another membership being opened through a guessed identifier.
const { data: doc, error: docError } = await supabase
.from('document_attachments')
.select('id, company_id, file_name, mime_type, storage_path')
.eq('id', id)
.eq('company_id', companyId)
.single()
if (docError || !doc) {
return NextResponse.json({ error: 'Document not found' }, { status: 404 })
}
// Use the service-role client to read from the non-public bucket only after
// the active-company authorization check above has succeeded.
const serviceClient = createServiceClient()
const { data: blob, error: downloadError } = await serviceClient.storage
.from('documents')
.download(doc.storage_path)
if (downloadError || !blob) {
return NextResponse.json(
{ error: `Failed to download document: ${getUserErrorMessage(downloadError) ?? 'unknown error'}` },
{ status: 500 },
)
}
const contentType = resolveContentType(doc.file_name, doc.mime_type)
return new NextResponse(blob, {
status: 200,
headers: {
'Content-Type': contentType,
// RFC 5987 dual form: NFD filenames from macOS/iOS uploads contain
// combining marks (> 0xFF), which undici Headers reject as non-
// ByteString values; splicing the raw name here 500ed the route.
'Content-Disposition': contentDisposition('inline', doc.file_name),
'Cache-Control': 'private, no-store',
// Block MIME sniffing: Content-Type is derived from DB metadata
// (with extension fallback for legacy rows), never from response
// content. Without nosniff a tampered file_name extension could
// serve a stored document under an attacker-chosen MIME type.
'X-Content-Type-Options': 'nosniff',
// Allow-list, not deny-list: anything that is not a natively
// inline-safe type (text/html mail bodies, XHTML, XML, SVG, JSON,
// unknown or legacy types) is uploader-controlled active content
// when rendered on this origin. The sandboxing policy neutralises
// scripts and outbound requests for all of them while the preview
// keeps rendering; see OPAQUE_DOCUMENT_CSP. PDF and raster images
// are exempt because the directive would also break Chrome's
// built-in PDF viewer (it renders through an internal <embed>).
...(inlineSafeMimeType(contentType)
? {}
: { 'Content-Security-Policy': OPAQUE_DOCUMENT_CSP }),
},
})
},
)
@@ -0,0 +1,240 @@
import { describe, it, expect, vi, beforeEach } from 'vitest'
import {
parseJsonResponse,
createMockRouteParams,
createQueuedMockSupabase,
} from '@/tests/helpers'
const { supabase: mockSupabase, enqueue, reset } = createQueuedMockSupabase()
// The route goes through withRouteContext: requireAuth (MFA on hosted) plus
// active-company resolution. The document is still authorized against its
// own company's membership inside the handler.
vi.mock('@/lib/auth/require-auth', () => ({
requireAuth: vi.fn(),
}))
vi.mock('@/lib/company/context', () => ({
getActiveCompanyId: vi.fn().mockResolvedValue('33333333-3333-4333-a333-333333333333'),
}))
// The storage download goes through the service-role client: the storage
// SELECT policy only covers the uploader's own folder, so the user-scoped
// client cannot read colleague-uploaded files within the same company.
const serviceDownloadMock = vi.fn()
const serviceStorageFromMock = vi.fn(() => ({ download: serviceDownloadMock }))
vi.mock('@/lib/supabase/server', () => ({
createClient: () => Promise.resolve(mockSupabase),
createServiceClient: () => ({ storage: { from: serviceStorageFromMock } }),
}))
vi.mock('@/lib/core/documents/document-service', () => ({
validateDocumentMagicBytes: vi.fn(),
}))
import { GET } from '../route'
import { requireAuth } from '@/lib/auth/require-auth'
import { validateDocumentMagicBytes } from '@/lib/core/documents/document-service'
import { NextResponse } from 'next/server'
// v4 UUIDs (variant 'a' / 'b' in the 4th group) so Zod's stricter validators
// accept them: the looser `2222...` style fails on the variant check.
const mockUser = { id: '11111111-1111-4111-a111-111111111111' }
const validDocId = '22222222-2222-4222-a222-222222222222'
const companyId = '33333333-3333-4333-a333-333333333333'
beforeEach(() => {
vi.clearAllMocks()
reset()
vi.mocked(requireAuth).mockResolvedValue({
user: mockUser as never,
supabase: mockSupabase as never,
error: null,
})
})
function req() {
return new Request(`http://localhost/api/documents/${validDocId}/integrity`)
}
describe('GET /api/documents/[id]/integrity', () => {
it('returns 401 when the user is not authenticated', async () => {
vi.mocked(requireAuth).mockResolvedValue({
user: null as never,
supabase: mockSupabase as never,
error: NextResponse.json({ error: 'Unauthorized' }, { status: 401 }),
})
const res = await GET(req(), createMockRouteParams({ id: validDocId }))
const { status } = await parseJsonResponse(res)
expect(status).toBe(401)
expect(serviceStorageFromMock).not.toHaveBeenCalled()
})
it('resolves the session through requireAuth, never a hand-rolled getUser()', async () => {
enqueue({ data: null, error: null })
await GET(req(), createMockRouteParams({ id: validDocId }))
expect(requireAuth).toHaveBeenCalledTimes(1)
expect(mockSupabase.auth.getUser).not.toHaveBeenCalled()
})
it('returns 400 when id is not a UUID', async () => {
const res = await GET(req(), createMockRouteParams({ id: 'not-a-uuid' }))
const { status, body } = await parseJsonResponse<{ error: string }>(res)
expect(status).toBe(400)
expect(body.error).toMatch(/invalid/i)
})
it('returns 404 when document is not found or is superseded', async () => {
enqueue({ data: null, error: null })
const res = await GET(req(), createMockRouteParams({ id: validDocId }))
const { status } = await parseJsonResponse(res)
expect(status).toBe(404)
})
it('returns 404 when caller is not a member of the document company', async () => {
enqueue({
data: {
id: validDocId,
company_id: companyId,
mime_type: 'application/pdf',
storage_path: 'documents/foo/bar.pdf',
},
error: null,
})
enqueue({ data: null, error: null }) // membership check returns null
const res = await GET(req(), createMockRouteParams({ id: validDocId }))
const { status, body } = await parseJsonResponse<{ error: string }>(res)
expect(status).toBe(404)
// The endpoint deliberately returns the same 404 as missing-document so
// the response cannot be used to enumerate documents across companies.
expect(body.error).toBe('Document not found')
})
it('returns { valid: true } and skips download when mime_type is null', async () => {
enqueue({
data: {
id: validDocId,
company_id: companyId,
mime_type: null,
storage_path: 'documents/foo/bar.pdf',
},
error: null,
})
enqueue({ data: { company_id: companyId }, error: null }) // membership
const res = await GET(req(), createMockRouteParams({ id: validDocId }))
const { status, body } = await parseJsonResponse<{ data: { valid: boolean } }>(res)
expect(status).toBe(200)
expect(body.data.valid).toBe(true)
expect(serviceStorageFromMock).not.toHaveBeenCalled()
})
it('returns { valid: true } when the bytes match the declared mime type', async () => {
enqueue({
data: {
id: validDocId,
company_id: companyId,
mime_type: 'application/pdf',
storage_path: 'documents/foo/bar.pdf',
},
error: null,
})
enqueue({ data: { company_id: companyId }, error: null })
const pdfBytes = new Uint8Array([0x25, 0x50, 0x44, 0x46, 0x2d, 0x31, 0x2e, 0x37])
const blob = new Blob([pdfBytes], { type: 'application/pdf' })
serviceDownloadMock.mockResolvedValue({ data: blob, error: null })
vi.mocked(validateDocumentMagicBytes).mockReturnValue(null)
const res = await GET(req(), createMockRouteParams({ id: validDocId }))
const { status, body } = await parseJsonResponse<{ data: { valid: boolean } }>(res)
expect(status).toBe(200)
expect(body.data.valid).toBe(true)
expect(Object.keys(body.data)).toEqual(['valid'])
})
it('returns { valid: false } without leaking the reason text', async () => {
enqueue({
data: {
id: validDocId,
company_id: companyId,
mime_type: 'application/pdf',
storage_path: 'documents/foo/bar.pdf',
},
error: null,
})
enqueue({ data: { company_id: companyId }, error: null })
const blob = new Blob([new Uint8Array([0x00, 0x00, 0x00, 0x00])])
serviceDownloadMock.mockResolvedValue({ data: blob, error: null })
vi.mocked(validateDocumentMagicBytes).mockReturnValue('Internal /storage/v1/object error 42')
const res = await GET(req(), createMockRouteParams({ id: validDocId }))
const { status, body } = await parseJsonResponse<{ data: Record<string, unknown> }>(res)
expect(status).toBe(200)
expect(body.data.valid).toBe(false)
// The whole point of the V1.2.5 / Art 25(2) hardening: internal text
// never appears in the response.
expect(body.data.reason).toBeUndefined()
expect(JSON.stringify(body)).not.toContain('storage/v1/object')
})
it('returns a generic 500 without leaking the underlying storage error', async () => {
enqueue({
data: {
id: validDocId,
company_id: companyId,
mime_type: 'application/pdf',
storage_path: 'documents/foo/bar.pdf',
},
error: null,
})
enqueue({ data: { company_id: companyId }, error: null })
serviceDownloadMock.mockResolvedValue({
data: null,
error: { message: 'storage internal: bucket=documents object=secret/path.pdf' },
})
const res = await GET(req(), createMockRouteParams({ id: validDocId }))
const { status, body } = await parseJsonResponse<{ error: string }>(res)
expect(status).toBe(500)
expect(body.error).toBe('Integrity check unavailable')
expect(JSON.stringify(body)).not.toContain('secret/path.pdf')
})
it('authorizes on the user-scoped client before the service-role download', async () => {
// The storage SELECT policy on the documents bucket only covers the
// uploader's own folder, so the download must use the service-role
// client or colleague-uploaded files 500 for every other company
// member. The compensating control is that both the row fetch and the
// explicit membership check run on the user-scoped client first.
// Source-level check: the queued mock collapses chained calls, so
// runtime introspection cannot distinguish which client ran the fetch.
const fs = await import('node:fs/promises')
const path = await import('node:path')
const routePath = path.resolve(__dirname, '../route.ts')
const source = await fs.readFile(routePath, 'utf8')
const membershipIdx = source.indexOf("from('company_members')")
const downloadIdx = source.indexOf('createServiceClient()')
expect(membershipIdx).toBeGreaterThan(-1)
expect(downloadIdx).toBeGreaterThan(membershipIdx)
})
it('filters the document lookup to the current version', async () => {
// The route's first `from('document_attachments')` chain must include
// `.eq('is_current_version', true)` so superseded versions cannot have
// their bytes probed via this surface. Source-level check rather than
// runtime spying: the proxy-based queued mock collapses every chained
// method into the same handler, so introspecting individual .eq calls
// is not feasible without rebuilding the mock.
const fs = await import('node:fs/promises')
const path = await import('node:path')
const routePath = path.resolve(__dirname, '../route.ts')
const source = await fs.readFile(routePath, 'utf8')
expect(source).toMatch(/\.eq\(['"]is_current_version['"],\s*true\)/)
})
})
+113
View File
@@ -0,0 +1,113 @@
import { NextResponse } from 'next/server'
import { z } from 'zod'
import { withRouteContext } from '@/lib/api/with-route-context'
import { createServiceClient } from '@/lib/supabase/server'
import { validateDocumentMagicBytes } from '@/lib/core/documents/document-service'
const ParamsSchema = z.object({ id: z.string().uuid() })
/**
* GET /api/documents/:id/integrity
*
* Probes the actual stored bytes against the declared MIME type. Used by the
* Bilagor modal to surface a clear "this file is corrupt: please re-upload"
* warning instead of relying on the browser's PDF viewer error UI, which
* only fires after the user has already tried to view the file.
*
* Some legacy MCP uploads landed with non-PDF bytes under
* `mime_type = 'application/pdf'` because magic-byte validation was added
* after those rows were written. This endpoint lets the UI detect and steer
* the user toward replacing them.
*
* Response shape is intentionally minimal: { valid: boolean } only. The
* reason for an invalid result is logged server-side rather than returned
* to the client to avoid information disclosure (V1.2.5 / GDPR Art 25(2))
* and to keep this from being a probe surface for storage internals.
*
* Wrapped in withRouteContext so auth (MFA on hosted), request ids and the
* completion log follow the house pattern. Authorization is still keyed on
* the document's own company (a member may probe a document in any company
* they belong to, same as document_attachments RLS), not on the wrapper's
* active company.
*/
export const GET = withRouteContext<{ params: Promise<{ id: string }> }>(
'document.integrity',
async (_request, { supabase, user, log }, { params }) => {
const rawParams = await params
const parsed = ParamsSchema.safeParse(rawParams)
if (!parsed.success) {
return NextResponse.json({ error: 'Invalid document id' }, { status: 400 })
}
const { id } = parsed.data
// Filter to the current version. The integrity check is meaningful only
// on the live file; superseded versions are archived bytes and should
// not be re-probed (they're already preserved in the version chain
// exactly as uploaded).
const { data: doc, error: docError } = await supabase
.from('document_attachments')
.select('id, company_id, mime_type, storage_path')
.eq('id', id)
.eq('is_current_version', true)
.single()
if (docError || !doc) {
return NextResponse.json({ error: 'Document not found' }, { status: 404 })
}
// Tenant membership: even with the user-scoped supabase client below,
// we want a clear 404 rather than relying on a storage-layer RLS deny
// (which can present as a generic error). RLS on document_attachments
// is the primary control; this is defense in depth.
const { data: membership } = await supabase
.from('company_members')
.select('company_id')
.eq('company_id', doc.company_id)
.eq('user_id', user.id)
.maybeSingle()
if (!membership) {
return NextResponse.json({ error: 'Document not found' }, { status: 404 })
}
if (!doc.mime_type) {
return NextResponse.json({ data: { valid: true } })
}
// Download via the service-role client: the storage SELECT policy only
// covers the uploader's own folder (documents/{uid}/...), so the
// user-scoped client cannot read colleague-uploaded files even within
// the same company. The document_attachments RLS fetch plus the explicit
// membership check above are the authorization (same model as the
// inline proxy route).
const serviceClient = createServiceClient()
const { data: blob, error: downloadError } = await serviceClient.storage
.from('documents')
.download(doc.storage_path)
if (downloadError || !blob) {
log.error('storage download failed for integrity check', downloadError as Error, {
documentId: id,
companyId: doc.company_id,
})
return NextResponse.json({ error: 'Integrity check unavailable' }, { status: 500 })
}
// Only the first 16 bytes are needed for magic-byte detection (PDF/PNG
// use at most 8, WebP needs 12). Trimming here doesn't change bandwidth
// (the full blob is already downloaded) but it makes the intent explicit
// and keeps memory churn off the hot path for large PDFs.
const headerBuffer = await blob.slice(0, 16).arrayBuffer()
const magicError = validateDocumentMagicBytes(headerBuffer, doc.mime_type)
if (magicError) {
log.warn('document failed magic-byte integrity check', {
documentId: id,
companyId: doc.company_id,
reason: magicError,
})
}
return NextResponse.json({ data: { valid: magicError === null } })
},
)
@@ -0,0 +1,214 @@
import { describe, it, expect, vi, beforeEach } from 'vitest'
import { eventBus } from '@/lib/events/bus'
import {
parseJsonResponse,
createMockRouteParams,
createQueuedMockSupabase,
} from '@/tests/helpers'
const { supabase: mockSupabase, enqueue, reset } = createQueuedMockSupabase()
vi.mock('@/lib/supabase/server', () => ({
createClient: () => Promise.resolve(mockSupabase),
}))
vi.mock('@/lib/company/context', () => ({
requireCompanyId: vi.fn().mockResolvedValue('company-1'),
getActiveCompanyId: vi.fn().mockResolvedValue('company-1'),
}))
vi.mock('@/lib/auth/require-write', () => ({
requireWritePermission: vi.fn().mockResolvedValue({ ok: true }),
}))
vi.mock('@/lib/init', () => ({
ensureInitialized: vi.fn(),
}))
import { POST } from '../route'
import { requireWritePermission } from '@/lib/auth/require-write'
import { NextResponse } from 'next/server'
const mockUser = { id: 'user-1', email: 'test@test.se' }
// Body fields are uuid-validated (LinkDocumentSchema): request fixtures must
// be real UUIDs. The enqueue mock rows keep their short ids; the queued mock
// doesn't correlate request input with mocked output.
const JE_ID = '11111111-1111-4111-8111-111111111111'
const OTHER_JE_ID = '22222222-2222-4222-8222-222222222222'
const INBOX_ID = '33333333-3333-4333-8333-333333333333'
const TX_ID = '44444444-4444-4444-8444-444444444444'
beforeEach(() => {
vi.clearAllMocks()
reset()
eventBus.clear()
mockSupabase.auth.getUser.mockResolvedValue({ data: { user: mockUser } })
vi.mocked(requireWritePermission).mockResolvedValue({ ok: true })
})
function makeReq(body: unknown) {
return new Request('http://localhost/api/documents/doc-1/link', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(body),
})
}
describe('POST /api/documents/[id]/link', () => {
it('returns 401 when not authenticated', async () => {
mockSupabase.auth.getUser.mockResolvedValue({ data: { user: null } })
const res = await POST(makeReq({ journal_entry_id: JE_ID }), createMockRouteParams({ id: 'doc-1' }))
const { status } = await parseJsonResponse(res)
expect(status).toBe(401)
})
it('returns 403 when caller has read-only role', async () => {
vi.mocked(requireWritePermission).mockResolvedValue({
ok: false,
response: NextResponse.json(
{ error: 'Du har endast läsbehörighet i detta företag.' },
{ status: 403 },
),
})
const res = await POST(makeReq({ journal_entry_id: JE_ID }), createMockRouteParams({ id: 'doc-1' }))
const { status } = await parseJsonResponse(res)
expect(status).toBe(403)
})
it('rejects a missing journal_entry_id', async () => {
const res = await POST(makeReq({}), createMockRouteParams({ id: 'doc-1' }))
const { body } = await parseJsonResponse<{ error: { code: string } }>(res)
expect(body.error.code).toBe('VALIDATION_ERROR')
})
it('rejects a non-uuid journal_entry_id', async () => {
const res = await POST(
makeReq({ journal_entry_id: 'not-a-uuid' }),
createMockRouteParams({ id: 'doc-1' }),
)
const { status, body } = await parseJsonResponse<{ error: { code: string } }>(res)
expect(status).toBe(400)
expect(body.error.code).toBe('VALIDATION_ERROR')
expect(mockSupabase.from).not.toHaveBeenCalled()
})
it('links the document and stamps the inbox item when inbox_item_id is given', async () => {
enqueue({ data: { id: 'je-1' } }) // journal entry company check
enqueue({ data: { id: 'doc-1', journal_entry_id: 'je-1', file_name: 'x.pdf' } }) // link update
enqueue({ data: null }) // inbox stamp update
const res = await POST(
makeReq({ journal_entry_id: JE_ID, inbox_item_id: INBOX_ID }),
createMockRouteParams({ id: 'doc-1' }),
)
const { status, body } = await parseJsonResponse<{ data: { id: string } }>(res)
expect(status).toBe(200)
expect(body.data.id).toBe('doc-1')
expect(mockSupabase.from).toHaveBeenCalledWith('document_attachments')
expect(mockSupabase.from).toHaveBeenCalledWith('invoice_inbox_items')
})
it('does not touch the inbox when no inbox_item_id is given', async () => {
enqueue({ data: { id: 'je-1' } }) // journal entry company check
enqueue({ data: { id: 'doc-1', journal_entry_id: 'je-1', file_name: 'x.pdf' } }) // link update
const res = await POST(
makeReq({ journal_entry_id: JE_ID }),
createMockRouteParams({ id: 'doc-1' }),
)
const { status } = await parseJsonResponse(res)
expect(status).toBe(200)
expect(mockSupabase.from).not.toHaveBeenCalledWith('invoice_inbox_items')
})
it('pins the document to the transaction when transaction_id is given', async () => {
enqueue({ data: { id: 'je-1' } }) // journal entry company check
enqueue({ data: { id: 'doc-1', journal_entry_id: 'je-1', file_name: 'x.pdf' } }) // link update
enqueue({ data: null }) // transaction pin update
const res = await POST(
makeReq({ journal_entry_id: JE_ID, transaction_id: TX_ID }),
createMockRouteParams({ id: 'doc-1' }),
)
const { status } = await parseJsonResponse(res)
expect(status).toBe(200)
expect(mockSupabase.from).toHaveBeenCalledWith('transactions')
})
it('does not touch transactions when no transaction_id is given', async () => {
enqueue({ data: { id: 'je-1' } }) // journal entry company check
enqueue({ data: { id: 'doc-1', journal_entry_id: 'je-1', file_name: 'x.pdf' } }) // link update
const res = await POST(
makeReq({ journal_entry_id: JE_ID }),
createMockRouteParams({ id: 'doc-1' }),
)
const { status } = await parseJsonResponse(res)
expect(status).toBe(200)
expect(mockSupabase.from).not.toHaveBeenCalledWith('transactions')
})
it('tolerates a failing transaction pin: the JE link is the primary effect', async () => {
enqueue({ data: { id: 'je-1' } }) // journal entry company check
enqueue({ data: { id: 'doc-1', journal_entry_id: 'je-1', file_name: 'x.pdf' } }) // link update
enqueue({ data: null, error: { message: 'rls denied' } }) // transaction pin fails
const res = await POST(
makeReq({ journal_entry_id: JE_ID, transaction_id: TX_ID }),
createMockRouteParams({ id: 'doc-1' }),
)
const { status, body } = await parseJsonResponse<{ data: { id: string } }>(res)
// The pin is row-level UX; its failure must not fail the (compliant) link.
expect(status).toBe(200)
expect(body.data.id).toBe('doc-1')
})
it('maps a period-lock trigger error to PERIOD_LOCKED', async () => {
enqueue({ data: { id: 'je-1' } }) // journal entry company check
enqueue({
data: null,
error: { message: 'new row violates ... locked/closed fiscal period' },
})
const res = await POST(
makeReq({ journal_entry_id: JE_ID, inbox_item_id: INBOX_ID }),
createMockRouteParams({ id: 'doc-1' }),
)
const { body } = await parseJsonResponse<{ error: { code: string } }>(res)
expect(body.error.code).toBe('PERIOD_LOCKED')
// The inbox stamp must not run when the link itself failed.
expect(mockSupabase.from).not.toHaveBeenCalledWith('invoice_inbox_items')
})
it('maps an already-linked error to DOC_LINK_ALREADY_LINKED', async () => {
enqueue({ data: { id: 'je-1' } }) // journal entry company check
enqueue({
data: null,
error: { message: 'document already linked to another entry' },
})
const res = await POST(
makeReq({ journal_entry_id: JE_ID }),
createMockRouteParams({ id: 'doc-1' }),
)
const { body } = await parseJsonResponse<{ error: { code: string } }>(res)
expect(body.error.code).toBe('DOC_LINK_ALREADY_LINKED')
})
it('rejects a journal entry outside the active company with DOC_LINK_ENTRY_NOT_FOUND', async () => {
// The company-scoped lookup finds no row: same result whether the id is
// bogus or belongs to another tenant. The document must never be updated.
enqueue({ data: null }) // journal entry company check → no match
const res = await POST(
makeReq({ journal_entry_id: OTHER_JE_ID }),
createMockRouteParams({ id: 'doc-1' }),
)
const { body } = await parseJsonResponse<{ error: { code: string } }>(res)
expect(body.error.code).toBe('DOC_LINK_ENTRY_NOT_FOUND')
expect(mockSupabase.from).not.toHaveBeenCalledWith('document_attachments')
expect(mockSupabase.from).not.toHaveBeenCalledWith('invoice_inbox_items')
})
})
+134
View File
@@ -0,0 +1,134 @@
import { NextResponse } from 'next/server'
import { ensureInitialized } from '@/lib/init'
import { linkToJournalEntry } from '@/lib/core/documents/document-service'
import { withRouteContext } from '@/lib/api/with-route-context'
import { errorResponseFromCode } from '@/lib/errors/get-structured-error'
import { LinkDocumentSchema } from '@/lib/api/schemas'
import { getErrorMessage as getUserErrorMessage } from '@/lib/errors/get-error-message'
ensureInitialized()
/**
* POST /api/documents/[id]/link: link a document to a journal entry.
*
* Body: { journal_entry_id: string, journal_entry_line_id?: string, inbox_item_id?: string, transaction_id?: string }
*
* When `inbox_item_id` is supplied (the "choose from inbox" flow), the inbox
* item is stamped with the verifikat id after a successful link so it drops out
* of the active inbox into "Bokförda": reusing the inbox's own
* created_journal_entry_id lifecycle. The document link is the legally-relevant
* write and happens first; the inbox stamp is operational housekeeping, so a
* stamp failure is logged but does not fail the request (the doc is correctly
* attached and the DB immutability trigger still blocks any double-link).
*
* When `transaction_id` is supplied (booking-flow callers that link underlag
* right after booking a bank transaction), the doc is also pinned to the
* transaction row (transactions.document_id) so the /transactions list shows
* the underlag indicator. Only set when the tx has no pin yet: first linked
* doc wins, and an existing räkenskapsinformation pin is never swapped (which
* would trip the immutability trigger). Same best-effort posture as the inbox
* stamp: a failure is logged but does not fail the request.
*/
export const POST = withRouteContext(
'document.link',
async (request, ctx, { params }: { params: Promise<{ id: string }> }) => {
const { id } = await params
const { supabase, companyId, log, requestId } = ctx
const opLog = log.child({ documentId: id })
const parsed = LinkDocumentSchema.safeParse(await request.json().catch(() => null))
if (!parsed.success) {
return errorResponseFromCode('VALIDATION_ERROR', opLog, {
requestId,
details: {
issues: parsed.error.issues.map((i) => ({
field: i.path.join('.'),
reason: i.message,
})),
},
})
}
const body = parsed.data
try {
const document = await linkToJournalEntry(
supabase,
companyId!,
id,
body.journal_entry_id,
body.journal_entry_line_id,
)
if (body.inbox_item_id) {
const { data: stamped, error: inboxError } = await supabase
.from('invoice_inbox_items')
.update({ created_journal_entry_id: body.journal_entry_id })
.eq('id', body.inbox_item_id)
.eq('company_id', companyId!)
// Only stamp the inbox item that actually owns this document: a
// mismatched pairing becomes a safe no-op rather than mis-marking an
// unrelated item as consumed.
.eq('document_id', id)
.select('id')
if (inboxError) {
// Non-fatal: the verifikat ↔ underlag link already succeeded.
opLog.warn('inbox item stamp after link failed', {
inboxItemId: body.inbox_item_id,
reason: getUserErrorMessage(inboxError),
})
} else if (!stamped || stamped.length === 0) {
// Zero rows updated means the supplied inbox_item_id / document_id
// pairing did not match (wrong company, wrong document, or a stale
// id). The doc link itself still succeeded; surface the cross-resource
// mismatch as an observable warning rather than silently ignoring it.
opLog.warn('inbox item stamp matched no rows (cross-resource mismatch)', {
inboxItemId: body.inbox_item_id,
})
}
}
if (body.transaction_id) {
const { error: pinError } = await supabase
.from('transactions')
.update({ document_id: id })
.eq('id', body.transaction_id)
.eq('company_id', companyId!)
// Never swap an existing pin: keeps "first linked doc wins" semantics
// for multi-doc bookings and avoids the BFL immutability trigger.
.is('document_id', null)
if (pinError) {
// Non-fatal: the verifikat ↔ underlag link already succeeded; the
// pin is row-level UX on the /transactions list.
opLog.warn('transaction pin after link failed', {
transactionId: body.transaction_id,
reason: getUserErrorMessage(pinError),
})
}
}
return NextResponse.json({ data: document })
} catch (err) {
opLog.error('document link failed', err as Error, {
journalEntryId: body.journal_entry_id,
})
const message = err instanceof Error ? err.message : ''
// Linking writes journal_entry_id on document_attachments; the
// enforce_period_lock trigger blocks that when the target entry sits in a
// closed/locked period.
if (/locked\/closed fiscal period|Bokföringen är låst/i.test(message)) {
return errorResponseFromCode('PERIOD_LOCKED', opLog, { requestId })
}
if (/journal entry not found/i.test(message)) {
return errorResponseFromCode('DOC_LINK_ENTRY_NOT_FOUND', opLog, { requestId })
}
if (/already linked/i.test(message)) {
return errorResponseFromCode('DOC_LINK_ALREADY_LINKED', opLog, { requestId })
}
return errorResponseFromCode('DOC_LINK_FAILED', opLog, {
requestId,
details: { reason: getUserErrorMessage(err) },
})
}
},
{ requireWrite: true },
)
+105
View File
@@ -0,0 +1,105 @@
import { NextResponse } from 'next/server'
import { ensureInitialized } from '@/lib/init'
import { withRouteContext } from '@/lib/api/with-route-context'
import { createServiceClient } from '@/lib/supabase/server'
import { deleteDocument } from '@/lib/core/documents/document-service'
import { eventBus } from '@/lib/events'
import { getErrorMessage as getUserErrorMessage } from '@/lib/errors/get-error-message'
ensureInitialized()
/**
* GET /api/documents/:id
* Fetch document metadata + signed download URL (60 min expiry)
*/
export const GET = withRouteContext<{ params: Promise<{ id: string }> }>(
'document.get',
async (_request, { supabase, companyId, user }, { params }) => {
const { id } = await params
// Fetch document record
const { data: doc, error: docError } = await supabase
.from('document_attachments')
.select('*')
.eq('id', id)
.eq('company_id', companyId)
.single()
if (docError || !doc) {
return NextResponse.json({ error: 'Document not found' }, { status: 404 })
}
// Sign the download URL (60 minutes) and persist the access event in
// parallel: both depend only on the row fetch and are independent of
// each other. The emit stays awaited (event-log-handler's insert must
// not race Vercel function suspension) and never rejects (the bus
// settles handlers via Promise.allSettled), so it cannot fail this
// Promise.all.
//
// Sign with the service-role client: the storage SELECT policy only
// covers the uploader's own folder (documents/{uid}/...), while
// document_attachments rows are company-scoped. Signing with the
// user-bound client fails for every attachment uploaded by another
// member of the same company. The row fetch above (RLS + explicit
// company filter) is the authorization, mirroring the inline proxy
// route.
const serviceClient = createServiceClient()
const [signResult] = await Promise.all([
serviceClient.storage.from('documents').createSignedUrl(doc.storage_path, 3600),
eventBus.emit({
type: 'document.accessed',
payload: {
document: { id: doc.id, file_name: doc.file_name },
userId: user.id,
companyId,
},
}),
])
const { data: signedUrl, error: signError } = signResult
if (signError) {
return NextResponse.json(
{ error: `Failed to create download URL: ${getUserErrorMessage(signError)}` },
{ status: 500 }
)
}
return NextResponse.json({
data: {
...doc,
download_url: signedUrl.signedUrl,
},
})
}
)
/**
* DELETE /api/documents/:id
* Remove an uploaded document. Only permitted when the document is not yet
* linked to a journal entry: once linked, it is räkenskapsinformation under
* BFL 7 kap 2§ and must be retained for 7 years. For linked docs the caller
* should use POST /api/documents/:id/versions to supersede via a new version.
*/
export const DELETE = withRouteContext<{ params: Promise<{ id: string }> }>(
'document.delete',
async (_request, { supabase, companyId }, { params }) => {
const { id } = await params
try {
const result = await deleteDocument(supabase, companyId, id)
if (!result.ok) {
return NextResponse.json({ error: result.message }, { status: result.status })
}
return NextResponse.json({ data: { id: result.document.id, deleted: true } })
} catch (error) {
console.error('[documents/DELETE] Failed to delete document:', error)
return NextResponse.json(
{ error: error instanceof Error ? getUserErrorMessage(error) : 'Failed to delete document' },
{ status: 500 }
)
}
},
{ requireWrite: true }
)
@@ -0,0 +1,82 @@
import { describe, it, expect, vi, beforeEach } from 'vitest'
import { NextResponse } from 'next/server'
import {
parseJsonResponse,
createMockRouteParams,
createQueuedMockSupabase,
} from '@/tests/helpers'
const { supabase: mockSupabase, reset } = createQueuedMockSupabase()
const requireAuthMock = vi.fn()
vi.mock('@/lib/auth/require-auth', () => ({
requireAuth: (...args: unknown[]) => requireAuthMock(...args),
}))
vi.mock('@/lib/company/context', () => ({
requireCompanyId: vi.fn().mockResolvedValue('company-1'),
getActiveCompanyId: vi.fn().mockResolvedValue('company-1'),
}))
vi.mock('@/lib/auth/require-write', () => ({
requireWritePermission: vi.fn().mockResolvedValue({ ok: true }),
}))
vi.mock('@/lib/init', () => ({ ensureInitialized: vi.fn() }))
const mockVerifyIntegrity = vi.fn()
vi.mock('@/lib/core/documents/document-service', () => ({
verifyIntegrity: (...args: unknown[]) => mockVerifyIntegrity(...args),
}))
import { POST } from '../route'
import { requireWritePermission } from '@/lib/auth/require-write'
const mockUser = { id: 'user-1', email: 'test@test.se' }
function makeReq() {
return new Request('http://localhost/api/documents/doc-1/verify', { method: 'POST' })
}
beforeEach(() => {
vi.clearAllMocks()
reset()
requireAuthMock.mockResolvedValue({ user: mockUser, supabase: mockSupabase, error: null })
vi.mocked(requireWritePermission).mockResolvedValue({ ok: true })
})
describe('POST /api/documents/[id]/verify', () => {
it('returns 401 when not authenticated', async () => {
requireAuthMock.mockResolvedValue({
user: null,
supabase: mockSupabase,
error: NextResponse.json({ error: 'Unauthorized' }, { status: 401 }),
})
const res = await POST(makeReq(), createMockRouteParams({ id: 'doc-1' }))
const { status } = await parseJsonResponse(res)
expect(status).toBe(401)
})
it('returns 403 when caller has read-only role', async () => {
vi.mocked(requireWritePermission).mockResolvedValue({
ok: false,
response: NextResponse.json(
{ error: 'Du har endast läsbehörighet i detta företag.' },
{ status: 403 },
),
})
const res = await POST(makeReq(), createMockRouteParams({ id: 'doc-1' }))
const { status } = await parseJsonResponse(res)
expect(status).toBe(403)
expect(mockVerifyIntegrity).not.toHaveBeenCalled()
})
it('returns the integrity result on success', async () => {
mockVerifyIntegrity.mockResolvedValue({ verified: true, hash_matches: true })
const res = await POST(makeReq(), createMockRouteParams({ id: 'doc-1' }))
const { status, body } = await parseJsonResponse<{ data: { verified: boolean } }>(res)
expect(status).toBe(200)
expect(body.data.verified).toBe(true)
expect(mockVerifyIntegrity).toHaveBeenCalledWith(mockSupabase, 'company-1', 'doc-1')
})
})
+31
View File
@@ -0,0 +1,31 @@
import { NextResponse } from 'next/server'
import { ensureInitialized } from '@/lib/init'
import { withRouteContext } from '@/lib/api/with-route-context'
import { verifyIntegrity } from '@/lib/core/documents/document-service'
import { getErrorMessage as getUserErrorMessage } from '@/lib/errors/get-error-message'
ensureInitialized()
/**
* POST /api/documents/:id/verify
* Verify document integrity by re-computing SHA-256 and comparing
*/
export const POST = withRouteContext<{ params: Promise<{ id: string }> }>(
'document.verify',
async (_request, { supabase, companyId }, { params }) => {
const { id } = await params
try {
const result = await verifyIntegrity(supabase, companyId, id)
return NextResponse.json({ data: result })
} catch (error) {
console.error('[documents/verify/POST] Verification failed:', error)
return NextResponse.json(
{ error: error instanceof Error ? getUserErrorMessage(error) : 'Verification failed' },
{ status: 500 }
)
}
},
{ requireWrite: true }
)
@@ -0,0 +1,104 @@
import { describe, it, expect, vi, beforeEach } from 'vitest'
import { NextResponse } from 'next/server'
import {
parseJsonResponse,
createMockRouteParams,
createQueuedMockSupabase,
} from '@/tests/helpers'
const { supabase: mockSupabase, reset } = createQueuedMockSupabase()
const requireAuthMock = vi.fn()
vi.mock('@/lib/auth/require-auth', () => ({
requireAuth: (...args: unknown[]) => requireAuthMock(...args),
}))
vi.mock('@/lib/company/context', () => ({
requireCompanyId: vi.fn().mockResolvedValue('company-1'),
getActiveCompanyId: vi.fn().mockResolvedValue('company-1'),
}))
vi.mock('@/lib/auth/require-write', () => ({
requireWritePermission: vi.fn().mockResolvedValue({ ok: true }),
}))
vi.mock('@/lib/init', () => ({ ensureInitialized: vi.fn() }))
const mockCreateNewVersion = vi.fn()
const mockValidateDocumentFile = vi.fn()
vi.mock('@/lib/core/documents/document-service', () => ({
createNewVersion: (...args: unknown[]) => mockCreateNewVersion(...args),
validateDocumentFile: (...args: unknown[]) => mockValidateDocumentFile(...args),
}))
import { POST } from '../route'
import { requireWritePermission } from '@/lib/auth/require-write'
const mockUser = { id: 'user-1', email: 'test@test.se' }
function makeReq(withFile = true) {
const form = new FormData()
if (withFile) {
form.append('file', new File(['content'], 'kvitto.pdf', { type: 'application/pdf' }))
}
return new Request('http://localhost/api/documents/doc-1/versions', {
method: 'POST',
body: form,
})
}
beforeEach(() => {
vi.clearAllMocks()
reset()
requireAuthMock.mockResolvedValue({ user: mockUser, supabase: mockSupabase, error: null })
vi.mocked(requireWritePermission).mockResolvedValue({ ok: true })
mockValidateDocumentFile.mockReturnValue(null)
})
describe('POST /api/documents/[id]/versions', () => {
it('returns 401 when not authenticated', async () => {
requireAuthMock.mockResolvedValue({
user: null,
supabase: mockSupabase,
error: NextResponse.json({ error: 'Unauthorized' }, { status: 401 }),
})
const res = await POST(makeReq(), createMockRouteParams({ id: 'doc-1' }))
const { status } = await parseJsonResponse(res)
expect(status).toBe(401)
})
it('returns 403 when caller has read-only role', async () => {
vi.mocked(requireWritePermission).mockResolvedValue({
ok: false,
response: NextResponse.json(
{ error: 'Du har endast läsbehörighet i detta företag.' },
{ status: 403 },
),
})
const res = await POST(makeReq(), createMockRouteParams({ id: 'doc-1' }))
const { status } = await parseJsonResponse(res)
expect(status).toBe(403)
expect(mockCreateNewVersion).not.toHaveBeenCalled()
})
it('returns 400 when no file is provided', async () => {
const res = await POST(makeReq(false), createMockRouteParams({ id: 'doc-1' }))
const { status, body } = await parseJsonResponse<{ error: string }>(res)
expect(status).toBe(400)
expect(body.error).toBe('No file provided')
})
it('creates a new version on the happy path', async () => {
mockCreateNewVersion.mockResolvedValue({ id: 'doc-2', version: 2 })
const res = await POST(makeReq(), createMockRouteParams({ id: 'doc-1' }))
const { status, body } = await parseJsonResponse<{ data: { id: string; version: number } }>(res)
expect(status).toBe(200)
expect(body.data).toEqual({ id: 'doc-2', version: 2 })
expect(mockCreateNewVersion).toHaveBeenCalledWith(
mockSupabase,
'user-1',
'doc-1',
expect.objectContaining({ name: 'kvitto.pdf', type: 'application/pdf' }),
)
})
})
+92
View File
@@ -0,0 +1,92 @@
import { NextResponse } from 'next/server'
import { ensureInitialized } from '@/lib/init'
import { withRouteContext } from '@/lib/api/with-route-context'
import { createNewVersion, validateDocumentFile } from '@/lib/core/documents/document-service'
import { getErrorMessage as getUserErrorMessage } from '@/lib/errors/get-error-message'
ensureInitialized()
/**
* POST /api/documents/:id/versions
* Create a new version of an existing document (atomic via RPC)
*
* Accepts multipart/form-data with:
* - file: The new version file
*/
export const POST = withRouteContext<{ params: Promise<{ id: string }> }>(
'document.versions.create',
async (request, { supabase, user }, { params }) => {
const { id } = await params
try {
const formData = await request.formData()
const file = formData.get('file') as File | null
if (!file) {
return NextResponse.json({ error: 'No file provided' }, { status: 400 })
}
const validationError = validateDocumentFile({ size: file.size, type: file.type })
if (validationError) {
return NextResponse.json({ error: validationError }, { status: 400 })
}
const buffer = await file.arrayBuffer()
const newVersion = await createNewVersion(supabase, user.id, id, {
name: file.name,
buffer,
type: file.type,
})
return NextResponse.json({ data: newVersion })
} catch (error) {
console.error('[documents/versions/POST] Version creation failed:', error)
return NextResponse.json(
{ error: error instanceof Error ? getUserErrorMessage(error) : 'Version creation failed' },
{ status: 500 }
)
}
},
{ requireWrite: true }
)
/**
* GET /api/documents/:id/versions
* List all versions in the document chain
*/
export const GET = withRouteContext<{ params: Promise<{ id: string }> }>(
'document.versions.list',
async (_request, { supabase, companyId }, { params }) => {
const { id } = await params
// First, check if the document belongs to the company
const { data: doc, error: docError } = await supabase
.from('document_attachments')
.select('id, original_id')
.eq('id', id)
.eq('company_id', companyId)
.single()
if (docError || !doc) {
return NextResponse.json({ error: 'Document not found' }, { status: 404 })
}
// The root document is either the original_id or the document itself
const rootId = doc.original_id || doc.id
// Fetch all versions in the chain
const { data: versions, error: versionsError } = await supabase
.from('document_attachments')
.select('*')
.eq('company_id', companyId)
.or(`id.eq.${rootId},original_id.eq.${rootId}`)
.order('version', { ascending: true })
if (versionsError) {
return NextResponse.json({ error: getUserErrorMessage(versionsError) }, { status: 500 })
}
return NextResponse.json({ data: versions })
}
)
@@ -0,0 +1,240 @@
import { describe, it, expect, vi, beforeEach } from 'vitest'
import { parseJsonResponse, createQueuedMockSupabase } from '@/tests/helpers'
import { NextResponse } from 'next/server'
const { supabase: mockSupabase, enqueue, reset } = createQueuedMockSupabase()
vi.mock('@/lib/auth/require-auth', () => ({ requireAuth: vi.fn() }))
vi.mock('@/lib/company/context', () => ({ getActiveCompanyId: vi.fn() }))
import { GET } from '../route'
import { requireAuth } from '@/lib/auth/require-auth'
import { getActiveCompanyId } from '@/lib/company/context'
const mockUser = { id: 'user-1', email: 't@t.se' }
const JE_A = 'aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa'
const JE_B = 'bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb'
const JE_C = 'cccccccc-cccc-4ccc-8ccc-cccccccccccc'
function makeReq(ids: string[]) {
return new Request(
`http://localhost/api/documents/counts?journal_entry_ids=${ids.join(',')}`,
)
}
beforeEach(() => {
vi.clearAllMocks()
reset()
;(requireAuth as ReturnType<typeof vi.fn>).mockResolvedValue({
user: mockUser,
supabase: mockSupabase,
})
;(getActiveCompanyId as ReturnType<typeof vi.fn>).mockResolvedValue('company-1')
})
// Queue order mirrors the route: the Promise.all (direct docs, supplier_invoices
// references, supplier_invoice_payments references), then the customer-invoice
// resolver (invoices by journal_entry_id, invoice_payments by journal_entry_id).
// The `document` embed carries the anchor state (journal_entry_id) of the SI's
// retained doc.
function enqueueAll(opts: {
direct?: Array<{ id: string; journal_entry_id: string }>
si?: Array<{
document_id: string
registration_journal_entry_id: string | null
payment_journal_entry_id: string | null
document: { journal_entry_id: string | null } | null
}>
sip?: Array<{
journal_entry_id: string
supplier_invoice: {
document_id: string | null
document: { journal_entry_id: string | null } | null
} | null
}>
invoices?: Array<{ id: string; journal_entry_id: string | null }>
payments?: Array<{ id: string; invoice_id: string | null; journal_entry_id: string | null }>
}) {
enqueue({ data: opts.direct ?? [], error: null })
enqueue({ data: opts.si ?? [], error: null })
enqueue({ data: opts.sip ?? [], error: null })
enqueue({ data: opts.invoices ?? [], error: null })
enqueue({ data: opts.payments ?? [], error: null })
}
describe('GET /api/documents/counts', () => {
it('returns 401 when not authenticated', async () => {
;(requireAuth as ReturnType<typeof vi.fn>).mockResolvedValue({
error: NextResponse.json({ error: 'Unauthorized' }, { status: 401 }),
})
const res = await GET(makeReq([JE_A]))
expect((await parseJsonResponse(res)).status).toBe(401)
})
it('returns 400 without journal_entry_ids', async () => {
const res = await GET(new Request('http://localhost/api/documents/counts'))
expect((await parseJsonResponse(res)).status).toBe(400)
})
it('returns 400 for more than 50 ids', async () => {
const ids = Array.from({ length: 51 }, (_, i) => `id-${i}`)
const res = await GET(makeReq(ids))
expect((await parseJsonResponse(res)).status).toBe(400)
})
it('returns 400 for non-UUID ids (they are interpolated into a PostgREST or-filter)', async () => {
const res = await GET(makeReq([JE_A, 'registration_journal_entry_id.in.(x)']))
expect((await parseJsonResponse(res)).status).toBe(400)
})
it('counts direct attachments per entry', async () => {
enqueueAll({
direct: [
{ id: 'doc-1', journal_entry_id: JE_A },
{ id: 'doc-2', journal_entry_id: JE_A },
{ id: 'doc-3', journal_entry_id: JE_B },
],
})
const res = await GET(makeReq([JE_A, JE_B, JE_C]))
const { status, body } = await parseJsonResponse<{ data: Record<string, number> }>(res)
expect(status).toBe(200)
expect(body.data).toEqual({ [JE_A]: 2, [JE_B]: 1 })
})
it('counts a supplier invoice doc for both referenced entries (registration + payment)', async () => {
enqueueAll({
si: [
{
document_id: 'doc-si',
registration_journal_entry_id: JE_A,
payment_journal_entry_id: JE_B,
document: { journal_entry_id: JE_A },
},
],
})
const res = await GET(makeReq([JE_A, JE_B]))
const { body } = await parseJsonResponse<{ data: Record<string, number> }>(res)
expect(body.data).toEqual({ [JE_A]: 1, [JE_B]: 1 })
})
it('ignores an UNANCHORED supplier invoice doc (outside the WORM deletion guards)', async () => {
enqueueAll({
si: [
{
document_id: 'doc-si',
registration_journal_entry_id: JE_A,
payment_journal_entry_id: JE_B,
document: { journal_entry_id: null },
},
],
sip: [
{
journal_entry_id: JE_C,
supplier_invoice: { document_id: 'doc-si', document: { journal_entry_id: null } },
},
],
})
const res = await GET(makeReq([JE_A, JE_B, JE_C]))
const { body } = await parseJsonResponse<{ data: Record<string, number> }>(res)
expect(body.data).toEqual({})
})
it('counts a partial-payment reference via supplier_invoice_payments', async () => {
enqueueAll({
sip: [
{
journal_entry_id: JE_A,
supplier_invoice: { document_id: 'doc-si', document: { journal_entry_id: JE_B } },
},
],
})
const res = await GET(makeReq([JE_A]))
const { body } = await parseJsonResponse<{ data: Record<string, number> }>(res)
expect(body.data).toEqual({ [JE_A]: 1 })
})
it('deduplicates a doc that is both directly linked and referenced', async () => {
enqueueAll({
direct: [{ id: 'doc-si', journal_entry_id: JE_A }],
si: [
{
document_id: 'doc-si',
registration_journal_entry_id: JE_A,
payment_journal_entry_id: null,
document: { journal_entry_id: JE_A },
},
],
})
const res = await GET(makeReq([JE_A]))
const { body } = await parseJsonResponse<{ data: Record<string, number> }>(res)
expect(body.data).toEqual({ [JE_A]: 1 })
})
it('never returns entries the caller did not ask about', async () => {
enqueueAll({
si: [
{
document_id: 'doc-si',
// The SI's other FK points at an entry outside the request.
registration_journal_entry_id: JE_C,
payment_journal_entry_id: JE_A,
document: { journal_entry_id: JE_C },
},
],
})
const res = await GET(makeReq([JE_A]))
const { body } = await parseJsonResponse<{ data: Record<string, number> }>(res)
expect(body.data).toEqual({ [JE_A]: 1 })
expect(body.data[JE_C]).toBeUndefined()
})
it('returns 500 when a lookup fails', async () => {
enqueue({ data: null, error: { message: 'boom' } })
enqueue({ data: [], error: null })
enqueue({ data: [], error: null })
const res = await GET(makeReq([JE_A]))
expect((await parseJsonResponse(res)).status).toBe(500)
})
it('reports customer invoices pointing at an entry apart from document counts (#2298)', async () => {
// JE_A: the invoice register links it directly AND a payment row points
// at it (one invoice counted once, plus a second invoice via payment).
// JE_B: only a payment row (a SIE-imported voucher matched to an invoice).
// JE_C: nothing. No document anywhere: `data` stays empty.
enqueueAll({
invoices: [{ id: 'inv-1', journal_entry_id: JE_A }],
payments: [
{ id: 'pay-1', invoice_id: 'inv-1', journal_entry_id: JE_A },
{ id: 'pay-2', invoice_id: 'inv-2', journal_entry_id: JE_A },
{ id: 'pay-3', invoice_id: 'inv-3', journal_entry_id: JE_B },
],
})
const res = await GET(makeReq([JE_A, JE_B, JE_C]), { params: Promise.resolve({}) })
const { status, body } = await parseJsonResponse<{
data: Record<string, number>
invoice_references: Record<string, number>
}>(res)
expect(status).toBe(200)
expect(body.data).toEqual({})
expect(body.invoice_references).toEqual({ [JE_A]: 2, [JE_B]: 1 })
})
it('never returns invoice references for entries the caller did not ask about', async () => {
enqueueAll({
payments: [{ id: 'pay-1', invoice_id: 'inv-1', journal_entry_id: JE_C }],
})
const res = await GET(makeReq([JE_A]), { params: Promise.resolve({}) })
const { body } = await parseJsonResponse<{ invoice_references: Record<string, number> }>(res)
expect(body.invoice_references).toEqual({})
})
it('returns 500 when the invoice-reference lookup fails', async () => {
enqueue({ data: [], error: null })
enqueue({ data: [], error: null })
enqueue({ data: [], error: null })
enqueue({ data: null, error: { message: 'boom' } }) // invoices by journal_entry_id
const res = await GET(makeReq([JE_A]), { params: Promise.resolve({}) })
expect((await parseJsonResponse(res)).status).toBe(500)
})
})
+157
View File
@@ -0,0 +1,157 @@
import { NextResponse } from 'next/server'
import { z } from 'zod'
import { withRouteContext } from '@/lib/api/with-route-context'
import { getErrorMessage as getUserErrorMessage } from '@/lib/errors/get-error-message'
import { getInvoiceReferencesForJournalEntries } from '@/lib/core/bookkeeping/journal-entry-references'
const uuidSchema = z.string().uuid()
/**
* GET /api/documents/counts?journal_entry_ids=id1,id2,...
* Returns underlag counts per journal entry ID.
* Max 50 IDs per request; every ID must be a UUID (the ids are interpolated
* into a PostgREST .or() filter string, so validation doubles as injection
* protection).
*
* `data` counts BOTH direct attachments (document_attachments.journal_entry_id)
* and documents retained on a supplier invoice that references the entry
* (registration/payment FK or a supplier_invoice_payments row). BFL 5 kap 7 §
* accepts underlag via hänvisning, and the expanded-row view
* (JournalEntryAttachments) already lists referenced docs: counting only
* direct links here made the list warning disagree with the opened row.
* A referenced doc counts only when ANCHORED to a journal entry
* (journal_entry_id set): unanchored docs sit outside the WORM deletion
* guards, so they must not silence the missing-underlag warning (mirrors the
* verifikat_without_documents RPC). Documents are deduplicated per entry so a
* doc that is both directly linked and referenced counts once.
*
* `invoice_references` counts, per requested entry, the customer invoices
* that point at it (invoices.journal_entry_id or an invoice_payments row):
* the customer-side hänvisning (#2298). Kept apart from `data` because a
* register invoice is not a document row: the list must not offer a
* paperclip with nothing behind it, but it must stop warning "Underlag
* saknas" for an entry the verifikat page already lists an invoice on.
* Same verdict as the RPC's customer arm and the verifikat detail page.
*/
export const GET = withRouteContext('document.counts', async (request, ctx) => {
const { supabase, companyId } = ctx
const { searchParams } = new URL(request.url)
const idsParam = searchParams.get('journal_entry_ids')
if (!idsParam) {
return NextResponse.json({ error: 'journal_entry_ids is required' }, { status: 400 })
}
const ids = idsParam.split(',').filter(Boolean)
if (ids.length === 0) {
return NextResponse.json({ data: {} })
}
if (ids.length > 50) {
return NextResponse.json({ error: 'Maximum 50 IDs per request' }, { status: 400 })
}
if (ids.some((id) => !uuidSchema.safeParse(id).success)) {
return NextResponse.json(
{ error: 'journal_entry_ids must be UUIDs' },
{ status: 400 },
)
}
const inList = `(${ids.join(',')})`
const [directRes, siRes, sipRes] = await Promise.all([
supabase
.from('document_attachments')
.select('id, journal_entry_id')
.eq('company_id', companyId)
.eq('is_current_version', true)
.in('journal_entry_id', ids),
supabase
.from('supplier_invoices')
.select(
'document_id, registration_journal_entry_id, payment_journal_entry_id, document:document_attachments(journal_entry_id)',
)
.eq('company_id', companyId)
.not('document_id', 'is', null)
.or(
`registration_journal_entry_id.in.${inList},payment_journal_entry_id.in.${inList}`,
),
supabase
.from('supplier_invoice_payments')
.select(
'journal_entry_id, supplier_invoice:supplier_invoices(document_id, document:document_attachments(journal_entry_id))',
)
.eq('company_id', companyId)
.in('journal_entry_id', ids),
])
if (directRes.error) {
return NextResponse.json({ error: getUserErrorMessage(directRes.error) }, { status: 500 })
}
if (siRes.error) {
return NextResponse.json({ error: getUserErrorMessage(siRes.error) }, { status: 500 })
}
if (sipRes.error) {
return NextResponse.json({ error: getUserErrorMessage(sipRes.error) }, { status: 500 })
}
// Distinct doc ids per entry: a supplier invoice's document referenced from
// both FK paths, or already directly linked, must not double count.
const docsByEntry = new Map<string, Set<string>>()
const add = (journalEntryId: string | null | undefined, documentId: string | null | undefined) => {
if (!journalEntryId || !documentId) return
let set = docsByEntry.get(journalEntryId)
if (!set) {
set = new Set<string>()
docsByEntry.set(journalEntryId, set)
}
set.add(documentId)
}
for (const row of (directRes.data ?? []) as { id: string; journal_entry_id: string | null }[]) {
add(row.journal_entry_id, row.id)
}
for (const row of (siRes.data ?? []) as unknown as {
document_id: string | null
registration_journal_entry_id: string | null
payment_journal_entry_id: string | null
document: { journal_entry_id: string | null } | null
}[]) {
if (!row.document?.journal_entry_id) continue // unanchored: not underlag
add(row.registration_journal_entry_id, row.document_id)
add(row.payment_journal_entry_id, row.document_id)
}
for (const row of (sipRes.data ?? []) as unknown as {
journal_entry_id: string | null
supplier_invoice: {
document_id: string | null
document: { journal_entry_id: string | null } | null
} | null
}[]) {
if (!row.supplier_invoice?.document?.journal_entry_id) continue // unanchored
add(row.journal_entry_id, row.supplier_invoice.document_id)
}
let invoiceRefs: Map<string, string[]>
try {
invoiceRefs = await getInvoiceReferencesForJournalEntries(supabase, companyId, ids)
} catch (err) {
return NextResponse.json({ error: getUserErrorMessage(err) }, { status: 500 })
}
// Referenced entries outside the requested set (an SI FK can point at an
// entry the caller didn't ask about) must not leak into the response.
const requested = new Set(ids)
const counts: Record<string, number> = {}
for (const [journalEntryId, docIds] of docsByEntry) {
if (requested.has(journalEntryId)) counts[journalEntryId] = docIds.size
}
const invoiceReferences: Record<string, number> = {}
for (const [journalEntryId, invoiceIds] of invoiceRefs) {
if (requested.has(journalEntryId)) invoiceReferences[journalEntryId] = invoiceIds.length
}
return NextResponse.json({ data: counts, invoice_references: invoiceReferences })
})
@@ -0,0 +1,127 @@
import { describe, it, expect, vi, beforeEach } from 'vitest'
import { eventBus } from '@/lib/events/bus'
import {
parseJsonResponse,
createMockRouteParams,
createQueuedMockSupabase,
} from '@/tests/helpers'
const { supabase: mockSupabase, enqueue, reset } = createQueuedMockSupabase()
vi.mock('@/lib/supabase/server', () => ({
createClient: () => Promise.resolve(mockSupabase),
}))
vi.mock('@/lib/company/context', () => ({
requireCompanyId: vi.fn().mockResolvedValue('company-1'),
getActiveCompanyId: vi.fn().mockResolvedValue('company-1'),
}))
vi.mock('@/lib/auth/require-write', () => ({
requireWritePermission: vi.fn().mockResolvedValue({ ok: true }),
}))
vi.mock('@/lib/init', () => ({
ensureInitialized: vi.fn(),
}))
import { GET } from '../route'
const mockUser = { id: 'user-1', email: 'test@test.se' }
beforeEach(() => {
vi.clearAllMocks()
reset()
eventBus.clear()
mockSupabase.auth.getUser.mockResolvedValue({ data: { user: mockUser } })
})
function makeReq() {
return new Request('http://localhost/api/documents/inbox-available')
}
describe('GET /api/documents/inbox-available', () => {
it('returns 401 when not authenticated', async () => {
mockSupabase.auth.getUser.mockResolvedValue({ data: { user: null } })
const res = await GET(makeReq(), createMockRouteParams({}))
const { status } = await parseJsonResponse(res)
expect(status).toBe(401)
})
it('returns [] when no eligible inbox items (no second query)', async () => {
enqueue({ data: [] }) // inbox items
const res = await GET(makeReq(), createMockRouteParams({}))
const { status, body } = await parseJsonResponse<{ data: unknown[] }>(res)
expect(status).toBe(200)
expect(body.data).toEqual([])
// Documents table never queried when there are no document ids.
expect(mockSupabase.from).not.toHaveBeenCalledWith('document_attachments')
})
it('joins inbox items to their documents and drops consumed/superseded ones', async () => {
enqueue({
data: [
{
id: 'inbox-1',
document_id: 'doc-1',
source: 'email',
created_at: '2026-05-01T00:00:00Z',
extracted_data: {
supplier: { name: 'Acme AB' },
totals: { total: 1250 },
invoice: { currency: 'SEK', invoiceDate: '2026-04-28' },
},
},
// doc-2's document is no longer current/unlinked → must be dropped.
{
id: 'inbox-2',
document_id: 'doc-2',
source: 'upload',
created_at: '2026-05-02T00:00:00Z',
extracted_data: null,
},
],
})
enqueue({
data: [
{
id: 'doc-1',
file_name: 'acme.pdf',
mime_type: 'application/pdf',
file_size_bytes: 1000,
journal_entry_id: null,
is_current_version: true,
},
],
})
const res = await GET(makeReq(), createMockRouteParams({}))
const { status, body } = await parseJsonResponse<{
data: Array<Record<string, unknown>>
}>(res)
expect(status).toBe(200)
expect(body.data).toHaveLength(1)
expect(body.data[0]).toEqual({
inbox_item_id: 'inbox-1',
document_id: 'doc-1',
file_name: 'acme.pdf',
mime_type: 'application/pdf',
file_size_bytes: 1000,
source: 'email',
created_at: '2026-05-01T00:00:00Z',
supplier_name: 'Acme AB',
amount: 1250,
currency: 'SEK',
invoice_date: '2026-04-28',
})
expect(mockSupabase.from).toHaveBeenCalledWith('invoice_inbox_items')
expect(mockSupabase.from).toHaveBeenCalledWith('document_attachments')
})
it('returns an error envelope when the inbox query fails', async () => {
enqueue({ data: null, error: { message: 'boom' } })
const res = await GET(makeReq(), createMockRouteParams({}))
const { status } = await parseJsonResponse(res)
expect(status).toBeGreaterThanOrEqual(500)
})
})
+114
View File
@@ -0,0 +1,114 @@
import { NextResponse } from 'next/server'
import { ensureInitialized } from '@/lib/init'
import { withRouteContext } from '@/lib/api/with-route-context'
import { errorResponse } from '@/lib/errors/get-structured-error'
import type { InvoiceExtractionResult } from '@/types'
ensureInitialized()
/**
* GET /api/documents/inbox-available: list invoice-inbox documents that are
* available to attach as underlag to a verifikat.
*
* Returns only *unconsumed* inbox items: those that have a file but have not
* yet become a supplier invoice, a direct journal entry, or been matched to a
* bank transaction, and whose underlying document is not already linked to a
* verifikation. This mirrors the inbox's own "Att göra" set, narrowed to items
* with an attachable file. Re-pointing an already-linked document is forbidden
* (BFL 7 kap: räkenskapsinformation is immutable), so those are excluded here
* and the DB immutability trigger is the backstop.
*
* `invoice_inbox_items` is a core table, so a core route may read it directly
* without importing from @/extensions. When the invoice-inbox extension is not
* in use the table is simply empty and this returns [].
*/
interface InboxRow {
id: string
document_id: string | null
source: string | null
created_at: string
extracted_data: InvoiceExtractionResult | null
}
interface DocRow {
id: string
file_name: string
mime_type: string | null
file_size_bytes: number
journal_entry_id: string | null
is_current_version: boolean
}
export const GET = withRouteContext('document.inbox_available', async (_request, ctx) => {
const { supabase, companyId, log, requestId } = ctx
// 1) Eligible inbox items: company-scoped (defense in depth alongside RLS),
// unconsumed, with a document.
const { data: inboxRows, error: inboxError } = await supabase
.from('invoice_inbox_items')
.select('id, document_id, source, created_at, extracted_data')
.eq('company_id', companyId)
.not('document_id', 'is', null)
.is('created_supplier_invoice_id', null)
.is('created_journal_entry_id', null)
.is('matched_transaction_id', null)
.order('created_at', { ascending: false })
.limit(100)
if (inboxError) {
log.error('inbox-available item query failed', inboxError)
return errorResponse(inboxError, log, { requestId })
}
const rows = (inboxRows ?? []) as InboxRow[]
const docIds = rows.map((r) => r.document_id).filter((id): id is string => !!id)
if (docIds.length === 0) {
return NextResponse.json({ data: [] })
}
// 2) The current, still-unlinked documents behind those items. Excluding
// docs with a journal_entry_id (already underlag elsewhere) and superseded
// versions keeps the picker honest even if an inbox column went stale.
const { data: docRows, error: docError } = await supabase
.from('document_attachments')
.select('id, file_name, mime_type, file_size_bytes, journal_entry_id, is_current_version')
.eq('company_id', companyId)
.in('id', docIds)
.is('journal_entry_id', null)
.eq('is_current_version', true)
if (docError) {
log.error('inbox-available document query failed', docError)
return errorResponse(docError, log, { requestId })
}
const docById = new Map<string, DocRow>()
for (const d of (docRows ?? []) as DocRow[]) docById.set(d.id, d)
// Preserve the inbox ordering (newest first); drop items whose document is
// gone, consumed, or superseded.
const data = rows
.map((row) => {
const doc = row.document_id ? docById.get(row.document_id) : undefined
if (!doc) return null
const ex = row.extracted_data
return {
inbox_item_id: row.id,
document_id: doc.id,
file_name: doc.file_name,
mime_type: doc.mime_type,
file_size_bytes: doc.file_size_bytes,
source: row.source,
created_at: row.created_at,
supplier_name: ex?.supplier?.name ?? null,
amount: ex?.totals?.total ?? null,
currency: ex?.invoice?.currency ?? 'SEK',
invoice_date: ex?.invoice?.invoiceDate ?? null,
}
})
.filter((x): x is NonNullable<typeof x> => x !== null)
return NextResponse.json({ data })
})
@@ -0,0 +1,60 @@
import { describe, it, expect, vi, beforeEach } from 'vitest'
const verifyCronSecret = vi.fn<() => unknown>(() => null)
vi.mock('@/lib/auth/cron', () => ({
verifyCronSecret: () => verifyCronSecret(),
}))
vi.mock('@/lib/supabase/service-client', () => ({
createServiceRoleClient: vi.fn(() => ({ mocked: true })),
}))
const sweepFloatingSupplierInvoiceDocuments = vi.fn()
vi.mock('@/lib/core/documents/supplier-invoice-underlag', () => ({
sweepFloatingSupplierInvoiceDocuments: (...args: unknown[]) =>
sweepFloatingSupplierInvoiceDocuments(...args),
}))
import { GET } from '../route'
function cronRequest(): Request {
return new Request('http://localhost:3000/api/documents/reanchor/cron')
}
beforeEach(() => {
vi.clearAllMocks()
verifyCronSecret.mockReturnValue(null)
process.env.NEXT_PUBLIC_SUPABASE_URL = 'http://localhost:54321'
process.env.SUPABASE_SERVICE_ROLE_KEY = 'service-role-key'
})
describe('GET /api/documents/reanchor/cron', () => {
it('rejects a request without a valid cron secret', async () => {
verifyCronSecret.mockReturnValue({ error: 'unauthorized' })
const response = await GET(cronRequest())
expect(response.status).toBe(401)
expect(sweepFloatingSupplierInvoiceDocuments).not.toHaveBeenCalled()
})
it('runs the sweep under the service-role client and reports the summary', async () => {
sweepFloatingSupplierInvoiceDocuments.mockResolvedValue({ candidates: 3, anchored: 2 })
const response = await GET(cronRequest())
const json = await response.json()
expect(response.status).toBe(200)
expect(json).toEqual({ data: { candidates: 3, anchored: 2 } })
expect(sweepFloatingSupplierInvoiceDocuments).toHaveBeenCalledWith({ mocked: true })
})
it('fails closed when Supabase configuration is missing', async () => {
delete process.env.SUPABASE_SERVICE_ROLE_KEY
const response = await GET(cronRequest())
expect(response.status).toBeGreaterThanOrEqual(500)
expect(sweepFloatingSupplierInvoiceDocuments).not.toHaveBeenCalled()
})
})
+40
View File
@@ -0,0 +1,40 @@
import { NextResponse } from 'next/server'
import { withCronContext } from '@/lib/api/with-cron-context'
import { createServiceRoleClient } from '@/lib/supabase/service-client'
import { sweepFloatingSupplierInvoiceDocuments } from '@/lib/core/documents/supplier-invoice-underlag'
import { errorResponseFromCode } from '@/lib/errors/get-structured-error'
/**
* GET /api/documents/reanchor/cron: daily 03:30 UTC (schedule in vercel.json).
*
* Re-anchors supplier-invoice retained documents that are floating although
* the invoice has a posted verifikat. The inline anchoring in the payment
* routes is best-effort (the booking is already committed when it runs), so a
* transient failure there leaves the verifikat flagged "Underlag saknas" with
* the PDF plainly attached to the invoice, and until now only a hand-written
* repair migration ever retried. Prod case 2026-08-28: kontantmetod payment
* verifikat posted, document eligible, anchor silently did nothing.
*
* Idempotent: an anchored document is never moved, locked/closed periods are
* skipped, and a clean run touches nothing.
*/
export const maxDuration = 120
export const GET = withCronContext('cron.documents_reanchor', async (_request, ctx) => {
const supabaseUrl = process.env.NEXT_PUBLIC_SUPABASE_URL
const supabaseServiceKey = process.env.SUPABASE_SERVICE_ROLE_KEY
if (!supabaseUrl || !supabaseServiceKey) {
return errorResponseFromCode('INTERNAL_ERROR', ctx.log, {
requestId: ctx.requestId,
details: { reason: 'Missing Supabase configuration' },
})
}
const supabase = createServiceRoleClient(supabaseUrl, supabaseServiceKey)
const result = await sweepFloatingSupplierInvoiceDocuments(supabase)
ctx.log.info('reanchor sweep finished', { ...result })
return NextResponse.json({ data: result })
})
+146
View File
@@ -0,0 +1,146 @@
import { NextResponse } from 'next/server'
import { ensureInitialized } from '@/lib/init'
import { uploadDocument, validateDocumentFile } from '@/lib/core/documents/document-service'
import { withRouteContext } from '@/lib/api/with-route-context'
import { getErrorMessage } from '@/lib/errors/get-error-message'
import { errorResponse, errorResponseFromCode } from '@/lib/errors/get-structured-error'
import type { DocumentUploadSource } from '@/types'
ensureInitialized()
/**
* POST /api/documents: upload a document to the WORM archive.
*
* multipart/form-data:
* file: the document file
* upload_source (optional): 'camera' | 'file_upload' | 'email' | …
* journal_entry_id (optional)
* journal_entry_line_id (optional)
*/
export const POST = withRouteContext(
'document.upload',
async (request, ctx) => {
const { user, supabase, companyId, log, requestId } = ctx
const formData = await request.formData()
const file = formData.get('file') as File | null
if (!file) {
return errorResponseFromCode('DOC_UPLOAD_NO_FILE', log, { requestId })
}
const validationError = validateDocumentFile({ size: file.size, type: file.type })
if (validationError) {
// The validator returns a Swedish string today. Bucket the failure into
// a size or type code based on its content.
const code = /storlek|stor|MB/i.test(validationError)
? 'DOC_UPLOAD_TOO_LARGE'
: 'DOC_UPLOAD_UNSUPPORTED_TYPE'
return errorResponseFromCode(code, log, {
requestId,
details: { reason: validationError, sizeBytes: file.size, mimeType: file.type },
})
}
const opLog = log.child({ filename: file.name, sizeBytes: file.size })
try {
// Whitelist the source — arbitrary strings from formData would otherwise
// land in the upload_source column; unknown values fall back to the
// default rather than 400ing an otherwise-valid upload.
const VALID_SOURCES: DocumentUploadSource[] = [
'camera', 'file_upload', 'email', 'e_invoice', 'scan', 'api', 'system',
]
const rawSource = formData.get('upload_source')
const uploadSource: DocumentUploadSource =
typeof rawSource === 'string' && VALID_SOURCES.includes(rawSource as DocumentUploadSource)
? (rawSource as DocumentUploadSource)
: 'file_upload'
const journalEntryId = formData.get('journal_entry_id') as string | null
const journalEntryLineId = formData.get('journal_entry_line_id') as string | null
const buffer = await file.arrayBuffer()
const document = await uploadDocument(supabase, user.id, companyId!, {
name: file.name,
buffer,
type: file.type,
}, {
upload_source: uploadSource,
journal_entry_id: journalEntryId || undefined,
journal_entry_line_id: journalEntryLineId || undefined,
})
return NextResponse.json({ data: document })
} catch (err) {
const message = err instanceof Error ? err.message : 'unknown'
// DB trigger rejects inserts whose journal_entry_id points at an entry
// in a closed/locked period. Surface as 400 with the real reason.
if (/locked\/closed fiscal period|Bokföringen är låst/i.test(message)) {
return errorResponseFromCode('DOC_UPLOAD_PERIOD_LOCKED', opLog, {
requestId,
details: { reason: getErrorMessage(err) },
})
}
// Magic-byte validation rejections (validateDocumentMagicBytes) are a
// client problem, not a storage failure: surface as 400 with an
// accurate message instead of the misleading "kunde inte sparas".
if (/kunde inte verifieras|matchar inte den angivna filtypen/i.test(message)) {
opLog.warn('document upload rejected by content validation', { reason: message })
return errorResponseFromCode('DOC_UPLOAD_INVALID_CONTENT', opLog, {
requestId,
details: { reason: getErrorMessage(err) },
})
}
// Full error is logged above; the raw message can leak storage-layer
// internals, so the client only gets the generic code + requestId.
opLog.error('document upload failed', err as Error)
return errorResponseFromCode('DOC_UPLOAD_STORAGE_FAILED', opLog, { requestId })
}
},
{ requireWrite: true },
)
/**
* GET /api/documents: list documents.
*
* Query params:
* journal_entry_id: filter by JE
* current_only: 'false' to include older versions (default true)
* limit, offset
*/
export const GET = withRouteContext(
'document.list',
async (request, ctx) => {
const { supabase, companyId, log, requestId } = ctx
const { searchParams } = new URL(request.url)
const journalEntryId = searchParams.get('journal_entry_id')
const currentOnly = searchParams.get('current_only') !== 'false'
// Clamp pagination — parseInt('abc') is NaN and unbounded limits let a
// caller demand the whole table in one page.
const rawLimit = parseInt(searchParams.get('limit') || '50', 10)
const limit = Number.isFinite(rawLimit) ? Math.min(Math.max(rawLimit, 1), 500) : 50
const rawOffset = parseInt(searchParams.get('offset') || '0', 10)
const offset = Number.isFinite(rawOffset) && rawOffset >= 0 ? rawOffset : 0
let query = supabase
.from('document_attachments')
.select('*', { count: 'exact' })
.eq('company_id', companyId)
.order('created_at', { ascending: false })
.range(offset, offset + limit - 1)
if (journalEntryId) query = query.eq('journal_entry_id', journalEntryId)
if (currentOnly) query = query.eq('is_current_version', true)
const { data, error, count } = await query
if (error) {
log.error('document list failed', error)
return errorResponse(error, log, { requestId })
}
return NextResponse.json({ data, count })
},
)
@@ -0,0 +1,355 @@
/**
* Tests for the nightly document integrity-verify cron.
*
* Covers the production defects fixed in this route:
* - the run must fit its budget (maxDuration 300 + batch default 200),
* - a document whose storage object cannot be downloaded must surface as an
* audit incident (INTEGRITY_FAILURE / DOCUMENT_OBJECT_MISSING) AND get a
* ledger row so it stops head-blocking the queue,
* - the queue and the stamp both live in document_integrity_checks: the route
* must never write to document_attachments, whose UPDATE trigger
* (enforce_period_lock_documents, migration 017) rejects every document
* linked to a closed/locked period and wedged the cron at 200/200 rejected,
* - and a rejected ledger or audit write must be counted, logged and reported
* rather than discarded, which is why the stall went unnoticed for weeks.
*/
import { describe, it, expect, vi, beforeEach } from 'vitest'
import { createHash } from 'node:crypto'
import { NextResponse } from 'next/server'
import { verifyCronSecret } from '@/lib/auth/cron'
vi.mock('@/lib/auth/cron', () => ({
verifyCronSecret: vi.fn(() => null),
}))
interface MockDoc {
id: string
user_id: string
company_id: string
storage_path: string
sha256_hash: string
file_name: string
last_checked_at: string | null
}
const state = {
documents: [] as MockDoc[],
fetchError: null as { message: string } | null,
downloadResults: new Map<string, { data: unknown; error: { message: string } | null }>(),
rpcCalls: [] as Array<{ fn: string; args: Record<string, unknown> }>,
ledgerInserts: [] as Array<Record<string, unknown>>,
ledgerInsertError: null as { message: string } | null,
auditInserts: [] as Array<Record<string, unknown>>,
auditInsertError: null as { message: string } | null,
}
function makeMockClient() {
return {
rpc: (fn: string, args: Record<string, unknown>) => {
state.rpcCalls.push({ fn, args })
return Promise.resolve({
data: state.fetchError ? null : state.documents,
error: state.fetchError,
})
},
from: (table: string) => {
if (table === 'document_integrity_checks') {
return {
insert: (row: Record<string, unknown>) => {
state.ledgerInserts.push(row)
return Promise.resolve({ error: state.ledgerInsertError })
},
}
}
if (table === 'audit_log') {
return {
insert: (row: Record<string, unknown>) => {
state.auditInserts.push(row)
return Promise.resolve({ error: state.auditInsertError })
},
}
}
if (table === 'document_attachments') {
// The whole point of the fix: a write here runs through
// enforce_period_lock_documents() and is rejected for every document
// linked to a closed/locked period.
throw new Error('the verify cron must never write to document_attachments')
}
throw new Error(`unexpected table: ${table}`)
},
storage: {
from: () => ({
download: (path: string) =>
Promise.resolve(
state.downloadResults.get(path) ?? {
data: null,
error: { message: 'Object not found' },
}
),
}),
},
}
}
vi.mock('@supabase/supabase-js', () => ({
createClient: vi.fn(() => makeMockClient()),
}))
import { GET, maxDuration } from '../route'
function cronRequest(): Request {
return new Request('http://localhost:3000/api/documents/verify/cron')
}
function makeDoc(overrides: Partial<MockDoc> = {}): MockDoc {
return {
id: 'doc-1',
user_id: 'user-1',
company_id: 'company-1',
storage_path: 'user-1/company-1/inbox/file.pdf',
sha256_hash: 'deadbeef',
file_name: 'file.pdf',
last_checked_at: null,
...overrides,
}
}
/** Register a downloadable object whose bytes hash to the returned sha256. */
function registerObject(path: string, content: string): string {
const buf = Buffer.from(content, 'utf8')
const arrayBuffer = buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength)
state.downloadResults.set(path, {
data: { arrayBuffer: async () => arrayBuffer },
error: null,
})
return createHash('sha256').update(buf).digest('hex')
}
beforeEach(() => {
vi.clearAllMocks()
process.env.NEXT_PUBLIC_SUPABASE_URL = 'https://example.supabase.co'
process.env.SUPABASE_SERVICE_ROLE_KEY = 'service-role-key'
delete process.env.DOCUMENT_VERIFY_BATCH_SIZE
state.documents = []
state.fetchError = null
state.downloadResults.clear()
state.rpcCalls = []
state.ledgerInserts = []
state.ledgerInsertError = null
state.auditInserts = []
state.auditInsertError = null
})
describe('GET /api/documents/verify/cron', () => {
it('returns 401 when the cron secret is invalid', async () => {
vi.mocked(verifyCronSecret).mockReturnValueOnce(
NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
)
const response = await GET(cronRequest())
expect(response.status).toBe(401)
expect(state.rpcCalls).toHaveLength(0)
})
it('declares a 300s function budget', () => {
expect(maxDuration).toBe(300)
})
it('draws the batch from the ledger queue, 200 by default, env override honored', async () => {
await GET(cronRequest())
expect(state.rpcCalls).toEqual([
{ fn: 'next_documents_for_integrity_check', args: { p_limit: 200 } },
])
process.env.DOCUMENT_VERIFY_BATCH_SIZE = '50'
await GET(cronRequest())
expect(state.rpcCalls[1]).toEqual({
fn: 'next_documents_for_integrity_check',
args: { p_limit: 50 },
})
})
it('appends a passed ledger row on a successful verification', async () => {
const doc = makeDoc()
const hash = registerObject(doc.storage_path, '%PDF-1.4 demo content')
state.documents = [{ ...doc, sha256_hash: hash }]
const response = await GET(cronRequest())
const json = await response.json()
expect(json).toEqual({
processed: 1,
verified: 1,
failures: 0,
missingObjects: 0,
writeFailures: 0,
errors: 0,
})
expect(state.ledgerInserts).toHaveLength(1)
expect(state.ledgerInserts[0]).toMatchObject({
document_id: doc.id,
company_id: doc.company_id,
result: 'passed',
expected_sha256: hash,
computed_sha256: hash,
storage_path: doc.storage_path,
detail: null,
})
expect(state.ledgerInserts[0].checked_at).toEqual(expect.any(String))
expect(state.auditInserts).toHaveLength(0)
})
it('writes an INTEGRITY_FAILURE audit row and a hash_mismatch ledger row on mismatch', async () => {
const doc = makeDoc({ sha256_hash: 'not-the-real-hash' })
registerObject(doc.storage_path, 'tampered content')
state.documents = [doc]
const response = await GET(cronRequest())
const json = await response.json()
expect(json.failures).toBe(1)
expect(json.missingObjects).toBe(0)
expect(json.writeFailures).toBe(0)
expect(state.auditInserts).toHaveLength(1)
expect(state.auditInserts[0].action).toBe('INTEGRITY_FAILURE')
expect(String(state.auditInserts[0].description)).not.toContain('DOCUMENT_OBJECT_MISSING')
expect(state.ledgerInserts).toHaveLength(1)
expect(state.ledgerInserts[0]).toMatchObject({
document_id: doc.id,
result: 'hash_mismatch',
expected_sha256: 'not-the-real-hash',
})
})
it('verifies via the company-scoped fallback key when a concurrent backfill re-homed the object', async () => {
// The batch snapshot carries a stale legacy pointer: mid-batch, the
// Phase B backfill copied the object to the company-scoped key and
// removed the source. This must NOT produce a permanent false
// DOCUMENT_OBJECT_MISSING audit row for a healthy document.
const doc = makeDoc({
id: 'doc-repointed',
storage_path: 'documents/user-1/1_receipt.pdf',
})
const hash = registerObject('documents/company-1/user-1/1_receipt.pdf', 'healthy bytes')
state.documents = [{ ...doc, sha256_hash: hash }]
const response = await GET(cronRequest())
const json = await response.json()
expect(state.auditInserts).toHaveLength(0)
expect(state.ledgerInserts.map((row) => row.document_id)).toEqual(['doc-repointed'])
expect(json).toEqual({
processed: 1,
verified: 1,
failures: 0,
missingObjects: 0,
writeFailures: 0,
errors: 0,
})
})
it('surfaces a missing storage object as an audit incident AND an object_missing ledger row', async () => {
const missing = makeDoc({ id: 'doc-missing', storage_path: 'user-1/company-1/gone.pdf' })
const healthy = makeDoc({ id: 'doc-healthy', storage_path: 'user-1/company-1/ok.pdf' })
const healthyHash = registerObject(healthy.storage_path, 'healthy content')
state.documents = [missing, { ...healthy, sha256_hash: healthyHash }]
const response = await GET(cronRequest())
const json = await response.json()
// The audit row is the incident surface for the missing object.
expect(state.auditInserts).toHaveLength(1)
const audit = state.auditInserts[0]
expect(audit.action).toBe('INTEGRITY_FAILURE')
expect(audit.record_id).toBe('doc-missing')
expect(String(audit.description)).toContain('DOCUMENT_OBJECT_MISSING')
expect(audit.new_state).toMatchObject({ reason: 'DOCUMENT_OBJECT_MISSING' })
// Both documents get a ledger row: the failing one must stop head-blocking
// the queue, and the healthy one was verified.
expect(state.ledgerInserts.map((row) => row.document_id).sort()).toEqual([
'doc-healthy',
'doc-missing',
])
expect(state.ledgerInserts.find((row) => row.document_id === 'doc-missing')).toMatchObject({
result: 'object_missing',
computed_sha256: null,
})
expect(json).toEqual({
processed: 2,
verified: 1,
failures: 0,
missingObjects: 1,
writeFailures: 0,
errors: 1,
})
})
it('does not write a ledger row when the audit insert fails, so it retries next run', async () => {
const missing = makeDoc({ id: 'doc-missing', storage_path: 'user-1/company-1/gone.pdf' })
state.documents = [missing]
state.auditInsertError = { message: 'insert blocked' }
const response = await GET(cronRequest())
const json = await response.json()
expect(state.auditInserts).toHaveLength(1)
expect(state.ledgerInserts).toHaveLength(0)
expect(json.missingObjects).toBe(0)
expect(json.writeFailures).toBe(1)
expect(json.errors).toBe(1)
})
it('reports a rejected ledger write instead of swallowing it', async () => {
const doc = makeDoc()
const hash = registerObject(doc.storage_path, 'healthy content')
state.documents = [{ ...doc, sha256_hash: hash }]
state.ledgerInsertError = { message: 'permission denied for table document_integrity_checks' }
const response = await GET(cronRequest())
const json = await response.json()
expect(state.ledgerInserts).toHaveLength(1)
expect(json).toEqual({
processed: 1,
verified: 0,
failures: 0,
missingObjects: 0,
writeFailures: 1,
errors: 1,
})
})
it('counts a rejected audit write on a hash mismatch as a write failure', async () => {
const doc = makeDoc({ sha256_hash: 'not-the-real-hash' })
registerObject(doc.storage_path, 'tampered content')
state.documents = [doc]
state.auditInsertError = { message: 'insert blocked' }
const response = await GET(cronRequest())
const json = await response.json()
expect(state.auditInserts).toHaveLength(1)
expect(state.ledgerInserts).toHaveLength(0)
expect(json.failures).toBe(0)
expect(json.writeFailures).toBe(1)
expect(json.errors).toBe(1)
})
it('returns an error envelope when the queue fetch fails', async () => {
state.fetchError = { message: 'db down' }
const response = await GET(cronRequest())
expect(response.status).toBeGreaterThanOrEqual(500)
})
it('reports zero processed when there is nothing to verify', async () => {
const response = await GET(cronRequest())
const json = await response.json()
expect(json).toEqual({ message: 'No documents to verify', processed: 0 })
})
})
+272
View File
@@ -0,0 +1,272 @@
import { createServiceRoleClient } from '@/lib/supabase/service-client'
import { NextResponse } from 'next/server'
import { withCronContext } from '@/lib/api/with-cron-context'
import { downloadDocumentObject } from '@/lib/core/documents/document-service'
import { errorResponse, errorResponseFromCode } from '@/lib/errors/get-structured-error'
/**
* GET /api/documents/verify/cron: nightly 03:00 UTC (schedule in vercel.json).
* Spot-checks WORM archive integrity by recomputing SHA-256 for the next
* batch of documents and appending the outcome to document_integrity_checks.
* Hash mismatches and unreadable storage objects additionally get an
* INTEGRITY_FAILURE row in the audit log, which is the durable incident
* surface.
*
* Both the queue and the stamp live in document_integrity_checks and NOT in
* document_attachments.last_integrity_check_at (now legacy): any UPDATE of a
* document linked to an entry in a closed/locked period is rejected by
* enforce_period_lock_documents() (migration 017, legally required and never
* touched), which had this cron wedged at 200 of 200 rejected per night with
* both write errors discarded. See
* supabase/migrations/20260901130000_document_integrity_checks.sql.
*/
// Vercel function budget; verification is sequential, see batch size below.
export const maxDuration = 300
// Measured ~0.8s per document (download + hash + ledger append), so 200
// documents finish in ~160s with headroom inside the 300s budget. The previous
// default of 500 hit the platform timeout around item ~250 every night, so the
// tail of the queue was never reached.
const DEFAULT_VERIFY_BATCH_SIZE = 200
type ServiceClient = ReturnType<typeof createServiceRoleClient>
type IntegrityResult = 'passed' | 'hash_mismatch' | 'object_missing'
/** One row of public.next_documents_for_integrity_check(). */
interface QueuedDocument {
id: string
user_id: string
company_id: string
storage_path: string
sha256_hash: string
file_name: string
last_checked_at: string | null
}
/**
* Append the outcome of one check to the integrity ledger. The write error is
* returned, never swallowed: a lost ledger row leaves the document at the head
* of the queue, and discarding exactly this error is why the control stayed
* dead for weeks without anyone noticing.
*/
async function recordCheck(
supabase: ServiceClient,
doc: QueuedDocument,
result: IntegrityResult,
computedHash: string | null,
detail: string | null
): Promise<{ error: { message: string } | null }> {
const { error } = await supabase.from('document_integrity_checks').insert({
company_id: doc.company_id,
document_id: doc.id,
checked_at: new Date().toISOString(),
expected_sha256: doc.sha256_hash,
computed_sha256: computedHash,
storage_path: doc.storage_path,
result,
detail,
})
return { error }
}
export const GET = withCronContext('cron.documents_verify', async (_request, ctx) => {
const supabaseUrl = process.env.NEXT_PUBLIC_SUPABASE_URL
const supabaseServiceKey = process.env.SUPABASE_SERVICE_ROLE_KEY
if (!supabaseUrl || !supabaseServiceKey) {
return errorResponseFromCode('INTERNAL_ERROR', ctx.log, {
requestId: ctx.requestId,
details: { reason: 'Missing Supabase configuration' },
})
}
const supabase = createServiceRoleClient(supabaseUrl, supabaseServiceKey)
const batchSize =
parseInt(process.env.DOCUMENT_VERIFY_BATCH_SIZE || '', 10) || DEFAULT_VERIFY_BATCH_SIZE
// Least-recently-checked first, never-checked ahead of those, tie-broken on
// created_at so the drain is a deterministic FIFO rather than heap order.
const { data, error: fetchError } = await supabase.rpc('next_documents_for_integrity_check', {
p_limit: batchSize,
})
if (fetchError) {
ctx.log.error('failed to fetch documents for verify', fetchError)
return errorResponse(fetchError, ctx.log, { requestId: ctx.requestId })
}
const documents = (data ?? []) as QueuedDocument[]
if (documents.length === 0) {
return NextResponse.json({ message: 'No documents to verify', processed: 0 })
}
let verified = 0
let failures = 0
let missingObjects = 0
// Ledger and audit writes the database rejected. Counted, logged and shipped
// in the response so a broken write path shows up on the first run instead
// of weeks later.
let writeFailures = 0
const summary = await ctx.forEach('document', documents, async (doc, itemCtx) => {
// Dual-layout download: the batch is snapshotted up front, and a
// concurrent Phase B backfill (scripts/backfill-document-storage-paths.ts)
// can re-home an object from the legacy uploader-scoped key to the
// company-scoped key (and later remove the source) mid-batch, leaving
// doc.storage_path stale. Trusting the stale pointer here wrote a
// PERMANENT false DOCUMENT_OBJECT_MISSING INTEGRITY_FAILURE row into the
// immutable audit log for a healthy document. The helper tries the
// stored pointer first, then the alternate layout.
const { blob: fileData, error: downloadError } = await downloadDocumentObject(
supabase,
doc.storage_path,
doc.company_id
)
if (downloadError || !fileData) {
// The storage object is unreadable: surface it as an incident in the
// audit log. The action stays INTEGRITY_FAILURE because the DB check
// constraint audit_log_action_check allows a fixed set of actions;
// the DOCUMENT_OBJECT_MISSING marker in description and new_state
// distinguishes a missing object from a hash mismatch.
const reason = downloadError?.message || 'download_failed'
const { error: auditError } = await supabase.from('audit_log').insert({
user_id: doc.user_id,
company_id: doc.company_id,
action: 'INTEGRITY_FAILURE',
table_name: 'document_attachments',
record_id: doc.id,
description: `DOCUMENT_OBJECT_MISSING: storage object for document "${doc.file_name}" at "${doc.storage_path}" could not be downloaded: ${reason}`,
old_state: { sha256_hash: doc.sha256_hash },
new_state: { reason: 'DOCUMENT_OBJECT_MISSING', download_error: reason },
})
if (auditError) {
// Append no ledger row, so the document keeps its place at the head of
// the queue and the incident write is re-attempted on the next run.
writeFailures++
itemCtx.log.error('audit insert failed for missing object', new Error(auditError.message), {
documentId: doc.id,
})
throw new Error(`audit insert failed for missing object: ${auditError.message}`)
}
const { error: ledgerError } = await recordCheck(
supabase,
doc,
'object_missing',
null,
`DOCUMENT_OBJECT_MISSING: ${reason}`
)
if (ledgerError) {
writeFailures++
itemCtx.log.error('integrity ledger write failed', new Error(ledgerError.message), {
documentId: doc.id,
result: 'object_missing',
})
throw new Error(`integrity ledger write failed: ${ledgerError.message}`)
}
missingObjects++
itemCtx.log.error('document object missing', new Error(reason), {
documentId: doc.id,
fileName: doc.file_name,
storagePath: doc.storage_path,
})
throw new Error(`DOCUMENT_OBJECT_MISSING: ${reason}`)
}
const buffer = await fileData.arrayBuffer()
const hashBuffer = await crypto.subtle.digest('SHA-256', buffer)
const hashArray = Array.from(new Uint8Array(hashBuffer))
const computedHash = hashArray.map((b) => b.toString(16).padStart(2, '0')).join('')
const isValid = computedHash === doc.sha256_hash
if (!isValid) {
// Audit row before ledger row: if the ledger row landed first and the
// audit write then failed, the document would leave the queue with the
// incident lost. This order re-checks it tomorrow instead.
const { error: auditError } = await supabase.from('audit_log').insert({
user_id: doc.user_id,
company_id: doc.company_id,
action: 'INTEGRITY_FAILURE',
table_name: 'document_attachments',
record_id: doc.id,
description: `Integrity check failed for document "${doc.file_name}": stored hash ${doc.sha256_hash}, computed hash ${computedHash}`,
old_state: { sha256_hash: doc.sha256_hash },
new_state: { computed_hash: computedHash },
})
if (auditError) {
writeFailures++
itemCtx.log.error('audit insert failed for hash mismatch', new Error(auditError.message), {
documentId: doc.id,
})
throw new Error(`audit insert failed for hash mismatch: ${auditError.message}`)
}
}
const { error: ledgerError } = await recordCheck(
supabase,
doc,
isValid ? 'passed' : 'hash_mismatch',
computedHash,
isValid ? null : `stored hash ${doc.sha256_hash}, computed hash ${computedHash}`
)
if (ledgerError) {
writeFailures++
itemCtx.log.error('integrity ledger write failed', new Error(ledgerError.message), {
documentId: doc.id,
result: isValid ? 'passed' : 'hash_mismatch',
})
throw new Error(`integrity ledger write failed: ${ledgerError.message}`)
}
if (!isValid) {
itemCtx.log.error('integrity failure', new Error('hash_mismatch'), {
documentId: doc.id,
fileName: doc.file_name,
storedHash: doc.sha256_hash,
computedHash,
})
failures++
} else {
verified++
}
})
ctx.log.info('document verify summary', {
processed: summary.total,
verified,
failures,
missingObjects,
writeFailures,
downloadErrors: summary.failed,
})
if (writeFailures > 0) {
// Loud on its own line: a rejected ledger write means the queue does not
// advance, which is exactly the silent stall this cron just came out of.
ctx.log.error('integrity ledger writes rejected', new Error('integrity_write_failed'), {
processed: summary.total,
writeFailures,
})
}
return NextResponse.json({
processed: summary.total,
verified,
failures,
missingObjects,
writeFailures,
errors: summary.failed,
})
})