Fix/usr fdbck ch (#1105)

* fix(privacy): mask voucher amounts in session replays

* fix: persist transaction source filter

* fix: clarify invoice filenames and booking previews

* fix: truncate long uploaded filenames

* feat: add invoice delivery history

* fix: harden invoice delivery history

* fix: include invoice deliveries in full archive
This commit is contained in:
Mattsson
2026-07-22 18:49:57 +02:00
committed by GitHub
parent 3e1ea29d02
commit 321e684523
58 changed files with 3742 additions and 285 deletions
@@ -12,6 +12,14 @@ 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: () => ({
@@ -73,9 +81,8 @@ describe('GET /api/documents/[id]/inline', () => {
expect(body.error).toBe('Document not found')
})
it('returns 404 when the user is not a member of the document company', async () => {
enqueue({ data: makeDoc(), error: null }) // doc lookup
enqueue({ data: null, error: null }) // membership lookup
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)
@@ -83,7 +90,6 @@ describe('GET /api/documents/[id]/inline', () => {
it('returns 500 when the storage download fails', async () => {
enqueue({ data: makeDoc(), error: null })
enqueue({ data: { company_id: 'company-1' }, error: null })
downloadMock.mockResolvedValue({ data: null, error: { message: 'boom' } })
const res = await GET(makeReq(), createMockRouteParams({ id: 'doc-1' }))
const { status } = await parseJsonResponse(res)
@@ -92,7 +98,6 @@ describe('GET /api/documents/[id]/inline', () => {
it('streams the file with an RFC 5987 Content-Disposition for an NFD filename', async () => {
enqueue({ data: makeDoc(), error: null })
enqueue({ data: { company_id: 'company-1' }, error: null })
const res = await GET(makeReq(), createMockRouteParams({ id: 'doc-1' }))
@@ -104,5 +109,6 @@ describe('GET /api/documents/[id]/inline', () => {
// 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')
})
})
+47 -59
View File
@@ -1,7 +1,7 @@
import { NextResponse } from 'next/server'
import { requireAuth } from '@/lib/auth/require-auth'
import { createServiceClient } from '@/lib/supabase/server'
import { contentDisposition } from '@/lib/api/content-disposition'
import { withRouteContext } from '@/lib/api/with-route-context'
import { getErrorMessage as getUserErrorMessage } from '@/lib/errors/get-error-message'
/**
@@ -43,66 +43,54 @@ function resolveContentType(fileName: string, dbMimeType: string | null): string
const ext = fileName.toLowerCase().split('.').pop() ?? ''
return EXTENSION_MIME_MAP[ext] ?? dbMimeType ?? 'application/octet-stream'
}
export async function GET(
_request: Request,
{ params }: { params: Promise<{ id: string }> }
) {
const { user, supabase, error } = await requireAuth()
if (error) return error
export const GET = withRouteContext<{ params: Promise<{ id: string }> }>(
'document.inline',
async (_request, { supabase, companyId }, { params }) => {
const { id } = await 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()
// Authorize via the auth-bound client: RLS + explicit company filter
// through user_company_ids (defense in depth).
const { data: doc, error: docError } = await supabase
.from('document_attachments')
.select('id, company_id, file_name, mime_type, storage_path')
.eq('id', id)
.single()
if (docError || !doc) {
return NextResponse.json({ error: 'Document not found' }, { status: 404 })
}
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)
// Explicit membership check on top of RLS.
const { data: membership } = await supabase
.from('company_members')
.select('company_id')
.eq('company_id', doc.company_id)
.eq('user_id', user.id)
.maybeSingle()
if (downloadError || !blob) {
return NextResponse.json(
{ error: `Failed to download document: ${getUserErrorMessage(downloadError) ?? 'unknown error'}` },
{ status: 500 },
)
}
if (!membership) {
return NextResponse.json({ error: 'Document not found' }, { status: 404 })
}
// Use the service-role client to read from the non-public bucket.
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 }
)
}
return new NextResponse(blob, {
status: 200,
headers: {
'Content-Type': resolveContentType(doc.file_name, doc.mime_type),
// 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, max-age=300',
// 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',
},
})
}
return new NextResponse(blob, {
status: 200,
headers: {
'Content-Type': resolveContentType(doc.file_name, doc.mime_type),
// 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',
},
})
},
)