# Block fake signups in one call

> Score each sign-up from its email, phone, IP, name and User-Agent with one API call, then allow it, ask for a second factor or refuse it, with the reasons logged.

In this guide you add one call to your sign-up route that scores the new account from everything the form and the request already give you, then you act on the answer: create the account, ask for a second factor, or refuse it with a message that does not accuse anyone.

Fake accounts rarely show one obvious sign. A throwaway inbox, a Tor exit node, a script's User-Agent, a domain registered last week and a name typed as `asdf` each mean little alone and a lot together. `POST /signup/check` runs the email, email domain age, phone, FTC report and IP checks in parallel, reads the name and the User-Agent, and adds up the points of every warning sign.

## What you need

- An API key in the `QELKA_API_KEY` environment variable. A test key is enough to follow the guide and spends nothing.
- A sign-up route on your server. The complete route is shown in Node.js with Express and in Python with Flask.
- With a live key, each call costs 3 credits, whatever fields you send, and nothing when one of the checks does not answer.

## 1. Send what you already have

Send the email address and the client IP address at least. Add the phone number if your form asks for it, the name, the `User-Agent` header of the request, and the country the user picked, if any. Every field is optional, but at least one is required.

```bash title="cURL"
curl https://api.qelka.com/v1/signup/check \
  --max-time 30 \
  -H "Authorization: Bearer $QELKA_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"email": "disposable@example.com", "ip": "198.51.100.200", "name": "Jane Doe", "user_agent": "curl/8.4.0"}'
```
```javascript title="Node.js"
const response = await fetch('https://api.qelka.com/v1/signup/check', {
  method: 'POST',
  headers: {
    Authorization: `Bearer ${process.env.QELKA_API_KEY}`,
    'Content-Type': 'application/json',
  },
  body: JSON.stringify({
    email: 'disposable@example.com',
    ip: '198.51.100.200',
    name: 'Jane Doe',
    user_agent: 'curl/8.4.0',
  }),
  signal: AbortSignal.timeout(30_000),
})
const result = await response.json()
console.log(result.decision, result.score)
```
```python title="Python"
import os

import requests

api_key = os.environ["QELKA_API_KEY"]
response = requests.post(
    "https://api.qelka.com/v1/signup/check",
    headers={"Authorization": f"Bearer {api_key}"},
    json={
        "email": "disposable@example.com",
        "ip": "198.51.100.200",
        "name": "Jane Doe",
        "user_agent": "curl/8.4.0",
    },
    timeout=30,
)
result = response.json()
print(result["decision"], result["score"])
```
```php title="PHP"
<?php
$ch = curl_init('https://api.qelka.com/v1/signup/check');
curl_setopt_array($ch, [
    CURLOPT_POST => true,
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_HTTPHEADER => [
        'Authorization: Bearer ' . getenv('QELKA_API_KEY'),
        'Content-Type: application/json',
    ],
    CURLOPT_POSTFIELDS => json_encode([
        'email' => 'disposable@example.com',
        'ip' => '198.51.100.200',
        'name' => 'Jane Doe',
        'user_agent' => 'curl/8.4.0',
    ]),
    CURLOPT_TIMEOUT => 30,
]);
$result = json_decode(curl_exec($ch), true);
echo $result['decision'], ' ', $result['score'], PHP_EOL;
```
```go title="Go"
package main

import (
	"bytes"
	"encoding/json"
	"fmt"
	"net/http"
	"os"
	"time"
)

func main() {
	payload, _ := json.Marshal(map[string]string{
		"email":      "disposable@example.com",
		"ip":         "198.51.100.200",
		"name":       "Jane Doe",
		"user_agent": "curl/8.4.0",
	})
	request, _ := http.NewRequest(http.MethodPost, "https://api.qelka.com/v1/signup/check", bytes.NewReader(payload))
	request.Header.Set("Authorization", "Bearer "+os.Getenv("QELKA_API_KEY"))
	request.Header.Set("Content-Type", "application/json")

	client := &http.Client{Timeout: 30 * time.Second}
	response, err := client.Do(request)
	if err != nil {
		panic(err)
	}
	defer response.Body.Close()

	var result map[string]any
	json.NewDecoder(response.Body).Decode(&result)
	fmt.Println(result["decision"], result["score"])
}
```
```ruby title="Ruby"
require 'json'
require 'net/http'

uri = URI('https://api.qelka.com/v1/signup/check')
request = Net::HTTP::Post.new(uri)
request['Authorization'] = "Bearer #{ENV.fetch('QELKA_API_KEY')}"
request['Content-Type'] = 'application/json'
request.body = {
  email: 'disposable@example.com',
  ip: '198.51.100.200',
  name: 'Jane Doe',
  user_agent: 'curl/8.4.0'
}.to_json

response = Net::HTTP.start(uri.host, uri.port, use_ssl: true, read_timeout: 30) do |http|
  http.request(request)
end
result = JSON.parse(response.body)
puts "#{result['decision']} #{result['score']}"
```

With a test key, `disposable@example.com` is the simulated disposable address and `198.51.100.200` a simulated Tor exit node, so the answer is `block` with three reasons: `email_disposable`, `ip_tor` and `user_agent_automation`. Each reason carries the input it comes from, its points and a message:

```json title="Response"
{
  "object": "signup_check",
  "decision": "block",
  "score": 100,
  "reasons": [
    { "code": "email_disposable", "field": "email", "severity": "high", "points": 70, "message": "example.com is a disposable email service." },
    { "code": "ip_tor", "field": "ip", "severity": "high", "points": 70, "message": "198.51.100.200 is a Tor exit node." },
    { "code": "user_agent_automation", "field": "user_agent", "severity": "high", "points": 40, "message": "The User-Agent names an automation tool or HTTP library (curl)." }
  ],
  "checks": { "email": "ok", "email_domain_age": "not_applicable", "phone": "not_provided", "phone_reports": "not_provided", "ip": "ok", "name": "ok", "user_agent": "ok" }
}
```

The full response also holds the result of every check (`email`, `email_domain_age`, `phone`, `phone_reports`, `ip`), `credits_used` and `cached`. The [reference](https://qelka.com/docs/api-reference/signup-check) describes every field.

## 2. Choose what each decision does

The score is the sum of the points of every reason, capped at 100. From 70 points the decision is `block`, from 30 it is `review`, below that `allow`. The [signup risk score](https://qelka.com/docs/signup-risk-score) page lists the weight of every reason.

| Decision | Suggested action | Why |
|---|---|---|
| `allow` | Create the account. | No sign, or only weak ones. |
| `review` | Create the account but hold back what is valuable, such as trial credits or a coupon, until the email address or the phone number is confirmed. Or queue it for a manual look. | A VPN, a hosting IP or a young domain is common among real people too. A second factor settles it without turning them away. |
| `block` | Refuse, and log the reasons. | Several strong signs together, such as a throwaway inbox from a Tor exit node. |

If your product tolerates more risk, or less, compare `score` with your own thresholds instead of reading `decision`. The reasons explain every point, so you can also ignore one: a developer tool may not care about `user_agent_short`, for example.

## 3. Add the check to your sign-up route

`checkSignup` returns the decision. It fails open: a timeout, a network error or an error status returns `allow` with no reasons, so a problem on the API side never stops a sign-up. Behind a proxy or a load balancer, read the client IP address from the header your platform sets, as `clientIp` does.

```javascript title="Node.js"
import express from 'express'
import { randomUUID } from 'node:crypto'

const passThrough = { decision: 'allow', score: 0, reasons: [] }

function clientIp(req) {
  return String(req.headers['cf-connecting-ip'] ?? req.headers['x-forwarded-for'] ?? req.socket.remoteAddress ?? '').split(',')[0].trim()
}

export async function checkSignup(fields) {
  const body = Object.fromEntries(Object.entries(fields).filter(([, value]) => typeof value === 'string' && value.trim() !== ''))
  if (Object.keys(body).length === 0) return passThrough
  try {
    const response = await fetch('https://api.qelka.com/v1/signup/check', {
      method: 'POST',
      headers: {
        Authorization: `Bearer ${process.env.QELKA_API_KEY}`,
        'Content-Type': 'application/json',
      },
      body: JSON.stringify(body),
      signal: AbortSignal.timeout(8000),
    })
    if (!response.ok) return passThrough
    return await response.json()
  } catch {
    return passThrough
  }
}

const app = express()

app.post('/signup', express.json(), async (req, res) => {
  const email = String(req.body.email ?? '').trim()
  const risk = await checkSignup({
    email,
    phone: req.body.phone,
    name: req.body.name,
    ip: clientIp(req),
    user_agent: req.headers['user-agent'],
  })
  if (risk.decision === 'block') {
    console.warn('signup refused', email, risk.reasons.map((reason) => reason.code))
    return res.status(422).json({ message: 'We could not create your account. Contact support if you think this is a mistake.' })
  }
  const account = { id: randomUUID(), email, needsVerification: risk.decision === 'review' }
  res.status(201).json(account)
})

app.listen(3000)
```
```python title="Python"
import os
import uuid

import requests
from flask import Flask, request

app = Flask(__name__)
API_KEY = os.environ["QELKA_API_KEY"]
PASS_THROUGH = {"decision": "allow", "score": 0, "reasons": []}

def client_ip():
    forwarded = request.headers.get("CF-Connecting-IP") or request.headers.get("X-Forwarded-For") or request.remote_addr or ""
    return forwarded.split(",")[0].strip()

def check_signup(fields):
    body = {key: value.strip() for key, value in fields.items() if isinstance(value, str) and value.strip()}
    if not body:
        return PASS_THROUGH
    try:
        response = requests.post(
            "https://api.qelka.com/v1/signup/check",
            headers={"Authorization": f"Bearer {API_KEY}"},
            json=body,
            timeout=8,
        )
    except requests.RequestException:
        return PASS_THROUGH
    if not response.ok:
        return PASS_THROUGH
    return response.json()

@app.post("/signup")
def signup():
    form = request.get_json(silent=True) or {}
    email = str(form.get("email") or "").strip()
    risk = check_signup({
        "email": email,
        "phone": form.get("phone"),
        "name": form.get("name"),
        "ip": client_ip(),
        "user_agent": request.headers.get("User-Agent"),
    })
    if risk["decision"] == "block":
        app.logger.warning("signup refused %s %s", email, [reason["code"] for reason in risk["reasons"]])
        return {"message": "We could not create your account. Contact support if you think this is a mistake."}, 422
    return {"id": str(uuid.uuid4()), "email": email, "needsVerification": risk["decision"] == "review"}, 201

if __name__ == "__main__":
    app.run(port=3000)
```

The `201` response stands for your own account creation code. `needsVerification` is where you hook your confirmation email or SMS code for `review`.

## 4. Word the refusal

The person in front of the form may be real: a privacy-minded user on Tor, a developer testing with `curl`. Do not list the reasons, do not accuse, and give a way out:

- Good: "We could not create your account. Contact support if you think this is a mistake."
- Not good: "Fraud detected: disposable email and Tor."

Keep the reasons in your logs, next to the account or the refused attempt, so support can answer and you can tune your thresholds.

## Test it

With a test key, every branch of your route has a fixed input:

| Send | Decision |
|---|---|
| `disposable@example.com` from `198.51.100.200` | `block`: disposable inbox and Tor exit node |
| `jane@example.com` from `203.0.113.7` | `review`: hosting provider IP |
| `jane@example.com` from `192.0.2.10` | `allow` |

```bash title="Terminal"
curl -i http://localhost:3000/signup \
  -H "Content-Type: application/json" \
  -H "X-Forwarded-For: 198.51.100.200" \
  -d '{"email": "disposable@example.com", "name": "Jane Doe"}'
```

Your route should answer `422` with the message. Send `jane@example.com` with `X-Forwarded-For: 192.0.2.10` and it answers `201`. With a live key, try a few real combinations in the free [signup risk checker](https://qelka.com/tools/signup-risk-checker) first.

## Next steps

- [Signup fraud check reference](https://qelka.com/docs/api-reference/signup-check): every field, check status and reason.
- [Signup risk score](https://qelka.com/docs/signup-risk-score): the weight of every reason and the decision thresholds.
- [Block disposable email signups](https://qelka.com/docs/guides/block-disposable-signups): when the email alone is enough.
- [Link safety](https://qelka.com/docs/api-reference/url): check the links new accounts post.
