/** * JWT 工具 —— 签发与校验用户令牌。 * * HS256 + 对称密钥:密钥来自 JWT_SECRET 环境变量(生产必须设置), * 缺省回退到开发默认值并打印警告(避免本地启动失败)。 */ import jwt from "jsonwebtoken"; /** 开发默认密钥(仅本地/测试使用,生产必须用 JWT_SECRET 覆盖)。 */ const DEV_SECRET = "perler-lab-dev-secret-do-not-use-in-prod"; function resolveSecret(): string { const secret = process.env["JWT_SECRET"]; if (!secret || secret === "") { if (process.env["NODE_ENV"] !== "test") { console.warn( "[auth] JWT_SECRET 未设置,使用开发默认密钥 —— 生产环境必须通过环境变量配置!", ); } return DEV_SECRET; } return secret; } const SECRET = resolveSecret(); /** JWT 载荷(sub = 用户 ID)。 */ export interface JwtPayload { sub: string; phone: string; } /** 签发访问令牌(默认 30 天,供移动端持续登录)。 */ export function signToken(payload: JwtPayload): string { return jwt.sign(payload, SECRET, { expiresIn: "30d" }); } /** 校验令牌:成功返回载荷,失败返回 undefined。 */ export function verifyToken(token: string): JwtPayload | undefined { try { const decoded = jwt.verify(token, SECRET); if (typeof decoded !== "object" || decoded === null) return undefined; const d = decoded as Record; if (typeof d["sub"] !== "string" || typeof d["phone"] !== "string") return undefined; return { sub: d["sub"], phone: d["phone"] }; } catch { return undefined; } }