140 lines
4.4 KiB
TypeScript
140 lines
4.4 KiB
TypeScript
/**
|
|
* Shared unsubscribe-token helper for marketing sequence mails.
|
|
*
|
|
* Sequence emails carry `/unsubscribe/<token>` links. The token is the
|
|
* authentication boundary for one-click unsubscribe, so web routes and worker
|
|
* mail producers must sign and verify the same payload shape.
|
|
*/
|
|
|
|
import { createHmac, timingSafeEqual } from "node:crypto";
|
|
|
|
type EnvRecord = Record<string, string | undefined>;
|
|
|
|
export interface UnsubscribeTokenPayload {
|
|
/** EmailSequenceRun.id this token unsubscribes from. */
|
|
runId: string;
|
|
/** Lead.id (may be null for tenant-scoped sequences). */
|
|
leadId: string | null;
|
|
/** Tenant.id (may be null for lead-scoped sequences). */
|
|
tenantId: string | null;
|
|
/** Issued-at unix seconds, used for debugging only. */
|
|
iat: number;
|
|
}
|
|
|
|
export interface SignUnsubscribeTokenInput {
|
|
runId: string;
|
|
leadId?: string | null;
|
|
tenantId?: string | null;
|
|
now?: () => Date;
|
|
secret?: string;
|
|
env?: EnvRecord;
|
|
}
|
|
|
|
export interface VerifyUnsubscribeTokenOptions {
|
|
secret?: string;
|
|
env?: EnvRecord;
|
|
}
|
|
|
|
export class UnsubscribeTokenSecretMissingError extends Error {
|
|
override readonly name = "UnsubscribeTokenSecretMissingError";
|
|
|
|
constructor() {
|
|
super("MARKETING_TOKEN_SECRET env var is not set; cannot sign or verify unsubscribe tokens.");
|
|
}
|
|
}
|
|
|
|
const TOKEN_VERSION = "u1";
|
|
const MIN_SECRET_BYTES = 32;
|
|
|
|
function getSecret(override?: string, env?: EnvRecord): Buffer {
|
|
const raw = override ?? env?.MARKETING_TOKEN_SECRET ?? env?.LEAD_CONVERSION_SECRET;
|
|
if (!raw || raw.length === 0) throw new UnsubscribeTokenSecretMissingError();
|
|
if (raw.length < MIN_SECRET_BYTES) throw new UnsubscribeTokenSecretMissingError();
|
|
return Buffer.from(raw, "utf8");
|
|
}
|
|
|
|
function b64uEncode(input: Buffer | string): string {
|
|
const buf = Buffer.isBuffer(input) ? input : Buffer.from(input, "utf8");
|
|
return buf.toString("base64url");
|
|
}
|
|
|
|
function b64uDecode(input: string): Buffer | null {
|
|
if (!/^[A-Za-z0-9_-]+$/u.test(input)) return null;
|
|
try {
|
|
return Buffer.from(input, "base64url");
|
|
} catch {
|
|
return null;
|
|
}
|
|
}
|
|
|
|
function nowSec(now?: () => Date): number {
|
|
return Math.floor((now ? now() : new Date()).getTime() / 1000);
|
|
}
|
|
|
|
export function signUnsubscribeToken(input: SignUnsubscribeTokenInput): string {
|
|
if (!input.runId || typeof input.runId !== "string") {
|
|
throw new TypeError("signUnsubscribeToken: runId required");
|
|
}
|
|
const secret = getSecret(input.secret, input.env);
|
|
const payload: UnsubscribeTokenPayload = {
|
|
runId: input.runId,
|
|
leadId: input.leadId ?? null,
|
|
tenantId: input.tenantId ?? null,
|
|
iat: nowSec(input.now),
|
|
};
|
|
const payloadB64 = b64uEncode(JSON.stringify(payload));
|
|
const sig = createHmac("sha256", secret).update(`${TOKEN_VERSION}.${payloadB64}`).digest();
|
|
return `${TOKEN_VERSION}.${payloadB64}.${b64uEncode(sig)}`;
|
|
}
|
|
|
|
export function verifyUnsubscribeToken(
|
|
token: string | null | undefined,
|
|
options: VerifyUnsubscribeTokenOptions = {}
|
|
): UnsubscribeTokenPayload | null {
|
|
if (!token || typeof token !== "string") return null;
|
|
const parts = token.split(".");
|
|
if (parts.length !== 3) return null;
|
|
const [version, payloadB64, sigB64] = parts;
|
|
if (version !== TOKEN_VERSION) return null;
|
|
let secret: Buffer;
|
|
try {
|
|
secret = getSecret(options.secret, options.env);
|
|
} catch {
|
|
return null;
|
|
}
|
|
const expected = createHmac("sha256", secret).update(`${version}.${payloadB64}`).digest();
|
|
const actual = b64uDecode(sigB64);
|
|
if (!actual || actual.length !== expected.length) return null;
|
|
if (!timingSafeEqual(actual, expected)) return null;
|
|
const payloadBuf = b64uDecode(payloadB64);
|
|
if (!payloadBuf) return null;
|
|
let parsed: unknown;
|
|
try {
|
|
parsed = JSON.parse(payloadBuf.toString("utf8"));
|
|
} catch {
|
|
return null;
|
|
}
|
|
if (!parsed || typeof parsed !== "object") return null;
|
|
const rec = parsed as Record<string, unknown>;
|
|
if (typeof rec.runId !== "string" || rec.runId.length === 0) return null;
|
|
return {
|
|
runId: rec.runId,
|
|
leadId: typeof rec.leadId === "string" ? rec.leadId : null,
|
|
tenantId: typeof rec.tenantId === "string" ? rec.tenantId : null,
|
|
iat: typeof rec.iat === "number" ? rec.iat : 0,
|
|
};
|
|
}
|
|
|
|
export function buildUnsubscribeUrl(args: {
|
|
baseUrl: string;
|
|
runId: string;
|
|
leadId?: string | null;
|
|
tenantId?: string | null;
|
|
secret?: string;
|
|
now?: () => Date;
|
|
}): string {
|
|
const token = signUnsubscribeToken(args);
|
|
const base = args.baseUrl.replace(/\/+$/, "");
|
|
return `${base}/unsubscribe/${token}`;
|
|
}
|