feat: 追溯码客户端预览(TOTP式令牌保护,不激活不计数,可切换激活状态预览)

This commit is contained in:
Nixevol
2026-07-12 23:16:37 +08:00
parent 8fd417aa87
commit c1d8fb9ca4
17 changed files with 696 additions and 191 deletions
@@ -0,0 +1,28 @@
import { createHmac, timingSafeEqual } from 'crypto';
// 追溯码预览令牌:类 TOTP 的时间窗口 HMAC 令牌。
// 周期 10 分钟;校验时接受「当前窗口 + 上一窗口」,即令牌实际有效 10~20 分钟。
// 无状态(不落库/不进 Redis),密钥复用 JWT_SECRET,后台随取随用、自动随时间轮换,
// 防止预览地址被打印/转发后长期有效。
export const PREVIEW_PERIOD_MS = 600_000;
const TOKEN_HEX_LEN = 16;
function tokenForWindow(secret: string, window: number): string {
return createHmac('sha256', secret).update(`preview:${window}`).digest('hex').slice(0, TOKEN_HEX_LEN);
}
export function currentPreviewToken(secret: string, now = Date.now()): string {
return tokenForWindow(secret, Math.floor(now / PREVIEW_PERIOD_MS));
}
export function isValidPreviewToken(secret: string, token: string | undefined, now = Date.now()): boolean {
if (!token || token.length !== TOKEN_HEX_LEN) return false;
const window = Math.floor(now / PREVIEW_PERIOD_MS);
const provided = Buffer.from(token, 'utf8');
// 当前窗口 + 上一窗口(宽限期),常量时间比较防时序侧信道
for (const w of [window, window - 1]) {
const expected = Buffer.from(tokenForWindow(secret, w), 'utf8');
if (provided.length === expected.length && timingSafeEqual(provided, expected)) return true;
}
return false;
}