> ## Documentation Index
> Fetch the complete documentation index at: https://usefoil.com/docs/llms.txt
> Use this file to discover all available pages before exploring further.

# Signup & account creation

> Stop fake signups and automated account creation. Verify Foil sealed tokens at registration and block bots and AI agents before you create the account.

> [!NOTE]
>
> Signup is the highest-leverage place to run Foil. Every downstream abuse pattern - spam, scraping, ratings manipulation, trial farming - starts with a bot-created account. A hard block here is cheaper than cleaning up later.

## The threat

Automated signup is the most common and most costly bot surface. Attackers create accounts in bulk to seed spam networks, farm free-trial credits, inflate referral payouts, reserve usernames, drain rate limits, or build a corpus of "aged" accounts for later sale. Because account creation is only occasional for legitimate users, you can afford a stricter policy here than on, say, a login page that a human might hit dozens of times a week.

Foil fits the shape of this problem well: you want a strong verdict *before* the row is written. The browser client streams observations the whole time a user is filling out the form, and `getSession()` flushes everything into a sealed handoff right at submit. Your backend verifies the token, checks the verdict, and decides whether to proceed - all before you touch the database.

Two detection categories matter most on this surface:

* **`automation`** - Playwright, Puppeteer, Selenium, Patchright, and related stealth tooling driving a headless browser.
* **`ai-agent`** - LLM-powered agents that operate a browser to complete signup end to end.

Foil detects both. On a signup page, it is reasonable to hard-block either.

## The flow

**1. Start Foil on page load**

The browser client begins collection immediately so a full fingerprint is available by the time the user submits.

**2. Request a sealed handoff at submit**

`getSession()` waits for fingerprinting to finish, flushes the latest observations, and returns `{ sessionId, sealedToken }`.

**3. Verify on the backend**

Use `safeVerifyFoilToken()` with your secret key to verify the token locally, with no extra network call, and check that the token is recent.

**4. Apply policy**

Hard-block on `bot`, step up on `inconclusive`, proceed on `human`.

## Client integration

Start Foil when the page loads, and call `getSession()` when the user submits the form. `getSession()` waits for fingerprinting to finish before it returns a handoff, so a user who submits quickly doesn't need a disabled button or a call to `waitForFingerprint()`. The example disables the submit button while the request is in flight so that a double click doesn't create two accounts, and it enables the button again when the request finishes.

```html theme={"dark"}
<script type="module">
  const foilPromise = import("https://cdn.usefoil.com/t.js").then(
    (Foil) =>
      Foil.start({
        publishableKey: "pk_live_your_publishable_key",
      }),
  );

  const submitButton = document.querySelector("#signup-submit");

  async function getFoilHandoff() {
    try {
      const foil = await foilPromise;
      return await foil.getSession();
    } catch (err) {
      // Send the form without a handoff. The server decides how to treat it.
      return null;
    }
  }

  async function submitSignup(formData) {
    submitButton.disabled = true;
    try {
      const foil = await getFoilHandoff();

      return await fetch("/api/signup", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ ...formData, foil }),
      });
    } finally {
      submitButton.disabled = false;
    }
  }
</script>
```

If the script fails to load or `getSession()` fails, the page sends the form without a handoff, so a blocked script doesn't leave the form unresponsive. The next section describes how the server treats a request without a valid token.

## Server verification

```javascript Node.js theme={"dark"}
const { safeVerifyFoilToken } = require("@abxy/foil-server");

app.post("/api/signup", async (req, res) => {
  const result = safeVerifyFoilToken(
    req.body.foil?.sealedToken,
    process.env.FOIL_SECRET_KEY,
  );

  if (!result.ok) {
    // Fail closed on signup - no token, no account.
    return res.status(403).json({ error: "Verification failed" });
  }

  const { decision } = result.data;

  if (decision.verdict === "bot") {
    return res.status(403).json({ error: "Signup blocked" });
  }

  if (decision.verdict === "inconclusive") {
    // Hold the signup and require email verification before activating
    await createAccount({ ...req.body, status: "pending_verification" });
    await sendVerificationEmail(req.body.email);
    return res.json({ status: "verify_email" });
  }

  await createAccount(req.body);
  res.json({ status: "created" });
});
```

```python Python theme={"dark"}
from foil_server import safe_verify_foil_token
import os

@app.post("/api/signup")
def signup(request):
    result = safe_verify_foil_token(
        (request.json.get("foil") or {}).get("sealedToken", ""),
        os.environ["FOIL_SECRET_KEY"],
    )

    if not result.ok:
        return {"error": "Verification failed"}, 403

    verdict = result.data.decision.verdict

    if verdict == "bot":
        return {"error": "Signup blocked"}, 403

    if verdict == "inconclusive":
        create_account(request.json, status="pending_verification")
        send_verification_email(request.json["email"])
        return {"status": "verify_email"}

    create_account(request.json)
    return {"status": "created"}
```

```go Go theme={"dark"}
import foil "github.com/abxy-labs/foil-server-go"

func signupHandler(w http.ResponseWriter, r *http.Request) {
    var body struct {
        Email    string `json:"email"`
        Foil struct {
            SealedToken string `json:"sealedToken"`
        } `json:"foil"`
    }
    json.NewDecoder(r.Body).Decode(&body)

    result := foil.SafeVerifyFoilToken(
        body.Foil.SealedToken,
        os.Getenv("FOIL_SECRET_KEY"),
    )
    if !result.OK {
        http.Error(w, "Verification failed", 403)
        return
    }

    switch result.Data.Decision.Verdict {
    case "bot":
        http.Error(w, "Signup blocked", 403)
        return
    case "inconclusive":
        createPendingAccount(body)
        sendVerificationEmail(body.Email)
        json.NewEncoder(w).Encode(map[string]string{"status": "verify_email"})
        return
    }

    createAccount(body)
    json.NewEncoder(w).Encode(map[string]string{"status": "created"})
}
```

```ruby Ruby theme={"dark"}
require "foil/server"

post "/api/signup" do
  body = JSON.parse(request.body.read)
  result = Foil::Server::SealedToken.safe_verify_foil_token(
    body.dig("foil", "sealedToken"),
  )
  halt 403, { error: "Verification failed" }.to_json unless result[:ok]

  case result[:data][:decision][:verdict]
  when "bot"
    halt 403, { error: "Signup blocked" }.to_json
  when "inconclusive"
    create_pending_account(body)
    send_verification_email(body["email"])
    { status: "verify_email" }.to_json
  else
    create_account(body)
    { status: "created" }.to_json
  end
end
```

```php PHP theme={"dark"}
use Foil\Server\SealedToken;

$body = json_decode(file_get_contents("php://input"), true);
$result = SealedToken::safeVerify(
    $body["foil"]["sealedToken"] ?? "",
    getenv("FOIL_SECRET_KEY"),
);

if (!$result->ok) {
    http_response_code(403);
    echo json_encode(["error" => "Verification failed"]);
    exit;
}

$verdict = $result->data->decision["verdict"];

if ($verdict === "bot") {
    http_response_code(403);
    echo json_encode(["error" => "Signup blocked"]);
    exit;
}

if ($verdict === "inconclusive") {
    createPendingAccount($body);
    sendVerificationEmail($body["email"]);
    echo json_encode(["status" => "verify_email"]);
    exit;
}

createAccount($body);
echo json_encode(["status" => "created"]);
```

```bash cURL theme={"dark"}
# Fallback path: fetch the stored session instead of verifying locally
curl https://api.usefoil.com/v1/sessions/sid_... \
  -H "Authorization: Bearer sk_live_..."
```

## Decisioning policy

| Verdict | Recommended action on signup |
| - | - |
| `human` | Create the account. |
| `inconclusive` | Create the account in a `pending_verification` state and require email (or phone) confirmation before unlocking it. |
| `bot` | Return a generic error. Do not create the account. |

Three policy choices worth making deliberately:

* **Fail closed when verification fails.** Return an error when the token is missing or invalid. Login fails closed in the same way (see [Login & credential stuffing](https://usefoil.com/docs/use-cases/login.md)). A real user can refresh and retry, and an attacker can't bypass Foil by omitting the token or sending a malformed one.
* **Reject stale tokens.** The server SDKs verify a token's contents but don't check its age. Reject a token whose `decision.evaluated_at` is more than a few minutes old, so that an attacker can't replay a token captured from one session. See [Verify the token on your server](https://usefoil.com/docs/use-cases/checkout.md#verify-the-token-on-your-server) for the check in each language.
* **Do not leak detection to the client.** Return the same message for `bot` and a generic server error. The browser client never receives verdicts directly - keeping them invisible at the response layer too means attackers get no signal to iterate against.

If you run the report-only mode from [Going to production](https://usefoil.com/docs/going-to-production.md) on signup, log `decision.verdict` and the actor label to see what you would block before you turn enforcement on. The actor label is the entry in `attribution.bot.labels` whose `kind` is `actor`, and its value is `automation`, `ai-agent`, `crawler`, or `unknown`. Some sessions have no actor label, so treat a missing label as `unknown`.

```javascript Node.js theme={"dark"}
const labels = result.data.attribution?.bot?.labels ?? [];
const actor = labels.find((label) => label.kind === "actor")?.value ?? "unknown";
```

The [API abuse & scraping](https://usefoil.com/docs/use-cases/api-abuse.md) guide shows this lookup in each language.

## What's next

> [card] [Server verification](https://usefoil.com/docs/server-verification.md)
>
> Reference for the underlying verification primitive.

> [card] [Going to production](https://usefoil.com/docs/going-to-production.md)
>
> Rollout plan - report-only, soft challenge, hard enforcement.

> [card] [Login protection](https://usefoil.com/docs/use-cases/login.md)
>
> Protect the login form against credential stuffing.

> [card] [KYC fraud](https://usefoil.com/docs/use-cases/kyc.md)
>
> Stack with your KYC vendor to catch identity farming.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.