// email-validation.org relay for brevo 1.0.0: npx wrangler deploy relay.mjs. MIT licence: see LICENSE. // Generated from the tested sources; do not edit. // integrations/brevo/src/constants.ts var VERSION = "1.0.0"; var USER_AGENT = `email-validation-brevo/${VERSION}`; var BREVO_ORIGIN = "https://api.brevo.com"; var ATTRIBUTES = Object.freeze({ status: "EV_STATUS", reason: "EV_REASON", action: "EV_ACTION", checkedAt: "EV_CHECKED_AT" }); var ATTRIBUTE_NAMES = Object.freeze(Object.values(ATTRIBUTES)); var BREVO_RETRYABLE_STATUSES = Object.freeze([408, 425, 429, 500, 502, 503, 504]); // integrations/brevo/src/core/http.ts var CallError = class extends Error { service; /** HTTP status, or 0 when no answer arrived. */ status; code; /** True when trying again later can succeed (rate limits, outages, network). */ retryable; /** Whole seconds from `Retry-After`, or null. */ retryAfter; requestId; constructor(service, fields, requestId = null) { super(`${service}: ${fields.message} (${fields.code}${requestId ? `, request ${requestId}` : ""})`); this.name = "CallError"; this.service = service; this.status = fields.status; this.code = fields.code; this.retryable = fields.retryable; this.retryAfter = fields.retryAfter ?? null; this.requestId = requestId; } }; function retryAfterSeconds(response, nowMs = Date.now()) { const value = response.headers.get("retry-after")?.trim(); if (!value) return null; if (/^\d+$/.test(value)) return Number(value); const at = Date.parse(value); return Number.isNaN(at) ? null : Math.max(0, Math.ceil((at - nowMs) / 1e3)); } async function send(opts, url, init) { if (new URL(url).origin !== opts.origin) { throw new CallError(opts.service, { status: 0, code: "invalid_request", message: `Refused a request to a host other than ${opts.origin}.`, retryable: false }); } const headers = new Headers(init.headers); headers.set("User-Agent", opts.userAgent); const fetchFn = opts.fetch; let timer; let signal; if (opts.headersOnly) { const controller = new AbortController(); timer = setTimeout( () => controller.abort(new DOMException("The request timed out.", "TimeoutError")), opts.timeoutMs ); signal = controller.signal; } else { signal = AbortSignal.timeout(opts.timeoutMs); } let response; try { response = await fetchFn(url, { ...init, headers, redirect: "manual", signal }); } catch (err) { throw failure(opts.service, err); } finally { if (timer !== void 0) clearTimeout(timer); } if (response.status >= 300 && response.status < 400) { throw new CallError(opts.service, { status: response.status, code: "unexpected_response", message: `Answered with a redirect (HTTP ${response.status}), which is never followed.`, retryable: false }); } return response; } function failure(service, err) { const timedOut = err instanceof Error && (err.name === "TimeoutError" || err.name === "AbortError"); return new CallError(service, { status: 0, code: timedOut ? "timeout" : "connection_error", message: timedOut ? "The request timed out." : "The service could not be reached.", retryable: true }); } async function jsonOrNull(response) { try { return await response.json(); } catch { return null; } } async function readJson(response, service) { let text; try { text = await response.text(); } catch (err) { throw failure(service, err); } try { return JSON.parse(text); } catch { return null; } } function isRecord(value) { return typeof value === "object" && value !== null && !Array.isArray(value); } var realSleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms)); async function withRetries(fn, opts) { for (let attempt = 1; ; attempt++) { try { return await fn(); } catch (err) { const again = err instanceof CallError && err.retryable && (opts.retryIf?.(err) ?? true); if (!again || attempt >= opts.attempts) throw err; await opts.sleep(Math.min(opts.maxWaitS, err.retryAfter ?? 2 ** attempt) * 1e3); } } } // integrations/brevo/src/core/vocabulary.ts var BASE_URLS = Object.freeze({ us: "https://api.email-validation.org", eu: "https://api-eu.email-validation.org" }); var STATUSES = Object.freeze(["valid", "invalid", "catch_all", "unknown", "disposable"]); var ACTIONS = Object.freeze(["send", "send_with_caution", "remove", "retry_later"]); var BULK_JOB_STATUSES = Object.freeze([ "analyzing", "ready", "queued", "running", "cancelling", "finalizing", "completed", "failed", "cancelled", "expired" ]); var TERMINAL_BULK_JOB_STATUSES = Object.freeze(["completed", "failed", "cancelled", "expired"]); var BULK_RESULT_COLUMNS = Object.freeze([ "ev_status", "ev_reason", "ev_action", "ev_free_email", "ev_role_account", "ev_disposable", "ev_catch_all_domain", "ev_did_you_mean", "ev_mx_found", "ev_mx_record", "ev_smtp_provider", "ev_domain_age_days" ]); var ACCOUNT_CODES = Object.freeze(["unauthorized", "insufficient_credits", "forbidden", "key_daily_cap"]); // integrations/brevo/src/core/email-validation.ts var SERVICE = "email-validation"; var DEFAULT_TIMEOUT_MS = 3e4; var RESULTS_PART_BYTES = 8 * 1024 * 1024; function regionOf(value) { if (value === void 0 || value === "" || value === "us") return "us"; if (value === "eu") return "eu"; throw new Error('EV_REGION must be "us" or "eu".'); } function checkKey(name, value) { if (typeof value !== "string" || !/^\S+$/.test(value)) throw new Error(`${name} is missing or holds whitespace.`); return value; } function sharesKey(text, key) { const run = 12; if (key.length < run) return key !== "" && text.includes(key); for (let i = 0; i + run <= key.length; i++) if (text.includes(key.slice(i, i + run))) return true; return false; } function codeOf(value, key) { return typeof value === "string" && /^[a-z][a-z0-9_]{0,63}$/.test(value) && !sharesKey(value, key) ? value : ""; } var PROCESSED_AT = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d{1,9})?Z$/; function requestIdOf(value, key) { return typeof value === "string" && /^req_[A-Za-z0-9]{1,60}$/.test(value) && !sharesKey(value, key) ? value : null; } async function errorFor(response, key) { const body = await jsonOrNull(response); const envelope = isRecord(body) && isRecord(body.error) ? body.error : null; const code = codeOf(envelope?.code, key) || "unexpected_response"; const message = `The API answered HTTP ${response.status}.`; const requestId = requestIdOf(envelope?.request_id, key) ?? requestIdOf(response.headers.get("x-request-id"), key); return new CallError( SERVICE, { status: response.status, code, message, // By status, as SDK_SPEC ยง7.1: an edge error page without our envelope is retried too (never charged). retryable: (response.status === 429 || response.status === 503) && code !== "key_daily_cap", retryAfter: retryAfterSeconds(response) }, requestId ); } function unexpected(status, what) { return new CallError(SERVICE, { status, code: "unexpected_response", message: `The API answered with something other than ${what}.`, retryable: false }); } async function call(config, path, init, query = "", timing = {}) { const origin = BASE_URLS[config.region ?? "us"]; const response = await send( { service: SERVICE, fetch: config.fetch ?? globalThis.fetch, origin, timeoutMs: timing.timeoutMs ?? config.timeoutMs ?? DEFAULT_TIMEOUT_MS, userAgent: config.userAgent, headersOnly: timing.headersOnly }, `${origin}${path}${query}`, { ...init, headers: { Authorization: `Bearer ${config.apiKey}`, ...init.headers } } ); if (!response.ok) throw await errorFor(response, config.apiKey); return response; } async function validateEmail(config, email, options = {}) { const payload = { email }; if (options.timeout !== void 0) payload.timeout = options.timeout; const response = await call(config, "/v1/validate", { method: "POST", headers: { Accept: "application/json", "Content-Type": "application/json" }, body: JSON.stringify(payload) }); const body = await readJson(response, SERVICE); if (!isRecord(body) || !STATUSES.includes(body.status)) throw unexpected(response.status, "a validation result"); const text = (name) => { const value = body[name]; return typeof value === "string" && !sharesKey(value, config.apiKey) ? value : ""; }; const reason = text("reason"); const action = text("action"); const processedAt = text("processed_at"); return { status: body.status, reason: /^[a-z_]{1,64}$/.test(reason) ? reason : "", action: ACTIONS.includes(action) ? action : "", processed_at: PROCESSED_AT.test(processedAt) ? processedAt : "", request_id: requestIdOf(body.request_id, config.apiKey) ?? "" }; } // integrations/brevo/src/brevo.ts var SERVICE2 = "brevo"; var ID_PATTERN = /^[1-9][0-9]{0,15}$/; var CONTACT_FIELDS_ERROR = "Not a Brevo contact id."; function codeOf2(body) { if (!isRecord(body) || typeof body.code !== "string") return null; const code = body.code.trim(); return code !== "" && code.length <= 64 && /^[\w .,'()-]+$/.test(code) ? code : null; } function brevoRetryAfter(response) { const header = retryAfterSeconds(response); if (header !== null) return header; const reset = response.headers.get("x-sib-ratelimit-reset")?.trim(); return reset && /^\d+$/.test(reset) ? Number(reset) : null; } async function errorFor2(response) { const brevoCode = codeOf2(await jsonOrNull(response)); return new CallError(SERVICE2, { status: response.status, code: `http_${response.status}`, message: `Brevo answered HTTP ${response.status}${brevoCode ? ` (${brevoCode})` : ""}.`, retryable: BREVO_RETRYABLE_STATUSES.includes(response.status), retryAfter: brevoRetryAfter(response) }); } async function call2(config, path, init) { const response = await send( { service: SERVICE2, fetch: config.fetch ?? globalThis.fetch, origin: BREVO_ORIGIN, timeoutMs: config.timeoutMs ?? DEFAULT_TIMEOUT_MS, userAgent: USER_AGENT }, `${BREVO_ORIGIN}/v3${path}`, { ...init, headers: { "api-key": config.apiKey, Accept: "application/json", ...init.body === void 0 ? {} : { "Content-Type": "application/json" } } } ); if (!response.ok) throw await errorFor2(response); return response; } function numbers(value) { return Array.isArray(value) ? value.filter((n) => Number.isSafeInteger(n)) : []; } function contactOf(item) { if (!isRecord(item) || !Number.isSafeInteger(item.id) || item.id < 1) return null; return { id: item.id, email: typeof item.email === "string" ? item.email : "", emailBlacklisted: item.emailBlacklisted === true, listUnsubscribed: numbers(item.listUnsubscribed), attributes: isRecord(item.attributes) ? item.attributes : {} }; } async function getContact(config, email) { const query = new URLSearchParams({ identifierType: "email_id" }); try { const response = await call2(config, `/contacts/${encodeURIComponent(email)}?${query}`, { method: "GET" }); return contactOf(await jsonOrNull(response)); } catch (err) { if (err instanceof CallError && err.status === 404) return null; throw err; } } function contactPath(id) { if (!Number.isSafeInteger(id) || id < 1) throw new Error(CONTACT_FIELDS_ERROR); return `/contacts/${id}?${new URLSearchParams({ identifierType: "contact_id" })}`; } async function updateAttributes(config, contactId, attributes) { await call2(config, contactPath(contactId), { method: "PUT", body: JSON.stringify({ attributes }) }); } async function listAttributes(config) { const body = await jsonOrNull(await call2(config, "/contacts/attributes", { method: "GET" })); const items = isRecord(body) && Array.isArray(body.attributes) ? body.attributes : []; return items.flatMap( (a) => isRecord(a) && typeof a.name === "string" ? [ { name: a.name, category: typeof a.category === "string" ? a.category : "", type: typeof a.type === "string" ? a.type : "" } ] : [] ); } async function missingAttributes(config, wrap = (fn) => fn()) { const existing = await wrap(() => listAttributes(config)); const missing = []; for (const name of ATTRIBUTE_NAMES) { const found = existing.find((a) => a.name.toUpperCase() === name); if (!found) missing.push(name); else if (found.category !== "normal" || found.type !== "text") { throw new Error(`The Brevo attribute ${name} exists but is not a normal text attribute: rename or delete it.`); } } return missing; } function statusOf(status) { return STATUSES.includes(status) ? status : "unknown"; } function attributesFor(verdict, checkedAt) { return { [ATTRIBUTES.status]: statusOf(verdict.status), [ATTRIBUTES.reason]: verdict.reason, [ATTRIBUTES.action]: verdict.action, [ATTRIBUTES.checkedAt]: checkedAt }; } var CHECKED_STATUSES = STATUSES.filter((s) => s !== "unknown"); function isChecked(contact) { const status = contact.attributes[ATTRIBUTES.status]; return typeof status === "string" && CHECKED_STATUSES.includes(status); } // integrations/brevo/src/handler.ts var MAX_HELD = 2e3; var HELD = /* @__PURE__ */ new Map(); function trim(held, except) { if (held.size <= MAX_HELD) return; for (const [key, h] of held) { if (h.reason === "maybe_charged" && key !== except) { held.delete(key); return; } } } function hold(held, key) { const mine = { reason: "in_progress" }; held.set(key, mine); trim(held); return mine; } function keepHeld(held, key, mine) { mine.reason = "maybe_charged"; held.delete(key); held.set(key, mine); trim(held, key); } function letGo(held, key, mine) { if (mine.reason === "in_progress" && held.get(key) === mine) held.delete(key); } function mayBeCharged(err) { if (!(err instanceof CallError)) return true; return !(err.status === 429 || err.status === 503 || err.status >= 400 && err.status < 500); } var MIN_SECRET_LENGTH = 32; var SECRET_PATTERN = /^[0-9A-Za-z_-]+$/; var MAX_BODY_BYTES = 32768; var BREVO_TIMEOUT_MS = 3e3; var CHECK_TIMEOUT_MS = 8e3; var CHECK_SERVICE_TIMEOUT_S = 5; var WRITE_RETRY = { attempts: 2, maxWaitS: 1 }; var DEFAULT_RETRY_AFTER_S = 600; var ATTRIBUTES_SEEN = /* @__PURE__ */ new Set(); function answer(status, body, headers = {}) { return new Response(JSON.stringify(body), { status, headers: { "Content-Type": "application/json", "Cache-Control": "no-store", ...headers } }); } async function sameSecret(given, expected) { const encoder = new TextEncoder(); const [a, b] = await Promise.all( [given, expected].map(async (s) => new Uint8Array(await crypto.subtle.digest("SHA-256", encoder.encode(s)))) ); let diff = 0; for (let i = 0; i < 32; i++) diff |= (a?.[i] ?? 0) ^ (b?.[i] ?? 0); return diff === 0; } async function keyId(key) { const digest = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(key)); return Array.from(new Uint8Array(digest), (b) => b.toString(16).padStart(2, "0")).join(""); } function configOf(env) { try { const config = { evKey: checkKey("EV_API_KEY", env.EV_API_KEY), brevoKey: checkKey("BREVO_API_KEY", env.BREVO_API_KEY), secret: checkKey("RELAY_SECRET", env.RELAY_SECRET), region: regionOf(env.EV_REGION), listId: env.BREVO_LIST_ID ? env.BREVO_LIST_ID : null }; if (config.secret.length < MIN_SECRET_LENGTH || !SECRET_PATTERN.test(config.secret)) return null; if (config.listId !== null && !ID_PATTERN.test(config.listId)) return null; return { ...config, listId: config.listId === null ? null : Number(config.listId) }; } catch { return null; } } async function authorized(request, secret) { const path = new URL(request.url).pathname.replace(/\/+$/, ""); const auth = request.headers.get("authorization") ?? ""; const bearer = /^Bearer\s+(\S+)$/i.exec(auth.trim())?.[1] ?? ""; const [byPath, byHeader] = await Promise.all([sameSecret(path, `/${secret}`), sameSecret(bearer, secret)]); return byPath || byHeader; } async function readText(request) { const declared = Number(request.headers.get("content-length") ?? "0"); if (!(declared <= MAX_BODY_BYTES)) return null; const bytes = await readCapped(request, MAX_BODY_BYTES); return bytes === null ? null : new TextDecoder().decode(bytes); } async function readCapped(request, max) { if (!request.body) return new Uint8Array(0); const reader = request.body.getReader(); const chunks = []; let size = 0; for (; ; ) { const { done, value } = await reader.read(); if (done) break; size += value.byteLength; if (size > max) { await reader.cancel().catch(() => { }); return null; } chunks.push(value); } const out = new Uint8Array(size); let offset = 0; for (const chunk of chunks) { out.set(chunk, offset); offset += chunk.byteLength; } return out; } function deliveryOf(text) { let body; try { body = JSON.parse(text); } catch { return null; } if (Array.isArray(body)) return { batched: true }; if (!isRecord(body) || typeof body.event !== "string") return null; const raw = body.list_id; const ids = Array.isArray(raw) ? raw : raw === void 0 ? [] : [raw]; const lists = []; for (const id of ids) { const n = typeof id === "string" && ID_PATTERN.test(id) ? Number(id) : id; if (!Number.isSafeInteger(n) || n < 1) return null; lists.push(n); } return { batched: false, event: body.event, email: typeof body.email === "string" ? body.email : "", lists }; } function beforeCheck(err) { if (err instanceof CallError) { const fields = { error: err.code, service: err.service, request_id: err.requestId }; if (err.retryable) { const wait = String(err.retryAfter ?? DEFAULT_RETRY_AFTER_S); return answer(429, { ...fields, retry: true }, { "Retry-After": wait }); } return answer(422, { ...fields, retry: false }); } return answer(422, { error: "relay_error", retry: false }); } function handle(request, env, deps = {}) { const work = serve(request, env, deps); deps.waitUntil?.(work.catch(() => { })); return work; } async function serve(request, env, deps) { const config = configOf(env); if (!config) return answer(500, { error: "relay_not_configured" }); if (!await authorized(request, config.secret)) return answer(404, { error: "not_found" }); if (request.method === "GET" || request.method === "HEAD") return answer(200, { result: "ok" }); if (request.method !== "POST") return answer(405, { error: "method_not_allowed" }, { Allow: "GET, POST" }); const text = await readText(request); if (text === null) return answer(400, { error: "invalid_request" }); const delivery = deliveryOf(text); if (delivery === null) return answer(400, { error: "invalid_request" }); if (delivery.batched) return answer(200, { result: "ignored", reason: "batched" }); if (delivery.event !== "list_addition") return answer(200, { result: "ignored", reason: "not_list_addition" }); if (config.listId !== null && !delivery.lists.includes(config.listId)) { return answer(200, { result: "ignored", reason: "other_list" }); } const email = delivery.email.trim(); if (email === "") return answer(200, { result: "skipped", reason: "no_email" }); const id = await keyId(config.brevoKey); const key = `${id}:${await keyId(email.toLowerCase())}`; const held = deps.held ?? HELD; const holding = held.get(key); if (holding) return answer(200, { result: "skipped", reason: holding.reason }); const mine = hold(held, key); try { return await relay(config, deps, email, id, held, key, mine); } finally { letGo(held, key, mine); } } async function relay(config, deps, email, id, held, key, mine) { const brevo = { apiKey: config.brevoKey, fetch: deps.fetch, timeoutMs: BREVO_TIMEOUT_MS }; let contactId; try { const seen = deps.attributesSeen ?? ATTRIBUTES_SEEN; if (!seen.has(id)) { const missing = await missingAttributes(brevo); if (missing.length > 0) return answer(422, { error: "attributes_missing", missing, retry: false }); seen.add(id); } const contact = await getContact(brevo, email); if (contact === null) return answer(200, { result: "skipped", reason: "not_found" }); if (isChecked(contact)) return answer(200, { result: "skipped", reason: "already_checked" }); if (contact.emailBlacklisted) return answer(200, { result: "skipped", reason: "blocklisted" }); contactId = contact.id; } catch (err) { return beforeCheck(err); } let verdict; try { verdict = await validateEmail( { apiKey: config.evKey, region: config.region, fetch: deps.fetch, timeoutMs: CHECK_TIMEOUT_MS, userAgent: USER_AGENT }, email, { timeout: CHECK_SERVICE_TIMEOUT_S } ); } catch (err) { if (!mayBeCharged(err)) return beforeCheck(err); keepHeld(held, key, mine); const code = err instanceof CallError ? err.code : "relay_error"; return answer(200, { result: "not_checked", error: `${code}_maybe_charged`, request_id: err instanceof CallError ? err.requestId : null, retry: false }); } const checkedAt = verdict.processed_at || new Date((deps.now ?? Date.now)()).toISOString(); try { await withRetries(() => updateAttributes(brevo, contactId, attributesFor(verdict, checkedAt)), { ...WRITE_RETRY, sleep: deps.sleep ?? realSleep }); } catch (err) { keepHeld(held, key, mine); const code = err instanceof CallError ? err.code : "relay_error"; return answer(200, { result: "not_saved", status: verdict.status, error: code, retry: false }); } return answer(200, { result: "saved", status: verdict.status, request_id: verdict.request_id }); } // integrations/brevo/src/relay.ts var relay_default = { fetch(request, env, ctx) { return handle(request, env, { waitUntil: (p) => ctx.waitUntil(p) }); } }; export { relay_default as default };