Files
adminandClaude Sonnet 4.6 d18d29168a feat(auth): phase 3 — replace Supabase GoTrue with bcryptjs+jose
Custom auth stack: bcryptjs password hashing (cost 10, GoTrue-compatible),
jose JWT session cookies (edge-safe, 8hr TTL), new API routes for
login/logout/reset/change-password, middleware rewritten to JWT-only
verification with no DB access. All 38 protected pages and API routes
migrated from supabase.auth.getUser() to getSession(). Supabase .from()
queries retained for Phase 4. lib/db/index.ts refactored to lazy Proxy
singleton to avoid module-level throw during Next.js build.

tsc: clean, build: clean, tests: 4/4 passed

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-07-23 16:20:04 +08:00

72 lines
2.9 KiB
TypeScript

import type { SupabaseClient } from '@supabase/supabase-js'
import { fileTypeFromBuffer } from 'file-type'
export type EvidenceStage = 'report' | 'response' | 'investigation' | 'capa' | 'verification'
const ALLOWED_MIME_TYPES = new Set([
'image/jpeg', 'image/png', 'image/gif', 'image/webp', 'image/heic', 'image/avif',
'video/mp4', 'video/quicktime', 'video/webm', 'video/x-msvideo',
'application/pdf',
'application/msword',
'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
'application/vnd.ms-excel',
'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
])
export async function uploadEvidenceFile(
supabase: SupabaseClient,
file: File,
incidentId: string,
stage: EvidenceStage,
userId: string,
): Promise<{ path: string; publicUrl: string; hash: string }> {
// 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`)
}
// Magic-byte validation — do not trust client-supplied MIME type
const buffer = await file.arrayBuffer()
const detected = await fileTypeFromBuffer(buffer)
const detectedMime = detected?.mime ?? null
if (!detectedMime || !ALLOWED_MIME_TYPES.has(detectedMime)) {
throw new Error(`File type not allowed: ${detectedMime ?? 'unknown'}`)
}
const ext = detected?.ext ?? file.name.split('.').pop() ?? 'bin'
const filename = `${Date.now()}-${Math.random().toString(36).slice(2)}.${ext}`
const path = `${userId}/${incidentId}/${stage}/${filename}`
const hash = await computeHashFromBuffer(buffer)
const { data: uploadData, error } = await supabase.storage
.from('evidence')
.upload(path, buffer, { contentType: detectedMime, 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 computeHashFromBuffer(buffer: ArrayBuffer): Promise<string> {
const hashBuffer = await crypto.subtle.digest('SHA-256', buffer)
return Array.from(new Uint8Array(hashBuffer))
.map(b => b.toString(16).padStart(2, '0'))
.join('')
}