# Humanless – complete documentation > Humanless is a verification inbox API and remote MCP server for end-to-end tests and AI browser agents. It gives every test run or agent task a disposable email inbox, a dedicated receive-only US phone number and a TOTP authenticator, and a push-based long-poll wait returns the OTP code or magic link (already parsed) the moment the message arrives. For testing and automating applications you own or are authorized to test. Source: https://usehumanless.com/llms.txt · Generated 2026-12-03. Each section below is one docs page; its canonical URL is given under its title. ## Humanless documentation URL: https://usehumanless.com/docs/ (Markdown: https://usehumanless.com/docs/index.md) > Humanless gives every test run and every AI agent task its own disposable email inbox, a dedicated receive-only US phone number and a TOTP authenticator. It returns the verification code or magic link, already parsed, as soon as the message arrives. You can use it through a REST API, a TypeScript SDK or a remote MCP server. Humanless is for testing and automating **applications you own or are authorized to test**, such as end-to-end suites, QA, and AI agents running sign-up, login and 2FA flows on your own product. See the [Terms](https://usehumanless.com/terms). ### How it works 1. **Create an identity.** `POST /v1/identities` with the channels you need (`email`, `sms`, `totp`). You get back an email address, an E.164 phone number and/or a base32 TOTP secret. 2. **Use it in your app.** Type the email or phone number into your sign-up or login form and submit it. 3. **Wait for the code.** `GET /v1/identities/:id/wait` long-polls and returns as soon as the message lands. You get the parsed `code` (OTP) and/or `url` (magic link). There is no polling interval to tune and no `sleep`. 4. **Delete the identity** when you're done. `DELETE /v1/identities/:id` releases its phone number for your next SMS identity. ### Start here - [Quickstart](https://usehumanless.com/docs/quickstart): get an API key and receive your first code in about two minutes with curl. - [REST API reference](https://usehumanless.com/docs/api): every endpoint, parameter, response field and error code. - [MCP server](https://usehumanless.com/docs/mcp): connect Claude Code, Claude Desktop, Cursor, VS Code or any MCP client to `https://api.usehumanless.com/mcp`. - [Playwright guide](https://usehumanless.com/docs/playwright): email OTP, magic link, SMS and TOTP tests with Playwright. - [TypeScript SDK](https://usehumanless.com/docs/sdk): the zero-dependency `Humanless` client, `waitForCode`, `waitForLink` and `withIdentity`. ### At a glance | | | |---|---| | API base URL | `https://api.usehumanless.com` | | MCP endpoint | `https://api.usehumanless.com/mcp` (Streamable HTTP, stateless) | | Auth | `Authorization: Bearer hl_live_...` | | Channels | `email` (OTP + magic links), `sms` (dedicated US numbers, receive-only), `totp` | | Wait | Push-based long-poll, up to 60 s per request, or Server-Sent Events | | Identity lifetime | 1 hour by default (`ttl_seconds`), up to 24 hours | | Errors | JSON `{ "error": { "code", "message", "details?" } }` with stable codes | ### Pricing - **Free**: email and TOTP identities, REST API, SDK and MCP. - **Pay as you go**: $5 per dedicated number per 30 days plus $0.10 per SMS received. Prepaid credits start at $20. - **Builder**: $49 per month with 1 dedicated US number and 500 SMS per month included. - **Pro**: $199 per month with 5 dedicated US numbers and 2,500 SMS per month. - Identity creation is rate-limited per plan (30, 300 or 1,000 per hour); see [rate limits](https://usehumanless.com/docs/api#rate-limits). Custom email domains are available on request (hello@usehumanless.com). - Additional SMS on Builder and Pro cost $0.08 each. ### Machine-readable docs Every docs page is also available as Markdown at the same path with a `.md` extension, for example [/docs/api.md](https://usehumanless.com/docs/api.md). The whole documentation set is at [/llms.txt](https://usehumanless.com/llms.txt) (index) and [/llms-full.txt](https://usehumanless.com/llms-full.txt) (everything in one file). --- ## Quickstart URL: https://usehumanless.com/docs/quickstart (Markdown: https://usehumanless.com/docs/quickstart.md) > Create a disposable inbox, send a code to it, and get the parsed OTP back from one blocking API call. It takes about two minutes and uses only curl. ### 1. Get an API key Sign up at [api.usehumanless.com/app](https://api.usehumanless.com/app) and create an API key. Keys start with `hl_live_`. Export it so the examples below can use it: ```bash export HUMANLESS_API_KEY="hl_live_..." ``` Send the key as a Bearer token on every request: `Authorization: Bearer hl_live_...`. Keep it secret. Store it in your CI secret store, not in your repository. ### 2. Create an identity ```bash curl -s -X POST https://api.usehumanless.com/v1/identities \ -H "Authorization: Bearer $HUMANLESS_API_KEY" \ -H "Content-Type: application/json" \ -d '{"channels":["email"]}' | tee identity.json export ID=$(jq -r .identity_id identity.json) ``` The response is `201 Created`. The second command saves its `identity_id` as `$ID` for steps 4 and 5 (no `jq`? Copy the `identity_id` value and run `export ID=`): ```json { "identity_id": "5b0d7c1e-8f2a-4c1b-9a63-2f1d0e7c4b11", "channels": ["email"], "email": "hl-k3j9x2m1qa@inbox.example", "phone": null, "totp_secret": null, "status": "active", "expires_at": "2026-12-03T13:00:00.000Z", "created_at": "2026-12-03T12:00:00.000Z", "ended_at": null } ``` Free accounts can use `email` and `totp`. To get a dedicated US phone number, add `"sms"`. That needs a paid plan or prepaid credits. ### 3. Make your app send a code Type the `email` into the sign-up or login form of the app you're testing and submit it, by hand or from your test. Any message sent to that address is delivered to this identity. ### 4. Wait for the code ```bash curl -s "https://api.usehumanless.com/v1/identities/$ID/wait?channel=email&timeout=60" \ -H "Authorization: Bearer $HUMANLESS_API_KEY" ``` The request stays open until a message arrives, then returns it with the code or link already extracted: ```json { "type": "otp", "code": "482913", "url": null, "channel": "email", "sender": "Acme ", "subject": "Confirm your Acme account", "received_at": "2026-12-03T12:00:04.512Z", "raw_snippet": "Your Acme verification code is 482913. It expires in 10 minutes." } ``` If nothing arrives within `timeout` seconds (60 at most), the API returns `408` with error code `timeout`. Call it again. ### 5. Clean up ```bash curl -s -X DELETE https://api.usehumanless.com/v1/identities/$ID \ -H "Authorization: Bearer $HUMANLESS_API_KEY" ``` Identities also expire on their own at `expires_at` (1 hour by default). Delete SMS identities as soon as you're done so your dedicated number is free for the next test. ### Next steps - Write it as a test: [Playwright guide](https://usehumanless.com/docs/playwright) - Give it to an agent: [MCP server](https://usehumanless.com/docs/mcp) - Every parameter and error: [REST API reference](https://usehumanless.com/docs/api) - Typed client: [TypeScript SDK](https://usehumanless.com/docs/sdk) --- ## REST API reference URL: https://usehumanless.com/docs/api (Markdown: https://usehumanless.com/docs/api.md) > The Humanless REST API has five endpoints under `https://api.usehumanless.com/v1`. They create an identity (email inbox, SMS number, TOTP secret), wait for the next message, read the current TOTP code, read the identity and delete it. Requests and responses are JSON, and every error has a stable machine-readable code. ### Basics - **Base URL:** `https://api.usehumanless.com/v1` - **Auth:** `Authorization: Bearer hl_live_...` on every request. A missing, malformed or revoked key returns `401 unauthorized`. - **Bodies:** JSON. Send `Content-Type: application/json`. An empty body is treated as `{}`. A body that isn't valid JSON returns `400 invalid_json`. - **IDs:** `identity_id` is a UUID. A malformed or unknown ID, or one that belongs to another account, returns `404 not_found`. - **Errors:** every non-2xx response has this shape: ```json { "error": { "code": "channel_not_enabled", "message": "This identity was not created with the sms channel" } } ``` Some errors also include `error.details`, for example quota numbers and a `billing_url`. When a `Retry-After` header is present, wait that many seconds before retrying. ### Endpoints | Method | Path | What it does | |---|---|---| | `POST` | `/v1/identities` | Create an identity | | `GET` | `/v1/identities/:id` | Read an identity | | `GET` | `/v1/identities/:id/wait` | Long-poll for the next email or SMS | | `GET` | `/v1/identities/:id/totp` | Current TOTP code | | `DELETE` | `/v1/identities/:id` | Delete an identity (idempotent) | ### The Identity object | Field | Type | Notes | |---|---|---| | `identity_id` | string (UUID) | Use it in every other call | | `channels` | array of `"email"`, `"sms"`, `"totp"` | The channels this identity was created with | | `email` | string or null | Disposable address, set when `email` is enabled | | `phone` | string or null | E.164 US number (`+1...`), set when `sms` is enabled. Receive-only | | `totp_secret` | string or null | Base32 secret (32 chars), set when `totp` is enabled. Enter it where the app says "can't scan the QR code?" | | `status` | `"active"`, `"deleted"` or `"expired"` | | | `expires_at` | ISO 8601 string | When the identity expires automatically | | `created_at` | ISO 8601 string | | | `ended_at` | ISO 8601 string or null | When it was deleted or expired | ### The Message object | Field | Type | Notes | |---|---|---| | `type` | `"otp"`, `"magic_link"` or `"raw"` | `otp`: a code was found (and `url` may also be set). `magic_link`: only a link was found. `raw`: neither was found, so read `raw_snippet` | | `code` | string or null | The extracted one-time code | | `url` | string or null | The extracted verification or sign-in link | | `channel` | `"email"` or `"sms"` | | | `sender` | string | Email `From` or the SMS sender number | | `subject` | string or null | Email subject. `null` for SMS | | `received_at` | ISO 8601 string | | | `raw_snippet` | string | The first 280 characters of the message as plain text | ### POST /v1/identities Creates a new identity. **Body** | Field | Type | Default | Notes | |---|---|---|---| | `channels` | array of `"email"`, `"sms"`, `"totp"` (1 to 3) | `["email"]` | `sms` needs a paid plan or prepaid credits | | `ttl_seconds` | positive integer | `3600` (1 hour) | Maximum `86400` (24 hours) | | `domain` | string | Your account's default domain, otherwise the platform domain | Email domain to use. It must be a platform domain or one of your verified domains, and only works with the `email` channel | ```bash curl -s -X POST https://api.usehumanless.com/v1/identities \ -H "Authorization: Bearer $HUMANLESS_API_KEY" \ -H "Content-Type: application/json" \ -d '{"channels":["email","sms","totp"],"ttl_seconds":900}' ``` **Response** `201 Created`: an [Identity](#the-identity-object). **SMS numbers.** Each paid account has dedicated US numbers: 1 on Builder, 5 on Pro, and extra or pay-as-you-go numbers paid from credits. They are never shared with other customers. An SMS identity holds one of your numbers until it is deleted or expires. After that, the number has a short cooldown (about 30 seconds) before the next SMS identity can use it. If every number is held by a live identity, you get `409 all_numbers_busy`. **Errors:** `400 invalid_request`, `400 invalid_domain`, `402 payment_required`, `402 sms_quota_exceeded`, `409 all_numbers_busy`, `429 rate_limited`, `429 sms_limit_reached`, `503 numbers_provisioning`, `503 phone_pool_exhausted`, `503 email_domain_not_configured`. ### GET /v1/identities/:id/wait Blocks until the next message for this identity arrives, then returns it. The wait is push-based, so it returns as soon as the message is received, with no polling interval. **Query parameters** | Param | Type | Default | Notes | |---|---|---|---| | `channel` | `any`, `email` or `sms` | `any` | Only return messages from this channel | | `timeout` | number of seconds, 0 to 60 | `30` | Fractions are allowed | | `since` | Unix time in milliseconds | none | See below | ```bash curl -s "https://api.usehumanless.com/v1/identities/$ID/wait?channel=sms&timeout=60" \ -H "Authorization: Bearer $HUMANLESS_API_KEY" ``` **Response** `200 OK`: a [Message](#the-message-object). If no message arrives before the timeout, you get `408 timeout`. Nothing is wrong, so call it again. **Consumption semantics** - Without `since`, each wait returns the oldest **unconsumed** message and marks it consumed. The next wait returns the next message. If your app sends two emails (for example a welcome email and then a code), the first wait may return the welcome email. Check `code` or `url` and wait again. - With `since`, the wait returns the oldest message received **at or after** that time, whether or not it was already consumed. Take `Date.now()` just **before** you submit the form, so a message that arrives before the wait starts is still caught. Repeating the same `since` returns the same message. To get the next one, advance `since` past that message's `received_at`. **Server-Sent Events.** Send `Accept: text/event-stream` to get a stream instead of JSON. The server sends one `message` event (data: the Message JSON) or one `timeout` event, then closes. It sends `: ping` comments every 15 seconds to keep the connection alive. A `404`, `409` or `410` is returned as a normal HTTP status before the stream starts. An error that happens during the stream is sent as an `error` event. ```bash curl -N "https://api.usehumanless.com/v1/identities/$ID/wait?timeout=60" \ -H "Authorization: Bearer $HUMANLESS_API_KEY" \ -H "Accept: text/event-stream" ``` **Proxies.** The request can stay open for up to 60 seconds. If it passes through your own proxy, set its read timeout above that. **Errors:** `400 invalid_request`, `404 not_found`, `408 timeout`, `409 channel_not_enabled` (for example `channel=sms` on an email-only identity), `410 identity_ended`. ### GET /v1/identities/:id/totp Returns the current 6-digit code for the identity's TOTP secret. ```json { "code": "159026", "seconds_remaining": 17 } ``` If `seconds_remaining` is very low (3 or less), wait for the next 30-second window before you type the code. **Errors:** `404 not_found`, `409 channel_not_enabled` (the identity has no `totp` channel), `410 identity_ended`. ### GET /v1/identities/:id Returns the [Identity](#the-identity-object), including ones that are deleted or expired, with their `status` and `ended_at`. **Errors:** `404 not_found`. ### DELETE /v1/identities/:id Deletes the identity. Its email address stops receiving mail and its phone number goes back to your account. You can call it again safely: deleting an identity that is already deleted or expired returns the same result. ```json { "identity_id": "5b0d7c1e-8f2a-4c1b-9a63-2f1d0e7c4b11", "status": "deleted" } ``` **Errors:** `404 not_found`. ### Error codes | Status | Code | Meaning and what to do | |---|---|---| | 400 | `invalid_request` | A parameter is invalid. The message names the field | | 400 | `invalid_json` | The request body isn't valid JSON | | 400 | `invalid_domain` | `domain` is not a platform domain or one of your verified domains. Omit it to use the default | | 401 | `unauthorized` | Missing, malformed or revoked API key | | 402 | `payment_required` | SMS needs Builder, Pro or prepaid credits. Use `email` or `totp`, or upgrade | | 402 | `sms_quota_exceeded` | The included SMS are used up and your credits can't pay for more. `details` includes `credit_balance_cents` and `billing_url`. Existing SMS identities keep receiving | | 404 | `not_found` | Unknown identity, or it belongs to another account | | 404 | `route_not_found` | No such API route | | 408 | `timeout` | No message arrived before `timeout`. Wait again | | 409 | `channel_not_enabled` | The identity wasn't created with that channel | | 409 | `all_numbers_busy` | Every dedicated number is held by a live identity. Delete the ones you've finished with, then retry | | 410 | `identity_ended` | The identity was deleted or expired. Create a new one | | 429 | `rate_limited` | Too many requests. Honor `Retry-After` | | 429 | `sms_limit_reached` | You've hit the daily limit on SMS identities. Honor `Retry-After` or use email | | 500 | `internal_error` | Unexpected server error | | 503 | `numbers_provisioning` | Your dedicated numbers are still being set up after an upgrade. Honor `Retry-After` (30 s) | | 503 | `phone_pool_exhausted` | No numbers are available right now. Retry later | | 503 | `email_domain_not_configured` | No email domain is configured on the server. Retrying won't help, so contact support | ### Rate limits Limits apply per API key per minute. Every response includes `X-RateLimit-Limit` and `X-RateLimit-Remaining`. A `429` also includes `X-RateLimit-Reset` and `Retry-After`. | Plan | API requests per key per minute | Identities created per account per hour | SMS identities per account per day | |---|---|---|---| | Free and pay-as-you-go | 120 | 30 | 100 | | Builder | 600 | 300 | 200 | | Pro | 1,800 | 1,000 | 1,000 | These are the current defaults and may change. Email `hello@usehumanless.com` if you need higher limits. ### Python example There's no Python SDK. The API is plain HTTP: ```python import os, time, requests API = "https://api.usehumanless.com/v1" H = {"Authorization": f"Bearer {os.environ['HUMANLESS_API_KEY']}"} me = requests.post(f"{API}/identities", headers=H, json={"channels": ["email"]}).json() since = int(time.time() * 1000) # ... submit me["email"] in the app you're testing ... r = requests.get(f"{API}/identities/{me['identity_id']}/wait", headers=H, params={"channel": "email", "timeout": 60, "since": since}) if r.status_code == 408: raise TimeoutError("no code yet: wait again") print(r.json()["code"]) requests.delete(f"{API}/identities/{me['identity_id']}", headers=H) ``` --- ## MCP server URL: https://usehumanless.com/docs/mcp (Markdown: https://usehumanless.com/docs/mcp.md) > Humanless runs a remote MCP server at `https://api.usehumanless.com/mcp`. It gives agents four tools: create a disposable email, SMS or TOTP identity, wait for the verification code or magic link, read the current TOTP code, and delete the identity. Nothing to install: you connect with one URL and one API key. Use it to let agents complete sign-up, login and 2FA steps in **applications you own or are authorized to test**. ### Connection details - **URL:** `https://api.usehumanless.com/mcp` - **Transport:** Streamable HTTP, stateless, JSON responses. Use `POST` only. `GET` and `DELETE` return `405` because the server keeps no sessions. - **Auth:** header `Authorization: Bearer hl_live_...`, the same key as the REST API. A missing or invalid key returns HTTP `401`. - **Rate limits:** every POST counts toward the same per-key limit as the REST API. Over the limit, you get `429` with `Retry-After`. Get a key at [api.usehumanless.com/app](https://api.usehumanless.com/app). ### Claude Code ```bash claude mcp add --transport http humanless https://api.usehumanless.com/mcp \ --header "Authorization: Bearer hl_live_YOUR_KEY" ``` ### Claude Desktop Claude Desktop starts local (stdio) servers from its config file. Bridge to the remote server with `mcp-remote` in `claude_desktop_config.json`: ```json { "mcpServers": { "humanless": { "command": "npx", "args": [ "-y", "mcp-remote", "https://api.usehumanless.com/mcp", "--header", "Authorization:${HUMANLESS_AUTH}" ], "env": { "HUMANLESS_AUTH": "Bearer hl_live_YOUR_KEY" } } } } ``` The header value is passed through an environment variable because some platforms mangle spaces inside `args`. ### Cursor Add this to `~/.cursor/mcp.json`, or to `.cursor/mcp.json` in a project: ```json { "mcpServers": { "humanless": { "url": "https://api.usehumanless.com/mcp", "headers": { "Authorization": "Bearer hl_live_YOUR_KEY" } } } } ``` ### VS Code (GitHub Copilot agent mode) Add this to `.vscode/mcp.json`. VS Code prompts for the key once and stores it securely: ```json { "inputs": [ { "type": "promptString", "id": "humanless-key", "description": "Humanless API key (hl_live_...)", "password": true } ], "servers": { "humanless": { "type": "http", "url": "https://api.usehumanless.com/mcp", "headers": { "Authorization": "Bearer ${input:humanless-key}" } } } } ``` ### Other clients Any MCP client that supports Streamable HTTP and custom headers works: ```json { "type": "http", "url": "https://api.usehumanless.com/mcp", "headers": { "Authorization": "Bearer hl_live_YOUR_KEY" } } ``` To test with curl, send both `Accept` types: ```bash curl -s https://api.usehumanless.com/mcp \ -H "Authorization: Bearer $HUMANLESS_API_KEY" \ -H "Content-Type: application/json" \ -H "Accept: application/json, text/event-stream" \ -d '{"jsonrpc":"2.0","id":1,"method":"tools/list"}' ``` From your own agent, with the TypeScript MCP SDK: ```ts import { Client } from "@modelcontextprotocol/sdk/client/index.js"; import { StreamableHTTPClientTransport } from "@modelcontextprotocol/sdk/client/streamableHttp.js"; const client = new Client({ name: "my-agent", version: "1.0.0" }); await client.connect(new StreamableHTTPClientTransport(new URL("https://api.usehumanless.com/mcp"), { requestInit: { headers: { Authorization: `Bearer ${process.env.HUMANLESS_API_KEY}` } }, })); const { structuredContent: identity } = await client.callTool({ name: "create_verification_identity", arguments: { channels: ["email"] }, }); ``` ### Tools The agent flow is: `create_verification_identity`, then fill and submit the form, then `wait_for_verification_code`, then enter the code or open the link. For 2FA, also call `get_totp_code`. Finish with `delete_verification_identity`. #### create_verification_identity Creates a disposable identity. It returns an email address (channel `email`), a real phone number that receives SMS (channel `sms`, paid plans only) and/or a TOTP secret to enroll as an authenticator app (channel `totp`). | Argument | Type | Default | Notes | |---|---|---|---| | `channels` | array of `"email"`, `"sms"`, `"totp"` (1 to 3) | `["email"]` | | | `ttl_seconds` | positive integer | Server default (1 hour) | How long the identity lives before it expires | | `domain` | string | Default domain | Omit it unless you've been told to use a specific domain | Returns text with the email, phone or TOTP secret and the next step. `structuredContent` is the Identity: `identity_id`, `channels`, `email`, `phone`, `totp_secret`, `status`, `expires_at`, `created_at`, `ended_at`. #### wait_for_verification_code Blocks until the next email or SMS arrives for an identity, then returns the extracted OTP code and/or magic link. The text starts with `OTP: ` and/or `Magic link: `. Call it right after submitting the form, without sleeping first. Each message is returned once. | Argument | Type | Default | Notes | |---|---|---|---| | `identity_id` | string | required | From `create_verification_identity` | | `channel` | `"any"`, `"email"` or `"sms"` | `"any"` | | | `timeout_seconds` | number, 0 to 60 | `30` | | | `since_unix_ms` | integer | none | Only return messages received at or after this time. Pass a time just before you submitted the form, so a message that arrived before the wait started is still caught | `structuredContent` is `{ "status": "received", "identity_id", "message": { type, code, url, channel, sender, subject, received_at, raw_snippet } }`. A timeout is **not** an error. It returns `{ "status": "timeout", "message": null }` and tells the agent to call again. #### get_totp_code Returns the current 6-digit code for an identity created with the `totp` channel. `structuredContent` is `{ "code", "seconds_remaining" }`. If `seconds_remaining` is very low, wait for the next window and call again. Read-only. | Argument | Type | Notes | |---|---|---| | `identity_id` | string | From `create_verification_identity` | #### delete_verification_identity Deletes an identity: its email stops receiving mail and its phone number is released. You can call it more than once safely. `structuredContent` is `{ "identity_id", "status": "deleted" }`. | Argument | Type | Notes | |---|---|---| | `identity_id` | string | From `create_verification_identity` | ### Errors Service errors come back as tool results with `isError: true`, so the agent can read them and recover. The text gives the status, the code and a suggested next step. `structuredContent.error` is `{ status, code, message, retry_after_seconds, details? }`. The codes are the same as in the [REST API](https://usehumanless.com/docs/api#error-codes), for example `payment_required` (retry with `["email"]` or `["totp"]`), `sms_quota_exceeded`, `not_found`, `identity_ended` (create a new identity), `channel_not_enabled`, `all_numbers_busy` (delete finished identities, then retry), `rate_limited` and `numbers_provisioning`. ### Example prompt > Sign up for a new account on http://localhost:3000 using a Humanless email identity, verify the email with the code you receive, enable two-factor authentication with a Humanless TOTP identity, then log out and log back in. Delete the identities at the end. --- ## Playwright guide URL: https://usehumanless.com/docs/playwright (Markdown: https://usehumanless.com/docs/playwright.md) > Give each Playwright test its own disposable inbox, phone number or authenticator, then wait for the parsed code with one call. This replaces fixed sleeps, shared test inboxes and webmail scraping with a push-based wait that returns as soon as the message arrives. ### Setup 1. Create an API key at [api.usehumanless.com/app](https://api.usehumanless.com/app). Set it as the `HUMANLESS_API_KEY` secret in CI. 2. Download the [TypeScript SDK](https://usehumanless.com/sdk/humanless.ts) into your project as `tests/humanless.ts` (see [SDK docs](https://usehumanless.com/docs/sdk)). ```ts // tests/humanless-client.ts import { Humanless } from "./humanless"; export const hl = new Humanless({ apiKey: process.env.HUMANLESS_API_KEY! }); ``` ### Before and after ```ts // Before: a real inbox, a fixed sleep, then scraping a webmail UI and hoping the first 6 digits are the code. await page.click("text=Send code"); await page.waitForTimeout(15_000); await mail.goto("https://webmail.example.com"); const code = (await mail.textContent(".msg"))!.match(/\d{6}/)![0]; ``` ```ts // After: a disposable inbox per test, an event-driven wait, and a parsed code. const { code } = await hl.waitForCode({ identityId: identity_id }); ``` ### Email OTP sign-up ```ts import { expect, test } from "@playwright/test"; import { withIdentity } from "./humanless"; import { hl } from "./humanless-client"; test("sign up with an email code", async ({ page }) => { await withIdentity(hl, { channels: ["email"] }, async ({ identity_id, email }) => { await page.goto("http://localhost:3100/signup"); await page.getByLabel("Email").fill(email!); await page.getByRole("button", { name: "Send verification code" }).click(); const { code } = await hl.waitForCode({ identityId: identity_id }); await page.getByLabel("Verification code").fill(code); await page.getByRole("button", { name: "Verify" }).click(); await expect(page.getByTestId("welcome")).toBeVisible(); }); }); ``` `withIdentity` deletes the identity even if the test fails. ### Magic link login Take a timestamp before you submit, so the wait can't miss a fast email: ```ts test("log in with a magic link", async ({ page }) => { await withIdentity(hl, { channels: ["email"] }, async ({ identity_id, email }) => { await page.goto("http://localhost:3100/login"); await page.getByLabel("Email").fill(email!); const since = Date.now(); await page.getByRole("button", { name: "Email me a link" }).click(); const { url } = await hl.waitForLink({ identityId: identity_id, since }); await page.goto(url); await expect(page.getByTestId("dashboard")).toBeVisible(); }); }); ``` ### SMS OTP SMS identities need a paid plan or prepaid credits. `phone` is in E.164 format (`+1...`). If your form has a separate country-code dropdown, type the number without `+1`. ```ts test("verify a phone number", async ({ page }) => { await withIdentity(hl, { channels: ["sms"] }, async ({ identity_id, phone }) => { await page.goto("http://localhost:3100/settings/phone"); await page.getByLabel("Phone").fill(phone!); await page.getByRole("button", { name: "Text me a code" }).click(); const { code } = await hl.waitForCode({ identityId: identity_id, channel: "sms" }); await page.getByLabel("Code").fill(code); }); }); ``` ### TOTP two-factor authentication Enroll the identity's `totp_secret` where your app offers "enter the key manually". Then read codes whenever the app asks for one: ```ts test("enable and use 2FA", async ({ page }) => { await withIdentity(hl, { channels: ["email", "totp"] }, async ({ identity_id, totp_secret }) => { // ...sign up with the email first... await page.getByRole("button", { name: "Can't scan the QR code?" }).click(); await page.getByLabel("Setup key").fill(totp_secret!); let t = await hl.getTotp(identity_id); if (t.seconds_remaining <= 3) { await page.waitForTimeout((t.seconds_remaining + 1) * 1000); t = await hl.getTotp(identity_id); } await page.getByLabel("Authentication code").fill(t.code); }); }); ``` ### Tips - **Never sleep before waiting.** Call `waitForCode` right after the click. It returns as soon as the message lands. - **Parallel workers:** create one identity per test. Email identities aren't capped per run, but identity creation is rate-limited per plan (30, 300 or 1,000 per hour; see [rate limits](https://usehumanless.com/docs/api#rate-limits)). SMS identities each hold one of your dedicated numbers (1 on Builder, 5 on Pro) until they are deleted, so run at most that many SMS tests at once. - **Resend buttons:** each resend sends a new code. Wait again and use the newest one. - **Timeouts:** the SDK's default overall wait is 60 s. Set Playwright's test timeout higher than that. - **Your own domain:** custom email domains are set up on request (email hello@usehumanless.com). Once one is verified for your account, pass it as `domain` when you create an identity; identity addresses are generated on it. --- ## TypeScript SDK URL: https://usehumanless.com/docs/sdk (Markdown: https://usehumanless.com/docs/sdk.md) > The Humanless SDK is one zero-dependency TypeScript file that wraps the REST API. It adds typed responses, typed errors and smart waits. `waitForCode` and `waitForLink` skip messages that have no code or link, and they re-poll until an overall deadline. It works anywhere `fetch` exists: Node 18+, Deno, Bun and browsers. ### Install The SDK is a single source file, published at [usehumanless.com/sdk/humanless.ts](https://usehumanless.com/sdk/humanless.ts). It isn't on npm yet. Download it into your project: ```bash curl -o humanless.ts https://usehumanless.com/sdk/humanless.ts ``` Then import it: ```ts import { Humanless, withIdentity } from "./humanless"; const hl = new Humanless({ apiKey: process.env.HUMANLESS_API_KEY! }); ``` #### Constructor options | Option | Type | Default | |---|---|---| | `apiKey` | string | required (`hl_live_...`) | | `baseUrl` | string | `process.env.HUMANLESS_BASE_URL`, otherwise `https://api.usehumanless.com` | | `fetch` | `typeof fetch` | global `fetch` (override it for tests or proxies) | ### Methods | Method | REST call | Returns | |---|---|---| | `createIdentity({ channels?, domain?, ttl_seconds? })` | `POST /v1/identities` | `Identity` | | `getIdentity(identityId)` | `GET /v1/identities/:id` | `Identity` | | `waitForMessage({ identityId, channel?, timeout?, since?, signal? })` | `GET /v1/identities/:id/wait` | `Message` (any type) | | `waitForCode(opts)` | same | `Message & { code: string }`. Skips messages without a code | | `waitForLink(opts)` | same | `Message & { url: string }`. Skips messages without a link | | `getTotp(identityId)` | `GET /v1/identities/:id/totp` | `{ code, seconds_remaining }` | | `deleteIdentity(identityId)` | `DELETE /v1/identities/:id` | `{ identity_id, status: "deleted" }` | #### Wait options | Option | Type | Default | Notes | |---|---|---|---| | `identityId` | string | required | | | `channel` | `"any"`, `"email"` or `"sms"` | `"any"` | | | `timeout` | seconds | `60` | Overall deadline across all long-poll rounds. Each round is at most 60 s | | `since` | Unix ms or `Date` | none | Take `Date.now()` just **before** you trigger the send. This makes the wait race-free and lets you read the same message again | | `signal` | `AbortSignal` | none | Cancels the wait | ### withIdentity `withIdentity(hl, opts, fn)` creates an identity, runs `fn`, and **always** deletes the identity afterwards, even if `fn` throws. That keeps your dedicated phone numbers free and avoids `409 all_numbers_busy`. ```ts await withIdentity(hl, { channels: ["email"] }, async ({ identity_id, email }) => { await page.getByLabel("Email").fill(email!); await page.getByRole("button", { name: "Send code" }).click(); const { code } = await hl.waitForCode({ identityId: identity_id }); await page.getByLabel("Code").fill(code); }); ``` ### Errors - `HumanlessError` is thrown for any non-2xx response. It has `status`, `code` (the API error code, for example `channel_not_enabled`), `message`, `retryAfterSeconds` and `details`. `err.isSmsQuotaExceeded` is `true` for `402 sms_quota_exceeded`. - `HumanlessTimeoutError` (a subclass with `status` 408 and `code` `"timeout"`) is thrown by the wait methods when the overall `timeout` passes. ```ts import { HumanlessError } from "./humanless"; try { await hl.createIdentity({ channels: ["sms"] }); } catch (err) { if (err instanceof HumanlessError && err.isSmsQuotaExceeded) { console.log("Top up or upgrade:", err.details?.billing_url); } else throw err; } ``` ### Types ```ts type IdentityChannel = "email" | "sms" | "totp"; interface Identity { identity_id: string; channels: IdentityChannel[]; email: string | null; phone: string | null; // E.164 totp_secret: string | null; // base32 status: "active" | "deleted" | "expired"; expires_at: string; created_at: string; ended_at: string | null; } 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; } ``` The SDK exports the old `Verifybox*` names as deprecated aliases, so code written against the earlier SDK keeps working.