Add a content security policy and expire mailed export links.
Responses had no CSP, the 48-hour download token never changed, and short share slugs could be guessed without a miss limit.
This commit is contained in:
1 parent
0fe2624002
commit
75649a9a42
18 files changed
+249
-19
No files matched your search
@@ -1,19 +1,55 @@
|
||||
import { createHmac, timingSafeEqual } from "crypto";
|
||||
|
||||
export function ruleExportToken(ruleId: string, pepper: string): string {
|
||||
/** 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}`)
|
||||
.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 expected = Buffer.from(ruleExportToken(ruleId, pepper));
|
||||
const actual = Buffer.from(token);
|
||||
if (expected.length !== actual.length) return false;
|
||||
return timingSafeEqual(expected, actual);
|
||||
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);
|
||||
}
|
||||
Reference in new issue
Block a user