---

title: Stop account takeover
description: Ask for a second step only when an account signs in from a browser it has not used before, and stop credential stuffing, with the knownprint event of each login.
---

## The threat

A stolen or reused password is still the right password, so the login form alone cannot tell the owner from the thief. Once in, the thief changes the email, the password or the payout details, spends the stored balance, or uses the account to defraud others.

What the thief rarely has is the owner's browser. knownprint gives your backend the `visitor_id` of the browser behind each login, so your code can recognise the browsers an account has used before and ask for a second step only when the account turns up on a new one. Customers on their usual browser skip it.

This guide covers where to identify, which fields to read, a decision table, a complete backend example for the login and for sensitive changes, how to use webhooks and search for review, and the mistakes that open the door again.

## Where to identify

| Moment                                                              | Why                                                         |
| ------------------------------------------------------------------- | ----------------------------------------------------------- |
| Login                                                               | The main decision: let in, ask for a second step, or refuse |
| Password reset request and completion                               | Takeovers often start with a reset                          |
| Changing the email address, phone number, password or second factor | The thief locks the owner out                               |
| Adding a payee, changing payout or refund details, withdrawing      | Where the money leaves                                      |
| Signing in to a new app or device you issue tokens to               | A new long-lived session                                    |

Identify in the login handler, when the user submits the form, and send the request id with the credentials. Do not pass the account to `identify()` in the page: your backend attaches it to the event only after the login has fully succeeded (below).

```js title="login.js"
// Once, when the page starts. Resolves null when the script is blocked or fails to load.
const agentReady = window.knownprint
  ? window.knownprint.load({ pk: 'pk_live_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx' }).catch(() => null)
  : Promise.resolve(null);

/** A fresh request id, or null when the agent is blocked, fails or takes longer than 3 seconds. */
function requestId(action) {
  const timeout = new Promise((resolve) => setTimeout(() => resolve(null), 3000));
  const attempt = agentReady
    .then((agent) => (agent === null ? null : agent.identify({ tags: { action } })))
    .then((result) => (result === null ? null : result.requestId))
    .catch(() => null);
  return Promise.race([attempt, timeout]);
}

document.querySelector('#login').addEventListener('submit', async (e) => {
  e.preventDefault();
  const form = e.currentTarget;
  // null when blocked or failed: log in without one; the backend treats it as unknown.
  const kp_request_id = await requestId('login');
  const res = await fetch('/login', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({
      username: form.username.value,
      password: form.password.value,
      kp_request_id,
    }),
  });
  handleLoginAnswer(await res.json());
});
```

[Add the browser agent](/install/browser) shows how to load the agent; [Protect a form](/install/forms) covers a plain HTML form.

## Which fields to read

| Field                                         | What it tells you at a login                                                                  | How to use it                                                                   |
| --------------------------------------------- | --------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------- |
| `visitor_id`                                  | The browser behind this login                                                                 | Is it one of the browsers this account has used?                                |
| `confidence`                                  | How sure knownprint is about `visitor_id`, from 0 to 1                                        | Skip the second step only when the browser is known and `confidence` is high    |
| `match_type`                                  | `new` when knownprint has not seen this browser before, as far as it can tell                 | A new browser is never a known browser of the account                           |
| `high_recall_id`                              | The past visitor this browser most likely is, when knownprint was not sure enough to match it | Context for a reviewer; never a reason to skip the second step                  |
| `signals.suspect_score.value`                 | 0 to 100: how much of the visit's signals your site should worry about                        | Raise the bar on a known browser, harden the second step on a new one           |
| `signals.bot.value`                           | `bad` when automation drove the browser                                                       | Credential stuffing is scripted: refuse ([Bots](/signals/bots))                 |
| `signals.tor`, `signals.proxy`, `signals.vpn` | The login came through Tor, a proxy or a VPN                                                  | Context, weighed in the suspect score ([Network signals](/signals/network))     |
| `network.country`                             | The country of the address, or null                                                           | Compare with the countries the account usually signs in from                    |
| `signals.high_activity`                       | The browser is among the busiest on your site today                                           | A browser trying many accounts ([Activity](/signals/activity))                  |
| `integrity.replayed`                          | True when this identification was sent before                                                 | Refuse it: never log in on a replayed request ([Integrity](/signals/integrity)) |

Two reads give the account's history. Both use `GET /v1/events` with `end` set to the login's `created_at`, so they look only at what happened before this login:

- `GET /v1/events?linked_id={account}&visitor_id={visitor}&end={created_at}&limit=1` answers "has this browser signed in to this account before?". The `visitor_id` filter also covers every visitor merged into it.
- `GET /v1/events?linked_id={account}&end={created_at}&limit=50` gives the account's recent sign-ins: their browsers and countries.

They work because your backend sets `linked_id` on an event only after a login succeeds (and on later events of the signed-in session), so every browser among the account's events is one that signed in successfully.

## Decision table

The thresholds are starting points to tune on your own traffic, not knownprint defaults. Rows are checked from the top; the first that applies decides.

| What you see                                                                                                                          | Decision                                                                                             |
| ------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------- |
| The request id was used before, the event was replayed, or it was made on another origin                                              | Block                                                                                                |
| `signals.bot.value` is `bad`                                                                                                          | Block, with the same answer as a wrong password                                                      |
| This browser failed to log in to 5 or more different accounts in the last hour                                                        | Block, with the same answer as a wrong password                                                      |
| The password is wrong                                                                                                                 | Refuse, and record the failure against the browser                                                   |
| No request id, the event is not found or stale, or knownprint did not answer                                                          | Challenge                                                                                            |
| The browser signed in to this account before, `confidence` is at least 0.9, and the suspect score is below 70                         | Allow                                                                                                |
| The browser signed in to this account before, but the suspect score is 70 or more                                                     | Challenge                                                                                            |
| The account was created in the last 24 hours and has no sign-in history yet                                                           | Allow, or apply your new-account rules                                                               |
| A new browser for this account, and the suspect score is 40 or more, or Tor or a proxy, or a country the account never signed in from | Challenge with your strongest second factor, notify the owner, and review if the account holds money |
| A new browser for this account                                                                                                        | Challenge                                                                                            |

A challenge is your second step: an authenticator code, a passkey, or a one-time code to the email or phone already on file. Never to a contact detail entered during the same session.

## Backend example

A complete Express handler in Node 22 with Postgres, using the `knownprint.js` module from [Read and verify the event](/guides#read-and-verify-the-event). It refuses bots and stuffing browsers, checks the password, decides between allow and challenge, and attaches the account to the event only once the login succeeds. The secret key needs `events:read` and `events:write`.

```js title="auth.js"
import express from 'express';
import session from 'express-session';
import { db, fired, kp, readEvent, suspectScore } from './knownprint.js';

const app = express();
app.use(express.json());
app.use(session({ secret: process.env.SESSION_SECRET, resave: false, saveUninitialized: false }));

// create table login_failures (
//   visitor_id text not null,
//   username text not null,
//   created_at timestamptz not null default now()
// );
// create index on login_failures (visitor_id, created_at);

const q = (params) => new URLSearchParams(params).toString();

/** The account's sign-ins before this event: is this browser one of them, and from where. */
async function historyOf(accountId, event) {
  const before = { linked_id: accountId, end: event.created_at };
  const same = await kp(`/v1/events?${q({ ...before, visitor_id: event.visitor_id, limit: '1' })}`);
  const recent = await kp(`/v1/events?${q({ ...before, limit: '50' })}`);
  return {
    knownBrowser: same.data.length > 0,
    hasHistory: recent.data.length > 0,
    countries: new Set(recent.data.map((e) => e.network.country).filter((c) => c !== null)),
  };
}

async function failedAccounts(visitorId) {
  const { rows } = await db.query(
    `select count(distinct username) as n from login_failures
      where visitor_id = $1 and created_at > now() - interval '1 hour'`,
    [visitorId],
  );
  return Number(rows[0].n);
}

/** Attaches the account to the login event: from now on this browser is one of its own. */
async function linkLogin(requestId, accountId) {
  await kp(`/v1/events/${requestId}`, {
    method: 'PATCH',
    // linked_id is a string of 1 to 128 characters
    body: { linked_id: String(accountId), tags: { action: 'login', result: 'success' } },
  }).catch(() => {}); // best effort: a failed update must not fail the login
}

/** The decision table above, for a correct password. The thresholds are examples to tune. */
async function decide(result, account) {
  if (result.outcome === 'unknown') return { decision: 'challenge', why: result.reason };
  const { event } = result;
  const score = suspectScore(event) ?? 100; // no score: treat as high
  let history;
  try {
    history = await historyOf(account.id, event);
  } catch {
    return { decision: 'challenge', why: 'history_unavailable' };
  }

  if (history.knownBrowser && event.confidence >= 0.9) {
    return score < 70
      ? { decision: 'allow', why: 'known_browser' }
      : { decision: 'challenge', why: `known_browser, suspect_score ${score}` };
  }
  // A brand-new account has no history yet; an old account without history is a new browser.
  const newAccount = Date.now() - Date.parse(account.createdAt) < 24 * 60 * 60_000;
  if (!history.hasHistory && newAccount) return { decision: 'allow', why: 'first_login' };

  const country = event.network.country;
  const strange =
    score >= 40 ||
    fired(event, 'tor') ||
    fired(event, 'proxy') ||
    (country !== null && !history.countries.has(country));
  return { decision: 'challenge', why: 'new_browser', strong: strange };
}

const REFUSED = { ok: false, error: 'invalid_credentials' };

app.post('/login', async (req, res) => {
  const { username, password, kp_request_id } = req.body;
  const result = await readEvent(kp_request_id);
  if (result.outcome === 'invalid') return res.status(401).json(REFUSED);

  const event = result.event ?? null;
  if (result.outcome === 'ok') {
    if (event.signals?.bot?.value === 'bad') return res.status(401).json(REFUSED);
    if ((await failedAccounts(event.visitor_id)) >= 5) return res.status(401).json(REFUSED);
  }

  const account = await checkPassword(username, password); // your own: { id, createdAt } or null
  if (account === null) {
    if (result.outcome === 'ok') {
      await db.query('insert into login_failures (visitor_id, username) values ($1, $2)', [
        event.visitor_id,
        username,
      ]);
    }
    return res.status(401).json(REFUSED);
  }

  const { decision, why, strong } = await decide(result, account);
  if (decision === 'allow') {
    if (result.outcome === 'ok') await linkLogin(event.request_id, account.id);
    req.session.accountId = account.id;
    req.session.visitorId = event?.visitor_id ?? null;
    return res.json({ ok: true });
  }

  // Challenge: remember the pending login and its event; link only after the second step.
  req.session.pending = {
    accountId: account.id,
    requestId: event?.request_id ?? null,
    visitorId: event?.visitor_id ?? null,
  };
  await sendSecondFactor(account, { strong: strong === true }); // your own
  if (strong) await notifyOwner(account, { why, country: event?.network.country ?? null });
  return res.json({ ok: false, next: 'second_factor' });
});

app.post('/login/second-factor', async (req, res) => {
  const pending = req.session.pending;
  if (!pending || !(await checkSecondFactor(pending.accountId, req.body.code))) {
    return res.status(401).json(REFUSED);
  }
  if (pending.requestId !== null) await linkLogin(pending.requestId, pending.accountId);
  req.session.pending = null;
  req.session.accountId = pending.accountId;
  req.session.visitorId = pending.visitorId;
  return res.json({ ok: true });
});
```

`checkPassword`, `sendSecondFactor`, `checkSecondFactor` and `notifyOwner` stand for your own code. [Verify a request in your backend](/install/server) explains the checks in `readEvent`; the search filters are in the [Events API](/api/events).

:::note Coming
The Node SDK wraps reading and verifying an event and the event update. It is coming with the SDK release; until then, call the routes directly as above. See [Node SDK](/sdks/node).
:::

### Sensitive changes after login

A stolen session cookie skips the login entirely. Identify again before a change that locks the owner out or moves money, and compare the browser with the one that logged in:

```js title="auth.js (continued)"
/** The visitor id and every visitor id merged into it. */
async function idsOf(visitorId) {
  const visitor = await kp(`/v1/visitors/${visitorId}`);
  return visitor === null ? [visitorId] : [visitor.visitor_id, ...visitor.aliases];
}

app.post('/account/email', async (req, res) => {
  if (!req.session.accountId) return res.status(401).end();
  const result = await readEvent(req.body.kp_request_id);
  let sameBrowser = false;
  if (result.outcome === 'ok' && req.session.visitorId !== null) {
    // If the visitor read fails, compare the ids as they are.
    const ids = await idsOf(result.event.visitor_id).catch(() => [result.event.visitor_id]);
    sameBrowser = ids.includes(req.session.visitorId) && result.event.confidence >= 0.9;
  }
  if (!sameBrowser) return res.json({ ok: false, next: 'reauthenticate' });
  await changeEmail(req.session.accountId, req.body.email); // your own
  return res.json({ ok: true });
});
```

A merge can change which id answers for a browser after the login, which is why the check resolves the aliases of the new event's visitor ([Visitors](/visitors)).

## Webhooks and search for review

- **Tell the owner.** Subscribe to `account.linked`. Since your backend links an account to an event only after a successful login, each delivery means "this account just signed in on a browser it never used before" (or was created on it, if you also link at signup as in [Fake signups](/guides/fake-signups)). Its `data` holds `visitor_id` and `linked_id`. Send the owner a "new sign-in" message with a link to secure the account.
- **Spot rings.** Subscribe to `account.related_found`. It arrives when a newly linked pair leaves an account with several browsers or a browser with several accounts; its `data` holds `visitor_id`, `linked_id` and the counts `visitors` and `linked_ids`. One browser signing in to many of your accounts is a takeover ring or an account reseller.
- **Investigate an account.** `GET /v1/linked/{linked_id}/related` lists the browsers that carried the account and the other accounts seen on those browsers. `GET /v1/events?linked_id={account}` gives the account's sign-ins, newest first, with the country and network of each.
- **Sweep for stuffing.** `GET /v1/events?bot=bad&start=...` lists the automated visits of a period, and `GET /v1/events?ip=203.0.113.0/24&start=...` everything from one range during an attack.

Verify every delivery ([Verify a webhook](/webhooks/verify)) and see [Webhooks](/webhooks) for the event types and retries. When a takeover is confirmed, label the login event `fraud` with `POST /v1/events/{request_id}/feedback`, and label a wrongly challenged one `legit` ([Feedback](/feedback)).

## Pitfalls

- **Linking the account before the login succeeds.** If the page passes the account to `identify()`, or your backend sets `linked_id` on a failed attempt, the thief's browser becomes one of the account's browsers and walks straight in next time. Set `linked_id` only after the password and any second step have passed, as the example does.
- **Letting a login through without a request id.** A stuffing script posts to your login endpoint directly and sends none. Treat it as unknown: a challenge, never a free pass.
- **Skipping the second step on `high_recall_id`.** It names the past visitor this browser most likely is when knownprint was not sure, and other browsers can look the same (`anonymity_set_size` above 1). A known browser is one that `visitor_id` names with high `confidence`, nothing less.
- **Different answers for different failures.** A bot, a stuffing browser and a wrong password must all get the same answer, or the attacker learns which passwords are right.
- **Challenging through a channel the thief controls.** Send the code to the email or phone that was on file before the session began, never to one changed in it.
- **Trusting the session alone.** A stolen session cookie needs no password. Identify again before sensitive changes and compare browsers.
- **Blocking every new browser.** People buy phones and reinstall browsers. A new browser is a reason for a second step, not for a refusal.
- **Forgetting retention.** Events are kept for your account's event retention period, between 30 and 365 days ([Privacy](/privacy#retention)); a login after a long absence finds no history and is treated as a new browser. To remember trusted browsers for longer, keep your own table of account and visitor id pairs and resolve merges with `GET /v1/visitors/{visitor_id}`.

## Related pages

- [Guides](/guides): the decision pattern every guide follows.
- [Accounts](/accounts): linked ids and how accounts relate to browsers.
- [Bots and scrapers](/guides/bots-and-scrapers): credential stuffing is a bot problem first.
- [Account sharing](/guides/account-sharing): many browsers on one account by consent rather than theft.
