BotRampart

Docs · Integration guide

Wiring BotRampart into a Node app.

Everything an application touches: options, route costs, sign-in, challenge handling in the browser, the policy file, logs and failure behaviour. Every HTTP exchange here is defined in the OpenAPI spec, and each sample names the operation it exercises.

Design, not product. This is the interface of the first build as specified; nothing here is published yet. The first build supports Node (Express, Fastify, Next.js). Python and Java SDKs share the same specification and conformance suite and come after.

Backend SDK options

server.js · Node, ExpresssyncInstance

import { botrampart } from "@botrampart/node";

const br = botrampart({
  site: "site_123",
  secretsFile: "/run/secrets/br_keys",   // site signing keys; two accepted at once for rotation
  core: "https://core.internal:8787",
  store: "memory",                        // or a Redis / Valkey client for exact shared budgets
  mode: "observe",                        // "observe" logs decisions; "enforce" applies them
  onCoreDown: "static",                   // keep enforcing the last synced policy
});
app.use(br.express());
OptionDefaultWhat it does
siterequiredSite ID; keys, policy and lake partitions are per site.
secretsFilerequiredHMAC keys that sign the session cookie and proof-of-work puzzles, so tier 1 works with Core unreachable. Alternative: tokens signed by Core with Ed25519, at one Core call per new session.
corenoneCore's URL. Without it the SDK runs alone: tiers 0 and 1, local budgets, the policy file on disk.
store"memory"Where budgets live. In memory, spend across instances is reconciled at each sync, so overspend is bounded by one sync interval; Redis or Valkey makes it exact.
mode"observe"Start every install in observe mode.
onCoreDown"static"Tokens still verify, budgets still count, the last policy still applies. Tier 2 cannot be served, so rules that require it fall back to throttle.

Each instance sends its counters to Core every 5 to 10 seconds and receives policy, directives and revocations in the same call. No per-request record leaves your app; session IDs travel as hashes.

Route costs

Path classes in the policy file cover most routes. Override a single route in code when the cost depends on the request:

Per-route costsredeemChallenge

app.get("/api/search", br.protect({ cost: 5 }), search);

// One GraphQL endpoint: price each operation by what it does
const COST = { ProductPage: 2, SearchProducts: 5, ExportOrders: 50 };
app.post("/graphql", br.protect({ cost: (req) => COST[req.body.operationName] ?? 10 }), graphql);

// A session that cannot pay gets a challenge response; once it passes and redeems,
// the browser SDK retries the request with the new credit.

For responses whose cost is only known afterwards (a report, an export), set BR-Cost on the response; the SDK settles the difference against the session.

res.set("BR-Cost", String(rowsExported / 100));

Signing in

Attach your user's ID once they authenticate. BotRampart stores only a keyed hash of it. Signed-in sessions refill three times faster, are exempt from network mint pressure, and their spend is also summed per account, so one account cannot fan out over many cookies.

Login handlersyncInstance

app.post("/login", async (req, res) => {
  const user = await authenticate(req);
  if (!user) {
    br.track(req, "login_failed");       // feeds credential-stuffing metrics at the next sync
    return res.sendStatus(401);
  }
  br.identify(req, res, user.id);        // stores HMAC-SHA256(site_uid_key, user.id) in the session
  res.json({ ok: true });
});

// In any handler:
// req.br = { sessionId, tier, credits, identified, risk: { score }, ai: {...}, decision: { action, ruleId, ref } }

In the browser

The browser SDK solves the proof-of-work in a Web Worker, collects a small set of interaction counts, and by default wraps fetch and XMLHttpRequest: when a response is a challenge, it runs the challenge and retries the request once.

app.jsgetChallenge

import { BotRampart } from "@botrampart/browser";

const br = BotRampart.init({
  site: "site_123",
  endpoint: "/_br",          // first-party routes mounted by the backend SDK
  mode: "lazy",              // solve in the background; "gate" shows an interstitial first
  autoRetry: true,
  signals: "standard",       // "standard" | "minimal" | "off"
  onBlock(ref) { showSupportMessage(ref); },
});

await br.ready();            // resolves once tier 1 is held
await br.ensure("human");    // step up before a sensitive action, such as opening checkout

If you handle responses yourself, a protected route answers 403 (or 429 with Retry-After for a throttle) with a header BR-Challenge: v1 and this body:

Challenge response from any protected routegetChallenge

HTTP/1.1 403 Forbidden
BR-Challenge: v1
Content-Type: application/json

{ "botrampart": { "v": 1, "action": "challenge", "tier": "human", "ref": "BR-7F3K2Q",
                  "url": "/_br/challenge?c=eyJ0IjoiaHVtYW4ifQ.c2ln", "retry": true } }

Pass the descriptor to br.challenge(), or fetch url yourself: for tier 1 it returns a signed puzzle, for tier 2 a widget URL. The solution or the widget's attestation goes to /_br/redeem:

Redeem a solved puzzleredeemChallenge

POST /_br/redeem
Content-Type: application/json

{ "type": "pow", "challenge": { "id": "ch_9Qx2LmT4vB7sK1aZ", "alg": "pbkdf2-sha256", "puzzles": 16, "...": "..." },
  "solutions": [4121, 977, 15003, 2210, 6431, 88, 3190, 7712, 504, 12880, 2999, 431, 9027, 1666, 5120, 7003],
  "solve_ms": 286 }

200 OK
Set-Cookie: __br_s=br1.…; Path=/; Secure; HttpOnly; SameSite=Lax
{ "ok": true, "tier": 1, "granted": 300, "credits": 300, "expires_at": 1794825300 }

For a page navigation the SDK serves a small interstitial instead, which shows the reference so the visitor can quote it to your support team. That page carries the "Protected by BotRampart" mark in the Community edition.

What the browser SDK collects

ModeCollected
standardCounts of pointer, touch and key events; time to first input; focus and visibility changes; proof-of-work solve time; viewport size class; the automation flag browsers expose.
minimalProof-of-work solve time and one "any input seen" flag.
offNothing beyond the proof-of-work solution.
Never, in any modeCanvas, WebGL or audio fingerprints, font lists, stable device identifiers, keystroke content, pointer coordinates outside the challenge widget.

Sent once per session and per challengepostSignals

POST /_br/signals
{ "mode": "standard", "input_events": 14, "pointer_events": 9, "touch_events": 0, "key_events": 5,
  "first_input_ms": 1840, "automation_flag": false, "viewport_class": "desktop", "pow_solve_ms": 286 }

For EU sites, run signals: "minimal" or "off" and document the cookie as a security measure. France's regulator says anti-robot measures whose sole purpose is securing the site or its sign-in need no consent;1 the cookie and signals must then be used for nothing else. This is an engineering reading, not legal advice.

The policy file

One versioned YAML file per site, kept in Git or edited in the console. Rules are evaluated in order and the first match wins, like Cloudflare's rules. Conditions are written in CEL and compiled by Core into a typed condition tree, which every SDK evaluates with the same small interpreter and the same conformance suite.

botrampart.policy.yaml (abridged)putPolicy

version: 12
path_classes:
  - { name: static,   match: ["/assets/*", "*.css", "*.js", "*.png"], cost: 0,  min_tier: 0 }
  - { name: general,  match: ["/*"],                                  cost: 1,  min_tier: 0 }
  - { name: search,   match: ["/api/search*"],                        cost: 5,  min_tier: 1 }
  - { name: login,    match: ["POST /login"],                         cost: 10, min_tier: 1 }
  - { name: checkout, match: ["/api/checkout*"],                      cost: 20, min_tier: 1 }
budget:
  refill_per_min: 20
  burst: 300
  provisional: 30
  grants: { pow: 300, human: 3000, step_up: 6000 }
  grant_decay: 0.5
  identified_multiplier: 3
mint: { ip: 20, prefix: 60, asn: baseline_x5 }
rules:
  - { id: verified-bots, when: "net.verified_bot in ['search_engine', 'monitoring']", then: allow }
  - { id: not-a-browser, when: "!ua.is_browser || ua.browser_age_years > 3", then: block }
  - { id: risk-5,        when: "risk.score >= 5", then: "challenge(human)" }
  - { id: ai-escalation, when: "ai.attack >= 0.9 && ai.confidence >= 0.7 && request.path_class in ['search', 'login']",
                         then: "log" }      # shadow first: change to challenge(human) later
  - { id: over-budget,   when: "session.credits < request.cost", then: "challenge(next_tier) || throttle" }
  - { id: default,       when: "true", then: allow }
FieldsExamplesFrom
request.*path_class, cost, methodThe request and your path classes
session.*tier, age, credits, identified, network_changes_1hThe cookie and the local budget
ua.*is_browser, family, browser_age_yearsUser agent, parsed against a bundled release table
net.*mint_pressure, verified_bot, country, asn_classMint buckets, crawler verification
signals.*automation_flag, no_input_after_30_requestsBrowser SDK, checked on the server
risk.score0 to 10A visible scorecard in the same file, every line editable
ai.*attack, risk_level, intent, action, confidenceThe five-minute loop, with expiry (shadow in the first build)

Actions: allow, log, challenge(pow | human | next_tier), pow(multiplier), throttle, block, degrade (tell your app to serve a cheaper response) and add_risk(n). A rule can run as log for a week before it enforces. Publishing creates an immutable version that SDKs pick up at the next sync; rollback is publishing the previous one. Always simulate first (example).

Logs and headers

The cookie is a bearer credential and must never reach a log. The SDK instead adds two response headers your edge can log and strip: BR-Sid, the first 12 hex characters of a hash of the session ID, and BR-Decision. A path that shows up in your access logs without BR-Decision is a route the SDK does not cover, which is how br doctor finds gaps.

log_format br escape=json '{"time":"$time_iso8601","path":"$uri","status":$status,'
  '"br_sid":"$upstream_http_br_sid","br_decision":"$upstream_http_br_decision"}';
proxy_hide_header BR-Sid;
proxy_hide_header BR-Decision;

Edge cases

SituationWhat to do
Publicly cacheable pagesThe SDK never sets the cookie on a response marked publicly cacheable, so your CDN can still cache it; the browser SDK starts the session through /_br.
An API on another originSet the cookie Domain for sibling subdomains, or send the token in a header for cross-origin calls.
WebSockets and streamsVerified at the upgrade, charged by connection time, re-verified on a timer.
Webhooks, partner APIs, mobile appsAdd a rule that allows requests authenticated by your own API key or signature before the over-budget rule.
SDK error or missing configurationFail mode per route: open for content, closed for login, sign-up and checkout.
Clock skew and key rotation60 seconds of tolerance; two keys accepted during rotation.

Testing your integration

  • Run CI and staging in observe mode, and assert on req.br.decision in your own tests.
  • Replay a draft policy against production traffic with simulatePolicy before every publish.
  • Look up any decision a tester saw by its reference with getDecision (example).

Sources

Every figure from someone else on this page, with the words it rests on. Checked on the date shown; the full ledger is claims.yaml.

  1. CNIL: Questions-réponses, cookies et autres traceurs (Q17). Lorsque ces solutions ont pour seule finalité la sécurisation du site ou d’un mécanisme d’authentification au bénéfice des utilisateurs, le consentement des utilisateurs n’est pas nécessaire. Checked 2026-11-18.