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>
This commit is contained in:
2026-07-23 16:20:04 +08:00
co-authored by Claude Sonnet 4.6
parent a95273b182
commit d18d29168a
67 changed files with 966 additions and 591 deletions
+13 -17
View File
@@ -2,21 +2,20 @@ export const dynamic = 'force-dynamic'
import { NextRequest, NextResponse } from 'next/server'
import { createClient } from '@/lib/supabase/server'
import { getSession } from '@/lib/auth/get-session'
export async function GET(
_request: NextRequest,
{ params }: { params: Promise<{ id: string }> }
) {
const { id } = await params
const supabase = await createClient()
const { data: { user }, error: authError } = await supabase.auth.getUser()
if (authError || !user) return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
const { data: profile } = await supabase.from('users').select('role').eq('id', user.id).single()
if (!profile || !['hse', 'admin', 'supervisor'].includes(profile.role))
const session = await getSession()
if (!session) return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
if (!['hse', 'admin', 'supervisor'].includes(session.role))
return NextResponse.json({ error: 'Forbidden' }, { status: 403 })
const supabase = await createClient()
const { data, error } = await supabase
.from('incident_addenda')
.select('id, body, created_at, author:users!author (name)')
@@ -32,16 +31,13 @@ export async function POST(
{ params }: { params: Promise<{ id: string }> }
) {
const { id } = await params
const supabase = await createClient()
const { data: { user }, error: authError } = await supabase.auth.getUser()
if (authError || !user) return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
const { data: profile } = await supabase
.from('users').select('role').eq('id', user.id).single()
if (!profile || !['hse', 'admin', 'supervisor'].includes(profile.role))
const session = await getSession()
if (!session) return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
if (!['hse', 'admin', 'supervisor'].includes(session.role))
return NextResponse.json({ error: 'Forbidden' }, { status: 403 })
const supabase = await createClient()
const body: { body?: string } = await request.json().catch(() => ({}))
const text = (body.body ?? '').trim()
if (!text) return NextResponse.json({ error: 'body required' }, { status: 422 })
@@ -50,7 +46,7 @@ export async function POST(
const { data: addendum, error } = await supabase
.from('incident_addenda')
.insert({ incident_id: id, author: user.id, body: text })
.insert({ incident_id: id, author: session.sub, body: text })
.select('id')
.single()
@@ -60,7 +56,7 @@ export async function POST(
p_table_name: 'incident_addenda',
p_record_id: addendum.id,
p_action: 'INSERT',
p_new_value: { incident_id: id, author: user.id, body: text },
p_new_value: { incident_id: id, author: session.sub, body: text },
})
return NextResponse.json({ id: addendum.id }, { status: 201 })
+7 -7
View File
@@ -2,6 +2,7 @@ export const dynamic = 'force-dynamic'
import { NextRequest, NextResponse } from 'next/server'
import { createClient } from '@/lib/supabase/server'
import { getSession } from '@/lib/auth/get-session'
import { createDeepSeekClient } from '@/lib/claude/client'
import { getApiKey } from '@/lib/settings'
@@ -10,19 +11,18 @@ export async function POST(
{ params }: { params: Promise<{ id: string }> }
) {
const { id } = await params
const supabase = await createClient()
const { data: { user }, error: authError } = await supabase.auth.getUser()
if (authError || !user) return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
const { data: profile } = await supabase.from('users').select('role').eq('id', user.id).single()
if (!profile || !['hse', 'admin'].includes(profile.role))
const session = await getSession()
if (!session) return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
if (!['hse', 'admin'].includes(session.role))
return NextResponse.json({ error: 'Forbidden' }, { status: 403 })
const supabase = await createClient()
const since = new Date(Date.now() - 60_000).toISOString()
const { count: recentCount } = await supabase
.from('audit_log')
.select('id', { count: 'exact', head: true })
.eq('changed_by', user.id)
.eq('changed_by', session.sub)
.eq('action', 'ai_rca_draft')
.gte('changed_at', since)
if ((recentCount ?? 0) > 0)
@@ -2,6 +2,7 @@ export const dynamic = 'force-dynamic'
import { NextRequest, NextResponse } from 'next/server'
import { createClient } from '@/lib/supabase/server'
import { getSession } from '@/lib/auth/get-session'
import { createDeepSeekClient } from '@/lib/claude/client'
import { getApiKey } from '@/lib/settings'
@@ -10,19 +11,18 @@ export async function POST(
{ params }: { params: Promise<{ id: string }> }
) {
const { id } = await params
const supabase = await createClient()
const { data: { user }, error: authError } = await supabase.auth.getUser()
if (authError || !user) return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
const { data: profile } = await supabase.from('users').select('role').eq('id', user.id).single()
if (!profile || !['hse', 'admin'].includes(profile.role))
const session = await getSession()
if (!session) return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
if (!['hse', 'admin'].includes(session.role))
return NextResponse.json({ error: 'Forbidden' }, { status: 403 })
const supabase = await createClient()
const since = new Date(Date.now() - 60_000).toISOString()
const { count: recentCount } = await supabase
.from('audit_log')
.select('id', { count: 'exact', head: true })
.eq('changed_by', user.id)
.eq('changed_by', session.sub)
.eq('action', 'ai_triage_suggest')
.gte('changed_at', since)
if ((recentCount ?? 0) > 0)
+7 -9
View File
@@ -2,6 +2,7 @@ export const dynamic = 'force-dynamic'
import { NextRequest, NextResponse } from 'next/server'
import { createClient } from '@/lib/supabase/server'
import { getSession } from '@/lib/auth/get-session'
import { createInAppNotifications } from '@/lib/notifications/in-app'
export async function POST(
@@ -9,16 +10,13 @@ export async function POST(
{ params }: { params: Promise<{ id: string }> }
) {
const { id } = await params
const supabase = await createClient()
const { data: { user }, error: authError } = await supabase.auth.getUser()
if (authError || !user) return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
const { data: profile } = await supabase
.from('users').select('role').eq('id', user.id).single()
if (!profile || !['hse', 'admin'].includes(profile.role))
const session = await getSession()
if (!session) return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
if (!['hse', 'admin'].includes(session.role))
return NextResponse.json({ error: 'Forbidden' }, { status: 403 })
const supabase = await createClient()
const { data: incident } = await supabase
.from('incidents')
.select('status, reference_no, reported_by')
@@ -49,7 +47,7 @@ export async function POST(
p_table_name: 'incidents',
p_record_id: id,
p_action: 'closed',
p_new_value: { status: 'closed', closed_at: closedAt, closed_by: user.id },
p_new_value: { status: 'closed', closed_at: closedAt, closed_by: session.sub },
})
if (incident.reported_by) {
+12 -17
View File
@@ -2,22 +2,20 @@ export const dynamic = 'force-dynamic'
import { NextRequest, NextResponse } from 'next/server'
import { createClient } from '@/lib/supabase/server'
import { getSession } from '@/lib/auth/get-session'
export async function POST(
request: NextRequest,
{ params }: { params: Promise<{ id: string }> }
) {
const { id } = await params
const supabase = await createClient()
const { data: { user }, error: authError } = await supabase.auth.getUser()
if (authError || !user) return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
const { data: profile } = await supabase
.from('users').select('role').eq('id', user.id).single()
if (!profile || !['hse', 'admin'].includes(profile.role))
const session = await getSession()
if (!session) return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
if (!['hse', 'admin'].includes(session.role))
return NextResponse.json({ error: 'Forbidden' }, { status: 403 })
const supabase = await createClient()
const { data: incident } = await supabase
.from('incidents').select('status').eq('id', id).single()
if (!incident) return NextResponse.json({ error: 'Not found' }, { status: 404 })
@@ -38,7 +36,7 @@ export async function POST(
.from('investigations')
.insert({
incident_id: id,
investigator_id: user.id,
investigator_id: session.sub,
method,
findings_text: body.findings_text ?? null,
root_cause_summary: body.root_cause_summary ?? null,
@@ -73,16 +71,13 @@ export async function PATCH(
{ params }: { params: Promise<{ id: string }> }
) {
const { id } = await params
const supabase = await createClient()
const { data: { user }, error: authError } = await supabase.auth.getUser()
if (authError || !user) return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
const { data: profile } = await supabase
.from('users').select('role').eq('id', user.id).single()
if (!profile || !['hse', 'admin'].includes(profile.role))
const session = await getSession()
if (!session) return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
if (!['hse', 'admin'].includes(session.role))
return NextResponse.json({ error: 'Forbidden' }, { status: 403 })
const supabase = await createClient()
const body = await request.json()
const { investigation_id, complete, ...fields } = body
+6 -7
View File
@@ -2,6 +2,7 @@ export const dynamic = 'force-dynamic'
import { NextRequest, NextResponse } from 'next/server'
import { createClient } from '@/lib/supabase/server'
import { getSession } from '@/lib/auth/get-session'
import { buildJkkp6Pdf, buildJkkp7Pdf, type JkkpIncident } from '@/lib/pdf/jkkp'
import { computeDoshObligation } from '@/lib/incidents/dosh'
@@ -14,15 +15,13 @@ export async function GET(
if (form !== 'jkkp6' && form !== 'jkkp7')
return NextResponse.json({ error: 'form must be jkkp6 or jkkp7' }, { status: 422 })
const supabase = await createClient()
const { data: { user }, error: authError } = await supabase.auth.getUser()
if (authError || !user) return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
const { data: profile } = await supabase
.from('users').select('role').eq('id', user.id).single()
if (!profile || !['hse', 'admin'].includes(profile.role))
const session = await getSession()
if (!session) return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
if (!['hse', 'admin'].includes(session.role))
return NextResponse.json({ error: 'Forbidden' }, { status: 403 })
const supabase = await createClient()
const { data: incident } = await supabase
.from('incidents')
.select(`
+6 -7
View File
@@ -1,17 +1,16 @@
import { NextResponse } from 'next/server'
import { createClient } from '@/lib/supabase/server'
import { getSession } from '@/lib/auth/get-session'
export const dynamic = 'force-dynamic'
export async function GET(_req: Request, { params }: { params: Promise<{ id: string }> }) {
const { id } = await params
const supabase = await createClient()
const { data, error: authError } = await supabase.auth.getUser()
if (authError || !data?.user) return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
const user = data.user
const session = await getSession()
if (!session) return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
const { data: profile } = await supabase.from('users').select('role, site_id').eq('id', user.id).single()
const role = profile?.role ?? ''
const supabase = await createClient()
const role = session.role
const { data: incident, error } = await supabase
.from('incidents')
@@ -33,7 +32,7 @@ export async function GET(_req: Request, { params }: { params: Promise<{ id: str
}
const reporter = incident.reporter as unknown as { id: string } | null
const isOwner = reporter?.id === user.id
const isOwner = reporter?.id === session.sub
const isSiteStaff = ['hse', 'supervisor', 'admin'].includes(role)
if (!isOwner && !isSiteStaff) {
return NextResponse.json({ error: 'Forbidden' }, { status: 403 })
+6 -6
View File
@@ -2,6 +2,7 @@ export const dynamic = 'force-dynamic'
import { NextRequest, NextResponse } from 'next/server'
import { createClient } from '@/lib/supabase/server'
import { getSession } from '@/lib/auth/get-session'
import { embedText } from '@/lib/claude/embed'
import { getApiKey } from '@/lib/settings'
@@ -10,14 +11,13 @@ export async function GET(
{ params }: { params: Promise<{ id: string }> }
) {
const { id } = await params
const supabase = await createClient()
const { data: { user }, error: authError } = await supabase.auth.getUser()
if (authError || !user) return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
const { data: profile } = await supabase.from('users').select('role').eq('id', user.id).single()
if (!profile || !['hse', 'admin'].includes(profile.role))
const session = await getSession()
if (!session) return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
if (!['hse', 'admin'].includes(session.role))
return NextResponse.json({ error: 'Forbidden' }, { status: 403 })
const supabase = await createClient()
const googleAiKey = await getApiKey(supabase, 'GOOGLE_AI_API_KEY')
const { data: incident } = await supabase
+8 -10
View File
@@ -2,6 +2,7 @@ export const dynamic = 'force-dynamic'
import { NextRequest, NextResponse } from 'next/server'
import { createClient } from '@/lib/supabase/server'
import { getSession } from '@/lib/auth/get-session'
interface TriageBody {
severity: number
@@ -17,16 +18,13 @@ export async function PATCH(
{ params }: { params: Promise<{ id: string }> }
) {
const { id } = await params
const supabase = await createClient()
const { data: { user }, error: authError } = await supabase.auth.getUser()
if (authError || !user) return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
const { data: profile } = await supabase
.from('users').select('role').eq('id', user.id).single()
if (!profile || !['hse', 'admin'].includes(profile.role))
const session = await getSession()
if (!session) return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
if (!['hse', 'admin'].includes(session.role))
return NextResponse.json({ error: 'Forbidden' }, { status: 403 })
const supabase = await createClient()
const body: TriageBody = await request.json()
if (body.severity < 1 || body.severity > 5)
return NextResponse.json({ error: 'severity must be 15' }, { status: 422 })
@@ -46,7 +44,7 @@ export async function PATCH(
is_dangerous_occurrence: body.is_dangerous_occurrence,
is_occupational_disease: body.is_occupational_disease,
triage_notes: body.triage_notes ?? null,
triaged_by: user.id,
triaged_by: session.sub,
triaged_at: new Date().toISOString(),
status: 'triaged',
})
@@ -58,7 +56,7 @@ export async function PATCH(
p_table_name: 'incidents',
p_record_id: id,
p_action: 'triage',
p_new_value: { severity: body.severity, status: 'triaged', triaged_by: user.id },
p_new_value: { severity: body.severity, status: 'triaged', triaged_by: session.sub },
})
return NextResponse.json({ ok: true })