Architecture
Understand how the applianceOne container that holds the bot, panel, worker, and database's services, web API, console, lifecycle loop, feature modules, storage, and job queue fit together before you change the code.
Services and Supervision
The image runs s6-overlay as its init system, with the service graph defined in packages/docker/manifest.json and generated into packages/docker/rootfs/etc/s6-overlay/s6-rc.d/. Nova initializes the appliance contract before any app-owned service starts.
| Service | Kind | Critical | Role |
|---|---|---|---|
nova-container-init | One-shot | No | Validates PUID, PGID, and TZ; chooses /config or a detected legacy /data; prepares keys/ and database/; changes ownership of the whole state directory; and writes the resolved NOVA_* and DATA_DIRECTORY variables |
prepare-state | One-shot | No | Moves the old postgres/ directory to database/ and the version 4.0 key from secrets/credential.key to keys/installation.key, only when each destination is empty |
prepare-postgres | One-shot | No | Validates database settings and initializes PostgreSQL with local trust and no TCP access |
postgres | Long-run | Yes | PostgreSQL 17, running as PUID:PGID, storing its cluster under NOVA_DATABASE_DIRECTORY, and listening only on its Unix socket in /tmp/postgresql with listen_addresses empty |
migrate | One-shot | No | Waits for PostgreSQL, creates the database, clears any role password left from version 4.0, and runs build/migrate.js, which applies migrations and makes, verifies, or converts the installation keyThe key that locks your secrets; back it up with the database |
bot | Long-run | No | The Discord GatewayThe live line from Discord that Start and Stop switch client, apps/bot/src/index.ts |
web | Long-run | Yes | The control panel, its JSON API, and the public routes, apps/bot/src/web.ts and apps/bot/src/server.ts |
worker | Long-run | Yes | Schedules and durable jobsQueued task kept in the database until it's done, apps/bot/src/worker.ts |
The resolved state tree is /config/keys/ and /config/database/ for a current install. Nova publishes it as NOVA_STATE_DIRECTORY, NOVA_KEYS_DIRECTORY, NOVA_INSTALLATION_KEY_FILE, and NOVA_DATABASE_DIRECTORY, with DATA_DIRECTORY as this app's state-root alias.
A critical service that exits with an error halts the applianceOne container that holds the bot, panel, worker, and database. The bot is intentionally not critical, so s6 restarts only that service and leaves the control panel available.
A one-shot that fails stops the container too, because the image sets S6_BEHAVIOUR_IF_STAGE2_FAILS=2.
Web Service and Console
apps/bot/src/web.ts starts the web process: it reads the settings, opens the database pool, prints the setup codeOne-time code from the container log that creates the Owner while no account exists, and serves the Express app from apps/bot/src/server.ts.
- Middleware —
server.tsturns offx-powered-by, trusts forwarded headers only from private and loopback addresses throughisTrustedProxyAddressinlib/http.ts, sets no-store and no-sniff headers, and parses JSON bodies of up to 64 KB, or 2 MB for feature saves and Backup imports. It also reads/webhooksbodies as raw bytes of up to 128 KB, and limits/api/v1to 300 requests a minute per address. - Route order — Health, webhooks, the invite page and its designer API, setup and sign-in, security, tokens, notifications, users, servers, features, the bot, logs, Backup, and last the console with its single-page fallback, then a JSON 404 and the error handler.
- Route modules — Each file in
apps/bot/src/routes/is aRunnerclass with aregister(app)method, and every API failure answers with the shared{ "error": { "code", "message", "issues" } }envelope fromsendError, while most public routes answer in plain text. - Access —
lib/access.tsresolves a browser session from thedsb_sessionanddsb_csrfcookies or adsb_bearer token, then checks the token's scope, the role's permission, and the user's server access. - Sign-in limits —
lib/attempts.tscounts failed passwords, codes, passkeys, and password confirmations per address in memory, 10 in 15 minutes, with a separate count for setup codes. - Backup security —
routes/backup.tsrequires a browser session andusers:managefor every endpoint, so bearer tokens and Operators are refused. Password plus TOTP or a passkey issues a five-minute grant whose digest is bound to one session, one export or import purpose, and one successful use. - Console — The React console lives in
apps/bot/src/web/, withapps/bot/index.htmlandapps/bot/invite.htmlas its two entry pages, which Vite builds intobuild/console. The web route serves the console with a strict content security policy, and the invite route serves the invite page with one that also allows Google reCAPTCHA.
Accounts and Tokens
- Users —
panel_usersholds each account's username, Argon2id password hash, role, and whether it's enabled, andpanel_user_guild_accessholds the chosen servers. - Sessions —
panel_sessionsstores SHA-256 hashes of the session and CSRF tokens, and each session lasts 24 hours. - Second factors —
panel_totp_credentials,panel_totp_enrollments,panel_recovery_codes, andpanel_sign_in_challengesback the authenticator app, whilepanel_passkeysandpanel_webauthn_ceremoniesback passkeys. - Setup —
panel_setup_claimsholds the hash and expiry of the one setup codeOne-time code from the container log that creates the Owner, andlib/panel-setup.tsmakes it and redeems it. - Tokens —
panel_api_tokensholds each token's name, scopes, expiry, last use, and SHA-256 hash, andlib/panel-tokens.tsmanages them.
Lifecycle Reconciliation
- Control row — One
bot_runtime_controlrow holds the desired stateWhether you last told the bot to run or stop, the generation, the encrypted Bot TokenThe bot's password for Discord, from the Developer Portal, and the Discord applicationYour bot's entry in the Discord Developer Portal ID. - Polling — The bot reads the row every
BOT_CONTROL_POLL_INTERVAL_MSand reconciles: stopped disconnects, a missing token reportsconfiguration_required, and a new generation reconnects. - Failures — A failed generation stays failed until the generation changes again, and the bot records each state in
runtime_heartbeats. - Generation — The docs call the generation the revisionA counter that makes the bot reload its latest settings, and lifecycle actions, token saves, feature saves and toggles, and Backup imports all increase it.
Feature Module Contract
connectGateway in apps/bot/src/index.ts is the event kernelThe code that turns saved features into a live bot. For each server from listNormalizedGuildSettings, it calls the prepare*Features function of each GatewayThe live line from Discord that Start and Stop switch module in the table below, which returns the module's active feature keys, configuration errors, intents, and a register function.
- One client — The kernel creates one discord.js
Clientwith the union of every module's intents,shardCount: 1, and no partials. - Registration — It calls each module's
register(client, guildId), then logs in with a 15-second limit and synchronizes the server registry. - Validation —
apps/bot/src/lib/feature-configuration-validation.tsruns the sameprepare*Featurescompilers with the real secret values when the API saves, enables, or imports a feature. An olderconfig.jsonsource validates the actual secret before it encrypts and stores it. - Slash commandsA /command members type in Discord's message box —
apps/bot/src/lib/application-commands.tscollects command contributions by server on one client and independently overwrites each server's command set when the client is ready.
| Module | Features |
|---|---|
anti-raid-features.ts | Anti-raid |
audit-features.ts | Audit notifications |
gateway-features.ts | Event broadcasts, thread bumping, role messages |
impersonator-features.ts | Impersonator alerts |
message-features.ts | Auto replies, suspicious words, regex rules, affiliate cleanup |
message-routing-features.ts | Message copiers, message proxies |
role-sync-features.ts | Role synchronization |
scammer-features.ts | Scammer alerts |
server-tool-features.ts | Server tools |
worker-features.ts | Scheduled posts, permission toggles, RSS feeds |
web-application-features.ts | Web applications |
The last two modules run outside the kernel: the worker's scheduler runs worker-features.ts to queue jobs, and the web service runs web-application-features.ts for the invite page and webhooks.
One GatewayThe live line from Discord that Start and Stop switch client serves every configured server. A command synchronization failure is logged with its Server ID and does not prevent the remaining servers from receiving their commands.
Configuration Storage
- Feature settings —
guild_featuresandguild_feature_valuesstore each setting as a typed path row, not as one JSON document. - Server profile —
guild_profilesholds each server's imported time zoneThe zone a schedule's times are read in; UTC by default and a settings version number. - Discovery —
discord_servers,discord_channels, anddiscord_roleshold what server discoveryThe bot lists its servers, channels, and roles for you found, and rows are marked unavailable instead of deleted. - Secrets —
guild_secretsholds encrypted feature secrets, keyed by the reference each feature setting stores. - Invite pages —
guild_invite_pagesholds each server's invite page design, andguild_invite_imagesholds its uploaded logos and banners. - Notifications —
notification_targetsholds each destination's name, service, events, and plain settings, with its secret fields sealed together insecrets_ciphertextand their names insecret_fields. - Exports —
lib/backup.tsopens only the selected Connection, Features, Notifications, and Access tokens sections. Secrets exist only in the response document, access tokens remain stored hashes, and users, sign-in security, sessions, logs, and Discord runtime data never enter the format. - Export-file imports — One transaction replaces included Connection and per-server Features sections, merges Notifications by case-insensitive name, adds nonduplicate access-token hashes for the importing user, and leaves omitted sections unchanged.
- Older config.json imports — One transaction replaces the selected server's feature rows and secrets, optionally updates the global Bot Token, and appends the
legacy_importsreport. Invalid legacy feature configurations are preserved disabled rather than weakening runtime validation.
Durable Jobs and Scheduler
- Queue — The
jobstable has a uniquededupe_key, and the workerBackground service that runs schedules and deliveries claims one job at a time withFOR UPDATE SKIP LOCKED, reclaiming locks older than 5 minutes. - Retries — A failed job returns to pending after 30 seconds and becomes
failedafterJOB_ATTEMPT_LIMITclaims, and jobs are never deleted. The last failure of any job but a notification queues a Job gave up notification throughnotifyJobFailedinlib/notifier.ts. - Job types —
discord.message.send,discord.permissions.apply,rss.feed.fetch,notification.send, andsystem.noop. - Notifications —
queueNotificationadds onenotification.sendjob for each destination that chose the event, with a dedupe key built from the event, the occurrence, and the destination. - Scheduler — One cursor named
worker-featuresinscheduler_cursorsscans every second since the last scan, capped at 24 hours, and queues jobs only while the desired stateWhether you last told the bot to run or stop is running with a token. - RSS state —
rss_feed_cursorsstores each feed's validators and recent item hashes.
Credential Vault
apps/bot/src/lib/credential-vault.ts encrypts values with AES-256-GCM, using the key from NOVA_INSTALLATION_KEY_FILE and associated data of the form discord-stonker-bot:<purpose>:v1.
| Purpose | Used for |
|---|---|
discord-token | The Bot TokenThe bot's password for Discord, from the Developer Portal |
guild-secret:<server ID>:<key> | Each feature secret |
panel-totp:<user ID> | Each authenticator appA phone app that makes six-digit sign-in codes secret |
panel-totp-enrollment:<user ID> | An authenticator appA phone app that makes six-digit sign-in codes setup that isn't finished yet |
notification:<destination ID> | The secret fields of one notification destination, sealed together |
credential-key-check | The check value that proves the key file belongs to this database |
apps/bot/src/lib/credential-key.ts runs in the migration job after the SQL files, so the key is ready before the bot, web, and workerBackground service that runs schedules and deliveries read it. prepareCredentialKey makes the key as 64 lowercase hexadecimal characters plus a newline when the file is missing, checks an existing key against the database, and atomically converts the version 4.0 raw 32-byte representation without changing the key bytes.
- Key check —
credential_key_checkholds one known value sealed with the key. A key that can't open it stops the migration job with the mismatch error, and a database without one is tested with one stored secret, then gets one. - Lost key — A missing file gets a new key, and one transaction clears the Bot TokenThe bot's password for Discord, from the Developer Portal, every
guild_secretsrow, each authenticator appA phone app that makes six-digit sign-in codes with its recovery codesA one-time backup code for when your authenticator is gone, every unfinished authenticator setup, and the sealed secrets of every notification destination, whose field names move tomissing_secrets. Each removed item becomes aremoved_secretsrow, the key file is written last, andmigrate.tslogscredential_key_replacedwith the list and queues a Saved secrets were removed notification. - Notice —
apps/bot/src/lib/removed-secrets.tsreturns the rows a user may act on asremovedSecretsinGET /api/v1/auth/mefor a browser sessionYour browser's sign-in, good for 24 hours, andDELETE /api/v1/auth/removed-secretsrecords a dismissal of them for that user with the CSRF header and answers204. Tokens get noremovedSecretsfield, and the delete answers them with403session_required. - Items — Each item has a
kindofbot-token,feature-secrets,authenticator, ornotificationand aremovedAttime. Feature items also carryserverId,serverName,featureKey, andfeatureName, and notification items carrynotificationIdandname, so the console can open the right page. - Visibility — Each user sees their own
authenticatorrow, and roles that can change settings also seebot-token, everynotificationrow, and thefeature-secretsrows of the servers they can open. Saving the Bot TokenThe bot's password for Discord, from the Developer Portal, saving a feature, importing a server's settings through Backup, and turning on an authenticator appA phone app that makes six-digit sign-in codes each delete the matching rows, and so does saving a notification destination with every removed secret, or removing it.
Database Migrations
apps/bot/src/migrate.ts applies every .sql file in apps/bot/migrations in name order and records a SHA-256 checksum for each in schema_migrations. Today that's one file, 001-initial.sql, which builds the whole 4.0.0 schema, and later changes go in new numbered files. A migration file that changes after it was applied stops the migration job.
After the last file, it prepares the installation keyThe key that locks your secrets; back it up with the database as described in Credential Vault. Any error is logged as migration_failed, and the bot, web, and workerBackground service that runs schedules and deliveries don't start.