All checks were successful
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
23 lines
1.1 KiB
TypeScript
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";
|
|
}
|