Responses had no CSP, the 48-hour download token never changed, and short share slugs could be guessed without a miss limit.
56 lines
1.6 KiB
TypeScript
56 lines
1.6 KiB
TypeScript
import { createHmac, timingSafeEqual } from "crypto";
|
|
|
|
/** How long a mailed export link stays valid after it is issued. */
|
|
export const RULE_EXPORT_TOKEN_TTL_MS = 7 * 24 * 60 * 60 * 1000;
|
|
|
|
function signExportMac(
|
|
ruleId: string,
|
|
version: number,
|
|
exp: number,
|
|
pepper: string,
|
|
): string {
|
|
return createHmac("sha256", pepper)
|
|
.update(`rule-export:${ruleId}:${version}:${exp}`)
|
|
.digest("base64url");
|
|
}
|
|
|
|
function timingSafeStringEqual(left: string, right: string): boolean {
|
|
const expected = Buffer.from(left);
|
|
const actual = Buffer.from(right);
|
|
if (expected.length !== actual.length) return false;
|
|
return timingSafeEqual(expected, actual);
|
|
}
|
|
|
|
export function ruleExportToken(
|
|
ruleId: string,
|
|
pepper: string,
|
|
version: number,
|
|
now = new Date(),
|
|
): string {
|
|
const exp = Math.floor((now.getTime() + RULE_EXPORT_TOKEN_TTL_MS) / 1000);
|
|
const mac = signExportMac(ruleId, version, exp, pepper);
|
|
return `${exp}.${version}.${mac}`;
|
|
}
|
|
|
|
export function ruleExportTokenMatches(
|
|
ruleId: string,
|
|
token: string,
|
|
pepper: string,
|
|
version: number,
|
|
now = new Date(),
|
|
): boolean {
|
|
if (token.length === 0) return false;
|
|
const parts = token.split(".");
|
|
if (parts.length !== 3) return false;
|
|
const exp = Number(parts[0]);
|
|
const tokenVersion = Number(parts[1]);
|
|
const mac = parts[2] ?? "";
|
|
if (!Number.isFinite(exp) || !Number.isInteger(tokenVersion) || mac.length === 0) {
|
|
return false;
|
|
}
|
|
if (tokenVersion !== version) return false;
|
|
if (exp * 1000 <= now.getTime()) return false;
|
|
const expected = signExportMac(ruleId, version, exp, pepper);
|
|
return timingSafeStringEqual(expected, mac);
|
|
}
|