You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

59 lines
1.5 KiB

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

import {
SignJWT,
jwtVerify,
decodeJwt,
type JWTPayload,
} from "jose";
import {
ADMIN_ROLE,
JWT_EXPIRY_SECONDS,
type AdminJwtPayload,
} from "@/lib/constants/auth";
import { unauthorized } from "@/modules/auth/errors";
function getJwtSecret(): Uint8Array {
const secret = process.env.JWT_SECRET;
if (!secret) {
throw new Error("JWT_SECRET 未配置");
}
return new TextEncoder().encode(secret);
}
function toAdminPayload(payload: JWTPayload): AdminJwtPayload {
if (typeof payload.sub !== "string" || payload.role !== ADMIN_ROLE) {
throw unauthorized("无效的令牌载荷");
}
return { sub: payload.sub, role: ADMIN_ROLE };
}
/** 签发管理员 JWT */
export async function signToken(payload: AdminJwtPayload): Promise<string> {
return new SignJWT({ role: payload.role })
.setProtectedHeader({ alg: "HS256" })
.setSubject(payload.sub)
.setIssuedAt()
.setExpirationTime(`${JWT_EXPIRY_SECONDS}s`)
.sign(getJwtSecret());
}
/** 校验管理员 JWT无效/过期/篡改抛 AuthError */
export async function verifyToken(token: string): Promise<AdminJwtPayload> {
try {
const { payload } = await jwtVerify(token, getJwtSecret(), {
algorithms: ["HS256"],
});
return toAdminPayload(payload);
} catch {
throw unauthorized("令牌无效或已过期");
}
}
/** 解码 JWT不校验签名仅调试/解析) */
export function decodeToken(token: string): AdminJwtPayload | null {
try {
return toAdminPayload(decodeJwt(token));
} catch {
return null;
}
}