File size: 5,816 Bytes
9d4a3b0 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 | import { mkdir, readFile, rename, writeFile } from "node:fs/promises";
import path from "node:path";
const codeTtlSeconds = 5 * 60;
const ticketTtlSeconds = 10 * 60;
const maxAttempts = 5;
type Challenge = { salt: string; hash: string; expiresAt: number; attempts: number };
type State = { challenges: Record<string, Challenge>; verified: Record<string, number> };
let stateQueue: Promise<unknown> = Promise.resolve();
function envValue(name: string) {
return process.env[name]?.trim() || "";
}
function bytesToHex(bytes: Uint8Array) {
return Array.from(bytes, (byte) => byte.toString(16).padStart(2, "0")).join("");
}
async function sha256Hex(value: string) {
const digest = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(value));
return bytesToHex(new Uint8Array(digest));
}
function randomHex(bytes: number) {
return bytesToHex(crypto.getRandomValues(new Uint8Array(bytes)));
}
function randomCode() {
const value = crypto.getRandomValues(new Uint32Array(1))[0] % 1_000_000;
return String(value).padStart(6, "0");
}
function stateFile(siteId: string) {
const dataDir = envValue("DATA_DIR") || envValue("WEBSITEBENCH_DATA_DIR") || "/tmp";
return path.join(dataDir, `${siteId}-public-clone-auth.json`);
}
async function loadState(file: string): Promise<State> {
try {
const parsed = JSON.parse(await readFile(file, "utf8")) as Partial<State>;
return {
challenges: parsed.challenges && typeof parsed.challenges === "object" ? parsed.challenges : {},
verified: parsed.verified && typeof parsed.verified === "object" ? parsed.verified : {},
};
} catch (error) {
if ((error as NodeJS.ErrnoException).code !== "ENOENT") throw error;
return { challenges: {}, verified: {} };
}
}
async function mutateState<T>(siteId: string, update: (state: State) => Promise<T> | T): Promise<T> {
const operation = stateQueue.then(async () => {
const file = stateFile(siteId);
await mkdir(path.dirname(file), { recursive: true });
const state = await loadState(file);
const result = await update(state);
const temporary = `${file}.${process.pid}.${randomHex(6)}.tmp`;
await writeFile(temporary, JSON.stringify(state), { encoding: "utf8", mode: 0o600 });
await rename(temporary, file);
return result;
});
stateQueue = operation.catch(() => undefined);
return operation;
}
async function scopeFor(siteId: string, sessionDigest: string, email: string) {
return sha256Hex(`${siteId}\0${sessionDigest}\0${email}`);
}
function mailConfiguration() {
const url = envValue("WEBSITEBENCH_MAIL_API_URL").replace(/\/+$/, "");
const token = envValue("WEBSITEBENCH_MAIL_API_TOKEN");
const from = envValue("WEBSITEBENCH_MAIL_FROM");
if (!url || !token || !from) throw new Error("Mailpit delivery is unavailable");
return { url, token, from };
}
export function benchmarkMailConfigured() {
return Boolean(envValue("WEBSITEBENCH_MAIL_API_URL") && envValue("WEBSITEBENCH_MAIL_API_TOKEN") && envValue("WEBSITEBENCH_MAIL_FROM"));
}
export async function issueBenchmarkCode(siteId: string, siteLabel: string, sessionDigest: string, email: string) {
const code = randomCode();
const salt = randomHex(16);
const scope = await scopeFor(siteId, sessionDigest, email);
await mutateState(siteId, (state) => {
state.challenges[scope] = {
salt,
hash: "",
expiresAt: Date.now() + codeTtlSeconds * 1000,
attempts: 0,
};
return undefined;
});
const hash = await sha256Hex(`${salt}:${code}`);
await mutateState(siteId, (state) => {
const challenge = state.challenges[scope];
if (challenge) challenge.hash = hash;
delete state.verified[scope];
return undefined;
});
const { url, token, from } = mailConfiguration();
const idempotencyKey = (await sha256Hex(`registration:${siteId}:${scope}:${salt}`)).slice(0, 48);
const response = await fetch(url, {
method: "POST",
headers: {
authorization: `Bearer ${token}`,
"content-type": "application/json",
accept: "application/json",
"idempotency-key": idempotencyKey,
},
body: JSON.stringify({
from,
to: [email],
subject: `${siteLabel} verification code`,
text: `Your ${siteLabel} verification code is:\n\n${code}\n\nThis code expires in 5 minutes.`,
}),
}).catch(() => null);
const result = await response?.json().catch(() => null) as { id?: string } | null;
if (!response?.ok || !result?.id) {
await mutateState(siteId, (state) => { delete state.challenges[scope]; });
throw new Error("verification email delivery failed");
}
return { expiresIn: codeTtlSeconds };
}
export async function verifyBenchmarkCode(siteId: string, sessionDigest: string, email: string, code: string) {
const scope = await scopeFor(siteId, sessionDigest, email);
return mutateState(siteId, async (state) => {
const challenge = state.challenges[scope];
if (!challenge || challenge.expiresAt <= Date.now() || !challenge.hash) {
delete state.challenges[scope];
return "expired";
}
if (/^[0-9]{6}$/.test(code) && await sha256Hex(`${challenge.salt}:${code}`) === challenge.hash) {
delete state.challenges[scope];
state.verified[scope] = Date.now() + ticketTtlSeconds * 1000;
return "verified";
}
challenge.attempts += 1;
if (challenge.attempts >= maxAttempts) {
delete state.challenges[scope];
return "locked";
}
return "invalid";
});
}
export async function consumeBenchmarkTicket(siteId: string, sessionDigest: string, email: string) {
const scope = await scopeFor(siteId, sessionDigest, email);
return mutateState(siteId, (state) => {
const expiresAt = state.verified[scope] ?? 0;
delete state.verified[scope];
return expiresAt > Date.now();
});
}
|