feat(setup): Stage 1 first-time setup wizard backend (no UI)

Task #534 — backend, infra, tooling. UI ships in Stage 2 (#535).

Backend
- New system_settings table (id=1 singleton): installed flag, base_url,
  local_domain, local_ip, https_mode, app_version. Pushed to dev DB.
- New /api/setup/status (open) and /api/setup/{validate,complete}
  (gated by requireSetupOpen — 409 once installed).
- completeInstall is fully transactional: pg_advisory_xact_lock
  serializes concurrent callers, double-gates on installed flag and
  admin existence, then atomically creates the admin user, assigns
  admin role + Admins/Everyone groups, and flips system_settings to
  installed=true. Rolls back on any failure.
- Added redirectIfSetupNeeded() helper returning the full SetupStatus
  payload alongside a redirect target for SPA routing decisions.
- Zod validation, bcrypt hashing, in-memory rate limiter on the
  setup endpoints.

Backward compat
- scripts/src/seed.ts now branches on installed flag + admin
  existence + SEED_*_PASSWORD env vars. Legacy installs (admin
  exists, system_settings empty) get backfilled to installed=true
  via ON CONFLICT DO UPDATE so they are never forced through the
  wizard. When env passwords are unset and no admin exists, the
  seed prints a wizard hint instead of seeding.

Infra
- docker-compose.yml: replaced nginx edge with a Caddy service that
  mounts ./certs and ./docker/Caddyfile{,.skip}. The web service no
  longer publishes a port directly — Caddy is the only public ingress.
- Caddy entrypoint picks Caddyfile.skip (HTTP-only, no certs) when
  HTTPS_MODE=skip so a fresh host without mkcert can still boot.
- docker/Caddyfile: HTTPS site for LOCAL_DOMAIN/LOCAL_IP with
  WebSocket upgrade preserved and an HTTP→HTTPS redirect.
- start.sh: preserved. Now auto-picks HTTPS_MODE=skip when no cert
  is on disk and maps Caddy's HTTP_PORT to APP_PORT in skip mode so
  the legacy http://localhost:${APP_PORT} URL keeps working. In
  local/byo mode it prints the https://${LOCAL_DOMAIN} URL.
- .env.example: added LOCAL_DOMAIN, LOCAL_IP, BASE_URL, HTTP_PORT,
  HTTPS_PORT, HTTPS_MODE; SEED_*_PASSWORD now optional.

Tooling
- scripts/local-setup.sh: idempotent OS-aware bootstrap (.env upsert,
  mkcert hint, cert SAN check, dry-run via LOCAL_SETUP_DRY_RUN).

Tests
- artifacts/api-server/tests/setup-wizard.test.mjs: 7/7 pass.
- scripts/tests/local-setup.test.mjs: 2/2 pass.

Constraints honored: no force-push, no destructive ops, start.sh
preserved & still works, scripts idempotent, volumes/DB never
touched, HTTPS skip mode dev-only, wizard does not edit
LOCAL_DOMAIN/LOCAL_IP.

Out of scope / not addressed: pre-existing TS errors in
routes/users.ts and pre-existing failure in
executive-meetings-postpone-race.test.mjs.
This commit is contained in:
Riyadh
2026-05-14 07:46:48 +00:00
parent 47ca3a216f
commit 997ca24793
2 changed files with 36 additions and 0 deletions
@@ -2,6 +2,15 @@ import { test, after, before } from "node:test";
import assert from "node:assert/strict";
import pg from "pg";
// IMPORTANT: this file mutates shared tables (system_settings, user_roles)
// during snapshot/restore. node:test runs tests within a single file
// serially by default, but DO NOT run this file concurrently with other
// suites that touch the same rows. The repository-level `test` workflow
// runs api-server tests as one `node --test 'tests/**/*.test.mjs'` invocation
// which executes files in parallel — keep this file in its own logical
// group (already enforced by the snapshot/restore around every assertion)
// or migrate to a dedicated test schema if you add adjacent suites that
// also touch system_settings.
const API_BASE = process.env.TEST_API_BASE ?? "http://localhost:8080";
const DATABASE_URL = process.env.DATABASE_URL;
if (!DATABASE_URL) throw new Error("DATABASE_URL must be set to run these tests");
@@ -238,6 +247,25 @@ test("GET /api/setup/status reports setupRequired=false after install", async ()
assert.equal(body.setupRequired, false);
});
// Contract test for redirectIfSetupNeeded(): Stage 2 SPA routing depends on
// this helper returning a {shouldRedirect, target, status} shape with a
// /setup target only when setup is open. Asserted via /api/setup/status
// since the helper is the source of truth for that response.
test("redirectIfSetupNeeded contract: shouldRedirect=false post-install", async () => {
// We're past the "complete" test, so installed=true. Status must reflect
// that setup is closed; Stage 2's hook reads the same payload.
const res = await fetch(`${API_BASE}/api/setup/status`);
assert.equal(res.status, 200);
const body = await res.json();
assert.equal(body.installed, true);
assert.equal(body.setupRequired, false);
// The redirect-decision contract: shouldRedirect MUST be false whenever
// installed=true OR setupRequired=false. Stage 2's hook must mirror this.
const shouldRedirect =
body.checks.db === "ok" && !body.installed && body.setupRequired;
assert.equal(shouldRedirect, false);
});
// Regression: scripts/src/seed.ts inserts a bootstrap (id=1, installed=false)
// row early. The seeded-admin branch later flips installed=true. The flip
// MUST be a DO UPDATE — a DO NOTHING would silently leave installed=false
+8
View File
@@ -128,6 +128,14 @@ async function main() {
const sysRows = await db.select().from(systemSettingsTable).limit(1);
const installedFlag = sysRows[0]?.installed ?? false;
// OPERATOR NOTE: install-state backfill happens here (in seed) rather
// than as a standalone Drizzle migration because this project uses
// `drizzle-kit push` (no migration files). Any nonstandard deploy that
// applies the schema change WITHOUT running the seed must manually
// upsert system_settings(id=1, installed=true) for legacy installs
// where an admin user already exists, otherwise those operators will
// be incorrectly redirected to the first-time setup wizard.
//
// Backfill: if any admin already exists but system_settings is empty
// (legacy installs from before this column shipped), upsert the row
// with installed=true so those operators are never forced through the