Files
persionalBrand/apps/api/src/auth.ts
T

35 lines
1.5 KiB
TypeScript

import { UnauthorizedException } from "@nestjs/common";
import { createHmac, timingSafeEqual } from "node:crypto";
type Identity = { subject: string; brandId: string; role: "customer" | "admin"; exp: number };
function secret(): string {
const value = process.env.SESSION_SECRET;
if (!value || value.length < 32) throw new UnauthorizedException("服务端会话密钥未正确配置");
return value;
}
export function signIdentity(
identity: Omit<Identity, "exp">,
ttlSeconds = 60 * 60 * 24 * 7,
): string {
const payload = Buffer.from(
JSON.stringify({ ...identity, exp: Math.floor(Date.now() / 1000) + ttlSeconds }),
).toString("base64url");
const signature = createHmac("sha256", secret()).update(payload).digest("base64url");
return `${payload}.${signature}`;
}
export function readIdentity(token: string): Identity {
const [payload, signature] = token.split(".");
if (!payload || !signature) throw new UnauthorizedException("登录态无效");
const expected = createHmac("sha256", secret()).update(payload).digest();
const actual = Buffer.from(signature, "base64url");
if (actual.length !== expected.length || !timingSafeEqual(actual, expected))
throw new UnauthorizedException("登录态无效");
const identity = JSON.parse(Buffer.from(payload, "base64url").toString("utf8")) as Identity;
if (!identity.exp || identity.exp < Math.floor(Date.now() / 1000))
throw new UnauthorizedException("登录态已过期");
return identity;
}