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>
38 lines
1.1 KiB
TypeScript
38 lines
1.1 KiB
TypeScript
import { SignJWT, jwtVerify, type JWTPayload } from 'jose'
|
|
|
|
const SESSION_COOKIE = 'ims_session'
|
|
const SESSION_TTL_SECONDS = 8 * 60 * 60 // 8 hours
|
|
|
|
export { SESSION_COOKIE }
|
|
|
|
function getSecret(): Uint8Array {
|
|
const secret = process.env.JWT_SECRET
|
|
if (!secret) throw new Error('JWT_SECRET not configured')
|
|
return new TextEncoder().encode(secret)
|
|
}
|
|
|
|
export interface SessionPayload {
|
|
sub: string // user id (UUID)
|
|
role: string // user_role enum value
|
|
siteId: string | null
|
|
name: string
|
|
}
|
|
|
|
export async function createSession(payload: SessionPayload): Promise<string> {
|
|
return new SignJWT({ ...payload } as JWTPayload)
|
|
.setProtectedHeader({ alg: 'HS256' })
|
|
.setIssuedAt()
|
|
.setExpirationTime(`${SESSION_TTL_SECONDS}s`)
|
|
.sign(getSecret())
|
|
}
|
|
|
|
/** Verify and decode a JWT. Returns null on invalid/expired. */
|
|
export async function verifySession(token: string): Promise<SessionPayload | null> {
|
|
try {
|
|
const { payload } = await jwtVerify(token, getSecret())
|
|
return payload as unknown as SessionPayload
|
|
} catch {
|
|
return null
|
|
}
|
|
}
|