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
+36 -53
View File
@@ -1,66 +1,49 @@
import { createServerClient } from '@supabase/ssr'
import { NextResponse, type NextRequest } from 'next/server'
import { ROLE_HOME, isValidRole, type UserRole } from '@/lib/auth/roles'
import { NextRequest, NextResponse } from 'next/server'
import { verifySession } from '@/lib/auth/session'
import { ROLE_HOME, isValidRole } from '@/lib/auth/roles'
const PUBLIC_ROUTES = ['/login', '/auth', '/api/cron', '/api/users', '/forgot-password', '/reset-password', '/api/auth']
const SHARED_ROUTES = ['/report', '/account']
export async function middleware(request: NextRequest) {
let supabaseResponse = NextResponse.next({ request })
const supabase = createServerClient(
process.env.NEXT_PUBLIC_SUPABASE_URL!,
process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY!,
{
cookies: {
getAll() { return request.cookies.getAll() },
setAll(cookiesToSet) {
cookiesToSet.forEach(({ name, value }) => request.cookies.set(name, value))
supabaseResponse = NextResponse.next({ request })
cookiesToSet.forEach(({ name, value, options }) =>
supabaseResponse.cookies.set(name, value, options),
)
},
},
},
)
const { data: { user } } = await supabase.auth.getUser()
const { pathname } = request.nextUrl
const isPublicRoute = pathname.startsWith('/login') || pathname.startsWith('/auth') || pathname.startsWith('/api/cron') || pathname.startsWith('/api/users') || pathname.startsWith('/forgot-password') || pathname.startsWith('/reset-password')
const isSharedRoute = pathname.startsWith('/report') || pathname.startsWith('/account')
// Use NEXT_PUBLIC_APP_URL to ensure redirects use the public host, not Next.js's internal host
const appBase = process.env.NEXT_PUBLIC_APP_URL?.replace(/\/$/, '')
?? `${request.nextUrl.protocol}//${request.nextUrl.host}${request.nextUrl.basePath ?? ''}`
const isPublicRoute = PUBLIC_ROUTES.some(r => pathname.startsWith(r))
const isSharedRoute = SHARED_ROUTES.some(r => pathname.startsWith(r))
if (!user && !isPublicRoute) {
return NextResponse.redirect(
`${appBase}/login?redirect=${encodeURIComponent(pathname + request.nextUrl.search)}`
)
// Derive appUrl from env or request
const appUrl = (process.env.APP_URL ?? `${request.nextUrl.protocol}//${request.nextUrl.host}`).replace(/\/$/, '')
// Read session from cookie (edge-compatible: jose only, no DB)
const token = request.cookies.get('ims_session')?.value ?? ''
const session = token ? await verifySession(token) : null
if (!session) {
if (isPublicRoute) return NextResponse.next()
const loginUrl = new URL(`${appUrl}/login`)
loginUrl.searchParams.set('redirect', pathname)
return NextResponse.redirect(loginUrl)
}
if (user && (pathname === '/' || pathname === '/login')) {
const redirect = request.nextUrl.searchParams.get('redirect')
if (redirect && redirect.startsWith('/') && !redirect.startsWith('//')) {
return NextResponse.redirect(`${appBase}${redirect}`)
}
const { data: profile } = await supabase.from('users').select('role').eq('id', user.id).single()
const role = profile?.role
if (isValidRole(role)) {
return NextResponse.redirect(`${appBase}${ROLE_HOME[role as UserRole]}`)
// Authed user on login or root
if (pathname === '/login' || pathname === '/') {
const redirectParam = request.nextUrl.searchParams.get('redirect')
const safeRedirect = redirectParam && redirectParam.startsWith('/') && !redirectParam.startsWith('//') ? redirectParam : null
const dest = safeRedirect ?? ROLE_HOME[session.role as keyof typeof ROLE_HOME] ?? '/login'
return NextResponse.redirect(new URL(`${appUrl}${dest}`))
}
if (isSharedRoute || isPublicRoute) return NextResponse.next()
// Role-prefix guard (no DB needed — role is in JWT)
if (!pathname.startsWith('/api/') && isValidRole(session.role) && session.role !== 'admin') {
const allowedPrefix = ROLE_HOME[session.role as keyof typeof ROLE_HOME]
if (allowedPrefix && !pathname.startsWith(allowedPrefix)) {
return NextResponse.redirect(new URL(`${appUrl}${allowedPrefix}`))
}
}
if (user && !isPublicRoute && !isSharedRoute && !pathname.startsWith('/api/') && pathname !== '/') {
const { data: profile } = await supabase.from('users').select('role').eq('id', user.id).single()
const role = profile?.role
if (isValidRole(role) && role !== 'admin') {
const allowedPrefix = ROLE_HOME[role as UserRole]
if (!pathname.startsWith(allowedPrefix)) {
return NextResponse.redirect(`${appBase}${allowedPrefix}`)
}
}
}
return supabaseResponse
return NextResponse.next()
}
export const config = {