System boundaries

Impromptu is split into a browser application, an HTTP API, and a realtime media system. React Router owns navigation and page data. Fastify owns trusted application decisions and HTTP validation. LiveKit carries room presence and WebRTC media.

Zod schemas from the API package form the contract between browser and server. Cloudflare and Envoy sit at the public edge, while OpenTofu describes the Hetzner and Cloudflare resources.

Browser -> Cloudflare -> Envoy -> Fastify
                           `----> LiveKit signaling
Browser ------------------------> LiveKit media

The product name is impromptu and the production domain is impromptu.social. Application code reads both values from the shared PRODUCT constant.

Repository boundaries

apps/api               Fastify API and browser-safe contract export
apps/api/src/accounts  Account registration, login, and sessions
apps/api/src/lobbies   Lobby persistence and lifecycle
apps/api/src/migrations  Versioned PostgreSQL migrations for every feature
apps/web             React Router application and browser tests
deploy               production and staging containers, configuration, and OpenTofu
Dockerfile           local development image
compose.yaml         local development stack
livekit.yaml         local LiveKit configuration

The API is organized by feature. A feature owns its routes and schemas together with their implementation and tests. Shared process configuration and application composition stay at the API source root.

The deploy/ directory is an extractable deployment boundary. It consumes a prebuilt application image and contains the files needed to provision and run both server stacks. Application source is not a runtime dependency of that directory.

API contracts

The API package owns HTTP methods, paths, request schemas, and response schemas. TypeScript types are inferred from those schemas. The browser-safe @impromptu/api/contracts export imports neither Fastify nor LiveKit runtime code.

Fastify validates incoming data and serializes responses against the contract. The browser parses responses with the same schemas. This keeps static types and runtime validation together without parallel DTOs or generated client code.

Realtime authorization

The backend decides whether a participant can publish. The frontend sends the person’s requested role and position, then uses the resulting token. It does not infer a role from room counts or silently change the request.

LiveKit grants are the security boundary:

Role Join Subscribe Publish media Publish data Update own metadata

Debater

Allowed

Allowed

Allowed

Denied

Denied

Spectator

Allowed

Allowed

Denied

Allowed

Allowed

The same role policy applies when the client UI is bypassed. LiveKit remains the source for connected participant presence, and backend allocation must handle concurrent attempts to claim a limited position.

Room features use LiveKit’s official client and React packages.

A participant may change role only while the lobby is waiting. They do so by joining again with the new intent and the current lobby’s id, so a change made inside a private lobby stays in that lobby. After the debate starts, new participants may spectate but cannot claim a debater position. The backend accepts the id only for a live lobby of the same topic, verifies the previous LiveKit token’s signature, expiry, and room grant, and issues a token with the new grants for the same participant identity. The browser remounts the room when the token changes and does not remove that identity through the leave endpoint. Keeping the identity stable preserves private lobby ownership and the Host badge for existing and newly joined viewers. Availability checks exclude the participant’s own current position; a rejected change leaves their reservation and connection intact. An expired room token requires rejoining before changing roles. Leaving or closing a lobby also requires a LiveKit token valid for that room; the server derives the participant identity from the token before releasing a reservation or checking lobby ownership.

The browser keeps the current join result, including the creator’s code, in session storage for that tab. Reloading the room restores the latest role, identity, code, and any spectator name and vote rather than an earlier navigation handoff. Chat messages are not saved in tab storage. A successful leave removes the saved result; a failed leave keeps it. Storage being disabled does not prevent the current room from working.

A token-authenticated participant snapshot checks membership on connection and reconnection. Retrieval failures show an error with a retry button while media, chat, and leaving remain usable. LiveKit presence events continue to drive the roster; entries are deduplicated by identity across counts, video slots, and the participant list. Snapshots never include join codes.

Topic status lists each connected or reserved participant with their role and side, so the browser can present debaters and spectators separately without deciding roles itself.

Accounts and persistence

Accounts and sessions are stored in PostgreSQL through MikroORM, on the same connection as lobbies. database.ts opens that connection with every feature’s entities, and each feature keeps its entities and store beside its routes. Tables change only through the versioned migrations in apps/api/src/migrations, which deployment applies before the application starts. Tests use in-memory stores with the same interface.

Usernames and email addresses are unique without regard to case: email addresses are stored in lower case, and a lower-cased username key carries the username constraint while the username keeps its original spelling. Passwords are hashed with salted scrypt and never stored or logged in plain text.

Signing in creates an opaque random session token. The browser holds it in an HttpOnly, SameSite=Lax cookie, marked Secure in production, and the database stores only its SHA-256 digest with a 30-day expiry. Logging out deletes the session. GET /api/auth/session reports the current account, or none, while account-only endpoints such as GET /api/account answer 401 without a valid session.

The browser validates forms with the same Zod schemas the API enforces. Field errors from the API use one { message, fieldErrors } shape, so client and server validation appear beside the same fields. Account-only pages check the session in their loader and redirect to the login page with a same-origin redirectTo path.

Round and voting deadlines are stored in PostgreSQL. The API schedules a timer for each deadline and reloads unfinished work when it starts. A failed deadline operation is retried; an idle application does not poll the database for work. The health endpoint checks database connectivity and returns 503 when the connection fails.

Frontend

The web application uses React Router Framework Mode, shadcn/ui, Tailwind, and LiveKit’s React package. Route data APIs handle navigation-bound reads and mutations. Local component state and LiveKit hooks cover transient interface and room state.

The API remains the source for application decisions, while LiveKit remains the source for connected-room state. The frontend does not copy either source into a global application store.

The API supplies three starter topics. A person can create another topic with a question, two positions, and public or private visibility. Each topic is its lobby, so its topic ID also identifies its LiveKit room. Created topics and their creator identities are stored in PostgreSQL through MikroORM. Public created topics appear beside the starters; private topics require a code and stay out of public discovery. Codes are hashed at rest. Created topics and codes do not expire automatically. The creator can close a created topic.

LiveKit is authoritative for connected participant presence and display names. Leaving disconnects the participant and releases any pending side reservation. Database schema changes are applied through versioned migrations before deployment.

Server-sent events notify the browser when public topic availability changes. The browser reads a fresh API snapshot after each event and after reconnection. The page route remains /debates/:topicId; tab session storage restores the latest join result after a reload.

A valid private code does not reserve a debater position. If another participant claims the chosen position first, the API rejects the join. Spectating remains available when both positions are occupied.

Guests join public and private lobbies without signing in. Their chosen display name is included in the LiveKit token and appears in the room participant list. Signed-in people have their username suggested as a display name. Debate participation and topic ownership are independent of account state. After the browser disconnects from LiveKit, leave requests release pending reservations and remove the participant from the room. Repeating a leave request is safe. After a successful leave, the browser returns home.

Fastify serves the compiled SPA in production. Vite provides the development server and proxies API requests during local development.

Edge and deployment

Cloudflare provides public DNS, HTTP proxying, and TLS. Envoy is the CNCF origin gateway and routes application traffic separately from LiveKit signaling. LiveKit media reaches the host directly because a standard Cloudflare HTTP proxy does not carry the required media transports.

Production and staging share the Hetzner host and Envoy. They use separate Compose projects, LiveKit instances, and media ports. One PostgreSQL container serves separate databases for production and staging, each owned by a different login role. Database access is restricted to host loopback and the container network. The application roles cannot connect to each other’s databases.

PostgreSQL data lives in a persistent Docker volume in a separate Compose project. Application deployments do not recreate the database or reset its data. Staging stays online at staging.impromptu.social. Each deployment applies versioned migrations and idempotent demo seeds before starting the new image. Database credentials are provisioned separately from application deployments.

OpenTofu owns the Hetzner host, firewall, SSH access, Cloudflare DNS records, origin certificates, and the zone settings required at the edge. Private keys and API credentials remain outside OpenTofu inputs and state. Successful CI for the current main or staging commit gates deployment to its corresponding environment. Each workflow builds an immutable application image, installs its runtime configuration, starts its Compose stack, and verifies the public application and signaling routes. Manual deployment remains available for initial provisioning and recovery.

The root Compose files are for source development. Server configuration belongs under deploy/, including its Dockerfile, Compose stacks, service configuration, scripts, environment template, and infrastructure code.

Verification

The Husky pre-commit hook and GitHub Actions both run npm run ci. A failed gate stops the commit. The command checks formatting, linting, strict TypeScript, tests, production builds, documentation generation, containers, workflows, and infrastructure configuration.

The TypeScript version comes from the root package.json. Tool compatibility is resolved by updating or replacing the affected tool rather than holding TypeScript to an older release.

References

Invitations and password recovery

An invitation link grants guest access to one lobby, including private lobbies. The API signs invitations and rejects altered or expired links. Opening a link shows the current question and availability before joining. Sending an email invitation requires the connected host’s room token and is subject to sending limits. Invitation links preserve the existing role and position checks.

Password recovery gives the same confirmation for registered and unregistered addresses. Reset tokens are random, expire, and are stored only as hashes. A successful reset consumes the token and revokes existing account sessions. Invitation and reset secrets travel in URL fragments to keep them out of HTTP request paths.

Each environment has its own Mailpit container and persistent mailbox. The application submits email over internal SMTP; Mailpit captures it for inspection and does not deliver it to external inboxes. The application proxies its UI and WebSocket updates at /mail/ under the application’s existing origin.

Mailbox access is assigned through configured account IDs. Each mailbox request requires a current session belonging to an allowed account. Mailpit’s HTTP and SMTP ports are reachable only within the local stack or through host loopback on the server. Production and staging use separate ports and mail volumes.