// 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 Demio: check the email address of the people who register for your Demio webinars. One * file, no dependencies; copy it into your server (Next.js, Remix, Hono, Express, Bun, Deno, Cloudflare Workers: * anything with `fetch` and Web Crypto). * * Demio cannot block a registration made on its own registration page: that page runs no code of yours. Demio's public * API (read 2026-11-24: https://my.demio.com/api/v1, headers `Api-Key` and `Api-Secret`) documents no webhooks and no * way to remove or cancel a registrant. What it documents is: list events, read an event and its sessions, register * someone (`PUT /event/register`, answered `201` with a join link), and read a session's participants * (`GET /report/{date_id}/participants`). So this file gives three pieces (the setup guide says which to use when): * * - `createDemioRegistration()`: for your own registration form. It checks the address first and calls Demio's * `PUT /event/register` only when the address is not one you stop: on this path a bad address never becomes a * registrant. * - `createDemioSweep()`: for registrations made on Demio's own page. It reads a session's participants, checks each * address once, and tells you each definite answer through `onResult`. It only reports: Demio's API cannot remove a * registrant, so you act on the report yourself (for example in Demio's dashboard, or in your email tool). * - `checkRegistrationEmail()`: the check alone, for your own code. * * Fails open: no key, a timeout, a network error, a rate limit or any error answer never stops a registration. Only a * definite answer whose status is in `stop` is stopped; `unknown` never is, and never replaces a definite answer kept * earlier. Our API key goes only to our API and the Demio key and secret only to https://my.demio.com, always in * headers (never Demio's query-string form); redirects are never followed; nothing here logs, or puts in an error, an * address, a key or a secret. */ export const VERSION = '1.0.0'; export const USER_AGENT = `email-validation-demio/${VERSION}`; /** Our API's two hosts: `eu` has addresses validated in the EU and their results stored there (same keys and credits). */ export const API_ORIGINS = Object.freeze({ us: 'https://api.email-validation.org', eu: 'https://api-eu.email-validation.org', }); /** The five statuses an answer can have. */ export const STATUSES = Object.freeze(['valid', 'invalid', 'catch_all', 'unknown', 'disposable'] as const); export type Status = (typeof STATUSES)[number]; /** The statuses you may stop. `valid` and `unknown` never stop a registrant. */ export const STOPPABLE = Object.freeze(['invalid', 'disposable', 'catch_all'] as const); export type StoppableStatus = (typeof STOPPABLE)[number]; export const DEFAULTS = Object.freeze({ /** A registration is a person asking to come: only an address that cannot receive mail is stopped by default. */ stop: Object.freeze(['invalid'] as const), /** * How long a check may take before the address stays unchecked: a little over the API's own 5-second limit, so a * check that needs longer comes back as a free `unknown` first. */ timeoutMs: 6000, /** * The longest one sweep may run, counted from its start: the Demio read, every check, every store call, every * `onResult` call and every wait fit in it (a check is sent only when its whole timeout, and the store write after it, * still fit). */ budgetMs: 60_000, /** The most addresses one sweep pays to check; the rest wait for the next sweep. */ maxChecks: 200, }); /** The API's shortest check time, in seconds: a check that needs longer ends as a free `unknown`. */ export const SERVER_TIMEOUT_S = 5; /** * Our API's error codes after which no check is sent with this key for `MAX_PAUSE_S`: the key is refused (or limited * to browser origins), out of credits or over its daily cap, so every check meanwhile would fail the same way. */ export const STOP_CODES = Object.freeze([ 'unauthorized', 'forbidden', 'forbidden_origin', 'insufficient_credits', 'key_daily_cap', ] as const); /** The stop code an error answer without our JSON code stands for, by its HTTP status (pausing is the safe side). */ const BY_HTTP_STATUS: Readonly> = { 401: 'unauthorized', 402: 'insufficient_credits', 403: 'forbidden', }; /** After our API's 429 or 503 without Retry-After, checks pause this long; a longer one is cut to MAX_PAUSE_S. */ export const DEFAULT_PAUSE_S = 30; export const MAX_PAUSE_S = 300; /** * A browser key (`ev_live_`, the 22-character account part, then `browser`): limited to allowed origins, so from a * server, which sends no Origin, every check would be refused. Only our server mints one. */ const BROWSER_KEY = /^ev_live_[0-9A-Za-z]{22}browser[0-9A-Za-z]{50}$/; /** Demio's public API: the only host the Demio key and secret are sent to. There is no host option. */ export const DEMIO_API_ORIGIN = 'https://my.demio.com'; export const DEMIO_API_BASE = `${DEMIO_API_ORIGIN}/api/v1`; /** Per Demio call, in milliseconds. */ export const DEMIO_TIMEOUT_MS = 10_000; /** * Demio's help center ("API Limitations") sets 180 requests a minute per account and a daily quota (100 calls on a * trial, 5,000 paid; shared with Zapier and other tools; reset at 00:00 UTC). Its API reference * (https://api-docs.demio.com/, read 2026-12-04) answers either limit with `417`: that ends a sweep at once * (`demio_rate_limited`; a daily quota does not clear in seconds) and the form gets it back. A `429`, which the * reference does not document, is handled cautiously: the sweep's read is tried again after its `Retry-After` (else * this many seconds, never less), at most `DEMIO_READ_TRIES` times in all, while the wait fits in the budget. */ export const DEMIO_DEFAULT_WAIT_S = 1; export const DEMIO_READ_TRIES = 3; /** The largest participants answer read (bytes); a larger one is refused rather than read without end. */ export const MAX_REPORT_BYTES = 16 * 1024 * 1024; /** The largest answer of our API read (bytes). */ const MAX_ANSWER_BYTES = 64 * 1024; /** How long a definite answer is kept (in memory and in a `store`), in seconds: webinars are often weeks away. */ export const MEMO_TTL_S = 30 * 24 * 60 * 60; /** Registrants and addresses kept in this process, per API key. */ export const MEMORY_MAX = 10_000; /** The longest a `store` read or write may take before it is treated as a miss (read) or skipped (write). */ export const STORE_TIMEOUT_MS = 1000; /** The longest `onResult` may take for one answer before the sweep goes on (it is then kept as not yet reported). */ export const REPORT_TIMEOUT_MS = 5000; export type FetchFn = (input: string, init?: RequestInit) => Promise; export interface CheckOptions { /** * Your email-validation.org API key (permission "Validate addresses"; not a browser key). Server-side only: read it * from env. */ apiKey: string | undefined; /** `us` (default) or `eu`. */ region?: 'us' | 'eu'; /** The statuses that stop a registrant (default `invalid`). */ stop?: readonly StoppableStatus[]; /** Whole milliseconds, 1 to 60000, before a check is given up as unchecked (default 6000). */ timeoutMs?: number; /** For tests and proxies; default: the global fetch. */ fetch?: FetchFn; } export interface Decision { /** False only when a definite answer's status is one you stop. */ allow: boolean; /** The answer's status, or null when there was no answer (then `error` says why). */ status: Status | null; reason: string | null; /** The answer's `disposable` flag (false without an answer). */ disposable: boolean; /** A suggested correction for a typo, e.g. `name@gmail.com`, or null (null too for an answer kept earlier). */ didYouMean: string | null; /** Why there is no answer (`missing_key`, `not_an_address`, `timeout`, `connection_error`, `paused`, our code). */ error: string | null; requestId: string | null; } interface Settings { apiKey: string; origin: string; stop: readonly StoppableStatus[]; timeoutMs: number; fetch: FetchFn; } /** Surrounding whitespace (a pasted line break) is trimmed; a key with anything but visible ASCII inside is no key. */ function keyOf(value: unknown): string { const trimmed = typeof value === 'string' ? value.trim() : ''; return /^[\x21-\x7e]+$/.test(trimmed) ? trimmed : ''; } function whole(name: string, value: unknown, min: number, max: number, unit: string): number { if (typeof value !== 'number' || !Number.isInteger(value) || value < min || value > max) { throw new TypeError(`${name} must be a whole number${unit} from ${min} to ${max}.`); } return value; } function settings(options: CheckOptions): Settings { if (!options || typeof options !== 'object') throw new TypeError('Options are required.'); const region = options.region ?? 'us'; if (region !== 'us' && region !== 'eu') throw new TypeError('region must be "us" or "eu".'); const stop = options.stop ?? DEFAULTS.stop; if (!Array.isArray(stop) || stop.some((s) => !(STOPPABLE as readonly string[]).includes(s))) { throw new TypeError(`stop must list only ${STOPPABLE.join(', ')}.`); } const timeoutMs = whole('timeoutMs', options.timeoutMs ?? DEFAULTS.timeoutMs, 1, 60_000, ' of milliseconds'); if (options.fetch !== undefined && typeof options.fetch !== 'function') { throw new TypeError('fetch must be a function.'); } const apiKey = keyOf(options.apiKey); if (BROWSER_KEY.test(apiKey)) { throw new TypeError('This is a browser key; use a key without allowed origins on the server.'); } return { apiKey, origin: API_ORIGINS[region], stop: Object.freeze([...stop]), timeoutMs, fetch: options.fetch ?? ((input: string, init?: RequestInit) => globalThis.fetch(input, init)), }; } function unchecked(error: string, requestId: string | null = null): Decision { return { allow: true, status: null, reason: null, disposable: false, didYouMean: null, error, requestId }; } /** Control and format characters (zero-width spaces and joiners, bidi marks, the BOM): never part of an address. */ const INVISIBLE = /[\p{Cc}\p{Cf}\p{Zl}\p{Zp}]/u; /** * Whether a value is worth a check: something@domain.tld with no spaces, no invisible characters and nothing of a link * (`:`, `/`, `?`, `#`): a link with an `@` in it, or a `mailto:`, is never sent. */ export function looksLikeAddress(value: unknown): value is string { if (typeof value !== 'string') return false; const v = value.trim(); return ( v.length <= 254 && // A format character is refused even at an end, where trim() would quietly drop a BOM. !/\p{Cf}/u.test(value) && !INVISIBLE.test(v) && /^[^\s@:/?#"<>()[\],;\\]+@[\p{L}\p{N}-]+(?:\.[\p{L}\p{N}-]+)*\.[\p{L}\p{N}-]{2,}$/u.test(v) ); } /** Retry-After in seconds: delay-seconds or an IMF-fixdate HTTP date; anything else is null. */ export function retryAfter(value: string | null, nowMs: number): number | null { if (typeof value !== 'string') return null; const t = value.trim(); if (/^\d{1,9}$/.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 - nowMs) / 1000)); } function isObject(v: unknown): v is Record { return v !== null && typeof v === 'object' && !Array.isArray(v); } /** What `call` read: the status, the headers and the JSON body (null when it was not JSON). */ export interface CallAnswer { status: number; headers: Headers; json: unknown; } /** A call that ran out of its time (body read included). */ class CallTimeout extends Error { constructor() { super('timeout'); this.name = 'TimeoutError'; } } /** Reads a body up to `maxBytes`; a longer one is cancelled and refused (`too_large`). */ async function boundedText(response: Response, maxBytes: number): Promise { const reader = response.body?.getReader(); if (!reader) return ''; const chunks: Uint8Array[] = []; let size = 0; for (;;) { const { done, value } = await reader.read(); if (done) break; size += value.byteLength; if (size > maxBytes) { await reader.cancel().catch(() => undefined); throw new Error('too_large'); } chunks.push(value); } const bytes = new Uint8Array(size); let at = 0; for (const chunk of chunks) { bytes.set(chunk, at); at += chunk.byteLength; } return new TextDecoder().decode(bytes); } /** * One request to an allowed origin only, redirects never followed, bounded by `timeoutMs` with the body read included * (and the body by `maxBytes`). Rejects on a foreign host, no answer, a redirect, a body too large or the time running * out; answers the status, headers and JSON body for any other status. */ export async function call( fetchFn: FetchFn, origin: string, url: string, init: RequestInit, timeoutMs: number, maxBytes: number = MAX_ANSWER_BYTES, ): Promise { if (new URL(url).origin !== origin) throw new Error(`Refused a request to a host other than ${origin}.`); const headers = new Headers(init.headers); headers.set('User-Agent', USER_AGENT); const controller = new AbortController(); let timer: ReturnType | undefined; const expired = new Promise((_, reject) => { timer = setTimeout(() => { controller.abort(new CallTimeout()); reject(new CallTimeout()); }, timeoutMs); }); expired.catch(() => { // raced below; a timeout that loses the race is not an unhandled rejection }); try { const response = await Promise.race([ fetchFn(url, { ...init, headers, redirect: 'manual', signal: controller.signal }), expired, ]); if ((response.status >= 300 && response.status < 400) || response.type === 'opaqueredirect') { await Promise.race([discard(response), expired]).catch(() => undefined); throw new Error('redirect'); } const text = await Promise.race([boundedText(response, maxBytes), expired]); let json: unknown = null; try { json = text ? JSON.parse(text) : null; } catch { // not JSON } return { status: response.status, headers: response.headers, json }; } finally { clearTimeout(timer); } } /** Frees a response's connection when its body is not read. */ async function discard(response: Response): Promise { try { await response.body?.cancel(); } catch { // already closed } } function isTimeout(err: unknown): boolean { const name = err instanceof Error ? err.name : ''; return name === 'TimeoutError' || name === 'AbortError'; } interface Checked { decision: Decision; /** Seconds checks should pause (our stop codes, or a 429 or 503), or null. */ pauseS: number | null; } /** True when `text` holds 12 or more characters of the key in a row: such a value is never kept. */ function sharesKey(text: string, key: string): boolean { 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; } /** Our error code as sent (lowercase, digits, `_`), never cleaned into shape: anything else is no code. */ function codeOf(value: unknown, key: string): string { 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: unknown, key: string): string | null { return typeof value === 'string' && /^req_[A-Za-z0-9]{1,60}$/.test(value) && !sharesKey(value, key) ? value : null; } /** One of our reasons (lowercase and `_`), else null. */ function reasonOf(value: unknown, key: string): string | null { return typeof value === 'string' && /^[a-z_]{1,64}$/.test(value) && !sharesKey(value, key) ? value : null; } async function check(s: Settings, email: string): Promise { const none = (error: string, requestId: string | null = null, pauseS: number | null = null): Checked => ({ decision: unchecked(error, requestId), pauseS, }); let answer: CallAnswer; try { answer = await call( s.fetch, s.origin, `${s.origin}/v1/validate`, { method: 'POST', headers: { Authorization: `Bearer ${s.apiKey}`, 'Content-Type': 'application/json', Accept: 'application/json', }, body: JSON.stringify({ email: email.trim(), timeout: SERVER_TIMEOUT_S }), }, s.timeoutMs, ); } catch (err) { if (isTimeout(err)) return none('timeout'); if (err instanceof Error && (err.message === 'redirect' || err.message === 'too_large')) { return none('unexpected_response'); } return none('connection_error'); } const record = isObject(answer.json) ? answer.json : {}; const headerId = requestIdOf(answer.headers.get('x-request-id'), s.apiKey); if (answer.status < 200 || answer.status > 299) { const error = isObject(record.error) ? record.error : {}; const given = codeOf(error.code, s.apiKey); const code = given || BY_HTTP_STATUS[answer.status] || ''; const requestId = requestIdOf(error.request_id, s.apiKey) ?? headerId; // A refused key or no credits pause by status too, whatever code the body gives (a code added later). const stops = (STOP_CODES as readonly string[]).includes(code) || answer.status === 401 || answer.status === 402; const limited = answer.status === 429 || answer.status === 503; const pauseS = stops ? MAX_PAUSE_S : limited ? Math.min( Math.max(1, retryAfter(answer.headers.get('retry-after'), Date.now()) ?? DEFAULT_PAUSE_S), MAX_PAUSE_S, ) : null; return none(code || `http_${answer.status}`, requestId, pauseS); } const status = record.status; const requestId = requestIdOf(record.request_id, s.apiKey) ?? headerId; if (typeof status !== 'string' || !(STATUSES as readonly string[]).includes(status)) { return none('unexpected_response', requestId); } const reason = reasonOf(record.reason, s.apiKey); return { decision: { allow: !stoppedFor(s, status as Status), status: status as Status, reason, disposable: record.disposable === true, didYouMean: typeof record.did_you_mean === 'string' && record.did_you_mean && !sharesKey(record.did_you_mean, s.apiKey) ? record.did_you_mean : null, error: null, requestId, }, pauseS: null, }; } /** Stopped only by its status: `valid` and `unknown` never stop, whatever else the answer says. */ function stoppedFor(s: Settings, status: Status): boolean { return (s.stop as readonly string[]).includes(status); } /** * A checker for one configuration (options are checked once, here), for your own code. Never rejects. Each check * uses one credit (`unknown`, malformed and sandbox addresses are free). It keeps nothing: use * `createDemioRegistration()` for one check per registrant and address. */ export function createEmailCheck(options: CheckOptions): (email: string) => Promise { const s = settings(options); return async (email) => { if (!s.apiKey) return unchecked('missing_key'); if (!looksLikeAddress(email)) return unchecked('not_an_address'); return check(s, email) .then((r) => r.decision) .catch(() => unchecked('internal_error')); }; } /** Checks one address in your own server code. Each check uses one credit. */ export function checkRegistrationEmail(email: string, options: CheckOptions): Promise { return createEmailCheck(options)(email); } // --------------------------------------------------------------------------------------------------------------- // Hashing. The address is never kept or used as a key: only the SHA-256 of its trimmed, lowercased form. const encoder = new TextEncoder(); async function sha256Hex(text: string): Promise { const digest = new Uint8Array(await crypto.subtle.digest('SHA-256', encoder.encode(text))); let out = ''; for (const b of digest) out += b.toString(16).padStart(2, '0'); return out; } function normalized(email: string): string { return email.trim().toLowerCase(); } // --------------------------------------------------------------------------------------------------------------- // Demio's ids. Demio's ids are whole numbers. They are taken here as a string of digits (or a safe whole number), kept // and reported as strings, and sent only to https://my.demio.com: in the path of the participants read, and in the // register body as the JSON number Demio's docs show. const ID = /^[1-9][0-9]{0,15}$/; /** A Demio id as a string of digits, else null (`12`, 12 and `"12"` are the same id; `0`, `-1`, `1.5`, `1e3` are not). */ export function idOf(value: unknown): string | null { if (typeof value === 'number') return Number.isSafeInteger(value) && value > 0 ? String(value) : null; return typeof value === 'string' && ID.test(value) && Number.isSafeInteger(Number(value)) ? value : null; } /** Demio's API key and secret (Demio: Account Settings → API). Read them from env. */ export interface DemioCredentials { apiKey: string | undefined; apiSecret: string | undefined; } interface Demio { headers: Record; } function demioOf(value: unknown): Demio { if (!isObject(value)) throw new TypeError('demio must be { apiKey, apiSecret } (Demio: Account Settings → API).'); const apiKey = keyOf(value.apiKey); const apiSecret = keyOf(value.apiSecret); if (!apiKey || !apiSecret) throw new TypeError('demio.apiKey and demio.apiSecret are both required.'); return { headers: { 'Api-Key': apiKey, 'Api-Secret': apiSecret, Accept: 'application/json' } }; } /** The error a Demio answer other than the documented one stands for (401 and 403: the key or secret refused). */ function demioError(status: number): string { if (status === 401 || status === 403) return 'demio_key_refused'; if (status === 429 || status === 417) return 'demio_rate_limited'; if (status >= 500) return 'demio_call_failed'; if (status >= 200 && status < 300) return 'demio_unexpected_answer'; return 'demio_call_refused'; } // --------------------------------------------------------------------------------------------------------------- // What is shared in this process, per API key (our host and the key's SHA-256): the answers kept, the checks in flight // and the pause. Two pieces with the same key share them, so a pause or an answer is never missed by a second route. /** A definite answer kept for a registrant and address: never the address, never a suggestion. */ export interface Remembered { status: Exclude; reason: string | null; disposable: boolean; requestId: string | null; /** Whether a sweep has told `onResult` (false: the next sweep tells it again, without a new check). */ reported: boolean; } /** * Where definite answers are kept across restarts and instances (Workers KV, Redis, a database table). Keys are * `ev-demio:`, values a * `Remembered`: never an address, a key or a secret. `ttlSeconds` is how long the value matters. Errors and calls * slower than STORE_TIMEOUT_MS are ignored (a check is then sent again). */ export interface Store { get(key: string): Promise | unknown; set(key: string, value: Remembered, ttlSeconds: number): Promise | void; } interface KeyState { id: string; memory: Map; inFlight: Map>; pausedUntil: number; pausedFor: string; } const KEYS = new Map(); /** Drops every kept answer and pause in this process (for tests, or after you fix a key). */ export function forgetAll(): void { KEYS.clear(); } async function keyState(s: Settings): Promise { const id = await sha256Hex(`${s.origin}\n${await sha256Hex(s.apiKey)}`); let state = KEYS.get(id); if (!state) { state = { id, memory: new Map(), inFlight: new Map(), pausedUntil: 0, pausedFor: '' }; KEYS.set(id, state); } return state; } const STORE_PREFIX = 'ev-demio:'; function storedAnswer(value: unknown): Remembered | null { if (!isObject(value)) return null; const { status, reason, disposable, requestId, reported } = value; if (typeof status !== 'string' || status === 'unknown' || !(STATUSES as readonly string[]).includes(status)) { return null; } return { status: status as Remembered['status'], reason: typeof reason === 'string' ? reason.slice(0, 64) : null, disposable: disposable === true, requestId: typeof requestId === 'string' ? requestId.slice(0, 64) : null, reported: reported !== false, }; } function bounded(work: () => Promise | T, ms: number): Promise { let timer: ReturnType | undefined; const late = new Promise((resolve) => { timer = setTimeout(() => resolve(undefined), ms); }); const run = Promise.resolve() .then(work) .catch(() => undefined); return Promise.race([run, late]).finally(() => clearTimeout(timer)); } class Memory { private readonly state: KeyState; private readonly store: Store | undefined; /** Milliseconds left for store calls (a sweep's budget); a store call never takes longer than this. */ private readonly timeLeft: () => number; constructor(state: KeyState, store: Store | undefined, timeLeft: () => number = () => STORE_TIMEOUT_MS) { this.state = state; this.store = store; this.timeLeft = timeLeft; } private limit(): number { return Math.max(0, Math.min(STORE_TIMEOUT_MS, this.timeLeft())); } /** Whether a store is used (its write after a check needs time kept for it). */ get shared(): boolean { return this.store !== undefined; } key(eventId: string, email: string): Promise { return sha256Hex(normalized(email)).then((address) => sha256Hex(`${this.state.id}\n${eventId}\n${address}`)); } async get(key: string): Promise { const kept = this.state.memory.get(key); if (kept && kept.expiresMs > Date.now()) return kept.value; if (kept) this.state.memory.delete(key); const store = this.store; if (!store) return null; const ms = this.limit(); if (ms <= 0) return null; const value = storedAnswer(await bounded(() => store.get(STORE_PREFIX + key), ms)); if (value) this.keep(key, value); return value; } async set(key: string, value: Remembered): Promise { this.keep(key, value); const store = this.store; const ms = this.limit(); if (store && ms > 0) await bounded(() => store.set(STORE_PREFIX + key, { ...value }, MEMO_TTL_S), ms); } private keep(key: string, value: Remembered): void { const memory = this.state.memory; memory.delete(key); memory.set(key, { value, expiresMs: Date.now() + MEMO_TTL_S * 1000 }); while (memory.size > MEMORY_MAX) { const oldest = memory.keys().next().value as string; memory.delete(oldest); } } } function storeOf(value: unknown): Store | undefined { if (value === undefined) return undefined; if (!isObject(value) || typeof value.get !== 'function' || typeof value.set !== 'function') { throw new TypeError('store must have get(key) and set(key, value, ttlSeconds).'); } return value as unknown as Store; } function decisionOf(s: Settings, kept: Remembered): Decision { return { allow: !stoppedFor(s, kept.status), status: kept.status, reason: kept.reason, disposable: kept.disposable, didYouMean: null, error: null, requestId: kept.requestId, }; } interface Answered { decision: Decision; /** The answer kept for this registrant and address (a definite one), or null. */ kept: Remembered | null; /** Whether the answer was kept earlier (no credit spent now). */ fromMemory: boolean; /** Whether a check was sent now. */ sent: boolean; } /** * One answer per registrant and address: a kept answer is used as it is; otherwise one check, whose definite answer is * kept. Checks of the same key at the same time wait for the one in flight (and, when it ends without an answer, one * of them checks again, not all). With the key paused, nothing is sent. A stopped answer from the form's path is kept * as not yet reported, so a sweep that meets the person on Demio's page still tells `onResult`; with * `unreportedAll` (the sweep's path) every answer is, until `onResult` has it. `known`: the memory just read, so it is * not read twice. */ async function answerFor( s: Settings, state: KeyState, memory: Memory, key: string, email: string, options: { unreportedAll: boolean; known?: Remembered | null }, ): Promise { let kept = options.known === undefined ? await memory.get(key) : options.known; for (;;) { if (kept) return { decision: decisionOf(s, kept), kept, fromMemory: true, sent: false }; const pending = state.inFlight.get(key); if (!pending) break; const shared = await pending; if (shared) return { decision: decisionOf(s, shared), kept: shared, fromMemory: true, sent: false }; kept = await memory.get(key); } if (state.pausedUntil > Date.now()) { return { decision: unchecked('paused'), kept: null, fromMemory: false, sent: false }; } let decision: Decision = unchecked('internal_error'); const run = (async (): Promise => { const checked = await check(s, email).catch(() => ({ decision: unchecked('internal_error'), pauseS: null })); decision = checked.decision; if (checked.pauseS !== null) { state.pausedUntil = Math.max(state.pausedUntil, Date.now() + checked.pauseS * 1000); state.pausedFor = decision.error ?? 'paused'; } if (decision.status === null || decision.status === 'unknown') return null; const value: Remembered = { status: decision.status, reason: decision.reason, disposable: decision.disposable, requestId: decision.requestId, reported: !options.unreportedAll && !stoppedFor(s, decision.status), }; await memory.set(key, value); return value; })(); state.inFlight.set(key, run); try { const value = await run; return { decision, kept: value, fromMemory: false, sent: true }; } finally { if (state.inFlight.get(key) === run) state.inFlight.delete(key); } } // --------------------------------------------------------------------------------------------------------------- // Registration from your own form: check, then Demio's PUT /event/register. export interface RegistrationOptions extends CheckOptions { /** Demio's API key and secret: sent only to https://my.demio.com, in headers. */ demio: DemioCredentials; /** Shares kept answers across instances (one check per event and address). */ store?: Store; } /** The person to register, in the fields of Demio's `PUT /event/register`. */ export interface Registrant { /** The Demio event id (a string of digits, or a whole number). */ eventId: string | number; /** The session (event date) id; without it Demio picks the nearest active session. */ dateId?: string | number; /** The registrant's first name (Demio requires it). */ name: string; email: string; lastName?: string; company?: string; website?: string; phoneNumber?: string; gdpr?: string; /** Custom registration fields by their identifier (Demio: the event's Customize tab, Registration block). */ customFields?: Readonly>; } export interface RegistrationResult { /** True only when Demio answered `201` with a join link. */ registered: boolean; /** * `registered`; `stopped` (our check stopped the address: Demio was not called); `failed` (Demio refused with a * 4xx, or the name is missing: nothing was registered; `error` says which); `unconfirmed` (no answer in time, a 5xx, * or a success answer not in Demio's documented form: the person may or may not be registered, so do not simply * try again; look in Demio first). */ outcome: 'registered' | 'stopped' | 'failed' | 'unconfirmed'; /** Our answer, or why there was none. */ decision: Decision; /** The person's unique join link from Demio, when registered. Show it to them; never log it. */ joinLink: string | null; /** * Demio's side, when not registered: `missing_name`, `name_too_long` (over 2,000 characters), `demio_key_refused` (401, 403), `demio_rate_limited` (417, 429), * `demio_call_refused` (another 4xx, e.g. a wrong event id or a field Demio refused), `demio_call_failed` (no answer * in time, a dropped connection, a 5xx), `demio_unexpected_answer` (a redirect, or a success answer other than a * `201` with a join link). */ error: string | null; /** Demio's HTTP status, when it answered. */ demioStatus: number | null; /** With `demio_rate_limited`: seconds Demio asked to wait, when it said. */ retryAfterS: number | null; } /** Field names of Demio's register body that a custom field may not take. */ const RESERVED = new Set([ 'id', 'ref_url', 'date_id', 'name', 'email', 'last_name', 'company', 'website', 'phone_number', 'gdpr', ]); const FIELD_ID = /^[A-Za-z0-9_]{1,64}$/; const MAX_FIELD_CHARS = 2000; function textField(name: string, value: unknown): string | undefined { if (value === undefined || value === null) return undefined; if (typeof value !== 'string' || value.length > MAX_FIELD_CHARS) { throw new TypeError(`${name} must be a string of at most ${MAX_FIELD_CHARS} characters.`); } return value; } /** Demio's register body for a registrant (only the documented fields; ids as the JSON numbers Demio shows). */ function registerBody(r: Registrant, eventId: string, dateId: string | null): Record { const body: Record = { id: Number(eventId) }; if (dateId !== null) body.date_id = Number(dateId); body.name = r.name.trim(); body.email = r.email.trim(); const optional: [string, unknown][] = [ ['last_name', r.lastName], ['company', r.company], ['website', r.website], ['phone_number', r.phoneNumber], ['gdpr', r.gdpr], ]; for (const [field, value] of optional) { const text = textField(field, value); if (text !== undefined) body[field] = text; } if (r.customFields !== undefined) { if (!isObject(r.customFields)) throw new TypeError('customFields must be an object of strings.'); for (const [field, value] of Object.entries(r.customFields)) { if (!FIELD_ID.test(field) || RESERVED.has(field)) { throw new TypeError('A custom field id must be letters, digits and _ (at most 64), not a built-in field.'); } const text = textField('A custom field', value); if (text !== undefined) body[field] = text; } } return body; } const JOIN_LINK = /^https:\/\/[A-Za-z0-9.-]+\/\S{1,512}$/; /** * For your own registration form: checks the address, then registers the person with Demio's `PUT /event/register` * only when the address is not one you stop. Fails open: with no answer (a timeout, an error, a paused key) the person * is registered. One check per event and address (a kept answer is reused, unpaid). Never rejects for a Demio or API * failure; throws a TypeError only for a registrant your code built wrong (an event id that is not a Demio id, a field * that is not a string). */ export function createDemioRegistration( options: RegistrationOptions, ): (registrant: Registrant) => Promise { const s = settings(options); const demio = demioOf(options?.demio); const store = storeOf(options.store); return async (registrant) => { if (!isObject(registrant)) throw new TypeError('registrant must be an object.'); const eventId = idOf(registrant.eventId); if (!eventId) throw new TypeError('registrant.eventId must be a Demio event id (digits).'); const dateId = registrant.dateId === undefined || registrant.dateId === null ? null : idOf(registrant.dateId); if (registrant.dateId !== undefined && registrant.dateId !== null && !dateId) { throw new TypeError('registrant.dateId must be a Demio session id (digits).'); } const result = ( outcome: RegistrationResult['outcome'], decision: Decision, extra: Partial = {}, ): RegistrationResult => ({ registered: outcome === 'registered', outcome, decision, joinLink: null, error: null, demioStatus: null, retryAfterS: null, ...extra, }); if (typeof registrant.name !== 'string' || !registrant.name.trim()) { return result('failed', unchecked('not_checked'), { error: 'missing_name' }); } if (registrant.name.length > MAX_FIELD_CHARS) { return result('failed', unchecked('not_checked'), { error: 'name_too_long' }); } if (typeof registrant.email !== 'string') throw new TypeError('registrant.email must be a string.'); const body = registerBody(registrant, eventId, dateId); let decision: Decision; if (!s.apiKey) decision = unchecked('missing_key'); else if (!looksLikeAddress(registrant.email)) decision = unchecked('not_an_address'); else { try { const state = await keyState(s); const memory = new Memory(state, store); const key = await memory.key(eventId, registrant.email); decision = (await answerFor(s, state, memory, key, registrant.email, { unreportedAll: false })).decision; } catch { decision = unchecked('internal_error'); } } if (!decision.allow) return result('stopped', decision); let answer: CallAnswer; try { answer = await call( s.fetch, DEMIO_API_ORIGIN, `${DEMIO_API_BASE}/event/register`, { method: 'PUT', headers: { ...demio.headers, 'Content-Type': 'application/json' }, body: JSON.stringify(body), }, DEMIO_TIMEOUT_MS, ); } catch (err) { // No answer (a timeout, a dropped connection): the request may still have reached Demio. if (err instanceof Error && (err.message === 'redirect' || err.message === 'too_large')) { return result('unconfirmed', decision, { error: 'demio_unexpected_answer' }); } return result('unconfirmed', decision, { error: 'demio_call_failed' }); } if (answer.status === 201) { const link = isObject(answer.json) ? answer.json.join_link : undefined; if (typeof link === 'string' && JOIN_LINK.test(link)) { return result('registered', decision, { joinLink: link, demioStatus: 201 }); } return result('unconfirmed', decision, { error: 'demio_unexpected_answer', demioStatus: 201 }); } if (answer.status >= 200 && answer.status < 300) { return result('unconfirmed', decision, { error: 'demio_unexpected_answer', demioStatus: answer.status }); } // A 5xx may come after Demio wrote the registration (a proxy's 502 or 504): it does not say nothing was applied. if (answer.status >= 500) { return result('unconfirmed', decision, { error: 'demio_call_failed', demioStatus: answer.status }); } return result('failed', decision, { error: demioError(answer.status), demioStatus: answer.status, retryAfterS: answer.status === 429 || answer.status === 417 ? retryAfter(answer.headers.get('retry-after'), Date.now()) : null, }); }; } // --------------------------------------------------------------------------------------------------------------- // The sweep: registrations made on Demio's own page, read from a session's participants and reported. export interface SweepOptions extends CheckOptions { /** Demio's API key and secret: sent only to https://my.demio.com, in headers. */ demio: DemioCredentials; /** Shares kept answers across instances and runs (one check per event and address). */ store?: Store; /** Whole milliseconds, 1 to 600000: the most one sweep may take, from its start (default 60000). */ budgetMs?: number; /** Whole number, 1 to 10000: the most addresses one sweep pays to check (default 200). */ maxChecks?: number; /** * Called once per participant and address with a definite answer (at least once: rarely twice, when two sweeps of * one event run at the same time or a store write did not land), never for one reported before. A stopped answer * from your form counts as not yet reported. The answer is kept as reported only when this returns (or resolves) * within REPORT_TIMEOUT_MS and the time left of the budget, without throwing; else the next sweep calls it again * with the kept answer, without a new check. */ onResult?: (result: SweepResult) => unknown; } /** One participant's definite answer. */ export interface SweepResult { eventId: string; dateId: string; /** The participant's address as Demio gave it: yours to act on; keep it out of shared logs. */ email: string; /** The participant's name as Demio gave it, or null. */ name: string | null; /** Demio's participation status (`did not attend`, `completed`...), or null. */ participantStatus: string | null; /** `stopped` when the status is one you stop, else `allowed`. Demio's API cannot remove anyone: you act on it. */ outcome: 'stopped' | 'allowed'; decision: Decision; /** Whether the answer was kept from an earlier check (no credit spent now). */ fromMemory: boolean; } export interface SweepSummary { /** `done`, or `ended_early` (then `error` says why and `left` how many addresses wait for the next sweep). */ outcome: 'done' | 'ended_early'; /** * Why it ended early, or why nothing was read: `missing_key`, `paused` (our API key), one of our stop codes, * `rate_limited`, `budget_spent`, `max_checks`, `demio_key_refused`, `demio_rate_limited`, `demio_call_refused`, * `demio_call_failed`, `demio_unexpected_answer`. */ error: string | null; /** Participants in Demio's answer. */ participants: number; /** Addresses checked now (each one credit, except free answers). */ checked: number; /** Definite answers reported to `onResult` (now checked, or kept and not reported before). */ reported: number; /** Of those, stopped. */ stopped: number; /** Addresses already reported by an earlier sweep: left alone. */ known: number; /** Addresses sent without a definite answer (a timeout, an `unknown`, an error): the next sweep checks them again. */ unchecked: number; /** Values that are not an address (never sent), and repeats of an address within the answer. */ skipped: number; /** At most this many addresses were not handled this time (the run ended early): the next sweep handles them. */ left: number; /** `onResult` calls that threw or ran past REPORT_TIMEOUT_MS: the next sweep reports them again, unpaid. */ reportFailed: number; } interface Participant { email: unknown; name: string | null; participantStatus: string | null; } function participantsOf(json: unknown): Participant[] | null { if (!isObject(json) || !Array.isArray(json.participants)) return null; return json.participants.map((p) => { const entry = isObject(p) ? p : {}; return { email: entry.email, name: typeof entry.name === 'string' ? entry.name.slice(0, 200) : null, participantStatus: typeof entry.status === 'string' ? entry.status.slice(0, 64) : null, }; }); } const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms)); /** The least time kept for a call after a wait: a wait that leaves less is not taken. */ const MIN_CALL_MS = 1000; /** * For registrations made on Demio's own page: reads one session's participants * (`GET /report/{date_id}/participants`), checks each address once per event and tells you each definite answer * through `onResult`. It only reports: Demio's API has no way to remove or cancel a registrant. Run it on a schedule * of your own (a cron), for example hourly for the sessions of the coming days. Never rejects for a Demio or API * failure; throws a TypeError only for an id that is not a Demio id. */ export function createDemioSweep( options: SweepOptions, ): (session: { eventId: string | number; dateId: string | number }) => Promise { const s = settings(options); const demio = demioOf(options?.demio); const store = storeOf(options.store); const budgetMs = whole('budgetMs', options.budgetMs ?? DEFAULTS.budgetMs, 1, 600_000, ' of milliseconds'); const maxChecks = whole('maxChecks', options.maxChecks ?? DEFAULTS.maxChecks, 1, 10_000, ''); if (options.onResult !== undefined && typeof options.onResult !== 'function') { throw new TypeError('onResult must be a function.'); } const onResult = options.onResult; return async (session) => { const eventId = idOf(session?.eventId); const dateId = idOf(session?.dateId); if (!eventId || !dateId) throw new TypeError('eventId and dateId must be Demio ids (digits).'); const startedMs = Date.now(); const left = () => budgetMs - (Date.now() - startedMs); const summary: SweepSummary = { outcome: 'done', error: null, participants: 0, checked: 0, reported: 0, stopped: 0, known: 0, unchecked: 0, skipped: 0, left: 0, reportFailed: 0, }; const end = (error: string): SweepSummary => { summary.outcome = 'ended_early'; summary.error = error; return summary; }; if (!s.apiKey) return end('missing_key'); const state = await keyState(s); // A paused key reads nothing from Demio: every check would fail the same way. if (state.pausedUntil > Date.now()) return end('paused'); // 1. The participants, read once (a 429 tried again after its Retry-After, within the budget). let participants: Participant[] | null = null; for (let attempt = 1; ; attempt++) { const timeoutMs = Math.min(DEMIO_TIMEOUT_MS, left()); if (timeoutMs <= 0) return end('budget_spent'); let answer: CallAnswer; try { answer = await call( s.fetch, DEMIO_API_ORIGIN, `${DEMIO_API_BASE}/report/${dateId}/participants`, { method: 'GET', headers: demio.headers }, timeoutMs, MAX_REPORT_BYTES, ); } catch (err) { if (err instanceof Error && (err.message === 'redirect' || err.message === 'too_large')) { return end('demio_unexpected_answer'); } return end('demio_call_failed'); } if (answer.status === 429) { const waitS = Math.max(1, retryAfter(answer.headers.get('retry-after'), Date.now()) ?? DEMIO_DEFAULT_WAIT_S); if (attempt >= DEMIO_READ_TRIES || waitS * 1000 + MIN_CALL_MS > left()) return end('demio_rate_limited'); await sleep(waitS * 1000); continue; } if (answer.status !== 200) return end(demioError(answer.status)); participants = participantsOf(answer.json); if (!participants) return end('demio_unexpected_answer'); break; } summary.participants = participants.length; // 2. Each address once: kept answers first, then checks while the budget, the cap and the key allow. `seen` holds // this run's addresses (in memory, for this run only) so a repeat in Demio's answer is skipped. // Every store call fits in what is left of the budget. const memory = new Memory(state, store, left); // A check is sent only when its whole timeout fits, with the store write after it. const checkNeedsMs = s.timeoutMs + (memory.shared ? STORE_TIMEOUT_MS : 0); const seen = new Set(); for (let i = 0; i < participants.length; i++) { if (left() <= 0) { summary.left = remaining(participants, i, seen); return end('budget_spent'); } const p = participants[i] as Participant; if (!looksLikeAddress(p.email)) { summary.skipped++; continue; } const email = p.email.trim(); if (seen.has(normalized(email))) { summary.skipped++; continue; } const key = await memory.key(eventId, email); const kept = await memory.get(key); if (kept?.reported) { seen.add(normalized(email)); summary.known++; continue; } if (!kept) { const stopBy = state.pausedUntil > Date.now() ? state.pausedFor || 'paused' : summary.checked >= maxChecks ? 'max_checks' : left() < checkNeedsMs ? 'budget_spent' : null; if (stopBy) { summary.left = remaining(participants, i, seen); return end(stopBy); } } seen.add(normalized(email)); let answered: Answered; try { answered = await answerFor(s, state, memory, key, email, { unreportedAll: true, known: kept }); } catch { answered = { decision: unchecked('internal_error'), kept: null, fromMemory: false, sent: false }; } if (answered.sent) summary.checked++; if (!answered.kept) { summary.unchecked++; // Our key refused, out of credits, over its cap or rate limited: the rest wait for the next sweep. if (state.pausedUntil > Date.now()) { summary.left = remaining(participants, i + 1, seen); return end(state.pausedFor || 'paused'); } continue; } if (answered.kept.reported) { // Reported meanwhile by another sweep running at the same time. summary.known++; continue; } // No time left to tell onResult: the answer is kept as not reported, and the next sweep reports it, unpaid. const reportMs = Math.min(REPORT_TIMEOUT_MS, left()); if (reportMs <= 0) { summary.left = remaining(participants, i + 1, seen) + 1; return end('budget_spent'); } const outcome = answered.decision.allow ? 'allowed' : 'stopped'; let ok = true; if (onResult) { const report: SweepResult = { eventId, dateId, email, name: p.name, participantStatus: p.participantStatus, outcome, decision: answered.decision, fromMemory: answered.fromMemory, }; ok = (await bounded(async () => { await onResult(report); return true; }, reportMs)) === true; } if (!ok) { summary.reportFailed++; continue; } summary.reported++; if (outcome === 'stopped') summary.stopped++; await memory.set(key, { ...answered.kept, reported: true }); } return summary; }; } /** Distinct addresses from index `from` on that this run has not handled: they wait for the next sweep. */ function remaining(participants: Participant[], from: number, seen: Set): number { const rest = new Set(); for (let i = from; i < participants.length; i++) { const email = (participants[i] as Participant).email; if (looksLikeAddress(email) && !seen.has(normalized(email))) rest.add(normalized(email)); } return rest.size; }