* fix(documents): RFC 5987 Content-Disposition so NFD filenames stop crashing inline view macOS/iOS uploads carry NFD-decomposed filenames (base letter + combining diaeresis U+0308, char code 776). undici Headers require ByteString values (every code unit <= 0xFF), so splicing the raw filename into the Content-Disposition header threw while building the response and the inline document route 500ed. 122 prod documents across 35 companies hit this; last crash 2026-07-09T16:17. Add lib/api/content-disposition.ts emitting the RFC 6266 dual form: an ASCII quoted fallback (NFC-normalize, then replace anything outside printable ASCII plus quote and backslash with _) and filename*=UTF-8''<percent-encoded> per RFC 5987 (encodeURIComponent on the NFC name, additionally escaping ! ' ( ) * which it leaves bare). Use it in the inline document route and in the two latent same-shape sites that embed raw employee names in payslip PDF headers. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * fix(api): sanitize lone surrogates before percent-encoding Content-Disposition (CodeRabbit) Unpaired UTF-16 surrogates survive normalize('NFC') and make encodeURIComponent throw a URIError, so replace them with U+FFFD via String.prototype.toWellFormed() before encoding so the helper always returns a valid header value. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> --------- Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
108 lines
4.0 KiB
TypeScript
108 lines
4.0 KiB
TypeScript
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'
|
|
|
|
/**
|
|
* 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.
|
|
*/
|
|
|
|
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 async function GET(
|
|
_request: Request,
|
|
{ params }: { params: Promise<{ id: string }> }
|
|
) {
|
|
const { user, supabase, error } = await requireAuth()
|
|
if (error) return error
|
|
|
|
const { id } = await params
|
|
|
|
// 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 })
|
|
}
|
|
|
|
// 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 (!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: ${downloadError?.message ?? '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',
|
|
},
|
|
})
|
|
}
|