// 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 Calendly: check the email address of each person who books a meeting with you (the * invitee). One file, no dependencies; copy it into your server (Next.js, Remix, Hono, Express, Bun, Deno, Cloudflare * Workers: anything with `fetch` and Web Crypto). * * Calendly cannot block a booking: its booking page has no step a check could run in, and its webhook subscriptions * (API v2) send `invitee.created` only after the invitee and the event exist, without reading the receiver's answer. * Its API (read 2026-11-23) has no way to write a note, a tag or a field on an invitee or an event (its notes and * custom fields belong to Contacts, which this file does not touch), and no way to cancel one invitee: it can read an * invitee and an event, and cancel a whole event. So this file gives two pieces * (README.md says which to use when): * * - `createCalendlyBookingHook()`: a receiver for Calendly's `invitee.created` webhook. It checks the * `Calendly-Webhook-Signature` header (`t=,v1=`, keyed with * the subscription's signing key) in constant time and holds `t` to a tolerance window (default 3 minutes, as * Calendly's docs show), answers Calendly at once, and then, in the background: reads the invitee fresh through the * API (when you give a token), checks the invitee's address with one `POST /v1/validate`, and tells you the result * through `onResult`. Only if you switch it on (`onStop: 'cancel'`) does it cancel a one-on-one event whose invitee's * address has a status you stop (default: `invalid` only), after reading the invitee and the event again, only while * the invitee is still active and still holds the address checked, and never a group event (a cancel ends the event * for everyone). Guests the invitee adds are never checked, so they never cancel the invitee's meeting. * - `checkBookingEmail()`: a server-side check for your own booking flow (Calendly's Scheduling API, * `POST /invitees`), called before you create the booking, so a bad address never gets one. * * Fails open: no key, a timeout, a network error, a rate limit or any error answer leaves the meeting as it is. Only a * definite answer whose status is in `stop` stops it; `unknown` never does, and never replaces a definite answer * remembered earlier. Our API key goes only to our API, the Calendly token only to https://api.calendly.com; redirects * are never followed; nothing here logs, or puts in an error, an address, a key or a token. */ export const VERSION = '1.0.0'; export const USER_AGENT = `email-validation-calendly/${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 meeting. */ export const STOPPABLE = Object.freeze(['invalid', 'disposable', 'catch_all'] as const); export type StoppableStatus = (typeof STOPPABLE)[number]; export const DEFAULTS = Object.freeze({ /** A booking is a person asking for your time: 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 invitee 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, /** What the receiver does to a stopped meeting: `none` only calls `onResult`; `cancel` is yours to switch on. */ onStop: 'none' as const, /** * How far the signature's `t` may be from now, in seconds: Calendly's docs use 3 minutes. A delivery outside it is * refused (`400`), as a wrong signature is. */ toleranceS: 180, /** The reason sent with a cancellation (Calendly shows it to the invitee and the host). */ reason: 'The email address given for this booking could not be verified.', /** * The longest all calls to Calendly for one delivery may take, waits for its rate limit included (milliseconds). * Under the 30 seconds a Cloudflare Worker's `waitUntil` keeps work alive after the answer. */ calendlyBudgetMs: 20_000, }); /** The widest tolerance window accepted, in seconds. */ export const MAX_TOLERANCE_S = 3600; /** 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 (from its error body, never a bare HTTP status, which a proxy page could send) after which * this receiver sends no check for `MAX_PAUSE_S`: the key is refused, 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', 'insufficient_credits', 'key_daily_cap', ] as const); /** After our API's 429 or 503 without Retry-After, checks pause this long; a longer Retry-After is cut to MAX_PAUSE_S. */ export const DEFAULT_PAUSE_S = 30; export const MAX_PAUSE_S = 300; /** The header that holds Calendly's signature: `t=,v1=`. */ export const SIGNATURE_HEADER = 'calendly-webhook-signature'; /** The one webhook event acted on; any other (`invitee.canceled`, no-shows, routing forms, ...) is answered `200`. */ export const ACTIONABLE_EVENTS = Object.freeze(['invitee.created'] as const); export type CalendlyEvent = (typeof ACTIONABLE_EVENTS)[number]; /** Calendly's API origin: the only host the Calendly token is sent to. */ export const CALENDLY_API_ORIGIN = 'https://api.calendly.com'; /** Per Calendly API call, in milliseconds. */ export const CALENDLY_TIMEOUT_MS = 10_000; /** A Calendly 429 with neither Retry-After nor X-RateLimit-Reset is tried again after this many seconds. */ export const CALENDLY_DEFAULT_WAIT_S = 2; /** How long a definite answer is remembered (in memory and in a `store`), in seconds. */ export const MEMO_TTL_S = 7 * 24 * 60 * 60; /** Invitees and addresses remembered in this process. */ export const MEMORY_MAX = 1000; /** 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 largest body read (bytes): an invitee delivery is a few kilobytes. */ export const MAX_BODY_BYTES = 256 * 1024; export type FetchFn = (input: string, init?: RequestInit) => Promise; export interface CheckOptions { /** Your email-validation.org API key (permission "Validate addresses"). Server-side only: read it from env. */ apiKey: string | undefined; /** `us` (default) or `eu`. */ region?: 'us' | 'eu'; /** The statuses that stop a meeting (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 (always null in the receiver). */ didYouMean: string | null; /** * Why there is no answer (`missing_key`, `not_an_address`, `timeout`, `connection_error`, `paused`, or our code), * or, with an answer the receiver could not act on, why (`group_event`, `invitee_changed`, `calendly_call_failed`...). */ 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 whitespace inside is no key. */ function keyOf(value: unknown): string { const trimmed = typeof value === 'string' ? value.trim() : ''; return /^[\x21-\x7e]+$/.test(trimmed) ? trimmed : ''; } 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 = options.timeoutMs ?? DEFAULTS.timeoutMs; if (typeof timeoutMs !== 'number' || !Number.isInteger(timeoutMs) || timeoutMs < 1 || timeoutMs > 60_000) { throw new TypeError('timeoutMs must be a whole number of milliseconds from 1 to 60000.'); } if (options.fetch !== undefined && typeof options.fetch !== 'function') throw new TypeError('fetch must be a function.'); const fetchFn = options.fetch ?? ((input: string, init?: RequestInit) => globalThis.fetch(input, init)); return { apiKey: keyOf(options.apiKey), origin: API_ORIGINS[region], stop: Object.freeze([...stop]), timeoutMs, fetch: fetchFn, }; } function unchecked(error: string, requestId: string | null = null): Decision { return { allow: true, status: null, reason: null, disposable: false, didYouMean: null, error, requestId }; } /** * Whether a value is worth a check: something@domain.tld with no spaces, control characters, colon or slash (and no * `?` or `#` in the domain). So a link, with a scheme (`https://example.com/@name`) or without one * (`www.example.com/@name`, `medium.com/@name/post.html`), 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 && !/\p{Cc}/u.test(v) && /^[^\s@:/]+@[^\s@:/?#]+\.[^\s@.:/?#]{2,}$/.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'; } } /** * One request to an allowed origin only, redirects never followed, bounded by `timeoutMs` with the body read included * (a `setTimeout`, so the bound is the host's clock). Rejects on a foreign host, no answer, a redirect 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, ): 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([response.text(), expired]); let json: unknown = null; try { json = JSON.parse(text); } 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, nowMs: () => number): 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') 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 code = codeOf(error.code, s.apiKey); const requestId = requestIdOf(error.request_id, s.apiKey) ?? headerId; const stops = (STOP_CODES as readonly string[]).includes(code); const pauses = answer.status === 429 || answer.status === 503; const pauseS = stops ? MAX_PAUSE_S : pauses ? Math.min(retryAfter(answer.headers.get('retry-after'), nowMs()) ?? 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); const disposable = record.disposable === true; return { decision: { allow: !stoppedFor(s, status as Status), status: status as Status, reason, disposable, didYouMean: typeof record.did_you_mean === 'string' && !sharesKey(record.did_you_mean, s.apiKey) && record.did_you_mean ? 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). */ 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, Date.now) .then((r) => r.decision) .catch(() => unchecked('internal_error')); }; } /** * Checks an address in your own server code before your booking flow creates the booking (Calendly's Scheduling API, * `POST /invitees`). Each check uses one credit: call it only from your booking path. */ export function checkBookingEmail(email: string, options: CheckOptions): Promise { return createEmailCheck(options)(email); } // --------------------------------------------------------------------------------------------------------------- // Webhook verification, as Calendly documents it: `Calendly-Webhook-Signature: t=,v1=`, where the // hex is the HMAC-SHA256, keyed with the subscription's signing key, of `t`, the character `.` and the raw request // body; a `t` too far from now is refused (replays). export class WebhookVerificationError extends Error { constructor(message: string) { super(message); this.name = 'WebhookVerificationError'; } } export type HeaderSource = Headers | Record; /** The signature header, any case; null when missing, repeated (as separate values) or not a string. */ function signatureHeader(headers: HeaderSource): string | null { // A Headers joins a repeated header with ", ": the parse below then sees two `t=` and refuses it. if (headers instanceof Headers) return headers.get(SIGNATURE_HEADER); if (!headers || typeof headers !== 'object') return null; const values: string[] = []; for (const [key, value] of Object.entries(headers)) { if (key.toLowerCase() !== SIGNATURE_HEADER || value === undefined || value === null) continue; if (typeof value === 'string') values.push(value); else if (Array.isArray(value) && value.every((v) => typeof v === 'string')) values.push(...value); else return null; } return values.length === 1 ? (values[0] as string) : null; } /** * The header's parts: exactly one `t` (whole seconds) and one to four `v1` (64 hex characters); other keys are * ignored. Null when it is not that. */ function parseSignature(value: string): { t: string; v1: Uint8Array[] } | null { const parts = value.split(','); if (parts.length > 8) return null; const ts: string[] = []; const v1: Uint8Array[] = []; for (const part of parts) { const at = part.indexOf('='); if (at < 1) return null; const key = part.slice(0, at).trim(); const val = part.slice(at + 1).trim(); if (key === 't') { if (!/^\d{1,12}$/.test(val)) return null; ts.push(val); } else if (key === 'v1') { const bytes = /^[0-9A-Fa-f]{64}$/.test(val) ? fromHex(val) : null; if (!bytes) return null; v1.push(bytes); } } if (ts.length !== 1 || v1.length < 1 || v1.length > 4) return null; return { t: ts[0] as string, v1 }; } const encoder = new TextEncoder(); function bodyBytes(body: string | Uint8Array): Uint8Array { return typeof body === 'string' ? encoder.encode(body) : body; } /** `t`, the character `.`, and the raw body: what Calendly signs. */ function signedContent(t: string, body: string | Uint8Array): Uint8Array { const head = encoder.encode(`${t}.`); const rest = bodyBytes(body); const out = new Uint8Array(head.length + rest.length); out.set(head, 0); out.set(rest, head.length); return out; } async function hmac(key: string, content: Uint8Array): Promise { const cryptoKey = await crypto.subtle.importKey( 'raw', encoder.encode(key) as BufferSource, { name: 'HMAC', hash: 'SHA-256' }, false, ['sign'], ); return new Uint8Array(await crypto.subtle.sign('HMAC', cryptoKey, content as BufferSource)); } function toHex(bytes: Uint8Array): string { let out = ''; for (const b of bytes) out += b.toString(16).padStart(2, '0'); return out; } async function sha256Hex(text: string): Promise { return toHex(new Uint8Array(await crypto.subtle.digest('SHA-256', encoder.encode(text) as BufferSource))); } /** The SHA-256 (hex) of an address, trimmed and lowercased: what the receiver remembers instead of the address. */ function addressHash(email: string): Promise { return sha256Hex(email.trim().toLowerCase()); } function fromHex(text: string): Uint8Array | null { if (!/^(?:[0-9a-fA-F]{2})+$/.test(text)) return null; const out = new Uint8Array(text.length / 2); for (let i = 0; i < out.length; i++) out[i] = Number.parseInt(text.slice(i * 2, i * 2 + 2), 16); return out; } function sameBytes(a: Uint8Array, b: Uint8Array): boolean { if (a.length !== b.length) return false; let diff = 0; for (let i = 0; i < a.length; i++) diff |= (a[i] as number) ^ (b[i] as number); return diff === 0; } function signingKeyOf(signingKey: string | undefined): string { const trimmed = typeof signingKey === 'string' ? signingKey.trim() : ''; if (trimmed === '') throw new WebhookVerificationError('Missing webhook signing key.'); return trimmed; } function toleranceOf(value: unknown): number { const toleranceS = value ?? DEFAULTS.toleranceS; if ( typeof toleranceS !== 'number' || !Number.isInteger(toleranceS) || toleranceS < 1 || toleranceS > MAX_TOLERANCE_S ) { throw new TypeError(`toleranceS must be a whole number of seconds from 1 to ${MAX_TOLERANCE_S}.`); } return toleranceS; } /** The `Calendly-Webhook-Signature` value for a body at `t` (unix seconds), as Calendly sends it (for tests). */ export async function signCalendlyWebhook(body: string | Uint8Array, signingKey: string, t: number): Promise { if (!Number.isInteger(t) || t < 0) throw new TypeError('t must be whole unix seconds.'); return `t=${t},v1=${toHex(await hmac(signingKeyOf(signingKey), signedContent(String(t), body)))}`; } export interface VerifyOptions { /** The clock in milliseconds (default `Date.now()`). */ nowMs?: number; /** How far `t` may be from now, in whole seconds, 1 to 3600 (default 180). */ toleranceS?: number; } /** * Verifies a delivery and returns the parsed body. `body` is the raw request body, exactly as received (a string or * the bytes). Throws `WebhookVerificationError` on any failed check: no signing key, no or a malformed or wrong * signature, a `t` outside the tolerance window, or a body that is not a JSON object. Each `v1` is compared in * constant time, all of them every time; the window is checked only after a signature matched. */ export async function verifyCalendlyWebhook( body: string | Uint8Array, headers: HeaderSource, signingKey: string | undefined, options: VerifyOptions = {}, ): Promise> { const key = signingKeyOf(signingKey); const toleranceS = toleranceOf(options.toleranceS); const given = signatureHeader(headers); if (!given) throw new WebhookVerificationError('Missing webhook signature.'); const parsed = parseSignature(given); if (!parsed) throw new WebhookVerificationError('The webhook signature does not match.'); const expected = await hmac(key, signedContent(parsed.t, body)); let matched = false; for (const candidate of parsed.v1) matched = sameBytes(candidate, expected) || matched; if (!matched) throw new WebhookVerificationError('The webhook signature does not match.'); const nowMs = options.nowMs ?? Date.now(); if (Math.abs(nowMs - Number(parsed.t) * 1000) > toleranceS * 1000) { throw new WebhookVerificationError('The webhook timestamp is outside the tolerance window.'); } let event: unknown = null; try { event = JSON.parse(typeof body === 'string' ? body : new TextDecoder().decode(body)); } catch { // not JSON: refused below } if (!isObject(event)) throw new WebhookVerificationError('The webhook body is not JSON.'); return event; } // --------------------------------------------------------------------------------------------------------------- // Calendly's resource links. A link is read only as these exact shapes on https://api.calendly.com: never a host of // the delivery's choosing, and never sent to our API as an address. const UUID = '[A-Za-z0-9_-]{1,64}'; const INVITEE_URI = new RegExp(`^https://api\\.calendly\\.com/scheduled_events/(${UUID})/invitees/(${UUID})$`); const EVENT_URI = new RegExp(`^https://api\\.calendly\\.com/scheduled_events/(${UUID})$`); /** An invitee's two ids. */ export interface InviteeIds { eventUuid: string; inviteeUuid: string; } /** The ids in an invitee link (`https://api.calendly.com/scheduled_events/{event}/invitees/{invitee}`), or null. */ export function parseInviteeUri(value: unknown): InviteeIds | null { const match = typeof value === 'string' ? INVITEE_URI.exec(value) : null; return match ? { eventUuid: match[1] as string, inviteeUuid: match[2] as string } : null; } /** The id in an event link (`https://api.calendly.com/scheduled_events/{event}`), or null. */ export function parseEventUri(value: unknown): string | null { const match = typeof value === 'string' ? EVENT_URI.exec(value) : null; return match ? (match[1] as string) : null; } const inviteeUri = (ids: InviteeIds) => `${CALENDLY_API_ORIGIN}/scheduled_events/${ids.eventUuid}/invitees/${ids.inviteeUuid}`; const eventUri = (eventUuid: string) => `${CALENDLY_API_ORIGIN}/scheduled_events/${eventUuid}`; // --------------------------------------------------------------------------------------------------------------- // The webhook receiver. export type StopAction = 'none' | 'cancel'; /** Keeps work running after the answer (Cloudflare Workers `ctx.waitUntil`, Next.js `after`, Vercel `waitUntil`). */ export type WaitUntil = (work: Promise) => void; /** A definite answer kept for an invitee and address: never the address, never a suggestion. */ export interface Remembered { status: Exclude; reason: string | null; disposable: boolean; requestId: string | null; } /** * Where definite answers are kept across restarts and instances (Workers KV, Redis, a database table). Keys are * `ev-calendly:`, values a `Remembered`: never an address, a * key or a token. `ttlSeconds` is how long the value matters. Errors and reads slower than STORE_TIMEOUT_MS are * ignored (the receiver then checks again). */ export interface Store { get(key: string): Promise | unknown; set(key: string, value: Remembered, ttlSeconds: number): Promise | void; } export interface HookOptions extends CheckOptions { /** * The webhook subscription's signing key: the `signing_key` you set when you created the subscription (a personal * access token), or your OAuth app's webhook signing key. Read it from env. */ signingKey: string | undefined; /** * A Calendly personal access token (or an OAuth access token, which expires and is never refreshed here) of the * account that owns the subscription. With it, the receiver reads each invitee fresh before it pays for a check * (which also proves the token works); `onStop: 'cancel'` needs it. Read it from env. Sent only to * https://api.calendly.com. */ calendlyToken?: string; /** What happens to a meeting whose invitee's address is stopped: `none` (default) or `cancel`. */ onStop?: StopAction; /** The reason sent with a cancellation. */ reason?: string; /** How far the signature's `t` may be from now, in whole seconds, 1 to 3600 (default 180). */ toleranceS?: number; /** The longest all Calendly calls of one delivery may take, rate-limit waits included (default 20000 ms). */ calendlyBudgetMs?: number; /** Keeps definite answers across restarts and instances. Default: this receiver's memory only. */ store?: Store; /** Keeps the background work running after the answer on a serverless host. Also accepted per delivery. */ waitUntil?: WaitUntil; /** Called once per invitee and address handled (never with the address). Errors it throws are ignored. */ onResult?: (result: HookResult) => void | Promise; /** For tests: the clock in milliseconds. Default `Date.now`. */ now?: () => number; } export interface HookResult { /** The scheduled event's id (the last part of its link). */ eventUuid: string; /** The invitee's id. */ inviteeUuid: string; /** The webhook event that started the check. */ event: CalendlyEvent; /** True when this invitee replaces one who rescheduled (`old_invitee` is set). */ rescheduled: boolean; /** * `allowed`; `stopped` (a status you stop: `action` says what was done; with `none` the meeting stays, and with * `cancel` configured `decision.error` says why it was not cancelled); or `unchecked` (no answer: the meeting * stays; `decision.error` says why). */ outcome: 'allowed' | 'stopped' | 'unchecked'; /** `cancel`, `none`, or null when nothing was decided. */ action: 'cancel' | 'none' | null; /** True when the answer came from an earlier check of this invitee (or the one it rescheduled) and address. */ remembered: boolean; /** Our answer. Its `didYouMean` is always null here: it is an address. */ decision: Decision; } export interface HookResponse { status: number; body: Record; /** The background work (the reads, the check, the cancel, `onResult`). Never rejects. */ done: Promise; } export interface Delivery { body: string | Uint8Array; headers: HeaderSource; /** Overrides the `waitUntil` option for this delivery. */ waitUntil?: WaitUntil; } const STORE_PREFIX = 'ev-calendly:'; const NOTHING: Promise = Promise.resolve(); /** A Calendly call that was refused (401/403: the token), failed (0: no answer, 429 past the budget, 5xx) or other. */ class CalendlyCallError extends Error { readonly status: number; constructor(status: number) { super(`Calendly answered HTTP ${status}`); this.status = status; } } function storedAnswer(value: unknown): Remembered | null { if (!isObject(value)) return null; const { status, reason, disposable, requestId } = 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 : null, disposable: disposable === true, requestId: typeof requestId === 'string' ? requestId : null, }; } /** Per invitee and address in this receiver. */ interface Memo { answer: Remembered | null; /** Set once the invitee was handled to its end (no later delivery of it does anything). */ outcome: HookResult['outcome'] | null; at: number; } /** The seconds a Calendly 429 asks to wait: Retry-After, else X-RateLimit-Reset (seconds), else null. */ function calendlyWait(headers: Headers, nowMs: number): number | null { const after = retryAfter(headers.get('retry-after'), nowMs); if (after !== null) return after; const reset = headers.get('x-ratelimit-reset')?.trim() ?? ''; return /^\d{1,9}$/.test(reset) ? Number(reset) : null; } const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms)); /** * Handles one delivery: `body` is the raw request body (string or bytes), `headers` its headers. Answers 400 for a * delivery that fails verification, else 200 at once; the work runs after the answer (`done`, also handed to * `waitUntil`) and its result goes to `onResult`. */ export function createCalendlyWebhookHandler(options: HookOptions): (delivery: Delivery) => Promise { const s = settings(options); const onStop = options.onStop ?? DEFAULTS.onStop; if (onStop !== 'none' && onStop !== 'cancel') throw new TypeError('onStop must be "none" or "cancel".'); const toleranceS = toleranceOf(options.toleranceS); const budgetMs = options.calendlyBudgetMs ?? DEFAULTS.calendlyBudgetMs; if (typeof budgetMs !== 'number' || !Number.isInteger(budgetMs) || budgetMs < 1 || budgetMs > 600_000) { throw new TypeError('calendlyBudgetMs must be a whole number of milliseconds from 1 to 600000.'); } const store = options.store; if (store !== undefined && (typeof store?.get !== 'function' || typeof store?.set !== 'function')) { throw new TypeError('store must have get and set.'); } const reasonText = typeof options.reason === 'string' && options.reason.trim() ? options.reason.trim().slice(0, 500) : DEFAULTS.reason; const token = keyOf(options.calendlyToken); const signingKey = options.signingKey; const now = options.now ?? Date.now; const memory = new Map(); const inFlight = new Map>(); let pausedUntil = 0; async function report(result: HookResult): Promise { try { await options.onResult?.(result); } catch { // the customer's callback never changes anything } } function remember(key: string, memo: Omit): void { memory.delete(key); memory.set(key, { ...memo, at: now() }); while (memory.size > MEMORY_MAX) memory.delete(memory.keys().next().value as string); } function recalled(key: string | null): Memo | null { if (key === null) return null; const memo = memory.get(key); if (!memo) return null; if (now() - memo.at > MEMO_TTL_S * 1000) { memory.delete(key); return null; } return memo; } /** `work`, or `fallback` once STORE_TIMEOUT_MS has passed (a hung store never holds the work). */ async function within(work: () => Promise | T, fallback: F): Promise { let timer: ReturnType | undefined; const late = new Promise((resolve) => { timer = setTimeout(() => resolve(fallback), STORE_TIMEOUT_MS); }); try { return await Promise.race([Promise.resolve().then(work), late]); } catch { return fallback; } finally { clearTimeout(timer); } } /** * One Calendly API call within the delivery's budget: a 429 is tried again after its Retry-After, else its * X-RateLimit-Reset, else CALENDLY_DEFAULT_WAIT_S (at least a second), while the wait fits in what is left of the * budget; past it, the call fails. */ async function calendly( deadline: number, method: string, path: string, body?: Record, ): Promise { for (;;) { const left = deadline - now(); if (left < 1) throw new CalendlyCallError(0); let answer: CallAnswer; try { answer = await call( s.fetch, CALENDLY_API_ORIGIN, `${CALENDLY_API_ORIGIN}${path}`, { method, headers: { Authorization: `Bearer ${token}`, Accept: 'application/json', ...(body === undefined ? {} : { 'Content-Type': 'application/json' }), }, ...(body === undefined ? {} : { body: JSON.stringify(body) }), }, Math.min(CALENDLY_TIMEOUT_MS, Math.floor(left)), ); } catch { throw new CalendlyCallError(0); } if (answer.status !== 429) return answer; const waitS = calendlyWait(answer.headers, now()) ?? CALENDLY_DEFAULT_WAIT_S; // At least a second between tries: a wait of 0 (or a past date) never turns into a tight loop. const waitMs = Math.max(1, waitS) * 1000; if (waitMs >= deadline - now()) throw new CalendlyCallError(429); await sleep(waitMs); } } const path = (ids: InviteeIds) => `/scheduled_events/${encodeURIComponent(ids.eventUuid)}/invitees/${encodeURIComponent(ids.inviteeUuid)}`; /** The invitee now, or undefined when it is gone; throws CalendlyCallError when Calendly refused or failed. */ async function readInvitee(deadline: number, ids: InviteeIds): Promise | undefined> { const answer = await calendly(deadline, 'GET', path(ids)); if (answer.status === 404) return undefined; if (answer.status < 200 || answer.status > 299) throw new CalendlyCallError(answer.status); const invitee = isObject(answer.json) && isObject(answer.json.resource) ? answer.json.resource : null; // Anything that is not this one invitee, of this one event, is never acted on. if (!invitee || invitee.uri !== inviteeUri(ids) || parseEventUri(invitee.event) !== ids.eventUuid) { throw new CalendlyCallError(-1); } return invitee; } /** The scheduled event now, or undefined when it is gone. */ async function readEvent(deadline: number, eventUuid: string): Promise | undefined> { const answer = await calendly(deadline, 'GET', `/scheduled_events/${encodeURIComponent(eventUuid)}`); if (answer.status === 404) return undefined; if (answer.status < 200 || answer.status > 299) throw new CalendlyCallError(answer.status); const event = isObject(answer.json) && isObject(answer.json.resource) ? answer.json.resource : null; if (!event || event.uri !== eventUri(eventUuid)) throw new CalendlyCallError(-1); return event; } /** Whether a fresh invitee still is active and holds the address checked; else why not. */ async function stillHolds(invitee: Record | undefined, address: string): Promise { if (invitee === undefined) return 'invitee_gone'; if (invitee.status !== 'active') return 'invitee_canceled'; const email = typeof invitee.email === 'string' ? invitee.email : ''; return email.trim() && (await addressHash(email)) === address ? null : 'invitee_changed'; } return async ({ body, headers, waitUntil }) => { let delivery: Record; try { delivery = await verifyCalendlyWebhook(body, headers, signingKey, { nowMs: now(), toleranceS }); } catch (err) { const message = err instanceof WebhookVerificationError ? err.message : 'Webhook verification failed.'; return { status: 400, body: { error: message }, done: NOTHING }; } const type = delivery.event; if (typeof type !== 'string' || !(ACTIONABLE_EVENTS as readonly string[]).includes(type)) { return { status: 200, body: { ignored: typeof type === 'string' ? type.slice(0, 64) : '' }, done: NOTHING }; } const invitee = isObject(delivery.payload) ? delivery.payload : null; const ids = invitee ? parseInviteeUri(invitee.uri) : null; // The invitee's link decides which event it belongs to; a payload naming another event is not acted on. if (!invitee || !ids || (invitee.event !== undefined && parseEventUri(invitee.event) !== ids.eventUuid)) { return { status: 200, body: { ignored: 'no_invitee' }, done: NOTHING }; } if (invitee.status === 'canceled') return { status: 200, body: { ignored: 'invitee_canceled' }, done: NOTHING }; const email = typeof invitee.email === 'string' && invitee.email.trim() ? invitee.email : null; if (!email) return { status: 200, body: { ignored: 'no_email' }, done: NOTHING }; const previous = parseInviteeUri(invitee.old_invitee); const work = (async () => { const address = await addressHash(email); const key = await sha256Hex(`${ids.eventUuid}/${ids.inviteeUuid}\n${address}`); const previousKey = previous ? await sha256Hex(`${previous.eventUuid}/${previous.inviteeUuid}\n${address}`) : null; // One invitee and address at a time: a second copy of the delivery waits for the first. for (let running = inFlight.get(key); running; running = inFlight.get(key)) await running; const mine = handle(ids, previous !== null, email, address, key, previousKey).catch(() => undefined); inFlight.set(key, mine); try { await mine; } finally { if (inFlight.get(key) === mine) inFlight.delete(key); } })().catch(() => { // handle reports its own failures; nothing may escape into the host's unhandled rejections }); try { (waitUntil ?? options.waitUntil)?.(work); } catch { // a host without waitUntil support: the work still runs on a long-lived server } return { status: 200, body: { received: true }, done: work }; }; async function handle( ids: InviteeIds, rescheduled: boolean, email: string, address: string, key: string, previousKey: string | null, ): Promise { const result = ( outcome: HookResult['outcome'], action: HookResult['action'], decision: Decision, remembered = false, ): HookResult => ({ eventUuid: ids.eventUuid, inviteeUuid: ids.inviteeUuid, event: 'invitee.created', rescheduled, outcome, action, remembered, decision, }); const leave = (error: string, decision: Decision = unchecked(error)) => report(result('unchecked', null, { ...decision, allow: true, didYouMean: null, error })); const failure = (err: unknown) => { const status = err instanceof CalendlyCallError ? err.status : 0; if (status === 401 || status === 403) return 'calendly_token_refused'; if (status === 429) return 'calendly_rate_limited'; if (status === -1) return 'unexpected_invitee'; if (status === 0 || status >= 500) return 'calendly_call_failed'; return 'calendly_call_refused'; }; const memo = recalled(key); // Handled to its end already (a copy of the delivery): nothing more to do or report. if (memo?.outcome) return; if (!s.apiKey) return leave('missing_key'); if (onStop === 'cancel' && !token) return leave('missing_calendly_token'); // A definite answer for this invitee (or the one it rescheduled) and address, from this process or the store. let answer = memo?.answer ?? recalled(previousKey)?.answer ?? null; if (!answer && store) { for (const k of previousKey ? [key, previousKey] : [key]) { answer = storedAnswer(await within(() => store.get(STORE_PREFIX + k), null)); if (answer) break; } } const fromMemory = answer !== null; // Checks are paused (our key refused, out of credits, rate-limited): no Calendly quota spent on a read either. if (!answer && now() < pausedUntil) return leave('paused'); const deadline = now() + budgetMs; // Read the invitee fresh: it proves the token before a check is paid, and an invitee already canceled (or gone, // or no longer holding the address) is not checked at all. if (token) { let why: string | null; try { why = await stillHolds(await readInvitee(deadline, ids), address); } catch (err) { return leave(failure(err)); } if (why) return leave(why); } let decision: Decision; if (answer) { decision = { allow: !stoppedFor(s, answer.status), status: answer.status, reason: answer.reason, disposable: answer.disposable, didYouMean: null, error: null, requestId: answer.requestId, }; } else { if (now() < pausedUntil) return leave('paused'); if (!looksLikeAddress(email)) return leave('not_an_address'); const checked = await check(s, email, now).catch(() => ({ decision: unchecked('internal_error'), pauseS: null })); if (checked.pauseS !== null) pausedUntil = Math.max(pausedUntil, now() + checked.pauseS * 1000); decision = { ...checked.decision, didYouMean: null }; // Only a definite answer is kept: our timeout, an error or an `unknown` keeps nothing and replaces nothing. if (decision.status !== null && decision.status !== 'unknown') { answer = { status: decision.status, reason: decision.reason, disposable: decision.disposable, requestId: decision.requestId, }; remember(key, { answer, outcome: null }); const kept = answer; if (store) await within(() => store.set(STORE_PREFIX + key, kept, MEMO_TTL_S), undefined); } } if (decision.status === null) return leave(decision.error ?? 'unchecked', decision); if (decision.allow) { // An `unknown` keeps nothing: a later copy of the delivery checks again. if (answer) remember(key, { answer, outcome: 'allowed' }); return report(result('allowed', null, decision, fromMemory)); } if (onStop === 'none') { remember(key, { answer, outcome: 'stopped' }); return report(result('stopped', 'none', decision, fromMemory)); } // `cancel`: read the invitee and the event again and cancel only while the invitee is still active and holds the // address checked, and the event is active and one-on-one (`invitees_counter.limit` 1: a group event is never // cancelled, as a cancel ends it for everyone). Anything else is reported stopped with no action and the reason // in `decision.error`; the answer stays kept (no outcome), so a later copy of the delivery tries again unpaid. const stopped = decision; const refuse = (error: string) => { remember(key, { answer, outcome: null }); return report(result('stopped', 'none', { ...stopped, error }, fromMemory)); }; try { const why = await stillHolds(await readInvitee(deadline, ids), address); if (why) return refuse(why); const event = await readEvent(deadline, ids.eventUuid); if (event === undefined) return refuse('event_gone'); if (event.status !== 'active') return refuse('event_not_cancelable'); if (typeof event.end_time === 'string' && Date.parse(event.end_time) <= now()) { return refuse('event_not_cancelable'); } const counter = isObject(event.invitees_counter) ? event.invitees_counter : null; if (counter?.limit !== 1 || typeof counter.active !== 'number' || counter.active > 1) { return refuse('group_event'); } const cancelled = await calendly( deadline, 'POST', `/scheduled_events/${encodeURIComponent(ids.eventUuid)}/cancellation`, { reason: reasonText }, ); if (cancelled.status === 404) return refuse('event_gone'); // Calendly answers 403 also for an event that ended or was cancelled since the read: not the token's fault. const message = isObject(cancelled.json) ? cancelled.json.message : null; if (cancelled.status === 403 && (message === 'Event in the past' || message === 'Event is already canceled')) { return refuse('event_not_cancelable'); } if (cancelled.status < 200 || cancelled.status > 299) throw new CalendlyCallError(cancelled.status); } catch (err) { return refuse(failure(err)); } remember(key, { answer, outcome: 'stopped' }); return report(result('stopped', 'cancel', stopped, fromMemory)); } } /** Reads a body as a stream, stopping past `max` bytes (a chunked body has no Content-Length to check first). */ async function readCapped(request: Request, max: number): Promise | null> { if (!request.body) return new Uint8Array(0); const reader = request.body.getReader(); const chunks: Uint8Array[] = []; 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; } /** * The same receiver for a web `Request` (Next.js route handlers, Remix, Hono, Workers, Bun, Deno): * `export const POST = createCalendlyBookingHook({ ... })`. On Workers pass the context so the work after the answer * runs to its end: `fetch: (request, env, ctx) => hook(request, ctx)`. */ export function createCalendlyBookingHook( options: HookOptions, ): (request: Request, ctx?: { waitUntil(work: Promise): void }) => Promise { const handle = createCalendlyWebhookHandler(options); return async (request, ctx) => { if (request.method !== 'POST') return Response.json({ error: 'Use POST.' }, { status: 405 }); const declared = Number(request.headers.get('content-length') ?? '0'); if (declared > MAX_BODY_BYTES) return Response.json({ error: 'Body too large.' }, { status: 413 }); const bytes = await readCapped(request, MAX_BODY_BYTES); if (bytes === null) return Response.json({ error: 'Body too large.' }, { status: 413 }); const waitUntil = ctx && typeof ctx.waitUntil === 'function' ? (w: Promise) => ctx.waitUntil(w) : undefined; const result = await handle({ body: bytes, headers: request.headers, waitUntil }); return Response.json(result.body, { status: result.status }); }; }