SDKs
Node SDK
Reference for @knownprint/sdk-node, the server SDK for Node.js: the API client, verifyRequestId with its consumed-id stores, verifyWebhook, errors and constants.
@knownprint/sdk-node is the server half of knownprint for Node.js. It gives you:
- A client over the server API routes your backend calls: events, feedback, visitors, related accounts and labelled pairs.
verifyRequestId, which checks a request id before you trust its event, with an in-memory or Redis store of the ids already used.Knownprint.verifyWebhook, which checks the signature of a webhook delivery and returns its envelope.
Answers are the API's JSON, returned unchanged and typed. Options are camelCase and are mapped to the API's field names for you.
Install
npm install @knownprint/sdk-nodeThe package is an ES module with TypeScript declarations, for Node.js 22 or later (it uses Node's global fetch unless you pass your own). Its one dependency is @knownprint/contracts, the package of the API's types.
Quick start
import { Knownprint, 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) }),
});import { KnownprintVerifyError } from '@knownprint/sdk-node';
import { kp } from './knownprint.js';
// requestId is the form's kp_request_id; ip is the address your own proxy reports.
const event = await kp.verifyRequestId(await kp.events.get(requestId), {
origin: 'https://shop.example',
ip,
});
// ... your rules on event.signals and event.signals.suspect_score ...
await kp.events.update(event.request_id, { linkedId: String(account.id) }); // 1 to 128 charactersimport { Knownprint } from '@knownprint/sdk-node';
// rawBody is the exact bytes received, before any JSON parsing.
const envelope = Knownprint.verifyWebhook(
req.headers,
rawBody,
process.env.KNOWNPRINT_WEBHOOK_SECRET,
);The SDK reads no environment variable itself: your code reads its configuration and passes it in.
Client
new Knownprint(options)
new Knownprint(options: KnownprintOptions)
interface KnownprintOptions {
secretKey: string;
baseUrl?: string;
fireOn?: 'account_events' | 'page_views';
consumedIds?: ConsumedIdStore;
timeoutMs?: number;
fetch?: typeof fetch;
now?: () => number;
}| Option | Default | Meaning |
|---|---|---|
secretKey | required | Your secret key, sk_live_... or sk_test_.... It is kept in a private field and sent only in the Authorization: Bearer header. An empty or missing key throws a TypeError. |
baseUrl | a local development address | The API address that comes with your account. Always set it; trailing slashes are removed. |
fireOn | 'account_events' | When your pages identify. 'account_events' is the only value accepted for now; any other throws a TypeError. |
consumedIds | a MemoryConsumedIdStore on this client's clock | Where verifyRequestId records used request ids. Pass a RedisConsumedIdStore when your backend runs more than one process. |
timeoutMs | 5000 | Each request is aborted after this many milliseconds. Must be a positive number, else a TypeError. |
fetch | Node's global fetch | A fetch to send requests with, for example one with your own agent or instrumentation. |
now | Date.now | The clock, in Unix milliseconds, used by verifyRequestId and the default memory store. |
Members of options that the constructor does not know are ignored.
How requests are sent
- Every request sends
Authorization: Bearer <secretKey>,Accept: application/jsonandUser-Agent: knownprint-sdk-node/<version>, plusContent-Type: application/jsonwhen it has a body. - Path parameters are percent-encoded. An empty string,
.or..as a path parameter throws aTypeErrorbefore anything is sent. - Each request is sent once. Nothing is retried, and no
Idempotency-Keyis sent. Retry in your own code where it is safe, and wait forRetry-Afterafter a429. - After
timeoutMsthe request is aborted and the call rejects with the abort'sTimeoutError. A network failure (no answer at all) rejects withfetch's own error. - Any answer other than 2xx rejects with a KnownprintApiError.
events
kp.events.get(requestId: string): Promise<Event1>
kp.events.update(
requestId: string,
patch: { linkedId?: string | null; tags?: Record<string, string | number | boolean> | null },
): Promise<Event1>
kp.events.feedback(
requestId: string,
feedback: { label: 'fraud' | 'legit'; note?: string },
): Promise<Feedback>| Method | Route | Scope | Resolves |
|---|---|---|---|
events.get | GET /v1/events/{request_id} | events:read | The event (Events). |
events.update | PATCH /v1/events/{request_id} | events:write | The updated event. |
events.feedback | POST /v1/events/{request_id}/feedback | events:write | The stored feedback. |
events.get rejects with status 404 when your environment holds no such event (an unknown id, an id of your other environment, or an event past retention), and 409 while a deletion of its visitor is pending.
events.update sends linked_id and tags as you give them: a value sets the field, null clears it, and leaving it out keeps it. Pass at least one. linkedId is a string of 1 to 128 characters: convert a numeric account id with String(). A new linkedId links the event's visitor to that account (Attach your account id and Accounts).
events.feedback labels an event fraud or legit, with an optional note of up to 1,000 characters. It resolves { id, event_id, label, note, created_at } (Feedback).
visitors and linked
kp.visitors.get(visitorId: string): Promise<Visitor1>
kp.visitors.delete(visitorId: string): Promise<unknown> // { job_id, status }
kp.visitors.related(visitorId: string): Promise<RelatedResponse>
kp.linked.related(linkedId: string): Promise<RelatedResponse>| Method | Route | Scope | Resolves |
|---|---|---|---|
visitors.get | GET /v1/visitors/{visitor_id} | events:read | The visitor (Visitors API). |
visitors.delete | DELETE /v1/visitors/{visitor_id} | visitors:delete | The 202 answer unchanged: { job_id, status }, with job_id a del_... id and status queued or running. Typed unknown. |
visitors.related | GET /v1/visitors/{visitor_id}/related | events:read | Account ids and visitors related to this visitor. |
linked.related | GET /v1/linked/{linked_id}/related | events:read | Visitors and account ids related to this account id (Linked accounts API). |
visitors.get with an id that a merge made into an alias answers the visitor that holds it now: its visitor_id and canonical_id are the surviving visitor, not the id you asked for. See Visitor ids may merge.
visitors.delete answers the same way whether the visitor exists or not, and the deletion runs in the background. Deletion calls are limited to 2 per second per key (Limits).
RelatedResponse is { visitors: [{ visitor_id, evidence }], linked_ids: [{ linked_id, evidence }] }, at most 50 of each.
labelledPairs
kp.labelledPairs.create(pair: {
requestIdA: string;
requestIdB: string;
label: 'same' | 'different';
evidence: 'moderator_confirmed' | 'moderator_suspected';
}): Promise<LabelledPair1>POST /v1/labelled-pairs, scope events:write. Records that the two request ids came from one person, for example when a moderator bans an account and names the earlier account it evades a ban for. Use moderator_confirmed only when the moderator is sure. The API accepts label 'same' only and answers 422 validation_failed for 'different' or for two equal request ids. It answers 404 when either event is unknown or past retention, 409 deletion_pending while a deletion of either visitor is pending, and 422 with detail purpose_not_security for an event not collected for security. Labelling a pair that is already labelled replaces its evidence. See Feedback.
verifyRequestId(event, options)
kp.verifyRequestId(event: Event1, options?: VerifyOptions): Promise<Event1>
interface VerifyOptions {
maxAgeMs?: number;
origin?: string;
ip?: string;
minConfidence?: number;
}Resolves the event unchanged when it passes, or rejects with a KnownprintVerifyError whose code names the first check that failed. The checks run in this order:
| Order | Code | Fails when |
|---|---|---|
| 1 | consumed | The store has seen this request_id within maxAgeMs plus 60 seconds. The id is recorded before any other check, so a stale or mismatched attempt also uses it up. |
| 2 | stale | received_at is more than maxAgeMs ago, more than 60 seconds in the future, or unreadable. |
| 3 | replayed | integrity.replayed is true. |
| 4 | origin_mismatch | origin is given and differs from integrity.origin. |
| 5 | ip_mismatch | ip is given and differs from network.ip, or network.ip is null. |
| 6 | low_confidence | minConfidence is given and is above confidence. |
| Option | Default | Meaning |
|---|---|---|
maxAgeMs | 10000 (SDK_FRESHNESS_MS) | How old the event may be, from its received_at. |
origin | not checked | Your page's origin, compared exactly with integrity.origin (for example https://shop.example). |
ip | not checked | The end user's address as your own proxy reports it. |
minConfidence | not checked | The lowest confidence you accept, from 0 to 1. |
Always pass origin and ip in production. For ip, use the entry your own proxy appended to X-Forwarded-For (the last one when your application sits directly behind it) or a header your proxy overwrites, never the first entry, which the client controls. The comparison is exact, so pass the address as knownprint writes it: IPv4 as a dotted quad (not ::ffff:203.0.113.24) and IPv6 in short lower-case form (The visitor address).
If the store fails (for example Redis is down), verifyRequestId rejects with the store's error and never passes the event.
verifyRequestId takes an event you have read, so a backend reads first and verifies second:
import { KnownprintApiError, KnownprintVerifyError } from '@knownprint/sdk-node';
let event = null;
try {
event = await kp.verifyRequestId(await kp.events.get(requestId), { origin, ip });
} catch (error) {
if (error instanceof KnownprintVerifyError) {
console.info('knownprint verification failed:', error.code);
} else if (!(error instanceof KnownprintApiError && [404, 409].includes(error.status))) {
console.warn('knownprint read failed:', error.message); // a 401, 429, 5xx or a timeout
}
}
// event === null: take your missing-id path.Every failure leaves event at null, so a slow or failing read never fails the form; alert on the warnings. A 404 or 409 is treated like a missing request id.
shouldIdentify(page) and fireOn
kp.fireOn: 'account_events'
kp.shouldIdentify(page: 'account_event' | 'page_view'): booleanshouldIdentify('account_event') is true and shouldIdentify('page_view') is false: identify on account events (signup, login, checkout, password reset), not on every page view. Server code that renders pages can use it to decide whether to include the public key and the form helper.
Knownprint.verifyWebhook(headers, rawBody, secret, options)
Knownprint.verifyWebhook(
headers: Record<string, string | string[] | undefined>,
rawBody: string | Uint8Array,
secret: string,
options?: { toleranceSeconds?: number; now?: () => number },
): WebhookEnvelope1A static method: it needs no client. It checks a delivery and returns its envelope, or throws a KnownprintWebhookError with the first check that failed, in this order:
| Order | Code | Fails when |
|---|---|---|
| 1 | missing_header | webhook-id, webhook-timestamp or webhook-signature is missing or empty. Header names match in any case. |
| 2 | timestamp_out_of_tolerance | webhook-timestamp is not a Unix time in seconds within toleranceSeconds of now, either way. |
| 3 | bad_signature | No v1,<base64> entry of webhook-signature equals the HMAC-SHA256 of {webhook-id}.{webhook-timestamp}.{body}, keyed with the base64 decoding of your secret's part after whsec_. Every entry is compared in constant time. |
| 4 | invalid_body | The body is not UTF-8 JSON holding exactly the envelope's fields with v equal to 1 and a known type. |
| Argument | Meaning |
|---|---|
headers | The request headers, as Node gives them (req.headers). Repeated headers are joined with a space. |
rawBody | The exact body received, as a string or bytes. Never pass a body you parsed and serialised again: the signature covers the exact bytes. |
secret | The endpoint's signing secret, whsec_ followed by base64. A secret of another shape throws a TypeError. |
options.toleranceSeconds | Default300 (WEBHOOK_SIGNATURE_TOLERANCE_SECONDS). |
options.now | The clock in Unix milliseconds, default Date.now. |
The envelope is { v, id, type, created_at, environment_id, visitor_id, data }, where type is one of event.identified, visitor.merged, account.linked, account.related_found, visitor.deleted, visitor.unmerged, visitor.split, visitor.suggested and webhook.test. What each carries is on Webhooks.
import express from 'express';
import { Knownprint, KnownprintWebhookError } from '@knownprint/sdk-node';
const app = express();
app.post('/hooks/knownprint', express.raw({ type: 'application/json' }), async (req, res) => {
let envelope;
try {
envelope = Knownprint.verifyWebhook(
req.headers,
req.body,
process.env.KNOWNPRINT_WEBHOOK_SECRET,
);
} catch (error) {
if (error instanceof KnownprintWebhookError) return res.status(401).end();
throw error;
}
if (await alreadyProcessed(envelope.id)) return res.status(204).end();
await handle(envelope); // your code; keep it quick or queue it
res.status(204).end();
});alreadyProcessed and handle are your own code. A delivery can arrive more than once, so record each envelope id you have handled. See Verify webhooks.
Consumed-id stores
verifyRequestId accepts each request id once. The store is where it records the ids it has seen.
interface ConsumedIdStore {
consume(requestId: string, ttlMs: number): Promise<boolean>;
}consume answers true exactly the first time it sees an id within ttlMs, and false after that. verifyRequestId calls it with maxAgeMs + 60000 (70 seconds by default).
MemoryConsumedIdStore
new MemoryConsumedIdStore(options?: { max?: number; now?: () => number })Keeps ids in the process's memory, each until ttlMs after its first use. Past max ids (default 100000, MEMORY_STORE_MAX) the oldest are dropped first. max must be a positive integer.
It is the default store, and it is enough only for a backend that runs as one process. With several processes or hosts, a replayed id could land on a process that has not seen it: use a shared store.
RedisConsumedIdStore
new RedisConsumedIdStore(options: {
setNx: (key: string, ttlMs: number) => Promise<boolean>;
prefix?: string;
})Keeps ids in your own Redis or Valkey. For each id it calls setNx(prefix + requestId, ttlMs), which must store the key only when it is absent, with that expiry, and answer whether it stored it. Keys are kp:sdk:consumed:{request_id} by default (SDK_CONSUMED_ID_PREFIX); pass prefix to share one Redis between several applications. setNx must be a function, else a TypeError.
fromNodeRedis(client)
fromNodeRedis(client: {
set(key: string, value: string, options: { PX: number; NX: true }): Promise<string | null>;
}): (key: string, ttlMs: number) => Promise<boolean>Builds setNx for a redis (node-redis) client: it sends SET key 1 PX <ttlMs> NX and answers true when Redis replies OK. The TTL is rounded up to a whole millisecond.
For another client, write setNx yourself. With ioredis:
import Redis from 'ioredis';
import { RedisConsumedIdStore } from '@knownprint/sdk-node';
const redis = new Redis(process.env.REDIS_URL);
const consumedIds = new RedisConsumedIdStore({
setNx: async (key, ttlMs) => (await redis.set(key, '1', 'PX', Math.ceil(ttlMs), 'NX')) === 'OK',
});Any store with an atomic "set if absent, with expiry" works the same way, such as a database table with a unique key and a cleanup job.
Errors
The SDK throws three error classes. Their messages carry the HTTP status, the error slug or the code only, never a request id, an address, a key or a body, so they are safe to log.
KnownprintApiError
Any answer other than 2xx.
| Field | Type | Meaning |
|---|---|---|
status | number | The HTTP status. |
type | string or null | The problem type URI from the application/problem+json body. |
slug | string or null | The last part of type, such as not_found or rate_limited. |
title | string or null | The problem's short title. |
detail | string or null | The problem's fixed one-sentence explanation. |
requestId | string or null | The id of the failed API request, to quote to your knownprint contact. |
Every field but status is null when the body is not a problem body (for example an HTML error page from a proxy in between). Slugs and statuses are listed on Errors.
KnownprintVerifyError
Thrown by verifyRequestId. code is one of consumed, stale, replayed, origin_mismatch, ip_mismatch and low_confidence (type VerifyErrorCode), as in the table above.
KnownprintWebhookError
Thrown by verifyWebhook. code is one of missing_header, timestamp_out_of_tolerance, bad_signature and invalid_body (type WebhookErrorCode). Answer the delivery with a 4xx status and do not process it.
Visitor ids may merge
A visitor id names one browser on one device as far as knownprint can tell, and what it can tell grows over time. knownprint never renumbers an id it gave you, but it can find later that two visitors are one device (a merge), undo a merge (an unmerge), or find that a visitor was two devices (a split). Each change is announced by a webhook: visitor.merged, visitor.unmerged, visitor.split, and visitor.suggested for a suggestion that changes no id.
So store the visitor id beside your own records, and resolve it when you act on it:
kp.visitors.get(storedId)answers the visitor that holds the id now. Compare itsvisitor_idwith the id you stored: when they differ, the stored id was merged intovisitor_id, and the visitor'saliaseslist the merged ids.- Subscribe to the four change webhooks,
visitor.merged,visitor.unmerged,visitor.splitandvisitor.suggested, and update the ids you stored (Visitors). A suggestion changes no id; it is a lead to review. - An event keeps the visitor id it was answered with, so after a merge
events.getcan name the alias. The visitor read is the current record.
Constants
| Export | Value | Meaning |
|---|---|---|
SDK_FRESHNESS_MS | 10000 | verifyRequestId's default maxAgeMs. |
CLOCK_SKEW_MS | 60000 | How far received_at may be in the future, and how long past maxAgeMs a used id is remembered. |
WEBHOOK_SIGNATURE_TOLERANCE_SECONDS | 300 | verifyWebhook's default toleranceSeconds. |
SDK_CONSUMED_ID_PREFIX | 'kp:sdk:consumed:' | The default key prefix of RedisConsumedIdStore. |
MEMORY_STORE_MAX | 100000 | MemoryConsumedIdStore's default max. |
DEFAULT_TIMEOUT_MS | 5000 | The default timeoutMs. |
DEFAULT_BASE_URL | a local development address | The default baseUrl; set baseUrl to your account's API address instead. |
VERSION | the package version | Also in USER_AGENT. |
USER_AGENT | 'knownprint-sdk-node/<version>' | The User-Agent of every request. |
Exports
| Kind | Names |
|---|---|
| Client | Knownprint |
| Stores | MemoryConsumedIdStore, RedisConsumedIdStore, fromNodeRedis |
| Errors | KnownprintApiError, KnownprintVerifyError, KnownprintWebhookError |
| Constants | SDK_FRESHNESS_MS, CLOCK_SKEW_MS, WEBHOOK_SIGNATURE_TOLERANCE_SECONDS, SDK_CONSUMED_ID_PREFIX, MEMORY_STORE_MAX, DEFAULT_TIMEOUT_MS, DEFAULT_BASE_URL, VERSION, USER_AGENT |
| Types | KnownprintOptions, VerifyOptions, ConsumedIdStore, FireOn, VerifyErrorCode, WebhookErrorCode, and the API shapes Event1, Visitor1, Feedback, RelatedResponse, LabelledPair1, WebhookEnvelope1 |