customer/src/modules/kits/links.ts
Peppa 3b808eb937
All checks were successful
peppa/lint lint: success за 1с
peppa/typecheck typecheck: success за 2с
deploy / deploy (pull_request) Successful in 24s
peppa/test test: success за 18с
peppa/build build: success за 1с
ci / checks (pull_request) Successful in 31s
CLT-5: цифровые комплекты — генерация XLSX, проверка, подписанные ссылки выдачи
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-15 14:07:35 +05:00

23 lines
1.1 KiB
TypeScript

import { createHmac, timingSafeEqual } from "node:crypto";
export const LINK_TTL_MS = 15 * 60 * 1000;
const mac = (secret: string, fileId: string, uid: string, exp: number): Buffer =>
createHmac("sha256", secret).update(`${fileId}.${uid}.${exp}`).digest();
export function signLink(secret: string, fileId: string, uid: string, now: number): string {
const exp = Math.floor((now + LINK_TTL_MS) / 1000);
const sig = mac(secret, fileId, uid, exp).toString("hex");
return `/api/kits/files/${fileId}?uid=${uid}&exp=${exp}&sig=${sig}`;
}
export type LinkCheck = "ok" | "invalid" | "expired";
export function checkLink(secret: string, fileId: string, q: Record<string, unknown>, now: number): LinkCheck {
const { uid, exp, sig } = q;
if (typeof uid !== "string" || typeof exp !== "string" || typeof sig !== "string") return "invalid";
if (!/^\d{1,12}$/.test(exp) || !/^[0-9a-f]{64}$/.test(sig)) return "invalid";
if (!timingSafeEqual(mac(secret, fileId, uid, Number(exp)), Buffer.from(sig, "hex"))) return "invalid";
return Number(exp) * 1000 < now ? "expired" : "ok";
}