57 lines
2.1 KiB
TypeScript
57 lines
2.1 KiB
TypeScript
import { UnauthorizedException } from "@nestjs/common";
|
|
import { createHmac, timingSafeEqual } from "node:crypto";
|
|
import { isPlaceholderSecret } from "./runtime-config.js";
|
|
|
|
type Identity = {
|
|
subject: string;
|
|
brandId: string;
|
|
role: "customer" | "admin";
|
|
tokenVersion?: number;
|
|
exp: number;
|
|
};
|
|
|
|
let warnedAboutPlaceholderSecret = false;
|
|
|
|
function secret(): string {
|
|
const value = process.env.SESSION_SECRET;
|
|
if (!value || value.length < 32) throw new UnauthorizedException("服务端会话密钥未正确配置");
|
|
if (isPlaceholderSecret(value)) {
|
|
// 生产环境已在启动时 fail fast;这里保留二次防线,避免绕过 createApp 的调用方签发弱 token。
|
|
if (process.env.NODE_ENV === "production")
|
|
throw new UnauthorizedException("服务端会话密钥未正确配置");
|
|
if (!warnedAboutPlaceholderSecret) {
|
|
warnedAboutPlaceholderSecret = true;
|
|
console.warn("[api] SESSION_SECRET 仍是示例占位符,仅可用于本地开发");
|
|
}
|
|
}
|
|
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;
|
|
}
|