knownprintDocs

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

Shell
npm install @knownprint/sdk-node

The 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

knownprint.js
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) }),
});
signup.js
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 characters
webhooks.js
import { 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)

TypeScript
new Knownprint(options: KnownprintOptions)

interface KnownprintOptions {
  secretKey: string;
  baseUrl?: string;
  fireOn?: 'account_events' | 'page_views';
  consumedIds?: ConsumedIdStore;
  timeoutMs?: number;
  fetch?: typeof fetch;
  now?: () => number;
}
OptionDefaultMeaning
secretKeyrequiredYour 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.
baseUrla local development addressThe 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.
consumedIdsa MemoryConsumedIdStore on this client's clockWhere verifyRequestId records used request ids. Pass a RedisConsumedIdStore when your backend runs more than one process.
timeoutMs5000Each request is aborted after this many milliseconds. Must be a positive number, else a TypeError.
fetchNode's global fetchA fetch to send requests with, for example one with your own agent or instrumentation.
nowDate.nowThe 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/json and User-Agent: knownprint-sdk-node/<version>, plus Content-Type: application/json when it has a body.
  • Path parameters are percent-encoded. An empty string, . or .. as a path parameter throws a TypeError before anything is sent.
  • Each request is sent once. Nothing is retried, and no Idempotency-Key is sent. Retry in your own code where it is safe, and wait for Retry-After after a 429.
  • After timeoutMs the request is aborted and the call rejects with the abort's TimeoutError. A network failure (no answer at all) rejects with fetch's own error.
  • Any answer other than 2xx rejects with a KnownprintApiError.

events

TypeScript
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>
MethodRouteScopeResolves
events.getGET /v1/events/{request_id}events:readThe event (Events).
events.updatePATCH /v1/events/{request_id}events:writeThe updated event.
events.feedbackPOST /v1/events/{request_id}/feedbackevents:writeThe 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

TypeScript
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>
MethodRouteScopeResolves
visitors.getGET /v1/visitors/{visitor_id}events:readThe visitor (Visitors API).
visitors.deleteDELETE /v1/visitors/{visitor_id}visitors:deleteThe 202 answer unchanged: { job_id, status }, with job_id a del_... id and status queued or running. Typed unknown.
visitors.relatedGET /v1/visitors/{visitor_id}/relatedevents:readAccount ids and visitors related to this visitor.
linked.relatedGET /v1/linked/{linked_id}/relatedevents:readVisitors 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

TypeScript
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)

TypeScript
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:

OrderCodeFails when
1consumedThe 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.
2stalereceived_at is more than maxAgeMs ago, more than 60 seconds in the future, or unreadable.
3replayedintegrity.replayed is true.
4origin_mismatchorigin is given and differs from integrity.origin.
5ip_mismatchip is given and differs from network.ip, or network.ip is null.
6low_confidenceminConfidence is given and is above confidence.
OptionDefaultMeaning
maxAgeMs10000 (SDK_FRESHNESS_MS)How old the event may be, from its received_at.
originnot checkedYour page's origin, compared exactly with integrity.origin (for example https://shop.example).
ipnot checkedThe end user's address as your own proxy reports it.
minConfidencenot checkedThe 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:

JavaScript
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

TypeScript
kp.fireOn: 'account_events'
kp.shouldIdentify(page: 'account_event' | 'page_view'): boolean

shouldIdentify('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)

TypeScript
Knownprint.verifyWebhook(
  headers: Record<string, string | string[] | undefined>,
  rawBody: string | Uint8Array,
  secret: string,
  options?: { toleranceSeconds?: number; now?: () => number },
): WebhookEnvelope1

A 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:

OrderCodeFails when
1missing_headerwebhook-id, webhook-timestamp or webhook-signature is missing or empty. Header names match in any case.
2timestamp_out_of_tolerancewebhook-timestamp is not a Unix time in seconds within toleranceSeconds of now, either way.
3bad_signatureNo 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.
4invalid_bodyThe body is not UTF-8 JSON holding exactly the envelope's fields with v equal to 1 and a known type.
ArgumentMeaning
headersThe request headers, as Node gives them (req.headers). Repeated headers are joined with a space.
rawBodyThe exact body received, as a string or bytes. Never pass a body you parsed and serialised again: the signature covers the exact bytes.
secretThe endpoint's signing secret, whsec_ followed by base64. A secret of another shape throws a TypeError.
options.toleranceSecondsDefault300 (WEBHOOK_SIGNATURE_TOLERANCE_SECONDS).
options.nowThe 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.

webhooks.js
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.

TypeScript
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

TypeScript
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

TypeScript
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)

TypeScript
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:

JavaScript
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.

FieldTypeMeaning
statusnumberThe HTTP status.
typestring or nullThe problem type URI from the application/problem+json body.
slugstring or nullThe last part of type, such as not_found or rate_limited.
titlestring or nullThe problem's short title.
detailstring or nullThe problem's fixed one-sentence explanation.
requestIdstring or nullThe 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 its visitor_id with the id you stored: when they differ, the stored id was merged into visitor_id, and the visitor's aliases list the merged ids.
  • Subscribe to the four change webhooks, visitor.merged, visitor.unmerged, visitor.split and visitor.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.get can name the alias. The visitor read is the current record.

Constants

ExportValueMeaning
SDK_FRESHNESS_MS10000verifyRequestId's default maxAgeMs.
CLOCK_SKEW_MS60000How far received_at may be in the future, and how long past maxAgeMs a used id is remembered.
WEBHOOK_SIGNATURE_TOLERANCE_SECONDS300verifyWebhook's default toleranceSeconds.
SDK_CONSUMED_ID_PREFIX'kp:sdk:consumed:'The default key prefix of RedisConsumedIdStore.
MEMORY_STORE_MAX100000MemoryConsumedIdStore's default max.
DEFAULT_TIMEOUT_MS5000The default timeoutMs.
DEFAULT_BASE_URLa local development addressThe default baseUrl; set baseUrl to your account's API address instead.
VERSIONthe package versionAlso in USER_AGENT.
USER_AGENT'knownprint-sdk-node/<version>'The User-Agent of every request.

Exports

KindNames
ClientKnownprint
StoresMemoryConsumedIdStore, RedisConsumedIdStore, fromNodeRedis
ErrorsKnownprintApiError, KnownprintVerifyError, KnownprintWebhookError
ConstantsSDK_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
TypesKnownprintOptions, VerifyOptions, ConsumedIdStore, FireOn, VerifyErrorCode, WebhookErrorCode, and the API shapes Event1, Visitor1, Feedback, RelatedResponse, LabelledPair1, WebhookEnvelope1