// 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 Cal.com: check the email address of each new booking's attendee. One file, no * dependencies; copy it into your server (Next.js, Remix, Hono, Express, Bun, Deno, Cloudflare Workers: anything with * `fetch` and Web Crypto). * * Cal.com has no hook that runs before it creates a booking. Its webhooks (`BOOKING_CREATED`, `BOOKING_REQUESTED`) are * sent after the booking exists, and Cal.com does not read the answer to decide anything. Its App Store apps * (calendars, video, payments, analytics, automation) have no step in the booking form either. So this file cannot * block a booking; it gives two pieces (the setup guide says which to use when): * * - `createCalcomBookingHook()`: a receiver for Cal.com's `BOOKING_CREATED` and `BOOKING_REQUESTED` webhooks. It * checks the `X-Cal-Signature-256` signature, checks the booker's address (the booking form's email answer) and, * when the answer is a status you stop (default: `invalid` only), tells you through `onResult` (default * `onStop: 'none'`), or, if you switch it on (`onStop: 'cancel'`), cancels the booking (or declines one still * waiting for confirmation) through Cal.com's API v2, a few seconds after answering the webhook. * - `checkBookingEmail()`: a server-side check for your own booking flow (Cal.com API v2 or Platform), called before * the booking is created, so a bad address never gets a booking. * * Fails open: no key, a timeout, a network error, a rate limit or any error answer leaves the booking. Only a * definite answer whose status is in `stop` stops it. Our API key goes only to our API, the Cal.com API key only to * your Cal.com API origin; redirects are never followed; nothing here logs an address or a key. */ export const VERSION = '1.0.0'; export const USER_AGENT = `email-validation-calcom/${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. A `valid` answer passes, unless it is marked disposable and `disposable` is stopped. */ export const STOPPABLE = Object.freeze(['invalid', 'disposable', 'catch_all', 'unknown'] as const); export type StoppableStatus = (typeof STOPPABLE)[number]; /** * `unknown` answers that mean our side ran out of time or failed: they never stop a booking, even with `unknown` in * `stop`. */ export const NEVER_STOP_REASONS = Object.freeze(['timeout', 'internal_error'] as const); 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 booking 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 booking: `none` only calls `onResult`; `cancel` is yours to switch on. */ onStop: 'none' as const, /** * The oldest delivery accepted, by its signed `createdAt`, in seconds. Cal.com's signature has no timestamp, so this * bound (ours, not Cal.com's) keeps an old captured delivery from being replayed. */ maxAgeS: 300, /** The reason sent with a cancellation or a decline (Cal.com shows it to the attendee and the host). */ reason: 'The email address given for this booking could not be verified.', /** With `cancel`: how long after the answer the booking is read and cancelled (see `actDelayMs`). */ actDelayMs: 5000, }); /** The API's shortest check time, in seconds: a check that needs longer ends as a free `unknown`. */ export const SERVER_TIMEOUT_S = 5; /** The header that holds Cal.com's signature: the HMAC-SHA256 hex digest of the raw body with the webhook secret. */ export const SIGNATURE_HEADER = 'x-cal-signature-256'; /** What Cal.com sends in the signature header when the webhook has no secret: such deliveries are refused. */ export const NO_SECRET_SIGNATURE = 'no-secret-provided'; /** The events the receiver acts on; it answers any other `200` and ignores it (the test ping included). */ export const EVENTS = Object.freeze(['BOOKING_CREATED', 'BOOKING_REQUESTED'] as const); export type CalcomEvent = (typeof EVENTS)[number]; /** Cal.com's hosted API v2 origin; a self-hosted Cal.com has its own (`calcom.origin`). */ export const CALCOM_API_ORIGIN = 'https://api.cal.com'; /** The `cal-api-version` the booking endpoints are called with on cal.com (its API v2 reference, read 2026-11-22). */ export const CALCOM_API_VERSION = '2026-02-25'; /** * The `cal-api-version` for a self-hosted Cal.com (any other origin): the open-source API v2 has no 2026-02-25 and * serves an unknown version from its oldest bookings controller (other shapes, no decline). 2024-08-13 is the newest * bookings version in the open-source repository (read 2026-11-22). */ export const SELF_HOSTED_API_VERSION = '2024-08-13'; 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 booking (default `invalid`). */ stop?: readonly StoppableStatus[]; /** Milliseconds before the booking stays 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; /** A suggested correction for a typo, e.g. `name@gmail.com`, or null. */ didYouMean: string | null; /** Why there is no answer: `missing_key`, `not_an_address`, `timeout`, `connection_error`, or the API's error 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 whitespace inside is no key. */ function keyOf(value: unknown): string { const trimmed = typeof value === 'string' ? value.trim() : ''; return /^\S+$/.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", not ${String(region)}.`); 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; // Whole milliseconds up to a minute: AbortSignal.timeout throws on a fraction or a huge value. if (typeof timeoutMs !== 'number' || !Number.isInteger(timeoutMs) || timeoutMs <= 0 || timeoutMs > 60_000) { throw new TypeError('timeoutMs must be a whole number of milliseconds from 1 to 60000.'); } 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 pass(error: string, requestId: string | null = null): Decision { return { allow: true, status: null, reason: null, didYouMean: null, error, requestId }; } /** Whether a value is worth a check: something@domain.tld with no spaces (anything else 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 && /^[^\s@]+@[^\s@]+\.[^\s@.]{2,}$/.test(v); } /** * One request to an allowed origin only, redirects never followed, bounded by `timeoutMs`. Rejects on a foreign * host, no answer or a redirect; answers the Response for any other status. */ export async function send( 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 response = await fetchFn(url, { ...init, headers, redirect: 'manual', signal: AbortSignal.timeout(timeoutMs), }); if ((response.status >= 300 && response.status < 400) || response.type === 'opaqueredirect') { await discard(response); throw new Error('redirect'); } return response; } /** 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 } } /** 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: unknown): Promise { if (!s.apiKey) return pass('missing_key'); if (!looksLikeAddress(email)) return pass('not_an_address'); let response: Response; try { response = await send( 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) { const name = err instanceof Error ? err.name : ''; if (name === 'TimeoutError' || name === 'AbortError') return pass('timeout'); if (err instanceof Error && err.message === 'redirect') return pass('unexpected_response'); return pass('connection_error'); } let body: unknown = null; try { body = await response.json(); } catch (err) { const name = err instanceof Error ? err.name : ''; if (name === 'TimeoutError' || name === 'AbortError') return pass('timeout'); body = null; } const record = isObject(body) ? body : {}; const headerId = requestIdOf(response.headers.get('x-request-id'), s.apiKey); if (!response.ok) { const error = isObject(record.error) ? record.error : {}; const code = codeOf(error.code, s.apiKey) || `http_${response.status}`; return pass(code, requestIdOf(error.request_id, s.apiKey) ?? headerId); } const status = record.status; const requestId = requestIdOf(record.request_id, s.apiKey) ?? headerId; if (typeof status !== 'string' || !(STATUSES as readonly string[]).includes(status)) { return pass('unexpected_response', requestId); } const reason = reasonOf(record.reason, s.apiKey); const ourFailure = status === 'unknown' && (NEVER_STOP_REASONS as readonly string[]).includes(reason ?? ''); const stopped = !ourFailure && ((s.stop as readonly string[]).includes(status) || (s.stop.includes('disposable') && record.disposable === true)); return { allow: !stopped, status: status as Status, reason, 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, }; } /** A checker for one configuration (options are checked once, here). Never rejects. */ export function createEmailCheck(options: CheckOptions): (email: string) => Promise { const s = settings(options); return (email) => check(s, email).catch(() => pass('internal_error')); } /** * Checks an address in your own server code before your booking flow (Cal.com API v2, Platform) creates the booking. * Each check uses one credit (`unknown`, malformed and sandbox addresses are free): call it only from your booking * path. */ export function checkBookingEmail(email: string, options: CheckOptions): Promise { return createEmailCheck(options)(email); } // --------------------------------------------------------------------------------------------------------------- // Webhook verification, as Cal.com's source signs it: `X-Cal-Signature-256` holds the HMAC-SHA256 hex digest of the // raw request body, keyed with the webhook's secret (`no-secret-provided` when the webhook has none). There is no // timestamp in the signature, so the signed body's `createdAt` is held to `maxAgeS`. 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 or not a string. */ function signatureHeader(headers: HeaderSource): string | null { 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; } const encoder = new TextEncoder(); function bodyBytes(body: string | Uint8Array): Uint8Array { return typeof body === 'string' ? encoder.encode(body) : body; } 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 secretOf(secret: string | undefined): string { const trimmed = typeof secret === 'string' ? secret.trim() : ''; if (trimmed === '') throw new WebhookVerificationError('Missing webhook secret.'); return trimmed; } /** The `X-Cal-Signature-256` value for a body (for tests of a receiver). */ export async function signCalcomWebhook(body: string | Uint8Array, secret: string): Promise { return toHex(await hmac(secretOf(secret), bodyBytes(body))); } /** * 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 or a wrong signature (a webhook saved without a * secret included), a body that is not a JSON object, or a `createdAt` missing or more than `maxAgeS` seconds from now. */ export async function verifyCalcomWebhook( body: string | Uint8Array, headers: HeaderSource, secret: string | undefined, options: { nowS?: number; maxAgeS?: number } = {}, ): Promise> { const key = secretOf(secret); const given = signatureHeader(headers); if (!given) throw new WebhookVerificationError('Missing webhook signature.'); if (given.trim() === NO_SECRET_SIGNATURE) { throw new WebhookVerificationError('The Cal.com webhook has no secret: set one in Cal.com.'); } const givenBytes = fromHex(given.trim()); const expected = await hmac(key, bodyBytes(body)); if (givenBytes === null || !sameBytes(givenBytes, expected)) { throw new WebhookVerificationError('The webhook signature does not match.'); } 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.'); const createdMs = typeof event.createdAt === 'string' ? Date.parse(event.createdAt) : Number.NaN; if (!Number.isFinite(createdMs)) throw new WebhookVerificationError('The webhook has no createdAt.'); const maxAge = options.maxAgeS ?? DEFAULTS.maxAgeS; const now = options.nowS ?? Date.now() / 1000; if (Math.abs(now - createdMs / 1000) > maxAge) { throw new WebhookVerificationError('The webhook createdAt is outside the allowed age.'); } return event; } // --------------------------------------------------------------------------------------------------------------- // Cal.com's API v2 (only for `onStop: 'cancel'`). export interface CalcomApiOptions { /** A Cal.com API key (`cal_live_…`, Settings → Developer → API keys) of the booking's owner. Server-side only. */ apiKey: string | undefined; /** The API v2 origin: `https://api.cal.com` (default) or your self-hosted Cal.com's. HTTPS, except on localhost. */ origin?: string; /** The `cal-api-version` header (default `2026-02-25` on api.cal.com, `2024-08-13` on any other origin). */ apiVersion?: string; } interface CalcomApi { origin: string; apiKey: string; apiVersion: string; } const LOCAL_HOSTS = new Set(['localhost', '127.0.0.1', '[::1]']); function calcomApi(options: CalcomApiOptions | undefined): CalcomApi | null { if (options === undefined) return null; if (!options || typeof options !== 'object') throw new TypeError('calcom must be an object.'); let url: URL; try { url = new URL(String(options.origin ?? CALCOM_API_ORIGIN).trim()); } catch { throw new TypeError('calcom.origin must be a URL, e.g. https://api.cal.com.'); } const local = LOCAL_HOSTS.has(url.hostname); if (url.protocol !== 'https:' && !(url.protocol === 'http:' && local)) { throw new TypeError('calcom.origin must use https (http only on localhost).'); } if (url.username || url.password || url.search || url.hash || (url.pathname !== '/' && url.pathname !== '')) { throw new TypeError('calcom.origin must be an origin only, with no path, query or credentials.'); } const fallback = url.origin === CALCOM_API_ORIGIN ? CALCOM_API_VERSION : SELF_HOSTED_API_VERSION; const apiVersion = typeof options.apiVersion === 'string' ? options.apiVersion.trim() : fallback; if (!/^\d{4}-\d{2}-\d{2}$/.test(apiVersion)) throw new TypeError('calcom.apiVersion must be a date, YYYY-MM-DD.'); return { origin: url.origin, apiKey: keyOf(options.apiKey), apiVersion }; } /** Cal.com refused or failed a call (status 0: no answer). */ class CalcomCallError extends Error { readonly status: number; constructor(status: number) { super(`Cal.com answered HTTP ${status}`); this.status = status; } } /** Per Cal.com API call. */ const CALCOM_TIMEOUT_MS = 10_000; // --------------------------------------------------------------------------------------------------------------- // 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; export interface HookOptions extends CheckOptions { /** The webhook's secret from Cal.com → Settings → Developer → Webhooks → your webhook. Read it from env. */ secret: string | undefined; /** Cal.com's API v2 access, for `onStop: 'cancel'` (not needed for `none`). */ calcom?: CalcomApiOptions; /** * What happens to a booking whose address is stopped: `none` (default) only calls `onResult`; `cancel` cancels an * accepted booking and declines one still waiting for the host's confirmation, `actDelayMs` after the answer. */ onStop?: StopAction; /** The reason sent with a cancellation or a decline (Cal.com shows it to the attendee and the host). */ reason?: string; /** * With `cancel`: how long after answering Cal.com the receiver reads and cancels the booking (default 5000 ms). * A self-hosted Cal.com sends the webhook in the middle of creating the booking and saves the booking's calendar * and video references only after the receiver answers; a booking cancelled before then keeps its calendar event. */ actDelayMs?: number; /** * With `cancel` on a serverless host: keeps the delayed cancel running after the answer. A long-running server * (Node, Bun, Deno) needs none. Also accepted per delivery. */ waitUntil?: WaitUntil; /** The oldest delivery accepted by its signed `createdAt`, in seconds (default 300). */ maxAgeS?: number; /** Called once per checked booking (never with the address). Errors it throws are ignored. */ onResult?: (result: HookResult) => void | Promise; /** For tests: the current time in seconds. */ nowS?: () => number; } export interface HookResult { /** The booking's uid (Cal.com's `payload.uid`). */ bookingUid: string; /** Cal.com's numeric booking id, when the delivery carries it. */ bookingId: number | null; event: CalcomEvent; /** * `allowed`; `stopped` (a status you stop: `action` says what was done; with `none` the booking stays); or * `unchecked` (no answer, or nothing could be done: the booking stays; `decision.error` says why). */ outcome: 'allowed' | 'stopped' | 'unchecked'; /** `cancel`, `decline`, `none`, or null when nothing was decided. */ action: 'cancel' | 'decline' | 'none' | null; /** Our answer. Its `didYouMean` is always null here: it is an address (the attendee's local part, another domain). */ decision: Decision; } export interface HookResponse { status: number; body: Record; } export interface Delivery { body: string | Uint8Array; headers: HeaderSource; /** Overrides the `waitUntil` option for this delivery. */ waitUntil?: WaitUntil; } const BOOKING_UID = /^[A-Za-z0-9_-]{1,128}$/; function isObject(v: unknown): v is Record { return v !== null && typeof v === 'object' && !Array.isArray(v); } /** Bookings already handled on this instance. */ const SEEN_MAX = 1000; interface Remembered { decision: Decision; /** null: a definite stop whose cancel is not done yet (scheduled, or a Cal.com failure a later delivery retries). */ outcome: HookResult['outcome'] | null; action: HookResult['action']; /** True while a delayed cancel is scheduled or running. */ scheduled?: boolean; } /** * The booker's address in a booking payload: the booking form's email answer (`responses.email.value`), else the * first attendee. Cal.com builds `BOOKING_CREATED`'s attendees booker first, but rebuilds `BOOKING_REQUESTED`'s from * its database with no order, so the form answer comes first. */ function bookerEmail(payload: Record): string | null { const responses = isObject(payload.responses) ? payload.responses : {}; const answer = isObject(responses.email) ? responses.email.value : responses.email; if (typeof answer === 'string' && answer.trim()) return answer; const attendees = Array.isArray(payload.attendees) ? payload.attendees : []; const first = attendees[0]; return isObject(first) && typeof first.email === 'string' ? first.email : 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. A cancel (`onStop: 'cancel'`) runs `actDelayMs` after the answer; its * result goes to `onResult`. */ export function createCalcomWebhookHandler(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 maxAgeS = options.maxAgeS ?? DEFAULTS.maxAgeS; if (typeof maxAgeS !== 'number' || !Number.isFinite(maxAgeS) || maxAgeS <= 0) { throw new TypeError('maxAgeS must be a number of seconds above 0.'); } const actDelayMs = options.actDelayMs ?? DEFAULTS.actDelayMs; if (typeof actDelayMs !== 'number' || !Number.isFinite(actDelayMs) || actDelayMs < 0) { throw new TypeError('actDelayMs must be a number of milliseconds, 0 or more.'); } const reasonText = typeof options.reason === 'string' && options.reason.trim() ? options.reason.trim() : DEFAULTS.reason; const api = calcomApi(options.calcom); const canAct = api !== null && api.apiKey !== ''; const secret = options.secret; // Keyed by the SHA-256 of the booking uid together with the address hash (never the address): an answer is reused // only for the same booking and the same address, so a delivery with another address is checked on its own. const seen = new Map(); const inFlight = new Map>(); const now = () => options.nowS?.() ?? Date.now() / 1000; async function calcom(method: string, path: string, body?: unknown): Promise { const a = api as CalcomApi; return send( s.fetch, a.origin, `${a.origin}${path}`, { method, headers: { Authorization: `Bearer ${a.apiKey}`, 'cal-api-version': a.apiVersion, Accept: 'application/json', ...(body === undefined ? {} : { 'Content-Type': 'application/json' }), }, ...(body === undefined ? {} : { body: JSON.stringify(body) }), }, CALCOM_TIMEOUT_MS, ); } /** The booking now: its status and whether the address checked is still on it; undefined when it is gone. */ async function readBooking( uid: string, address: string, ): Promise<{ status: string; hasAddress: boolean; seated: boolean } | undefined> { const response = await calcom('GET', `/v2/bookings/${encodeURIComponent(uid)}`); if (response.status === 404) { await discard(response); return undefined; } if (!response.ok) { await discard(response); throw new CalcomCallError(response.status); } const body = await response.json().catch(() => null); const data = isObject(body) ? body.data : undefined; // An array (a recurring series) or anything else that is not this one booking: never acted on. if (!isObject(data) || data.uid !== uid) return { status: 'unexpected', hasAddress: false, seated: false }; const attendees = (Array.isArray(data.attendees) ? data.attendees : []).filter(isObject); const seated = attendees.some((a) => typeof a.seatUid === 'string'); let hasAddress = false; for (const a of attendees) { for (const field of [a.email, a.displayEmail]) { if (typeof field === 'string' && (await addressHash(field)) === address) hasAddress = true; } } return { status: typeof data.status === 'string' ? data.status : '', hasAddress, seated }; } /** POSTs a cancel or a decline; Cal.com answers 200 with `status: "success"` or `"error"`. */ async function act(uid: string, action: 'cancel' | 'decline'): Promise { const body = action === 'cancel' ? { cancellationReason: reasonText } : { reason: reasonText }; const response = await calcom('POST', `/v2/bookings/${encodeURIComponent(uid)}/${action}`, body); const answer = await response.json().catch(() => null); if (!response.ok) throw new CalcomCallError(response.status); if (isObject(answer) && answer.status === 'error') throw new CalcomCallError(400); } async function report(result: HookResult): Promise { try { await options.onResult?.(result); } catch { // the customer's callback never changes the answer } } function remember(key: string, entry: Remembered): void { seen.delete(key); seen.set(key, entry); while (seen.size > SEEN_MAX) seen.delete(seen.keys().next().value as string); } return async ({ body, headers, waitUntil }) => { let event: Record; try { event = await verifyCalcomWebhook(body, headers, secret, { nowS: now(), maxAgeS }); } catch (err) { const message = err instanceof WebhookVerificationError ? err.message : 'Webhook verification failed.'; return { status: 400, body: { error: message } }; } const name = event.triggerEvent; if (!(EVENTS as readonly unknown[]).includes(name)) { return { status: 200, body: { ignored: String(name ?? '') } }; } const payload = isObject(event.payload) ? event.payload : null; const uid = payload && typeof payload.uid === 'string' && BOOKING_UID.test(payload.uid) ? payload.uid : null; // No booking uid: Cal.com's test ping, or a custom payload template without one. Nothing to check. if (!payload || !uid) return { status: 200, body: { ignored: 'no_booking' } }; const bookingId = typeof payload.bookingId === 'number' ? payload.bookingId : null; const email = bookerEmail(payload); if (!email) return { status: 200, body: { ignored: 'no_email' } }; const address = await addressHash(email); const key = await sha256Hex(`${uid}\n${address}`); // One booking and address at a time: a second delivery (a resend, a replay) waits for the first and gets its answer. const running = inFlight.get(key); if (running) { const first = await running; return { status: first.status, body: { ...first.body, duplicate: true } }; } const keepAlive = waitUntil ?? options.waitUntil; const work = handleBooking(uid, bookingId, name as CalcomEvent, email, address, key, keepAlive); inFlight.set(key, work); try { return await work; } finally { inFlight.delete(key); } }; async function handleBooking( uid: string, bookingId: number | null, eventName: CalcomEvent, email: string, address: string, key: string, keepAlive: WaitUntil | undefined, ): Promise { const result = (outcome: HookResult['outcome'], action: HookResult['action'], decision: Decision): HookResult => ({ bookingUid: uid, bookingId, event: eventName, outcome, action, decision, }); if (onStop === 'cancel' && !canAct) { // Fails open like a missing API key: nothing could be done to the booking, so nothing is checked or paid. await report(result('unchecked', null, pass('missing_calcom_api_key'))); return { status: 200, body: { outcome: 'unchecked', error: 'missing_calcom_api_key' } }; } const earlier = seen.get(key); if (earlier?.outcome) { const action = earlier.action ? { action: earlier.action } : {}; return { status: 200, body: { outcome: earlier.outcome, ...action, duplicate: true } }; } if (earlier?.scheduled) { return { status: 200, body: { outcome: 'stopped', action: 'scheduled', duplicate: true } }; } let decision = earlier?.decision; if (!decision) { decision = await check(s, email).catch(() => pass('internal_error')); // `didYouMean` is a suggested address: the hook needs none, so it is neither remembered nor handed to onResult. decision = { ...decision, didYouMean: null }; // Only definite answers are remembered: a delivery resent after our outage is checked again. if (decision.status !== null) { remember(key, { decision, outcome: decision.allow ? 'allowed' : null, action: null }); } } if (decision.allow) { const outcome = decision.status === null ? 'unchecked' : 'allowed'; await report(result(outcome, null, decision)); return { status: 200, body: { outcome, ...(decision.error ? { error: decision.error } : {}) } }; } if (onStop === 'none') { remember(key, { decision, outcome: 'stopped', action: 'none' }); await report(result('stopped', 'none', decision)); return { status: 200, body: { outcome: 'stopped', action: 'none', status: decision.status } }; } // `cancel`: answer first, act later. A self-hosted Cal.com that sends webhooks inline waits for this answer before // it saves the booking's calendar and video references; cancelled before that, the host's calendar event stays. const stopped = decision; remember(key, { decision: stopped, outcome: null, action: null, scheduled: true }); const later = (async () => { await sleep(actDelayMs); await cancelLater(uid, address, key, stopped, result); })().catch(() => { // cancelLater reports its own failures; nothing may escape into the host's unhandled rejections }); try { keepAlive?.(later); } catch { // a host without waitUntil support: the work still runs on a long-lived server } return { status: 200, body: { outcome: 'stopped', action: 'scheduled', status: stopped.status } }; } /** * Reads the booking, then cancels or declines it. The delivery is a copy taken when it was sent: act only on a booking * that is still live and still has the address checked; decline (not cancel) one still waiting for confirmation. */ async function cancelLater( uid: string, address: string, key: string, decision: Decision, result: (o: HookResult['outcome'], a: HookResult['action'], d: Decision) => HookResult, ): Promise { const leave = async (error: string): Promise => { remember(key, { decision, outcome: 'unchecked', action: null }); await report(result('unchecked', null, { ...decision, allow: true, error })); }; let action: 'cancel' | 'decline'; try { const booking = await readBooking(uid, address); if (booking === undefined) return await leave('booking_gone'); if (booking.status === 'cancelled' || booking.status === 'rejected') return await leave('booking_already_closed'); if (booking.status === 'pending') action = 'decline'; else if (booking.status === 'accepted' || booking.status === 'awaiting_host') action = 'cancel'; else return await leave('unexpected_booking'); // Seats are never cancelled in this version: a cancel without a seat id cancels every seat. if (booking.seated) return await leave('seated_booking'); if (!booking.hasAddress) return await leave('attendee_changed'); await act(uid, action); } catch (err) { const status = err instanceof CalcomCallError ? err.status : 0; if (status === 0 || status === 429 || status >= 500) { // The answer stays remembered with no outcome: if Cal.com sends the delivery again, it is not checked (or // paid) again and the cancel is tried again. Cal.com's core sends a booking webhook once, so onResult hears. remember(key, { decision, outcome: null, action: null }); await report(result('unchecked', null, { ...decision, allow: true, error: 'calcom_call_failed' })); return; } // Refused (a wrong or revoked key, no access to the booking): a retry cannot help. The booking stays. await leave('calcom_call_refused'); return; } remember(key, { decision, outcome: 'stopped', action }); await report(result('stopped', action, decision)); } } /** The largest body read (bytes): a booking delivery is a few kilobytes. */ export const MAX_BODY_BYTES = 256 * 1024; /** 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 = createCalcomBookingHook({ ... })`. On Workers pass the context: * `fetch: (request, env, ctx) => hook(request, ctx)`. */ export function createCalcomBookingHook( options: HookOptions, ): (request: Request, ctx?: { waitUntil(work: Promise): void }) => Promise { const handle = createCalcomWebhookHandler(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 }); }; }