@camada/node
v0.4.0
Published
camada backend SDK for Node: request capture, inline blocking, first-party beacon serving; Express/Fastify/Nest/Koa adapters
Readme
@camada/node
camada's backend SDK for Node: captures request metadata on response-finish (real status,
latency, and the true wire header order no proxy position can see), enforces the tenant
blocklist inline before your app runs, and serves the fingerprint beacon first-party at
/_cam/b.js + /_cam/fp. Fails open by design: a camada outage or bug never 5xxes your app.
npm install @camada/nodeRequires Node 20 or later.
Quickstart
Env (printed by camada onboarding / npm run seed in dev):
CAMADA_KEY=<ingest_token>.<snap_token>
CAMADA_INGEST_URL=http://localhost:8787 # dev only; defaults to production ingestExpress / Connect
import camada from '@camada/node';
app.use(camada.express()); // before express.json() / urlencoded() and before helmetMount camada first. It still works behind body parsers (it uses the req.body they leave for
its challenge and beacon POSTs) and behind helmet (the challenge page replaces any inherited
Content-Security-Policy with its own), but first is cheapest: a blocked request never pays for
parsing. Under a prefix (app.use('/api', camada.express())) rules and events see the full path
(/api/…), and camada's own endpoints answer under the prefix (/api/_cam/b.js, /api/_cam/fp,
/api/__camada/challenge). The beacon tag (scriptTag()) and the challenge form point under the
prefix too, unless you set scriptPath or challengePath yourself: an explicit path is used
exactly as given. The beacon posts next to its script, so fpPath can stay as it is.
Fastify
import { camadaFastify } from '@camada/node/fastify';
await app.register(camadaFastify);NestJS (default Express platform; on the Fastify platform register the fastify plugin instead)
import { CamadaModule } from '@camada/node/nest';
@Module({ imports: [CamadaModule.forRoot()] }) // Nest ≤10: CamadaModule.forRoot({ routes: '*' })Nest registers its body parsers before module middleware; camada reads what they parsed, so the
default bodyParser: true is fine. Tested on Nest 11. Nest 10 (routes: '*') is checked through
the Express 4 wildcard mount it registers, not against Nest 10 itself.
Koa
import { camadaKoa } from '@camada/node/koa';
app.use(camadaKoa()); // before @koa/bodyparserRegister it first. Behind @koa/bodyparser or koa-bodyparser it reads the form and beacon from
ctx.request.body. Under koa-mount it works like an Express prefix mount: rules and events see the
full path, and its own endpoints answer under the prefix.
What it does per request
- Refreshes the blocklist snapshot off-path (30 s poll, ETag; cold start fails open). Every
poll and event batch carries
x-camada-sdk: @camada/node/<version>. - Resolves the client IP per your tenant's trusted-proxy config — raw
X-Forwarded-Foris never trusted without it (CAMADA_TRUSTED_PROXY=hops:1|cidrs:…|verceloverrides locally). On a unix-socket listener (nginx or Passenger in front) Node has no peer address, so the walk runs without one and trusts the local proxy that owns the socket. A TCP request whose peer is already gone (the client reset the connection) gets no IP: no ip rules, no challenge. - Runs your ordered custom rules (see below), then the allow, block and challenge lists.
Blocked →
403withx-block-reasonbefore your app; the event still ships, withst: 403andblk: <reason>(ip4|ip6|path|rule) so the analyst counts SDK blocks apart from your app's own 403s. - Serves
/_cam/b.js(the beacon, first-party — no third-party domain for ad-blockers or CSP to break) and relays/_cam/fpposts to ingest with the resolved client IP. - Otherwise: sets
x-rid+ the_sfpsession cookie (kept when the app later replaces Set-Cookie throughsetHeader/writeHead), and on response-finish ships one batched, redacted event (Authorization/Cookie values never leave the process; credential-looking query values are scrubbed; see @camada/core). A client that disconnects mid-response still ships its one event, with the status set so far anddurup to the disconnect.
Custom rules
Your Rules page holds one ordered list per project, and this SDK walks it before the allow, block and challenge lists. First match wins — the order is the precedence — and each rule carries one of four actions:
| action | what this SDK does | on the event |
|---|---|---|
| skip | passes the request | nothing |
| block | 403 before your app | blk: "rule", rl: "<rule id>" |
| challenge | serves the proof-of-work page to page loads (challenge: false opts out). A non-HTML request (fetch/XHR/API) is not challenged: it reaches your app with x-camada-challenge: 1 on the response | page: blk: "challenge"; non-HTML: its normal event plus chs: 1 (never sampled out or excluded) |
| warn | passes the request and marks it for the analyst | wrn: "<rule id>" |
A skip rule also carries a record matches flag, which only the analyst reads: a recorded skip is still scored and shows on your dashboard as Allowed, an unrecorded one is dropped before scoring. Either way the request passes here, unstamped — the built-in Allow-list is a skip rule with recording on.
A rule block also names the row that decided, so the response says which rule to edit:
HTTP/1.1 403 Forbidden
x-block-reason: rule
x-block-rule: cr_4f2a9c1b7e03A rule may also test one request header (is, contains or matches), and the header name is
matched case-insensitively against what the client actually sent. Headers belong to the request
plane alone: the analyst never sees them, so it treats a header rule as not matching and only a
v5 SDK like this one enforces it.
The rules ride the v5 snapshot, which this SDK asks for by default. snapshotVersion: 4
pins the allow/challenge lists without the rules, 3 the block list alone; a project that
has not published the container you ask for is answered with the next one down, so asking
for the newest is always safe.
HTML templates add the beacon with the helper (or use @camada/react's <CamadaBeacon/>):
res.send(`<head>${camada.scriptTag(req)}</head>…`);App-context outcomes (the signals no edge tap can see; identifiers are HMAC-hashed in-process):
camada.track(req, 'login_failed', { user: email });The event name is free-form, but the analyst's app-context rules read a fixed vocabulary — use these names and the credential-stuffing, password-spray, account-aggregation, signup-velocity, carding and coupon rules fire on your app's own truth instead of path heuristics:
| event | when |
|---|---|
| login_failed / login_succeeded | a password (or passwordless) login attempt settled; pass { user } so attempts per account can be counted |
| signup | an account was created |
| password_reset | a reset was requested |
| mfa_failed | a second factor was rejected |
| payment_failed / payment_succeeded | a payment authorisation settled |
| coupon_failed | a promo/voucher code was rejected |
TLS fingerprint behind Cloudflare
Node has no TLS handshake to read, but Cloudflare does. Set CAMADA_TLSX_HEADER=x-camada-tlsx
(or createCamada({ tlsxHeader: 'x-camada-tlsx' })) and add a Transform Rule that sets it:
Rules > Transform Rules > Modify Request Header, "Set dynamic", header x-camada-tlsx, value
cf.tls_client_extensions_sha1, on every request. The rule is required and must set
(overwrite) the header: without it a client-sent x-camada-tlsx passes through Cloudflare
untouched. The value feeds the same matcher as @camada/hono's request.cf.tlsClientExtensionsSha1:
the snapshot's tls entries block with x-block-reason: tls, and tlsx is / is_in rule
conditions apply.
This needs Cloudflare to connect to the app directly. The header is believed only in cidrs mode,
when the socket peer is a non-loopback address inside Cloudflare's ranges, because anyone else can
write it:
CAMADA_TRUSTED_PROXY=cidrs:173.245.48.0/20,103.21.244.0/22,… # Cloudflare's published ranges
CAMADA_TLSX_HEADER=x-camada-tlsxEvery range in CAMADA_TRUSTED_PROXY=cidrs:… is trusted to write the header, the same trust it gets
for X-Forwarded-For, so list only Cloudflare's ranges there. A non-Cloudflare proxy range (a docker
bridge, an internal load balancer) would let anyone who reaches that proxy set the fingerprint.
Behind a local reverse proxy (nginx or Caddy on loopback) or a cloudflared tunnel the peer is
loopback, so the header is not read and tlsx conditions fail open; X-Forwarded-For is never
consulted. The same holds in none, hops or vercel mode, from any other peer, with no readable
peer (unix listeners included), or with a malformed value (over 128 characters, outside
[A-Za-z0-9+/=_-], or a repeated header). The Transform Rule must overwrite the header on every
request: on a request it skips, a client-sent value passes through. The same trusted value is sent
to camada as tlsx on request events (pass, block, challenge and upgrade rows); node never adds it
to track() rows or the beacon relay, and a value that failed the checks above is never sent. The
analyst uses it to group traffic by TLS fingerprint and to recommend or block rare fingerprints.
WebSockets
Node hands an upgrade request (a WebSocket handshake) to the server's 'upgrade' listeners,
never to the request handler the middleware runs in, so the middleware alone never sees one.
Pass the server to attach() and each upgrade ships one event with st: 101:
const server = app.listen(3000); // Fastify: app.server · Nest: app.getHttpServer() · Koa: app.listen()
camada.attach(server); // returns the server; calling it twice is harmless
new WebSocketServer({ server }); // ws, socket.io, … attach before or after, either wayIt only observes. The handshake stays your WebSocket library's: camada writes nothing to the
socket, adds no delay, sets no session cookie (the event carries the visitor's existing _sfp),
and never blocks or challenges an upgrade. A server with no 'upgrade' listener of its own
behaves exactly as before. The event is recorded when Node hands the upgrade over, so a
handshake your library then rejects still ships st: 101.
Operational notes
CAMADA_DISABLED=1— kill switch, checked per request.CAMADA_SERVERLESS=1— lazy snapshot refresh (no interval timer); cold invocations fail open and catch up asynchronously. Each request's event (and everytrack()row) is POSTed as the response finishes instead of waiting for the 15 s batch timer, which a frozen function never runs. Pass the platform'swaitUntilso the invocation stays alive for that POST:
Where the platform has noimport { waitUntil } from '@vercel/functions'; const camada = createCamada({ waitUntil }); // also holds the lazy snapshot refresh openwaitUntil, the POST starts before the response completes but can still be frozen mid-flight; use a fetch adapter (@camada/hono,@camada/next) there.- The challenge page sends its own
Content-Security-Policyallowing only its inline script and style bysha256hash, and drops anyContent-Security-Policy(-Report-Only)set before it. - Enforcement scope at this position: IP, path, user-agent and request-header conditions. ASN,
country conditions can't be evaluated in-app and fail open (a rule that needs one never
matches here; run
@camada/honoon Cloudflare Workers for those). TLS-fingerprint conditions match only with the opt-inCAMADA_TLSX_HEADER(see "TLS fingerprint behind Cloudflare"); without it they fail open too. await camada.stop()in your own graceful shutdown stops polling and the event queue. It returns a promise that settles once queued rows (a drain in flight, or rows held by an ingest 429) are sent, or counted as dropped if the send fails; it never rejects.- Memory: ~5 MB per loaded snapshot.
Develop
npm install && npm run build && npm test && npm run checkSibling checkouts of camada-core and camada-browser must exist (file: deps).
