/** * Finding: S-04 * * Newsletter double opt-in. Subscribing sends exactly one confirmation email; nothing else is * sent until the link is clicked. Tokens are random, stored only as a SHA-256 hash, single-use * and expire after 48 hours, so a leaked database can't be used to confirm addresses. */ import { createHash, randomBytes } from "node:crypto"; const TOKEN_TTL_MS = 48 * 60 * 60 * 1000; export type PendingSubscription = { emailHash: string; tokenHash: string; expiresAt: Date }; export const sha256 = (value: string) => createHash("sha256").update(value).digest("hex"); export function issueConfirmation(email: string): { token: string; record: PendingSubscription } { const token = randomBytes(32).toString("base64url"); return { token, // goes into the email link only, never stored record: { emailHash: sha256(email.trim().toLowerCase()), tokenHash: sha256(token), expiresAt: new Date(Date.now() + TOKEN_TTL_MS), }, }; } export const confirmationUrl = (token: string) => `https://www.cynbit.in/newsletter/confirm?t=${encodeURIComponent(token)}`; /** * The confirm endpoint consumes the token atomically, so a link can't be replayed: * * UPDATE "Subscriber" SET "confirmedAt" = now(), "tokenHash" = NULL * WHERE "tokenHash" = $1 AND "expiresAt" > now() AND "confirmedAt" IS NULL * RETURNING id; * * The subscribe endpoint responds identically whether or not the address already exists, * so it can't be used to discover who is subscribed. */ export const CONFIRM_SQL = ` UPDATE "Subscriber" SET "confirmedAt" = now(), "tokenHash" = NULL WHERE "tokenHash" = $1 AND "expiresAt" > now() AND "confirmedAt" IS NULL RETURNING id`;