// email-validation.org for Auth0 1.0.0: an Action for the Pre User Registration trigger. // // It checks the email address of each new sign-up (Database and Passwordless connections) with email-validation.org // and stops the sign-up when the result's status is one you chose to stop (or, while disposable is chosen, the result // is marked disposable). Everything else goes through: when the // address is fine, when there is no address, and whenever a check cannot be made (our API slow, down, rate limited, a // wrong key, any error). A check is never retried, so it never holds a sign-up up for longer than EV_FETCH_TIMEOUT_MS. // // Settings are the Action's secrets (Auth0 dashboard: the Action's code editor, the key icon, Add Secret): // EV_API_KEY required: an API key with the permission "Validate addresses" (a daily credit cap is wise). // EV_REGION optional: "eu" sends the checks to our EU host (EU data residency); anything else is US. // EV_STOP_STATUSES optional: the statuses that stop a sign-up, separated by commas, from valid, invalid, // catch_all, unknown and disposable. Default "invalid,disposable"; "none" stops nothing (the // results are only logged). While disposable is on the list, an answer marked disposable // is stopped whatever its status (an unknown that means our side could not finish excepted). // EV_DENY_MESSAGE optional: the message the person signing up sees instead of the default ones below. // // Each check costs one credit; unknown results and test addresses on sandbox.email-validation.org are free. // Logs hold the status, the reason, our error code and the request id, never the address or the key. const EV_VERSION = '1.0.0'; const EV_ORIGINS = { us: 'https://api.email-validation.org', eu: 'https://api-eu.email-validation.org' }; const EV_STATUSES = ['valid', 'invalid', 'catch_all', 'unknown', 'disposable']; const EV_DEFAULT_STOP = ['invalid', 'disposable']; // Our API answers within this many seconds (its shortest wait; a slower check comes back unknown, reason timeout, // free), and the Action stops waiting a second later. Auth0 gives the whole trigger 20 seconds. const EV_CHECK_TIMEOUT_S = 5; const EV_FETCH_TIMEOUT_MS = 6000; // Unknown results that mean our side could not finish the check, not something about the address: they never stop a // sign-up, even when unknown is in EV_STOP_STATUSES. const EV_OUR_SIDE_REASONS = ['timeout', 'internal_error']; // After a 429 or 503 without Retry-After, no check is sent for this long; a longer Retry-After is cut to EV_MAX_PAUSE_S. const EV_DEFAULT_PAUSE_S = 30; const EV_MAX_PAUSE_S = 300; const EV_MESSAGES = { invalid: 'This email address cannot receive email. Please check it or use another address.', disposable: 'Please sign up with a permanent email address, not a disposable one.', other: 'Please sign up with a different email address.', }; // Until when no check is sent, after our API asked to wait. Lives as long as Auth0 keeps this Action instance loaded. let evPausedUntil = 0; /** * @param {Event} event - Details about the context and user that is attempting to register. * @param {PreUserRegistrationAPI} api - Interface whose methods can be used to change the behavior of the signup. */ exports.onExecutePreUserRegistration = async (event, api) => { // What this run has to say, written as one log line at the end: Auth0 keeps 256 characters of console.log output // per Action run. The check's outcome comes first, notes about the settings after it. const log = { outcome: [], notes: [] }; let verdict = null; try { verdict = await evVerdict(event, log); } catch { log.outcome.push('not checked: unexpected error; the sign-up goes on.'); } evFlush(log); if (verdict) api.access.deny(verdict.reason, verdict.userMessage); }; // { reason, userMessage } when the sign-up is to be stopped, otherwise null. async function evVerdict(event, log) { const secrets = event && typeof event.secrets === 'object' && event.secrets !== null ? event.secrets : {}; const user = event && typeof event.user === 'object' && event.user !== null ? event.user : {}; const email = typeof user.email === 'string' ? user.email : ''; if (!email.includes('@')) return null; const apiKey = typeof secrets.EV_API_KEY === 'string' ? secrets.EV_API_KEY.trim() : ''; if (!apiKey || /\s/.test(apiKey)) { log.outcome.push('not checked: the secret EV_API_KEY is missing.'); return null; } const stop = evStopList(secrets.EV_STOP_STATUSES, log); const result = await evCheck(email, apiKey, secrets.EV_REGION, log); if (!result) return null; if (stop.length === 0) { log.outcome.push( `checked: ${result.status} (reason ${result.reason || 'none'}); EV_STOP_STATUSES is none, nothing is stopped.`, ); return null; } // An answer marked disposable (valid, invalid or unknown) stops too while disposable is stopped: our API keeps // invalid or unknown as the status of some addresses on disposable domains. const listed = stop.includes(result.status) || (stop.includes('disposable') && result.disposable); if (!listed) return null; if (result.status === 'unknown' && EV_OUR_SIDE_REASONS.includes(result.reason)) return null; const custom = typeof secrets.EV_DENY_MESSAGE === 'string' ? secrets.EV_DENY_MESSAGE.trim() : ''; const kind = result.status === 'invalid' ? 'invalid' : result.disposable ? 'disposable' : result.status; let userMessage = custom || EV_MESSAGES[kind] || EV_MESSAGES.other; if (!custom && result.status === 'invalid' && result.didYouMean) { userMessage = `${userMessage} Did you mean ${result.didYouMean}?`; } const reason = `email-validation.org: ${result.status} (reason ${result.reason || 'none'}, request ${result.requestId || 'none'})`; return { reason, userMessage }; } // The stop list from EV_STOP_STATUSES: absent or empty is the default, "none" is an empty list, unknown names are // noted and left out. function evStopList(value, log) { if (typeof value !== 'string' || value.trim() === '') return EV_DEFAULT_STOP; if (value.trim().toLowerCase() === 'none') return []; const names = value .split(',') .map((name) => name.trim().toLowerCase()) .filter((name) => name !== ''); const unknown = names.filter((name) => !EV_STATUSES.includes(name)); if (unknown.length > 0) log.notes.push(`EV_STOP_STATUSES: left out ${unknown.join(', ')} (not a status).`); const known = names.filter((name) => EV_STATUSES.includes(name)); if (known.length === 0) { log.notes.push('EV_STOP_STATUSES names no status: the default invalid,disposable applies.'); return EV_DEFAULT_STOP; } return known; } /** True when `text` holds 12 or more characters of the key in a row: such a value is never kept. */ 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; } /** One of our reasons (lowercase and `_`), else null. */ function reasonOf(value, key) { return typeof value === 'string' && /^[a-z_]{1,64}$/.test(value) && !sharesKey(value, key) ? value : null; } /** Our error code as sent (lowercase, digits, `_`), never cleaned into shape: anything else is no code. */ function codeOf(value, key) { return typeof value === 'string' && /^[a-z][a-z0-9_]{0,63}$/.test(value) && !sharesKey(value, key) ? value : ''; } /** A request id of our shape (`req_` and letters or digits), else null. */ function requestIdOf(value, key) { return typeof value === 'string' && /^req_[A-Za-z0-9]{1,60}$/.test(value) && !sharesKey(value, key) ? value : null; } // The result as { status, reason, disposable, didYouMean, requestId }, or null when the address was not checked (logged). async function evCheck(email, apiKey, region, log) { if (Date.now() < evPausedUntil) { log.outcome.push('not checked: paused after a rate limit.'); return null; } const origin = typeof region === 'string' && region.trim().toLowerCase() === 'eu' ? EV_ORIGINS.eu : EV_ORIGINS.us; let response; let text; try { response = await fetch(`${origin}/v1/validate`, { method: 'POST', headers: { Authorization: `Bearer ${apiKey}`, 'Content-Type': 'application/json', Accept: 'application/json', 'User-Agent': `email-validation-auth0/${EV_VERSION}`, }, body: JSON.stringify({ email, timeout: EV_CHECK_TIMEOUT_S }), redirect: 'manual', signal: AbortSignal.timeout(EV_FETCH_TIMEOUT_MS), }); text = await response.text(); } catch { // Never retried: the check may have run and been charged, and the sign-up is waiting. log.outcome.push('not checked: no answer from the API in time (not retried).'); return null; } let body = {}; try { const parsed = JSON.parse(text); if (parsed !== null && typeof parsed === 'object') body = parsed; } catch { // not JSON (e.g. an error page in front of our API) } if (response.status === 200 && EV_STATUSES.includes(body.status)) { return { status: body.status, reason: reasonOf(body.reason, apiKey) ?? '', disposable: body.disposable === true, didYouMean: typeof body.did_you_mean === 'string' && body.did_you_mean.includes('@') && !sharesKey(body.did_you_mean, apiKey) ? body.did_you_mean : '', requestId: requestIdOf(body.request_id, apiKey) ?? '', }; } const error = body.error && typeof body.error === 'object' ? body.error : {}; const code = codeOf(error.code, apiKey) || 'unexpected_response'; const requestId = requestIdOf(error.request_id, apiKey) ?? requestIdOf(response.headers.get('x-request-id'), apiKey); const where = ` (HTTP ${response.status}, ${code}${requestId ? `, request ${requestId}` : ''})`; if ((response.status === 429 || response.status === 503) && code !== 'key_daily_cap') { const after = evRetryAfter(response.headers.get('retry-after')); evPausedUntil = Date.now() + Math.min(after === null ? EV_DEFAULT_PAUSE_S : after, EV_MAX_PAUSE_S) * 1000; log.outcome.push(`not checked: rate limited${where}.`); return null; } log.outcome.push(`not checked${where}.`); return null; } // Retry-After in seconds: delay-seconds, or an HTTP date (IMF-fixdate, RFC 850 or asctime); anything else is null. const EV_HTTP_DATES = [ /^(Mon|Tue|Wed|Thu|Fri|Sat|Sun), \d{2} (Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) \d{4} \d{2}:\d{2}:\d{2} GMT$/, /^(Monday|Tuesday|Wednesday|Thursday|Friday|Saturday|Sunday), \d{2}-(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)-\d{2} \d{2}:\d{2}:\d{2} GMT$/, /^(Mon|Tue|Wed|Thu|Fri|Sat|Sun) (Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) [ \d]\d \d{2}:\d{2}:\d{2} \d{4}$/, ]; function evRetryAfter(value) { if (typeof value !== 'string') return null; const text = value.trim(); if (/^\d+$/.test(text)) return Number(text); if (!EV_HTTP_DATES.some((form) => form.test(text))) return null; // asctime has no zone: it is GMT. const at = Date.parse(/GMT$/.test(text) ? text : `${text} GMT`); return Number.isNaN(at) ? null : Math.max(0, Math.ceil((at - Date.now()) / 1000)); } // One console.log per run, cut to the 256 characters Auth0 keeps per Action run. function evFlush(log) { const parts = [...log.outcome, ...log.notes]; if (parts.length > 0) console.log(`email-validation.org: ${parts.join(' ')}`.slice(0, 256)); }