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
- 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. - Your backend reads the event with your secret key:
GET /v1/events/{request_id}. - 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.
- Your code reads the fields that matter for this action and picks one of four decisions: allow, challenge, review or block.
- Your code acts, stores the
visitor_idandrequest_idbeside its own record (the order, the account, the claim), and attaches your account id to the event withPATCH /v1/events/{request_id}. - 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.
| Moment | Why identify here | Guide |
|---|---|---|
| Checkout, payment, adding a card | Card testing and stolen cards | Payment fraud |
| Login, password reset, changing email, phone or payout details | Stolen passwords and takeovers | Account takeover |
| Signup | Fake accounts in bulk | Fake signups |
| Redeeming a code, starting a trial, claiming a bonus or referral | One reward per browser, not per email | Promo abuse |
| Signup or login of a banned user | Bans that stick | Ban evasion |
| Login to a paid plan | One subscription shared by many | Account sharing |
| Search, sending a one-time code, posting, booking | Scripts and scrapers | Bots 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.
// 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:
| Check | Field | Why |
|---|---|---|
| The request id has the right shape | request_id matches ^evt_[a-z2-7]{26}$ | Anything else is not a knownprint request id |
| It is used once | your own store of accepted request ids | A request id copied from one request and sent again is a replay |
| It is fresh | received_at within 10 seconds of now | The identify answer expires 10 seconds after knownprint received it |
| It came from your site | integrity.origin equals your origin, such as https://shop.example | A request id made on another site's page is not your visitor |
| It was not replayed | integrity.replayed is false | True 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.
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
| Decision | What it means | Typical actions |
|---|---|---|
| Allow | Nothing in the event gives you reason to doubt it | Let the action through with no extra step |
| Challenge | Some doubt, and the honest user can clear it cheaply | A second factor, an email or SMS code, 3-D Secure, a CAPTCHA you run, re-entering the password |
| Review | Enough doubt that a person should look before the action completes | Hold the order, delay the payout, queue the account for a moderator |
| Block | Clear evidence of abuse, or a request that cannot be genuine | Refuse 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:
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.nullis 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:
confidencesays how sure knownprint is aboutvisitor_id. Automate a block on a match only above a confidence you choose; review below it.high_recall_idnames 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_sizeis 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:
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/eventslists your events newest first, filtered byvisitor_id,linked_id,ip(an address or a range),startandend,bot,vpnandmin_suspect_score, withlimit(1 to 500, 50 by default) and acursorfor 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.