统一模板包 visual 契约并补齐完成证据;修复 release 版本一致性、管理员 token 撤销、CORS 与默认品牌配置;收敛依赖安全风险并完成全量回归验证。
45 lines
1.5 KiB
TypeScript
45 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";
|
|
tokenVersion?: number;
|
|
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,
|
|
tokenVersion: identity.tokenVersion ?? 0,
|
|
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;
|
|
}
|