/** * Humanless client SDK: a tiny, zero-dependency fetch client for the Humanless REST API. * * const hl = new Humanless({ apiKey: process.env.HUMANLESS_API_KEY! }); * const id = await hl.createIdentity({ channels: ["email"] }); * // ...make the app send a code to id.email... * const { code } = await hl.waitForCode({ identityId: id.identity_id }); * * Works in Node 18+, Deno, Bun and browsers (anything with global fetch). */ export type IdentityChannel = "email" | "sms" | "totp"; export type WaitChannel = "any" | "email" | "sms"; export interface Identity { identity_id: string; channels: IdentityChannel[]; email: string | null; phone: string | null; totp_secret: string | null; status: "active" | "deleted" | "expired"; expires_at: string; created_at: string; ended_at: string | null; } export interface Message { type: "otp" | "magic_link" | "raw"; code: string | null; url: string | null; channel: "email" | "sms"; sender: string; subject: string | null; received_at: string; raw_snippet: string; } export interface TotpCode { code: string; seconds_remaining: number; } export interface CreateIdentityOptions { /** * Default ["email"]. "sms" needs a paid plan and leases one of the account's dedicated numbers: * 409 `all_numbers_busy` when all are held by live identities, 503 `numbers_provisioning` (Retry-After) right after an upgrade. */ channels?: IdentityChannel[]; /** Email domain to use (a platform domain or one of your verified domains). */ domain?: string; /** Lifetime in seconds (server default 1h). */ ttl_seconds?: number; } export interface WaitOptions { identityId: string; /** Which inbox to watch. Default "any". */ channel?: WaitChannel; /** Overall deadline in seconds across all long-poll rounds. Default 60. */ timeout?: number; /** * Unix ms. Only messages received at/after this instant are eligible, consumed or not. * Pass Date.now() taken just BEFORE you trigger the send to make the wait race-free and re-readable. */ since?: number | Date; /** Abort the wait early. */ signal?: AbortSignal; } export interface HumanlessOptions { apiKey: string; /** Default: process.env.HUMANLESS_BASE_URL (legacy: VERIFYBOX_BASE_URL) or https://api.usehumanless.com */ baseUrl?: string; /** Custom fetch (tests, proxies). Default: global fetch. */ fetch?: typeof fetch; } /** Any non-2xx API response. `code` is the API's machine-readable error code. */ export class HumanlessError extends Error { constructor( readonly status: number, readonly code: string, message: string, readonly retryAfterSeconds?: number, /** The API's machine-readable `error.details`, when present (e.g. quota numbers and `billing_url`). */ readonly details?: Record, ) { super(`${code}: ${message}`); this.name = "HumanlessError"; } /** * True for `sms_quota_exceeded` (402): the account's included SMS are used up and its credits can't pay * for more, so NEW SMS identities are refused until the owner tops up credits or upgrades * (`details.billing_url`). Existing SMS identities keep receiving. Fall back to email/TOTP. */ get isSmsQuotaExceeded(): boolean { return this.code === "sms_quota_exceeded"; } } /** Thrown by waitForCode / waitForLink / waitForMessage when the overall deadline passes. */ export class HumanlessTimeoutError extends HumanlessError { constructor(seconds: number) { super(408, "timeout", `No matching message arrived within ${seconds}s`); this.name = "HumanlessTimeoutError"; } } /** Server-side cap on a single long-poll round. */ const MAX_ROUND_SECONDS = 60; const DEFAULT_WAIT_SECONDS = 60; function envBaseUrl(): string | undefined { const g = globalThis as { process?: { env?: Record } }; return g.process?.env?.HUMANLESS_BASE_URL ?? g.process?.env?.VERIFYBOX_BASE_URL; } export class Humanless { readonly baseUrl: string; readonly #apiKey: string; readonly #fetch: typeof fetch; constructor(opts: HumanlessOptions) { if (!opts?.apiKey) throw new Error("Humanless: apiKey is required"); this.#apiKey = opts.apiKey; this.baseUrl = (opts.baseUrl ?? envBaseUrl() ?? "https://api.usehumanless.com").replace(/\/+$/, ""); this.#fetch = opts.fetch ?? globalThis.fetch.bind(globalThis); } async #request(method: string, path: string, body?: unknown, signal?: AbortSignal): Promise { const res = await this.#fetch(`${this.baseUrl}${path}`, { method, headers: { authorization: `Bearer ${this.#apiKey}`, accept: "application/json", ...(body !== undefined ? { "content-type": "application/json" } : {}), }, body: body !== undefined ? JSON.stringify(body) : undefined, signal, }); const text = await res.text(); let json: unknown = null; try { json = text ? JSON.parse(text) : null; } catch { /* non-JSON body (proxy error page etc.) */ } if (!res.ok) { const err = (json as { error?: { code?: string; message?: string; details?: Record } } | null)?.error; const ra = res.headers.get("retry-after"); throw new HumanlessError( res.status, err?.code ?? `http_${res.status}`, err?.message ?? (text.slice(0, 200) || res.statusText), ra ? Number(ra) : undefined, err?.details && typeof err.details === "object" ? err.details : undefined, ); } return json as T; } /** POST /v1/identities */ createIdentity(opts: CreateIdentityOptions = {}): Promise { return this.#request("POST", "/v1/identities", opts); } /** GET /v1/identities/:id */ getIdentity(identityId: string): Promise { return this.#request("GET", `/v1/identities/${encodeURIComponent(identityId)}`); } /** GET /v1/identities/:id/totp — the current 6-digit code for the identity's TOTP secret. */ getTotp(identityId: string): Promise { return this.#request("GET", `/v1/identities/${encodeURIComponent(identityId)}/totp`); } /** DELETE /v1/identities/:id — idempotent; frees the account's phone number for its next SMS identity. */ deleteIdentity(identityId: string): Promise<{ identity_id: string; status: "deleted" }> { return this.#request("DELETE", `/v1/identities/${encodeURIComponent(identityId)}`); } /** * Waits for the next message (any type). Long-polls GET /wait, re-polling on 408 until the * overall deadline. Each returned message is consumed: the next call returns the next one. */ waitForMessage(opts: WaitOptions): Promise { return this.#waitUntil(opts, () => true); } /** Waits for a message that contains an OTP code. Messages without a code are skipped. */ async waitForCode(opts: WaitOptions): Promise { return (await this.#waitUntil(opts, (m) => m.code !== null)) as Message & { code: string }; } /** Waits for a message that contains a magic link. Messages without a link are skipped. */ async waitForLink(opts: WaitOptions): Promise { return (await this.#waitUntil(opts, (m) => m.url !== null)) as Message & { url: string }; } async #waitUntil(opts: WaitOptions, accept: (m: Message) => boolean): Promise { const totalSeconds = opts.timeout ?? DEFAULT_WAIT_SECONDS; const deadline = Date.now() + totalSeconds * 1000; const since = opts.since instanceof Date ? opts.since.getTime() : opts.since; let seenUntil: string | null = null; // with `since`, skip messages already rejected by `accept` for (;;) { const remaining = (deadline - Date.now()) / 1000; if (remaining <= 0) throw new HumanlessTimeoutError(totalSeconds); const q = new URLSearchParams({ channel: opts.channel ?? "any", timeout: String(Math.min(MAX_ROUND_SECONDS, Math.max(0, Math.round(remaining * 10) / 10))), }); if (since !== undefined) { const s = seenUntil ? Math.max(since, Date.parse(seenUntil) + 1) : since; q.set("since", String(Math.floor(s))); } let msg: Message; try { msg = await this.#request( "GET", `/v1/identities/${encodeURIComponent(opts.identityId)}/wait?${q}`, undefined, opts.signal, ); } catch (e) { if (e instanceof HumanlessError && e.status === 408) continue; // round timed out; deadline check above throw e; } if (accept(msg)) return msg; seenUntil = msg.received_at; } } } /** * Creates an identity, runs `fn`, and ALWAYS deletes the identity afterwards (even if `fn` throws), * so the account's dedicated phone number is free again promptly (409 all_numbers_busy otherwise). Great inside a Playwright test: * * await withIdentity(hl, { channels: ["email"] }, async (id) => { ... }); */ export async function withIdentity( hl: Humanless, opts: CreateIdentityOptions, fn: (identity: Identity) => Promise, ): Promise { const identity = await hl.createIdentity(opts); try { return await fn(identity); } finally { await hl.deleteIdentity(identity.identity_id).catch(() => {}); } } /** @deprecated Renamed to {@link Humanless}. Kept so code written against the Verifybox SDK keeps working. */ export const Verifybox = Humanless; /** @deprecated Renamed to {@link Humanless}. */ export type Verifybox = Humanless; /** @deprecated Renamed to {@link HumanlessOptions}. */ export type VerifyboxOptions = HumanlessOptions; /** @deprecated Renamed to {@link HumanlessError}. */ export const VerifyboxError = HumanlessError; /** @deprecated Renamed to {@link HumanlessError}. */ export type VerifyboxError = HumanlessError; /** @deprecated Renamed to {@link HumanlessTimeoutError}. */ export const VerifyboxTimeoutError = HumanlessTimeoutError; /** @deprecated Renamed to {@link HumanlessTimeoutError}. */ export type VerifyboxTimeoutError = HumanlessTimeoutError;