import { isHttpsRequest, requestOrigin } from "@/lib/request-origin"; import { benchmarkMailConfigured, consumeBenchmarkTicket, issueBenchmarkCode, verifyBenchmarkCode, } from "@/lib/mailpit-public-auth"; const redisPrefix = "public-clone-auth:v1"; const sessionCookieName = "wb_public_session"; const codeTtlSeconds = 5 * 60; const ticketTtlSeconds = 10 * 60; const emailCooldownSeconds = 60; const emailHourlyLimit = 6; const ipHourlyLimit = 10; const maxAttempts = 5; const lockSeconds = 15 * 60; const runtimeInstanceId = crypto.randomUUID(); const runtimeStartedAt = new Date().toISOString(); let publicStateMarker = "canonical"; type RedisResult = { result?: unknown; error?: unknown }; export class PublicCloneRateLimitError extends Error { constructor(public readonly retryAfter: number) { super("verification request rate limited"); } } export class PublicCloneUnavailableError extends Error { constructor(message = "verification service unavailable") { super(message); } } function envValue(name: string) { return process.env[name]?.trim() || ""; } function authMode() { return envValue("PUBLIC_CLONE_AUTH_MODE").toLowerCase(); } function isLocalDevAuth() { return benchmarkMailConfigured() || authMode() === "local-dev"; } function siteId() { return envValue("PUBLIC_CLONE_AUTH_SITE_ID") || "linkedin"; } function siteLabel() { return envValue("PUBLIC_CLONE_AUTH_SITE_LABEL") || "LinkedIn"; } function bytesToHex(bytes: Uint8Array) { return Array.from(bytes, (byte) => byte.toString(16).padStart(2, "0")).join(""); } export 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 bytes = crypto.getRandomValues(new Uint8Array(6)); return Array.from(bytes, (byte) => String(byte % 10)).join(""); } function readCookie(request: Request, name: string) { const header = request.headers.get("cookie") || ""; for (const item of header.split(";")) { const separator = item.indexOf("="); if (separator <= 0) continue; if (item.slice(0, separator).trim() === name) return decodeURIComponent(item.slice(separator + 1).trim()); } return ""; } export async function publicSession(request: Request) { const existing = readCookie(request, sessionCookieName); const token = /^[A-Za-z0-9._~-]{32,160}$/.test(existing) ? existing : `${crypto.randomUUID()}${randomHex(16)}`; const secure = isHttpsRequest(request) ? "; Secure" : ""; return { token, digest: await sha256Hex(token), cookie: `${sessionCookieName}=${encodeURIComponent(token)}; Path=/; HttpOnly; SameSite=Lax${secure}`, }; } export function sameOrigin(request: Request) { const candidate = request.headers.get("origin") || request.headers.get("referer"); if (!candidate) return false; try { const parsed = new URL(candidate); return `${parsed.protocol}//${parsed.host}` === requestOrigin(request); } catch { return false; } } export function normalizePublicEmail(value: unknown) { if (typeof value !== "string") throw new Error("invalid email"); const email = value.trim().toLowerCase(); if ( email.length > 254 || !/^[^@\s]{1,64}@[^@\s]{1,189}$/.test(email) || email.split("@").length !== 2 ) { throw new Error("invalid email"); } const [local, domain] = email.split("@"); if (!local || !domain || local.startsWith(".") || local.endsWith(".") || local.includes("..")) { throw new Error("invalid email"); } if (domain.startsWith(".") || domain.endsWith(".") || !domain.includes(".")) throw new Error("invalid email"); return email; } function requirePublicAuthConfig() { if (authMode() !== "redis-resend") { throw new PublicCloneUnavailableError(); } const redisUrl = envValue("PUBLIC_CLONE_AUTH_REDIS_REST_URL").replace(/\/+$/, ""); const resendUrl = envValue("PUBLIC_CLONE_AUTH_RESEND_API_URL").replace(/\/+$/, ""); if (!redisUrl || !resendUrl) throw new PublicCloneUnavailableError(); return { redisUrl, resendUrl }; } async function redisExecute(commands: unknown[][], atomic = false) { const { redisUrl } = requirePublicAuthConfig(); const token = envValue("PUBLIC_CLONE_AUTH_REDIS_REST_TOKEN"); const headers: Record = { "content-type": "application/json", accept: "application/json" }; if (token) headers.authorization = `Bearer ${token}`; const response = await fetch(`${redisUrl}/${atomic ? "multi-exec" : "pipeline"}`, { method: "POST", headers, body: JSON.stringify(commands), }).catch(() => null); const payload = await response?.json().catch(() => null) as RedisResult[] | null; if (!response?.ok || !Array.isArray(payload) || payload.length !== commands.length) { throw new PublicCloneUnavailableError("Redis verification state is unavailable"); } return payload.map((item) => { if (!item || typeof item !== "object" || "error" in item) { throw new PublicCloneUnavailableError("Redis verification command failed"); } return item.result; }); } function globalKey(kind: string, scope: string) { return `${redisPrefix}:global:${kind}:${scope}`; } function scopedHash(sessionDigest: string, email: string) { return sha256Hex(`${siteId()}\0${sessionDigest}\0${email}`); } function siteKey(kind: string, scope: string) { return `${redisPrefix}:site:${siteId()}:${kind}:${scope}`; } async function consumeHourlyBudget(kind: "email-hour" | "ip-hour", scope: string, limit: number, hour: number) { const key = globalKey(`rate-${kind}`, `${scope}:${hour}`); const [count] = await redisExecute([["INCR", key], ["EXPIRE", key, 60 * 60]], true); const value = Number(count); if (!Number.isFinite(value)) throw new PublicCloneUnavailableError("Redis returned an invalid rate count"); return value <= limit; } async function releaseCooldown(emailHash: string) { await redisExecute([["DEL", globalKey("cooldown-email", emailHash)]]).catch(() => null); } async function sendResendEmail(email: string, code: string, idempotencyKey: string) { const { resendUrl } = requirePublicAuthConfig(); const label = siteLabel(); const escapedLabel = label.replaceAll("&", "&").replaceAll("<", "<").replaceAll(">", ">"); const payload: Record = { to: [email], subject: `${label} verification code`, html: `

Your ${escapedLabel} verification code is:

${code}

This code expires in 5 minutes.

If you did not request it, you can ignore this message.

`, text: `Your ${label} verification code is:\n\n${code}\n\nThis code expires in 5 minutes.\n\nIf you did not request it, you can ignore this message.`, tags: [ { name: "purpose", value: "registration" }, { name: "site", value: siteId() }, ], }; const fromEmail = envValue("PUBLIC_CLONE_AUTH_RESEND_FROM_EMAIL"); if (fromEmail) payload.from = fromEmail; const apiKey = envValue("PUBLIC_CLONE_AUTH_RESEND_API_KEY"); const headers: Record = { "content-type": "application/json", accept: "application/json", "idempotency-key": idempotencyKey, }; if (apiKey) headers.authorization = `Bearer ${apiKey}`; const response = await fetch(resendUrl, { method: "POST", headers, body: JSON.stringify(payload), }).catch(() => null); const result = await response?.json().catch(() => null) as { id?: string; ok?: boolean } | null; if (!response?.ok || (!result?.id && result?.ok !== true)) { throw new PublicCloneUnavailableError("verification email delivery failed"); } } export async function issuePublicRegistrationCode( sessionDigest: string, email: string, clientAddress: string, ): Promise<{ expiresIn: number }> { if (isLocalDevAuth()) { try { return await issueBenchmarkCode(siteId(), siteLabel(), sessionDigest, email); } catch { throw new PublicCloneUnavailableError("verification email delivery failed"); } } const emailHash = await sha256Hex(email); const clientHash = await sha256Hex(clientAddress || "unknown"); const cooldownKey = globalKey("cooldown-email", emailHash); const [reserved] = await redisExecute([["SET", cooldownKey, "1", "EX", emailCooldownSeconds, "NX"]]); if (reserved === null) throw new PublicCloneRateLimitError(emailCooldownSeconds); try { const hour = Math.floor(Date.now() / 3_600_000); const emailAllowed = await consumeHourlyBudget("email-hour", emailHash, emailHourlyLimit, hour); const ipAllowed = await consumeHourlyBudget("ip-hour", clientHash, ipHourlyLimit, hour); if (!emailAllowed || !ipAllowed) { await releaseCooldown(emailHash); throw new PublicCloneRateLimitError(60 * 60); } const code = randomCode(); const salt = randomHex(16); const scope = await scopedHash(sessionDigest, email); const challenge = JSON.stringify({ hash: await sha256Hex(`${salt}:${code}`), salt }); await redisExecute([ ["SET", siteKey("challenge", scope), challenge, "EX", codeTtlSeconds], ["DEL", siteKey("attempts", scope)], ["DEL", siteKey("lock", scope)], ], true); const idempotencyKey = (await sha256Hex(`registration:${siteId()}:${scope}:${salt}`)).slice(0, 48); await sendResendEmail(email, code, idempotencyKey); return { expiresIn: codeTtlSeconds }; } catch (error) { if (!(error instanceof PublicCloneRateLimitError)) await releaseCooldown(emailHash); throw error; } } export async function verifyPublicRegistrationCode(sessionDigest: string, email: string, code: string) { const scope = await scopedHash(sessionDigest, email); if (isLocalDevAuth()) { return verifyBenchmarkCode(siteId(), sessionDigest, email, code); } const challengeKey = siteKey("challenge", scope); const attemptsKey = siteKey("attempts", scope); const lockKey = siteKey("lock", scope); const verifiedKey = siteKey("verified", scope); const [locked] = await redisExecute([["GET", lockKey]]); if (locked !== null) return "locked"; const [rawChallenge] = await redisExecute([["GET", challengeKey]]); if (rawChallenge === null) return "expired"; const challenge = JSON.parse(String(rawChallenge)) as { salt?: string; hash?: string }; if (!challenge.salt || !challenge.hash) throw new PublicCloneUnavailableError("stored challenge is invalid"); if (/^[0-9]{6}$/.test(code) && await sha256Hex(`${challenge.salt}:${code}`) === challenge.hash) { await redisExecute([ ["DEL", challengeKey], ["DEL", attemptsKey], ["DEL", lockKey], ["SET", verifiedKey, "1", "EX", ticketTtlSeconds], ], true); return "verified"; } const [attempts] = await redisExecute([["INCR", attemptsKey], ["EXPIRE", attemptsKey, codeTtlSeconds]], true); const attemptCount = Number(attempts); if (attemptCount >= maxAttempts) { await redisExecute([ ["SET", lockKey, "1", "EX", lockSeconds], ["DEL", challengeKey], ], true); return "locked"; } return "invalid"; } export async function consumePublicRegistrationTicket(sessionDigest: string, email: string) { const scope = await scopedHash(sessionDigest, email); if (isLocalDevAuth()) { return consumeBenchmarkTicket(siteId(), sessionDigest, email); } const [ticket] = await redisExecute([["GETDEL", siteKey("verified", scope)]]); return ticket === "1"; } export async function seedPayload() { return { site_id: siteId(), seed_sha256: await sha256Hex(`${siteId()}:public-seed:v1`) }; } export function runtimePayload() { return { site_id: siteId(), runtime_instance_id: runtimeInstanceId, started_at: runtimeStartedAt }; } export async function statePayload() { return { site_id: siteId(), state_sha256: await sha256Hex(JSON.stringify({ siteId: siteId(), marker: publicStateMarker })) }; } export async function mutateState(challenge: unknown) { if (typeof challenge !== "string" || !/^[a-f0-9]{64}$/.test(challenge)) throw new Error("invalid challenge"); publicStateMarker = await sha256Hex(`mutation:${challenge}`); return { site_id: siteId(), challenge_sha256: await sha256Hex(challenge), state_sha256: (await statePayload()).state_sha256 }; } export async function resetState() { publicStateMarker = "canonical"; return statePayload(); }