Skip to content
FlyCockpit
Knowledge Base/ Deployment & REST API
Knowledge Base logo

Deployment, REST API & Backups

Knowledge BaseRust + TypeScriptApache-2.0
Repository

Deploy Knowledge Base on Dokploy with dedicated worker and PostgreSQL 18, automate KBs via the /api/v1 REST API, and run encrypted offline age backups and restores.

Platforms: Linux, macOS, Windows (kb CLI) · Docker (server)

Dokploy on a Linux VPS is the supported production deployment target: one server and one dedicated worker on the same host sharing a single local persistent volume (KB_DATA_ROOT), backed by PostgreSQL 18 and Valkey 9.1 (noeviction).

Production self-hosting (Dokploy)

Generate a pinned Compose stack and environment checklist from a checkout:

pnpm dokploy:config \
  --environment production \
  --git-ref release/<commit-sha> \
  --git-url https://github.com/FlyCockpit/knowledge-base.git \
  --url https://kb.example.com \
  --project knowledge-base-production \
  --proxy-network dokploy-network

Key architectural requirements enforced by the generated Compose:

  • Single host, single replica, stop-first: Both server and worker mount kb-data at /var/lib/knowledge-base (UID/GID 1000, non-root) and hold native volume lifetime flocks. In Swarm, label exactly one node knowledge-base=true. Never delete lock files to recover readiness; a competing startup exits 85 (FENCE_HELD).
  • Base runtime: All images build on Node 26 Debian 13 (trixie) glibc with Git 2.45+ (required for git merge-tree --merge-base). PostgreSQL 18 needs no extensions; Valkey 9.1 runs with AOF and maxmemory-policy noeviction.
  • Mirror tmpfs: The worker mounts a private UID 1000, mode 0700 16 MiB tmpfs (noexec,nosuid,nodev) at /run/kb-mirror for external mirror deploy keys; worker startup refuses a disk-backed directory.
  • Minimal initial secrets: For a fresh deploy, set only POSTGRES_PASSWORD, REDIS_PASSWORD, KB_MASTER_KEY (base64 of 32 random bytes), BETTER_AUTH_SECRET, and ADMIN_EMAIL. Backups, SMTP, SSO, and S3 assets all start disabled.
  • Schema migrations: Server starts with MIGRATE_ON_START=true and applies committed Prisma migrations before HTTP admission; worker starts with MIGRATE_ON_START=false and waits up to 300 s for compatible schema history.

Confirm a deployment is live after rollout:

pnpm deploy:check https://kb.example.com --commit <full-sha>
pnpm dokploy:verify --server <project>-server --worker <project>-worker --url https://kb.example.com

First admin without SMTP (SETUP_KEY)

If email delivery is not configured yet:

  1. Set SETUP_KEY (32–512 random chars, pnpm generate:secret) alongside ADMIN_EMAIL on the server and deploy.
  2. From a checkout, run pnpm deploy:generate-admin --url https://kb.example.com --email admin@example.com and type SETUP_KEY at the prompt to print a 1-hour one-time link.
  3. Open the link, set the password, sign in, enroll 2FA, then remove SETUP_KEY and redeploy.

Home server behind Cloudflare Tunnel

Knowledge Base opens no WebSockets or SSE streams (MCP is POST-only JSON). Run cloudflared either directly on a private Docker network pointing at http://<project>-server:3000 (TRUST_PROXY_HOPS=1) or via Dokploy’s Traefik (TRUST_PROXY_HOPS=2 only after configuring Traefik’s forwardedHeaders.trustedIPs for cloudflared). Never publish the server port on 0.0.0.0 alongside a non-zero TRUST_PROXY_HOPS.

Environment variables reference

The .env.example files are generated from scripts/lib/env-manifest.ts (pnpm env:sync / pnpm env:check).

Variable Role Default / Notes
DATABASE_URL server, worker, offline PostgreSQL 18 connection string
REDIS_URL server, worker Valkey 9.1 / Redis connection string (noeviction)
KB_DATA_ROOT server, worker, offline /var/lib/knowledge-base (holds repos/, assets/, index/, models/)
KB_MASTER_KEY server, worker, offline Required; base64 of exactly 32 random bytes. Encrypts provider keys, sealed records, shares, and mirror deploy keys
BETTER_AUTH_SECRET server, offline Required; strong secret for sessions, password pepper, TOTP, and backup codes
BETTER_AUTH_SECRET_PREVIOUS server, restore Optional during password-pepper rotation (does not cover TOTP/backup codes)
BETTER_AUTH_URL server Required; canonical https:// origin (no path); sets OAuth issuer and MCP resource
ADMIN_EMAIL server Required in production; single canonical bootstrap admin address
SIGNUP_ENABLED server false (closed public signup; admin invitations still work)
SETUP_KEY server Optional temporary 32–512 char key for first-admin bootstrap without SMTP
TRUST_PROXY_HOPS server 0 default (1 in generated Dokploy Compose); exact reverse-proxy hop count
MIGRATE_ON_START entrypoint true on server, false on worker
SMTP_* / SSO_* server Optional email delivery (use port 587 or 465) and SSO configuration
KB_ASSET_S3_ENABLED server, worker, offline false; enables remote S3 asset authority (requires KB_ASSET_S3_BUCKET, _REGION, KB_ASSET_CACHE_MAX_BYTES ≥ 25 MiB, and separate runtime vs operator keys)
BACKUP_ENABLED server, worker, backup false; enables quiesced encrypted bundles before migrations/deletions and daily schedule
BACKUP_AGE_RECIPIENT backup / migration Public age recipient (age1pq1… recommended via age-keygen -pq) when backups are enabled
BACKUP_SCHEDULE / BACKUP_HOUR_UTC / BACKUP_KEEP backup off (set daily), 3, 14
BACKUP_S3_* / BACKUP_MONITOR_S3_* backup / worker Optional off-site S3 target (distinct from both asset S3 key IDs) + ListBucket-only monitor key
KB_CLI_RELEASE_BASE_URL / KB_CLI_SOURCE_REV server Optional mirror URL or commit SHA for /install.sh and /install.ps1

REST API (/api/v1) and credential separation

The /api/v1 REST API is a control plane for automation (for example provisioning one KB per project and minting a scoped agent token for it). It never reads or writes Markdown documents—content work happens over /mcp. The OpenAPI 3.1 spec is served anonymously at GET /api/v1/openapi.json.

Strict separation from MCP tokens

Surface REST API key (kbk_…) MCP PAT (kbp_…) / OAuth
/api/v1/* Accepted Refused (401)
/mcp, /git/*, /kb-assets/*, /rpc Refused (401) Accepted (PAT for Git)

Create API keys in Settings → API keys (max 10 live keys/user; 365-day default expiry; immutable after mint). Each key sets explicit ceilings for reach (all accessible KBs, chosen KBs, or only KBs this key creates), permissions (read/propose/write/review/manage), KB create/delete, token minting, tool groups & write mode, and whether child tokens end when the key ends. Every call intersects the key’s ceilings with the owner’s live permissions.

Automation workflow examples

All create/delete calls (POST /kbs, POST /kbs/{kbId}/tokens, DELETE /kbs/{kbId}) require an Idempotency-Key header (1–128 chars of A-Za-z0-9_-):

export KB=https://kb.example.com
export KEY="$(cat ~/.config/kb-api-key)"   # kbk_...

# 1. Create a knowledge base
curl -sS -X POST "$KB/api/v1/kbs" \
  -H "Authorization: Bearer $KEY" \
  -H "Content-Type: application/json" \
  -H "Idempotency-Key: create-project-42" \
  -d '{"name":"Project 42","slug":"project-42","description":"Notes for project 42."}'

# 2. Mint a propose-only child MCP token for that KB (secret shown once)
curl -sS -X POST "$KB/api/v1/kbs/$KB_ID/tokens" \
  -H "Authorization: Bearer $KEY" \
  -H "Content-Type: application/json" \
  -H "Idempotency-Key: agent-token-42" \
  -d '{"name":"Project 42 agent","bits":["propose"],"toolGroups":["read","edit"],"authoringMode":"edit"}'

# 3. List or revoke child tokens
curl -sS "$KB/api/v1/kbs/$KB_ID/tokens" -H "Authorization: Bearer $KEY"
curl -sS -X DELETE "$KB/api/v1/tokens/$TOKEN_ID" -H "Authorization: Bearer $KEY"

# 4. Tombstone the KB (requires current metadataVersion and confirm: "DELETE")
curl -sS -X DELETE "$KB/api/v1/kbs/$KB_ID" \
  -H "Authorization: Bearer $KEY" \
  -H "Content-Type: application/json" \
  -H "Idempotency-Key: delete-project-42" \
  -d '{"metadataVersion":1,"confirm":"DELETE"}'

Default REST limits (configurable where noted under Admin → Limits): 5 KB creates/owner/hour (shared across web/MCP/REST), 20 live owned KBs/person, 200 live child tokens/API key, 200 child mints/key/hour, and 120 /api/v1 requests/IP/minute.

Encrypted offline backup and restore

Knowledge Base backs up PostgreSQL metadata, bare Git repositories, and asset authority together as a single quiesced, age-encrypted kb/backup/1 bundle (.age + .age.complete marker). Rebuildable SQLite indexes (index/), model weights (models/), and Valkey queues are intentionally excluded. A Postgres-only dump cannot restore a Knowledge Base instance.

Enabling backups and key custody

Backups default off (BACKUP_ENABLED=false). To opt in:

  1. Generate a post-quantum age identity (age v1.3.2 is compiled into the image) and store the private key offline in your operator vault:
age-keygen -pq -o /private/operator/backup-identity.txt
  1. Regenerate your Dokploy Compose with --backups true, set BACKUP_ENABLED=true, supply only the public recipient (age1pq1…) in BACKUP_AGE_RECIPIENT, mount the shared /app/backups volume, and set BACKUP_SCHEDULE=daily on the backup service.
  2. Back up KB_MASTER_KEY, BETTER_AUTH_SECRET, and the private age identity separately from backup bundles and application volumes. Missing required keys refuse restore promotion.
  3. When KB_ASSET_S3_ENABLED=true, bundles record a verified asset-inventory.jsonl without duplicating asset bytes—enable bucket versioning + replication or object lock, and ensure BACKUP_S3_ACCESS_KEY_ID is distinct from both runtime and operator asset S3 keys.

When enabled, taking a backup issues a durable maintenance request that drains server writes and worker jobs (up to 5 minutes), acquires both exclusive volume flocks and database locks, exports a consistent Postgres snapshot + Git/asset inventories, encrypts the bundle, and verifies completion before resuming service. Pending migrations and scheduled deletions automatically require this same bundle.

Restoring into a fresh destination

Restores never overwrite a live deployment. Provision a fresh empty PostgreSQL 18 database and a new empty (or skeleton-only, UID 1000) KB_DATA_ROOT volume, stop server and worker, mount the verified .age + .age.complete pair and private identity read-only, and run the server image’s offline restore command:

# Direct offline server-image invocation
restore /input/bundle.age /keys/identity.txt 00000000-0000-4000-8000-000000000001

# Or via the bundled Linux host helper on Dokploy:
bash host.sh list
bash host.sh backup
bash host.sh drill
bash host.sh restore latest /private/operator/backup-identity.txt <attempt-uuid>
  • Retry rule: If a restore fails after writing its durable intent, leave staging intact and retry with the exact same bundle, identity, target, and <attempt-uuid>.
  • S3 restores: Pass --asset-source-remap when restoring to a replicated bucket/prefix, and run asset-storage cache-reconcile --limit <bytes> --attempt <new-uuid> afterward to initialize an empty local cache ledger before starting runtimes.
  • Post-restore authority reset: Promotion increments the authority epoch, preserves user accounts/roles/tombstones, revokes all sessions, OAuth grants, PATs, and device logins, disconnects external mirrors (destroying deploy keys), places a 7-day hold on scheduled deletions, and schedules fresh SQLite index rebuilds from Git (re-downloading enabled built-in weights automatically). Users sign in anew and mint fresh credentials.
  • Password pepper rotation: Stop all servers, set BETTER_AUTH_SECRET=<new> and BETTER_AUTH_SECRET_PREVIOUS=<old>, start until logs confirm zero hashes remain under the previous key, then remove _PREVIOUS. Note that changing BETTER_AUTH_SECRET invalidates sessions and requires re-enrolling TOTP/backup codes; if a key is lost, recover unusable passwords with pnpm auth:pepper:reset-unusable --allow-non-local --confirm <count>.