# SecureNow SDK — Agent Skill

> **Node.js security:** Use a supported, patched runtime: Node.js 22.23.4+, 24.22.1+, or 26.12.1+ on its respective release line. Earlier patches are affected by [CVE-2026-111497](https://nodejs.org/en/blog/vulnerability/october-2026-security-releases). Upgrading the SecureNow package does not patch Node.js; upgrade the runtime and restart every application process.

The integration playbook for the `securenow` npm package. A coding agent that reads only this file can plug SecureNow into a Node.js app, turn on every feature, deploy it and prove it works. It describes 8.26.0; items marked **(8.25.0+)** or **(8.26.0+)** are new in that version, so an older install needs `npm install securenow@latest` for them (check with `npx securenow version`). The terminal reference is [SKILL-CLI.md](./SKILL-CLI.md). Both files ship in `node_modules/securenow/`.

## Rules for the agent

1. Never print, paste or commit `.securenow/admin.json`, `.securenow/runtime.json` or `.securenow/credentials*.json`: they hold the admin token and the runtime API key (`snk_live_...`). Mask keys in summaries.
2. Start authentication only with `npx securenow login` from the project root, then wait for the person to finish the browser step. Never open an auth URL yourself (the CLI generates the callback and state).
3. Configuration lives in `.securenow/runtime.json`. The SDK reads exactly two environment variables, `SECURENOW_CREDENTIALS` and `SECURENOW_DISABLED`. Every other `SECURENOW_*` variable (`SECURENOW_APPID`, `SECURENOW_API_KEY`, `SECURENOW_INSTANCE`, `SECURENOW_NO_UUID`, `SECURENOW_LOGGING_ENABLED`, `SECURENOW_CAPTURE_BODY`, ...) is ignored, whatever an older guide says. Do not create `.env` files for SecureNow.
4. Ask the person before anything that changes enforcement in production: blocks, allowlist entries, rate limits, challenges, session revocations, rule promotion, blocking mode. CLI writes reach the running app within about 10 seconds; MCP writes need `confirm: true` and a reason.
5. Put the preload on the command that actually starts the server process (start script, Dockerfile `CMD`, PM2 `node_args`, systemd `ExecStart`). Keep the project's existing middleware, instrumentation and scripts.
6. Confirm any CLI command or flag with `npx securenow help <command>` (works offline). Don't invent URLs or ports: smoke-test only a URL the project or the person gives you.

## 1. Your stack → what to do

| Your stack | Wire it with | Section |
|---|---|---|
| Express, Fastify, NestJS, Koa, Hapi, Hono (`@hono/node-server`), Polka, Feathers, h3, raw `http`/`https`/`http2`, any server on `node:http` | `node -r securenow/register <entry>`, the same flag for CommonJS, ESM and TypeScript | 3.0–3.11 |
| Next.js 15 or 16 | `npx securenow init` (writes `instrumentation.ts`, patches `next.config.*`) | 3.12 |
| Next.js 14 | `npx securenow init` **(8.25.0+)** | 3.13 |
| Nuxt 3 or 4 | `modules: ['securenow/nuxt']` in `nuxt.config`, then `npx securenow init` | 3.14 |
| Vite (`vite preview`, a Vite SSR server) | `node -r securenow/register-vite ...` or `-r securenow/register` | 3.15 |
| Bun 1.3, app served through `node:http` | `bun --preload securenow/register app.js` | 3.16 |
| IP blocking only, no telemetry | `node -r securenow/firewall-only <entry>` | 3.17 |
| PM2, Docker, Kubernetes, systemd, Railway/Render/Heroku/Fly, Vercel | the wiring above, plus production credentials | 6 |
| Deno, Cloudflare Workers, Vercel Edge / Next.js Edge runtime, `Bun.serve`, browser-only apps | not supported: SecureNow runs inside a Node.js process | 9 |
| AWS Lambda and other serverless functions | not supported or tested: don't promise it | 9 |

## 2. Setup checklist

1. **Install.** `npm install securenow@latest` (or the project's package manager), then `npx securenow version`.
2. **Log in.** `npx securenow login` from the project root. The person picks or creates the app in the browser. It writes `.securenow/runtime.json` (app key, runtime API key, SDK config) and `.securenow/admin.json` (CLI/MCP auth) and adds both to `.gitignore` without ignoring the whole `.securenow/` folder. One lane at a time: `npx securenow app connect` (runtime only) or `npx securenow admin login` (admin only). Check with `npx securenow whoami`.
3. **Init.** `npx securenow init` detects the framework (Next.js, Nuxt, Express, Fastify, Koa, Hapi, otherwise plain Node), fills `.securenow/runtime.json` with defaults and an explanation for each key (`deploymentEnvironment: "local"`; change it with `--env staging` etc.), writes `instrumentation.ts` and patches `next.config.*` for Next.js, prints the start-script change for plain Node, reminds you to add the module for Nuxt, and warns about a PM2 ecosystem file that uses a bare `-r securenow/register`. When an instrumentation file or config is too custom to patch, it prints an agent-ready prompt with the exact edits instead.
4. **Wire.** Section 3 for the stack.
5. **Deploy credentials.** `npx securenow credentials runtime --env production` writes `.securenow/credentials.production.json`. Ship it as `<app-root>/.securenow/credentials.json` (secret file or mount), or, on hosts without file mounts, print it as one variable with `--format env` and store `SECURENOW_CREDENTIALS` as a secret (section 6).
6. **Verify.** `npx securenow whoami`, `npx securenow doctor`, `npx securenow test-span`, start the app and read its `[securenow]` lines, send one real request, then `npx securenow status` and `npx securenow today` (section 7).

## 3. Wiring per framework

Every server built on `node:http` is covered by one preload: tracing, logs, header and body capture, crash capture, the firewall, rate limits, challenges and, **(8.25.0+)**, the zero-code session guard. No application code changes.

```json
{
  "scripts": {
    "start": "node -r securenow/register src/index.js",
    "dev": "node -r securenow/register --watch src/index.js"
  }
}
```

Other ways to load the same preload:

- `npx securenow run src/index.js`: spawns Node with the preload (and the ESM hook for ESM apps) and passes Node flags through (`--watch`, `--inspect`). `npx securenow src/index.js` is a shorthand.
- `NODE_OPTIONS="-r securenow/register" npm start`, when the start command can't be edited. Every Node process started with that variable loads SecureNow, npm itself included, so prefer the flag in the script.
- CommonJS only: `require('securenow/register');` as the very first line of the entry file, before any other `require`.

### 3.0 CommonJS, ESM and TypeScript

- **CommonJS:** the `-r` flag, or the first-line `require`.
- **ESM** (`"type": "module"` or an `.mjs` entry): use the `-r` flag. It registers the OpenTelemetry ESM hook through `module.register()` (Node 20.6+) and prints `[securenow] ESM loader hook auto-registered (module.register)`. Don't `import 'securenow/register'` inside the app: static imports load before it runs, so Express, pg and the rest are not instrumented.
- **TypeScript:** `node -r securenow/register --import tsx src/index.ts`, or `node -r securenow/register -r ts-node/register src/index.ts` (SecureNow first), or run the compiled output: `node -r securenow/register dist/index.js`. Types ship for `securenow/events`, `securenow/sessions`, `securenow/tracing`, `securenow/nextjs`, `securenow/nuxt`.

### 3.1 Express

```js
// src/index.js: no SecureNow code
const express = require('express');
const app = express();
app.use(express.json()); // SecureNow records the body the app reads
app.post('/api/login', (req, res) => res.json({ ok: true }));
app.listen(3000);
```

Start with `node -r securenow/register src/index.js`. Records `http.route` (`/users/:id`). One span per middleware is off by default (`config.otel.middlewareSpans`). Tested on Express 4.22 and 5.3 (CommonJS, ESM, tsx, `NODE_OPTIONS`, `securenow run`).

### 3.2 Fastify

Start with `node -r securenow/register server.js`. The route template (`http.route`, span name `GET /users/:id`) and handler exceptions come from Fastify's `fastify.initialization` diagnostics channel. Tested on Fastify 5.12.

### 3.3 NestJS

```bash
npm run build && node -r securenow/register dist/main.js     # compiled (production)
node -r securenow/register -r ts-node/register src/main.ts   # TypeScript directly
```

`-r securenow/register` goes before `-r ts-node/register`. Records `http.route`. Tested on NestJS 11.2 with the default Express adapter.

### 3.4 Koa

Start with the preload. `http.route` needs `@koa/router`; body capture needs a body parser (`koa-bodyparser` or `@koa/bodyparser`), because SecureNow records the body as the app reads it. Tested on Koa 3.3 with `@koa/router`.

### 3.5 Hapi

Start with the preload. Records `http.route`. Tested on Hapi 21.4.

### 3.6 Hono (`@hono/node-server`)

```js
// app.mjs
import { serve } from '@hono/node-server';
import { Hono } from 'hono';

const app = new Hono();
app.get('/users/:id', (c) => c.json({ id: c.req.param('id') }));
serve({ fetch: app.fetch, port: 3000 });
```

Start with `node -r securenow/register app.mjs`. Only Hono served by `@hono/node-server` is covered (not `Bun.serve`, Deno or Workers). `http.route` and handler exceptions (5xx, with their stack) on the request span **(8.25.0+)**; before, spans show the raw path. Tested on Hono 4.

### 3.7 Polka

Start with the preload. Polka has no body parser: add one for body capture. Pass errors to `next(err)`; a thrown error crashes Polka. `http.route` and `next(err)` exceptions on the span **(8.25.0+)**. Tested on Polka 0.5.

### 3.8 Feathers

Feathers 5 with the Express (`@feathersjs/express`) or Koa transport: start with the preload. `http.route` and 5xx service errors on the span **(8.25.0+)**. Tested on Feathers 5.0.

### 3.9 h3

```js
const http = require('http');
const { createApp, createRouter, defineEventHandler, toNodeListener } = require('h3');

const app = createApp();
const router = createRouter().get('/users/:id', defineEventHandler((event) => ({ id: event.context.params.id })));
app.use(router);
http.createServer(toNodeListener(app)).listen(3000);
```

Start with the preload. `http.route` and handler exceptions on the span **(8.25.0+)**. Tested on h3 1.15. Nitro inside Nuxt: section 3.14.

### 3.10 Raw `http`, `https`, `http2`

Start with the preload. `http.createServer`, `https.createServer` and the HTTP/2 compatibility API (the `'request'` event) are covered; an HTTP/2 server driven only by raw `'stream'` events is not. Spans carry the raw path (no route templates).

### 3.11 Other servers on `node:http`

Any framework that ends in a `node:http` server gets traces, capture and the firewall from the preload. Only the frameworks above are tested, and others show the raw path instead of a route template.

### 3.12 Next.js 15 and 16 (App Router and Pages Router)

Run `npx securenow init`. It writes `instrumentation.ts` (`.js` when there is no `tsconfig.json`):

```ts
export async function register() {
  if (process.env.NEXT_RUNTIME === 'nodejs') {
    try {
      const securenowNext = await import('securenow/nextjs');
      const registerSecureNow = securenowNext.registerSecureNow || securenowNext.default?.registerSecureNow;
      registerSecureNow({ captureBody: true });
      await import('securenow/nextjs-auto-capture');
    } catch (error) {
      console.error('[securenow] SecureNow did not start; the app is running without it:', error);
    }
  }
}
```

and patches `next.config.*` (or creates `next.config.mjs`):

```js
/** @type {import('next').NextConfig} */
const nextConfig = {
  serverExternalPackages: ['securenow'],
  outputFileTracingIncludes: {
    '/*': ['./node_modules/securenow/**/*'],
  },
};

export default nextConfig;
```

- Keep the imports inside the `nodejs` block, with no `webpackIgnore` comment and no early `return`. Next.js then drops them from the Edge build and traces `securenow` and its dependencies into `output: 'standalone'`. The `try/catch` keeps the app serving if SecureNow can't start.
- **`src/` layout:** Next.js loads the instrumentation file from the folder that holds `app/` or `pages/`. With `src/app` or `src/pages`, `init` writes `src/instrumentation.ts` **(8.25.0+; before, it wrote the project root, which Next.js 14 and 15 never load there)** and moves a root file it generated earlier. `--src`/`--root` force the folder, `--ts`/`--js` the language, and `--force` replaces an existing file (the old one is kept as `.bak`).
- Re-running `init` replaces an instrumentation file that `init` generated before 8.24.0 (its `webpackIgnore` imports left OpenTelemetry out of standalone images and every request returned 500). A file you edited is left alone and `init` prints the merge prompt.
- `registerSecureNow(options?)` accepts `{ captureBody?, serviceName?, endpoint?, environment?, noUuid? }`. Leave `serviceName` and `noUuid` alone: the dashboard finds the app by `service.name`, which must equal the app key.
- Captured: HTTP server spans with client IP, redacted headers and bodies (JSON, form, GraphQL, multipart metadata), console logs, the firewall, rate limits and challenges. `http.route` on the HTTP span **(8.25.0+)**; before, Next.js 16 put it on Next's own span and Next.js 15 recorded `next.route`.
- The Edge runtime is not instrumented: `middleware.ts` on the Edge and routes with `export const runtime = 'edge'` get nothing. Node.js route handlers, server components and API routes are covered.
- Works with `next start` and `output: 'standalone'`, built with Turbopack or webpack. Standalone and Vercel: section 6.
- You don't need `securenow/nextjs-middleware` or `securenow/nextjs-wrapper`: since 8.24.0 bodies are captured at the HTTP layer, and `securenow/nextjs-auto-capture` (imported above) is only a fallback.

### 3.13 Next.js 14 (8.25.0+)

`npx securenow init` writes the same instrumentation file. A new config is:

```js
/** @type {import('next').NextConfig} */
const nextConfig = {
  experimental: {
    instrumentationHook: true,
    serverComponentsExternalPackages: ['securenow'],
    outputFileTracingIncludes: {
      '/*': ['./node_modules/securenow/**/*'],
    },
  },
};

export default nextConfig;
```

With an existing config, `init` prints these exact edits (Next.js 14 keeps the three keys under `experimental`). Tested on Next.js 14.2 with `next start` and standalone output.

### 3.14 Nuxt 3 and 4

```ts
// nuxt.config.ts
export default defineNuxtConfig({
  modules: ['securenow/nuxt'],
});
```

Then run `npx securenow init` to fill `.securenow/runtime.json`.

- The module keeps `securenow` external (Nitro copies it, with its dependencies, into `.output/server/node_modules`) and adds a Nitro plugin that loads the same runtime as `-r securenow/register`, plus `http.route` from the matched route and handler errors as exceptions.
- No `securenow: { ... }` options in `nuxt.config`: they are ignored, with a build warning. Settings live in `.securenow/runtime.json`.
- Production: `node .output/server/index.mjs`, with `.securenow/credentials.json` in the folder you start it from, or `SECURENOW_CREDENTIALS`.
- `nuxt dev` is traced too. Its requests come through Nuxt's dev proxy: the client IP is known from 8.25.0 (before, it was unknown, so IP blocking only applied to the built server).
- Without the module: `node -r securenow/register .output/server/index.mjs`.
- Tested on Nuxt 3.21 and 4.6 (module, `.output` copied on its own as in a Docker image, `nuxt dev`, `-r` preload).

### 3.15 Vite

Browser telemetry is not sent to SecureNow (browser ingestion is disabled since 8.0, and `securenow/web-vite` sends nothing). Instrument the Node process that serves the app:

```bash
node -r securenow/register-vite node_modules/vite/bin/vite.js preview
node -r securenow/register server.js   # a Vite SSR server (Express + Vite middleware, ...)
```

`securenow/register-vite` is the same runtime as `securenow/register`. A static build served by nginx or a CDN has no Node process to protect; wire SecureNow into its API server instead.

### 3.16 Bun

```bash
bun --preload securenow/register app.js
```

For apps served through `node:http` (tested: Express 5 on Bun 1.3). `Bun.serve` is not traced or protected.

### 3.17 Firewall only

```bash
node -r securenow/firewall-only src/index.js
npx securenow run --firewall-only src/index.js
```

Blocklist, allowlist, scoped blocks, rate limits, challenges and, **(8.25.0+)**, the zero-code session guard. No traces, no logs, no OpenTelemetry. It needs the runtime API key like the full preload.

## 4. Configuration: `.securenow/runtime.json`

### File anatomy

```json
{
  "apiKey": "snk_live_...",
  "app": { "key": "<app-uuid>", "name": "my-api" },
  "config": {
    "runtime": { "deploymentEnvironment": "local" },
    "logging": { "enabled": true },
    "capture": { "body": true, "multipart": true, "maxBodySize": 10240, "sensitiveFields": [] },
    "networking": { "trustedProxies": [] },
    "firewall": { "failMode": "open" }
  }
}
```

- `apiKey`: the app-scoped runtime key (scopes `traces:write`, `logs:write`, `firewall:read`, `blocklist:read`, `allowlist:read`). Without it the ingest accepts nothing and the firewall does not start. Rotate it with `npx securenow api-key create` or `npx securenow api-key set snk_live_...`.
- `app.key`: the app's UUID. It becomes `service.name`, which the dashboard matches exactly.
- `_securenow`: a schema version and an explanation for every key, written by `init`. Leave it.
- A key you leave out takes its default. `app.instance` in older files is ignored (use `config.otel.endpoint`).

### Where the SDK looks (first match wins, files are never merged)

1. `SECURENOW_CREDENTIALS`: the same JSON, raw or base64.
2. A project file. The SDK searches the working directory (and npm's `INIT_CWD`) and the entry script's folder, then each of their parent folders; under PM2 it searches the app folder PM2 recorded and the script's folder instead. In each folder the order is `.securenow/runtime.json`, `.securenow/credentials.json`, then `credentials.staging.json`, `credentials.production.json`, `credentials.preview.json`, `credentials.local.json`, `credentials.test.json`, `credentials.development.json`, `credentials.dev.json`, `credentials.prod.json`.
3. The same names in `~/.securenow/`.

So a `runtime.json` left on a server beats the `credentials.production.json` next to it, and `credentials.staging.json` beats `credentials.production.json`. The startup line says which source won: `credentials=/srv/app/.securenow/credentials.json` or `credentials=env:SECURENOW_CREDENTIALS` (printed by `-r securenow/register` and Nuxt; Next.js prints `service.name` and `Environment` lines instead).

### Every key (all under `config` except `apiKey` and `app`)

| Key | Default | Change it when |
|---|---|---|
| `logging.enabled` | `true` | You don't want `console.*` exported as logs (crash capture needs it on) |
| `logging.redact` | `true` | **(8.25.0+)** You need log lines exported exactly as written (redaction replaces credential fields and secret shapes with `[REDACTED]`) |
| `capture.body` | `true` | Bodies must never leave the process. Detections then lose body payloads |
| `capture.multipart` | `true` | You don't want multipart field values and file metadata (file content is never captured) |
| `capture.maxBodySize` | `10240` bytes (minimum 1024) | Your JSON bodies are larger: bigger bodies are recorded as `[TOO LARGE: <n> bytes]` |
| `capture.sensitiveFields` | `[]` | You have extra field names to redact (added to the built-ins; also applied to header names) |
| `otel.endpoint` | `null` = `https://ingest.securenow.ai` | Advanced: sending to your own OTLP collector (the SecureNow dashboard then sees nothing) |
| `otel.tracesEndpoint`, `otel.logsEndpoint` | `null` | Advanced: split collectors |
| `otel.headers` | `{}` | Extra OTLP headers. App key, auth and environment headers are added for you |
| `otel.logLevel` | `"error"` | `debug` while troubleshooting; `none` hides export errors |
| `otel.disableInstrumentations` | `[]` | You want to skip an instrumentation: full package names, e.g. `"@opentelemetry/instrumentation-dns"` |
| `otel.middlewareSpans` | `false` | You want one span per Express/Koa middleware per request (high volume, no detection uses them) |
| `runtime.deploymentEnvironment` | `"production"` (`init` writes `"local"`) | Every deployment: `production`, `staging`, `preview`, `local`, `test`... (`dev`/`development` become `local`, `prod` becomes `production`) |
| `runtime.noUuid` | `null` = automatic (one service name for every worker when `app.key` is set) | Never: `false` adds a per-process suffix and the dashboard no longer finds the app |
| `runtime.strict` | `false` | PM2/cluster workers should exit when no app identity resolves |
| `runtime.testSpan` | `false` | You want a `securenow.startup.smoke` span at every boot (`npx securenow test-span` is usually better) |
| `networking.trustedProxies` | `[]` | A load balancer, CDN or proxy with a public address sits in front of the app: IPv4/IPv6 addresses, CIDRs (IPv6 ranges 8.25.0+) or `"cloudflare"` |
| `firewall.failMode` | `"open"` | `"closed"`: every request gets 403 until the first sync succeeds |
| `firewall.statusCode` | `403` | You want another status for blocked requests |
| `firewall.log` | `true` | You want no firewall lines in the console (this also hides the startup `Firewall:` lines) |
| `firewall.tcp` | `false` | Layer 2: drop blocked clients at the TCP connection (direct connections only) |
| `firewall.iptables` | `false` | Layer 3: kernel DROP (Linux, root or `CAP_NET_ADMIN`) |
| `firewall.cloud` | `null` | Layer 4: `"cloudflare"`, `"aws"` or `"gcp"` |
| `firewall.cloudDryRun` | `false` | Log the WAF pushes without applying them |
| `firewall.cloudflare.apiToken`, `.accountId` | `null` | Layer 4 on Cloudflare (secret) |
| `firewall.aws.wafIpSetId`, `.wafIpSetName`, `.wafScope` | `null`, `"securenow-blocklist"`, `"REGIONAL"` | Layer 4 on AWS WAF (`npm i @aws-sdk/client-wafv2`; AWS credentials from the standard chain) |
| `firewall.gcp.projectId`, `.securityPolicy` | `null` | Layer 4 on Cloud Armor (`npm i @google-cloud/compute`) |
| `firewall.rateLimitStore` | `null` (each process counts alone) | Several workers or servers must share rate-limit counters: `"redis://host:6379"` or `rediss://...` |
| `firewall.versionCheckInterval` | `10` seconds | `1`–`2` for near-instant propagation of blocks (unchanged checks are a cheap 304) |
| `firewall.syncInterval` | `3600` seconds | Safety-net full resync; rarely changed |
| `firewall.apiUrl` | SecureNow | Leave unset |
| `firewall.enabled` | ignored | Deprecated. Turn the firewall on or off per app and environment with `npx securenow firewall enable` / `disable` |
| `sessions.guard` **(8.25.0+)** | `false` | Revoked sessions should get a 401 in any framework, with no code |
| `sessions.capture` **(8.25.0+)** | `false` | Requests with a session should send `session.seen` for session-theft detection |
| `sessions.cookieNames` **(8.25.0+)** | `[]` | Your session cookie is not one of the defaults (section 5.10) |

### Environment variables

- `SECURENOW_CREDENTIALS`: the runtime credentials JSON, raw or base64, for hosts that can't mount a file. It wins over every file. `npx securenow credentials runtime --env production --format env` prints `SECURENOW_CREDENTIALS=<base64>`. A value that isn't credentials JSON is ignored with a warning.
- `SECURENOW_DISABLED=1` (or `true`, `yes`, `on`): the SDK stays off in that process, with no traces, logs, events, firewall or session sync; `guard()` just calls `next()`. It prints `[securenow] disabled by SECURENOW_DISABLED (register not started)`. For test runs: `SECURENOW_DISABLED=1 npm test`.
- Nothing else is read by SecureNow. OpenTelemetry's own `OTEL_*` variables still reach the OpenTelemetry SDK underneath, and you need none of them. SecureNow sets `OTEL_METRICS_EXPORTER=none` when it is unset, so no metrics reader retries `localhost:4318`.

## 5. Features

### 5.1 Traces

- **What:** one server span per request with method, route (`http.route` where section 3 says so), status code, client IP (`http.client_ip`, `http.client_ip.source`, `http.socket_ip`, `http.proxy.trusted`), redacted headers and body, plus child spans for outgoing HTTP and databases (Postgres, MySQL, MongoDB, Redis...). `service.name` is the app key; `deployment.environment` comes from the config.
- **On:** automatic once wired. To skip one instrumentation, list its package name in `config.otel.disableInstrumentations`.
- **Verify:** `npx securenow test-span` prints `Span accepted (HTTP 200)`. Send one request to the app, then `npx securenow traces --env <env> --limit 5` and `npx securenow traces show <traceId> --env <env>` (it starts with the request: route, status, client IP, user agent and the redacted body **(8.26.0+)**). In a project signed in with `securenow login`, these commands use the project's app without `--app` **(8.26.0+)**.

### 5.2 Logs

- **What:** `console.log`, `info`, `warn`, `error` and `debug` become log records (INFO, INFO, WARN, ERROR, DEBUG) linked to the active trace, and still print to the terminal. In code:

  ```js
  const { getLogger } = require('securenow/tracing');
  const logger = getLogger('billing', '1.0.0'); // null when logging is disabled
  logger?.emit({ severityNumber: 13, severityText: 'WARN', body: 'Card declined', attributes: { orderId: 'o_123' } });
  ```

  **Redacted before export (8.25.0+):** credential fields (password, token, apiKey, authorization, cookie, OTP codes, card numbers...) in logged objects, JSON and `key=value` text, and secret shapes anywhere in the line (JWTs, Bearer/Basic credentials, `sk_`/`pk_`/`rk_`/`snk_` keys, card numbers, emails) become `[REDACTED]`. The terminal still shows the line as written, and attributes you pass to `getLogger().emit()` are exported as set. `config.logging.redact: false` turns it off. Redaction goes by field names and value shapes, so a secret in free text ("the new password is hunter2") still goes out: don't log secrets. Before 8.25.0, lines were exported as written.
- **On:** `config.logging.enabled` (default `true`); redaction `config.logging.redact` (default `true`).
- **Verify:** the startup line `Logging: ENABLED → https://ingest.securenow.ai/v1/logs`; `npx securenow logs --env <env> --since 15m`; `npx securenow logs errors --since 1h` (failures grouped by message). From a shell or CI: `npx securenow log send "Deploy done" --level info --attrs version=1.2.3`.

### 5.3 Header and body capture, redaction

- **What:**
  - `http.request.headers`: JSON of the request headers, each value cut at 500 characters, dropped if the whole set exceeds 8 KB.
  - `http.request.body` for `application/json`, `application/x-www-form-urlencoded` and `application/graphql`, up to `maxBodySize`; a larger body is recorded as `[TOO LARGE: <n> bytes]`. Other content types (text, XML, binary) are not captured.
  - `multipart/form-data` as metadata: text fields (up to 1000 characters each, 100 parts) and files as field, name, type and size, never their content.
  - The body is observed while the app reads it, never consumed. A route that never reads its body (no body parser) records none.
- **Redaction**, before anything leaves the process:
  - Header names: `cookie`, `set-cookie`, `authorization`, `proxy-authorization`, any name containing `token`, `secret`, `password`, `passwd`, `csrf`, `xsrf`, `session`, `api-key`, `apikey`, `api_key`, `credential`, `signature`, `private-key` or `x-auth`, and OTP names.
  - Body field names, case-insensitive substring match (68 built-in names; the startup line counts them): passwords, secrets, tokens, `auth`, `authorization`, `bearer`, credentials, session ids, cookies, card, CVV, IBAN, account, routing and sort codes, tax ids, SSN, PIN, email, phone, mobile, date of birth, first/last/full name, address, postcode, zip, passport, license. OTP names (`code`, `otp`, `otpCode`, `oneTimeCode`, `verificationCode`, `passcode`, `mfaCode`, `totpCode`, `recoveryCode`, `backupCode`...) match exactly, so `status_code` and `error_code` stay readable.
  - Values that look like secrets, under any field name: JWTs, `Bearer`/`Basic` credentials, `sk_`/`pk_`/`rk_`/`snk_` live and test keys, email addresses, card numbers that pass the Luhn check.
  - URL query parameters with OTP names. Other query values are kept (attack payloads in URLs are what detections read), so keep secrets out of URLs.
- **On:** on by default. Tune `config.capture.body`, `multipart`, `maxBodySize` and `sensitiveFields` (extra names; they apply to header names too, ignoring case and punctuation).
- **Verify:** `npx securenow redact '{"email":"a@b.co","password":"x","otpCode":"123456","status_code":200}'` shows what is kept; after a real POST, `npx securenow traces show <traceId>` shows the redacted `http.request.body`.

### 5.4 Client IP and trusted proxies

- **What:** the client IP is the connection's address unless the connection comes from a trusted proxy. Then it is the right-most untrusted address in `X-Forwarded-For`, or else `CF-Connecting-IP`, `True-Client-IP`, `X-Real-IP` or `X-Client-IP`. Trusted by default: private ranges (`10/8`, `172.16/12`, `192.168/16`, `100.64/10`, `169.254/16`, `fc00::/7`), loopback, the host's own addresses and, **(8.25.0+)**, Unix-socket and named-pipe connections (nginx `proxy_pass http://unix:/run/app.sock`, Nuxt's dev proxy). A client can't choose its IP through `X-Forwarded-For`. The firewall, rate limits, `session.seen` and traces all use this IP.
- **On:** `config.networking.trustedProxies` takes exact IPv4/IPv6 addresses, IPv4 CIDRs, IPv6 CIDRs **(8.25.0+)**, and `"cloudflare"` (Cloudflare's published edge ranges, IPv6 ones included from 8.25.0):

  ```json
  { "config": { "networking": { "trustedProxies": ["cloudflare", "203.0.113.10", "198.51.100.0/24"] } } }
  ```

  The proxy must forward the visitor, for nginx: `proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;`.
- **Verify:** in `npx securenow traces show <traceId>`, `http.client_ip` is the visitor and `http.client_ip.source` is `x-forwarded-for` (or `cf-connecting-ip`...), not `socket` with the proxy's address. `npx securenow protect status` says whether the app sees real client IPs: blocking mode is refused while more than 20% of its traffic comes through a proxy it doesn't trust.

### 5.5 Firewall (layers 1 to 4)

- **What:** syncs the app's blocklist (yours plus SecureNow's known-bad IP feed, refreshed hourly), allowlist, scoped blocks, rate limits and challenges. It checks a version every `versionCheckInterval` (10 s, ETag/304) and resyncs fully every `syncInterval` (3600 s); matching happens in memory. It fails open by default, and a circuit breaker pauses polling for 2 minutes after 5 consecutive API errors. Each request goes through: allowlist (when one is active, an unlisted IP is blocked and a listed IP skips every other check), then blocklist, scoped blocks (route, method), challenge, rate limit.

  | Layer | Turn on | What it does | Limits |
  |---|---|---|---|
  | 1 HTTP | always, once the runtime API key is present | 403 JSON `{"error":"Forbidden","ip":"..."}`, or an HTML page with the masked IP for browsers; status from `firewall.statusCode` | Works behind proxies (forwarding headers) |
  | 2 TCP | `"tcp": true` | Destroys the socket before HTTP parsing, zero bytes sent | Sees only the connection's source IP; connections from trusted proxies are left to layer 1. Use 8.25.0+: before, it hooked `listen()` and missed the servers most apps start before the SDK has finished starting |
  | 3 OS | `"iptables": true` | Kernel DROP: a `SECURENOW_BLOCK` chain in iptables (ip6tables for IPv6), or a `securenow` nft table where iptables is missing **(8.25.0+)** | Linux, root or `CAP_NET_ADMIN`, `iptables`/`nft` installed; direct client connections only. Use 8.25.0+: it validates every entry, runs without a shell and applies each sync as one batch, and an IPv6 entry no longer stops the sync |
  | 4 Cloud WAF | `"cloud": "cloudflare"`, `"aws"` or `"gcp"` | Pushes the global blocklist to the edge, at most every 30 s | Cloudflare: fills an account IP list `securenow-blocklist` that your own WAF rule must reference. AWS: WAFv2 IP set. GCP: Cloud Armor rules at priority 2000, `deny(403)`. Use 8.25.2+ (IPv6 ranges, Cloud Armor's 10-range limit, stale rules, IPv4-mapped entries fixed). AWS tested against real IP sets; Cloudflare and GCP request format tested only |

  Layers 2 to 4 carry the global blocklist. Scoped blocks, rate limits and challenges are layer 1 only.
- **On:** automatic with the runtime API key. Each app and environment also has a remote switch, `npx securenow firewall enable|disable --app <key> --env production`, applied without a deploy. `config.firewall.enabled` is ignored.
- **Verify:** startup lines `Firewall: ENABLED`, `Firewall: environment=<env>`, `Firewall: Layer 1 (HTTP 403) active` and `Firewall: synced <n> global blocked IPs (<x> exact + <y> CIDR ranges) and <z> scoped block rules`. Then `npx securenow firewall status --env <env>`, `npx securenow firewall test-ip 203.0.113.7 --path /admin --env <env>` and `npx securenow firewall hits --since 1h`.

### 5.6 Rate limits

- **What:** 429 with `Retry-After`, `X-RateLimit-Limit`, `X-RateLimit-Window` and `X-SecureNow-Rate-Limit-Rule` (JSON `{"error":"Too Many Requests","ip":"...","retryAfter":<s>}`, or a small HTML page for browsers). A rule matches a route (exact, prefix or regex), a method, optionally an IP or CIDR, an app and an environment, and counts per IP, globally, per request-header value (API key, tenant) or per cookie value (session); header and cookie values are hashed, and requests without them count per IP. Rules live in SecureNow, not in your code; running apps apply them within about 10 seconds.
- **On:** create from the CLI, MCP or dashboard:

  ```bash
  npx securenow ratelimit add --route /api/login --method POST --limit 5 --window 1m --env production --reason "login brute force"
  npx securenow ratelimit add --route /api/ --limit 100 --window 1m --header x-api-key --env production   # per API key
  npx securenow ratelimit add --route /app --limit 300 --window 1m --cookie session --env production      # per session cookie
  npx securenow ratelimit from-text "5 per minute per IP on POST /api/login for 2h" --yes
  ```

  Counters live in each process. With PM2 cluster or several servers, each process counts on its own (the effective limit is multiplied) unless they share Redis: `"config": { "firewall": { "rateLimitStore": "redis://your-redis:6379" } }` (`rediss://`, `user:password@` and `/db` work). The firewall never waits on Redis; at most a request or two per process can slip past while a reply is in flight, and it falls back to in-process counting if Redis is unreachable.
- **Verify:** `npx securenow ratelimit test 203.0.113.42 --path /api/login --method POST --env production`; startup line `Firewall: synced <n> rate-limit rules` (and `shared rate-limit counters: connecting to ...` with Redis); `npx securenow firewall hits --action rate_limited --since 1h`. Rules are per environment and the CLI defaults to `production`: to try one against a local app, create it with `--env local`.

### 5.7 Challenges (proof of work)

- **What:** a softer step than a block. Browsers (`Accept: text/html`) get a 403 interstitial that solves a proof of work by itself (14 bits by default, about a second or less) and receives a pass cookie bound to the IP and user agent, valid 30 minutes by default. Clients that don't accept HTML get a 403 JSON `{"error":"challenge_required","challenge":{...}}` with the header `X-SecureNow-Challenge: required`, so don't challenge API routes that non-browser clients call. A challenge can escalate to a block after repeated failures.
- **On:**

  ```bash
  npx securenow challenge add --route /login --clearance 30m --env production
  npx securenow challenge add 203.0.113.0/24 --route /signup --difficulty 16 --escalate-to-block --fail-threshold 10 --block-ttl-hours 24
  ```

- **Verify:** `npx securenow challenge test 203.0.113.9 --path /login --method GET --env production`; `npx securenow firewall hits --action captcha_challenged --since 1h`.

### 5.8 Blocklist, allowlist, trusted IPs

- **Blocklist:** block an IP address or CIDR range, IPv4 or IPv6, everywhere or on a route, optionally with an expiry (IPv6 ranges are enforced by securenow 8.25.0+). An unblock stops enforcement and keeps the history.

  ```bash
  npx securenow blocklist add 203.0.113.42 --env production --duration 24h --reason "credential stuffing"
  npx securenow blocklist add 203.0.113.42 --route /admin --mode prefix --method ALL --reason "admin probing"
  npx securenow blocklist unblock <id> --reason "false alarm after review"
  ```

- **Allowlist (dangerous):** deny-by-default. Once any active entry exists for an app and environment, only listed IPs get through and everyone else gets 403. Listed IPs also skip the blocklist, rate limits and challenges. Use it only to lock an app to known IPs, with the person's approval: `npx securenow allowlist add <ip> --app <key> --env production --label "Office" --reason "..."`.
- **Trusted IPs:** known-safe infrastructure (uptime monitors, office VPN, your own servers). Alerts on them are suppressed; they restrict nobody: `npx securenow trusted add <ip> --label "Uptime monitor"`.
- **Verify:** `npx securenow blocklist list --env production`, `npx securenow firewall test-ip <ip> --env production`, `npx securenow firewall hits --ip <ip>`. Blocks reach running apps within about 10 seconds.

### 5.9 Custom security events: `track()`

- **What:** your app reports what only it knows (sign-ins, OTPs, password resets, MFA). Events feed brute-force, credential-stuffing and account-takeover detection, and alert rules can query them (`attributes_string['event.type']`, `['enduser.id']`, `['session.id']`, `['http.client_ip']`). `track()` is fire-and-forget: it buffers (1000 events at most, oldest dropped), sends batches of up to 100 every 2 seconds and never throws. It uses the runtime credentials, so it also works in a script without the preload; `flush()` returns a promise for scripts that exit right away.

  ```js
  const { track } = require('securenow/events');   // ESM: import { track } from 'securenow/events';
  track('auth.login.failure', { userId, sessionId, ip, userAgent, severity: 'warn', attributes: { reason: 'bad_password' } });
  ```

  Properties: `userId`, `sessionId`, `ip`, `userAgent`, `severity` (`trace`, `debug`, `info`, `warn`, `error`, `fatal`), `ts` (epoch ms), `attributes` (strings, numbers, booleans).

- **Recommended auth events:**

  | Event | Emit when |
  |---|---|
  | `auth.login.failure` | A sign-in fails (unknown user, wrong password) |
  | `auth.login.success` | A sign-in succeeds |
  | `auth.otp.send.requested` | Someone asks for a one-time code or magic link |
  | `auth.otp.send.result` | The SMS/email provider accepted or refused the send |
  | `auth.otp.verify.failure` | A wrong or expired code is entered |
  | `auth.otp.verify.success` | A code is accepted |
  | `auth.password_reset.requested` | A reset is requested |
  | `auth.password_reset.completed` | A password is changed through a reset |
  | `auth.mfa.challenge.failure` | A second factor fails |
  | `auth.mfa.challenge.success` | A second factor succeeds |
  | `auth.session.revoked` | Your app signs a user out everywhere or kills a session |

- **Login route example (Express):**

  ```js
  const { track } = require('securenow/events');
  const { resolveClientIp } = require('securenow/resolve-ip');

  app.post('/api/login', async (req, res) => {
    const ip = resolveClientIp(req);              // the same trusted-proxy rules as the firewall
    const userAgent = req.get('user-agent');
    const user = await findUserByEmail(req.body.email);
    if (!user || !(await verifyPassword(user, req.body.password))) {
      track('auth.login.failure', {
        userId: user ? user.id : undefined,        // your internal id, never the password
        ip, userAgent, severity: 'warn',
        attributes: { reason: user ? 'bad_password' : 'unknown_user', method: 'password' },
      });
      return res.status(401).json({ error: 'Invalid email or password' });
    }
    const session = await createSession(user);
    track('auth.login.success', { userId: user.id, ip, userAgent, attributes: { method: 'password' } });
    res.json({ ok: true });
  });
  ```

  If you also send `sessionId` and want it to match revocations made through the session guard, send what the guard computes, `require('securenow/sessions').sha256(<session cookie value exactly as sent>)`, or give the guard your own `getSessionId` (section 5.10).

- **Inside a request, `ip` and `userAgent` fill themselves (8.26.0+).** When `track()` runs while SecureNow is handling a request and you leave `ip` or `userAgent` out, they come from that request: the address resolved with the firewall's trusted-proxy rules (a client can't choose it with `X-Forwarded-For`) and its `User-Agent`. This is how to report events from a Next.js route handler, which only gets a Web `Request` and can't tell who connected. Values you pass win. Outside a request (a script, a queue worker) nothing is added. `require('securenow/resolve-ip').currentClientIp()` returns the same address for your own code (`''` outside a request). It needs the runtime API key (the firewall's request hook carries the request).

  ```ts
  // Next.js route handler (Node.js runtime), app/api/login/route.ts
  import { track } from 'securenow/events';

  export async function POST(request: Request) {
    const { email, password } = await request.json();
    const user = await findUserByEmail(email);
    if (!user || !(await verifyPassword(user, password))) {
      track('auth.login.failure', { userId: user?.id, severity: 'warn', attributes: { reason: user ? 'bad_password' : 'unknown_user' } });
      return Response.json({ error: 'Invalid email or password' }, { status: 401 });
    }
    track('auth.login.success', { userId: user.id, attributes: { method: 'password' } });
    // ...create the session
  }
  ```
- **Verify:** `npx securenow telemetry fields --since 1h --json` lists the custom event types observed for the app. From a shell or a non-JS service: `npx securenow event send auth.login.failure --user u_test --ip 203.0.113.10 --attrs reason=test` (add `--env local` to tag it local).

### 5.10 Session revocation

Revoke a stolen session or every session of a user, from the CLI, MCP-capable automation or the dashboard; the SDK pulls active revocations every 30 seconds (outbound, ETag-cached) and rejects matching requests locally. Fail-open: an outage never blocks sign-ins.

```bash
npx securenow revoke session <session-id> --reason "impossible travel" --duration 24h --app <key>
npx securenow revoke user <user-id> --reason "account takeover"      # default expiry 7d
npx securenow revoke list
npx securenow revoke restore <revocation-id> --reason "verified with the user"
```

The session id is what the SDK computes: the SHA-256 of the Bearer token, or else of the first session cookie found. Cookies looked up, in order: your `sessions.cookieNames` **(8.25.0+)**, then `__Secure-next-auth.session-token`, `__Host-next-auth.session-token`, `next-auth.session-token`, `connect.sid`, `session`, `sid`. The user id is the `sub` claim of a JWT Bearer token. To get the id of one session for a test: `node -e "console.log(require('securenow/sessions').sha256(process.argv[1]))" '<cookie value>'`.

Pick one way to enforce:

1. **Zero code, every framework (8.25.0+).** In `.securenow/runtime.json`:

   ```json
   { "config": { "sessions": { "guard": true, "capture": true, "cookieNames": ["my_app_session"] } } }
   ```

   `guard` answers a revoked session or user with 401 (body `Session revoked`) and clears the session cookies; `capture` sends `session.seen`, deduplicated per session and IP every 5 minutes, for session-theft detection (impossible travel, concurrent networks). It runs in the firewall's request hook, so it needs the runtime API key, and it works with `-r securenow/register`, Next.js, Nuxt and `securenow/firewall-only`.

2. **Express-style middleware: `guard()`** (Express, Connect, Polka, NestJS on the Express adapter, Feathers with Express):

   ```js
   const sessions = require('securenow/sessions');
   app.use(sessions.guard());   // default extraction above
   // or with your own ids (after your session middleware):
   app.use(sessions.guard({ getSessionId: (req) => req.session?.id, getUserId: (req) => req.user?.id }));
   ```

   A revoked request gets 401 with the session cookies cleared: JSON `{"error":"Session revoked. Please sign in again.","code":"session_revoked"}` where `res.json` exists (Express), plain `Session revoked` otherwise. Options: `getSessionId(req)`, `getUserId(req)`, `onRevoked(req, res, next, { sessionId, userId })`, `capture` (default `true`: also sends `session.seen`), `captureWindowMs` (default 300000), `syncIntervalMs` (default 30000). In NestJS, call `app.use(sessions.guard())` in `main.ts`.

3. **Anything else: `check()` (8.25.0+).** `sessions.check(req, options?)` takes a Node request or a Web `Request` and returns `{ revoked, sessionId, userId }`; you answer 401 yourself. Options: `getSessionId`, `getUserId`, `capture` (default `true`), `ip` (for `session.seen`; with a Web `Request`, which has no socket, it defaults to the address of the request SecureNow is handling **(8.26.0+)**).

   ```js
   const sessions = require('securenow/sessions');

   // Fastify
   fastify.addHook('onRequest', async (request, reply) => {
     if (sessions.check(request.raw).revoked) return reply.code(401).send({ error: 'session_revoked' });
   });

   // Koa
   app.use(async (ctx, next) => {
     if (sessions.check(ctx.req).revoked) { ctx.status = 401; ctx.body = { error: 'session_revoked' }; return; }
     await next();
   });

   // Hono (c.req.raw is a Web Request)
   app.use('*', async (c, next) => {
     if (sessions.check(c.req.raw).revoked) return c.json({ error: 'session_revoked' }, 401);
     await next();
   });

   // h3
   app.use(defineEventHandler((event) => {
     if (sessions.check(event.node.req).revoked) { setResponseStatus(event, 401); return { error: 'session_revoked' }; }
   }));
   ```

   ```ts
   // Next.js route handler (Node.js runtime), app/api/account/route.ts
   import { check } from 'securenow/sessions';

   export async function GET(request: Request) {
     if (check(request).revoked) return Response.json({ error: 'session_revoked' }, { status: 401 });
     return Response.json({ ok: true });
   }
   ```

4. **Lower level:** `sessions.isRevoked({ sessionId, userId })` returns a boolean. Call `sessions.start()` once at boot when this is all you use (`guard()`, `check()` and the zero-code guard start the sync themselves).

- **Verify:** revoke a test session, wait up to 30 seconds, then send a request with that cookie or token: it gets 401 and `Set-Cookie` headers that clear the session cookies. `npx securenow revoke list` shows the entry; `npx securenow revoke restore <id>` lifts it.

### 5.11 Crash capture

- **What:** an uncaught exception or unhandled promise rejection becomes a FATAL log record with `exception.type`, `exception.message` and `exception.stacktrace`. Logs and the spans that ended before the crash are flushed (up to 2 seconds), then the process exits as Node would (stack on stderr, exit code 1). If the app registered its own handler, the error is recorded as ERROR and the app decides. OTLP export errors never crash the app.
- **On:** automatic while `config.logging.enabled` is `true`.
- **Verify:** `npx securenow logs --level fatal --since 1h --env <env>`.

### 5.12 Detection

- **Starter protection:** when an app is created or first sends traffic it gets about 20 rules (SQL injection, XSS, traversal, command and template injection, Log4Shell, Spring4Shell, metadata SSRF, CRLF, prototype pollution, `.env`/`.git`/backup probes, exploit kits, attack-tool user agents, failed sign-ins, 404 scanning) in **monitor** mode: they alert and block nothing. In **block** mode the block-ready rules block the address for 6 hours on exploit signatures. Only a signed-in person can turn blocking on, and only when the app sees real client IPs (5.4).

  ```bash
  npx securenow protect status          # mode, rules, alerts, ready to block?
  npx securenow protect block --app <key>     # a person, after reviewing
  npx securenow protect monitor --app <key>   # back to alerts only
  ```

- **Alert rules from English:** SecureNow drafts an instant rule (each request, as it arrives) or a periodic one (SQL on a schedule) from your app's real data, checks it, and creates it in **test mode**: it alerts but nothing acts on it (no instant block, automation or agent action).

  ```bash
  npx securenow alerts rules from-text "one IP failing 10 sign-ins in 5 minutes" --app <key> --draft-only   # review
  npx securenow alerts rules from-text "one IP failing 10 sign-ins in 5 minutes" --app <key>                # create (asks to confirm)
  npx securenow alerts rules test <rule-id> --wait                  # dry run on real data
  npx securenow alerts rules test <rule-id> --mode live --wait      # inserts 6 synthetic attack requests first
  npx securenow alerts rules runs <rule-id> --since 1h              # what each run saw, and why it did or didn't notify
  npx securenow alerts rules why <rule-id> --ip 203.0.113.50        # why it did or didn't alert on one address
  npx securenow alerts rules promote <rule-id> --yes                # a person moves it to prod
  ```

  Agents don't promote: they ask with `npx securenow alerts rules request-promotion <rule-id> --reason "..." --evidence "..."`, and a person decides (`npx securenow human promotions`).
- **SQL rules:** read the contract first (`npx securenow telemetry schema --json`, offline, and `node_modules/securenow/TELEMETRY-SQL.md`), check fields really sent (`npx securenow telemetry fields --app <key> --since 24h --json`), dry-run (`npx securenow alerts rules validate --sql @rule.sql --app <key>`), then `alerts rules create --name "..." --sql @rule.sql --apps <key>`. Scope app keys with `__USER_APP_KEYS__` and return an `ip` column.
- **What fires:** `npx securenow today` (the Overview), `npx securenow attacker <ip>`, `npx securenow review` (rules that fired too wide), `npx securenow human` (decisions waiting for a person). Details: SKILL-CLI.md.

### 5.13 MCP for coding agents

- **Local stdio server** (after `npx securenow login`):

  ```bash
  claude mcp add securenow -- npx securenow mcp
  codex mcp add securenow -- npx securenow mcp
  ```

  Cursor, `.cursor/mcp.json`: `{ "mcpServers": { "securenow": { "command": "npx", "args": ["securenow", "mcp"] } } }`.
- **Hosted server:** `https://api.securenow.ai/mcp` with OAuth sign-in (an API key as `Authorization: Bearer <key>` also works), e.g. `claude mcp add --transport http securenow https://api.securenow.ai/mcp`.
- Read tools are annotated read-only; every write tool refuses to run without `confirm: true` and a non-empty `reason`. `npx securenow mcp --profile investigator|detection|responder` serves fewer tools. Details and tool counts: SKILL-CLI.md.

## 6. Deployment

### 6.1 Production credentials

```bash
npx securenow credentials runtime --env production                 # writes .securenow/credentials.production.json
npx securenow credentials runtime --env production --format env    # prints SECURENOW_CREDENTIALS=<base64>
```

The file has the app key, the runtime API key and the config, with `deploymentEnvironment` set, and never the admin token. Ship it as `<app-root>/.securenow/credentials.json` (the generated name also works when it is the only file), or store the printed line as a secret environment variable. Both contain the runtime API key: secret storage only, never the image registry or the repository. Keep `.securenow/runtime.json` and `admin.json` out of images with a `.dockerignore`:

```
.securenow/admin.json
.securenow/runtime.json
.securenow/credentials*.json
```

### 6.2 Docker

Plain Node:

```dockerfile
FROM node:24-slim
WORKDIR /app
COPY package*.json ./
RUN npm ci --omit=dev
COPY . .
CMD ["node", "-r", "securenow/register", "src/index.js"]
```

```bash
docker run -v "$PWD/.securenow/credentials.production.json:/app/.securenow/credentials.json:ro" my-api
# or, without a file:
npx securenow credentials runtime --env production --format env > securenow.env   # secret: don't commit
docker run --env-file securenow.env my-api
```

Next.js standalone (`output: 'standalone'` in `next.config`):

```dockerfile
FROM node:24-slim AS build
WORKDIR /app
COPY package*.json ./
RUN npm ci
COPY . .
RUN npm run build

FROM node:24-slim
WORKDIR /app
ENV NODE_ENV=production
COPY --from=build /app/.next/standalone ./
COPY --from=build /app/.next/static ./.next/static
COPY --from=build /app/public ./public
# credentials: mount /app/.securenow/credentials.json (next to server.js) or pass SECURENOW_CREDENTIALS
CMD ["node", "server.js"]
```

Nuxt (`.output`):

```dockerfile
FROM node:24-slim AS build
WORKDIR /app
COPY package*.json ./
RUN npm ci
COPY . .
RUN npm run build

FROM node:24-slim
WORKDIR /app
COPY --from=build /app/.output ./.output
# credentials: mount /app/.securenow/credentials.json or pass SECURENOW_CREDENTIALS
CMD ["node", ".output/server/index.mjs"]
```

Layer 3 (`firewall.iptables`) in a container needs `--cap-add NET_ADMIN`, a root process and the `iptables` package in the image. Layers 2 and 3 act on the connection's source address, so they only help when clients connect to the container directly, not through a load balancer or proxy (layer 1 handles those with forwarding headers).

### 6.3 Kubernetes

As a file:

```bash
kubectl create secret generic securenow-credentials --from-file=credentials.json=.securenow/credentials.production.json
```

```yaml
containers:
  - name: api
    image: my-api
    volumeMounts:
      - name: securenow
        mountPath: /app/.securenow/credentials.json
        subPath: credentials.json
        readOnly: true
volumes:
  - name: securenow
    secret:
      secretName: securenow-credentials
```

Or as an environment variable:

```bash
npx securenow credentials runtime --env production --format env > securenow.env
kubectl create secret generic securenow-env --from-env-file=securenow.env
```

```yaml
envFrom:
  - secretRef:
      name: securenow-env
```

### 6.4 PM2

```js
// ecosystem.config.cjs (.cjs so require.resolve works in "type": "module" projects too)
module.exports = {
  apps: [{
    name: 'api',
    script: './src/index.js',
    cwd: __dirname,
    exec_mode: 'cluster',       // or 'fork'
    instances: 'max',
    node_args: ['-r', require.resolve('securenow/register')],
  }],
};
```

- Always the absolute path from `require.resolve`, computed when PM2 loads the file. In cluster mode Node resolves a bare `-r securenow/register` from the PM2 daemon's folder, so workers started from elsewhere (`pm2 resurrect` at boot) crash-loop with `Cannot find module 'securenow/register'`.
- Each process reads the `.securenow/` folder of the app PM2 started, wherever the daemon runs, and every worker reports under one service name. A PM2 process without credentials says so at startup.
- TypeScript: `node_args: ['-r', require.resolve('securenow/register'), '-r', require.resolve('ts-node/register')]`.
- Several workers count rate limits separately unless `firewall.rateLimitStore` points at Redis.
- After changing `node_args`: `pm2 delete api && pm2 start ecosystem.config.cjs && pm2 save`.

### 6.5 systemd and plain VMs

```ini
[Service]
WorkingDirectory=/srv/my-api
ExecStart=/usr/bin/node -r securenow/register src/index.js
Restart=always
User=my-api
# credentials: /srv/my-api/.securenow/credentials.json (mode 600, owned by my-api)
# or: EnvironmentFile=/etc/my-api/securenow.env   (the line printed by --format env)
```

Credentials are searched from the working directory and the entry script's folder, so set `WorkingDirectory` to the app folder.

### 6.6 Hosts without file mounts (Railway, Render, Heroku, Fly...)

Store the output of `npx securenow credentials runtime --env production --format env` as a secret variable named `SECURENOW_CREDENTIALS` (dashboard, `fly secrets set`, `heroku config:set`...) and keep the preload in the start command (`web: node -r securenow/register src/index.js` in a Procfile).

### 6.7 Vercel

Next.js on Vercel goes through `@vercel/otel` (an optional dependency); set `SECURENOW_CREDENTIALS` in the project's environment variables. Not tested end to end, and the firewall is not verified on Vercel serverless functions. Edge functions and Edge middleware are not instrumented. AWS Lambda and other serverless platforms are not supported or tested.

## 7. Verification checklist

| Step | Command | Good output |
|---|---|---|
| Version | `npx securenow version` | `securenow v8.24.0` or newer (8.25.0+ for the marked items) |
| Auth | `npx securenow whoami` | Admin auth and the runtime app both present |
| Config | `npx securenow env` | `Service name` = the app key UUID, the expected `Environment`, `Firewall enabled` (not `missing firewall API key`) |
| Connectivity | `npx securenow doctor` | `All checks passed.` (traces, logs, API, firewall sync) |
| Ingest | `npx securenow test-span` | `Span accepted (HTTP 200)` |
| App start | start the app | `[securenow] pid=... appId="<app-uuid>" instance=... apiKey=set credentials=<path or env:SECURENOW_CREDENTIALS> → service.name=<app-uuid> ...` (`apiKey=missing`: no runtime API key, so the gateway rejects telemetry and firewall sync; before 8.25.0 the field showed whether the app key was set), `OTel SDK started → https://ingest.securenow.ai/v1/traces`, `Logging: ENABLED`, `Request body capture: ENABLED (max: 10240 bytes, redacting 68 sensitive fields)`, `Firewall: ENABLED`, `Firewall: environment=<env>`, `Firewall: synced <n> global blocked IPs (...) and <n> scoped block rules`. ESM apps first print `ESM loader hook auto-registered (module.register)`. Next.js prints `Next.js App -> service.name=<app-uuid> apiKey=set credentials=<...>` (the `apiKey` and `credentials` fields 8.25.0+), `Environment: <env>`, `OpenTelemetry started for Next.js -> ...`, `Request body capture: ENABLED (...)` **(8.26.0+)** and the same Firewall lines |
| Traffic | one real request, then `npx securenow traces --env <env> --limit 5` | The request, with `http.client_ip` and (where supported) `http.route` |
| Overview | `npx securenow status --env <env>` and `npx securenow today` | The app covered: data flowing, firewall on, detection monitoring |
| Firewall | `npx securenow firewall status --env <env>`, `npx securenow firewall test-ip 203.0.113.7 --env <env>` | Firewall on for the app and environment; the verdict for the IP |

Bad signs: no `[securenow]` line at all (the preload is not on the command that starts the server), `credentials=none`, `service.name=securenow-free-<uuid>` or `nextjs-app-<uuid>` (no app key found), `Firewall: initial sync failed` (key, network or environment), `disabled by SECURENOW_DISABLED`.

## 8. Troubleshooting

| Symptom | Cause | Fix |
|---|---|---|
| No data in the dashboard | The process that serves HTTP didn't load the SDK (no `[securenow]` lines) | Put the preload on the real start command (script, `CMD`, PM2 `node_args`, `ExecStart`) |
| | Looking at the wrong environment: `init` writes `local`, the CLI and dashboard default to `production` | `--env local` or `--env all`, or set `deploymentEnvironment` for that deployment |
| | Runtime API key missing (`npx securenow env` says `missing firewall API key`) | `npx securenow app connect` or `npx securenow api-key create` |
| | `service.name` isn't the app key (`noUuid: false`, a custom `serviceName`) | Remove the override |
| | `SECURENOW_DISABLED` set; outbound HTTPS to `ingest.securenow.ai` blocked; trial ended (HTTP 402) | Unset it; open egress; subscribe |
| Wrong credentials picked up | `SECURENOW_CREDENTIALS` in the environment, a stray `runtime.json` next to the production file, a `credentials.staging.json`, a parent folder's or `~/.securenow/` file | Read the `credentials=` startup line, then remove the stray source (order in section 4) |
| PM2 cluster crash-loop, `Cannot find module 'securenow/register'` | Bare `-r securenow/register` resolved from the PM2 daemon's folder | `node_args: ['-r', require.resolve('securenow/register')]`, then `pm2 delete <name> && pm2 start ecosystem.config.cjs && pm2 save` |
| Next.js standalone: every request 500, `Cannot find module '@opentelemetry/...'` | Instrumentation file from `init` before 8.24.0 (`webpackIgnore` imports) | Run `npx securenow init` again (it replaces that file) or remove `webpackIgnore`; rebuild |
| Next.js: no SecureNow lines at startup | Instrumentation file in the wrong folder (Next.js 14 and 15 ignore a root file in a `src/` layout), or Next.js 14 without `experimental.instrumentationHook` | Rerun `npx securenow init` (8.25.0+ writes or moves it to `src/`) or move it to `src/instrumentation.ts`; Next.js 14 config in section 3.13 |
| Body not captured | Content type other than JSON, form, GraphQL or multipart; the route never reads its body; body over `maxBodySize` (`[TOO LARGE: <n> bytes]`); `capture.body: false`; Edge runtime | Add a body parser, raise `maxBodySize`, check the config, use the Node.js runtime |
| Client IP is the proxy's address | The proxy has a public address SecureNow doesn't trust, or doesn't send `X-Forwarded-For` | Add it to `networking.trustedProxies` (IP, CIDR or `"cloudflare"`), make it forward the client; `http.client_ip.source` should read `x-forwarded-for` |
| Blocked IP still gets through | Firewall not running (no `Firewall: synced` line); block scoped to another app, environment or route; firewall switched off for that environment; the IP resolves to the proxy; the IP is on the allowlist (listed IPs skip the blocklist); not yet propagated; layer 2/3 behind a proxy | `npx securenow firewall test-ip <ip> --path <path> --env <env>`, `npx securenow firewall apps`, `npx securenow firewall hits --ip <ip>`; wait one `versionCheckInterval` (10 s) |
| ESM app: no `http.route`, no library spans | ESM hook not registered: SDK loaded with an `import` inside the app instead of `-r`, Node older than 20.6, or a wrapper that hides the entry script | `node -r securenow/register <entry>` directly; look for `ESM loader hook auto-registered`. Hono, h3, Feathers and Polka routes need 8.25.0+ |
| Rate limit not applied | Rule created for `production` while the app reports `local`; route or method mismatch; counted per worker | `npx securenow ratelimit test <ip> --path <path> --method <m> --env <env>`; Redis store for clusters |
| Revoked session still works | Sync not yet run (every 30 s); no enforcement wired (`sessions.guard` 8.25.0+, `guard()` or `check()`); different session id (SHA-256 of the exact cookie value) or a custom cookie name | Wait 30 s; wire one of 5.10; add `sessions.cookieNames` (8.25.0+) or a `getSessionId` |
| Every request 403 at boot | `firewall.failMode: "closed"` and the first sync failed | Fix connectivity, or keep `failMode: "open"` |
| Tests send data to the real app | Test runs load the project's `.securenow` credentials | `SECURENOW_DISABLED=1 npm test` |

## 9. Tested on, and honest limits

**Tested end to end** (traces, client IP, body reaching the app, body capture with redaction, header redaction, 403 block, 429 rate limit, challenge, error span, exception, logs): Node 24.22 (CI: Node 24); Express 4.22 and 5.3; Fastify 5.12; NestJS 11.2; Koa 3.3; Hapi 21.4; Hono 4; Polka 0.5; Feathers 5.0; h3 1.15; Next.js 14.2 (`next start` and standalone), 15.5 and 16.4 (Turbopack and webpack, `next start` and standalone); Nuxt 3.21 and 4.6; Bun 1.3; PM2 5.4 (fork and cluster). Older majors are expected to work but are not tested: say "tested on", not "supports every version".

**Not supported:** Edge runtimes (Cloudflare Workers, Vercel Edge, Next.js Edge middleware and routes), Deno, `Bun.serve`, browser telemetry.
**Not tested:** Vercel (firewall unverified on its serverless functions), AWS Lambda and other serverless platforms.
**Layers 2 to 4:** turn them on with 8.25.0+ only (in 8.24.0 layer 2 dropped nothing for most apps and layers 3 and 4 mishandled IPv6). **Cloud WAF (layer 4):** AWS WAF is tested against real IP sets (IPv4 and IPv6, emptied list) from 8.25.2; Cloudflare and GCP are tested on the request format only, not against real accounts. On Cloudflare your own WAF rule must reference the `securenow-blocklist` list.
**IPv6:** the blocklist, allowlist, trusted IPs, rate limits, challenges and API-key IP limits take IPv6 addresses and CIDR ranges, stored in canonical form (`2001:DB8::1` = `2001:db8::1`); layer 1 and trusted proxies match them **(8.25.0+; older SDKs match exact IPv6 addresses but ignore IPv6 ranges)**. A trusted-IP range can be no wider than /8 (IPv4) or /32 (IPv6).
**`nuxt dev`:** before 8.25.0 the client IP was unknown, so IP blocking only applied to the built server.
**Log redaction (8.25.0+)** goes by field names and value shapes: a secret in free text with no recognizable shape is exported as written.

## 10. Package entry points

| Import | Use |
|---|---|
| `securenow/register` (also `securenow`) | The preload: tracing, logs, capture, crash capture, firewall (`node -r securenow/register`) |
| `securenow/firewall-only` | Preload: firewall only, no OpenTelemetry |
| `securenow/register-vite` | Same runtime as `securenow/register`, for the Node process serving a Vite app |
| `securenow/nextjs` | `registerSecureNow(options?)`, called from `instrumentation.ts` |
| `securenow/nextjs-auto-capture` | Body-capture fallback imported by the generated instrumentation file |
| `securenow/nuxt` | Nuxt 3/4 module (`modules: ['securenow/nuxt']`) |
| `securenow/events` | `track(type, props)`, `flush()` |
| `securenow/sessions` | `guard()`, `capture()`, `isRevoked()`, `start()`, `sha256()`; `check()` **(8.25.0+)** |
| `securenow/tracing` | `getLogger(name, version)`, `isLoggingEnabled()` |
| `securenow/resolve-ip` | `resolveClientIp(req)`, `resolveClientIpWithDetails(req)`, `resolveSocketIp(socket)`, `isFromTrustedProxy(ip)`, `currentClientIp()` **(8.26.0+)** |
| `securenow/cidr` | `createMatcher(list)` returns `{ isBlocked(ip), stats() }` for IPv4 and IPv6 addresses and ranges (IPv6 ranges 8.25.0+); `parseCidr`, `parseCidr6`, `parseIp`, `ipToInt`, `matchesCidr` |
| `securenow/firewall` | `getStats()`, `getMatcher()`, `getAllowlistMatcher()`, `init()`/`shutdown()` for custom setups |
| `securenow/rate-limits` | API helpers: `parseRateLimitText()`, `createRateLimitFromText()`, `createRateLimit()`, `listRateLimits()` (use the CLI or MCP for one-off rules) |
| `securenow/telemetry-schema` | The ClickHouse table/field contract for alert SQL (also `npx securenow telemetry schema --json`) |
| `securenow/app-config` | The resolved configuration (`resolveAll()`, `resolveFirewallOptions()`...) |
| `securenow/nextjs-webpack-config`, `securenow/nextjs-middleware`, `securenow/nextjs-wrapper`, `securenow/console-instrumentation`, `securenow/web-vite` | Legacy: not needed for a new setup |

Examples:

```js
// An internal health endpoint that shows the firewall is synced (the preload's own module instance)
const firewall = require('securenow/firewall');
app.get('/healthz/securenow', (req, res) => {
  const s = firewall.getStats();
  res.json({ initialized: s.initialized, blocked: s.blocked, rateLimited: s.rateLimited, circuit: s.circuitState });
});

// CIDR matching
const { createMatcher } = require('securenow/cidr');
const office = createMatcher(['10.0.0.0/8', '192.168.1.0/24']);
office.isBlocked('10.0.0.5'); // true
```

The same helpers exist in the CLI without writing Node: `npx securenow redact '<json>'`, `npx securenow cidr match <ip> <cidr,...>` (exit 0 on a match, 2 otherwise), `npx securenow cidr parse <cidr>`, `npx securenow env`, `npx securenow log send`, `npx securenow event send`, `npx securenow test-span`.
