// SPDX-License-Identifier: MIT // // MIT License // // Copyright (c) 2026 Email Validation LLC // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. /* * email-validation.org for ConvertFlow, in the visitor's browser (1.0.0). Checks the address typed into a * ConvertFlow form's email field before the form is sent, and shows a message under the field when the address cannot * receive mail, so the visitor can correct it (by default only a definite `invalid` is refused). * * It registers an async validator with ConvertFlow's JavaScript API, `convertflow.validations({ email: fn })`: the * function gets the field's value and answers `true` (allowed), `false` (ConvertFlow's own message) or a string (that * message). ConvertFlow's help centre says such a validator "overrides" the field's own validation, so an empty field * is refused only with `required` (default true; `required: false` for an optional email field). It registers at once * when ConvertFlow's API is ready (`convertflow.person` is set), else on `cfReady`, and again on every later `cfReady` * (a single-page app's `convertflow.start()` reloads the campaigns). * * Never your secret key: only a browser key (API keys → Create key → On a public web page: Validate addresses only, * your site in its allowed origins and a daily credit cap, both required). Any other key sends nothing and one console * warning says so. Plain JavaScript, no dependencies, no build step: * * * * * Fails open: no key, a value that is not a string, an error answer, a redirect, a network failure, no answer within * `timeoutMs`, anything unexpected: the address is allowed. A check waits `waitMs` (400) after the last value before it * is sent, so a validation run while the visitor types costs nothing (the call it replaces answers `true`). One request * per distinct address on a page; an answer is kept for the page (500 addresses at most), a check that got no answer is * asked again. Nothing is written to the console but those warnings, so an address is never logged. */ (() => { /** @type {any} */ const root = typeof window !== 'undefined' ? window : globalThis; const VERSION = '1.0.0'; const ORIGINS = { us: 'https://api.email-validation.org', eu: 'https://api-eu.email-validation.org' }; const STATUSES = ['valid', 'invalid', 'catch_all', 'unknown', 'disposable']; /** The statuses a field may refuse; `valid` and `unknown` are always allowed. */ const BLOCKABLE = ['invalid', 'disposable', 'catch_all']; /** The sentence shown under the field, by status (the same as our other browser packages' defaults). */ const MESSAGES = { invalid: 'This address cannot receive email. Please check it for typos.', disposable: 'Please use a permanent email address, not a disposable one.', catch_all: 'We could not confirm that this address can receive email. Please use another address.', }; const NOT_BROWSER_KEY_WARNING = 'email-validation: Not a browser key; nothing is checked in the browser.'; const BAD_OPTIONS_WARNING = 'email-validation: ConvertFlow options refused: '; const REGISTER_FAILED_WARNING = 'email-validation: ConvertFlow did not take the email validator; nothing is checked.'; // A browser key carries the word `browser` right after `ev_live_` and the 22-character account part; only our server // mints one, and only for a key limited to Validate, allowed origins and a daily credit cap. const BROWSER_KEY = /^ev_live_[0-9A-Za-z]{22}browser[0-9A-Za-z]{50}$/; /** Seconds our API may spend on a check; a longer check comes back as a free `unknown`. */ const SERVER_TIMEOUT_S = 5; const DEFAULT_TIMEOUT_MS = 8000; /** How long a check waits after the last value before it is sent: a validation run while typing sends nothing. */ const DEFAULT_WAIT_MS = 400; const MAX_REMEMBERED = 500; // after a 429 or 503: Retry-After, 30 seconds without one, at most 300 const DEFAULT_PAUSE_S = 30; const MAX_PAUSE_S = 300; /** @param {unknown} v @returns {v is Record} */ function isObject(v) { return v !== null && typeof v === 'object' && !Array.isArray(v); } /** * Whether a value is worth a check: something@domain.tld with no spaces, no control characters and nothing of a link * (`:` anywhere; `/`, `?` or `#` in the domain; a `/` that starts or ends the local part, or two together): a link * with an `@` in it, or a `mailto:`, is never sent. A `/` inside the local part (`first/last@example.com`) is allowed, * as RFC 5322 allows it. * @param {unknown} value * @returns {value is string} */ function looksLikeAddress(value) { if (typeof value !== 'string') return false; const v = value.trim(); return v.length <= 254 && !/\p{Cc}/u.test(v) && /^[^\s@:/]+(?:\/[^\s@:/]+)*@[^\s@:/?#]+\.[^\s@.:/?#]{2,}$/.test(v); } /** @param {string | null} value @returns {number | null} */ function retryAfterSeconds(value) { if (typeof value !== 'string') return null; const t = value.trim(); if (/^\d+$/.test(t)) return Number(t); if (!/^[A-Za-z]{3}, \d{2} [A-Za-z]{3} \d{4} \d{2}:\d{2}:\d{2} GMT$/.test(t)) return null; const at = Date.parse(t); return Number.isNaN(at) ? null : Math.max(0, Math.ceil((at - Date.now()) / 1000)); } /** * @typedef {{ browserKey?: string, region?: 'us' | 'eu', block?: string[], messages?: Record, * timeoutMs?: number, waitMs?: number, field?: string, required?: boolean }} Options * @typedef {{ block: boolean, status: string | null, message: string | null, checked: boolean, * notChecked: string | null }} Verdict */ /** @param {unknown} options */ function configure(options) { if (!isObject(options)) throw new TypeError('options must be an object'); const region = options.region === undefined ? 'us' : options.region; if (region !== 'us' && region !== 'eu') throw new TypeError('region must be "us" or "eu"'); const block = options.block === undefined ? ['invalid'] : options.block; if (!Array.isArray(block) || block.some((s) => BLOCKABLE.indexOf(s) < 0)) { throw new TypeError(`block must list only ${BLOCKABLE.join(', ')}`); } /** @type {Record} */ const messages = { invalid: MESSAGES.invalid, disposable: MESSAGES.disposable, catch_all: MESSAGES.catch_all }; if (options.messages !== undefined) { if (!isObject(options.messages)) throw new TypeError('messages must be an object'); for (const name of BLOCKABLE) { const m = options.messages[name]; if (m === undefined) continue; if (typeof m !== 'string' || !m.trim()) throw new TypeError(`messages.${name} must be a sentence`); messages[name] = m; } } const timeoutMs = options.timeoutMs === undefined ? DEFAULT_TIMEOUT_MS : options.timeoutMs; if (typeof timeoutMs !== 'number' || !Number.isInteger(timeoutMs) || timeoutMs < 1 || timeoutMs > 60000) { throw new TypeError('timeoutMs must be a whole number of milliseconds from 1 to 60000'); } const waitMs = options.waitMs === undefined ? DEFAULT_WAIT_MS : options.waitMs; if (typeof waitMs !== 'number' || !Number.isInteger(waitMs) || waitMs < 0 || waitMs > 5000) { throw new TypeError('waitMs must be a whole number of milliseconds from 0 to 5000'); } const required = options.required === undefined ? true : options.required; if (typeof required !== 'boolean') throw new TypeError('required must be true or false'); const field = options.field === undefined ? 'email' : options.field; if (typeof field !== 'string' || !/^[A-Za-z0-9_-]{1,100}$/.test(field)) { throw new TypeError('field must be the email field\'s slug, such as "email"'); } if (options.browserKey !== undefined && typeof options.browserKey !== 'string') { throw new TypeError('browserKey must be a string'); } return { key: typeof options.browserKey === 'string' ? options.browserKey.trim() : '', origin: region === 'eu' ? ORIGINS.eu : ORIGINS.us, block: block.slice(), messages: messages, timeoutMs: timeoutMs, waitMs: waitMs, required: required, field: field, }; } /** @param {string | null} notChecked @returns {Verdict} */ function allowed(notChecked) { return { block: false, status: null, message: null, checked: false, notChecked: notChecked }; } /** * The checker for one configuration. Throws a TypeError for bad options; never rejects after that. * @param {Options} options */ function create(options) { const cfg = configure(options); /** @type {Map>} */ const remembered = new Map(); // set after a refused key, no credits, a forbidden origin or the daily cap: nothing more is sent from this page /** @type {string | null} */ let off = null; let pausedUntil = 0; if (cfg.key === '') off = 'no_api_key'; else if (!BROWSER_KEY.test(cfg.key)) { off = 'not_a_browser_key'; try { root.console.warn(NOT_BROWSER_KEY_WARNING); } catch (_) { // no console } } /** @param {string} email @returns {Promise} */ function ask(email) { if (off) return Promise.resolve(allowed(off)); if (Date.now() < pausedUntil) return Promise.resolve(allowed('paused')); const controller = new root.AbortController(); let timedOut = false; const timer = root.setTimeout(() => { timedOut = true; controller.abort(); }, cfg.timeoutMs); /** @type {any} */ let answer; return Promise.resolve() .then(() => root.fetch(`${cfg.origin}/v1/validate`, { method: 'POST', headers: { Authorization: `Bearer ${cfg.key}`, 'Content-Type': 'application/json' }, body: JSON.stringify({ email: email, timeout: SERVER_TIMEOUT_S }), // no cookies; the page's origin at most, never its URL (which could hold an address in its query) credentials: 'omit', referrerPolicy: 'strict-origin', redirect: 'manual', signal: controller.signal, }), ) .then((/** @type {any} */ response) => { answer = response; return response.json().catch(() => null); }) .then( (/** @type {unknown} */ body) => { root.clearTimeout(timer); const status = answer.status; if (status === 200 && isObject(body) && STATUSES.indexOf(body.status) >= 0) { const blocks = cfg.block.indexOf(body.status) >= 0; return { block: blocks, status: body.status, message: blocks ? cfg.messages[body.status] || null : null, checked: true, notChecked: null, }; } const code = isObject(body) && isObject(body.error) ? body.error.code : null; // a refused key, no credits, a forbidden origin, the daily cap: the page stops checking if (status === 401 || status === 402 || status === 403 || code === 'key_daily_cap') { off = 'stopped_on_page'; return allowed('api_error'); } if (status === 429 || status === 503) { const after = retryAfterSeconds(answer.headers.get('retry-after')); pausedUntil = Date.now() + Math.min(after === null ? DEFAULT_PAUSE_S : after, MAX_PAUSE_S) * 1000; return allowed('rate_limited'); } return allowed(status >= 400 ? 'api_error' : 'unexpected_response'); }, () => { root.clearTimeout(timer); return allowed(timedOut ? 'timeout' : 'network_error'); }, ) .catch(() => allowed('unexpected_response')); } /** * The verdict for one value: one request per distinct address on the page (case and spaces aside), a check on its * way shared, an answer kept; no answer is forgotten so the next validation asks again. * @param {unknown} value * @returns {Promise} */ function check(value) { if (!looksLikeAddress(value)) return Promise.resolve(allowed('not_an_address')); const email = value.trim(); const key = email.toLowerCase(); const known = remembered.get(key); if (known) return known; const promise = ask(email); while (remembered.size >= MAX_REMEMBERED) { const oldest = remembered.keys().next(); if (oldest.done) break; remembered.delete(oldest.value); } remembered.set(key, promise); promise.then((v) => { if (!v.checked && remembered.get(key) === promise) remembered.delete(key); }); return promise; } /** @param {string} value @returns {Promise} */ function answerFor(value) { return check(value).then( (v) => (v.block && v.message ? v.message : true), () => true, ); } /** * The validation waiting out `waitMs` before its check is sent; one at a time, a newer value replaces it. * @type {{ key: string, promise: Promise, resolve: (v: boolean | string) => void, * timer: unknown } | null} */ let waiting = null; /** * ConvertFlow's validator for the email field: `true` (allowed; also a value that is not a string, which cannot be * checked), `false` (an empty value when `required`, or a value that is not an address: ConvertFlow's own message) * or the message for a refused address. A check that would send a request first waits `waitMs` with no newer value; * a validation replaced by a newer value answers `true`. * @param {unknown} value * @returns {Promise} */ function validate(value) { if (typeof value !== 'string') return Promise.resolve(true); if (!value.trim()) return Promise.resolve(!cfg.required); if (!looksLikeAddress(value)) return Promise.resolve(false); const key = value.trim().toLowerCase(); if (waiting && waiting.key === key) return waiting.promise; if (waiting) { root.clearTimeout(waiting.timer); waiting.resolve(true); waiting = null; } // Nothing to wait for when no request would leave: a known answer, a check on its way, no key, a stop or a pause. if (cfg.waitMs === 0 || remembered.has(key) || off || Date.now() < pausedUntil) return answerFor(value); /** @type {(v: boolean | string) => void} */ let resolve = () => {}; /** @type {Promise} */ const promise = new Promise((r) => { resolve = r; }); /** @type {{ key: string, promise: Promise, resolve: (v: boolean | string) => void, timer: unknown }} */ const entry = { key: key, promise: promise, resolve: resolve, timer: null }; entry.timer = root.setTimeout(() => { if (waiting === entry) waiting = null; answerFor(value).then(resolve); }, cfg.waitMs); waiting = entry; return promise; } return { check: check, validate: validate, field: cfg.field }; } /** * Registers the validator with ConvertFlow: at once when its API is ready (`convertflow.person` is set, which its * developer reference says holds from `cfReady` on), else on `cfReady`; and again on every later `cfReady`, since * `convertflow.start()` reloads the campaigns. Registering again is harmless: the same function for the same slug. * @param {Options} options */ function install(options) { const guard = create(options); let warned = false; function register() { const cf = root.convertflow; if (!cf || typeof cf.validations !== 'function') return; /** @type {Record Promise>} */ const validators = {}; validators[guard.field] = guard.validate; try { cf.validations(validators); } catch (_) { // an older ConvertFlow, or one that refuses the call: one line, never a broken page or a throwing listener if (warned) return; warned = true; try { root.console.warn(REGISTER_FAILED_WARNING); } catch (_) { // no console } } } const cf = root.convertflow; if (cf && cf.person !== undefined && cf.person !== null) register(); if (typeof root.addEventListener === 'function') root.addEventListener('cfReady', register); return guard; } root.EmailValidationConvertFlow = Object.freeze({ VERSION: VERSION, MESSAGES: Object.freeze(MESSAGES), create: create, install: install, looksLikeAddress: looksLikeAddress, }); // Set before this script: installs itself. A bad option is one console line, never a broken page. if (isObject(root.emailValidationConvertFlow)) { try { install(root.emailValidationConvertFlow); } catch (err) { try { root.console.warn(BAD_OPTIONS_WARNING + (err instanceof Error ? err.message : 'unknown')); } catch (_) { // no console } } } })();