import { sign, verify } from 'hono/jwt'; const JWT_EXPIRY_SECONDS = 30 * 24 * 60 * 60; export function getJwtSecret(): string { const secret = process.env.JWT_SECRET; if (!secret) throw new Error('JWT_SECRET env var is required'); return secret; } export async function createToken( userId: string, email: string | null, role: string, username: string | null, mustResetPassword: boolean, tokenVersion: number = 0, ): Promise { const now = Math.floor(Date.now() / 1000); return sign( { sub: userId, email, role, username, mustResetPassword, tokenVersion, iat: now, exp: now + JWT_EXPIRY_SECONDS }, getJwtSecret(), ); } export async function verifyToken(token: string): Promise<{ sub: string; email: string | null; role: string; username: string | null; mustResetPassword: boolean; tokenVersion: number; }> { const payload = await verify(token, getJwtSecret(), 'HS256'); return { sub: payload.sub as string, email: (payload.email as string) ?? null, role: (payload.role as string) ?? 'user', username: (payload.username as string) ?? null, mustResetPassword: (payload.mustResetPassword as boolean) ?? false, tokenVersion: (payload.tokenVersion as number) ?? 0, }; }