> ## 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.

# Login & credential stuffing

> Block account takeover at login. Use Foil to detect credential stuffing, step up inconclusive sessions, and rate-limit by visitor fingerprint, not just IP.

> [!NOTE]
>
> Login is a hot path. A real user will hit it dozens of times a month, so your error budget for false positives is small. The right pattern is a narrow action-time check at password submit - not a page-load probe - paired with a step-up challenge on `inconclusive` rather than a block.

## The threat

Credential-stuffing tools replay dumps of leaked `email:password` pairs against login endpoints at high volume. The goal is account takeover: any hit becomes a compromised account. Unlike signup, the attacker isn't trying to create *new* identity - they're trying to prove that an existing identity is theirs. That changes the policy calculus.

The pattern to detect is automated typing and submission: a headless browser driving a form fill, or an HTTP-level script bypassing the UI entirely. Foil's `automation` attribution (Playwright/Puppeteer/Selenium) and `ai-agent` attribution (LLM-driven login) both land here.

Two properties of the login surface shape the integration:

* **Users arrive hot.** They click a link in an email, they open a bookmark, they come back from a timeout, and they can submit the form within a second of the page loading. `getSession()` waits for fingerprinting to finish, so the handoff for these users can take a moment longer, but you never need to disable the form.
* **False positives are expensive.** Locking a human out of their own account is a worse user experience than letting a bot try three times against a non-matching password. The verdict is one input among several - Foil goes on one side of a scale that already has rate limiting and MFA on it.

## The flow

**1. Start Foil on page load**

Collection begins. You don't need to disable the form while Foil collects, because `getSession()` waits for fingerprinting to finish. Users arriving cold can submit right away.

**2. Call getSession() at password submit**

Not on page load. You want the freshest possible observation set, and you want collection to include the keystroke and mouse signals from the user typing their password.

**3. Verify and fold into your auth decision**

A `bot` verdict returns the same generic error as a wrong password. An `inconclusive` verdict with an otherwise-valid password triggers a step-up challenge.

**4. Rate-limit by visitor fingerprint, not just IP**

The verified token carries a `visitor_fingerprint.id`. Use it to apply per-device limits that survive residential-proxy IP rotation.

## Client integration

Call `getSession()` lazily at password submit. `getSession()` waits for fingerprinting to finish before it returns a handoff, so you don't need to call `waitForFingerprint()` first.

```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",
      }),
  );

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

  document.querySelector("#login-form").addEventListener("submit", async (e) => {
    e.preventDefault();
    const foil = await getFoilHandoff();

    await fetch("/api/login", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({
        email: e.target.email.value,
        password: e.target.password.value,
        foil,
      }),
    });
  });
</script>
```

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

## Server verification

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

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

  // Check the password regardless - don't skip the bcrypt compare.
  // A bot should not be able to use timing to distinguish states.
  const passwordMatches = await verifyPassword(req.body.email, req.body.password);

  if (!foilResult.ok || foilResult.data.decision.verdict === "bot") {
    // Generic error - same response shape as wrong password.
    return res.status(401).json({ error: "Invalid credentials" });
  }

  if (!passwordMatches) {
    return res.status(401).json({ error: "Invalid credentials" });
  }

  const verdict = foilResult.data.decision.verdict;
  const visitorId = foilResult.data.visitor_fingerprint?.id;

  if (verdict === "inconclusive") {
    // Password is correct, but we're not confident. Require a second factor.
    const challengeToken = await issueStepUpChallenge(req.body.email, visitorId);
    return res.json({ status: "step_up", challengeToken });
  }

  const session = await issueLoginSession(req.body.email);
  res.json({ status: "ok", session });
});
```

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

@app.post("/api/login")
def login(request):
    foil_result = safe_verify_foil_token(
        (request.json.get("foil") or {}).get("sealedToken", ""),
        os.environ["FOIL_SECRET_KEY"],
    )
    password_matches = verify_password(
        request.json["email"], request.json["password"]
    )

    if not foil_result.ok or foil_result.data.decision.verdict == "bot":
        return {"error": "Invalid credentials"}, 401

    if not password_matches:
        return {"error": "Invalid credentials"}, 401

    verdict = foil_result.data.decision.verdict
    visitor = foil_result.data.visitor_fingerprint
    visitor_id = visitor.id if visitor else None

    if verdict == "inconclusive":
        challenge = issue_step_up_challenge(request.json["email"], visitor_id)
        return {"status": "step_up", "challengeToken": challenge}

    return {"status": "ok", "session": issue_login_session(request.json["email"])}
```

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

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

    tr := foil.SafeVerifyFoilToken(
        body.Foil.SealedToken,
        os.Getenv("FOIL_SECRET_KEY"),
    )
    passwordOK := verifyPassword(body.Email, body.Password)

    if !tr.OK || tr.Data.Decision.Verdict == "bot" || !passwordOK {
        http.Error(w, "Invalid credentials", 401)
        return
    }

    if tr.Data.Decision.Verdict == "inconclusive" {
        visitorID := ""
        if v := tr.Data.VisitorFingerprint; v != nil {
            visitorID = v.ID
        }
        challenge := issueStepUpChallenge(body.Email, visitorID)
        json.NewEncoder(w).Encode(map[string]string{
            "status":         "step_up",
            "challengeToken": challenge,
        })
        return
    }

    json.NewEncoder(w).Encode(map[string]any{
        "status":  "ok",
        "session": issueLoginSession(body.Email),
    })
}
```

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

post "/api/login" do
  body = JSON.parse(request.body.read)
  tr = Foil::Server::SealedToken.safe_verify_foil_token(
    body.dig("foil", "sealedToken"),
  )
  password_ok = verify_password(body["email"], body["password"])

  decision = tr[:ok] ? tr[:data][:decision] : nil
  visitor  = tr[:ok] ? tr[:data][:visitor_fingerprint] : nil

  if !tr[:ok] || decision[:verdict] == "bot" || !password_ok
    halt 401, { error: "Invalid credentials" }.to_json
  end

  if decision[:verdict] == "inconclusive"
    challenge = issue_step_up_challenge(body["email"], visitor && visitor[:id])
    { status: "step_up", challengeToken: challenge }.to_json
  else
    { status: "ok", session: issue_login_session(body["email"]) }.to_json
  end
end
```

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

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

if (!$tr->ok || $tr->data->decision["verdict"] === "bot" || !$passwordOk) {
    http_response_code(401);
    echo json_encode(["error" => "Invalid credentials"]);
    exit;
}

if ($tr->data->decision["verdict"] === "inconclusive") {
    $challenge = issueStepUpChallenge($body["email"], $tr->data->visitor_fingerprint["id"] ?? null);
    echo json_encode(["status" => "step_up", "challengeToken" => $challenge]);
    exit;
}

echo json_encode(["status" => "ok", "session" => issueLoginSession($body["email"])]);
```

```bash cURL theme={"dark"}
# Session readback - useful for async audit jobs, not the login hot path.
curl https://api.usefoil.com/v1/sessions/sid_... \
  -H "Authorization: Bearer sk_live_..."
```

## Decisioning policy

| Verdict | Recommended action on login |
| - | - |
| `human` + password matches | Issue a session. |
| `human` + password mismatch | Return generic `Invalid credentials`. |
| `inconclusive` + password matches | Require a second factor (TOTP, email OTP, WebAuthn). |
| `inconclusive` + password mismatch | Return generic `Invalid credentials`. |
| `bot` | Return generic `Invalid credentials`. Always. |

Four things to get right:

* **Always check the password.** Skipping the bcrypt compare on a `bot` verdict creates a timing oracle. Run the comparison, throw the result away if Foil blocks.
* **Return identical responses for bot-detected and password-mismatch.** Status code, body shape, timing. Any difference is signal for an attacker automating against your endpoint.
* **Prefer step-up over block on `inconclusive`.** If the password is correct and the verdict is ambiguous, a legitimate user can pass a TOTP prompt. A bot running on a dump of leaked credentials usually can't.
* **Fail closed and reject stale tokens.** A request with a missing, invalid, or expired token gets the same generic error as a `bot` verdict. Don't accept the login without a token, because an attacker could skip Foil by omitting it. The server SDKs don't check a token's age, so reject a token whose `decision.evaluated_at` is more than a few minutes old. 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.

## Rate-limiting by visitor fingerprint

The verified token exposes `visitor_fingerprint.id` - a per-device identifier that survives cookie clears, incognito mode, and residential-proxy IP rotation. It's the right key for login attempt counters.

```javascript Node.js theme={"dark"}
const redis = require("redis");
const { safeVerifyFoilToken } = require("@abxy/foil-server");
const client = redis.createClient();
const connected = client.connect(); // node-redis v4 requires an explicit connect.

async function checkLoginRateLimit(foilToken) {
  await connected;
  const result = safeVerifyFoilToken(foilToken, process.env.FOIL_SECRET_KEY);
  if (!result.ok) return { allowed: false, reason: "no_token" };

  const visitorId = result.data.visitor_fingerprint?.id;
  if (!visitorId) return { allowed: true };

  const key = `login_attempts:${visitorId}`;
  const attempts = await client.incr(key);
  if (attempts === 1) await client.expire(key, 3600); // 1h window

  if (attempts > 10) {
    return { allowed: false, reason: "rate_limited", visitorId };
  }
  return { allowed: true, visitorId };
}
```

This is complementary to IP-based rate limiting, not a replacement. Run both. IP counters catch volumetric attacks; fingerprint counters catch distributed attacks routed through rotating residential proxies where each request comes from a different IP but the underlying device is the same.

> [!NOTE]
>
> The server SDKs type `visitor_fingerprint` as nullable, so the example checks for a missing ID. Foil resolves the visitor fingerprint before it issues a token, so a token from the browser SDK carries one. If your code does see a missing ID, skip the fingerprint counter and rely on the IP counter instead of blocking the request.

## What's next

> [card] [Signup protection](https://usefoil.com/docs/use-cases/signup.md)
>
> Block automated account creation.

> [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 and monitoring.

> [card] [Verdicts & scoring](https://usefoil.com/docs/verdicts-and-scoring.md)
>
> Understand what `inconclusive` actually means.


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