43 lines
1.5 KiB
TypeScript
43 lines
1.5 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 }> {
|
|
const { data: { user } } = await supabase.auth.getUser()
|
|
if (!user) throw new Error('Not authenticated')
|
|
|
|
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, error } = await supabase.storage
|
|
.from('evidence')
|
|
.upload(path, file, { contentType: file.type, upsert: false })
|
|
|
|
if (error) throw new Error(error.message)
|
|
|
|
const { data: urlData } = supabase.storage.from('evidence').getPublicUrl(data.path)
|
|
|
|
return { path: data.path, publicUrl: urlData.publicUrl, hash }
|
|
}
|
|
|
|
export function getEvidenceUrl(supabase: SupabaseClient, path: string): string {
|
|
const { data } = supabase.storage.from('evidence').getPublicUrl(path)
|
|
return data.publicUrl
|
|
}
|
|
|
|
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('')
|
|
}
|