# Backant — Complete Machine-Readable Technical Reference (llms-full.txt) > Canonical single-file technical documentation for LLMs and AI coding agents. > Index map: https://backant.app/llms.txt · OpenAPI 3.1: https://backant.app/openapi.json · Security: https://backant.app/docs/security.html · Comparison: https://backant.app/docs/compare.html --- ## Part 1: Platform Overview, Published Releases & Operational Boundaries # Backant > **Any coding agent. Any frontend. One backend standard.** Backant is a coherent backend platform combining code-first TypeScript development with visual Flow DAG orchestration, multi-tenant application authentication, BullMQ background jobs, Cloudflare R2 storage, and SSE Live Queries — designed for human engineers and AI coding agents. ## Published Packages & Releases - **CLI (`backant-cli`)**: `0.5.25` — https://www.npmjs.com/package/backant-cli · https://github.com/backant-app/backant-cli - **Desktop (`Backant.app`, macOS Apple Silicon)**: `0.5.7` — https://github.com/backant-app/backant-desktop/releases/download/v0.5.7/Backant-0.5.7-arm64.dmg - **Auth SDK (`@backant-app/auth-sdk`)**: `0.2.0` — https://www.npmjs.com/package/@backant-app/auth-sdk · https://github.com/backant-app/backant-auth-sdk - **Live Query SDK (`@backant-app/live-sdk`)**: `0.1.0` — https://www.npmjs.com/package/@backant-app/live-sdk · https://github.com/backant-app/live-sdk ## Core Architecture - **Database**: MongoDB 7 replica set (`rs0`) with multi-tenant, multi-environment `modelData` envelopes (`{ serverId, env, modelName, data, createdAt, updatedAt }`) and separate databases for `staging` and `production`. - **Workflows**: Native 10-node strict Flow DAG engine (`trigger`, `action`, `if`, `switch`, `loop`, `parallel`, `retry`, `delay`, `subflow`, `human`) with cycle-free `[FLOW-DAG-001]` validation, JEXL expressions, symmetric `ctx` capabilities (`ctx.models`, `ctx.services`, `ctx.assets`, `ctx.jobs`, `ctx.secrets`), and execution logs. - **Action Runtime & Deadlines (Contract v2 — `schemaVersion: 2`)**: Route handlers (`export default async function (ctx)`), Flow actions (`(ctx, input)`), and Jobs (`(ctx)`) share a pure, code-exportable `ctx` contract (`ctx.req`, `ctx.models`, `ctx.services`, `ctx.assets`, `ctx.jobs`, `ctx.secrets`, `ctx.json(data, status)`, `ctx.error(status, code, message)`). Legacy v1 `(req, res)`, `this.*`, and raw `ctx.db` emit `[MIGRATE-V2-*]` Tombstone diagnostics through `v0.8.0` and upgrade automatically via `backant migrate`. Synchronous HTTP actions run with a unified `AbortSignal` deadline budget (`60s` default, configurable up to `90s` via `config.ts`, `25 MB` max `fetch()` response). JSON/form bodies are capped at `5 MB` (`413 PAYLOAD_TOO_LARGE`); malformed JSON (`400 INVALID_JSON`) and unsupported encodings (`415`) return deterministic `4xx` responses. - **Background Jobs**: Redis + BullMQ durable queues (separate Redis instances for staging and production) with startup reconciliation, `300s` default / `600s` max job deadline budgets propagated to `fetch()` and `ctx.services`, worker-role isolation (`ENABLE_INTERNAL_JOB_WORKERS`), dedicated worker services, and full sandbox support (`fetch`, `Blob`, `File`, `FormData`, `ctx.assets`, `ctx.services.stt`, `ctx.services.pdf`, `ctx.secrets`). - **Storage & Media**: S3-compatible Cloudflare R2 with tenant-scoped keys (`tenants/.../assets/...`), presigned & multipart uploads (`1 GB`), zero-config wildcard/ETag CORS sync, server-side `ctx.assets.getBuffer()`/`completeUpload()`, custom-route `multipart/form-data` (`ctx.req.files`, `25 MB`/file, `50 MB` total), and built-in `ctx.services.stt.transcribe()` (Groq/OpenAI Whisper with `429` retry). Built-in HTML → PDF via `ctx.services.pdf.render({ html, format, margin, headerHtml, footerHtml })` → `{ buffer, mimeType, size }` (isolated headless-Chromium/Gotenberg sidecar; JS disabled, public `https://` assets only, `2 MB` HTML / `25 MB` PDF / `30s` limits) — no Puppeteer or external PDF API needed. Note: `auth.storage.*` requires an active `auth.login()` session (`401` otherwise); no-auth apps use Action `ctx.assets.getUploadUrl()` + `completeUpload()`. Never send binary files as base64 JSON (`5 MB` JSON cap). - **Realtime**: Server-Sent Events (SSE) Live Queries (`/api/live-query/*`) consumed via `@backant-app/live-sdk`. - **Application Auth & RBAC**: Strictly isolated from platform developer accounts. Supports four templates (`basic-auth`, `role-based`, `saas`, `advanced-access-control`), TOTP MFA, OAuth, organizations, and Bring-Your-Own-Provider (BYOP) transactional email. - **Developer & AI Workflow**: Bidirectional CLI ↔ Studio sync (`backant push` / `backant pull`), OAuth 2.1 + PKCE login (macOS Keychain), per-project account pinning (`.bestudio/targets.json`), global `SKILL.md` installation (`backant skill sync --global`), and built-in stdio MCP server (`backant mcp`). ## Security, Operational Boundaries & Current Status - **Studio Access**: Backant Cloud Studio (`https://app.backant.app`) is currently Invite-Only Early Access. CLI, SDKs, and macOS Desktop are publicly downloadable. - **Snapshot Rollback Scope**: Definition snapshots cover schemas, routes, actions, flows, jobs, services, and auth configs. Reverting a snapshot restores definitions without touching live customer records (`modelData`), application users, or uploaded R2 assets. - **Action Runtime Threat Model**: Host-side egress (DNS-pinned SSRF & 25 MB wire/decompressed stream caps), `ModelQueryPolicy` (PCRE2+RE2 safe regex & query caps), pre-operation quotas, static AST `config.ts` manifests, and `$secret:KEY` Host header injection are enforced by the platform host; migrating handler execution from in-process `vm2` to a dedicated untrusted isolate runner + `gVisor` boundary is tracked on the pre-GA roadmap. - **macOS Binary Signing**: Preview macOS DMG builds are not yet notarized with an Apple Developer ID (first launch requires removing the macOS quarantine attribute). - **Data Ownership & Export-First Design**: Project definitions are plain TypeScript and JSON (`schemaVersion: 2`) in Git, constrained to standard Express/Zod/MongoDB/BullMQ/S3 primitives with zero un-exportable runtime magic. Application records live as standard MongoDB JSON/BSON documents (exportable to NDJSON + `manifest.json` via `backant data export`) and assets live in standard S3-compatible R2 storage. Standalone code export (`backant export`) is on the active roadmap. ## Documentation & Links - [Homepage](https://backant.app/): Platform overview and interactive capability walkthroughs - [Full Machine-Readable Reference (`llms-full.txt`)](https://backant.app/llms-full.txt): Single-file complete technical reference compiled from `llms.txt` and official AI agent skills - [OpenAPI 3.1 Specification (`openapi.json`)](https://backant.app/openapi.json): Machine-readable HTTP API contract for Application Auth, Managed R2 Storage, Live Query SSE, and Health - [Developer Documentation](https://backant.app/docs/): Quickstart, architecture, security boundaries, and full CLI reference - [Backant MCP Server Guide](https://backant.app/docs/mcp.html): Official stdio MCP setup (`npx -y backant-cli mcp`) for Claude Code, Cursor, Antigravity, Codex, and Windsurf - [Auth & BYOP Email Guide](https://backant.app/docs/auth-and-email.html): Application auth templates, organizations, and BYOP email setup - [Security Architecture & VDP](https://backant.app/docs/security.html): Encryption, tenant isolation, runtime threat model, and vulnerability disclosure (`/.well-known/security.txt`) - [Backant vs. Convex, Supabase, Appwrite, Encore.ts & Firebase](https://backant.app/docs/compare.html): Objective engineering comparison, AI coding agent DX deep dive, and portability trade-offs - [Public Roadmap & Changelog](https://backant.app/docs/roadmap.html): Shipped milestones, active priorities, and pre-GA gates - [Reference Examples (`backant-examples`)](https://github.com/backant-app/backant-examples): CI-validated Contract v2 reference backends (`saas-tasks` and `ai-doc-pipeline`) - [Backant Studio](https://app.backant.app): Web control plane and visual Flow canvas --- ## Part 2: Official AI Agent Skill (SKILL.md) # Work with Backant projects Backant is a backend platform whose project definitions can be managed as files and deployed with the `backant` CLI. Follow the project’s existing structure and let the CLI validate changes before reporting them complete. ## Discover before changing - Read the project’s `AGENTS.md` and `backant.config.json` (or legacy `bestudio.config.json` in older projects), then inspect the files related to the requested change. - Start with `backant --help`; use `backant --help` before relying on unfamiliar arguments or options. - The installed CLI is authoritative for available commands. Do not assume a command exists because another platform has it. - Reuse valid project examples where available. If the project has no relevant example, consult `references/project-definitions.md` for the supported model and flow basics. - For application auth templates, BYOP email, organizations, data/custom policies, and admin vs runtime APIs, use `references/auth-and-email.md` and `be-studio-backend/docs/application-user-management.md`. - For zero-config built-in Storage (Cloudflare R2 presigned/multipart uploads, `auth.storage`, `ctx.assets`, and `backant storage`), use `references/storage.md`. ## Make focused changes - Keep edits within the requested project area and preserve unrelated files and user instructions. - Do not invent schemas, fields, node types, or runtime APIs. Use existing definitions, the reference file, and validation errors as evidence. - For Route actions (`routes/*/action.ts`), always use the Contract v2 single-parameter signature `export default async function (ctx)` — never `(req, res)`, `this.*`, `res.json()`, `ctx.db`, or inline arrow exports — and follow the sandbox rules in `references/project-definitions.md`. Read request data via `ctx.req.{body,params,query,headers,files,user}` and return values directly or via `return ctx.json(data, status, headers)`. If an older project uses `schemaVersion: 1` or `(req, res)`, run `backant migrate`. - Custom routes automatically parse `multipart/form-data` into `ctx.req.files` (default `25 MB`/file, `50 MB` total; use `file.toFile()` / `file.toBlob()` with `FormData`). JSON/form request bodies are capped at `5 MB` (`413 PAYLOAD_TOO_LARGE`) — never send PDF/audio/video/image files as base64 JSON; use `multipart/form-data` or direct R2 presigned upload (`ctx.assets.getUploadUrl()` -> `PUT` -> `ctx.assets.completeUpload()`). - Actions, Flows, and Jobs share unified `ctx` capabilities: `fetch()` (`25 MB` response cap; inherits the enclosing Action `60s` default / `90s` max or Background Job `300s` default / `600s` max `AbortSignal` deadline), `Blob`, `File`, `FormData`, `ctx.models`, `ctx.services`, `ctx.assets`, `ctx.jobs`, and `ctx.secrets`. For slow LLM/TTS/batch tasks (35–45s+ and mandatorily >90s), prefer `ctx.jobs.run()`. - **Built-in PDF:** Server-side HTML → PDF is built in via `ctx.services.pdf.render({ html, format, landscape, margin, headerHtml, footerHtml })` → `{ buffer, mimeType, size }` (isolated Chromium sidecar; JavaScript disabled, only public `https://` assets / `data:` URIs, `2 MB` HTML / `25 MB` PDF / `30s` limits). Do not add Puppeteer or an external PDF SaaS; save the buffer with `ctx.assets.create()`. See `references/storage.md`. - **Storage Auth Rule:** `auth.storage.*` requires an active `auth.login()` session (`401` otherwise). For no-auth/single-user apps without login, issue presigned R2 URLs via backend Action `ctx.assets.getUploadUrl()` -> browser `PUT` -> `ctx.assets.completeUpload(uploadId)` instead of calling `auth.storage.*` directly. - For `models.` operations in actions, flows, and jobs, follow the exact `Models Runtime API` contract in `references/project-definitions.md` (do not guess Mongoose/Mongo driver signatures). - For Flow action code, follow the `(ctx, input)` interface described in `references/project-definitions.md`. - Do not expose credentials, tokens, or secret values in files, command output, or the final response. ## Validate in a closed loop 1. Run `backant validate` after making project definition changes. 2. If it reports errors, inspect the named file and message, fix the cause, and run validation again. 3. Continue until validation succeeds. Report any remaining warning or limitation accurately. 4. Do not claim the project is valid based only on successfully writing files. ## Push only when requested - Confirm the requested target environment before deployment. `--env` selects the environment; it does not select the server. - Do not push unless the user asks to deploy or push. Never target production unless the user explicitly requests it. - The CLI defaults to Backant Cloud. Check `backant push --help` for the current options before pushing. - After an explicitly requested push, report the selected environment and the CLI result. ## Error Reporting - Backant API 5xx errors and unexpected CLI crashes are automatically reported when telemetry is enabled. - Never manually report an error that was already automatically reported. - Use `backant report --type dx` for undocumented DX or documentation problems not captured by the CLI. - Never attach project files, schemas, environment variables, or secrets without explicit user permission. - To triage failed action requests (`5xx` or `traceId: "tr_..."`), use `backant logs list --errors --since 24h` or `backant logs list --trace `, then `backant logs get ` to inspect `httpCalls` (including `errorCode` / `errorCause` on transport failures) and `dbOperations`. --- ## Part 3: Reference: Project Definitions, Contract v2, Flows & Jobs # Model, Route, Action, and Flow definitions (Contract v2 — `schemaVersion: 2`) Use this reference when creating or changing a model, HTTP route, action, job, or Flow. Prefer valid examples already present in the project; `backant validate` is the final structural check. If an existing project still uses `schemaVersion: 1` or legacy `(req, res)` / `this.*` syntax, run `backant migrate` first. ## Routes & Actions (`routes//`) - Store each route in `routes//route.json` with `method` (`GET`, `POST`, `PUT`, `PATCH`, `DELETE`), `path` (starting with `/`), and either `action` (e.g. `"./action.ts"`) or `flow` (a flow folder ID). - Store HTTP action handlers in `.ts` files (typically `routes//action.ts`) using a **named or anonymous default function export with a single `(ctx)` parameter**: `export default async function (ctx) { ... }` - Inline arrow default exports (`export default async (ctx) => ...`), named-only exports (`export const handler = ...`), multi-parameter `(req, res)` signatures, `this.*` bindings, `res.json()`, and raw `ctx.db.collection()` calls are rejected by `backant validate` (`[MIGRATE-V2-*]`). - **Request & Response on `ctx`:** - Read request inputs from `ctx.req`: `ctx.req.body`, `ctx.req.params`, `ctx.req.query`, `ctx.req.headers`, `ctx.req.files`, `ctx.req.user`, `ctx.req.method`, `ctx.req.path`. - Return JSON (`200 OK`) by returning a plain serializable object: `return { ok: true, items };`. - Return a custom HTTP status or response headers with `return ctx.json({ error: "Not found" }, 404)` or `return ctx.json({ data: created }, 201, { "x-request-mode": "created" })`. - Raise deterministic HTTP errors from anywhere in the handler via `ctx.error(400, "TITLE_REQUIRED", "Title is required")`. - **Unified Ecosystem Capabilities on `ctx` (Routes, Flows, and Jobs):** - `ctx.models.` — Validated Model CRUD API (enforces Zod schemas and `applicationAuth.dataPolicies`). - `ctx.services` — Platform services (`llm`, `tts`, `stt`, `image`, `pdf`, `csv`, `json`, `video`, `email`, `alignment`). Built-in, always-on: `ctx.services.stt.transcribe()` and `ctx.services.pdf.render()` (HTML → PDF, see `references/storage.md`). - `ctx.assets` — Built-in Cloudflare R2 object storage (`getUploadUrl`, `completeUpload`, `getSignedUrl`, `getBuffer`, `create`, `list`, `delete`). - `ctx.jobs` — Durable BullMQ background job queue (`await ctx.jobs.run(jobId, payload)`). - `ctx.secrets` — Frozen environment & Account Vault secrets (`ctx.secrets.GEMINI_API_KEY`). - `ctx.env` (`"dev" | "staging" | "prod"` in Routes; `{ serverId, env, userId?, tenantId? }` in Flows), `ctx.signal` (`AbortSignal`), `ctx.config` (`config.ts` exports). - TypeScript type annotations (`: any`, `interface`, `type`, `as const`), top-level `const` declarations, and helper functions above `export default async function` are supported and transpiled for the sandbox. - **Sandbox restrictions:** Do not use runtime `import` statements (other than `import type`), `import()`, `require()`, `process.`, `fs.`, `global.`, `eval()`, `Function()`, `child_process`, `__dirname`, `__filename`, or raw `ctx.db`. Use `ctx.models`, `ctx.services`, `ctx.assets`, `ctx.jobs`, `ctx.secrets`, and `fetch()` (`25 MB` max response; `fetch()` inherits the enclosing Action `60s`/`90s` or Job `300s`/`600s` `AbortSignal` deadline; `Blob`, `File`, and `FormData` are available in both Action and Job sandboxes). - **Execution Timeouts, Quotas & Sync vs Background Jobs:** Synchronous HTTP actions are for interactive requests (`60s` default; exceptionally override up to `90000ms` via `config.ts` using `export const timeoutMs = { value: 90000, options: { type: "number", label: "Action Timeout (ms)" } }`). Each execution enforces pre-operation Host quotas (`200` DB ops, `30` outbound HTTP requests, `10` job enqueues, max spawn chain depth `3`, `256 KB` job payload; `429 RESOURCE_QUOTA_EXCEEDED`) and bounded admission concurrency (`429 EXECUTION_QUEUE_FULL`). For slow LLM/TTS/vision/batch work that may exceed `35-45s` — and **mandatorily** for anything over `90s` — enqueue a Background Job via `ctx.jobs.run(jobId, payload)` (fire-and-forget returning `{ jobId }`, then track via job status / realtime; jobs have a `300s` default / `600s` max deadline budget). Avoid blocking HTTP actions with `ctx.jobs.run(..., { wait: true })` for slow workloads. - **Static `config.ts` Manifests, Scoped Secrets & Outbound Egress Policy:** `config.ts` files are parsed statically via TypeScript AST (never executed as arbitrary JS; dynamic calls, `process.env`, and spreads fail with `CONFIG_MUST_BE_STATIC_MANIFEST`). Prefer **Tier-1 Host-Side Secret Injection** via `export const secretBindings = { STRIPE_KEY: { allowedHosts: ["api.stripe.com"], headerName: "Authorization" } } as const;` and pass `headers: { Authorization: "Bearer $secret:STRIPE_KEY" }` to `fetch()` so secret plaintext stays on the Host (`$secret:KEY` is permitted once per allowed HTTPS header value, rejected in URLs/bodies or conflicting case-insensitive headers with `SECRET_HEADER_CONFLICT`, and stripped on redirects). When raw string access on `ctx.secrets` is required (e.g. webhook HMAC verification), declare `export const secrets = ["STRIPE_WEBHOOK_SECRET"] as const;` and optional `export const egress = ["api.stripe.com"] as const;`. Outbound `fetch()` blocks internal/private/metadata IPs (DNS-pinned), enforces `25 MB` wire and decompressed stream caps (`EGRESS_DECOMPRESSION_LIMIT_EXCEEDED`), and strips sensitive headers across cross-origin redirects. - **Multipart uploads:** Custom routes automatically parse `multipart/form-data` (default: `25 MB` per file, `50 MB` total, `5` files max). Text fields populate `ctx.req.body` and uploaded files populate `ctx.req.files` with `{ fieldname, originalname, mimetype, size, buffer, toBlob(), toFile() }`. ## Models - Store each model in `models//model.json`. - `modelName` is required, starts with an uppercase letter, and contains only letters and numbers. - The folder name must match `modelName` case-insensitively. For example, `ShortsProject` belongs in `models/shortsproject/` under the current validator. - `fields` must be a non-empty array. Each field needs `name`, `type`, and a `rules` array (which can be empty). - Supported field types are `string`, `number`, `boolean`, `date`, `object`, `array`, and `objectId`. - Indexes are optional; each index needs a non-empty `fields` array. ### Models Runtime API (`ctx.models.`) In Route actions (`ctx.models.`), Flow actions (`ctx.models.`), and Jobs (`ctx.models.`), each defined model exposes: - `validate(data)` → `{ valid: boolean, errors?: Array<{ field, message, value? }> }` - `find(query?, options?)` → `Promise` (`options`: `{ sort?, limit?, skip?, projection? }`) - `findOne(query, options?)` → `Promise` - `findOneById(id)` → `Promise` - `count(query?)` → `Promise` - `create(data)` → `Promise<{ success: boolean, data?: any, error?: string, validation?: ... }>` - `createMany(items)` → `Promise<{ success: boolean, data?: any[], errors?: Array<{ index, error }> }>` - `updateOne(query, update)` → `Promise<{ success: boolean, data?: any, error?: string, validation?: ..., count?: number }>` - `updateMany(query, update)` → `Promise<{ success: boolean, error?: string, validation?: ..., count?: number }>` - `delete(query)` / `deleteOne(query)` → `Promise<{ success: boolean, error?: string }>` - `deleteMany(query)` → `Promise<{ success: boolean, error?: string, count?: number }>` Important runtime rules: - `updateOne(query, update)` and `updateMany(query, update)` accept a **plain partial object** (e.g. `{ status: "approved" }`) or MongoDB update operators (`{ $set: { status: "approved" } }`). - `createdAt` and `updatedAt` are **server-managed** (`updatedAt` is overwritten with the server's `new Date()` on every update). Always check `result.success` to verify an operation succeeded — never compare `result.data.updatedAt` against a client-computed timestamp. - Write/delete methods return a `{ success, data?, error?, count? }` envelope, whereas `find`/`findOne`/`findOneById` return the model data object(s) directly. - `ModelQueryPolicy` enforces `limit <= 500` on `find()` (default `500`), `createMany` batch size `<= 100` (`1 MB` per document), `sort` up to `3` fields, `projection` up to `50` fields, and linear-time PCRE2+RE2 safe `$regex` patterns (`<= 128` chars, `i`/`m`/`s` flags only, no nested quantifiers `(a+)+`, no lookarounds/backreferences, and no multiple unbounded `.*` wildcards -> `400 UNSAFE_REGEX_PATTERN`). ## Flows (`flows//flow.json`) - Store each Flow in `flows//flow.json`. - The root object needs a non-empty `entry` node ID and a `nodes` object. The entry value must be a key in `nodes`. - Each node’s `id` must match its key. `nodeName` must be unique within the Flow and match `/^[a-zA-Z][a-zA-Z0-9_]*$/`. - Supported node types are `trigger`, `action`, `if`, `switch`, `loop`, `parallel`, `retry`, `delay`, `subflow`, and `human`. - **Strict DAG Invariant (`[FLOW-DAG-001]`):** Every Flow graph (and every `loop`, `retry`, and `parallel` subgraph) must be a **Directed Acyclic Graph (DAG)** with zero back-edge cycles. Always express iteration using `loop` or `retry` nodes so Flows remain deterministically executable and compilable to structured TypeScript. - A node transition uses an object such as `"next": { "nodeId": "saveProject" }`; the referenced node must exist. - An `action` node needs non-empty code using the `(ctx, input)` signature (`export default async function (ctx, input) { ... }`). The Flow runtime exposes `ctx.models`, `ctx.services`, `ctx.assets`, `ctx.jobs`, `ctx.secrets`, `ctx.vars`, `ctx.results`, and `ctx.trigger`. - An `if` node needs a non-empty `condition` and a valid `then` reference; `else` is optional. For less common node types, inspect a working project example and the detailed errors from `backant validate`. Do not infer runtime behavior from structural validity alone. --- ## Part 4: Reference: Application Auth, Organizations & BYOP Email # Application auth and email (Backant CLI) ## Templates Use `backant auth templates` or `backant auth add