# knownprint in the backend: Node (Express, Fastify, Next.js)

Part of the knownprint quickstart for AI coding agents, Step 6. Read
https://knownprint.com/quickstart.md first: it holds the rules that apply here (never read or print
secrets, ask before touching a live server, an unknown result is never a pass). This file covers the
module that reads the event, runs the six checks and decides, and how to call it from a handler. The
checks and rules it implements are written out in https://knownprint.com/quickstart/other.md.

Use the module as written. It reads `KNOWNPRINT_API`, `KNOWNPRINT_SECRET_KEY` and
`KNOWNPRINT_SITE_ORIGINS`, never logs a request id, an address or a secret, and turns every failure
into an "unknown" result that takes the challenge path.

## The module

Node 18 or later, the built-in `fetch`, and Redis when the app runs more than one process:

```js
// knownprint.js (server)
import { isIP, SocketAddress } from 'node:net';

const API = process.env.KNOWNPRINT_API;
const SECRET_KEY = process.env.KNOWNPRINT_SECRET_KEY;
const SITE_ORIGINS = new Set(
  String(process.env.KNOWNPRINT_SITE_ORIGINS ?? '')
    .split(',')
    .map((origin) => origin.trim())
    .filter(Boolean),
);
const REQUEST_ID = /^evt_[a-z2-7]{26}$/;
const MAX_AGE_MS = 10_000;
const CLOCK_SKEW_MS = 60_000;

// Single use. One process only: with several, replace the body with Redis:
// return (await redis.set(`kp:used:${id}`, '1', { PX: 70_000, NX: true })) !== null;
const used = new Map();
async function useOnce(id) {
  const now = Date.now();
  for (const [key, until] of used) if (until <= now) used.delete(key);
  if (used.has(id)) return false;
  used.set(id, now + MAX_AGE_MS + CLOCK_SKEW_MS);
  return true;
}

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;
  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 visitor's address: the last X-Forwarded-For entry when the peer is the site's own proxy
 * (here on the same host), else the peer itself. Never the first entry.
 */
export function clientIp(peerAddress, forwardedFor) {
  const peer = canonicalIp(peerAddress);
  if (peer === '127.0.0.1' || peer === '::1') {
    const entries = String(forwardedFor ?? '')
      .split(',')
      .map((entry) => entry.trim())
      .filter(Boolean);
    if (entries.length > 0) return canonicalIp(entries[entries.length - 1]);
  }
  return peer;
}

async function call(method, path, body) {
  const res = await fetch(`${API}${path}`, {
    method,
    headers: {
      Authorization: `Bearer ${SECRET_KEY}`,
      Accept: 'application/json',
      ...(body === undefined ? {} : { 'Content-Type': 'application/json' }),
    },
    body: body === undefined ? undefined : JSON.stringify(body),
    signal: AbortSignal.timeout(5_000),
  });
  if (res.status === 404 || res.status === 409) return null;
  if (!res.ok) throw new Error(`knownprint answered ${res.status}`);
  return res.json();
}

/** { ok: true, event } or { ok: false, reason }. Never throws. */
export async function verifyRequestId(requestId, ip) {
  try {
    if (typeof requestId !== 'string' || !REQUEST_ID.test(requestId)) {
      return { ok: false, reason: 'missing' };
    }
    if (!(await useOnce(requestId))) return { ok: false, reason: 'used' };
    const event = await call('GET', `/v1/events/${requestId}`);
    if (event === null) return { ok: false, reason: 'not_found' };
    const age = Date.now() - Date.parse(event.received_at);
    if (!(age <= MAX_AGE_MS && age >= -CLOCK_SKEW_MS)) return { ok: false, reason: 'stale' };
    if (event.integrity.replayed) return { ok: false, reason: 'replayed' };
    if (!SITE_ORIGINS.has(event.integrity.origin)) return { ok: false, reason: 'origin' };
    if (event.network.ip === null || event.network.ip !== canonicalIp(ip)) {
      return { ok: false, reason: 'address' };
    }
    return { ok: true, event };
  } catch (error) {
    console.warn('knownprint:', error.message); // never log the request id or the address
    return { ok: false, reason: 'error' };
  }
}

/** 'allow' | 'challenge' | 'review' | 'block'. Example thresholds: tune them. */
export function decide(result) {
  if (!result.ok) return 'challenge'; // unknown: never allow, never block on this alone
  const s = result.event.signals;
  const score = s.suspect_score?.value ?? null;
  if (s.bot?.value === 'bad') return 'block';
  if (score === null) return 'challenge';
  if (s.tampering?.value === true || score >= 60) return 'review';
  if (score >= 30) return 'challenge';
  return 'allow';
}

/** Attach your account id to the event once the account exists. Never throws. */
export async function linkAccount(requestId, accountId) {
  try {
    await call('PATCH', `/v1/events/${requestId}`, { linked_id: String(accountId) });
  } catch (error) {
    console.warn('knownprint link:', error.message);
  }
}
```

Express:

```js
import express from 'express';
import { clientIp, decide, linkAccount, verifyRequestId } from './knownprint.js';

const app = express();
app.post('/signup', express.urlencoded({ extended: false }), async (req, res) => {
  const ip = clientIp(req.socket.remoteAddress, req.headers['x-forwarded-for']);
  const result = await verifyRequestId(req.body.kp_request_id, ip);
  const decision = decide(result);
  if (decision === 'block') return res.status(403).send('We could not complete this request.');
  // 'challenge' and 'review': continue with your own extra step (email code, manual review).
  const account = await createAccount(req.body, { decision }); // your code
  if (result.ok) await linkAccount(result.event.request_id, account.id);
  res.redirect(303, decision === 'allow' ? '/welcome' : '/verify');
});
```

Next.js App Router (`app/api/signup/route.js`, a Node runtime route). A route handler cannot see
the connection's peer address, so the app must listen only on loopback behind the site's proxy
(`next start -H 127.0.0.1`); then every request came through the proxy, and the code passes the
loopback peer explicitly:

```js
import { clientIp, decide, linkAccount, verifyRequestId } from '@/lib/knownprint';

export async function POST(request) {
  const body = await request.json();
  // Valid only while the app listens on 127.0.0.1 behind the site's own nginx or Caddy.
  const ip = clientIp('127.0.0.1', request.headers.get('x-forwarded-for'));
  const result = await verifyRequestId(body.kp_request_id, ip);
  const decision = decide(result);
  if (decision === 'block') return Response.json({ error: 'refused' }, { status: 403 });
  const account = await createAccount(body, { decision }); // your code
  if (result.ok) await linkAccount(result.event.request_id, account.id);
  return Response.json({ next: decision === 'allow' ? '/welcome' : '/verify' });
}
```

Next: https://knownprint.com/quickstart.md, the end of Step 6.
