This is the abridged developer documentation for Heimdal # Introduction > Heimdal checks an email address and an IP address at signup and tells you whether they look like trouble. One endpoint, one JSON answer. Heimdal is a signup-protection API. Before you create an account, send the visitor’s IP address, email address, or both. Heimdal answers with a set of risk signals and a `block` recommendation, and you decide what to do with them. GET`/v1/check` ```sh curl -G "https://heimdal.codebrewerz.com/api/v1/check" \ -H "Authorization: Bearer $HEIMDAL_API_KEY" \ --data-urlencode "ip=185.220.101.1" \ --data-urlencode "email=test@mailinator.com" ``` ```json { "block": true, "reasons": ["disposable_email", "tor", "vpn", "bad_isp"], "email": { "address": "test@mailinator.com", "domain": "mailinator.com", "disposable": true }, "ip": { "address": "185.220.101.1", "tor": true, "vpn": true, "proxy": false, "bad_isp": true, "asn": 60729, "isp": "TORSERVERS-NET Stiftung Erneuerbare Freiheit" }, "custom": { "matched": [] } } ``` ## What it checks [Section titled “What it checks”](#what-it-checks) | Signal | True when | | ------------------ | ----------------------------------------------------------------------------- | | `email.disposable` | The email’s domain belongs to a disposable mail provider. 150,000+ domains. | | `ip.tor` | The address is a Tor exit node. | | `ip.proxy` | The address is a known open proxy. | | `ip.vpn` | The address belongs to a VPN provider’s network. | | `ip.bad_isp` | The address belongs to a hosting, datacenter or VPN network. 2,000+ networks. | | `custom.matched` | The email, its domain or the address is on one of your own lists. | `block` is `true` when at least one of them fires. If that is stricter than you want, ignore `block` and read the individual signals. [Signals explained](/docs/reference/signals/) covers what each one does and does not tell you. ## How it works [Section titled “How it works”](#how-it-works) * **Local lists.** Heimdal keeps its lists on its own servers and refreshes them every hour (Tor, proxies) or every day (everything else). A check is a lookup: Heimdal never connects to the address you send and never contacts the mail server. * **Server to server.** You call the API from your backend with a secret key. It is not meant for browsers or mobile apps. * **Your decision.** Heimdal reports. Whether a signal blocks a signup, triggers a CAPTCHA or is only logged is up to you. [Best practices](/docs/guides/best-practices/) has a sensible starting policy. ## Pricing [Section titled “Pricing”](#pricing) There is one plan, Shield, and it includes everything: $59 a month, or $590 a year (ten months). | Included | | | ------------------------ | ------------------------------------------------------- | | API calls | Unlimited | | Email and IP checks | Disposable domains, Tor, open proxies, VPNs, bad ISPs | | Custom lists | 20 lists, 50,000 entries per account | | Monitoring and analytics | Counts per reason over time, and a log of recent checks | | Priority support | Yes | The first subscription for an email address starts with a 7-day free trial. A card is required to start it and is not charged until the trial ends. “Unlimited” means there is no monthly quota. A per-key rate limit protects the service: 100 requests a second. See [Rate limits](/docs/reference/rate-limits/). ## What Heimdal stores [Section titled “What Heimdal stores”](#what-heimdal-stores) Hourly counters (total, blocked, and one per reason) kept for 12 months, with no IP addresses or emails in them. The recent-checks log in the dashboard holds the checked IP address and email, capped at the newest 10,000 checks per account and 30 days. Under heavy load the log is a sample; the counters stay exact. Checks made from the dashboard’s playground are not stored. ## What Heimdal does not do [Section titled “What Heimdal does not do”](#what-heimdal-does-not-do) * It does not verify that a mailbox exists or that a domain can receive mail. * It has no allowlists. Lists only add reasons to block; handle exceptions in your own code. * It returns no location data for an IP address, only the network it belongs to (`ip.asn`, `ip.isp`). * It has no client SDK and needs none: the API is one HTTP request. * It sends no webhooks or email alerts. ## Using an AI assistant? [Section titled “Using an AI assistant?”](#using-an-ai-assistant) Every page has **Copy as Markdown** and **Copy LLM prompt** under its title, and the whole site is available as [`llms.txt`](/docs/llms.txt), [`llms-full.txt`](/docs/llms-full.txt) and an [OpenAPI spec](/docs/openapi.json). [Docs for AI agents](/docs/ai-agents/) has a ready setup prompt. ## Next steps [Section titled “Next steps”](#next-steps) [Quickstart](/docs/quickstart/)Create a key and make your first check. [Check endpoint](/docs/reference/check/)Every parameter and response field. [Best practices](/docs/guides/best-practices/)Timeouts, failing open, and which signals to act on. [Better Auth](/docs/guides/better-auth/)Guard email sign-up with a before hook. # Quickstart > From no account to a working check in a few minutes. ## 1. Create an API key [Section titled “1. Create an API key”](#1-create-an-api-key) 1. Sign up at and start the 7-day trial. 2. In the dashboard, open **API keys** and create a key. 3. Copy it. The full key is shown once and starts with `hd_`. Put the key in an environment variable on your server. The examples below read it from `HEIMDAL_API_KEY`. ```sh export HEIMDAL_API_KEY="hd_your_key" ``` ## 2. Make a request [Section titled “2. Make a request”](#2-make-a-request) Send an IP address, an email address, or both. This example sends an address that has served as a Tor exit node and a mailbox at a well-known disposable provider. * curl ```sh curl -X POST "https://heimdal.codebrewerz.com/api/v1/check" \ -H "Authorization: Bearer $HEIMDAL_API_KEY" \ -H "Content-Type: application/json" \ -d '{"ip":"185.220.101.1","email":"test@mailinator.com"}' ``` * Node (fetch) ```js const response = await fetch("https://heimdal.codebrewerz.com/api/v1/check", { method: "POST", headers: { Authorization: `Bearer ${process.env.HEIMDAL_API_KEY}`, "Content-Type": "application/json", }, body: JSON.stringify({ ip: "185.220.101.1", email: "test@mailinator.com" }), signal: AbortSignal.timeout(2000), }); console.log(await response.json()); ``` * Node (axios) ```js import axios from "axios"; const { data } = await axios.post( "https://heimdal.codebrewerz.com/api/v1/check", { ip: "185.220.101.1", email: "test@mailinator.com" }, { headers: { Authorization: `Bearer ${process.env.HEIMDAL_API_KEY}` }, timeout: 2000, }, ); console.log(data); ``` * Python ```python import os import requests response = requests.post( "https://heimdal.codebrewerz.com/api/v1/check", json={"ip": "185.220.101.1", "email": "test@mailinator.com"}, headers={"Authorization": f"Bearer {os.environ['HEIMDAL_API_KEY']}"}, timeout=2, ) print(response.json()) ``` * Java ```java // Java 11+, no dependencies. import java.net.URI; import java.net.http.HttpClient; import java.net.http.HttpRequest; import java.net.http.HttpResponse; import java.time.Duration; public class Check { public static void main(String[] args) throws Exception { String key = System.getenv("HEIMDAL_API_KEY"); if (key == null || key.isBlank()) { throw new IllegalStateException("Set HEIMDAL_API_KEY"); } HttpClient client = HttpClient.newBuilder() .connectTimeout(Duration.ofSeconds(2)) .build(); HttpRequest request = HttpRequest.newBuilder(URI.create("https://heimdal.codebrewerz.com/api/v1/check")) .timeout(Duration.ofSeconds(2)) .header("Authorization", "Bearer " + key) .header("Content-Type", "application/json") .POST(HttpRequest.BodyPublishers.ofString("{\"ip\":\"185.220.101.1\",\"email\":\"test@mailinator.com\"}")) .build(); HttpResponse response = client.send(request, HttpResponse.BodyHandlers.ofString()); // 200: the check. Anything else: {"error":{"code","message"}}. System.out.println(response.statusCode() + " " + response.body()); } } ``` * Rust Cargo.toml ```rust // [dependencies] // reqwest = { version = "0.13", features = ["json", "query"] } // serde_json = "1" // tokio = { version = "1", features = ["macros", "rt-multi-thread"] } use std::time::Duration; #[tokio::main] async fn main() -> Result<(), Box> { let key = std::env::var("HEIMDAL_API_KEY")?; let client = reqwest::Client::builder() .timeout(Duration::from_secs(2)) .build()?; let response = client .post("https://heimdal.codebrewerz.com/api/v1/check") .bearer_auth(&key) .json(&serde_json::json!({"ip":"185.220.101.1","email":"test@mailinator.com"})) .send() .await?; // 200: the check. Anything else: {"error":{"code","message"}}. let status = response.status(); let answer: serde_json::Value = response.json().await?; println!("{status} {answer}"); Ok(()) } ``` * Go ```go package main import ( "fmt" "io" "net/http" "os" "strings" "time" ) func main() { client := &http.Client{Timeout: 2 * time.Second} req, err := http.NewRequest("POST", "https://heimdal.codebrewerz.com/api/v1/check", strings.NewReader(`{"ip":"185.220.101.1","email":"test@mailinator.com"}`)) if err != nil { panic(err) } req.Header.Set("Authorization", "Bearer "+os.Getenv("HEIMDAL_API_KEY")) req.Header.Set("Content-Type", "application/json") res, err := client.Do(req) if err != nil { panic(err) } defer res.Body.Close() body, _ := io.ReadAll(res.Body) fmt.Println(string(body)) } ``` * PHP ```php 2]); $response = $client->post("https://heimdal.codebrewerz.com/api/v1/check", [ 'headers' => ['Authorization' => 'Bearer ' . getenv('HEIMDAL_API_KEY')], 'json' => ['ip' => "185.220.101.1", 'email' => "test@mailinator.com"], ]); echo $response->getBody(); ``` ## 3. Read the answer [Section titled “3. Read the answer”](#3-read-the-answer) ```json { "block": true, "reasons": ["disposable_email", "tor", "vpn", "bad_isp"], "email": { "address": "test@mailinator.com", "domain": "mailinator.com", "disposable": true }, "ip": { "address": "185.220.101.1", "tor": true, "vpn": true, "proxy": false, "bad_isp": true, "asn": 60729, "isp": "TORSERVERS-NET Stiftung Erneuerbare Freiheit" }, "custom": { "matched": [] } } ``` * `block` is the short answer: `true` when any signal fired. * `reasons` names the signals that fired. * `email` and `ip` hold the detail for each value you sent. A value you did not send comes back as `null`. ## 4. Decide [Section titled “4. Decide”](#4-decide) The simplest integration refuses the signup when `block` is `true`: ```js const result = await response.json(); if (result.block) { // Refuse the signup, or ask for more proof. } ``` `block` is strict: it is also `true` for an ordinary person on a VPN. Most products want something softer, such as refusing disposable email, Tor and open proxies while only logging VPN and hosting networks. Read [Best practices](/docs/guides/best-practices/) before you ship. ## Next steps [Section titled “Next steps”](#next-steps) * [Check endpoint](/docs/reference/check/): every parameter and response field. * [Signals explained](/docs/reference/signals/): what each signal means. * [Node.js guide](/docs/guides/node/): a complete helper with a timeout that fails open. # Check endpoint > The one endpoint. Send an IP address, an email address, or both, and get the signals for each. GET`/v1/check` POST`/v1/check` Base URL: ```txt https://heimdal.codebrewerz.com/api ``` Both methods do the same thing. `GET` takes its input from the query string, `POST` from a JSON body. Prefer `POST` in production: query strings tend to end up in access logs along the way, and a body keeps email addresses out of them. ## Request [Section titled “Request”](#request) ### Headers [Section titled “Headers”](#headers) | Header | Description | | --------------- | ------------------------------------------------------------------------------------------------- | | `Authorization` | `Bearer hd_…`. Required unless you send `x-api-key`. See [Authentication](/docs/authentication/). | | `x-api-key` | The key on its own. An alternative to `Authorization`. | | `Content-Type` | `POST` only. Send `application/json`. The body is parsed as JSON whatever this header says. | ### Parameters [Section titled “Parameters”](#parameters) Query parameters on `GET`, fields of the JSON object on `POST`. Send at least one of the two. | Field | Type | Description | | ------- | ------ | ------------------------------------------------------------------------------------ | | `ip` | string | The visitor’s IPv4 or IPv6 address. One address: no port, no CIDR range, no zone id. | | `email` | string | The email address the visitor typed. | * Each value may be at most 320 characters. * Surrounding whitespace is trimmed. An empty string and a JSON `null` both count as “not sent”. * `ip` accepts IPv4-mapped IPv6 (`::ffff:203.0.113.7`) and looks it up as the IPv4 address it wraps. * `email` needs a domain with at least one dot after the last `@`. Internationalised domains are accepted. Heimdal looks at the domain only and does not validate the part before the `@`. * Fields other than `ip` and `email` are ignored. * On `GET`, URL-encode the values. A literal `+` in a query string means a space, so `name+tag@example.com` must be sent as `name%2Btag@example.com`. ### Examples [Section titled “Examples”](#examples) `POST` with a JSON body: * curl ```sh curl -X POST "https://heimdal.codebrewerz.com/api/v1/check" \ -H "Authorization: Bearer $HEIMDAL_API_KEY" \ -H "Content-Type: application/json" \ -d '{"ip":"185.220.101.1","email":"test@mailinator.com"}' ``` * Node (fetch) ```js const response = await fetch("https://heimdal.codebrewerz.com/api/v1/check", { method: "POST", headers: { Authorization: `Bearer ${process.env.HEIMDAL_API_KEY}`, "Content-Type": "application/json", }, body: JSON.stringify({ ip: "185.220.101.1", email: "test@mailinator.com" }), signal: AbortSignal.timeout(2000), }); console.log(await response.json()); ``` * Node (axios) ```js import axios from "axios"; const { data } = await axios.post( "https://heimdal.codebrewerz.com/api/v1/check", { ip: "185.220.101.1", email: "test@mailinator.com" }, { headers: { Authorization: `Bearer ${process.env.HEIMDAL_API_KEY}` }, timeout: 2000, }, ); console.log(data); ``` * Python ```python import os import requests response = requests.post( "https://heimdal.codebrewerz.com/api/v1/check", json={"ip": "185.220.101.1", "email": "test@mailinator.com"}, headers={"Authorization": f"Bearer {os.environ['HEIMDAL_API_KEY']}"}, timeout=2, ) print(response.json()) ``` * Java ```java // Java 11+, no dependencies. import java.net.URI; import java.net.http.HttpClient; import java.net.http.HttpRequest; import java.net.http.HttpResponse; import java.time.Duration; public class Check { public static void main(String[] args) throws Exception { String key = System.getenv("HEIMDAL_API_KEY"); if (key == null || key.isBlank()) { throw new IllegalStateException("Set HEIMDAL_API_KEY"); } HttpClient client = HttpClient.newBuilder() .connectTimeout(Duration.ofSeconds(2)) .build(); HttpRequest request = HttpRequest.newBuilder(URI.create("https://heimdal.codebrewerz.com/api/v1/check")) .timeout(Duration.ofSeconds(2)) .header("Authorization", "Bearer " + key) .header("Content-Type", "application/json") .POST(HttpRequest.BodyPublishers.ofString("{\"ip\":\"185.220.101.1\",\"email\":\"test@mailinator.com\"}")) .build(); HttpResponse response = client.send(request, HttpResponse.BodyHandlers.ofString()); // 200: the check. Anything else: {"error":{"code","message"}}. System.out.println(response.statusCode() + " " + response.body()); } } ``` * Rust Cargo.toml ```rust // [dependencies] // reqwest = { version = "0.13", features = ["json", "query"] } // serde_json = "1" // tokio = { version = "1", features = ["macros", "rt-multi-thread"] } use std::time::Duration; #[tokio::main] async fn main() -> Result<(), Box> { let key = std::env::var("HEIMDAL_API_KEY")?; let client = reqwest::Client::builder() .timeout(Duration::from_secs(2)) .build()?; let response = client .post("https://heimdal.codebrewerz.com/api/v1/check") .bearer_auth(&key) .json(&serde_json::json!({"ip":"185.220.101.1","email":"test@mailinator.com"})) .send() .await?; // 200: the check. Anything else: {"error":{"code","message"}}. let status = response.status(); let answer: serde_json::Value = response.json().await?; println!("{status} {answer}"); Ok(()) } ``` * Go ```go package main import ( "fmt" "io" "net/http" "os" "strings" "time" ) func main() { client := &http.Client{Timeout: 2 * time.Second} req, err := http.NewRequest("POST", "https://heimdal.codebrewerz.com/api/v1/check", strings.NewReader(`{"ip":"185.220.101.1","email":"test@mailinator.com"}`)) if err != nil { panic(err) } req.Header.Set("Authorization", "Bearer "+os.Getenv("HEIMDAL_API_KEY")) req.Header.Set("Content-Type", "application/json") res, err := client.Do(req) if err != nil { panic(err) } defer res.Body.Close() body, _ := io.ReadAll(res.Body) fmt.Println(string(body)) } ``` * PHP ```php 2]); $response = $client->post("https://heimdal.codebrewerz.com/api/v1/check", [ 'headers' => ['Authorization' => 'Bearer ' . getenv('HEIMDAL_API_KEY')], 'json' => ['ip' => "185.220.101.1", 'email' => "test@mailinator.com"], ]); echo $response->getBody(); ``` `GET` with query parameters: * curl ```sh curl "https://heimdal.codebrewerz.com/api/v1/check?ip=185.220.101.1&email=test%40mailinator.com" \ -H "Authorization: Bearer $HEIMDAL_API_KEY" ``` * Node (fetch) ```js const response = await fetch("https://heimdal.codebrewerz.com/api/v1/check?ip=185.220.101.1&email=test%40mailinator.com", { headers: { Authorization: `Bearer ${process.env.HEIMDAL_API_KEY}` }, signal: AbortSignal.timeout(2000), }); console.log(await response.json()); ``` * Node (axios) ```js import axios from "axios"; const { data } = await axios.get("https://heimdal.codebrewerz.com/api/v1/check", { params: { ip: "185.220.101.1", email: "test@mailinator.com" }, headers: { Authorization: `Bearer ${process.env.HEIMDAL_API_KEY}` }, timeout: 2000, }); console.log(data); ``` * Python ```python import os import requests response = requests.get( "https://heimdal.codebrewerz.com/api/v1/check", params={"ip": "185.220.101.1", "email": "test@mailinator.com"}, headers={"Authorization": f"Bearer {os.environ['HEIMDAL_API_KEY']}"}, timeout=2, ) print(response.json()) ``` * Java ```java // Java 11+, no dependencies. import java.net.URI; import java.net.http.HttpClient; import java.net.http.HttpRequest; import java.net.http.HttpResponse; import java.time.Duration; public class Check { public static void main(String[] args) throws Exception { String key = System.getenv("HEIMDAL_API_KEY"); if (key == null || key.isBlank()) { throw new IllegalStateException("Set HEIMDAL_API_KEY"); } HttpClient client = HttpClient.newBuilder() .connectTimeout(Duration.ofSeconds(2)) .build(); HttpRequest request = HttpRequest.newBuilder(URI.create("https://heimdal.codebrewerz.com/api/v1/check?ip=185.220.101.1&email=test%40mailinator.com")) .timeout(Duration.ofSeconds(2)) .header("Authorization", "Bearer " + key) .GET() .build(); HttpResponse response = client.send(request, HttpResponse.BodyHandlers.ofString()); // 200: the check. Anything else: {"error":{"code","message"}}. System.out.println(response.statusCode() + " " + response.body()); } } ``` * Rust Cargo.toml ```rust // [dependencies] // reqwest = { version = "0.13", features = ["json", "query"] } // serde_json = "1" // tokio = { version = "1", features = ["macros", "rt-multi-thread"] } use std::time::Duration; #[tokio::main] async fn main() -> Result<(), Box> { let key = std::env::var("HEIMDAL_API_KEY")?; let client = reqwest::Client::builder() .timeout(Duration::from_secs(2)) .build()?; let response = client .get("https://heimdal.codebrewerz.com/api/v1/check") .bearer_auth(&key) .query(&[("ip", "185.220.101.1"), ("email", "test@mailinator.com")]) .send() .await?; // 200: the check. Anything else: {"error":{"code","message"}}. let status = response.status(); let answer: serde_json::Value = response.json().await?; println!("{status} {answer}"); Ok(()) } ``` * Go ```go package main import ( "fmt" "io" "net/http" "os" "time" ) func main() { client := &http.Client{Timeout: 2 * time.Second} req, err := http.NewRequest("GET", "https://heimdal.codebrewerz.com/api/v1/check?ip=185.220.101.1&email=test%40mailinator.com", nil) if err != nil { panic(err) } req.Header.Set("Authorization", "Bearer "+os.Getenv("HEIMDAL_API_KEY")) res, err := client.Do(req) if err != nil { panic(err) } defer res.Body.Close() body, _ := io.ReadAll(res.Body) fmt.Println(string(body)) } ``` * PHP ```php 2]); $response = $client->get("https://heimdal.codebrewerz.com/api/v1/check", [ 'headers' => ['Authorization' => 'Bearer ' . getenv('HEIMDAL_API_KEY')], 'query' => ['ip' => "185.220.101.1", 'email' => "test@mailinator.com"], ]); echo $response->getBody(); ``` ## Response [Section titled “Response”](#response) A successful check answers `200` with a JSON object. ```json { "block": true, "reasons": ["disposable_email", "tor", "vpn", "bad_isp"], "email": { "address": "test@mailinator.com", "domain": "mailinator.com", "disposable": true }, "ip": { "address": "185.220.101.1", "tor": true, "vpn": true, "proxy": false, "bad_isp": true, "asn": 60729, "isp": "TORSERVERS-NET Stiftung Erneuerbare Freiheit" }, "custom": { "matched": [] } } ``` ### Fields [Section titled “Fields”](#fields) | Field | Type | Description | | ------------------------ | ---------------- | --------------------------------------------------------------------------------------------------------------------------------------- | | `block` | boolean | `true` when `reasons` is not empty. | | `reasons` | string\[] | The signals that fired, always in this order: `disposable_email`, `tor`, `proxy`, `vpn`, `bad_isp`, `custom_list`. Empty when none did. | | `email` | object or `null` | `null` when you sent no `email`. | | `email.address` | string | The address as Heimdal compared it: trimmed, lowercased, with the domain in its ASCII form. | | `email.domain` | string | The part after the last `@`, lowercased. An internationalised domain is in its ASCII (`xn--`) form. | | `email.disposable` | boolean | The domain, or a parent of it, is on the disposable-domain list, or its mail servers belong to a known disposable provider. | | `ip` | object or `null` | `null` when you sent no `ip`. | | `ip.address` | string | The address as you sent it, trimmed. | | `ip.tor` | boolean | The address is a Tor exit node. | | `ip.vpn` | boolean | The address belongs to a VPN provider’s network. | | `ip.proxy` | boolean | The address is on the open-proxy list. | | `ip.bad_isp` | boolean | The address belongs to a hosting, datacenter or VPN network. Always `true` when `ip.vpn` is. | | `ip.asn` | number or `null` | The number of the network (autonomous system) that announces the address. `null` when no network does, as for private addresses. | | `ip.isp` | string or `null` | That network’s name. `null` when unknown. | | `custom` | object | Always present. | | `custom.matched` | array | The entries on your [custom lists](/docs/custom-lists/) that this check hit. | | `custom.matched[].list` | string | The name of the list that holds the entry. | | `custom.matched[].kind` | string | `email`, `domain`, `ip` or `cidr`. | | `custom.matched[].value` | string | The entry as stored. | [Signals explained](/docs/reference/signals/) describes how each signal is decided. ### TypeScript [Section titled “TypeScript”](#typescript) There is no SDK. If you want the response typed, this is the whole of it: ```ts type CheckResult = { block: boolean; reasons: ( "disposable_email" | "tor" | "proxy" | "vpn" | "bad_isp" | "custom_list" )[]; email: { address: string; domain: string; disposable: boolean } | null; ip: { address: string; tor: boolean; vpn: boolean; proxy: boolean; bad_isp: boolean; asn: number | null; isp: string | null; } | null; custom: { matched: { list: string; kind: "email" | "domain" | "ip" | "cidr"; value: string; }[]; }; }; ``` ### Sending one value [Section titled “Sending one value”](#sending-one-value) A value you leave out comes back as `null`, and its signals cannot fire. This is the answer to a check with only an `email`: ```json { "block": false, "reasons": [], "email": { "address": "ada@example.com", "domain": "example.com", "disposable": false }, "ip": null, "custom": { "matched": [] } } ``` ### Response headers [Section titled “Response headers”](#response-headers) | Header | Sent | | -------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `Cache-Control: no-store` | On every response. The lists change, so an answer should not be reused. | | `Heimdal-Degraded: custom_lists` | On a `200` when your custom lists could not be read. The signals are valid, but `custom.matched` is empty and `custom_list` is missing from `reasons`. | | `Retry-After` | On a `429`, in seconds: `1` when the key went over its per-second limit, up to `60` when the address sent too many requests with a missing or invalid key. On a `503` while Heimdal restarts: `5`. | ## Errors [Section titled “Errors”](#errors) Errors answer with a `4xx` or `5xx` status and this body: ```json { "error": { "code": "invalid_ip", "message": "`ip` must be one IPv4 or IPv6 address, without a port or zone." } } ``` Every code is listed in [Errors and limits](/docs/reference/errors/). # Docs for AI agents > Every page as Markdown, llms.txt, an OpenAPI spec and ready prompts, so an AI assistant or coding agent can integrate Heimdal from the source rather than from memory. These docs are written for people and for agents. Everything a person reads here, an agent can fetch as plain text, with no JavaScript and no sign-in. ## Hand the integration to an assistant [Section titled “Hand the integration to an assistant”](#hand-the-integration-to-an-assistant) Paste this into ChatGPT, Claude, Cursor, Copilot or any coding agent that can read URLs. It points the agent at the full docs and states the rules that matter most: keep the key on the server, set a timeout, fail open. Setup prompt for your AI assistant ```md You are helping me add Heimdal, a sign-up fraud API, to my application's sign-up flow. First read https://heimdal.codebrewerz.com/docs/llms-full.txt (or https://heimdal.codebrewerz.com/docs/llms.txt for the page index), then look at my codebase, find where accounts are created, and add a Heimdal check there. Ground rules for Heimdal: - API base URL: https://heimdal.codebrewerz.com/api. Endpoint: GET or POST /v1/check with `ip` and/or `email`. - Authenticate with `Authorization: Bearer `. Keys start with `hd_`. Read the key from the HEIMDAL_API_KEY environment variable; never hard-code it or send it to a browser. - Call Heimdal from the server only, at sign-up, with a timeout of about 2 seconds. If it times out or answers 5xx, allow the sign-up (fail open) and log it. - Errors are JSON: `{ "error": { "code", "message" } }`. 401 means a bad key, 402 no subscription, 429 rate limited. - Full documentation: https://heimdal.codebrewerz.com/docs/llms-full.txt. OpenAPI spec: https://heimdal.codebrewerz.com/docs/openapi.json. Each docs page is also Markdown at its URL plus `.md`. Block or flag the sign-up when the answer has `"block": true`, show the user a neutral message, and add a test that mocks the Heimdal response. ``` Or start a chat with it:[ChatGPT](https://chatgpt.com/?hints=search\&q=You%20are%20helping%20me%20add%20Heimdal%2C%20a%20sign-up%20fraud%20API%2C%20to%20my%20application's%20sign-up%20flow.%20First%20read%20https%3A%2F%2Fheimdal.codebrewerz.com%2Fdocs%2Fllms-full.txt%20\(or%20https%3A%2F%2Fheimdal.codebrewerz.com%2Fdocs%2Fllms.txt%20for%20the%20page%20index\)%2C%20then%20look%20at%20my%20codebase%2C%20find%20where%20accounts%20are%20created%2C%20and%20add%20a%20Heimdal%20check%20there.%0A%0AGround%20rules%20for%20Heimdal%3A%0A-%20API%20base%20URL%3A%20https%3A%2F%2Fheimdal.codebrewerz.com%2Fapi.%20Endpoint%3A%20GET%20or%20POST%20%2Fv1%2Fcheck%20with%20%60ip%60%20and%2For%20%60email%60.%0A-%20Authenticate%20with%20%60Authorization%3A%20Bearer%20%3Ckey%3E%60.%20Keys%20start%20with%20%60hd_%60.%20Read%20the%20key%20from%20the%20HEIMDAL_API_KEY%20environment%20variable%3B%20never%20hard-code%20it%20or%20send%20it%20to%20a%20browser.%0A-%20Call%20Heimdal%20from%20the%20server%20only%2C%20at%20sign-up%2C%20with%20a%20timeout%20of%20about%202%20seconds.%20If%20it%20times%20out%20or%20answers%205xx%2C%20allow%20the%20sign-up%20\(fail%20open\)%20and%20log%20it.%0A-%20Errors%20are%20JSON%3A%20%60%7B%20%22error%22%3A%20%7B%20%22code%22%2C%20%22message%22%20%7D%20%7D%60.%20401%20means%20a%20bad%20key%2C%20402%20no%20subscription%2C%20429%20rate%20limited.%0A-%20Full%20documentation%3A%20https%3A%2F%2Fheimdal.codebrewerz.com%2Fdocs%2Fllms-full.txt.%20OpenAPI%20spec%3A%20https%3A%2F%2Fheimdal.codebrewerz.com%2Fdocs%2Fopenapi.json.%20Each%20docs%20page%20is%20also%20Markdown%20at%20its%20URL%20plus%20%60.md%60.%0A%0ABlock%20or%20flag%20the%20sign-up%20when%20the%20answer%20has%20%60%22block%22%3A%20true%60%2C%20show%20the%20user%20a%20neutral%20message%2C%20and%20add%20a%20test%20that%20mocks%20the%20Heimdal%20response.)·[Claude](https://claude.ai/new?q=You%20are%20helping%20me%20add%20Heimdal%2C%20a%20sign-up%20fraud%20API%2C%20to%20my%20application's%20sign-up%20flow.%20First%20read%20https%3A%2F%2Fheimdal.codebrewerz.com%2Fdocs%2Fllms-full.txt%20\(or%20https%3A%2F%2Fheimdal.codebrewerz.com%2Fdocs%2Fllms.txt%20for%20the%20page%20index\)%2C%20then%20look%20at%20my%20codebase%2C%20find%20where%20accounts%20are%20created%2C%20and%20add%20a%20Heimdal%20check%20there.%0A%0AGround%20rules%20for%20Heimdal%3A%0A-%20API%20base%20URL%3A%20https%3A%2F%2Fheimdal.codebrewerz.com%2Fapi.%20Endpoint%3A%20GET%20or%20POST%20%2Fv1%2Fcheck%20with%20%60ip%60%20and%2For%20%60email%60.%0A-%20Authenticate%20with%20%60Authorization%3A%20Bearer%20%3Ckey%3E%60.%20Keys%20start%20with%20%60hd_%60.%20Read%20the%20key%20from%20the%20HEIMDAL_API_KEY%20environment%20variable%3B%20never%20hard-code%20it%20or%20send%20it%20to%20a%20browser.%0A-%20Call%20Heimdal%20from%20the%20server%20only%2C%20at%20sign-up%2C%20with%20a%20timeout%20of%20about%202%20seconds.%20If%20it%20times%20out%20or%20answers%205xx%2C%20allow%20the%20sign-up%20\(fail%20open\)%20and%20log%20it.%0A-%20Errors%20are%20JSON%3A%20%60%7B%20%22error%22%3A%20%7B%20%22code%22%2C%20%22message%22%20%7D%20%7D%60.%20401%20means%20a%20bad%20key%2C%20402%20no%20subscription%2C%20429%20rate%20limited.%0A-%20Full%20documentation%3A%20https%3A%2F%2Fheimdal.codebrewerz.com%2Fdocs%2Fllms-full.txt.%20OpenAPI%20spec%3A%20https%3A%2F%2Fheimdal.codebrewerz.com%2Fdocs%2Fopenapi.json.%20Each%20docs%20page%20is%20also%20Markdown%20at%20its%20URL%20plus%20%60.md%60.%0A%0ABlock%20or%20flag%20the%20sign-up%20when%20the%20answer%20has%20%60%22block%22%3A%20true%60%2C%20show%20the%20user%20a%20neutral%20message%2C%20and%20add%20a%20test%20that%20mocks%20the%20Heimdal%20response.) On every docs page, **Copy LLM prompt** (under the title) copies that page in the same frame, ready for you to add your task at the end. **Copy as Markdown** copies the page alone. ## Machine-readable files [Section titled “Machine-readable files”](#machine-readable-files) | File | What it holds | | ----------------------------------------- | ----------------------------------------------------------------------------------------------------------------- | | [`/llms.txt`](/docs/llms.txt) | The index: quick facts about the API, then every page as a Markdown link with its description. | | [`/llms-full.txt`](/docs/llms-full.txt) | All docs in one Markdown file. | | [`/llms-small.txt`](/docs/llms-small.txt) | All docs, abridged for small context windows. | | `.md` | Any page as Markdown: [`/quickstart.md`](/docs/quickstart.md), [`/reference/check.md`](/docs/reference/check.md). | | [`/openapi.json`](/docs/openapi.json) | OpenAPI 3.1 for `GET` and `POST /v1/check`, with every field, error and header. | Each HTML page also names its Markdown copy in a `` tag, and the files are served with `Access-Control-Allow-Origin: *`, so tools running in a browser can read them too. ## Crawlers [Section titled “Crawlers”](#crawlers) `robots.txt` allows every crawler, AI crawlers by name included (GPTBot, ClaudeBot, PerplexityBot and others). The docs hold nothing private. ## Tips for agents [Section titled “Tips for agents”](#tips-for-agents) * Read [`/llms.txt`](/docs/llms.txt) first, then only the pages the task needs. * Prefer the [OpenAPI spec](/docs/openapi.json) for field names and types; prefer the [check reference](/docs/reference/check/) for what the fields mean. * Call the API from server code only. A key in a browser bundle or a mobile app is a leaked key. * Treat `block` as a recommendation. [Best practices](/docs/guides/best-practices/) has a sensible starting policy. # Authentication > Every request carries an API key. Keys start with hd_, belong to one account, and must stay on your server. ## Create a key [Section titled “Create a key”](#create-a-key) In the [dashboard](https://heimdal.codebrewerz.com), open **API keys** and create a key. The full key is shown once, when you create it. If you lose it, create a new one and revoke the old one. Keys start with `hd_`. A key belongs to your account and works while the account’s subscription is active: every call checks emails and IP addresses, matches your [custom lists](/docs/custom-lists/) and counts toward your analytics. ## Send the key [Section titled “Send the key”](#send-the-key) Send the key in the `Authorization` header as a bearer token: ```http Authorization: Bearer hd_your_key ``` If your HTTP client makes that awkward, the `x-api-key` header works the same way: ```http x-api-key: hd_your_key ``` When a request carries both, the bearer token is used. * curl ```sh curl "https://heimdal.codebrewerz.com/api/v1/check?email=test%40mailinator.com" \ -H "Authorization: Bearer $HEIMDAL_API_KEY" ``` * Node (fetch) ```js const response = await fetch("https://heimdal.codebrewerz.com/api/v1/check?email=test%40mailinator.com", { headers: { Authorization: `Bearer ${process.env.HEIMDAL_API_KEY}` }, signal: AbortSignal.timeout(2000), }); console.log(await response.json()); ``` * Node (axios) ```js import axios from "axios"; const { data } = await axios.get("https://heimdal.codebrewerz.com/api/v1/check", { params: { email: "test@mailinator.com" }, headers: { Authorization: `Bearer ${process.env.HEIMDAL_API_KEY}` }, timeout: 2000, }); console.log(data); ``` * Python ```python import os import requests response = requests.get( "https://heimdal.codebrewerz.com/api/v1/check", params={"email": "test@mailinator.com"}, headers={"Authorization": f"Bearer {os.environ['HEIMDAL_API_KEY']}"}, timeout=2, ) print(response.json()) ``` * Java ```java // Java 11+, no dependencies. import java.net.URI; import java.net.http.HttpClient; import java.net.http.HttpRequest; import java.net.http.HttpResponse; import java.time.Duration; public class Check { public static void main(String[] args) throws Exception { String key = System.getenv("HEIMDAL_API_KEY"); if (key == null || key.isBlank()) { throw new IllegalStateException("Set HEIMDAL_API_KEY"); } HttpClient client = HttpClient.newBuilder() .connectTimeout(Duration.ofSeconds(2)) .build(); HttpRequest request = HttpRequest.newBuilder(URI.create("https://heimdal.codebrewerz.com/api/v1/check?email=test%40mailinator.com")) .timeout(Duration.ofSeconds(2)) .header("Authorization", "Bearer " + key) .GET() .build(); HttpResponse response = client.send(request, HttpResponse.BodyHandlers.ofString()); // 200: the check. Anything else: {"error":{"code","message"}}. System.out.println(response.statusCode() + " " + response.body()); } } ``` * Rust Cargo.toml ```rust // [dependencies] // reqwest = { version = "0.13", features = ["json", "query"] } // serde_json = "1" // tokio = { version = "1", features = ["macros", "rt-multi-thread"] } use std::time::Duration; #[tokio::main] async fn main() -> Result<(), Box> { let key = std::env::var("HEIMDAL_API_KEY")?; let client = reqwest::Client::builder() .timeout(Duration::from_secs(2)) .build()?; let response = client .get("https://heimdal.codebrewerz.com/api/v1/check") .bearer_auth(&key) .query(&[("email", "test@mailinator.com")]) .send() .await?; // 200: the check. Anything else: {"error":{"code","message"}}. let status = response.status(); let answer: serde_json::Value = response.json().await?; println!("{status} {answer}"); Ok(()) } ``` * Go ```go package main import ( "fmt" "io" "net/http" "os" "time" ) func main() { client := &http.Client{Timeout: 2 * time.Second} req, err := http.NewRequest("GET", "https://heimdal.codebrewerz.com/api/v1/check?email=test%40mailinator.com", nil) if err != nil { panic(err) } req.Header.Set("Authorization", "Bearer "+os.Getenv("HEIMDAL_API_KEY")) res, err := client.Do(req) if err != nil { panic(err) } defer res.Body.Close() body, _ := io.ReadAll(res.Body) fmt.Println(string(body)) } ``` * PHP ```php 2]); $response = $client->get("https://heimdal.codebrewerz.com/api/v1/check", [ 'headers' => ['Authorization' => 'Bearer ' . getenv('HEIMDAL_API_KEY')], 'query' => ['email' => "test@mailinator.com"], ]); echo $response->getBody(); ``` ## Keep the key on your server [Section titled “Keep the key on your server”](#keep-the-key-on-your-server) Caution Never call the check endpoint from a browser or a mobile app. Anyone can read a key that ships to a client, and use your subscription with it. The API is built for server-to-server calls. Cross-origin browser requests are refused: only the Heimdal dashboard’s own origin is allowed by CORS. * Store the key in an environment variable or a secret manager, not in source control. * Use a separate key for each service and environment, so you can revoke one without touching the others. * Each key has its own rate limit: 100 requests a second. See [Rate limits](/docs/reference/rate-limits/). ## Revoke and rotate [Section titled “Revoke and rotate”](#revoke-and-rotate) Revoke a key in the dashboard under **API keys**. To rotate a key without downtime: 1. Create a new key. 2. Deploy it to your service. 3. Revoke the old key once nothing uses it. ## When authentication fails [Section titled “When authentication fails”](#when-authentication-fails) | Status | Code | Meaning | | ------ | ----------------------- | ------------------------------------------------------------- | | `401` | `missing_api_key` | No key in `Authorization` or `x-api-key`. | | `401` | `invalid_api_key` | The key does not exist or was revoked. | | `402` | `subscription_required` | The key is valid, but the account has no active subscription. | If a renewal payment fails, the API keeps answering for 3 days so you can fix the payment method. After that it answers `402` until the subscription is active again. The full list of errors is in [Errors and limits](/docs/reference/errors/). # Custom lists > Your own blocklists of emails, domains, IP addresses and ranges, checked on every call. A custom list is a named set of entries that you want to block: the customer who charged back, a competitor’s domain, a network that keeps abusing your trial. Every check made with one of your account’s keys is compared against all of your lists, and a hit comes back in `custom.matched`. ## Create a list [Section titled “Create a list”](#create-a-list) Lists are managed in the [dashboard](https://heimdal.codebrewerz.com) under **Custom lists**. Create a list, give it a name, and add entries one at a time or paste many at once, one per line. There is no public API for managing lists. The check endpoint only reads them. ## Entry kinds [Section titled “Entry kinds”](#entry-kinds) You do not choose a kind. Heimdal works it out from what you enter: | Kind | Example | Recognised by | Matches | | -------- | ----------------- | ------------------------- | ---------------------------------------------------- | | `email` | `bad@example.com` | Contains an `@` | That one mailbox. | | `cidr` | `198.51.100.0/24` | Contains a `/` | Every address in the range. IPv4 and IPv6 both work. | | `ip` | `203.0.113.7` | Is an IP address | That one address. | | `domain` | `evil.example` | Any other name with a dot | Every email at that domain and at its subdomains. | Entries are trimmed and lowercased when you add them, and internationalised domains are stored in their ASCII form. These are refused, because they could never match: * Wildcards such as `*.example.com`. A `domain` entry already covers its subdomains. * Names without a dot, such as `localhost`. * Anything with a space in it. * A range with an impossible prefix, such as `1.2.3.4/99`. ## How matching works [Section titled “How matching works”](#how-matching-works) ### Emails [Section titled “Emails”](#emails) An `email` entry matches the same mailbox, compared without regard to case. `Bad@Example.com` and `bad@example.com` are one mailbox. Plus tags and dots are not folded. An entry for `bad@example.com` does not match `bad+1@example.com`. ### Domains [Section titled “Domains”](#domains) A `domain` entry matches the email’s domain and every subdomain of the entry. An entry for `evil.example` matches `x@evil.example` and `x@mail.evil.example`. Matching walks up from the email’s domain and stops at its registrable domain. An entry for a public suffix such as `co.uk` therefore does not match the domains registered under it. Domain entries apply to emails only. They are never compared with an IP address. ### IP addresses and ranges [Section titled “IP addresses and ranges”](#ip-addresses-and-ranges) An `ip` entry matches that exact address. A `cidr` entry matches every address in its range. IPv4 and IPv4-mapped IPv6 are the same address here: an entry for `198.51.100.0/24` matches a check for `::ffff:198.51.100.200`. ## In the response [Section titled “In the response”](#in-the-response) Each matching entry is listed with the name of its list, its kind and its value. Any match adds `custom_list` to `reasons` and sets `block` to `true`. ```json { "block": true, "reasons": ["custom_list"], "email": { "address": "x@mail.evil.example", "domain": "mail.evil.example", "disposable": false }, "ip": null, "custom": { "matched": [{ "list": "Banned", "kind": "domain", "value": "evil.example" }] } } ``` One check can hit several entries, in one list or in several. All of them are returned. ## Timing [Section titled “Timing”](#timing) * A change to a list applies to the next check. * A new subscription takes up to 60 seconds to reach the API. Until then every call answers `402`. ## Limits [Section titled “Limits”](#limits) | Limit | Value | | ------- | -------------------------------------------- | | Lists | 20 per account | | Entries | 50,000 per account, counted across all lists | ## If the lists cannot be read [Section titled “If the lists cannot be read”](#if-the-lists-cannot-be-read) A check does not fail because your lists are unavailable. Heimdal answers `200` with every other signal, leaves `custom.matched` empty, and adds the header `Heimdal-Degraded: custom_lists`. See [Degraded answers](/docs/reference/errors/#degraded-answers). ## Lists only block [Section titled “Lists only block”](#lists-only-block) There are no allowlists. A custom list can add a reason to block; it cannot remove one. To let a known customer through despite a signal, make that exception in your own code. # Data sources > The lists behind every signal, who maintains them, and how often Heimdal refreshes each one. Heimdal’s signals are built from openly licensed lists, merged with entries that Heimdal maintains itself. This page names every public source. Each list remains the work of its maintainers. ## Sources [Section titled “Sources”](#sources) | Signal | Source | Refreshed | | ---------------- | --------------------------------------------------------------------------------------------- | --------- | | Disposable email | [disposable/disposable-email-domains](https://github.com/disposable/disposable-email-domains) | Daily | | Disposable email | [ivolo/disposable-email-domains](https://github.com/ivolo/disposable-email-domains) | Daily | | Disposable email | [7c/fakefilter](https://github.com/7c/fakefilter) | Daily | | Tor | [Tor Project bulk exit list](https://check.torproject.org/torbulkexitlist) | Hourly | | Open proxy | [monosans/proxy-list](https://github.com/monosans/proxy-list) | Hourly | | Network of an IP | [sapics/ip-location-db](https://github.com/sapics/ip-location-db), the `origin-asn` database | Daily | | Network of an IP | [iptoasn.com](https://iptoasn.com), used when the source above cannot be fetched | Daily | | VPN | [X4BNet/lists_vpn](https://github.com/X4BNet/lists_vpn), the VPN network list | Daily | | VPN | [O-X-L/risk-db-lists](https://github.com/O-X-L/risk-db-lists), `kind_vpn` | Daily | | Bad ISP | [X4BNet/lists_vpn](https://github.com/X4BNet/lists_vpn), the datacenter network list | Daily | | Bad ISP | [brianhama/bad-asn-list](https://github.com/brianhama/bad-asn-list) | Daily | | Bad ISP | [O-X-L/risk-db-lists](https://github.com/O-X-L/risk-db-lists), `kind_hosting` | Daily | “Network of an IP” is the map from an address to the network that announces it. It supplies `ip.asn` and `ip.isp`, and it is how the `vpn` and `bad_isp` signals find the network to look up. The VPN lists also feed `bad_isp`, as [Signals explained](/docs/reference/signals/#bad-isp) describes. From the X4BNet project Heimdal uses the lists of network numbers only, not the generated IP ranges. Every source is a list that Heimdal downloads and keeps on its own servers. Nothing from your checks is sent to a third party. The one exception is the email’s domain, never the address: Heimdal looks up its MX records in DNS, like any mail server would, to recognise fresh [disposable domains](/docs/reference/signals/#disposable-email). ## Heimdal’s own entries [Section titled “Heimdal’s own entries”](#heimdals-own-entries) Heimdal maintains private additions for four of the signals: disposable domains, proxy addresses, VPN networks and risky networks. They are merged with the public lists at every refresh and apply to every customer. A response does not say whether a signal came from a public list or a private entry. Your own [custom lists](/docs/custom-lists/) are separate. They apply to your account only and are reported under `custom.matched`. ## What the lists hold [Section titled “What the lists hold”](#what-the-lists-hold) These are floors, not exact counts. Heimdal checks after every refresh that the live data stays above them. | List | At least | | ----------------------------------------- | -------- | | Disposable email domains | 150,000 | | Risky networks (hosting, datacenter, VPN) | 2,000 | | IP ranges that belong to VPN networks | 7,000 | ## How refreshing works [Section titled “How refreshing works”](#how-refreshing-works) * Heimdal looks for updates every hour. The Tor and proxy lists are fetched again once their copy is an hour old, every other list once its copy is a day old. * A refresh builds a complete new set of lists and swaps it in at once. A check never sees a half-updated state. * A download is checked before it is used. One that is empty, far smaller than expected, or under half the size of the last good copy is rejected, and the last good copy stays in use. * After a restart Heimdal loads its saved copies first, so it can answer without waiting for the network. Until the disposable-domain list, the Tor list and the network map have each loaded once, the API answers `503 lists_unavailable`. ## Report a wrong entry [Section titled “Report a wrong entry”](#report-a-wrong-entry) If a domain or a network is listed wrongly, the lasting fix is at the source: report it to the maintainers of the list that carries it. The correction reaches Heimdal at the next refresh, within a day for most lists. # Best practices > Where to call Heimdal, how long to wait for it, what to do when it does not answer, and which signals deserve a hard block. ## Call it once, on your server, before you create the account [Section titled “Call it once, on your server, before you create the account”](#call-it-once-on-your-server-before-you-create-the-account) Run the check in your signup handler, after you have validated the form and before you write the user to your database or send any email. A refused signup then costs you nothing. * **Send both values.** The email catches disposable inboxes, the IP address catches Tor, proxies and server networks. Either alone sees half the picture. * **Check once per signup.** Do not check on every page view or every login, and do not store the answer to reuse later: the lists change every hour. * **Stay on the server.** The API key must never reach a browser. See [Authentication](/docs/authentication/#keep-the-key-on-your-server). * **Prefer `POST`.** A JSON body keeps email addresses out of URLs and access logs. ## Send the visitor’s real IP address [Section titled “Send the visitor’s real IP address”](#send-the-visitors-real-ip-address) Behind a load balancer or a CDN, the address your code sees is the proxy’s. Send the address of the visitor: * Read it from the header your own proxy sets, and only trust that header when the request really came through your proxy. A visitor can write anything into `X-Forwarded-For`. * If the value might be malformed, validate it or leave `ip` out. An invalid `ip` answers `400` and takes the email check down with it. * If you have no address, send the email alone. `ip` comes back as `null`. In development the address is usually `127.0.0.1`. That is fine: a private address has no network, so none of the IP signals fire. ## Set a timeout [Section titled “Set a timeout”](#set-a-timeout) A signup must not hang because of a network problem between you and Heimdal. Give the request a short timeout and move on when it expires. Two seconds is generous. ```js const response = await fetch("https://heimdal.codebrewerz.com/api/v1/check", { method: "POST", headers: { Authorization: `Bearer ${process.env.HEIMDAL_API_KEY}`, "Content-Type": "application/json", }, body: JSON.stringify({ ip, email }), signal: AbortSignal.timeout(2000), }); ``` ## Fail open [Section titled “Fail open”](#fail-open) When the check does not produce an answer, let the signup through. Turning away a real customer because of an outage is worse than letting one doubtful signup pass, and you still have email verification behind it. | What happened | What to do | | ------------------------ | ---------------------------------------------------------------------------- | | Timeout or network error | Allow the signup. Log it. | | `429 rate_limited` | Allow the signup. Log it; if it keeps happening, find the runaway caller. | | `503` | Allow the signup. Log it. | | `401` or `402` | Allow the signup, and alert yourself: the key or the subscription is broken. | | `400` | Allow the signup, and fix the request your code builds. | Do not retry inside the signup request. A retry makes the visitor wait, and failing open already covers the gap. Never show Heimdal’s error messages to your users. They are written for your logs. Heimdal’s own signup does exactly this: if the check cannot answer, the signup goes ahead and the failure is logged. ## Choose a policy [Section titled “Choose a policy”](#choose-a-policy) `block` is `true` when any signal fires. That is the strictest policy there is, and for most products it refuses too many good customers. A VPN alone sets it. Start from the policy Heimdal uses on its own signup, and tighten it only where you see abuse: | Signal | Suggested action | Why | | ------------------ | -------------------- | ----------------------------------------------------------------------------------- | | `email.disposable` | Refuse | A throwaway inbox has no purpose at signup other than avoiding you. | | `ip.tor` | Refuse | Few genuine signups arrive through Tor; a lot of abuse does. | | `ip.proxy` | Refuse | Open proxies are abused by design. | | `custom.matched` | Refuse | You put the entry there. | | `ip.vpn` | Log, or add friction | Plenty of legitimate people are on a VPN, developers and remote workers among them. | | `ip.bad_isp` | Log, or add friction | Company networks and cloud desktops live here too. | ```js function refusalFor(result) { if (result.email?.disposable) { return "Disposable email addresses can't be used to sign up."; } if (result.ip?.tor || result.ip?.proxy) { return "Sign-ups from this network aren't allowed. Contact support if this is a mistake."; } if (result.custom.matched.length > 0) { return "This sign-up can't be completed. Contact support if this is a mistake."; } return null; } ``` Caution Do not block on `vpn` alone unless you mean it. If your product has a specific reason to refuse VPN users, such as regional licensing or a history of trial abuse through VPNs, make that a deliberate choice and tell the visitor why they were refused. ### Between allowing and refusing [Section titled “Between allowing and refusing”](#between-allowing-and-refusing) A signal does not have to end the signup. For `vpn` and `bad_isp` in particular, consider a step that costs an honest visitor little: * Require email verification before the account can do anything. * Show a CAPTCHA. * Hold back the free trial or the free credits until a payment method is added. * Put the account in a queue for manual review. ## Tell the visitor what to fix [Section titled “Tell the visitor what to fix”](#tell-the-visitor-what-to-fix) A refusal the visitor can act on loses fewer customers: * For a disposable email, say so. People with a real address will use it. * For a network signal, say that signups from this network are not allowed, and give a way to reach you. Do not say which list they are on. ## Log what you decided [Section titled “Log what you decided”](#log-what-you-decided) Store `reasons`, and `ip.asn` and `ip.isp` when present, next to the signup: for the ones you refused and for the ones you let through. A month of that data shows whether your policy is too strict or too loose. The dashboard keeps this for you: counts per reason over time, and a log of recent checks. ## Look after your keys [Section titled “Look after your keys”](#look-after-your-keys) * One key per service and environment. * Rotate a key by creating the new one first. A revoked key can keep working for up to 60 seconds. * A leaked key lets someone else use your subscription and probe your custom lists. Revoke it and create a new one. # Better Auth > Guard email-and-password sign-up with a before hook. This is the same hook Heimdal runs on its own signup. [Better Auth](https://www.better-auth.com) runs `hooks.before` ahead of every auth endpoint. A hook on the `/sign-up/email` path can check the visitor and refuse the sign-up before anything is written to your database. ## Before you start [Section titled “Before you start”](#before-you-start) * A working Better Auth setup with `emailAndPassword` enabled. This guide was written against Better Auth 1.7. * `@better-auth/core` in your dependencies, at the same version as `better-auth`. The hook imports `getIP` from it. * Your Heimdal key in the `HEIMDAL_API_KEY` environment variable. ## 1. Add the helper [Section titled “1. Add the helper”](#1-add-the-helper) Save this next to your auth file. It is the TypeScript form of the helper from the [Node.js guide](/docs/guides/node/), which explains each part: `checkSignup` calls the API with a timeout and returns `null` when there is no answer, and `refusalFor` turns an answer into a message or `null`. heimdal.ts ```ts import { isIP } from "node:net"; export type CheckResult = { block: boolean; reasons: string[]; email: { address: string; domain: string; disposable: boolean } | null; ip: { address: string; tor: boolean; vpn: boolean; proxy: boolean; bad_isp: boolean; asn: number | null; isp: string | null; } | null; custom: { matched: { list: string; kind: string; value: string }[] }; }; const CHECK_URL = "https://heimdal.codebrewerz.com/api/v1/check"; /** Heimdal's answer, or `null` when the check could not be made. */ export async function checkSignup(input: { ip: string | null; email: string; }): Promise { try { const response = await fetch(CHECK_URL, { method: "POST", headers: { Authorization: `Bearer ${process.env.HEIMDAL_API_KEY}`, "Content-Type": "application/json", }, // An address that is not valid would fail the whole request: leave it out. body: JSON.stringify({ ip: isIP(input.ip ?? "") ? input.ip : null, email: input.email, }), signal: AbortSignal.timeout(2000), }); if (!response.ok) { const { error } = await response.json(); console.error( `Heimdal ${response.status} ${error.code}: ${error.message}`, ); return null; } return await response.json(); } catch (cause) { console.error("Heimdal check failed, sign-up allowed:", cause); return null; } } /** The message that refuses this sign-up, or `null` to let it through. */ export function refusalFor(result: CheckResult | null): string | null { if (result === null) return null; if (result.email?.disposable) { return "Disposable email addresses can't be used to sign up."; } if (result.ip?.tor || result.ip?.proxy) { return "Sign-ups from this network aren't allowed. Contact support if this is a mistake."; } if (result.custom.matched.length > 0) { return "This sign-up can't be completed. Contact support if this is a mistake."; } return null; } ``` ## 2. Add the hook [Section titled “2. Add the hook”](#2-add-the-hook) auth.ts ```ts import { getIP } from "@better-auth/core/utils/ip"; import { betterAuth } from "better-auth"; import { APIError, createAuthMiddleware } from "better-auth/api"; import { checkSignup, refusalFor } from "./heimdal"; export const auth = betterAuth({ // ...the options you already have emailAndPassword: { enabled: true }, advanced: { // The header your reverse proxy puts the visitor's address in. ipAddress: { ipAddressHeaders: ["x-forwarded-for"] }, }, hooks: { before: createAuthMiddleware(async (ctx) => { if (ctx.path !== "/sign-up/email") return; const email = ctx.body?.email; // Not a sign-up body: Better Auth's own validation refuses it next. if (typeof email !== "string") return; const source = ctx.request ?? ctx.headers; const ip = source === undefined ? null : getIP(source, ctx.context.options); const result = await checkSignup({ ip, email }); const refusal = refusalFor(result); if (refusal !== null) { throw new APIError("BAD_REQUEST", { message: refusal }); } }), }, }); ``` A refused sign-up answers `400` with your message, and no user is created. ## How it works [Section titled “How it works”](#how-it-works) * **`ctx.path`** is the auth endpoint being called. The hook returns early for everything except email sign-up, so sign-in and every other route are untouched. * **`getIP`** resolves the visitor’s address the way Better Auth itself does, from the headers named in `advanced.ipAddress`. It returns `null` when it cannot find an address it trusts, and the helper then checks the email alone. * **`checkSignup`** fails open. If Heimdal does not answer within two seconds, `result` is `null`, `refusalFor` returns `null`, and the sign-up goes ahead. * **`APIError`** thrown from a `before` hook stops the request and reaches the client as written. ## Get the IP address right [Section titled “Get the IP address right”](#get-the-ip-address-right) `getIP` only trusts what you configure: * With no `trustedProxies`, it accepts the header only when it holds exactly one address. A header with a chain of addresses gives `null`. * Behind more than one proxy, list your proxies so the chain can be read from the right: ```ts advanced: { ipAddress: { ipAddressHeaders: ["x-forwarded-for"], trustedProxies: ["10.0.0.0/8"], }, }, ``` * In development Better Auth falls back to a local address. Heimdal answers with no IP signals for it, which is what you want. If sign-ups in production never show an IP signal, log `ip` in the hook. A `null` there means the header name or the trusted proxies do not match your setup, and the Tor and proxy checks are not running. ## Show the message [Section titled “Show the message”](#show-the-message) The message arrives on the client as the error of the sign-up call: ```ts const { error } = await authClient.signUp.email({ email, password, name }); if (error) { // "Disposable email addresses can't be used to sign up." showError(error.message); } ``` ## What it covers [Section titled “What it covers”](#what-it-covers) The hook guards email-and-password sign-up. Sign-ups that enter another way, such as a social provider, do not pass through `/sign-up/email` and are not checked by it. # Java > A complete integration with Java's built-in HttpClient. One class that calls the API with a timeout and fails open, one method that turns the answer into a decision, and a Spring Boot sign-up handler. This guide needs Java 17 or later (records, `java.net.http`). The client has one dependency, Jackson, to read JSON; most Java web apps already have it. pom.xml ```xml com.fasterxml.jackson.core jackson-databind 2.23.0 ``` ## 1. Call the API [Section titled “1. Call the API”](#1-call-the-api) `Heimdal.check` returns Heimdal’s answer, or `Optional.empty()` when there is none: a timeout, a network error, or an error status. Empty means “no opinion”, and the caller lets the sign-up through. Heimdal.java ```java import java.io.IOException; import java.net.InetAddress; import java.net.URI; import java.net.http.HttpClient; import java.net.http.HttpRequest; import java.net.http.HttpResponse; import java.time.Duration; import java.util.LinkedHashMap; import java.util.Map; import java.util.Optional; import java.util.logging.Logger; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; public final class Heimdal { private static final Logger LOG = Logger.getLogger(Heimdal.class.getName()); private static final URI CHECK_URL = URI.create("https://heimdal.codebrewerz.com/api/v1/check"); private static final Duration TIMEOUT = Duration.ofSeconds(2); private final HttpClient client = HttpClient.newBuilder() .connectTimeout(TIMEOUT) .build(); private final ObjectMapper json = new ObjectMapper(); private final String apiKey; public Heimdal(String apiKey) { if (apiKey == null || apiKey.isBlank()) { throw new IllegalArgumentException("Set HEIMDAL_API_KEY"); } this.apiKey = apiKey; } public static Heimdal fromEnv() { return new Heimdal(System.getenv("HEIMDAL_API_KEY")); } /** Heimdal's answer, or empty when the check could not be made. */ public Optional check(String ip, String email) { Map body = new LinkedHashMap<>(); // An address that is not valid would fail the whole request: leave it out. if (isIp(ip)) body.put("ip", ip); if (email != null) body.put("email", email); try { HttpRequest request = HttpRequest.newBuilder(CHECK_URL) .timeout(TIMEOUT) .header("Authorization", "Bearer " + apiKey) .header("Content-Type", "application/json") .POST(HttpRequest.BodyPublishers.ofString(json.writeValueAsString(body))) .build(); HttpResponse response = client.send(request, HttpResponse.BodyHandlers.ofString()); JsonNode answer = json.readTree(response.body()); if (response.statusCode() != 200) { JsonNode error = answer.path("error"); LOG.warning("Heimdal " + response.statusCode() + " " + error.path("code").asText() + ": " + error.path("message").asText()); return Optional.empty(); } return Optional.of(answer); } catch (IOException e) { LOG.warning("Heimdal check failed, sign-up allowed: " + e); return Optional.empty(); } catch (InterruptedException e) { Thread.currentThread().interrupt(); return Optional.empty(); } } /** Literal IPv4 or IPv6 only: never resolves a host name. */ static boolean isIp(String value) { if (value == null || value.isBlank()) return false; if (!value.matches("[0-9.]+|[0-9a-fA-F:.]*:[0-9a-fA-F:.]*")) return false; try { InetAddress.getByName(value); return true; } catch (IOException e) { return false; } } } ``` `HttpClient` is thread-safe: create one `Heimdal` and share it, for example as a Spring bean. ## 2. Decide [Section titled “2. Decide”](#2-decide) Keep the policy in one method, apart from the HTTP call. This one refuses disposable email, Tor, open proxies and custom-list hits. VPN and hosting networks pass. SignupPolicy.java ```java import java.util.Optional; import com.fasterxml.jackson.databind.JsonNode; public final class SignupPolicy { /** The message that refuses this sign-up, or empty to let it through. */ public static Optional refusalFor(Optional result) { if (result.isEmpty()) return Optional.empty(); JsonNode answer = result.get(); if (answer.path("email").path("disposable").asBoolean(false)) { return Optional.of("Disposable email addresses can't be used to sign up."); } JsonNode ip = answer.path("ip"); if (ip.path("tor").asBoolean(false) || ip.path("proxy").asBoolean(false)) { return Optional.of( "Sign-ups from this network aren't allowed. Contact support if this is a mistake."); } if (answer.path("custom").path("matched").size() > 0) { return Optional.of( "This sign-up can't be completed. Contact support if this is a mistake."); } return Optional.empty(); } } ``` To use the strict policy instead, refuse whenever `answer.path("block").asBoolean()` is true. [Best practices](/docs/guides/best-practices/#choose-a-policy) explains the trade-off. ## 3. Use it in your sign-up handler [Section titled “3. Use it in your sign-up handler”](#3-use-it-in-your-sign-up-handler) The example uses Spring Boot. The two calls are the same in any framework: Jakarta Servlet, Micronaut, Quarkus or Javalin. SignupController.java ```java import java.util.Map; import jakarta.servlet.http.HttpServletRequest; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RestController; @RestController public class SignupController { private final Heimdal heimdal = Heimdal.fromEnv(); record SignupRequest(String email, String password) {} @PostMapping("/signup") public ResponseEntity signup(@RequestBody SignupRequest body, HttpServletRequest http) { // Behind a proxy, set server.forward-headers-strategy=native so this is // the client's address, not the proxy's. var result = heimdal.check(http.getRemoteAddr(), body.email()); var refusal = SignupPolicy.refusalFor(result); if (refusal.isPresent()) { return ResponseEntity.badRequest().body(Map.of("error", refusal.get())); } // Create the user as you do today. return ResponseEntity.status(201).build(); } } ``` ## What this gets right [Section titled “What this gets right”](#what-this-gets-right) * **It fails open.** No answer from Heimdal never blocks a sign-up. * **It has a timeout.** Connect and response are both capped at two seconds. * **It sends the visitor’s address**, and only when it is a literal IP address. * **It keeps the key on the server**, in `HEIMDAL_API_KEY`, and refuses to start without it. * **It reads errors**: every non-200 answer is `{"error":{"code","message"}}` and is logged with its code. ## Test it [Section titled “Test it”](#test-it) ```sh curl -X POST "http://localhost:8080/signup" \ -H "Content-Type: application/json" \ -d '{"email": "test@mailinator.com", "password": "Correct-horse-9"}' ``` ```json { "error": "Disposable email addresses can't be used to sign up." } ``` # Node.js > A complete integration with the built-in fetch. One helper that calls the API with a timeout and fails open, and one function that turns the answer into a decision. This guide needs Node.js 18 or later for the built-in `fetch` and `AbortSignal.timeout`. It has no dependencies. ## 1. Call the API [Section titled “1. Call the API”](#1-call-the-api) `checkSignup` returns Heimdal’s answer, or `null` when there is none: a timeout, a network error, or an error status. `null` means “no opinion”, and the caller lets the signup through. heimdal.js ```js import { isIP } from "node:net"; const CHECK_URL = "https://heimdal.codebrewerz.com/api/v1/check"; /** Heimdal's answer, or `null` when the check could not be made. */ export async function checkSignup({ ip, email }) { try { const response = await fetch(CHECK_URL, { method: "POST", headers: { Authorization: `Bearer ${process.env.HEIMDAL_API_KEY}`, "Content-Type": "application/json", }, // An address that is not valid would fail the whole request: leave it out. body: JSON.stringify({ ip: isIP(ip ?? "") ? ip : null, email }), signal: AbortSignal.timeout(2000), }); if (!response.ok) { const { error } = await response.json(); console.error( `Heimdal ${response.status} ${error.code}: ${error.message}`, ); return null; } return await response.json(); } catch (cause) { console.error("Heimdal check failed, signup allowed:", cause); return null; } } ``` ## 2. Decide [Section titled “2. Decide”](#2-decide) Keep the policy in one function, apart from the HTTP call, so you can change it without touching the plumbing. This one refuses disposable email, Tor, open proxies and custom-list hits. VPN and hosting networks pass. heimdal.js ```js /** The message that refuses this signup, or `null` to let it through. */ export function refusalFor(result) { if (result === null) return null; if (result.email?.disposable) { return "Disposable email addresses can't be used to sign up."; } if (result.ip?.tor || result.ip?.proxy) { return "Sign-ups from this network aren't allowed. Contact support if this is a mistake."; } if (result.custom.matched.length > 0) { return "This sign-up can't be completed. Contact support if this is a mistake."; } return null; } ``` To use the strict policy instead, replace the body with `return result?.block ? "…" : null`. [Best practices](/docs/guides/best-practices/#choose-a-policy) explains the trade-off. ## 3. Use it in your signup handler [Section titled “3. Use it in your signup handler”](#3-use-it-in-your-signup-handler) The example uses Express. The two calls are the same in any framework. server.js ```js import express from "express"; import { checkSignup, refusalFor } from "./heimdal.js"; const app = express(); app.use(express.json()); // Behind one reverse proxy. Without this, `req.ip` is the proxy's address. app.set("trust proxy", 1); app.post("/signup", async (req, res) => { const { email } = req.body; const result = await checkSignup({ ip: req.ip, email }); const refusal = refusalFor(result); if (refusal !== null) { return res.status(400).json({ error: refusal }); } if (result !== null && result.reasons.length > 0) { console.info("signup allowed with signals", result.reasons, result.ip?.asn); } // Create the user as you do today. res.status(201).end(); }); app.listen(3000); ``` ## What this gets right [Section titled “What this gets right”](#what-this-gets-right) * **It fails open.** No answer from Heimdal never blocks a signup. * **It has a timeout.** The visitor waits two seconds at most. * **It sends the visitor’s address.** `trust proxy` makes `req.ip` the client address that your proxy reports. Set it to match your own setup. * **It keeps the key on the server**, in `HEIMDAL_API_KEY`. * **It logs signals it did not act on**, so you can review the policy later. ## Test it [Section titled “Test it”](#test-it) With the server running, a signup with a disposable address is refused: ```sh curl -X POST "http://localhost:3000/signup" \ -H "Content-Type: application/json" \ -d '{"email": "test@mailinator.com", "password": "correct horse battery"}' ``` ```json { "error": "Disposable email addresses can't be used to sign up." } ``` # Rust > A complete integration with reqwest and tokio. One function that calls the API with a timeout and fails open, typed answers with serde, a policy function, and an axum sign-up handler. This guide uses `reqwest` with `tokio`, and `serde` for typed answers. The handler example uses `axum`. Cargo.toml ```toml [dependencies] reqwest = { version = "0.13", features = ["json"] } serde = { version = "1", features = ["derive"] } serde_json = "1" tokio = { version = "1", features = ["macros", "rt-multi-thread"] } tracing = "0.1" # For the handler in step 3: axum = "0.8" ``` ## 1. Call the API [Section titled “1. Call the API”](#1-call-the-api) `check_signup` returns Heimdal’s answer, or `None` when there is none: a timeout, a network error, or an error status. `None` means “no opinion”, and the caller lets the sign-up through. Only the fields the policy reads are typed; serde ignores the rest. src/heimdal.rs ```rust use std::net::IpAddr; use std::time::Duration; use serde::{Deserialize, Serialize}; const CHECK_URL: &str = "https://heimdal.codebrewerz.com/api/v1/check"; #[derive(Serialize)] struct Query<'a> { #[serde(skip_serializing_if = "Option::is_none")] ip: Option, #[serde(skip_serializing_if = "Option::is_none")] email: Option<&'a str>, } #[derive(Debug, Deserialize)] pub struct Answer { pub block: bool, pub reasons: Vec, pub email: Option, pub ip: Option, pub custom: Custom, } #[derive(Debug, Deserialize)] pub struct EmailSignals { pub disposable: bool, } #[derive(Debug, Deserialize)] pub struct IpSignals { pub tor: bool, pub proxy: bool, pub vpn: bool, pub bad_isp: bool, pub asn: Option, } #[derive(Debug, Deserialize)] pub struct Custom { pub matched: Vec, } #[derive(Deserialize)] struct ErrorBody { error: ErrorDetail, } #[derive(Deserialize)] struct ErrorDetail { code: String, message: String, } /// One client for the whole app: it pools connections. Build it once. pub fn client() -> reqwest::Client { reqwest::Client::builder() .connect_timeout(Duration::from_secs(2)) .timeout(Duration::from_secs(2)) .build() .expect("TLS backend available") } /// Heimdal's answer, or `None` when the check could not be made. pub async fn check_signup( client: &reqwest::Client, api_key: &str, ip: Option<&str>, email: Option<&str>, ) -> Option { // An address that is not valid would fail the whole request: leave it out. let ip = ip .and_then(|value| value.parse::().ok()) .map(|addr| addr.to_string()); let response = client .post(CHECK_URL) .bearer_auth(api_key) .json(&Query { ip, email }) .send() .await; let response = match response { Ok(response) => response, Err(err) => { tracing::warn!("Heimdal check failed, sign-up allowed: {err}"); return None; } }; let status = response.status(); if !status.is_success() { match response.json::().await { Ok(body) => tracing::warn!( "Heimdal {status} {}: {}", body.error.code, body.error.message ), Err(_) => tracing::warn!("Heimdal {status}"), } return None; } match response.json::().await { Ok(answer) => Some(answer), Err(err) => { tracing::warn!("Heimdal answer unreadable, sign-up allowed: {err}"); None } } } ``` ## 2. Decide [Section titled “2. Decide”](#2-decide) Keep the policy in one function, apart from the HTTP call. This one refuses disposable email, Tor, open proxies and custom-list hits. VPN and hosting networks pass. src/heimdal.rs ```rust /// The message that refuses this sign-up, or `None` to let it through. pub fn refusal_for(answer: Option<&Answer>) -> Option<&'static str> { let answer = answer?; if answer.email.as_ref().is_some_and(|email| email.disposable) { return Some("Disposable email addresses can't be used to sign up."); } if answer.ip.as_ref().is_some_and(|ip| ip.tor || ip.proxy) { return Some( "Sign-ups from this network aren't allowed. Contact support if this is a mistake.", ); } if !answer.custom.matched.is_empty() { return Some("This sign-up can't be completed. Contact support if this is a mistake."); } None } ``` To use the strict policy instead, refuse whenever `answer.block` is `true`. [Best practices](/docs/guides/best-practices/#choose-a-policy) explains the trade-off. ## 3. Use it in your sign-up handler [Section titled “3. Use it in your sign-up handler”](#3-use-it-in-your-sign-up-handler) The example uses axum. The two calls are the same in any framework. src/main.rs ```rust mod heimdal; use std::net::SocketAddr; use std::sync::Arc; use axum::extract::{ConnectInfo, State}; use axum::http::StatusCode; use axum::response::IntoResponse; use axum::routing::post; use axum::{Json, Router}; use serde::Deserialize; struct AppState { heimdal: reqwest::Client, api_key: String, } #[derive(Deserialize)] struct Signup { email: String, password: String, } async fn signup( State(state): State>, // Behind a proxy, read the client address from the header your proxy // sets instead: this is the proxy's own address. ConnectInfo(peer): ConnectInfo, Json(body): Json, ) -> impl IntoResponse { let ip = peer.ip().to_string(); let answer = heimdal::check_signup( &state.heimdal, &state.api_key, Some(&ip), Some(&body.email), ) .await; if let Some(refusal) = heimdal::refusal_for(answer.as_ref()) { return ( StatusCode::BAD_REQUEST, Json(serde_json::json!({ "error": refusal })), ) .into_response(); } // Create the user as you do today, with body.password. let _ = &body.password; StatusCode::CREATED.into_response() } #[tokio::main] async fn main() { let state = Arc::new(AppState { heimdal: heimdal::client(), api_key: std::env::var("HEIMDAL_API_KEY").expect("Set HEIMDAL_API_KEY"), }); let app = Router::new() .route("/signup", post(signup)) .with_state(state); let listener = tokio::net::TcpListener::bind("0.0.0.0:3000").await.unwrap(); axum::serve( listener, app.into_make_service_with_connect_info::(), ) .await .unwrap(); } ``` ## What this gets right [Section titled “What this gets right”](#what-this-gets-right) * **It fails open.** No answer from Heimdal never blocks a sign-up. * **It has a timeout.** Connect and the whole request are capped at two seconds. * **It reuses one client**, so connections to Heimdal are pooled. * **It sends the visitor’s address**, and only when it parses as an IP address. * **It keeps the key on the server**, in `HEIMDAL_API_KEY`, and refuses to start without it. * **It reads errors**: every non-2xx answer is `{"error":{"code","message"}}` and is logged with its code. ## Test it [Section titled “Test it”](#test-it) ```sh curl -X POST "http://localhost:3000/signup" \ -H "Content-Type: application/json" \ -d '{"email": "test@mailinator.com", "password": "Correct-horse-9"}' ``` ```json { "error": "Disposable email addresses can't be used to sign up." } ``` # Errors > Every error the check endpoint can return, what causes it, and what your code should do about it. ## Error format [Section titled “Error format”](#error-format) An error answers with a `4xx` or `5xx` status and a JSON body with one `error` object: ```json { "error": { "code": "rate_limited", "message": "Too many requests this second for this key. Retry in a second." } } ``` * `code` is stable. Branch on it in code. * `message` is written for the developer reading a log. It can change, and it is not meant for your users. ## Error codes [Section titled “Error codes”](#error-codes) | Status | Code | Cause | What to do | | ------ | ----------------------- | ------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------- | | `400` | `invalid_request` | Neither `ip` nor `email` was sent, a value is not a string or is longer than 320 characters, or the `POST` body is not a JSON object. | Fix the request. | | `400` | `invalid_ip` | `ip` is not a single IPv4 or IPv6 address. Ports, CIDR ranges and zone ids are refused. | Send a bare address, or leave `ip` out. | | `400` | `invalid_email` | `email` has no `@`, or no domain with a dot after it. | Validate the address before you call. | | `401` | `missing_api_key` | No key in `Authorization: Bearer` or `x-api-key`. | Send the key. See [Authentication](/docs/authentication/). | | `401` | `invalid_api_key` | The key does not exist or was revoked. | Check the key, or create a new one. | | `402` | `subscription_required` | The account has no active subscription. | Start or renew the subscription in the dashboard. | | `413` | `payload_too_large` | The request body is larger than 16 KB. | Send only `ip` and `email`. | | `429` | `rate_limited` | The key went over its per-second limit, or this address sent too many requests with a missing or invalid key. | Wait for the time in `Retry-After` and retry. See [Rate limits](/docs/reference/rate-limits/). | | `503` | `lists_unavailable` | Heimdal has just started and has not loaded its lists yet. | Retry shortly. Let the signup through in the meantime. | | `503` | `service_unavailable` | Something failed on Heimdal’s side, or it is restarting. | Retry shortly (after `Retry-After`, when sent). Let the signup through in the meantime. | ### Messages [Section titled “Messages”](#messages) These are the messages the API sends today. They read like this in your logs: | Code | Message | | ----------------------- | ----------------------------------------------------------------------------------- | | `invalid_request` | Send `ip`, `email`, or both, as strings of at most 320 characters. | | `invalid_ip` | `ip` must be one IPv4 or IPv6 address, without a port or zone. | | `invalid_email` | `email` must be an address with a domain, like `name@example.com`. | | `missing_api_key` | Send your API key in the Authorization header: Bearer hd\_… | | `invalid_api_key` | This API key is not valid. | | `subscription_required` | This account has no active subscription. Start or renew one in the dashboard. | | `rate_limited` | Too many requests this second for this key. Retry in a second. | | `rate_limited` | Too many requests with a missing or invalid API key from this address. Retry later. | | `payload_too_large` | Request body too large. | | `lists_unavailable` | The lists are still loading. Retry shortly. | | `service_unavailable` | The service is temporarily unavailable. Retry shortly. | ### Order of checks [Section titled “Order of checks”](#order-of-checks) A request is checked in this order, and the first failure is the answer: 1. API key (`401`, or `429` after too many bad keys from one address) 2. Subscription (`402`) 3. Rate limit for the key (`429`) 4. Input (`400`) 5. Lists loaded (`503`) So a request with a bad key and a bad body answers `401`, and a request refused with `400` has already counted toward the rate limit. ### Handling errors [Section titled “Handling errors”](#handling-errors) Do not make a signup depend on Heimdal being reachable. On a timeout, a network error, a `429` or any `5xx`, let the signup through and log what happened. A `401` or a `402` means your integration needs attention: let the signup through as well, and alert yourself. [Best practices](/docs/guides/best-practices/#fail-open) shows the pattern. ## Limits [Section titled “Limits”](#limits) Request rates per key and per address are on [Rate limits](/docs/reference/rate-limits/). | Limit | Value | | ----------------------------- | ------------------------------------ | | Monthly quota | None | | Length of `ip`, `email` | 320 characters | | Request body | 16 KB | | Key and subscription changes | Take effect within 60 seconds | | Access after a failed renewal | 3 days | | Custom lists | 20 lists, 50,000 entries per account | ### Subscription and grace period [Section titled “Subscription and grace period”](#subscription-and-grace-period) The API answers while your subscription is active, the trial included. If a renewal payment fails, access continues for 3 days. After that every call answers `402 subscription_required` until the subscription is active again. A change to your subscription or your keys can take up to 60 seconds to reach the API. That covers a new subscription, a cancellation that takes effect, and a revoked key. ## Degraded answers [Section titled “Degraded answers”](#degraded-answers) Every check also reads your custom lists. If that read fails, Heimdal still answers `200` with every other signal and adds this header: ```http Heimdal-Degraded: custom_lists ``` `custom.matched` is then empty and `custom_list` is missing from `reasons`, whether or not an entry would have matched. If your custom lists are essential to a decision, check for the header and treat the answer as incomplete. ## Caching [Section titled “Caching”](#caching) Every response carries `Cache-Control: no-store`. The Tor and proxy lists change every hour, and your custom lists change whenever you edit them, so do not keep an answer to reuse later. Check once, at the moment of the signup. # Rate limits > There is no monthly quota. Per-second limits per API key, and per-address limits on bad keys, protect the service. | Limit | Value | | ----------------------------------- | ----------------- | | Requests per API key | 100 per second | | Missing or invalid keys per address | 30 per 60 seconds | | Monthly quota | None | Every `/v1/check` answer carries the IETF rate-limit headers: ```http RateLimit-Policy: "shield";q=100;w=1 RateLimit: "shield";r=99;t=1 ``` `q` is the limit, `w` the window in seconds, `r` the requests left and `t` the seconds until the window resets. Over the limit the API answers `429 rate_limited` with `Retry-After` in seconds. Too many requests with a missing or invalid key from one address are answered the same way, under the policy `"bad-key";q=30;w=60`, until the window resets. Limits are counted per key, so two services with a key each do not share an allowance. On a `429`, let the sign-up through and retry later; see [Errors](/docs/reference/errors/). # Signals explained > What each signal means, how it is decided, and what it does not tell you. A check returns up to six signals. Each one is a fact about the email’s domain or the address’s network. None of them is a verdict about the person. | Reason | Field | Based on | Refreshed | | ------------------ | ------------------ | ----------------------------- | ----------- | | `disposable_email` | `email.disposable` | The email’s domain | Daily | | `tor` | `ip.tor` | The exact address | Hourly | | `proxy` | `ip.proxy` | The exact address | Hourly | | `vpn` | `ip.vpn` | The network the address is in | Daily | | `bad_isp` | `ip.bad_isp` | The network the address is in | Daily | | `custom_list` | `custom.matched` | Your own lists | Immediately | The lists behind them are named in [Data sources and attribution](/docs/data-sources/). ## `block` and `reasons` [Section titled “block and reasons”](#block-and-reasons) `reasons` lists the signals that fired, always in the order of the table above. `block` is `true` exactly when `reasons` is not empty. That makes `block` the strictest possible policy: any one signal is enough. It suits products where a fake account is expensive and a refused visitor is cheap. For most signups it is too strict on its own, because a VPN alone sets it. Read the individual signals instead; [Best practices](/docs/guides/best-practices/#choose-a-policy) suggests a starting point. ## Disposable email [Section titled “Disposable email”](#disposable-email) `email.disposable` is `true` when the email’s domain is on a list of disposable mail providers: services that hand out throwaway inboxes with no signup. * Only the domain counts. `anything@mailinator.com` is disposable whatever comes before the `@`. * Subdomains match their parent. `test@inbox.mailinator.com` is disposable because `mailinator.com` is listed. * Matching stops at the registrable domain. A stray entry for a public suffix such as `co.uk` never flags the organisations registered under it. * Comparison is case-insensitive, and internationalised domains are compared in their ASCII form. * A domain on no list is also disposable when its mail servers belong to a known disposable provider. Some providers register new domains every day, faster than any list; they all deliver to the same servers. Heimdal looks up the domain’s MX records, caches the answer for six hours, and treats a slow or failed lookup as “not disposable”. Heimdal does not check that the mailbox exists or that the address belongs to the visitor. A `false` here means “not a known disposable provider”, not “a real person’s inbox”. Keep your email verification step. ## Tor [Section titled “Tor”](#tor) `ip.tor` is `true` when the address is on the Tor Project’s list of current exit nodes. The match is on the exact address, and the list is refreshed every hour. The Tor Project’s list currently holds IPv4 addresses only, so in practice this signal fires for IPv4 visitors. ## Open proxy [Section titled “Open proxy”](#open-proxy) `ip.proxy` is `true` when the address is on a list of open public proxies: HTTP and SOCKS proxies that anyone can route traffic through. The match is on the exact address, and the list is refreshed every hour. Open proxies come and go quickly. An address can be listed a little after it stopped being a proxy, or not yet be listed when it starts. ## VPN [Section titled “VPN”](#vpn) `ip.vpn` is `true` when the address belongs to a network operated by a VPN provider. This is decided per network, not per address. Heimdal finds the network (the autonomous system) that announces the address, then checks whether that network is on a VPN list. Every address in a listed network gets `vpn: true`. A VPN is not evidence of fraud. Developers, remote workers, travellers and people who care about privacy all use them. See [Best practices](/docs/guides/best-practices/#choose-a-policy) before you block on this signal alone. ## Bad ISP [Section titled “Bad ISP”](#bad-isp) `ip.bad_isp` is `true` when the address belongs to a network that ordinary visitors rarely connect from: hosting companies, datacenters, other networks known for abuse, and VPN providers. Like `vpn`, it is decided per network. It answers the question “is this a server rather than a home or mobile connection?”. Legitimate traffic comes from these networks too, for example company proxies and cloud desktops. Treat `bad_isp` as a reason to look closer rather than a reason to refuse. ## Network details [Section titled “Network details”](#network-details) `ip.asn` and `ip.isp` are not signals. They tell you which network announces the address, so you can log it or apply rules of your own. * `asn` is the autonomous system number, for example `60729`. * `isp` is the network’s registered name. * Both are `null` for an address that no network announces, such as a private address (`10.0.0.1`, `127.0.0.1`) or unallocated space. `vpn` and `bad_isp` are then `false`. * `isp` can be `null` on its own when the network has no name on record. ## Custom lists [Section titled “Custom lists”](#custom-lists) `custom.matched` holds the entries on your own lists that the email or the address hit. Any match adds `custom_list` to `reasons` and sets `block`. See [Custom lists](/docs/custom-lists/). ## IPv4, IPv6 and mapped addresses [Section titled “IPv4, IPv6 and mapped addresses”](#ipv4-ipv6-and-mapped-addresses) Both address families are supported. An IPv4-mapped IPv6 address such as `::ffff:203.0.113.7` is looked up as `203.0.113.7`, which is what a dual-stack server reports for IPv4 visitors. `ip.address` in the response echoes what you sent. ## When a signal is wrong [Section titled “When a signal is wrong”](#when-a-signal-is-wrong) Lists lag behind reality, in both directions. If a domain or a network is flagged wrongly: * Handle it in your own code first. Heimdal has no allowlist, so skip the check, or ignore the signal, for the customers you know. * Report it to the maintainers of the list that carries it. The fix reaches Heimdal at the next refresh.