58 lines
2.3 KiB
TypeScript
58 lines
2.3 KiB
TypeScript
import type { SupabaseClient } from '@supabase/supabase-js'
|
|
|
|
export type EvidenceStage = 'report' | 'response' | 'investigation' | 'capa' | 'verification'
|
|
|
|
export async function uploadEvidenceFile(
|
|
supabase: SupabaseClient,
|
|
file: File,
|
|
incidentId: string,
|
|
stage: EvidenceStage,
|
|
): Promise<{ path: string; publicUrl: string; hash: string }> {
|
|
// Fix 3: Safe auth.getUser() destructuring
|
|
const { data, error: authError } = await supabase.auth.getUser()
|
|
if (authError || !data?.user) throw new Error('Not authenticated')
|
|
const user = data.user
|
|
|
|
// Fix 2: Server-side size limit before processing
|
|
const isVideo = file.type.startsWith('video/')
|
|
const maxBytes = isVideo ? 200 * 1024 * 1024 : 10 * 1024 * 1024
|
|
if (file.size > maxBytes) {
|
|
throw new Error(`File too large: max ${isVideo ? '200MB' : '10MB'} for this file type`)
|
|
}
|
|
|
|
const ext = file.name.split('.').pop() ?? 'bin'
|
|
const filename = `${Date.now()}-${Math.random().toString(36).slice(2)}.${ext}`
|
|
const path = `${user.id}/${incidentId}/${stage}/${filename}`
|
|
|
|
const hash = await computeHash(file)
|
|
|
|
const { data: uploadData, error } = await supabase.storage
|
|
.from('evidence')
|
|
.upload(path, file, { contentType: file.type, upsert: false })
|
|
|
|
if (error) throw new Error(error.message)
|
|
|
|
// Fix 1: Use createSignedUrl (private bucket) — 10-year URL for DB storage
|
|
const { data: signedData, error: signedError } = await supabase.storage
|
|
.from('evidence')
|
|
.createSignedUrl(uploadData.path, 315360000) // ~10 years
|
|
if (signedError || !signedData) throw new Error(signedError?.message ?? 'Failed to sign URL')
|
|
|
|
return { path: uploadData.path, publicUrl: signedData.signedUrl, hash }
|
|
}
|
|
|
|
// Fix 1: getEvidenceUrl is now async, uses 1-hour signed URL
|
|
export async function getEvidenceUrl(supabase: SupabaseClient, path: string): Promise<string> {
|
|
const { data, error } = await supabase.storage.from('evidence').createSignedUrl(path, 3600)
|
|
if (error || !data) throw new Error(error?.message ?? 'Failed to sign URL')
|
|
return data.signedUrl
|
|
}
|
|
|
|
async function computeHash(file: File): Promise<string> {
|
|
const buffer = await file.arrayBuffer()
|
|
const hashBuffer = await crypto.subtle.digest('SHA-256', buffer)
|
|
return Array.from(new Uint8Array(hashBuffer))
|
|
.map(b => b.toString(16).padStart(2, '0'))
|
|
.join('')
|
|
}
|