Install
Verify a request in your backend
Read the event behind a request id with your secret key, check that it is fresh, unused and from your own page, decide with your own rules, and attach your account id.
The page only ever holds a request id. Everything knownprint found about the visit stays on the server side until your backend asks for it with your secret key. This page shows the whole backend half: read the event, verify it, decide, and attach your account id afterwards.
form POST with kp_request_id
-> GET /v1/events/{request_id} (secret key)
-> verify: unused, fresh, not replayed, your origin, the same address, confident enough
-> decide with your rules on signals and the suspect score
-> PATCH /v1/events/{request_id} (linked_id = your account id)Before you start you need:
- The page set up to send a request id with the form: Add the browser agent and Protect your forms. By convention the id arrives in the form field
kp_request_id. - Your secret key (
sk_live_...orsk_test_...), kept on the server only, and the API address that comes with your account. The examples read them fromKNOWNPRINT_SECRET_KEYandKNOWNPRINT_API. - A shared store for used request ids if your backend runs more than one process. The examples use Redis; anything with an atomic "set if absent, with expiry" works.
Read the event
Exchange the request id for the event with GET /v1/events/{request_id}. The secret key needs the events:read scope.
curl "$KNOWNPRINT_API/v1/events/$REQUEST_ID" \
-H "Authorization: Bearer $KNOWNPRINT_SECRET_KEY" \
-H "Accept: application/json"A request id is evt_ followed by 26 characters from a to z and 2 to 7. Check the shape before you call the API (/^evt_[a-z2-7]{26}$/), so a form field an attacker filled with anything never reaches a URL.
The answer is the full event. These are the fields the verification and the decision below use; Events lists every field.
{
"request_id": "evt_6cgdjsd3qhozl3xuff7lpftxr4",
"environment_id": "env_ob7rx73fgg6pvj4tdfzyr6lg3q",
"received_at": "2026-06-01T14:03:27.412Z",
"visitor_id": "v_jxz4djj6egpy6r4sreptmrwlna",
"confidence": 0.98,
"network": {
"ip": "203.0.113.24",
"country": "NL"
},
"integrity": {
"origin": "https://shop.example",
"replayed": false
},
"signals": {
"bot": { "value": "not_detected", "confidence": 1, "reasons": [] },
"vpn": { "value": false, "confidence": 0.9, "reasons": [] },
"suspect_score": { "value": 0, "confidence": 1, "reasons": [] }
},
"linked_id": null
}The example is abridged: a real event carries every field of Events, and signals holds every signal, each either an object or null when it could not be read.
| Status | Problem | What it means | What to do |
|---|---|---|---|
| 200 | The event. | Verify it. | |
| 401 | unauthorized | No valid secret key: missing, mistyped, revoked, or a public key sent by mistake. | Fix your configuration. Do not retry. |
| 403 | forbidden_scope | The key lacks events:read. | Use a key with the scope. |
| 404 | not_found | No such event in this key's environment: a made-up id, an id from your other environment (test or live), or an event past retention. | Treat it as a missing request id. |
| 409 | deletion_pending | A deletion of this event's visitor is in progress. | Treat it as a missing request id. |
| 429 | rate_limited | Your key is over its rate limit. | Wait for Retry-After, or treat it as missing if the user is waiting. |
| 500 | internal | knownprint failed to answer. | Treat it as missing; alert if it repeats. |
Errors are application/problem+json bodies; see Errors. Reading an event does not use it up: you can read the same event again, for example from a review tool. Single use is something your backend enforces, as the next section shows.
Verify the event
An event tells you about a visit, but a request id is only a string in a form. Someone can copy one from their own browser into a bot's request, replay a captured form, or mint ids on a different site. Before you trust the event for this request, check six things, in this order:
| Check | Fails when | Why |
|---|---|---|
| 1. Single use | You have already accepted this request id once. | A request id answers for one action. A second use is a replay of a captured or shared id. |
| 2. Freshness | received_at is more than 10 seconds ago (or more than 60 seconds in the future, which only a badly wrong clock explains). | The page identifies at the moment the user acts. An old id was saved and reused. The expiresAt the page receives is received_at plus the same 10 seconds. |
| 3. Not replayed | integrity.replayed is true. | This identification was sent before. Refuse it. |
| 4. Your origin | integrity.origin is not your site's origin, exactly (https://shop.example, scheme and host, with a port only if it is not the default). | The id was made on another page than yours. |
| 5. The same address | network.ip is not the address your own proxy reports for this form post, or is null. | The id was made from another network than the one posting the form: a common sign of ids made on one machine and used from another. |
| 6. Confidence | confidence is below the minimum you set. | knownprint was not sure enough of the visitor id for the decision you are about to take. |
Burn the id first, before any other check, so that a stale or mismatched attempt also uses it up and cannot be retried with a better guess.
The visitor address
Compare network.ip with the address of the end user as your own proxy reports it, never with the first entry of X-Forwarded-For:
X-Forwarded-Foris a list each proxy appends to. Its first entry is whatever the client sent, and a client can send anything.- The entry you can trust is the one your own proxy appended: the last entry, when your application sits directly behind that proxy. If there are several proxies of yours in a chain, count from the right, past each of them.
- If your proxy overwrites a header of its own with the client address (for example a CDN's client address header that it always replaces), read that header instead.
- With no proxy in front of your application, use the socket's peer address.
Your proxy must send the header. Caddy's reverse_proxy does so by default; nginx does only when the location that serves your application sets proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; (and proxy_set_header X-Forwarded-Proto $scheme; if your application reads the scheme), as Install on nginx shows. Without it, the address your backend sees is your proxy's, and check 5 fails for every visitor.
Write the address the way knownprint writes it before you compare: an IPv4 address as a dotted quad (Node often reports IPv4 on a dual-stack socket as ::ffff:203.0.113.24, which must become 203.0.113.24), and an IPv6 address in its short lower-case form (2001:db8::1, not 2001:DB8:0:0:0:0:0:1).
When your proxy sends no valid proxy secret, network.ip is the address that connected to knownprint, your own server's, and the check fails for every visitor. Treat a null address the same way, as a failed check, and fix the proxy: see The visitor's address.
Minimum confidence
confidence runs from 0 to 1 and says how sure knownprint is that visitor_id is the right visitor. Set a minimum only for decisions that depend on recognising a returning browser, such as "this browser already made three accounts". A decision that rests on the signals of this one visit (a bot, a proxy, tampering) does not need one. See Concepts for what the visitor id and confidence mean.
Decide with your rules
A verified event is a description of a visit, not a verdict. knownprint does not block anyone: your code decides, with rules that fit the action. Start from the suspect score and the few signals that matter for the action, and keep the thresholds in configuration so you can tune them.
// Example thresholds only: tune them on your own traffic.
export function decide(event) {
const s = event.signals;
const score = s.suspect_score?.value ?? null;
if (s.bot?.value === 'bad') return 'block';
if (score === null) return 'challenge'; // not computed: unknown, never clean
if (s.tampering?.value === true) return 'review';
if (score >= 60) return 'review';
if (score >= 30) return 'challenge'; // for example a one-time code by email
return 'allow';
}signals.suspect_score.valueadds up what the visit's signals found, from 0 to 100, andreasonsnames the signals that counted. See Suspect score.- Every signal has
value,confidenceandreasons, and isnullwhen it could not be read. Treatnullas "unknown", never as "clean" or "dirty". See Signals. - Combine the event with what you know: the account's age, the order value, how many accounts the visitor already holds (Accounts), and the visitor's history (Visitors).
- When your team reviews a case, send the outcome back as feedback (Feedback).
The Guides give worked rule sets for payment fraud, account takeover, fake signups and other cases.
Examples
All three examples do the same thing: read the event, verify it, decide, and return the event or null. Use the one that fits your stack.
curl and Redis (to try it by hand)
This is useful to see the checks on a real event before you write code. Run it within 10 seconds of the identification.
#!/usr/bin/env bash
set -euo pipefail
REQUEST_ID="$1" # the kp_request_id the form posted
SITE_ORIGIN="https://shop.example"
CLIENT_IP="$2" # the address your proxy reported for the form post
[[ "$REQUEST_ID" =~ ^evt_[a-z2-7]{26}$ ]] || { echo "malformed request id"; exit 1; }
EVENT=$(curl -sf "$KNOWNPRINT_API/v1/events/$REQUEST_ID" \
-H "Authorization: Bearer $KNOWNPRINT_SECRET_KEY" -H "Accept: application/json")
# 1. Single use: SET ... NX answers OK the first time only. Keep it 70 s (10 s + 60 s).
[[ "$(redis-cli SET "kp:consumed:$REQUEST_ID" 1 PX 70000 NX)" == "OK" ]] || { echo consumed; exit 1; }
# 2. Freshness: received_at at most 10 s ago.
RECEIVED=$(jq -r '.received_at' <<<"$EVENT")
AGE_MS=$(( $(date +%s%3N) - $(date -d "$RECEIVED" +%s%3N) ))
(( AGE_MS <= 10000 && AGE_MS >= -60000 )) || { echo stale; exit 1; }
# 3 to 5. Replay, origin and address.
jq -e '.integrity.replayed == false' <<<"$EVENT" >/dev/null || { echo replayed; exit 1; }
jq -e --arg o "$SITE_ORIGIN" '.integrity.origin == $o' <<<"$EVENT" >/dev/null || { echo origin_mismatch; exit 1; }
jq -e --arg ip "$CLIENT_IP" '.network.ip == $ip' <<<"$EVENT" >/dev/null || { echo ip_mismatch; exit 1; }
jq '{visitor_id, confidence, suspect_score: .signals.suspect_score.value, bot: .signals.bot.value}' <<<"$EVENT"The date calls use GNU coreutils; on macOS install coreutils and use gdate.
Node with fetch and Redis
Plain Node 22 with the global fetch and the redis client. The same shape works in any language: one HTTP GET, one atomic "set if absent" and five comparisons.
import { isIP, SocketAddress } from 'node:net';
import { createClient } from 'redis';
const API = process.env.KNOWNPRINT_API;
const SECRET_KEY = process.env.KNOWNPRINT_SECRET_KEY;
const REQUEST_ID = /^evt_[a-z2-7]{26}$/;
const MAX_AGE_MS = 10_000;
const CLOCK_SKEW_MS = 60_000;
const redis = createClient({ url: process.env.REDIS_URL });
await redis.connect();
export class VerifyError extends Error {
constructor(code) {
super(`knownprint verification failed: ${code}`);
this.code = code;
}
}
/** An address as knownprint writes it: IPv4 dotted quad, IPv6 short and lower case. */
export function canonicalIp(text) {
if (typeof text !== 'string') return null;
const value = text.trim();
if (isIP(value) === 4) return value;
if (isIP(value) !== 6) return null;
// Short and lower case first, so every spelling of an IPv4-mapped address is caught below.
const short = new SocketAddress({ address: value, family: 'ipv6' }).address;
const mapped = /^::ffff:(\d{1,3}(?:\.\d{1,3}){3})$/.exec(short);
return mapped ? mapped[1] : short;
}
/**
* The end user's address: the last X-Forwarded-For entry when the peer is your own proxy
* (here on the same host), else the socket address. Never the first entry.
*/
export function clientIp(req) {
const peer = canonicalIp(req.socket.remoteAddress);
const fromProxy = peer === '127.0.0.1' || peer === '::1';
if (fromProxy) {
const entries = String(req.headers['x-forwarded-for'] ?? '')
.split(',')
.map((entry) => entry.trim())
.filter(Boolean);
if (entries.length > 0) return canonicalIp(entries[entries.length - 1]);
}
return peer;
}
/** The event, or null when knownprint holds none for this id. Throws on other failures. */
export async function readEvent(requestId) {
const res = await fetch(`${API}/v1/events/${requestId}`, {
headers: { authorization: `Bearer ${SECRET_KEY}`, accept: 'application/json' },
signal: AbortSignal.timeout(5_000),
});
if (res.status === 404 || res.status === 409) return null;
if (!res.ok) {
const problem = await res.json().catch(() => null);
throw new Error(`knownprint answered ${res.status} ${problem?.type ?? ''}`.trim());
}
return res.json();
}
/** Throws a VerifyError with the first check that failed, else returns the event. */
export async function verifyEvent(event, { origin, ip, minConfidence }) {
// 1. Burn the id first: SET key 1 PX ttl NX answers 'OK' only the first time.
const first = await redis.set(`kp:consumed:${event.request_id}`, '1', {
PX: MAX_AGE_MS + CLOCK_SKEW_MS,
NX: true,
});
if (first === null) throw new VerifyError('consumed');
// 2. Fresh.
const age = Date.now() - Date.parse(event.received_at);
if (!Number.isFinite(age) || age > MAX_AGE_MS || age < -CLOCK_SKEW_MS) {
throw new VerifyError('stale');
}
// 3. Not replayed.
if (event.integrity.replayed) throw new VerifyError('replayed');
// 4. Made on your page.
if (event.integrity.origin !== origin) throw new VerifyError('origin_mismatch');
// 5. From the address that posted the form.
if (event.network.ip === null || canonicalIp(ip) !== event.network.ip) {
throw new VerifyError('ip_mismatch');
}
// 6. Sure enough of the visitor id, when you ask for it.
if (minConfidence !== undefined && event.confidence < minConfidence) {
throw new VerifyError('low_confidence');
}
return event;
}
/** The verified event of a form post, or null when there is none to trust. */
export async function identifiedEvent(req, requestId) {
const ip = clientIp(req);
if (typeof requestId !== 'string' || !REQUEST_ID.test(requestId) || ip === null) return null;
try {
const event = await readEvent(requestId);
if (event === null) return null;
return await verifyEvent(event, { origin: 'https://shop.example', ip });
} catch (error) {
// Log the code or the status, never the request id, the address or the body.
console.warn('knownprint:', error.code ?? error.message);
return null;
}
}Use it in a route. This one uses Express; any framework works the same way.
import express from 'express';
import { decide } from './decide.js';
import { identifiedEvent } from './knownprint.js';
const app = express();
app.use(express.urlencoded({ extended: false }));
app.post('/signup', async (req, res) => {
const event = await identifiedEvent(req, req.body.kp_request_id);
const outcome = event === null ? 'challenge' : decide(event);
if (outcome === 'block') return res.status(403).send('Sign-up refused.');
const account = await createAccount(req.body, { verified: outcome === 'allow' });
if (event !== null) await linkAccount(event.request_id, account.id);
res.redirect(outcome === 'allow' ? '/welcome' : '/verify-email');
});createAccount is your own code; linkAccount is in Attach your account id.
Node SDK
verifyRequestId makes the six checks in the order above and throws a KnownprintVerifyError whose code names the first that failed. events.get throws a KnownprintApiError with the HTTP status for any answer other than 2xx.
import {
Knownprint,
KnownprintApiError,
KnownprintVerifyError,
RedisConsumedIdStore,
fromNodeRedis,
} from '@knownprint/sdk-node';
import { createClient } from 'redis';
const redis = createClient({ url: process.env.REDIS_URL });
await redis.connect();
export const kp = new Knownprint({
secretKey: process.env.KNOWNPRINT_SECRET_KEY,
baseUrl: process.env.KNOWNPRINT_API,
consumedIds: new RedisConsumedIdStore({ setNx: fromNodeRedis(redis) }),
});
const REQUEST_ID = /^evt_[a-z2-7]{26}$/;
/** The verified event of a form post, or null when there is none to trust. */
export async function identifiedEvent(requestId, ip) {
if (typeof requestId !== 'string' || !REQUEST_ID.test(requestId) || !ip) return null;
try {
const event = await kp.events.get(requestId);
return await kp.verifyRequestId(event, { origin: 'https://shop.example', ip });
} catch (error) {
if (error instanceof KnownprintVerifyError) {
console.info('knownprint verification failed:', error.code);
} else if (!(error instanceof KnownprintApiError && error.status === 404)) {
console.warn(
'knownprint read failed:',
error instanceof KnownprintApiError ? error.status : error.name,
);
}
return null;
}
}verifyRequestId options are origin, ip, minConfidence and maxAgeMs (default 10,000). It compares ip with network.ip as given, so pass the address in the form described in The visitor address. Without a consumedIds store the client keeps used ids in its own process memory, which is only enough for a backend that runs as one process.
Attach your account id
Once you know which account acted (the account you just created, or the one that logged in), write its id onto the event with PATCH /v1/events/{request_id}. The key needs the events:write scope.
curl -X PATCH "$KNOWNPRINT_API/v1/events/$REQUEST_ID" \
-H "Authorization: Bearer $KNOWNPRINT_SECRET_KEY" \
-H "Content-Type: application/json" \
-H "Idempotency-Key: link-$REQUEST_ID" \
-d '{"linked_id": "acct_1842"}'export async function linkAccount(requestId, accountId) {
const res = await fetch(`${process.env.KNOWNPRINT_API}/v1/events/${requestId}`, {
method: 'PATCH',
headers: {
authorization: `Bearer ${process.env.KNOWNPRINT_SECRET_KEY}`,
'content-type': 'application/json',
'idempotency-key': `link-${requestId}`,
},
body: JSON.stringify({ linked_id: String(accountId) }), // 1 to 128 characters
signal: AbortSignal.timeout(5_000),
});
// A failure here must not undo the sign-up: log the status and go on.
if (!res.ok) console.warn('knownprint link failed:', res.status);
}With the Node SDK the same call is await kp.events.update(event.request_id, { linkedId: String(account.id) }).
What the body takes:
| Field | Type | Rules | Effect |
|---|---|---|---|
linked_id | string or null | 1 to 128 characters, no U+0000. | A string sets the event's account id and links its visitor to that account. null clears it. Leaving the field out keeps it. |
tags | object or null | Up to 64 keys of 1 to 64 characters; values are strings (up to 256 characters), numbers or booleans; under 4,096 bytes as compact JSON. | Replaces the event's tags whole. null clears them. Leaving the field out keeps them. |
The body must hold at least one of the two and nothing else. The answer is 200 with the updated event. A body that is not JSON is 400 schema_mismatch; a body that breaks the rules above is 422 validation_failed (invalid_body, or invalid_subject for a malformed linked_id); the other errors are those of the read. When a new linked_id replaces an earlier one, or null clears it, the visitor's link to the earlier account is removed, so a correction stops relating the two.
Why from the server, and not in the browser? The page can also pass a linkedId to the identification, which suits a page where the user is already signed in. But anything the page sends can be changed by whoever controls the browser. An account id your backend writes after verification is one you can rely on, and at signup the account does not exist yet when the page identifies.
Linking is what makes Accounts work: every browser an account has used, every account a browser has used, and the account.linked and account.related_found webhooks. Store the visitor_id beside your own account record as well, so you can find the visitor later, for example to delete it when the user asks (Visitors).
The Idempotency-Key header is optional: 1 to 255 visible ASCII characters (otherwise 422, detail idempotency_key). With it, a retried PATCH within 24 hours answers the stored result, with Idempotency-Replayed: true, instead of running twice. A key is tied to its request: the same key with a different body, such as a later correction to another account id, answers 409 idempotency_conflict, so give a correction a key of its own (for example relink-$REQUEST_ID-2). See API reference.
Handle a missing request id
Some form posts arrive without a request id you can trust. That is normal, and your backend needs a rule for it. It happens when:
- The browser blocked the script (a content blocker, JavaScript turned off, a very old browser).
- The identification did not finish in time. The form helper waits 3 seconds, then submits the form without the field rather than keep the user waiting.
- Your page blocked collection until the user chooses (consent mode
blocked). - The request id was not found, was in deletion, or failed verification.
- A client posted the form directly, without your page: scripts and bots often do.
Treat all of these the same way: as an unknown visit, not as a clean one and not automatically as fraud.
- Do not block outright. Real users with content blockers would be locked out.
- Do not let it through as if it were verified. Otherwise an attacker only needs to drop the field.
- Apply the step you use for medium risk: an email or SMS code, a CAPTCHA, holding the order for review, a lower limit for a new account, or a rate limit on the account and the address.
Count verification outcomes by code (missing, consumed, stale, replayed, origin_mismatch, ip_mismatch, low_confidence, read errors) in your metrics. A small steady share of missing ids is normal; a sudden jump usually means a broken proxy rule, a new content security policy, or an attack that strips the field. See Go live.