Skip to content
Documentation

Architecture

This page is published from the server repository. Edit on GitHub View source

This page covers how the server is put together: the processes that run, the three kinds of caller and the path each request takes, where the code lives, and how the functional modules feed each other. The agent-facing protocol is detailed in Agent protocol, and the checks on each path in Security model.

Processes

 agents ──mTLS──▶ nginx :8443 ──▶ Next.js app :3000 ──▶ PostgreSQL
 browsers ───────▶   (proxy)       (Node runtime)   └──▶ telemetry archive (optional:
 scheduler ──────▶                                        a directory or an S3 bucket)
                                         │
                                         └──▶ LLM endpoint (optional, case narratives)
                                         └──▶ webhook receivers (optional, notifications)
ProcessWhat it isDefined in
Proxynginx. Terminates TLS on port 8443, verifies agent client certificates, passes the verified subject and a shared secret to the application, and applies body-size and rate limits per path.nginx.conf
ApplicationOne Next.js 14 application (App Router, TypeScript). Serves the agent endpoints, the console's API, the console pages and the scheduled-job routes.app/, lib/
DatabasePostgreSQL 15, the system of record for every tenant, agent, detection, case, release and audit row.prisma/schema.prisma
Telemetry archiveOptional Parquet files on a local directory or an S3-compatible bucket, written by a scheduled job.lib/lake-*.ts

There is no background worker process. Everything that is not a response to a request runs when an external scheduler calls one of the scheduled-job routes. The application keeps no state between requests other than what is in PostgreSQL, the archive and the file-system artifact store, so several instances can run behind the proxy; the places that need mutual exclusion take PostgreSQL advisory locks rather than in-process ones.

Runtimes inside the application

Next.js compiles parts of the application for two runtimes:

  • Edge. middleware.ts runs on every /api/* and /console/* request before the route. The Edge runtime cannot load Prisma, so the middleware asks the application's own /api/auth/get-session route over the loopback to read a session (lib/session-lookup.ts).
  • Node. Route handlers, server components and instrumentation.ts, which runs once at start-up. It loads instrumentation-node.ts only on the Node runtime, which checks that the decoy table exists and installs the shutdown handler that flushes pending decoy alarms.

Three kinds of caller

Every request belongs to exactly one of three identities, and the identities never mix: an agent cannot act with a session, and a session cannot act as an agent.

flowchart LR
  A[Agent] -->|client certificate| N[nginx]
  B[Browser / API client] -->|session cookie| N
  S[Scheduler] -->|Bearer CRON_SECRET| N
  N -->|X-Client-Cert-*<br/>X-Proxy-Secret| M[middleware.ts]
  M -->|public path:<br/>identity headers stripped| AR[agent routes<br/>authenticateAgent]
  M -->|public path| CR[cron routes<br/>verifyCronRequest]
  M -->|session found:<br/>x-tenant-id, x-user-id set| UR[console routes<br/>requireTenantMember / requireTenantAdmin]
  M -->|no session| L[redirect /login]
CallerCredentialChecked byTenant comes from
AgentmTLS client certificate whose common name is an enrolled agent's enrollment IDnginx (certificate), then authenticateAgent (proxy secret, verified subject, enrolled agent)The agent row the certificate names
Console userbetter-auth session cookie with an active organizationmiddleware.ts, then requireTenantMember or requireTenantAdmin in the route; requireConsoleTenant in pagesThe session's activeOrganizationId
SchedulerAuthorization: Bearer <CRON_SECRET>verifyCronRequestNone: jobs iterate over every tenant

The middleware keeps a fixed list of public paths (agent ingest and downloads, /api/auth, /api/health, /api/cron/*, /login, /). On those it removes any client-supplied x-tenant-id and x-user-id and lets the route authenticate the caller itself. On every other matched path it looks up the session, redirects to /login without one, and otherwise sets those two headers from the session. Route handlers read the tenant only from them, through getTenantId, never from the request body.

Code layout

PathContents
app/api/Route handlers. One directory per resource; the path is the URL.
app/console/, app/login/Console pages (React server components).
components/Client components used by the console pages.
lib/Server logic. Most of it is pure functions over plain data, with the Prisma calls kept in thin store modules or in the route, so the logic is unit-testable without a database.
assistant/The case-narrative evidence graph, prompt and LLM client.
prisma/schema.prismaThe database schema, including the better-auth tables.
middleware.tsSession check and identity headers.
nginx.conf, Dockerfile, docker-compose.ymlThe proxy and the development stack.
scripts/Development certificates, the standalone start script and the test runner.
tests/Unit, integration and acceptance suites (Testing).
ingest/, fleet/, hunt/, ...Module notes only, no code: the design and status of each functional area.

Route handlers either wrap their body in route, which maps HttpError subclasses to their status, a ZodError to 400 and anything else to a logged 500 with no detail, or do the same mapping in their own try/catch. No stack trace or driver message reaches a caller.

Functional modules

The server's functions are organized by area. Each row names the routes and library modules that implement it; the module note has the design and status.

AreaWhat it doesRoutesLibraryNote
IngestAccepts events, detections, heartbeats and decoy registrations from enrolled agentsapp/api/ingest/*, app/api/v1/ingest/*detection-payload.ts, health-beacon.ts, ingest-stats.ts, decoy.tsingest
CasesGroups one host's detections into cases; opens a case for a silent agentapp/api/cases/*, app/api/cron/group-detections, app/api/cron/detect-silent-agentscase-grouping.ts, case-grouping-store.ts, silent-agent-case.ts, case-detail.tsassistant
Fleet correlationJoins cases of several hosts that share a file hash or a signed-in identity into fleet casesapp/api/fleet-cases/*, app/api/cron/join-fleet-casesfleet-case.ts, fleet-case-load.tsfleet
PrevalencePer-tenant first-seen, last-seen and host counts for hashes, paths, parent-child pairs and domains; the signed common-set snapshotapp/api/prevalence, app/api/snapshot/*, app/api/cron/prune-prevalence, app/api/cron/build-snapshotsprevalence.ts, common-set-snapshot.ts, snapshot-publish.tsprevalence
Entity graphA case's subgraph and pivots from a hash, path or domain to every host that showed it, computed on readapp/api/cases/[id]/graph, app/api/graph/pivotgraph.tsgraph
HuntingSaved and scheduled hunts, ad-hoc search over detections, cases and the archive, drafts of Sigma rules and IOC setsapp/api/hunts/*, app/api/cron/run-huntshunt.ts, hunt-search.ts, hunt-runner.ts, hunt-graduation.tshunt
Telemetry archiveQueues accepted event batches and writes them as Parquet, with per-tenant retention and audited deletionapp/api/cron/write-lake, app/api/cron/prune-lakelake-writer.ts, lake-store.ts, lake-s3-store.ts, lake-retention.ts, lake-query.tsdatalake
Fleet operationsAgent and ingest health, ring status, ring assignment, halt and rollbackapp/api/ops/*, app/api/rings/*, app/api/agents/*, app/api/content/*, app/api/release/*fleet-health.ts, rings.ts, ring-actions.ts, release-publish.tsops, Content and releases
AssistantLLM-written case narratives over an allowlisted evidence graph, with citations checked against the caseapp/api/cases/[id]/narrative/regenerateassistant/, case-narrative.tsassistant
IntegrationsSigned webhooks for host health changes and new hunt matches, through an outboxapp/api/notify/*, app/api/cron/deliver-notificationslib/notify/integrations
TenancyTenant provisioning, the tenant–organization pairing, rolesapp/api/admin/tenants, app/api/auth/*tenant-provisioning.ts, auth.ts, admin-auth.tsSecurity model

Three areas are planned and have notes but no code yet: cloud-side detection, the DFIR workbench and attack disruption.

The corpus routes (app/api/corpus/*) store benign telemetry samples per tenant and export a finalized version as JSONL for model training. They are not yet part of the agent protocol: the submit route is not on the middleware's list of agent paths.

Data flows

From an agent's upload to a case

flowchart TD
  EV[POST /api/ingest/events] -->|observations, one upsert per batch| PS[(prevalence_sightings)]
  EV -->|archive on| LB[(lake_batches)]
  LB -->|cron write-lake| PQ[(Parquet archive)]
  DT[POST /api/ingest/detection] --> D[(detections)]
  DT -->|observations| PS
  HB[POST /api/ingest/heartbeat] --> AG[(agents.last_seen)]
  HB --> AH[(agent_health)]
  D -->|cron group-detections| C[(cases)]
  AG -->|cron detect-silent-agents| C
  D -->|cron join-fleet-cases| FC[(fleet_cases)]
  PS -->|cron build-snapshots| SN[(common_set_snapshots)]
  C -->|analyst action| N[(case_narratives)]
  • Events are not stored in PostgreSQL. Every accepted event feeds the prevalence counters; with the archive on, the batch is also queued in lake_batches before the request is answered, and write-lake turns the queue into Parquet. With the archive off, events are counted and dropped.
  • Detections are stored as they arrive, with no case. group-detections later assigns each ungrouped detection to a case of the same agent: same or related ATT&CK technique within 30 minutes (case-grouping.ts). join-fleet-cases then links detections of different agents that share an executed file hash or a non-generic identity within 24 hours into one fleet case (fleet-case.ts).
  • Heartbeats refresh agents.last_seen and store the latest health beacon. An agent with no heartbeat for five minutes is silent: detect-silent-agents opens one case for it, and the notification job tells the tenant's webhooks.
  • Reads combine these: GET /api/cases/[id] returns a case's detections, the fleet prevalence of what each touched, the files its ransomware detections say were renamed or deleted, and the latest narrative, marked stale when a detection joined the case after the narrative was written. GET /api/cases/[id]/graph returns the case's entity graph.

From an operator to the fleet

Content, binary releases, key rotations and snapshots flow the other way: an operator stages artifacts and publishes a manifest signed offline, the server checks it and serves it to the agents of the ring, and agents verify every signature themselves. The server never holds a signing key. Content and releases covers this path.