knownprintDocs

Guides

Guides

Turn a knownprint event into a decision (allow, challenge, review or block) at the moments where fraud costs you money.

knownprint answers and your code decides. Each identification gives your backend an event: the browser behind the request (visitor_id), how sure knownprint is (confidence), and the signals of the visit, summed up in one suspect score. What you do with it depends on the moment: a login, a payment and a free trial carry different risks and deserve different answers.

This page explains the pattern every guide follows: where to call identify(), how to read and verify the event, how to map it to one of four decisions, and how to record the outcome. The guides below then apply it to one kind of fraud each.

The flow of a decision

  1. The page calls identify() right before the action you want to protect (a signup, a login, a payment) and sends the request id (evt_...) along with that action.
  2. Your backend reads the event with your secret key: GET /v1/events/{request_id}.
  3. Your backend verifies the event: the request id is used once, the event is fresh, it came from your own origin and it was not replayed.
  4. Your code reads the fields that matter for this action and picks one of four decisions: allow, challenge, review or block.
  5. Your code acts, stores the visitor_id and request_id beside its own record (the order, the account, the claim), and attaches your account id to the event with PATCH /v1/events/{request_id}.
  6. When you learn the truth later (a chargeback, a confirmed takeover, a customer who was wrongly blocked), you label the event with POST /v1/events/{request_id}/feedback.

The page never sees the visitor id or the signals, and it never decides. Anything decided in the browser can be changed by whoever controls the browser.

Where to call identify

Call identify() on the actions where a decision matters, at the moment the user acts, not when the page loads. knownprint is built for these account events; calling it on every page view adds nothing to your decisions and spends your rate limits.

MomentWhy identify hereGuide
Checkout, payment, adding a cardCard testing and stolen cardsPayment fraud
Login, password reset, changing email, phone or payout detailsStolen passwords and takeoversAccount takeover
SignupFake accounts in bulkFake signups
Redeeming a code, starting a trial, claiming a bonus or referralOne reward per browser, not per emailPromo abuse
Signup or login of a banned userBans that stickBan evasion
Login to a paid planOne subscription shared by manyAccount sharing
Search, sending a one-time code, posting, bookingScripts and scrapersBots and scrapers

In the page, load the agent once when the page starts (Add the browser agent), then identify inside the handler of the action and send the request id with it. For a plain HTML form, Protect a form writes the request id into a hidden field for you.

checkout.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 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); // blocked, offline or failed: send the action without a request id
  return Promise.race([attempt, timeout]);
}

document.querySelector('#pay').addEventListener('click', async () => {
  const kp_request_id = await requestId('checkout');
  await fetch('/checkout', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({ cart: cartId, kp_request_id }),
  });
});

Never hold the user back while knownprint answers: if no request id arrives in time, send the action without one and let your backend treat it as unknown (below).

Read and verify the event

Your backend reads the event with a secret key that has the events:read scope, and checks it before it trusts it. These checks are the same in every guide:

CheckFieldWhy
The request id has the right shaperequest_id matches ^evt_[a-z2-7]{26}$Anything else is not a knownprint request id
It is used onceyour own store of accepted request idsA request id copied from one request and sent again is a replay
It is freshreceived_at within 10 seconds of nowThe identify answer expires 10 seconds after knownprint received it
It came from your siteintegrity.origin equals your origin, such as https://shop.exampleA request id made on another site's page is not your visitor
It was not replayedintegrity.replayed is falseTrue means this identification was sent before; refuse it

Verify a request in your backend explains each check in depth. Here is a module that every example in these guides can use. It needs Node 22 and Postgres for the store of used request ids; any shared store with an atomic "insert if absent" works.

knownprint.js
import { createHmac, timingSafeEqual } from 'node:crypto';
import pg from 'pg';

const API = process.env.KNOWNPRINT_API; // the API address that comes with your account
const SECRET = process.env.KNOWNPRINT_SECRET_KEY; // sk_live_...
const ORIGIN = process.env.SITE_ORIGIN; // for example https://shop.example

export const db = new pg.Pool();

// create table kp_used_request_ids (
//   request_id text primary key,
//   used_at timestamptz not null default now()
// );
// A daily job may delete rows older than a day.

export class KnownprintApiError extends Error {
  constructor(status, problem) {
    super(`knownprint ${status} ${problem?.type?.split('/').pop() ?? ''}`.trim());
    this.status = status;
    this.problem = problem; // the application/problem+json body, or null
  }
}

/** Calls the knownprint API with the secret key; null on 404, throws on any other error. */
export async function kp(path, { method = 'GET', body, idempotencyKey } = {}) {
  const headers = { Authorization: `Bearer ${SECRET}`, Accept: 'application/json' };
  if (body !== undefined) headers['Content-Type'] = 'application/json';
  if (idempotencyKey !== undefined) headers['Idempotency-Key'] = idempotencyKey;
  const res = await fetch(`${API}${path}`, {
    method,
    headers,
    body: body === undefined ? undefined : JSON.stringify(body),
    signal: AbortSignal.timeout(3000),
  });
  if (res.status === 404) return null;
  const data = await res.json().catch(() => null);
  if (!res.ok) throw new KnownprintApiError(res.status, data);
  return data;
}

/**
 * Reads and verifies the event of a request id. The outcome is:
 * - 'ok' with the event;
 * - 'unknown' when there is nothing to trust (no request id, not found, too old,
 *   knownprint unreachable);
 * - 'invalid' when the request id was used before, replayed, or made on another origin.
 */
export async function readEvent(requestId) {
  if (typeof requestId !== 'string' || !/^evt_[a-z2-7]{26}$/.test(requestId)) {
    return { outcome: 'unknown', reason: 'no_request_id' };
  }
  const first = await db.query(
    'insert into kp_used_request_ids (request_id) values ($1) on conflict do nothing',
    [requestId],
  );
  if (first.rowCount === 0) return { outcome: 'invalid', reason: 'used_before' };

  let event;
  try {
    event = await kp(`/v1/events/${requestId}`);
  } catch {
    return { outcome: 'unknown', reason: 'knownprint_unavailable' };
  }
  if (event === null) return { outcome: 'unknown', reason: 'not_found' };
  if (event.integrity.replayed) return { outcome: 'invalid', reason: 'replayed', event };
  if (event.integrity.origin !== ORIGIN) return { outcome: 'invalid', reason: 'origin', event };
  const age = Date.now() - Date.parse(event.received_at);
  if (!(age <= 10_000 && age >= -60_000)) return { outcome: 'unknown', reason: 'stale', event };
  return { outcome: 'ok', event };
}

/** True only when the signal was read and fired. */
export const fired = (event, name) => event.signals?.[name]?.value === true;

/** The suspect score from 0 to 100, or null when it was not computed. */
export function suspectScore(event) {
  const value = event.signals?.suspect_score?.value;
  return typeof value === 'number' ? value : null;
}

/**
 * Checks a webhook delivery and returns its envelope; throws when it is not genuine.
 * `rawBody` is the body exactly as received, as a string.
 */
export function verifyWebhook(headers, rawBody, secret, toleranceSeconds = 300) {
  const id = headers['webhook-id'];
  const timestamp = headers['webhook-timestamp'];
  const signatures = headers['webhook-signature'];
  if (!id || !timestamp || !signatures) throw new Error('missing_header');
  // Unix seconds: decimal digits, no sign, no leading zero.
  if (!/^(?:0|[1-9][0-9]{0,15})$/.test(timestamp)) throw new Error('timestamp_out_of_tolerance');
  if (Math.abs(Date.now() / 1000 - Number(timestamp)) > toleranceSeconds) {
    throw new Error('timestamp_out_of_tolerance');
  }
  const key = Buffer.from(secret.slice('whsec_'.length), 'base64');
  const expected = createHmac('sha256', key).update(`${id}.${timestamp}.${rawBody}`).digest();
  const ok = signatures.split(' ').some((entry) => {
    if (!entry.startsWith('v1,')) return false;
    const given = Buffer.from(entry.slice(3), 'base64');
    return given.length === expected.length && timingSafeEqual(given, expected);
  });
  if (!ok) throw new Error('bad_signature');
  return JSON.parse(rawBody);
}

verifyWebhook follows the Standard Webhooks scheme that every delivery is signed with; Verify a webhook explains it step by step.

A 404 from GET /v1/events/{request_id} means no event of your environment has that id. A 409 with deletion_pending means the visitor is being deleted at your request; kp() throws it, and readEvent treats it as unknown. Every status and error code is listed in API errors.

The four decisions

DecisionWhat it meansTypical actions
AllowNothing in the event gives you reason to doubt itLet the action through with no extra step
ChallengeSome doubt, and the honest user can clear it cheaplyA second factor, an email or SMS code, 3-D Secure, a CAPTCHA you run, re-entering the password
ReviewEnough doubt that a person should look before the action completesHold the order, delay the payout, queue the account for a moderator
BlockClear evidence of abuse, or a request that cannot be genuineRefuse the action, with a plain message that does not say why

Choose the cheapest decision that stops the abuse. A challenge costs an honest customer a few seconds; a wrong block costs you the customer. Keep blocks for what cannot be innocent: automation, replayed requests, a browser that already used the reward, an account limit you set.

A starting point that each guide refines:

decide.js
import { readEvent, suspectScore } from './knownprint.js';

/** A first decision from the event alone. The thresholds are examples to tune. */
export async function baseDecision(requestId) {
  const result = await readEvent(requestId);
  if (result.outcome === 'invalid') return { decision: 'block', why: result.reason };
  if (result.outcome === 'unknown') return { decision: 'challenge', why: result.reason };

  const { event } = result;
  if (event.signals?.bot?.value === 'bad') return { decision: 'block', why: 'bot', event };

  const score = suspectScore(event);
  if (score === null) return { decision: 'challenge', why: 'no_score', event };
  if (score >= 70) return { decision: 'review', why: `suspect_score ${score}`, event };
  if (score >= 40) return { decision: 'challenge', why: `suspect_score ${score}`, event };
  return { decision: 'allow', why: 'clean', event };
}

The thresholds here (40 and 70) and in every guide are starting points for you to tune on your own traffic, not knownprint defaults. The suspect score explains what the number adds up; Signals lists every signal behind it.

Unknown is not a pass

The most common mistake is to treat "no answer" as "nothing wrong". A request reaches your backend without a usable event when:

  • the page sent no request id: a content blocker stopped the script, the network failed, or a bot called your endpoint directly without running the page at all;
  • the request id is not found, is older than 10 seconds, or knownprint did not answer in time;
  • a signal is null: it could not be read on that visit. null is unknown, never false.

A bot that skips your page sends no request id, so an endpoint that allows requests without one has no protection. Decide per action what unknown means: for a login you may let the user through with a second factor, for a payment you may hold the order or run 3-D Secure, for a reward you may hold it. Never treat unknown as allow on an action that pays out.

The same caution applies to the identity fields:

  • confidence says how sure knownprint is about visitor_id. Automate a block on a match only above a confidence you choose; review below it.
  • high_recall_id names the past visitor this browser most likely is when knownprint was not sure enough to match it. It is a lead for review, never proof.
  • anonymity_set_size is the lookalike count: 1 plus the known browsers that look the same as this one. Above 1, a lead to another visitor is weaker, because several browsers fit.

Visitors explains these fields in depth.

Record the outcome

Store request_id and visitor_id with your own record of the action (the order, the account, the reward). Events are kept for your account's event retention period (between 30 and 365 days) and then deleted (Privacy), and your own records are what you will search when a chargeback arrives months later.

Attach your account id to the event once you know it, and label the event when you learn the truth:

record.js
import { kp } from './knownprint.js';

// The account behind the action (scope events:write).
await kp(`/v1/events/${requestId}`, {
  method: 'PATCH',
  // linked_id is a string of 1 to 128 characters
  body: { linked_id: String(account.id), tags: { action: 'checkout', order: order.id } },
});

// Weeks later, when the chargeback arrives (scope events:write).
await kp(`/v1/events/${order.kpRequestId}/feedback`, {
  method: 'POST',
  body: { label: 'fraud', note: 'chargeback, reason: card not present' },
  idempotencyKey: `chargeback-${order.id}`,
});

A PATCH replaces the event's tags as a whole, the tags the page sent included, so send every tag you want to keep; a member you leave out of the body stays as it was, and null clears it. label is fraud or legit; note is optional, up to 1,000 characters. Feedback covers labels; Events API covers both routes.

Review with search and webhooks

Two tools serve your review queue and your investigations:

  • Search. GET /v1/events lists your events newest first, filtered by visitor_id, linked_id, ip (an address or a range), start and end, bot, vpn and min_suspect_score, with limit (1 to 500, 50 by default) and a cursor for the next page. GET /v1/events?visitor_id=v_... also returns the events of every visitor merged into it. See Events API.
  • Webhooks. knownprint can call your backend for each identification (event.identified), when an account id is first seen on a browser (account.linked), and when that makes an account share a browser or a browser carry several accounts (account.related_found). Deliveries are signed; verify each one (Verify a webhook). See Webhooks.

The related reads answer the question a reviewer asks most: who else? GET /v1/visitors/{visitor_id}/related lists the visitors and account ids related to a browser, and GET /v1/linked/{linked_id}/related the browsers that carried an account id and the other accounts seen on those browsers. They are an aid to review, not an identification. See Linked ids API.

The guides

  • Payment fraud: stop card testing and stolen cards by counting cards per browser and holding risky payments before capture.
  • Account takeover: ask for a second step only when an account signs in from a browser it has not used before.
  • Fake signups: see how many accounts a browser has already opened before you create another.
  • Bots and scrapers: block automation on logins, searches and one-time codes, and treat a missing request id as unknown.
  • Promo abuse: one welcome code, bonus, referral reward or free trial per browser instead of per email.
  • Ban evasion: keep banned users out when they come back with a new email or a new account.
  • Account sharing: see every browser an account uses and enforce the limits of each plan.