diff --git a/.budgetignore b/.budgetignore
index b71ebb2b..53662a9a 100644
--- a/.budgetignore
+++ b/.budgetignore
@@ -51,16 +51,3 @@ apps/server/src/api/routes/maps.paint.ts cohesive request flow, steps already e
# function per event.
apps/server/src/rooms/lifecycle/onJoin.completion.ts critical-path lifecycle, single coherent function
apps/server/src/rooms/lifecycle/onLeave.ts critical-path lifecycle, single coherent function
-
-# Local audio/video track lifecycle state machine (mic + cam). One cohesive
-# class whose methods all operate on the same shared mutable state — the
-# desired/published/pending flags, the republish/release timers and the
-# _micOp/_camOp serialization promises — under one disposal contract (every
-# method guards on _disposed and chains on the op promises). The I/O seams
-# (getUserMedia + publish/unpublish) are ALREADY extracted into
-# microphonePublishing.ts and cameraPublishing.ts; what remains is the stateful
-# orchestration, which cannot be split without exposing that private mutable
-# state across module boundaries or duplicating the concurrency/disposal guards,
-# fracturing the very serialization guarantees the class exists to provide.
-# 828 LoC.
-apps/web/src/av/core/TrackManager.ts av track lifecycle state machine, io seams already extracted
diff --git a/.env.example b/.env.example
index 6795eb4d..389323e6 100644
--- a/.env.example
+++ b/.env.example
@@ -1,6 +1,6 @@
-# =============================================================================
+# ---
# Meetropolis Environment Configuration
-# =============================================================================
+# ---
# Copy this file to .env and adjust values for your environment.
# NEVER commit .env files with real credentials!
#
@@ -14,7 +14,7 @@
#
# JWT_SECRET and API_TOKEN_PEPPER are required; the stack refuses
# to start until they are set.
-# =============================================================================
+# ---
# -----------------------------------------------------------------------------
# Core Configuration
@@ -22,13 +22,23 @@
# Node environment: development | production | test
# Local-only default. The Docker stack in compose.yaml hard-codes
-# NODE_ENV=production for the server and web services, so this value only
+# NODE_ENV for the server and web services, so this value only
# takes effect for a non-Docker `npm run dev` workflow.
+# Configure a runtime mode locally only when needed.
+# NODE_ENV=
NODE_ENV=development
# Server port (Colyseus + Express)
PORT=2567
+# Optional Prometheus scrape listener. Unset or empty disables it. The
+# public app always answers GET/HEAD /metrics with 404. Direct runs bind
+# loopback by default. The bundled compose.yaml sets METRICS_HOST to the
+# container interface and does not publish this port to the host, so a
+# scraper must sit on the same container network.
+# METRICS_PORT=9100
+# METRICS_HOST=127.0.0.1
+
# Log level: trace | debug | info | warn | error | fatal
LOG_LEVEL=info
@@ -46,6 +56,17 @@ LOG_LEVEL=info
# a value (see the ${JWT_SECRET:?} guard in compose.yaml). Generate one with:
# openssl rand -hex 32
JWT_SECRET=
+# World room tenant isolation: ZONE_PRIVACY_TENANT_ENFORCE is on unless it is
+# set to exactly false. On, a session that joins a world room of another
+# tenant is refused (tenant_mismatch). Turning it off admits such joins with
+# a warning, and room-wide messages then reach the foreign client.
+
+# Protected pack and NPC media files: MEMBER_ASSETS_ENFORCE is off unless it is
+# set to exactly true. On, /packs and /npc-media answer 404 and files are only
+# served to signed-in members of the tenant through /member-assets/v1; desktop
+# apps without the asset protocol marker are asked to update (HTTP 426, world
+# close code 4426).
+# MEMBER_ASSETS_ENFORCE=true
# Pepper for API token hashing (min 16 chars, use: openssl rand -hex 16).
# Also peppers password-reset tokens (PasswordReset.token stores
@@ -71,7 +92,7 @@ POSTGRES_PASSWORD=postgres
POSTGRES_DB=meetropolis
# Host port for the bundled Postgres. Override if 5432 is already in use,
-# e.g. POSTGRES_PORT=5433.
+# e.g. POSTGRES_PORT set to 5433.
# POSTGRES_PORT=5432
# -----------------------------------------------------------------------------
@@ -114,12 +135,8 @@ LIVEKIT_API_SECRET=secret
# Host LAN IP for LiveKit ICE (Docker Desktop on macOS / Windows). Required
# when joining from a different device on the same network. Defaults to
# 127.0.0.1 which only works for connections from the Docker host itself.
-# HOST_IP=192.168.1.42
-
-# Hostname the web container advertises to the browser (Vite HMR host).
-# Defaults to "localhost". Set to your LAN IP when accessing the dev server
-# from another device.
-# DEV_HOST=localhost
+# Configure the host address locally if needed.
+# HOST_IP=
# -----------------------------------------------------------------------------
# Optional closed-source modules (paths)
@@ -141,12 +158,8 @@ LIVEKIT_API_SECRET=secret
# Application title displayed in
and HTML head. Falls back to a
# generic "Virtual Office (Self-Hosted)" string when unset.
-# VITE_APP_TITLE="Virtual Office (Self-Hosted)"
-
-# Marketing tracking pixel ID. Only consumed by the optional brand module.
-# Self-hosters must NOT reuse a third-party production pixel; either
-# provide your own ID or leave unset to disable tracking.
-# VITE_META_PIXEL_ID=
+# Set the browser page title locally if desired.
+# VITE_APP_TITLE=
# -----------------------------------------------------------------------------
# Frontend (Vite)
@@ -164,7 +177,6 @@ VITE_LIVEKIT_URL=ws://localhost:7880
# Feature flags
VITE_FEATURE_AV_SETTINGS=true
-VITE_FEATURE_VOICE_ISOLATION=on
# VITE_FEATURE_VOICE_ONLY=true
# -----------------------------------------------------------------------------
@@ -194,8 +206,10 @@ VITE_FEATURE_VOICE_ISOLATION=on
# Debug options (development only!)
VITE_DEBUG_LOGS=true
VITE_DEBUG_AUTOLOGIN=false
-# VITE_DEBUG_AUTOLOGIN_EMAIL=admin@meetropolis.local
-# VITE_DEBUG_AUTOLOGIN_PASSWORD=admin123
+# Configure a local development test account before enabling autologin.
+# VITE_DEBUG_AUTOLOGIN_EMAIL=
+# Set the local development test account password before enabling autologin.
+# VITE_DEBUG_AUTOLOGIN_PASSWORD=
# HMR (Hot Module Replacement) for development
VITE_HMR_HOST=localhost
@@ -205,10 +219,17 @@ VITE_HMR_PROTOCOL=ws
# CORS & Proxy
# -----------------------------------------------------------------------------
-# Allowed origins (comma-separated)
-# Development: http://localhost:5173,http://localhost:5174
-# Production: https://yourdomain.com,https://*.yourdomain.com,tauri://localhost,http://tauri.localhost
-CORS_ORIGIN=http://localhost:5173,http://localhost:5174
+# Allowed browser origins, comma separated. Every entry must be an exact
+# origin (`scheme://host[:port]`): wildcards, suffix rules and paths are
+# refused, and the server refuses to start when the list is missing or
+# malformed. The same list decides for the HTTP API, for the matchmaking route
+# and for the websocket upgrade.
+# Development: the local web dev server.
+# Production: the public web origin plus both desktop origins of the official
+# app (`tauri://localhost` on macOS/Linux, `http://tauri.localhost` on
+# Windows). An operator who uses the /tools pages adds the API origin of the
+# deployment to the list.
+CORS_ORIGIN=http://localhost:5173,http://localhost:5174,tauri://localhost,http://tauri.localhost
# Trust proxy headers. Set this to the NUMBER of reverse-proxy hops in front of
# the server (e.g. 1 for a single Traefik). Express then derives the client IP
@@ -221,11 +242,16 @@ TRUST_PROXY=1
# Secure cookies (set true in production with HTTPS)
COOKIE_SECURE=false
-# Public-facing base URL fuer Invite-/Guest-/Verify-Links, die der OSS-Server
-# in API-Responses ausliefert (zum manuellen Weitergeben durch den Admin).
-# Wenn unset, sind die Links relativ. Self-Hoster sollten ihre oeffentliche
-# Web-URL setzen.
+# Public web app base used for invitation, guest, verification and password
+# reset links returned by the server or sent by e-mail. Use an absolute HTTP(S)
+# URL for the web app; billing URLs, request origins and the API host are never
+# used as fallbacks. Development and test stacks may explicitly allow loopback
+# bases; never enable that switch in a live deployment.
+# The server logs a startup warning when this base is missing or unusable; link
+# requests then fail closed instead of guessing a destination.
# PUBLIC_BASE_URL=https://app.example.com
+# Accept a loopback or *.localhost base (local try-out, dev and test stacks only):
+# PUBLIC_BASE_URL_ALLOW_LOOPBACK=true
# Public registration toggle (OSS fallback when no enterprise settings are
# stored). When unset, registration is enabled. Set to "false" or "0" to
@@ -254,6 +280,25 @@ COOKIE_SECURE=false
# RATE_LIMIT_REGISTER_WINDOW_MS=3600000
# RATE_LIMIT_REGISTER_MAX=10
#
+# POST /auth/invite — sending an invitation, keyed per signed-in user instead of
+# the client IP (default: 30 / 60 min):
+# RATE_LIMIT_INVITE_CREATE_WINDOW_MS=3600000
+# RATE_LIMIT_INVITE_CREATE_MAX=30
+#
+# POST /invites/:id/resend — resending one invitation, keyed per invitation
+# (default: 5 / 60 min):
+# RATE_LIMIT_INVITE_RESEND_WINDOW_MS=3600000
+# RATE_LIMIT_INVITE_RESEND_MAX=5
+#
+# POST /public/invites/preview — anonymous invitation preview (default: 30 / 10 min):
+# RATE_LIMIT_INVITE_PREVIEW_WINDOW_MS=600000
+# RATE_LIMIT_INVITE_PREVIEW_MAX=30
+#
+# POST /invites/accept — accepting an invitation with an existing account
+# (default: 30 / 10 min):
+# RATE_LIMIT_INVITE_ACCEPT_WINDOW_MS=600000
+# RATE_LIMIT_INVITE_ACCEPT_MAX=30
+#
# POST /auth/forgot + /auth/reset — password reset, per IP (default: 10 / 15 min):
# RATE_LIMIT_PASSWORD_RESET_WINDOW_MS=900000
# RATE_LIMIT_PASSWORD_RESET_MAX=10
@@ -306,13 +351,30 @@ COOKIE_SECURE=false
# RATE_LIMIT_MATCHMAKE_WINDOW_MS=60000
# RATE_LIMIT_MATCHMAKE_MAX=120
+# -----------------------------------------------------------------------------
+# Rate limiting (websocket upgrades)
+# -----------------------------------------------------------------------------
+# Every websocket upgrade attempt is counted per client address before the
+# origin check, so a client that hammers the handshake path runs into a budget
+# instead of into the origin policy. The address is resolved with the
+# TRUST_PROXY setting above, so a forwarded address counts as the client only
+# when the deployment trusts the proxy in front of it. An exhausted budget
+# answers 429 with a Retry-After header instead of a handshake.
+#
+# The mobile gateway joins from inside the server process and the npc-service
+# runs in its own container: both share the budget of their source address.
+# Raise the budget for a very large NPC roster (default: 120 / 60s).
+# WS_UPGRADE_RATE_LIMIT_MAX=120
+# WS_UPGRADE_RATE_LIMIT_WINDOW_MS=60000
+
# Slug of the default tenant: the tenant a single-tenant (OSS) install runs as,
# and the one a join without a tenant is filed under. It is the partition key of
# that tenant's world room, so it must be a valid tenant slug: lower-case
# letters, digits, "_" and "-", 1 to 64 characters. The server refuses to start
# with any other value instead of locking everyone out at runtime. Unset or
# empty means `default`.
-# DEFAULT_TENANT_SLUG=default
+# Set a default tenant slug locally only when overriding the built-in fallback.
+# DEFAULT_TENANT_SLUG=
# Template tenant slug — every new tenant receives a copy of THIS tenant's
# default map on sign-up (Enterprise only). Point it at a dedicated blueprint
@@ -320,7 +382,8 @@ COOKIE_SECURE=false
# drafts and scratch maps, and each new customer would inherit them. The seed
# bootstraps the tenant named here (apps/server/prisma/seed.ts). Defaults to
# `template` in code when unset.
-# TEMPLATE_TENANT_SLUG=template
+# Set a template tenant slug locally only when overriding the built-in fallback.
+# TEMPLATE_TENANT_SLUG=
# -----------------------------------------------------------------------------
# Character editor (Phase 2)
@@ -334,7 +397,8 @@ COOKIE_SECURE=false
# Path to the v5 sprite catalog (packages/shared/sprite/catalog.json). Optional
# override; by default the server finds the copy shipped next to its build (or
# the workspace file in dev).
-# SPRITE_CATALOG_PATH=/abs/path/to/catalog.json
+# Set a catalog path locally only to override the packaged catalog.
+# SPRITE_CATALOG_PATH=
# -----------------------------------------------------------------------------
# Mobile gateway
@@ -353,11 +417,13 @@ COOKIE_SECURE=false
# Irrelevant for pure OSS builds. The OSS server contains no Stripe code.
# Stripe API keys (get from https://dashboard.stripe.com/apikeys)
-# STRIPE_SECRET_KEY=sk_live_...
-# STRIPE_WEBHOOK_SECRET=whsec_...
+# STRIPE_SECRET_KEY=
+# STRIPE_WEBHOOK_SECRET=
# Public URL for billing redirects
-# BILLING_PUBLIC_URL=https://yourdomain.com
+# Not used for invitation, guest, verification or reset links (see PUBLIC_BASE_URL).
+# Configure a public billing base address locally when enabling billing links.
+# BILLING_PUBLIC_URL=
# Price IDs for different plans (optional, can use priceId directly)
# STRIPE_PRICE_STARTER=price_...
@@ -374,7 +440,7 @@ COOKIE_SECURE=false
# Password reset is self-service: POST /auth/forgot mails a single-use link
# that expires after 30 minutes (the token is stored hashed, see
# API_TOKEN_PEPPER). Without a configured provider no reset mail can be
-# delivered and the admin path (POST /admin/users/:id/reset-token, token handed
+# delivered and the super admin path (POST /admin/users/:id/reset-token, token handed
# over out of band) is the only way to reset a password — which leaves a tenant
# owner who forgot theirs with nobody above them to ask. Configure a provider.
#
@@ -382,13 +448,22 @@ COOKIE_SECURE=false
# 1. EE-Resend, when the optional `@meetropolis/tenancy` module is loaded
# AND `RESEND_API_KEY` + `RESEND_FROM` are set.
# 2. OSS-SMTP, when `SMTP_HOST` + `SMTP_FROM` are set.
-# 3. OSS-Console fallback: logs subject + recipient domain only, returns
-# `false` from send() so verify-requests keep surfacing tokens via the
-# API response. A WARN log fires once at boot.
+# 3. OSS-Console fallback: delivers nothing and logs no recipient, subject,
+# link or token; send() returns `false`. It does not count as delivery:
+# verification requests, registration with an invitation code and
+# invitation acceptance by unconfirmed accounts answer
+# 503 EMAIL_DELIVERY_UNAVAILABLE. A log entry fires once at boot (error
+# level in production). Self-hosting needs SMTP_HOST and SMTP_FROM to
+# admit new users.
#
# See README.md "Production Mail Setup" for DKIM/SPF/DMARC guidance and
# recommended providers (SES, Brevo/Mailgun, Postmark, Resend-SMTP).
#
+# Manual account confirmation without a mail provider. Only effective
+# while no delivering mail route is configured; only a super admin
+# can confirm a pending account (see README "Manual account confirmation").
+# MANUAL_ACCOUNT_CONFIRMATION=true
+#
# SMTP host (enables OSS-SMTP when set together with SMTP_FROM).
# Examples: smtp.brevo.com, email-smtp.eu-central-1.amazonaws.com,
# smtp.postmarkapp.com, smtp.resend.com, sandbox.smtp.mailtrap.io
@@ -436,7 +511,8 @@ COOKIE_SECURE=false
# minimal: brand polish is an EE feature.
#
# Display name in subjects, headings and footer. Default: "Meetropolis".
-# MAIL_BRAND_NAME=Meetropolis
+# Set the email brand label locally if desired.
+# MAIL_BRAND_NAME=
#
# Default locale when neither the caller nor the recipient User.locale row
# supplies one. Accepts "de" or "en". Default: "de".
@@ -452,22 +528,26 @@ COOKIE_SECURE=false
# RESEND_API_KEY and RESEND_FROM are set, the EE-Resend provider takes
# precedence over the OSS-SMTP stack above.
#
-# RESEND_API_KEY=re_your-api-key
-# RESEND_FROM=noreply@yourdomain.com
+# RESEND_API_KEY=
+# Configure a verified sender locally before enabling this email provider.
+# RESEND_FROM=
#
# Additional EE-tenancy brand knobs (read only by the EE templates):
-# BRAND_NAME="Workspace"
-# BRAND_DESCRIPTION_DE="Beschreibung deiner Plattform"
+# Set the optional brand label locally if desired.
+# BRAND_NAME=
+# Set the optional German brand description locally if desired.
+# BRAND_DESCRIPTION_DE=
# BRAND_DESCRIPTION_EN="Description of your platform"
-# SUPPORT_EMAIL=support@yourdomain.com
+# Configure an optional public support contact locally.
+# SUPPORT_EMAIL=
# -----------------------------------------------------------------------------
# Admin Tools (served at /tools, disabled if unset)
# -----------------------------------------------------------------------------
# HTTP Basic Auth credentials for the /tools route
-# TOOLS_USER=admin
-# TOOLS_PASSWORD=changeme
+# TOOLS_USER=
+# TOOLS_PASSWORD=
# -----------------------------------------------------------------------------
# NPC Service
@@ -481,9 +561,10 @@ NPC_SERVICE_URL=http://npc-service:3100
# apps/server/src/rooms/lifecycle/onAuth.ts). REQUIRED in production: the
# server refuses NPC joins in production if this is unset or left at the
# `dev-npc-secret` default. Generate with: openssl rand -hex 32
-NPC_SERVICE_SECRET=dev-npc-secret
+# Set a local service credential before enabling NPC integration.
+NPC_SERVICE_SECRET=
-# Directory for NPC media file storage (shared volume between server and NPC service)
+# Shared by the server (upload, serving, deletion) and the npc service. Default /data/npc-media. Set it to a writable directory for local runs without Docker.
NPC_MEDIA_DIR=/data/npc-media
# Server URL as seen from NPC service (internal Docker network)
@@ -498,9 +579,15 @@ NPC_MEDIA_DIR=/data/npc-media
# (gitignored, auto-merged by Docker Compose), not in this file.
# -----------------------------------------------------------------------------
-# Seed Data (Development only)
+# Seed Data
# -----------------------------------------------------------------------------
+# Production requires SEED_ADMIN_EMAIL (set explicitly; the historical
+# default address is allowed) and SEED_ADMIN_PASSWORD (non-template).
+# Development may omit the keys and use the fallbacks below.
-SEED_ADMIN_EMAIL=admin@meetropolis.local
-SEED_ADMIN_PASSWORD=admin123
-SEED_ADMIN_NAME=Root Admin
+# Set a local seed administrator email before running the seed step.
+SEED_ADMIN_EMAIL=
+# Set a local seed administrator password before running the seed step.
+SEED_ADMIN_PASSWORD=
+# Set an optional local seed administrator display label.
+SEED_ADMIN_NAME=
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index ab8761c4..c62e1e58 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -130,6 +130,108 @@ jobs:
- run: npm -w @meetropolis/web run test
- run: npm -w @meetropolis/server run test
+ test-db:
+ name: Database tests (server)
+ runs-on: ubuntu-latest
+ # Points at a real, throwaway database instead of the workflow-wide dummy.
+ # The database tests only accept 127.0.0.1:35440 (see
+ # apps/server/test/fixtures/httpFixture.ts), so the service is published
+ # on that port.
+ env:
+ DATABASE_URL: 'postgresql://ci:ci@127.0.0.1:35440/ci'
+ services:
+ postgres:
+ image: postgres:16-alpine
+ env:
+ POSTGRES_USER: ci
+ POSTGRES_PASSWORD: ci
+ POSTGRES_DB: ci
+ ports:
+ - 35440:5432
+ options: >-
+ --health-cmd "pg_isready -U ci -d ci"
+ --health-interval 5s
+ --health-timeout 5s
+ --health-retries 12
+ # Mail catcher for invites.integration.test.ts (SMTP 1025, HTTP API 8025).
+ # STARTTLS with a self-signed certificate generated at start, so the
+ # server exercises the same TLS path as against a real mail server.
+ mailpit:
+ image: axllent/mailpit:v1.32.0
+ env:
+ MP_SMTP_AUTH_ACCEPT_ANY: '1'
+ MP_SMTP_AUTH_ALLOW_INSECURE: '1'
+ MP_SMTP_TLS_CERT: sans:mailpit
+ MP_SMTP_TLS_KEY: sans:mailpit
+ ports:
+ - 1025:1025
+ - 8025:8025
+ # Test SFU for avAccessRevocation.integration.test.ts. Participants join
+ # over real WebRTC, so the RTC ports are published 1:1 and the node IP is
+ # the runner's loopback. devkey/secret are the public development keys,
+ # not a secret. The test pauses this container through `docker pause`.
+ livekit:
+ image: livekit/livekit-server:v1.13.11@sha256:25cd902de7cacbd5f1f779f6a6ac1eae20ba8f56b0935934ce6b0ab80d1e3d20
+ env:
+ LIVEKIT_CONFIG: |
+ port: 7880
+ bind_addresses: ["0.0.0.0"]
+ rtc:
+ tcp_port: 7881
+ udp_port: 7882
+ use_external_ip: false
+ node_ip: 127.0.0.1
+ keys:
+ devkey: secret
+ logging:
+ level: info
+ ports:
+ - 7880:7880
+ - 7881:7881
+ - 7882:7882/udp
+ steps:
+ - uses: actions/checkout@v7
+ - uses: actions/setup-node@v7
+ with:
+ node-version-file: .nvmrc
+ cache: npm
+ # Activate the packageManager pin from package.json (see note above).
+ - run: corepack enable
+ - run: npm ci
+ - run: npm -w @meetropolis/shared run build
+ - run: npm run generate
+ - name: prisma migrate deploy
+ working-directory: apps/server
+ run: npx prisma migrate deploy
+ # Neither image is guaranteed to ship a health check the runner waits
+ # for, so wait for both HTTP endpoints explicitly (at most 60 s each).
+ - name: Wait for Mailpit and the test SFU
+ run: |
+ for url in http://127.0.0.1:8025/api/v1/info http://127.0.0.1:7880/; do
+ for _ in $(seq 1 60); do
+ curl -fsS -o /dev/null "$url" && continue 2
+ sleep 1
+ done
+ echo "Service at $url did not become ready" >&2
+ exit 1
+ done
+ - name: npm -w @meetropolis/server run test:db
+ env:
+ MAILPIT_URL: http://127.0.0.1:8025
+ MAILPIT_SMTP_HOST: 127.0.0.1
+ MAILPIT_SMTP_PORT: '1025'
+ LIVEKIT_URL: ws://127.0.0.1:7880
+ LIVEKIT_API_KEY: devkey
+ LIVEKIT_API_SECRET: secret
+ TEST_SFU_CONTAINER: ${{ job.services.livekit.id }}
+ # worldAccess.outage.integration.test.ts pauses the test database
+ # through `docker pause`, like the SFU test above.
+ TEST_PG_CONTAINER: ${{ job.services.postgres.id }}
+ # wsUpgradeLimit.integration.test.ts starts the server on this port.
+ # It is not published by any service of this job.
+ WS_UPGRADE_TEST_PORT: '35441'
+ run: npm -w @meetropolis/server run test:db
+
build:
name: Build (web + server) — OSS-only smoke
runs-on: ubuntu-latest
diff --git a/.gitignore b/.gitignore
index 5b2c5f52..f764cd28 100644
--- a/.gitignore
+++ b/.gitignore
@@ -25,6 +25,9 @@ coverage/
apps/web/test-results/
apps/web/playwright-report/
apps/web/blob-report/
+# The visual baselines of the visual test suite stay local: the golden PNGs are
+# generated per slot and must not end up in the history.
+/apps/web/e2e/visual/__screenshots__/
# --- Local environment ---
.env
diff --git a/.husky/commit-msg b/.husky/commit-msg
index da994831..5b0509de 100755
--- a/.husky/commit-msg
+++ b/.husky/commit-msg
@@ -1 +1,4 @@
+#!/bin/sh
+set -e
+
npx --no -- commitlint --edit "$1"
diff --git a/.husky/pre-commit b/.husky/pre-commit
index 2312dc58..e9a1fc45 100755
--- a/.husky/pre-commit
+++ b/.husky/pre-commit
@@ -1 +1,4 @@
+#!/bin/sh
+set -e
+
npx lint-staged
diff --git a/.husky/pre-push b/.husky/pre-push
new file mode 100755
index 00000000..77e1d232
--- /dev/null
+++ b/.husky/pre-push
@@ -0,0 +1,4 @@
+#!/bin/sh
+set -e
+
+exec "$(git rev-parse --show-toplevel)/scripts/pre-push.sh"
diff --git a/.lintstagedrc.json b/.lintstagedrc.json
deleted file mode 100644
index b9bc57fc..00000000
--- a/.lintstagedrc.json
+++ /dev/null
@@ -1,5 +0,0 @@
-{
- "*.{ts,tsx}": ["eslint --fix", "prettier --write"],
- "*.{js,mjs,cjs}": ["eslint --fix", "prettier --write"],
- "*.{json,md,yml,yaml,css,html}": ["prettier --write"]
-}
diff --git a/.lintstagedrc.mjs b/.lintstagedrc.mjs
new file mode 100644
index 00000000..a6d76541
--- /dev/null
+++ b/.lintstagedrc.mjs
@@ -0,0 +1,46 @@
+import path from 'node:path';
+
+const workspaces = [
+ { directory: 'apps/web', name: '@meetropolis/web' },
+ // Database tests need DATABASE_URL and run through `npm run test:db`;
+ // the hook runs the server's unit test project only.
+ { directory: 'apps/server', name: '@meetropolis/server', vitestArgs: ['--project', 'server'] },
+ { directory: 'packages/shared', name: '@meetropolis/shared' },
+];
+
+const quote = (value) => `'${value.replaceAll("'", "'\\''")}'`;
+
+const typescriptTasks = (files) => {
+ const root = process.cwd();
+ const stagedFiles = files.map((file) => {
+ const absolute = path.resolve(file);
+ return {
+ absolute,
+ relative: path.relative(root, absolute).split(path.sep).join('/'),
+ };
+ });
+ const filesArgument = stagedFiles.map(({ absolute }) => quote(absolute)).join(' ');
+ const tasks = [`eslint --fix ${filesArgument}`, `prettier --write ${filesArgument}`];
+
+ for (const workspace of workspaces) {
+ const workspaceFiles = stagedFiles.filter(({ relative }) => relative.startsWith(`${workspace.directory}/`));
+ if (workspaceFiles.length === 0) continue;
+
+ tasks.push(`npm -w ${workspace.name} run typecheck`);
+
+ const workspaceRoot = path.resolve(root, workspace.directory);
+ const relatedFiles = workspaceFiles
+ .map(({ absolute }) => quote(path.relative(workspaceRoot, absolute).split(path.sep).join('/')))
+ .join(' ');
+ const vitestArgs = (workspace.vitestArgs ?? []).map((arg) => ` ${arg}`).join('');
+ tasks.push(`npx vitest related --run --root ${quote(workspaceRoot)}${vitestArgs} ${relatedFiles}`);
+ }
+
+ return tasks;
+};
+
+export default {
+ '*.{ts,tsx}': typescriptTasks,
+ '*.{js,mjs,cjs}': ['eslint --fix', 'prettier --write'],
+ '*.{json,md,yml,yaml,css,html}': ['prettier --write'],
+};
diff --git a/.prettierignore b/.prettierignore
index 3b3a5352..bf207541 100644
--- a/.prettierignore
+++ b/.prettierignore
@@ -12,6 +12,8 @@ apps/server/prisma/schema.composed.prisma
# Vendor / third-party assets
apps/web/public/
+# Verbatim third-party license texts, bound by sha256 in compliance/dependency-evidence.json
+compliance/licenses/
apps/web/src-tauri/
# Standalone HTML editors (haben eigenes inline-JS-Format, nicht prettier-tauglich)
@@ -46,3 +48,6 @@ build_output.txt
packages/brand/
packages/desktop/
packages/tenancy-enterprise/
+
+# Local editor settings
+.codex/
diff --git a/.stylelintrc.json b/.stylelintrc.json
new file mode 100644
index 00000000..c5c3a9e2
--- /dev/null
+++ b/.stylelintrc.json
@@ -0,0 +1,5 @@
+{
+ "rules": {
+ "color-no-hex": true
+ }
+}
diff --git a/AGENTS.md b/AGENTS.md
index b9ae7be1..36433deb 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -288,6 +288,13 @@ Do not add `@tauri-apps` imports anywhere in `apps/web/`. Tauri-specific
code belongs exclusively in the Desktop module, which is not part of
this distribution.
+The machine-readable norm for these boundaries is the `sourceImports`
+section of [`compliance/policy.json`](compliance/policy.json): protected
+package roots, families and scopes, the only allowed loader imports and
+the pinned files. `scripts/license-gate.mjs` enforces it on source imports
+and on the dependency entries of every `package.json` and npm lockfile.
+Change the policy file, not this list; on any difference the policy wins.
+
---
## Security
diff --git a/CHANGELOG.md b/CHANGELOG.md
index a02ae9fa..31c2f2ad 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -7,14 +7,34 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
## [Unreleased]
+### Added
+
+- Self-hosting without a mail provider: with `MANUAL_ACCOUNT_CONFIRMATION=true` a super admin can confirm pending accounts by hand (`GET /admin/pending-confirmations`, `POST /admin/users/:id/confirm-email`); pending confirmations expire after 7 days.
+
### Changed
+- **Breaking (enterprise integration):** The tenant deletion callback in
+ `adminLoader` now requires `deletionProtocol: 'tenant-delete-v2'` with a
+ managed prepare/cleanup pair and an explicit internal retention plan and
+ deadline. Upgrade the host and enterprise module together; mismatched
+ versions reject deletion before any database DELETE statement with
+ `tenant_deletion_contract_required`. Without a valid internal plan the
+ deletion is rejected with `retention_journal_unavailable` (HTTP 409).
+- **Breaking (self-hosting):** NPC media now resolve from one directory. Without `NPC_MEDIA_DIR` the server uses `/data/npc-media`, the same default as the npc service; before, uploads defaulted to `/../../npc-media` and static serving to a directory next to the build output. If you did not set `NPC_MEDIA_DIR`, set it to your existing media directory or move its contents to `/data/npc-media`. When the directory cannot be created, the server logs `npc_media.dir_unavailable` at startup.
+- **Breaking (self-hosting):** Node.js 24.15 or newer below 25 is now required (`engines.node`). `npm ci --engine-strict` refuses older Node versions; `.nvmrc` stays `24` and resolves to the latest 24.x.
+- **Breaking (self-hosting):** invitation, guest, email-verification, password-reset and welcome links are built only from `PUBLIC_BASE_URL`. The fallbacks to relative links, `BILLING_PUBLIC_URL` and the request origin or host are gone, and loopback bases need `PUBLIC_BASE_URL_ALLOW_LOOPBACK=true`. A missing or unusable value is logged at startup, and link requests fail with `public_base_url_missing`. The web client copies invitation links from the server instead of building them from the window origin.
+- **Breaking (self-hosting):** Without a mail provider (`SMTP_HOST` and `SMTP_FROM` unset, no enterprise mail module), the console fallback does not count as delivery: verification requests, acceptance of an invitation by an unverified account and registration with an invitation code answer `503 EMAIL_DELIVERY_UNAVAILABLE`, and `POST /auth/forgot` answers `ok` without sending anything. A configured provider that fails to deliver a verification email also answers `503 EMAIL_DELIVERY_UNAVAILABLE`. No confirmation token is returned by any verification response; a password reset without mail works only through a super admin's `POST /admin/users/:id/reset-token`, which returns the link. Invitations still return their link for copying with `emailSent: false`, and creating a guest returns its magic link. Configure `SMTP_HOST` and `SMTP_FROM` before inviting users.
+- **Breaking (API):** invitation routes no longer carry the invitation code in the URL path, so request, rate-limit and error logs never contain a still-valid code. Revoking and resending address the invitation by its id (`DELETE /invites/:id`, `POST /invites/:id/resend`), the public preview and the acceptance by an existing account take the code in the JSON body (`POST /public/invites/preview`, `POST /invites/accept`), and `GET /invites` returns `id` and `url` instead of `code`. Listing, revoking and resending are limited to tenant admins and owners. Clients that still call `DELETE /invites/`, such as older desktop builds that bundle the previous web client, receive `404 not found`, and the invitation link those builds copy ends in `?invite=undefined`; they need the updated client. Invitations now expire after 7 days; open invitations created before the upgrade get 7 days from the migration. `POST /auth/register` with an invitation code is bound to the invited address and answers `400 invite_unavailable`, `400 invite_expired` or `403 invite_email_mismatch` instead of the previous messages. Invitations without an email address can no longer be redeemed (403 `invite_email_mismatch`) and have to be issued again.
- Web client: a terminal connection error (guest expiry, session
takeover, rejected authentication, outdated client, billing and limit
errors, and with the transcription module a missing consent) now leaves
LiveKit before the overlay appears. Before, the client kept publishing
and subscribing behind the overlay. AV resumes with the next join the
world accepts.
+- Server: a world room now refuses a session of another tenant by default
+ (close code 4401, `tenant_mismatch`). Before, this needed
+ `ZONE_PRIVACY_TENANT_ENFORCE=true`; now only an explicit `false` admits
+ such a join, with a warning.
- Web client: disposing the AV manager (unmount, or the reset of a join
that failed after its room was set up) now leaves LiveKit before the
teardown, which therefore runs up to 5 s later. A leave that exceeds
@@ -31,6 +51,50 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
not support. Removing a member no longer asks twice, and logging out all
other devices reports its result inline instead of with `alert()`. ESLint
now rejects native `confirm`, `alert` and `prompt` in `apps/web`.
+- World server: joining the world always requires a valid session, also
+ with `ZONE_PRIVACY_AUTH_ENFORCE` unset. A join without a session token
+ (desktop builds that predate the join token) is refused with 4401
+ `unauthorized`; the identity the client names is no longer accepted in
+ its place. `ZONE_PRIVACY_AUTH_ENFORCE` now only gates the client
+ zone-privacy version check.
+- World server: a join whose verified tenant has no resolvable slug is
+ refused with 4401 `tenant_unresolved` instead of falling back to the
+ tenant slug the client sent.
+- Server: access revocations use one presence channel, `access_revoked`
+ with `{ userId, origin }`, instead of one `access_revoked:`
+ channel per tenant, and each world room checks the user's sessions
+ against the tenant each session was verified for.
+ `broadcastAccessRevoked(userId)` no longer takes a tenant slug,
+ `accessRevokedChannel` and `disconnectPlayers` are removed, and
+ `revokeAccountAccess(userId, tenantSlugs)` is new.
+- World server: `WorldRoom.onCreate` is async and waits for the
+ revocation subscription; when subscribing fails, the room is not
+ created.
+- World server: open world sessions hold an access lease. The periodic
+ access check runs every 30 s (was 60 s) and renews it. A session that
+ cannot be re-verified ends after at most 120 s with the new code 4503
+ `access_unverified`, which the web client treats as a reconnect; native
+ clients should do the same. A guest ends exactly at its stored expiry.
+ `WORLD_ACCESS_SWEEP_MS` (default 30000) and `WORLD_ACCESS_LEASE_MS`
+ (default 120000, at least twice the sweep) tune both intervals.
+- World server: a world session ends once its database session is gone
+ (logout, password reset, revoked sessions, or removal from another
+ tenant, which signs the user out everywhere), with 4401
+ `session_revoked`: at once on a revocation, otherwise at the next
+ access check.
+- Server: HTTP log fields and metric labels now use route templates
+ instead of concrete request paths. Early `http.request` logs no longer
+ include a `path` field; unmatched requests use ``. This
+ changes values consumed by dashboards and log parsers.
+- Server: personal API tokens now have a level chosen at creation
+ (`scope` in `POST /api-tokens`, default `read`). `read` tokens only use
+ safe methods (GET, HEAD and OPTIONS); `write` tokens may also change
+ data. Tokens granted before this change keep full access (migrated as
+ `write`). No token reaches passwords, email changes, account deletion,
+ sessions, token management, `/auth`, `/me`, `/users/me`, `/admin`,
+ `/debug` or platform administration: those need a signed-in browser
+ session, and a rejected token call answers like a missing token
+ (usually `401`).
### Fixed
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
index f321b01a..dea81aa1 100644
--- a/CONTRIBUTING.md
+++ b/CONTRIBUTING.md
@@ -106,6 +106,10 @@ packages/
npm -w @meetropolis/server run test
npm -w @meetropolis/web run test
+# Server tests that need a database: set DATABASE_URL to a migrated,
+# disposable test database first (see TEST_STRATEGY.md, "Database Tests")
+npm -w @meetropolis/server run test:db
+
# Run specific test file
npm -w @meetropolis/web run test -- src/lib/geom.test.ts
```
diff --git a/CREDITS.md b/CREDITS.md
index a2521d83..feb0ae9d 100644
--- a/CREDITS.md
+++ b/CREDITS.md
@@ -15,21 +15,35 @@ sound effects, tilesets, fonts) that ships in the repository.
### Character sprites
The six built-in office characters are generated procedurally from
-hand-authored pixel-grid templates (a small rendering engine plus data
-catalogs). No third-party pixel data is read, sampled, or referenced. The
-generator code and its catalogs live in
-[`tools/sprite-generator/`](tools/sprite-generator/) so the output is
-reproducible and the community can extend the cast without external
-dependencies.
+hand-authored pixel-grid templates by the Python generator in
+[`tools/sprite-generator/`](tools/sprite-generator/) (`generate.py`).
+No third-party pixel data is read, sampled, or referenced, so the PNG
+output is reproducible and the community can extend the cast without
+external dependencies.
+
+The versioned catalog `packages/shared/sprite/catalog.json` (schema
+`meetropolis-sprite-catalog/v6`) is produced separately through the
+asset-atelier catalog path:
+[`tools/asset-lab/scripts/sprite-catalog.ts`](tools/asset-lab/scripts/sprite-catalog.ts)
+reads the existing catalog as its base and applies `buildAtelierCatalog`
+from [`tools/asset-lab/src/avatar-catalog.ts`](tools/asset-lab/src/avatar-catalog.ts)
+with the Atelier raster additions. The Python `export_catalog.py` chain
+(schema v5, documented in
+[`tools/sprite-generator/README.md`](tools/sprite-generator/README.md))
+remains the legacy exporter and is no longer the authoritative
+generation for the current v6 catalog.
| Asset path | Artist | License | Source |
| ------------------------------------------- | --------- | ------- | ------------------------- |
| `apps/web/public/assets/sprites/*.png` (6×) | Tiamat UG | MIT | `tools/sprite-generator/` |
-The generator code in [`tools/sprite-generator/`](tools/sprite-generator/) is
-AGPL-3.0-only; its generated output — these six sprites and
-`packages/shared/sprite/catalog.json` — is MIT-licensed by Tiamat UG,
-consistent with the `apps/web` and `@meetropolis/shared` packages it ships in.
+The Python generator code in [`tools/sprite-generator/`](tools/sprite-generator/) is
+AGPL-3.0-only; its generated output — these six sprites — is MIT-licensed by Tiamat UG,
+consistent with the `apps/web` package it ships in.
+The current `packages/shared/sprite/catalog.json` (schema v6) is likewise
+MIT-licensed by Tiamat UG, consistent with the `@meetropolis/shared`
+package it ships in; it is produced through the asset-atelier catalog path
+described above, not the legacy Python v5 export.
The AGPL-3.0 copyleft applies to third parties who run the generator themselves.
### Prepared atelier product generation
@@ -80,13 +94,20 @@ The build script itself is AGPL-3.0-only. `collision.png` is Tiamat's own genera
## Fonts
-| Family | Source | License |
-| ----------------------------------------------------- | ------ | ------- |
-| _(none bundled in the repo today; system fonts only)_ | — | — |
+| Family | Path | Accompanying license text |
+| -------------- | ------------------------------------------------ | ----------------------------------- |
+| Press Start 2P | `apps/web/public/fonts/PressStart2P-Regular.ttf` | SIL OFL 1.1 (see accompanying text) |
-If a font ends up bundled later (for example to guarantee a consistent
-look across browsers), it must be SIL OFL or a similarly permissive
-license and listed here with a download source and version.
+The OSS source tree contains the unmodified upstream file
+`apps/web/public/fonts/PressStart2P-Regular.ttf` (version 3.000) from the
+public google/fonts repository, `ofl/pressstart2p/PressStart2P-Regular.ttf`
+at revision `dbd72d6ef9ebea750d33c02c7189633e972d6a40`, and the
+accompanying license text `apps/web/public/fonts/PressStart2P-OFL.txt`. The
+text identifies SIL OFL 1.1 and names the Press Start 2P Project Authors.
+
+Any additional font bundled later (for example to guarantee a consistent
+look across browsers) must be SIL OFL or a similarly permissive license
+and listed here with a download source and version.
## Sound effects
diff --git a/LICENSING.md b/LICENSING.md
index c8a049ee..b4949e05 100644
--- a/LICENSING.md
+++ b/LICENSING.md
@@ -38,6 +38,8 @@ third-party contexts.
The optional private submodules under `packages/brand`, `packages/desktop`,
and `packages/tenancy-enterprise` are not part of this OSS distribution and
carry their own commercial licenses; see those repositories for details.
+Source code and assets from the closed-source modules (brand, desktop,
+enterprise and mobile) are never checked into this repository.
Third-party dependencies are listed and attributed in [`NOTICE`](NOTICE).
@@ -127,9 +129,11 @@ exact wording and the Developer Certificate of Origin sign-off requirement.
## Trademarks
-The "Meetropolis" name and any associated logos are trademarks of Tiamat UG
-and are **not** covered by AGPL-3.0 or MIT. Permitted and prohibited uses are
-documented in [`TRADEMARKS.md`](TRADEMARKS.md).
+Trademark rights to the Meetropolis name and logos are not granted by the
+AGPL/MIT copyright licenses. For exactly the ten own brand and image files
+listed in [`TRADEMARKS.md`](TRADEMARKS.md),
+MIT explicitly applies as the copyright license. The conditions for trademark
+use continue to apply independently.
## Questions
diff --git a/README.md b/README.md
index d577a5dc..7e1aff62 100644
--- a/README.md
+++ b/README.md
@@ -1,7 +1,3 @@
-
-
-
-
# Meetropolis
An open-source virtual office platform for remote teams. Proximity-based
@@ -9,7 +5,7 @@ spatial audio/video, a live 2D world built on Phaser, and a real-time
multi-user engine powered by Colyseus.
[](https://github.com/lass-machen/meetropolis/actions/workflows/ci.yml)
-
+



@@ -46,6 +42,9 @@ in `.env.example` on purpose — `compose.yaml` refuses to start
(`:?required`) until you set them, so generate and fill them in
**before** the first `docker compose up`, not after a failed start.
+Set `PUBLIC_BASE_URL` to the absolute public URL of the web app (for example `https://meet.example.com`). It is the only base for invitation, guest, email-verification, password-reset and welcome links. Without a usable value the server logs a warning at startup and refuses to create those links (`public_base_url_missing`) instead of handing out a broken one. A loopback or `*.localhost` base is accepted only with `PUBLIC_BASE_URL_ALLOW_LOOPBACK=true`, for a local try-out on `http://localhost:5173`; never set that flag in production.
+**Breaking change:** earlier versions fell back to relative links, to `BILLING_PUBLIC_URL` or to the request origin or host. These fallbacks are gone, so set `PUBLIC_BASE_URL` before upgrading.
+
`compose.yaml` ships no reverse proxy and no TLS terminator — you are
expected to put your own (Traefik, Caddy, nginx, etc.) in front of the
server and web containers for production. See `## Production deployment`
@@ -65,6 +64,8 @@ override or in the (private) deploy repo.
Requires a running PostgreSQL instance. Configure `DATABASE_URL` in `.env`.
+Set `NPC_MEDIA_DIR` to a writable directory (for example `./.data/npc-media`); its default `/data/npc-media` is meant for the Docker volume, and the server logs `npc_media.dir_unavailable` if it cannot create it.
+
```bash
npm install
npm run dev # starts server + web concurrently
@@ -166,17 +167,21 @@ boundaries; the OSS build runs fully without them.
Copy `.env.example` to `.env`. Key variables:
-| Variable | Description |
-| -------------------- | ----------------------------------------------------- |
-| `DATABASE_URL` | PostgreSQL connection string |
-| `JWT_SECRET` | JWT signing secret (32+ chars in production) |
-| `LIVEKIT_URL` | LiveKit server URL |
-| `LIVEKIT_API_KEY` | LiveKit API key |
-| `LIVEKIT_API_SECRET` | LiveKit API secret |
-| `HOST_IP` | Host LAN IP for LiveKit ICE (Docker Desktop on macOS) |
-| `CORS_ORIGIN` | Allowed CORS origins (required in production) |
-| `VITE_API_BASE` | Server URL baked into the web bundle at _build_ time |
-| `VITE_LIVEKIT_URL` | LiveKit URL baked into the web bundle at _build_ time |
+| Variable | Description |
+| -------------------- | ---------------------------------------------------------------------------------------- |
+| `DATABASE_URL` | PostgreSQL connection string |
+| `JWT_SECRET` | JWT signing secret (32+ chars in production) |
+| `LIVEKIT_URL` | LiveKit server URL |
+| `LIVEKIT_API_KEY` | LiveKit API key |
+| `LIVEKIT_API_SECRET` | LiveKit API secret |
+| `HOST_IP` | Host LAN IP for LiveKit ICE (Docker Desktop on macOS) |
+| `CORS_ORIGIN` | Exact list of allowed browser origins (required) |
+| `PUBLIC_BASE_URL` | Absolute public web app URL used for shareable links |
+| `METRICS_PORT` | Optional scrape listener; unset disables it |
+| `METRICS_HOST` | Bind address for that listener (default loopback) |
+| `VITE_API_BASE` | Server URL baked into the web bundle at _build_ time |
+| `VITE_LIVEKIT_URL` | LiveKit URL baked into the web bundle at _build_ time |
+| `NPC_MEDIA_DIR` | Storage directory for NPC media, shared with the npc service (default `/data/npc-media`) |
See `.env.example` for the full list including optional variables.
@@ -282,9 +287,7 @@ Before deploying for your team or customers:
2. Provide your own legal pages (`/privacy`, `/terms`, `/impressum`). The
default build renders neutral placeholders.
3. Update the HTML title and meta description in `apps/web/index.html`.
-4. Configure your own analytics tracking (`VITE_META_PIXEL_ID`) or leave it
- disabled.
-5. Review and adjust source strings that reference "Meetropolis" if you
+4. Review and adjust source strings that reference "Meetropolis" if you
intend to publish a derivative product (see [TRADEMARKS.md](TRADEMARKS.md)).
## API tokens
@@ -292,8 +295,8 @@ Before deploying for your team or customers:
Control your presence remotely via personal API tokens:
1. Open "API Tokens and Docs" from the top-right menu.
-2. Create a token. It is shown only once, save it.
-3. Use it to control mic, camera, screenshare and DND status:
+2. Create a token and pick its level: `read` (default, only safe methods such as GET, HEAD and OPTIONS) or `write` (may also change data). It is shown only once, save it. Tokens created before levels existed keep full access (`write`).
+3. Use a `write` token to control mic, camera, screenshare and DND status, since this changes state:
```bash
curl -X POST "http://localhost:2567/controls" \
@@ -302,6 +305,8 @@ curl -X POST "http://localhost:2567/controls" \
-d '{"mic": false, "dnd": true}'
```
+No token, not even `write`, can change a password or email address, delete an account, manage sessions or tokens (`/api-tokens`), or reach `/auth`, `/me`, `/users/me`, `/admin`, `/debug` or platform administration (pack upload, archive and delete, and map import under `/admin`); those need a signed-in browser session.
+
## Production deployment
The bundled `compose.yaml` covers the minimum self-host case (Postgres
@@ -319,6 +324,69 @@ The bundled `compose.yaml` covers the minimum self-host case (Postgres
| `CORS_ORIGIN` | Explicit list of allowed origins |
| `COOKIE_SECURE` | `true` |
+`CORS_ORIGIN` holds exact origins (`scheme://host[:port]`) and nothing else:
+no wildcard, no suffix rule, no path, and `null` is not an origin. The server
+refuses to start when the list is missing or malformed, in every mode. The
+same list decides for the HTTP API, for the matchmaking route and for the
+websocket upgrade: an origin that is not listed gets `403` and no CORS
+headers, and `Origin: null` is refused as well. A request without an `Origin`
+header is not a browser request: it stays possible for native clients,
+webhooks and health checks, gets no CORS headers, and is decided by the
+route's own auth.
+
+The official desktop app reports `tauri://localhost` on macOS/Linux and
+`http://tauri.localhost` on Windows. Both must be listed explicitly, older
+builds included. The same applies to the API origin of an operator who uses
+the `/tools` pages: it is an ordinary origin now, there is no same-origin
+exception any more. See [`docs/origin-allowlist.md`](docs/origin-allowlist.md).
+
+`GET`/`HEAD` `/metrics` on the public app port always returns 404.
+Prometheus scrapes `METRICS_PORT` (compose default 9100) on the
+container network. `compose.yaml` does not publish that port and does
+not put a proxy route in front of it. Direct runs bind loopback unless
+`METRICS_HOST` is set. See [`docs/metrics.md`](docs/metrics.md).
+
+Websocket upgrades are budgeted per client address: every upgrade
+attempt is counted before the origin check, and an exhausted budget
+answers `429` with a `Retry-After` header instead of a handshake.
+`WS_UPGRADE_RATE_LIMIT_MAX` (default 120) sets the budget,
+`WS_UPGRADE_RATE_LIMIT_WINDOW_MS` (default 60000) the window. The mobile
+gateway joins from inside the server process and the npc-service runs in
+its own container: both share the budget of their source address.
+
+Every production start path (server entrypoint, migration service, and
+the server process itself) enforces the credential policy below before
+any migration, seed, or listen work. A violation stops the start and
+reports only the offending key name, never a value. `TOOLS_PASSWORD`
+stays optional: unset or empty keeps the tools route disabled and the
+start valid.
+
+| Variable | Production rule |
+| -------------------- | ------------------------------------------ |
+| `LIVEKIT_API_KEY` | Present, non-blank, not the template value |
+| `LIVEKIT_API_SECRET` | Present, non-blank, not the template value |
+| `DATABASE_URL` | Valid Postgres URL, password neither blank |
+| | nor the template value |
+| `POSTGRES_PASSWORD` | When set, non-blank and not the template |
+| | value |
+| `TOOLS_PASSWORD` | When set, non-blank and not the template |
+| | value |
+
+The seed program additionally enforces `SEED_ADMIN_EMAIL` and
+`SEED_ADMIN_PASSWORD` before it opens a database connection. It uses
+the same production mode detection as the start path and does not
+require LiveKit or tools credentials.
+
+| Variable | Production rule |
+| --------------------- | ---------------------------------------- |
+| `SEED_ADMIN_EMAIL` | Present and non-blank; an explicit |
+| | historical default address is allowed |
+| `SEED_ADMIN_PASSWORD` | Present, non-blank, and not the template |
+| | value |
+
+Development keeps the previous fallbacks. A violation exits with
+status 1 and prints only the offending key name.
+
See [`docs/livekit-production.md`](docs/livekit-production.md) for the
LiveKit-specific hardening walkthrough (replacing `--dev`, rotating
keys, ICE / NAT setup, verification).
@@ -335,9 +403,10 @@ keys, ICE / NAT setup, verification).
## Production Mail Setup
The OSS server can send transactional email (invites, guest magic links,
-verify links, welcome emails) over plain SMTP via
-[nodemailer](https://nodemailer.com/). Sensitive tokens (password reset)
-are NEVER sent by email — the admin generates them via the admin UI.
+verify links, welcome emails, password reset links) over plain SMTP via
+[nodemailer](https://nodemailer.com/). Password reset is self-service:
+`POST /auth/forgot` mails a reset link to the account's address and
+answers `{ ok: true }` without returning the link or token.
### Provider precedence
@@ -346,10 +415,60 @@ The mail loader resolves a single active provider at server boot:
1. **EE-Resend** — when the optional `@meetropolis/tenancy` module is
installed and both `RESEND_API_KEY` + `RESEND_FROM` are set.
2. **OSS-SMTP (nodemailer)** — when `SMTP_HOST` + `SMTP_FROM` are set.
-3. **Console fallback** — last-resort, logs subject + recipient domain
- only (no body in production), returns `false` from `send()` so
- verify-requests keep surfacing tokens via the API response. A
- one-time WARN log fires at boot: `email.fallback_console`.
+3. **Console fallback** — last resort when no provider is configured. It
+ delivers nothing and logs only a redacted marker without recipient,
+ subject, link or token; `send()` returns `false`. A one-time log entry
+ `email.fallback_console` fires at boot (error level in production,
+ warning otherwise). The console fallback does not count as delivery,
+ see [Running without a mail provider](#running-without-a-mail-provider).
+
+### Running without a mail provider
+
+Self-hosting needs a mail provider to admit new users. Without
+`SMTP_HOST` and `SMTP_FROM` (and without the enterprise mail module) the
+server cannot confirm or register new accounts, except through
+[manual account confirmation](#manual-account-confirmation):
+
+- `POST /auth/verify/request` answers `503 EMAIL_DELIVERY_UNAVAILABLE`.
+- `POST /auth/register` with an invitation code answers
+ `503 EMAIL_DELIVERY_UNAVAILABLE`.
+- `POST /invites/accept` by an account whose email address is not yet
+ confirmed answers `503 EMAIL_DELIVERY_UNAVAILABLE`.
+- `POST /auth/forgot` answers `{ ok: true }` but issues and sends nothing.
+
+No API response contains a confirmation token.
+
+What still works without mail:
+
+- Creating an invitation returns its link (`inviteUrl`) with
+ `emailSent: false`. Copy and share the link; accounts whose email
+ address is already confirmed can accept it.
+- Creating a guest returns the guest's magic link for copying.
+- A super admin can create a password reset link with
+ `POST /admin/users/:id/reset-token`; the response contains the link.
+ For tenant admins the same route answers
+ `503 EMAIL_DELIVERY_UNAVAILABLE` without a mail provider.
+
+#### Manual account confirmation
+
+When no mail provider is configured (no `SMTP_HOST` with `SMTP_FROM` and
+no enterprise mail module), setting `MANUAL_ACCOUNT_CONFIRMATION=true`
+lets a super admin confirm new accounts by hand. The switch has no effect
+while a delivering mail route exists: with SMTP or the enterprise mail
+module configured, email proof always applies, even when sending fails.
+
+With the switch active, registration with an invitation code and
+acceptance of an invitation by an unconfirmed account create a pending
+confirmation instead of answering `503 EMAIL_DELIVERY_UNAVAILABLE`. Until
+confirmation the account has no access and no membership.
+
+Only a super admin (an owner of the internal tenant) can confirm: in the
+admin overlay or with `GET /admin/pending-confirmations` and
+`POST /admin/users/:id/confirm-email`. A pending confirmation expires
+after 7 days, or earlier when the invitation itself expires; afterwards
+the person needs a new invitation. Check the identity and the address of
+the person through another channel before confirming. Confirmation sets `emailVerifiedAt`, and the server logs record
+the confirmation with the account identifiers of the admin and the person.
### Recommended providers
@@ -529,7 +648,7 @@ remote group on broadband at home, will rarely hit a NAT scenario that
TURN solves. STUN-only (the OSS default) is enough. Only invest in
TURN once a real user reports audio/video that never connects.
-## Out of scope (not implemented in Block C)
+## Out of scope (not implemented yet)
These items are deliberately not part of the OSS-SMTP stack and would
require dedicated blocks:
@@ -542,8 +661,6 @@ require dedicated blocks:
relay with bounce logs.
- Per-tenant rate-limiting for guest invites. `express-rate-limit` is
installed but not wired up — track as a follow-up.
-- Self-service password reset via email. Block C is invite/verify/guest
- only; password reset remains admin-triggered with token-in-UI.
## Contributing
diff --git a/SECURITY.md b/SECURITY.md
index 851f3332..467933d5 100644
--- a/SECURITY.md
+++ b/SECURITY.md
@@ -75,6 +75,7 @@ When contributing to this project, please:
- JWT tokens are used for session management
- Passwords are hashed using bcrypt with appropriate cost factor
- API tokens are hashed before storage
+- Personal API tokens carry a level: `read` tokens only use safe methods (GET, HEAD and OPTIONS) while `write` tokens may also change data. No token reaches account, token management or platform administration routes, which require a browser session.
- The Colyseus `world` room binds every non-NPC join to the identity
carried by a server-verified JWT (`onAuth`, see
`apps/server/src/rooms/lifecycle/onAuth.ts`), never to a client-supplied
diff --git a/TEST_STRATEGY.md b/TEST_STRATEGY.md
index 1acfd835..dfac845b 100644
--- a/TEST_STRATEGY.md
+++ b/TEST_STRATEGY.md
@@ -10,7 +10,7 @@ This file defines the test strategy for the Meetropolis monorepo. It is intended
| Unit Tests (Server) | Vitest + Supertest | `apps/server/src/**/*.test.ts` | Active |
| Unit Tests (Shared) | Vitest | `packages/shared/src/**/*.test.ts` | New |
| E2E Tests | Playwright | `apps/web/e2e/*.spec.ts` | In Development |
-| Integration Tests | Vitest | `apps/server/src/**/*.integration.test.ts` | Planned (none) |
+| Integration Tests | Vitest | `apps/server/src/**/*.integration.test.ts` | Active (DB) |
---
@@ -160,8 +160,34 @@ npm run ci:local
npm run test -w @meetropolis/server
npm run test -w @meetropolis/web
npm run test -w @meetropolis/shared
+
+# Server tests that need a migrated database (see "Database Tests")
+npm run test:db -w @meetropolis/server
+```
+
+### Database Tests
+
+`npm test` in `apps/server` never needs a database. Tests that need a
+migrated PostgreSQL database run in their own Vitest projects through
+`npm run test:db`:
+
+- File names end in `.integration.test.ts`. Exceptions are listed in
+ `databaseTestFiles` in `apps/server/vitest.config.ts`.
+- `DATABASE_URL` must point at a migrated, disposable test database. Without
+ it the run fails at once with a clear message; nothing is skipped.
+- The files run one at a time. Files with database-wide effects (triggers on
+ shared tables, deletes without a tenant filter) belong in
+ `exclusiveTestFiles` and run last.
+
+```bash
+# Example with a local throwaway database
+export DATABASE_URL=postgresql://user:password@localhost:5432/meetropolis_test
+(cd apps/server && npx prisma migrate deploy)
+npm run test:db -w @meetropolis/server
```
+Never point `DATABASE_URL` at a database whose data you want to keep.
+
---
## 4. Mocking Strategies
diff --git a/TRADEMARKS.md b/TRADEMARKS.md
index d3674cd1..26eeea38 100644
--- a/TRADEMARKS.md
+++ b/TRADEMARKS.md
@@ -36,16 +36,33 @@ grant any rights to use the Marks.
## If you fork or self-host
-The public OSS repository intentionally ships **no** brand assets or
-marketing copy. The following areas are reserved for the private,
-closed-source modules operated by Tiamat and are protected by this
-policy:
+The public OSS repository contains own brand and image files
+for which MIT is explicitly the copyright license (see
+[`apps/web/LICENSE`](apps/web/LICENSE)). Exactly these ten files are
+davon erfasst:
+
+- `apps/web/public/logo.png`
+- `apps/web/public/favicon.svg`
+- `apps/web/public/favicon.ico`
+- `apps/web/public/favicon-16.png`
+- `apps/web/public/favicon-32.png`
+- `apps/web/public/apple-touch-icon.png`
+- `apps/web/public/icon-192.png`
+- `apps/web/public/icon-512.png`
+- `apps/web/public/icon-512-maskable.png`
+- `apps/web/public/images/pub/open-source-teaser-ide.png`
+
+With this exception no additional copyright licenses are granted for
+other files or private modules. The following areas
+remain reserved for Tiamat's private, closed-source modules and
+are protected by this policy:
- Marketing landing sections (Hero, Pricing, Comparison, Social Proof,
Final CTA, Problem/Solution)
- Legal pages (Terms of Service, Privacy Policy, Imprint) with
Meetropolis-specific content
-- Brand logo, wordmark, favicons, product screenshots, editor video
+- Additional brand, logo, favicon, screenshot and editor video content
+ of optional private modules outside the ten files listed above
- Meta-Pixel tracking integration
- Multi-tenant administration, Stripe billing, pricing-plan CRUD,
asset-pack marketplace, audit log
@@ -57,9 +74,7 @@ expected to:
OSS repository ships this directory as a placeholder slot).
2. Provide your own legal pages (Privacy Policy, Terms, Imprint).
3. Adjust the HTML title and favicon path in `apps/web/index.html`.
-4. If you want marketing tracking, set your own `VITE_META_PIXEL_ID`.
- Do not reuse the Meetropolis pixel ID under any circumstances.
-5. Replace source-code strings that prominently use the "Meetropolis"
+4. Replace source-code strings that prominently use the "Meetropolis"
name with your own branding.
## Contact
diff --git a/apps/loadtest/Dockerfile b/apps/loadtest/Dockerfile
index 984db76e..e1a7069c 100644
--- a/apps/loadtest/Dockerfile
+++ b/apps/loadtest/Dockerfile
@@ -4,13 +4,18 @@ WORKDIR /app
COPY package.json package-lock.json* ./
COPY ./apps/loadtest/package.json ./apps/loadtest/package.json
+COPY ./packages/shared/package.json ./packages/shared/package.json
-RUN npm install -w @meetropolis/loadtest
+RUN npm install -w @meetropolis/shared -w @meetropolis/loadtest
COPY . .
+RUN npm run build -w @meetropolis/shared
+
WORKDIR /app/apps/loadtest
+LABEL org.opencontainers.image.licenses="AGPL-3.0-only"
+
CMD ["npm", "run", "dev"]
diff --git a/apps/loadtest/README.md b/apps/loadtest/README.md
index 2d61a4dd..edd0ee49 100644
--- a/apps/loadtest/README.md
+++ b/apps/loadtest/README.md
@@ -4,21 +4,41 @@ Example:
```bash
# From repo root
-npm -w @meetropolis/loadtest run dev
-
-# Or with environment overrides
-API_BASE=http://localhost:2567 \
- LIVEKIT_URL=ws://localhost:7880 \
+LOADTEST_TENANT=throwaway \
+ LOADTEST_ACCOUNTS_FILE=./accounts.json \
+ API_BASE=http://localhost:2567 \
USERS=30 \
RAMP=5 \
DURATION=90 \
npm -w @meetropolis/loadtest run dev
```
+`accounts.json` is a JSON array, kept outside the repository:
+
+```json
+[{ "email": "person@example.com", "password": "replace-me" }]
+```
+
+## Accounts and tenant
+
+`LOADTEST_ACCOUNTS_FILE` points at that array. Each object needs `email`
+and `password`. `LOADTEST_TENANT` is the tenant slug, sent as `X-Tenant`.
+Each simulated user takes one account. The run stops when there are fewer
+accounts than `USERS`. The file contents are never printed.
+
+Use only test accounts that are members of a disposable tenant. Do not point
+this tool at production, and do not reuse production passwords. Keep the
+file out of the repository and out of logs.
+
+The world client signs in with `POST /auth/login` and joins with that
+session. The LiveKit client calls `POST /livekit/token` with the same
+session. `SKIP_LIVEKIT=true` skips the LiveKit client. `LIVEKIT_URL` is an
+optional websocket override; otherwise the client reads `GET /livekit/url`.
+
Prerequisites: a local self-host stack (db, server, web, livekit) is
running, for example via `docker compose up` from the repository root.
The server rate-limits `POST /matchmake/...` per client IP (120 per minute by
-default), and every bot joins from the same address. A run that joins more than
-that per minute needs `RATE_LIMIT_MATCHMAKE_MAX` raised on the server (or
+default), and every client joins from the same address. A run that joins more
+than that per minute needs `RATE_LIMIT_MATCHMAKE_MAX` raised on the server (or
`RATE_LIMIT_ENABLED=false` for a throwaway stack).
diff --git a/apps/loadtest/package.json b/apps/loadtest/package.json
index 3a7a2eb2..3b5b4481 100644
--- a/apps/loadtest/package.json
+++ b/apps/loadtest/package.json
@@ -11,10 +11,11 @@
"typecheck": "tsc -p tsconfig.json --noEmit"
},
"dependencies": {
- "@colyseus/sdk": "^0.17.43",
- "@livekit/rtc-node": "^1.1.0",
+ "@colyseus/sdk": "^0.18.10",
+ "@livekit/rtc-node": "^1.2.2",
+ "@meetropolis/shared": "*",
"dotenv": "^17.4.2",
- "livekit-server-sdk": "^2.19.1"
+ "livekit-server-sdk": "^2.20.0"
},
"devDependencies": {
"tsx": "^4.23.15",
diff --git a/apps/loadtest/src/index.ts b/apps/loadtest/src/index.ts
index 5ed8968a..1a02ca21 100644
--- a/apps/loadtest/src/index.ts
+++ b/apps/loadtest/src/index.ts
@@ -1,27 +1,40 @@
import 'dotenv/config';
+import { existsSync, readFileSync } from 'node:fs';
import { runScenario } from './scenario.js';
+import { parseAccounts, redactSecrets, type LoadtestAccount } from './workers/session.js';
-async function main() {
+async function main(): Promise {
const modeRaw = process.env.MODE || 'node';
const mode: 'node' | 'browser' = modeRaw === 'browser' ? 'browser' : 'node';
const users = Number(process.env.USERS || 20);
const rampPerSec = Number(process.env.RAMP || 5);
- // Prefer explicit env; when running inside Docker, default to service name
- let runningInDocker = false;
+ const apiBase = process.env.API_BASE || (existsSync('/.dockerenv') ? 'http://server:2567' : 'http://localhost:2567');
+ const room = process.env.ROOM || 'world';
+ const durationSec = Number(process.env.DURATION || 60);
+ const tenant = requireEnv('LOADTEST_TENANT');
+ const accounts = loadAccounts();
+ await runScenario({ mode, users, rampPerSec, apiBase, room, durationSec, tenant, accounts });
+}
+
+function requireEnv(name: string): string {
+ const value = process.env[name];
+ if (!value) throw new Error(`${name} is required`);
+ return value;
+}
+
+function loadAccounts(): LoadtestAccount[] {
+ const path = requireEnv('LOADTEST_ACCOUNTS_FILE');
+ let raw: string;
try {
- const { existsSync } = await import('node:fs');
- runningInDocker = existsSync('/.dockerenv');
+ raw = readFileSync(path, 'utf8');
} catch {
- runningInDocker = false;
+ throw new Error('LOADTEST_ACCOUNTS_FILE could not be read');
}
- const apiBase = process.env.API_BASE || (runningInDocker ? 'http://server:2567' : 'http://localhost:2567');
- const livekitUrl = process.env.LIVEKIT_URL || 'ws://localhost:7880';
- const room = process.env.ROOM || 'world';
- const durationSec = Number(process.env.DURATION || 60);
- await runScenario({ mode, users, rampPerSec, apiBase, livekitUrl, room, durationSec });
+ return parseAccounts(raw);
}
-main().catch((e) => {
- console.error('Loadtest failed:', e);
+main().catch((error: unknown) => {
+ const message = error instanceof Error ? error.message : 'unknown error';
+ console.error('Loadtest failed:', redactSecrets(message));
process.exit(1);
});
diff --git a/apps/loadtest/src/scenario.ts b/apps/loadtest/src/scenario.ts
index 190c719b..d525dc39 100644
--- a/apps/loadtest/src/scenario.ts
+++ b/apps/loadtest/src/scenario.ts
@@ -1,53 +1,85 @@
import { spawnColyseusBot } from './workers/colyseusBot.js';
-// The LiveKit bot is imported dynamically so the dependency stays optional.
+import type { LoadtestAccount } from './workers/session.js';
+import type { LivekitBotOptions } from './workers/livekitBot.js';
export async function runScenario(opts: {
mode: 'node' | 'browser';
users: number;
rampPerSec: number;
apiBase: string;
- livekitUrl: string;
room: string;
durationSec: number;
-}) {
+ tenant: string;
+ accounts: LoadtestAccount[];
+}): Promise {
+ if (opts.accounts.length < opts.users) {
+ throw new Error(`not enough loadtest accounts: have ${opts.accounts.length}, need ${opts.users}`);
+ }
const bots: Array<{ stop: () => Promise }> = [];
const startAt = Date.now();
const skipLivekit = process.env.SKIP_LIVEKIT === 'true';
for (let i = 0; i < opts.users; i++) {
- const identity = `bot-${String(i + 1).padStart(3, '0')}`;
- // Ramp-up
- if (i > 0 && opts.rampPerSec > 0) {
- const delayMs = Math.floor(1000 * (i / opts.rampPerSec));
- await new Promise((r) => setTimeout(r, delayMs));
+ await rampDelay(i, opts.rampPerSec);
+ const account = opts.accounts[i];
+ if (!account) {
+ throw new Error(`not enough loadtest accounts: have ${opts.accounts.length}, need ${opts.users}`);
}
- // Start Colyseus bot
- bots.push(await spawnColyseusBot({ apiBase: opts.apiBase, identity }));
- // Start LiveKit bot
+ const world = await spawnColyseusBot({
+ apiBase: opts.apiBase,
+ tenant: opts.tenant,
+ email: account.email,
+ password: account.password,
+ });
+ bots.push(world);
if (!skipLivekit) {
- try {
- const mod: typeof import('./workers/livekitBot.js') = await import('./workers/livekitBot.js');
- bots.push(
- await mod.spawnLivekitBot({
- livekitUrl: opts.livekitUrl,
- apiBase: opts.apiBase,
- roomName: opts.room,
- identity,
- }),
- );
- } catch {
- // LiveKit is optional: when the import fails, keep running Colyseus-only.
- }
+ await startLivekitBot(bots, {
+ apiBase: opts.apiBase,
+ tenant: opts.tenant,
+ token: world.token,
+ roomName: opts.room,
+ });
}
}
- // Run for duration
- const until = startAt + opts.durationSec * 1000;
- while (Date.now() < until) {
- await new Promise((r) => setTimeout(r, 1000));
+ await waitUntil(startAt + opts.durationSec * 1000);
+ await stopAll(bots);
+}
+
+function rampDelay(index: number, rampPerSec: number): Promise {
+ if (index === 0 || rampPerSec <= 0) return Promise.resolve();
+ const delayMs = Math.floor(1000 * (index / rampPerSec));
+ return new Promise((resolve) => {
+ setTimeout(resolve, delayMs);
+ });
+}
+
+async function startLivekitBot(bots: Array<{ stop: () => Promise }>, opts: LivekitBotOptions): Promise {
+ try {
+ const mod: typeof import('./workers/livekitBot.js') = await import('./workers/livekitBot.js');
+ bots.push(await mod.spawnLivekitBot(opts));
+ } catch (error: unknown) {
+ if (isMissingModule(error)) return;
+ throw error;
}
- // Stop all
- for (const b of bots) {
+}
+
+function isMissingModule(error: unknown): boolean {
+ return typeof error === 'object' && error !== null && 'code' in error && error.code === 'ERR_MODULE_NOT_FOUND';
+}
+
+async function waitUntil(untilMs: number): Promise {
+ while (Date.now() < untilMs) {
+ await new Promise((resolve) => {
+ setTimeout(resolve, 1000);
+ });
+ }
+}
+
+async function stopAll(bots: Array<{ stop: () => Promise }>): Promise {
+ for (const bot of bots) {
try {
- await b.stop();
- } catch {}
+ await bot.stop();
+ } catch {
+ // One bot failing to stop must not skip the others.
+ }
}
}
diff --git a/apps/loadtest/src/workers/colyseusBot.ts b/apps/loadtest/src/workers/colyseusBot.ts
index 81c66a05..73cb8cdb 100644
--- a/apps/loadtest/src/workers/colyseusBot.ts
+++ b/apps/loadtest/src/workers/colyseusBot.ts
@@ -1,117 +1,174 @@
import { Client } from '@colyseus/sdk';
+import { ZONE_PRIVACY_PROTOCOL_VERSION } from '@meetropolis/shared';
+import {
+ apiHttpBase,
+ apiWsBase,
+ authHeaders,
+ loginBot,
+ readResponseJson,
+ redactSecrets,
+ type LoginOptions,
+} from './session.js';
-type Zone = { id: string; name: string; polygon: Array<{ x: number; y: number }> };
+type Point = { x: number; y: number };
+type Zone = { polygon?: Point[] };
type MapEntry = { name?: string; zones?: Zone[] };
-function centroid(points: Array<{ x: number; y: number }>): { x: number; y: number } {
- if (!points || points.length === 0) return { x: 0, y: 0 };
- let sx = 0,
- sy = 0;
- for (const p of points) {
- sx += p.x;
- sy += p.y;
+const FALLBACK_WAYPOINTS: Point[] = [
+ { x: 80, y: 80 },
+ { x: 160, y: 80 },
+ { x: 160, y: 160 },
+ { x: 80, y: 160 },
+];
+
+export type ColyseusBot = {
+ userId: string;
+ sessionId: string;
+ token: string;
+ stop: () => Promise;
+};
+
+export async function spawnColyseusBot(opts: LoginOptions): Promise {
+ const session = await loginBot(opts);
+ const client = new Client(apiWsBase(opts.apiBase));
+ client.auth.token = session.token;
+ const room = await joinWorld(client, opts.tenant);
+ const waypoints = await loadWaypoints(opts.apiBase, opts.tenant, session.token);
+ const alive = { value: true };
+ startPatrol(room, waypoints, alive);
+ return {
+ userId: session.userId,
+ sessionId: room.sessionId,
+ token: session.token,
+ async stop() {
+ alive.value = false;
+ try {
+ await room.leave();
+ } catch {
+ // The room may already be gone.
+ }
+ },
+ };
+}
+
+function centroid(points: Point[]): Point {
+ if (points.length === 0) return { x: 0, y: 0 };
+ let sx = 0;
+ let sy = 0;
+ for (const point of points) {
+ sx += point.x;
+ sy += point.y;
}
return { x: Math.round(sx / points.length), y: Math.round(sy / points.length) };
}
-export async function spawnColyseusBot(opts: { apiBase: string; identity: string }) {
- const toWs = (url: string) => url.replace(/^http(s?):\/\//, 'ws$1://');
- const toHttp = (url: string) => url.replace(/^ws(s?):\/\//, 'http$1://');
- const wsEndpoint = toWs(opts.apiBase);
- const httpEndpoint = toHttp(opts.apiBase);
-
- const client = new Client(wsEndpoint);
-
- // Retry matchmaking a few times to avoid transient "connection refused" during warmup
- async function joinWithRetry(maxAttempts: number, baseDelayMs: number) {
- let attempt = 0;
+function sleep(ms: number): Promise {
+ return new Promise((resolve) => {
+ setTimeout(resolve, ms);
+ });
+}
- while (true) {
- try {
- return await client.joinOrCreate('world', { identity: opts.identity, name: opts.identity });
- } catch (e: unknown) {
- attempt++;
- if (attempt >= maxAttempts) throw e;
- const delay = Math.min(5000, baseDelayMs * Math.pow(2, attempt - 1));
- await new Promise((r) => setTimeout(r, delay));
- }
+async function joinWorld(client: Client, tenant: string) {
+ let attempt = 0;
+ while (attempt < 6) {
+ try {
+ return await client.joinOrCreate('world', {
+ tenant,
+ zonePrivacyVersion: ZONE_PRIVACY_PROTOCOL_VERSION,
+ });
+ } catch (error: unknown) {
+ attempt += 1;
+ if (attempt >= 6) throw new Error(joinFailure(error));
+ await sleep(Math.min(5000, 200 * 2 ** (attempt - 1)));
}
}
+ throw new Error('world join failed');
+}
- const room = await joinWithRetry(6, 200);
+function joinFailure(error: unknown): string {
+ const message = error instanceof Error ? redactSecrets(error.message) : '';
+ if (!message) return 'world join failed';
+ return `world join failed: ${message.slice(0, 180)}`;
+}
- // Load zones and build waypoints (centroids)
- let waypoints: Array<{ x: number; y: number }> = [];
+async function loadWaypoints(apiBase: string, tenant: string, token: string): Promise {
try {
- const mapsRes = await fetch(`${httpEndpoint}/maps`, { method: 'GET' });
- if (mapsRes.ok) {
- const mapsRaw: unknown = await mapsRes.json();
- const maps: MapEntry[] = Array.isArray(mapsRaw) ? (mapsRaw as MapEntry[]) : [];
- const office: MapEntry | null = maps.find((m) => (m?.name || '').toLowerCase() === 'office') || maps[0] || null;
- const zones: Zone[] = Array.isArray(office?.zones) ? office.zones : [];
- const cs = zones
- .map((z) => (Array.isArray(z?.polygon) ? centroid(z.polygon) : null))
- .filter((c): c is { x: number; y: number } => !!c);
- if (cs.length > 0) waypoints = cs;
- }
- } catch {}
- // Fallback circular movement if no zones are available
- if (waypoints.length === 0) {
- waypoints = [
- { x: 80, y: 80 },
- { x: 160, y: 80 },
- { x: 160, y: 160 },
- { x: 80, y: 160 },
- ];
+ const response = await fetch(`${apiHttpBase(apiBase)}/maps`, {
+ method: 'GET',
+ headers: authHeaders(tenant, token),
+ });
+ if (!response.ok) return FALLBACK_WAYPOINTS;
+ const centers = waypointsFromMaps(await readResponseJson(response));
+ if (centers.length > 0) return centers;
+ } catch {
+ return FALLBACK_WAYPOINTS;
}
+ return FALLBACK_WAYPOINTS;
+}
- // Randomise the order per bot.
- waypoints = [...waypoints].sort(() => Math.random() - 0.5);
+function waypointsFromMaps(raw: unknown): Point[] {
+ if (!Array.isArray(raw)) return [];
+ const maps = raw.filter(isMapEntry);
+ const office = maps.find((map) => (map.name || '').toLowerCase() === 'office') || maps[0];
+ const zones = office && Array.isArray(office.zones) ? office.zones : [];
+ const centers: Point[] = [];
+ for (const zone of zones) {
+ if (Array.isArray(zone.polygon)) centers.push(centroid(zone.polygon));
+ }
+ return centers;
+}
- let alive = true;
- let idx = 0;
- let pos = { x: waypoints[0].x, y: waypoints[0].y };
- const speed = 40; // Pixels per second.
- let lastTs = Date.now();
+function isMapEntry(value: unknown): value is MapEntry {
+ return typeof value === 'object' && value !== null;
+}
+
+function directionOf(dx: number, dy: number): 'up' | 'down' | 'left' | 'right' {
+ if (Math.abs(dx) > Math.abs(dy)) return dx > 0 ? 'right' : 'left';
+ return dy > 0 ? 'down' : 'up';
+}
+
+type JoinedRoom = Awaited>;
+function startPatrol(room: JoinedRoom, waypoints: Point[], alive: { value: boolean }): void {
+ const route = [...waypoints].sort(() => Math.random() - 0.5);
+ let index = 0;
+ let pos = { x: route[0].x, y: route[0].y };
+ const speed = 40;
+ let lastTs = Date.now();
void (async () => {
- // Initial position.
- try {
- room.send('move', { x: pos.x, y: pos.y, direction: 'down' });
- } catch {}
- while (alive) {
+ sendMove(room, pos, 'down');
+ while (alive.value) {
const now = Date.now();
const dt = Math.max(1, now - lastTs) / 1000;
lastTs = now;
- const target = waypoints[idx % waypoints.length];
+ const target = route[index % route.length];
const dx = target.x - pos.x;
const dy = target.y - pos.y;
const dist = Math.hypot(dx, dy);
if (dist < 3) {
- // Brief dwell time in the zone before moving to the next waypoint.
- idx++;
- await new Promise((r) => setTimeout(r, 500 + Math.floor(Math.random() * 800)));
+ index += 1;
+ await sleep(500 + Math.floor(Math.random() * 800));
continue;
}
- const step = Math.min(dist, speed * dt);
- if (dist > 0) {
- pos = { x: Math.round(pos.x + (dx / dist) * step), y: Math.round(pos.y + (dy / dist) * step) };
- }
- // Richtung approximieren
- const dir = Math.abs(dx) > Math.abs(dy) ? (dx > 0 ? 'right' : 'left') : dy > 0 ? 'down' : 'up';
- try {
- room.send('move', { x: pos.x, y: pos.y, direction: dir });
- } catch {}
- await new Promise((r) => setTimeout(r, 150));
+ pos = stepToward(pos, dx, dy, dist, Math.min(dist, speed * dt));
+ sendMove(room, pos, directionOf(dx, dy));
+ await sleep(150);
}
})();
+}
+function stepToward(pos: Point, dx: number, dy: number, dist: number, step: number): Point {
+ if (dist <= 0) return pos;
return {
- async stop() {
- alive = false;
- try {
- await room.leave();
- } catch {}
- },
+ x: Math.round(pos.x + (dx / dist) * step),
+ y: Math.round(pos.y + (dy / dist) * step),
};
}
+
+function sendMove(room: JoinedRoom, pos: Point, direction: string): void {
+ try {
+ room.send('move', { x: pos.x, y: pos.y, direction });
+ } catch {
+ // A dropped move is retried on the next tick.
+ }
+}
diff --git a/apps/loadtest/src/workers/livekitBot.ts b/apps/loadtest/src/workers/livekitBot.ts
index c4e374a1..da7d242d 100644
--- a/apps/loadtest/src/workers/livekitBot.ts
+++ b/apps/loadtest/src/workers/livekitBot.ts
@@ -7,144 +7,217 @@ import {
TrackPublishOptions,
TrackSource,
type RemoteParticipant,
- type RemoteTrackPublication,
} from '@livekit/rtc-node';
-import { AccessToken } from 'livekit-server-sdk';
+import { ZONE_PRIVACY_PROTOCOL_VERSION } from '@meetropolis/shared';
+import { apiHttpBase, authHeaders, readResponseJson } from './session.js';
const SAMPLE_RATE = 48_000;
const NUM_CHANNELS = 1;
const FRAME_DURATION_MS = 20;
-const SAMPLES_PER_FRAME = Math.floor((SAMPLE_RATE * FRAME_DURATION_MS) / 1000); // 960
+const SAMPLES_PER_FRAME = Math.floor((SAMPLE_RATE * FRAME_DURATION_MS) / 1000);
+const PARTICIPANT_FIELD = 'identity';
-export async function spawnLivekitBot(opts: {
+export type LivekitBotOptions = {
apiBase: string;
- livekitUrl: string;
+ tenant: string;
+ token: string;
roomName: string;
- identity: string;
-}): Promise<{ stop: () => Promise }> {
- // Generate server-side token (same flow as before, livekit-server-sdk stays).
- const apiKey = process.env.LIVEKIT_API_KEY || 'devkey';
- const apiSecret = process.env.LIVEKIT_API_SECRET || 'secret';
- const at = new AccessToken(apiKey, apiSecret, { identity: opts.identity });
- at.addGrant({
- room: opts.roomName,
- roomJoin: true,
- canPublish: true,
- canSubscribe: true,
+};
+
+type LivekitRun = {
+ alive: boolean;
+ samples: number;
+ lastInboundAudio: number;
+ lastRemoteParticipants: number;
+};
+
+type ConnectedRoom = {
+ room: Room;
+ audioSource: AudioSource;
+ trackSid: string | undefined;
+ timeToConnectMs: number;
+};
+
+export async function spawnLivekitBot(opts: LivekitBotOptions): Promise<{ stop: () => Promise }> {
+ const userId = subjectFromSessionToken(opts.token);
+ const url = await resolveLivekitUrl(opts.apiBase, opts.tenant, opts.token);
+ const participantToken = await requestParticipantToken(opts, userId);
+ const connected = await connectRoom(url, participantToken);
+ const run: LivekitRun = { alive: true, samples: 0, lastInboundAudio: 0, lastRemoteParticipants: 0 };
+ const silence = pushSilence(connected.audioSource, run);
+ const sampler = sampleRoom(connected.room, run);
+ return {
+ stop: () => finishLivekitBot(connected, run, silence, sampler, opts.roomName, userId),
+ };
+}
+
+function subjectFromSessionToken(token: string): string {
+ const payload = token.split('.')[1];
+ if (!payload) throw new Error('session token has no subject');
+ let parsed: unknown;
+ try {
+ parsed = JSON.parse(Buffer.from(payload, 'base64url').toString('utf8')) as unknown;
+ } catch {
+ throw new Error('session token has no subject');
+ }
+ if (typeof parsed !== 'object' || parsed === null || !('sub' in parsed)) {
+ throw new Error('session token has no subject');
+ }
+ const subject = parsed.sub;
+ if (typeof subject !== 'string' || subject.length === 0) throw new Error('session token has no subject');
+ return subject;
+}
+
+async function resolveLivekitUrl(apiBase: string, tenant: string, token: string): Promise {
+ const fromEnv = process.env.LIVEKIT_URL;
+ if (fromEnv && fromEnv.trim()) return normalizeLivekitUrl(fromEnv);
+ const response = await fetch(`${apiHttpBase(apiBase)}/livekit/url`, {
+ method: 'GET',
+ headers: authHeaders(tenant, token),
});
- const token = await at.toJwt();
+ if (!response.ok) throw new Error(`livekit url request failed with status ${response.status}`);
+ const url = readUrlField(await readResponseJson(response));
+ if (!url) throw new Error('livekit url missing');
+ return normalizeLivekitUrl(url);
+}
- const t0 = Date.now();
- const room = new Room();
- await room.connect(opts.livekitUrl, token, {
- autoSubscribe: false,
- dynacast: false,
+function readUrlField(body: unknown): string | null {
+ if (typeof body !== 'object' || body === null || !('url' in body)) return null;
+ const url = body.url;
+ return typeof url === 'string' && url.trim() ? url : null;
+}
+
+function normalizeLivekitUrl(input: string): string {
+ const trimmed = input.trim();
+ if (trimmed.startsWith('ws://') || trimmed.startsWith('wss://')) return trimmed;
+ if (trimmed.startsWith('http://')) return `ws://${trimmed.slice('http://'.length)}`;
+ if (trimmed.startsWith('https://')) return `wss://${trimmed.slice('https://'.length)}`;
+ return trimmed;
+}
+
+async function requestParticipantToken(opts: LivekitBotOptions, userId: string): Promise {
+ const response = await fetch(`${apiHttpBase(opts.apiBase)}/livekit/token`, {
+ method: 'POST',
+ headers: {
+ 'Content-Type': 'application/json',
+ ...authHeaders(opts.tenant, opts.token),
+ },
+ body: JSON.stringify({
+ roomName: opts.roomName,
+ name: userId,
+ zonePrivacyVersion: ZONE_PRIVACY_PROTOCOL_VERSION,
+ [PARTICIPANT_FIELD]: userId,
+ }),
});
- const timeToConnectMs = Date.now() - t0;
+ if (!response.ok) throw new Error(`livekit token request failed with status ${response.status}`);
+ const participantToken = (await response.text()).trim();
+ if (!participantToken) throw new Error(`livekit token request failed with status ${response.status}`);
+ return participantToken;
+}
- // Publish silence audio so the bot looks like a normal participant with a mic track.
+async function connectRoom(url: string, participantToken: string): Promise {
+ const started = Date.now();
+ const room = new Room();
+ await room.connect(url, participantToken, { autoSubscribe: false, dynacast: false });
+ const publisher = room.localParticipant;
+ if (!publisher) throw new Error('livekit room has no local participant');
const audioSource = new AudioSource(SAMPLE_RATE, NUM_CHANNELS);
const audioTrack = LocalAudioTrack.createAudioTrack('loadtest-audio', audioSource);
const publishOptions = new TrackPublishOptions({ source: TrackSource.SOURCE_MICROPHONE });
- const publication = await room.localParticipant!.publishTrack(audioTrack, publishOptions);
- const trackSid = publication.sid;
-
- // Periodically push silent frames (zero PCM) to keep the publication alive
- // and provide realistic upstream traffic for SFU stress testing.
- let alive = true;
- const silenceFramePromise = (async () => {
- const silentSamples = new Int16Array(SAMPLES_PER_FRAME * NUM_CHANNELS); // initialised to 0
- while (alive) {
- try {
- const frame = new AudioFrame(silentSamples, SAMPLE_RATE, NUM_CHANNELS, SAMPLES_PER_FRAME);
- await audioSource.captureFrame(frame);
- } catch {
- // If capture fails (e.g. track was unpublished), stop.
- break;
- }
+ const publication = await publisher.publishTrack(audioTrack, publishOptions);
+ return { room, audioSource, trackSid: publication.sid, timeToConnectMs: Date.now() - started };
+}
+
+async function pushSilence(audioSource: AudioSource, run: LivekitRun): Promise {
+ const silentSamples = new Int16Array(SAMPLES_PER_FRAME * NUM_CHANNELS);
+ while (run.alive) {
+ try {
+ const frame = new AudioFrame(silentSamples, SAMPLE_RATE, NUM_CHANNELS, SAMPLES_PER_FRAME);
+ await audioSource.captureFrame(frame);
+ } catch {
+ break;
}
- })();
+ }
+}
- let samples = 0;
- let lastInboundAudio = 0;
- let lastRemoteParticipants = 0;
+async function sampleRoom(room: Room, run: LivekitRun): Promise {
+ while (run.alive) {
+ try {
+ const participants = Array.from(room.remoteParticipants.values());
+ subscribeFirstAudio(participants);
+ run.lastRemoteParticipants = participants.length;
+ run.lastInboundAudio = countAudioTracks(participants);
+ run.samples += 1;
+ } catch {
+ // Sampling must not abort the bot.
+ }
+ await new Promise((resolve) => {
+ setTimeout(resolve, 1000);
+ });
+ }
+}
- // Periodically subscribe to a few participants (simulate proximity) and
- // sample basic metrics. rtc-node exposes `room.remoteParticipants` as a Map
- // and each RemoteTrackPublication has `setSubscribed(boolean)`.
- const samplerPromise = (async () => {
- while (alive) {
+function subscribeFirstAudio(participants: RemoteParticipant[]): void {
+ for (const participant of participants.slice(0, 5)) {
+ for (const publication of participant.trackPublications.values()) {
+ if (publication.kind !== TrackKind.KIND_AUDIO) continue;
try {
- const parts: RemoteParticipant[] = Array.from(room.remoteParticipants.values());
- const firstN = parts.slice(0, 5);
- for (const p of firstN) {
- const pubs: RemoteTrackPublication[] = Array.from(p.trackPublications.values());
- for (const pub of pubs) {
- if (pub.kind === TrackKind.KIND_AUDIO) {
- try {
- pub.setSubscribed(true);
- } catch {
- /* ignore */
- }
- }
- }
- }
- // Basic metrics
- lastRemoteParticipants = parts.length;
- let inboundAudio = 0;
- for (const p of parts) {
- const pubs: RemoteTrackPublication[] = Array.from(p.trackPublications.values());
- for (const pub of pubs) {
- if (pub.kind === TrackKind.KIND_AUDIO) inboundAudio++;
- }
- }
- lastInboundAudio = inboundAudio;
- samples++;
+ publication.setSubscribed(true);
} catch {
- // Ignore sampling errors: they should not abort the bot.
+ // A publication can disappear between the snapshot and the subscribe call.
}
- await new Promise((r) => setTimeout(r, 1000));
}
- })();
+ }
+}
- return {
- async stop() {
- alive = false;
- // Wait for background loops so we don't capture frames after disconnect.
- await Promise.allSettled([silenceFramePromise, samplerPromise]);
- try {
- if (trackSid) {
- await room.localParticipant?.unpublishTrack(trackSid);
- }
- } catch {
- /* ignore */
- }
- try {
- await audioSource.close();
- } catch {
- /* ignore */
- }
- try {
- await room.disconnect();
- } catch {
- /* ignore */
- }
- // Emit summary line for ingestion
- try {
- console.log(
- JSON.stringify({
- event: 'livekit_bot_summary',
- identity: opts.identity,
- room: opts.roomName,
- timeToConnectMs,
- samples,
- lastRemoteParticipants,
- lastInboundAudio,
- }),
- );
- } catch {
- /* ignore */
- }
- },
- };
+function countAudioTracks(participants: RemoteParticipant[]): number {
+ let inboundAudio = 0;
+ for (const participant of participants) {
+ for (const publication of participant.trackPublications.values()) {
+ if (publication.kind === TrackKind.KIND_AUDIO) inboundAudio += 1;
+ }
+ }
+ return inboundAudio;
+}
+
+async function finishLivekitBot(
+ connected: ConnectedRoom,
+ run: LivekitRun,
+ silence: Promise,
+ sampler: Promise,
+ roomName: string,
+ userId: string,
+): Promise {
+ run.alive = false;
+ await Promise.allSettled([silence, sampler]);
+ await releaseRoom(connected);
+ console.log(
+ JSON.stringify({
+ event: 'livekit_bot_summary',
+ userId,
+ room: roomName,
+ timeToConnectMs: connected.timeToConnectMs,
+ samples: run.samples,
+ lastRemoteParticipants: run.lastRemoteParticipants,
+ lastInboundAudio: run.lastInboundAudio,
+ }),
+ );
+}
+
+async function releaseRoom(connected: ConnectedRoom): Promise {
+ try {
+ if (connected.trackSid) await connected.room.localParticipant?.unpublishTrack(connected.trackSid);
+ } catch {
+ // Unpublish is best-effort during shutdown.
+ }
+ try {
+ await connected.audioSource.close();
+ } catch {
+ // The source may already be closed.
+ }
+ try {
+ await connected.room.disconnect();
+ } catch {
+ // Disconnect is best-effort during shutdown.
+ }
}
diff --git a/apps/loadtest/src/workers/session.ts b/apps/loadtest/src/workers/session.ts
new file mode 100644
index 00000000..a85f3f22
--- /dev/null
+++ b/apps/loadtest/src/workers/session.ts
@@ -0,0 +1,160 @@
+export type LoginOptions = {
+ apiBase: string;
+ tenant: string;
+ email: string;
+ password: string;
+};
+
+export type BotSession = {
+ token: string;
+ userId: string;
+};
+
+export type LoadtestAccount = {
+ email: string;
+ password: string;
+};
+
+export function apiHttpBase(apiBase: string): string {
+ return apiBase.replace(/\/+$/, '').replace(/^ws(s?):\/\//, 'http$1://');
+}
+
+export function apiWsBase(apiBase: string): string {
+ return apiHttpBase(apiBase).replace(/^http(s?):\/\//, 'ws$1://');
+}
+
+export function authHeaders(tenant: string, token: string): Record {
+ return {
+ 'X-Tenant': tenant,
+ Authorization: `Bearer ${token}`,
+ };
+}
+
+export function redactSecrets(text: string): string {
+ return text
+ .replace(/[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+/g, '[redacted]')
+ .replace(/Bearer\s+\S+/gi, 'Bearer [redacted]');
+}
+
+export async function readResponseJson(response: Response): Promise {
+ const body: unknown = await response.json();
+ return body;
+}
+
+export function parseAccounts(raw: string): LoadtestAccount[] {
+ const parsed = parseJson(raw);
+ if (!Array.isArray(parsed)) {
+ throw new Error('LOADTEST_ACCOUNTS_FILE must contain a JSON array');
+ }
+ return parsed.map(readAccount);
+}
+
+export async function loginBot(opts: LoginOptions): Promise {
+ const response = await postLogin(opts);
+ const body = await readJsonBody(response);
+ if (!response.ok) throw loginError(response.status, body);
+ const token = readAuthToken(response.headers);
+ const userId = readUserId(body);
+ if (!token || !userId) throw new Error(`login failed with status ${response.status}`);
+ return { token, userId };
+}
+
+function parseJson(text: string): unknown {
+ try {
+ return JSON.parse(text) as unknown;
+ } catch {
+ throw new Error('LOADTEST_ACCOUNTS_FILE is not valid JSON');
+ }
+}
+
+function readAccount(value: unknown): LoadtestAccount {
+ if (typeof value !== 'object' || value === null) {
+ throw new Error('LOADTEST_ACCOUNTS_FILE entries need email and password');
+ }
+ if (!('email' in value) || !('password' in value)) {
+ throw new Error('LOADTEST_ACCOUNTS_FILE entries need email and password');
+ }
+ const email = value.email;
+ const password = value.password;
+ if (typeof email !== 'string' || email.length === 0) {
+ throw new Error('LOADTEST_ACCOUNTS_FILE entries need email and password');
+ }
+ if (typeof password !== 'string' || password.length === 0) {
+ throw new Error('LOADTEST_ACCOUNTS_FILE entries need email and password');
+ }
+ return { email, password };
+}
+
+async function postLogin(opts: LoginOptions): Promise {
+ try {
+ return await fetch(`${apiHttpBase(opts.apiBase)}/auth/login`, {
+ method: 'POST',
+ headers: {
+ 'Content-Type': 'application/json',
+ 'X-Tenant': opts.tenant,
+ },
+ body: JSON.stringify({ email: opts.email, password: opts.password }),
+ });
+ } catch {
+ throw new Error('login failed: network error');
+ }
+}
+
+async function readJsonBody(response: Response): Promise {
+ const text = await response.text();
+ if (!text) return null;
+ try {
+ return JSON.parse(text) as unknown;
+ } catch {
+ return null;
+ }
+}
+
+function loginError(status: number, body: unknown): Error {
+ const code = readErrorCode(body);
+ if (!code) return new Error(`login failed with status ${status}`);
+ return new Error(`login failed with status ${status}: ${code}`);
+}
+
+function readErrorCode(body: unknown): string | null {
+ if (typeof body !== 'object' || body === null || !('error' in body)) return null;
+ const error = body.error;
+ if (typeof error !== 'string' || !/^[a-z0-9_ .:-]{1,80}$/i.test(error)) return null;
+ if (error.split('.').length === 3) return null;
+ return error;
+}
+
+function readUserId(body: unknown): string | null {
+ if (typeof body !== 'object' || body === null || !('id' in body)) return null;
+ const id = body.id;
+ return typeof id === 'string' && id.length > 0 ? id : null;
+}
+
+function readAuthToken(headers: Headers): string | null {
+ for (const line of cookieHeaderLines(headers)) {
+ const token = tokenFromCookieLine(line);
+ if (token) return token;
+ }
+ return null;
+}
+
+function cookieHeaderLines(headers: Headers): string[] {
+ const listed = headers.getSetCookie();
+ if (listed.length > 0) return listed;
+ const single = headers.get('set-cookie');
+ return single ? [single] : [];
+}
+
+function tokenFromCookieLine(line: string): string | null {
+ const first = line.split(';')[0] ?? '';
+ const eq = first.indexOf('=');
+ if (eq <= 0) return null;
+ if (first.slice(0, eq).trim() !== 'auth_token') return null;
+ const raw = first.slice(eq + 1).trim();
+ if (!raw) return null;
+ try {
+ return decodeURIComponent(raw);
+ } catch {
+ return raw;
+ }
+}
diff --git a/apps/npc-service/Dockerfile b/apps/npc-service/Dockerfile
index d00ee8e1..c0401b6d 100644
--- a/apps/npc-service/Dockerfile
+++ b/apps/npc-service/Dockerfile
@@ -29,6 +29,8 @@ WORKDIR /workspace/apps/npc-service
ENV NODE_ENV=production
+LABEL org.opencontainers.image.licenses="AGPL-3.0-only"
+
EXPOSE 3100
CMD ["node", "--enable-source-maps", "dist/index.js"]
diff --git a/apps/npc-service/package.json b/apps/npc-service/package.json
index 753e0a30..c7eb5997 100644
--- a/apps/npc-service/package.json
+++ b/apps/npc-service/package.json
@@ -8,22 +8,24 @@
"dev": "tsx src/index.ts",
"start": "node --enable-source-maps dist/index.js",
"build": "tsc -p tsconfig.json",
- "typecheck": "tsc -p tsconfig.json --noEmit"
+ "typecheck": "tsc -p tsconfig.json --noEmit",
+ "test": "vitest run --config vitest.config.ts"
},
"dependencies": {
"@meetropolis/shared": "*",
- "@colyseus/sdk": "^0.17.43",
- "@livekit/rtc-node": "^1.1.0",
- "livekit-server-sdk": "^2.19.1",
- "express": "^5.2.1",
- "pino": "^10.3.1",
- "zod": "^4.6.4",
+ "@colyseus/sdk": "^0.18.10",
+ "@livekit/rtc-node": "^1.2.2",
+ "livekit-server-sdk": "^2.20.0",
+ "express": "^5.3.0",
+ "pino": "^10.4.0",
+ "zod": "^4.6.6",
"dotenv": "^17.4.2"
},
"devDependencies": {
"@types/express": "^5.0.6",
- "@types/node": "^26.6.2",
+ "@types/node": "^26.6.6",
"tsx": "^4.23.15",
- "typescript": "^6.0.3"
+ "typescript": "^6.0.3",
+ "vitest": "^5.1.0"
}
}
diff --git a/apps/npc-service/src/bot/livekitGrant.test.ts b/apps/npc-service/src/bot/livekitGrant.test.ts
new file mode 100644
index 00000000..3be8287e
--- /dev/null
+++ b/apps/npc-service/src/bot/livekitGrant.test.ts
@@ -0,0 +1,36 @@
+import { AccessToken, TokenVerifier } from 'livekit-server-sdk';
+import { describe, expect, it } from 'vitest';
+import { npcRoomConnectOptions, npcVideoGrant } from './livekitGrant.js';
+
+const TEST_API_KEY = 'test-key';
+const TEST_API_SECRET = 'test-secret-with-more-than-32-characters';
+
+describe('npcVideoGrant', () => {
+ it('sets every grant explicitly and denies publishing data', () => {
+ expect(npcVideoGrant('tenant:world')).toEqual({
+ room: 'tenant:world',
+ roomJoin: true,
+ canPublish: true,
+ canSubscribe: true,
+ canPublishData: false,
+ });
+ });
+
+ it('produces a token whose verified claims deny publishing data', async () => {
+ const accessToken = new AccessToken(TEST_API_KEY, TEST_API_SECRET, { identity: 'npc-test' });
+ accessToken.addGrant(npcVideoGrant('tenant:world'));
+ const token = await accessToken.toJwt();
+
+ const claims = await new TokenVerifier(TEST_API_KEY, TEST_API_SECRET).verify(token);
+
+ expect(claims.video?.canPublishData).toBe(false);
+ expect(claims.video?.canPublish).toBe(true);
+ expect(claims.video?.canSubscribe).toBe(true);
+ });
+});
+
+describe('npcRoomConnectOptions', () => {
+ it('never subscribes to other participants on its own', () => {
+ expect(npcRoomConnectOptions).toEqual({ autoSubscribe: false, dynacast: false });
+ });
+});
diff --git a/apps/npc-service/src/bot/livekitGrant.ts b/apps/npc-service/src/bot/livekitGrant.ts
new file mode 100644
index 00000000..ff91a11a
--- /dev/null
+++ b/apps/npc-service/src/bot/livekitGrant.ts
@@ -0,0 +1,20 @@
+import type { VideoGrant } from 'livekit-server-sdk';
+
+// Set every grant explicitly: unset grants default to allowed on the server,
+// so leaving out canPublishData would still let this participant publish data.
+// canSubscribe must be true: the Rust SDK's wait_pc_connection() waits for
+// the subscriber PeerConnection to reach "connected" state. With canSubscribe: false,
+// the server never sends a subscriber offer, causing a 15s timeout.
+export function npcVideoGrant(roomName: string): VideoGrant {
+ return {
+ room: roomName,
+ roomJoin: true,
+ canPublish: true,
+ canSubscribe: true,
+ canPublishData: false,
+ };
+}
+
+// NPC bots only publish. They never subscribe to other participants on their
+// own, so no participant's media reaches a bot without an explicit request.
+export const npcRoomConnectOptions = { autoSubscribe: false, dynacast: false } as const;
diff --git a/apps/npc-service/src/bot/livekitPublisher.ts b/apps/npc-service/src/bot/livekitPublisher.ts
index dc6a90fd..013d4b21 100644
--- a/apps/npc-service/src/bot/livekitPublisher.ts
+++ b/apps/npc-service/src/bot/livekitPublisher.ts
@@ -1,5 +1,6 @@
import type { NpcSpawnCommand } from '@meetropolis/shared';
import { logger } from '../index.js';
+import { npcRoomConnectOptions, npcVideoGrant } from './livekitGrant.js';
import { parseWavFrames, transcodeToPcm } from './mediaPlayer.js';
// Lazy imports for @livekit/rtc-node (may not be available in all environments)
@@ -18,6 +19,8 @@ async function getLkServerSdk(): Promise {
interface LivekitTrackHandle {
stop?: () => void | Promise;
+ // Set for video handles so a new publish of the same source replaces the old one
+ source?: number;
}
export class LivekitPublisher {
@@ -41,18 +44,12 @@ export class LivekitPublisher {
const sdk = await getLkServerSdk();
const at = new sdk.AccessToken(livekitApiKey, livekitApiSecret, { identity });
- // canSubscribe must be true: the Rust SDK's wait_pc_connection() waits for
- // the subscriber PeerConnection to reach "connected" state. With canSubscribe: false,
- // the server never sends a subscriber offer, causing a 15s timeout.
- at.addGrant({ room: roomName, roomJoin: true, canPublish: true, canSubscribe: true });
+ at.addGrant(npcVideoGrant(roomName));
const token = await at.toJwt();
this.room = new lk.Room();
logger.info(`[LivekitPublisher ${identity}] Connecting to ${livekitUrl} room=${roomName}...`);
- await this.room.connect(livekitUrl, token, {
- autoSubscribe: false,
- dynacast: false,
- });
+ await this.room.connect(livekitUrl, token, npcRoomConnectOptions);
this.connected = true;
logger.info(`[LivekitPublisher ${identity}] Connected to room ${roomName}`);
} catch (e) {
@@ -162,19 +159,49 @@ export class LivekitPublisher {
}
async publishVideo(filePath: string, loop?: boolean, _mimeType?: string): Promise {
- if (!this.connected) await this.connect();
- const identity = this.command.npc.identity;
- logger.info(`[LivekitPublisher ${identity}] publishVideo: ${filePath} loop=${!!loop}`);
- // TODO: Implement video frame pipeline
- logger.warn(`[LivekitPublisher ${identity}] Video publishing not yet implemented (requires FFmpeg pipeline)`);
+ const lk = await getLkRtcNode();
+ await this.publishVideoFile(filePath, loop, lk.TrackSource.SOURCE_CAMERA, 'npc-video');
}
async publishScreenshare(filePath: string, loop?: boolean, _mimeType?: string): Promise {
+ const lk = await getLkRtcNode();
+ await this.publishVideoFile(filePath, loop, lk.TrackSource.SOURCE_SCREENSHARE, 'npc-screenshare');
+ }
+
+ private async publishVideoFile(
+ filePath: string,
+ loop: boolean | undefined,
+ source: import('@livekit/rtc-node').TrackSource,
+ trackName: string,
+ ): Promise {
if (!this.connected) await this.connect();
const identity = this.command.npc.identity;
- logger.info(`[LivekitPublisher ${identity}] publishScreenshare: ${filePath} loop=${!!loop}`);
- // TODO: Implement screenshare pipeline (similar to video but as screen source)
- logger.warn(`[LivekitPublisher ${identity}] Screenshare publishing not yet implemented`);
+ logger.info(`[LivekitPublisher ${identity}] ${trackName}: ${filePath} loop=${!!loop}`);
+ await this.stopTracksBySource(source);
+ const lk = await getLkRtcNode();
+ // Loaded lazily like the LiveKit SDK above; keeps the module's import block unchanged
+ const { startVideoTrack } = await import('./videoTrack.js');
+ const playback = await startVideoTrack(lk, this.room!.localParticipant!, filePath, { source, trackName, loop });
+ const handle: LivekitTrackHandle = { source, stop: playback.stop };
+ this.activeTracks.push(handle);
+ try {
+ await playback.done;
+ } finally {
+ const idx = this.activeTracks.indexOf(handle);
+ if (idx >= 0) this.activeTracks.splice(idx, 1);
+ }
+ }
+
+ private async stopTracksBySource(source: import('@livekit/rtc-node').TrackSource): Promise {
+ const matching = this.activeTracks.filter((t) => t.source === source);
+ this.activeTracks = this.activeTracks.filter((t) => t.source !== source);
+ for (const track of matching) {
+ try {
+ await track.stop?.();
+ } catch {
+ /* ignore track stop errors */
+ }
+ }
}
async stopAllMedia(): Promise {
diff --git a/apps/npc-service/src/bot/livekitPublisher.video.integration.test.ts b/apps/npc-service/src/bot/livekitPublisher.video.integration.test.ts
new file mode 100644
index 00000000..168eb686
--- /dev/null
+++ b/apps/npc-service/src/bot/livekitPublisher.video.integration.test.ts
@@ -0,0 +1,175 @@
+import { spawn } from 'node:child_process';
+import { randomUUID } from 'node:crypto';
+import { mkdtemp, rm, writeFile } from 'node:fs/promises';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import pino from 'pino';
+import { AccessToken } from 'livekit-server-sdk';
+import { Room, RoomEvent, TrackKind, TrackSource, VideoStream } from '@livekit/rtc-node';
+import type { RemoteParticipant, RemoteTrack, RemoteTrackPublication } from '@livekit/rtc-node';
+import { afterAll, afterEach, beforeAll, describe, expect, it, vi } from 'vitest';
+import type { NpcSpawnCommand } from '@meetropolis/shared';
+import { LivekitPublisher } from './livekitPublisher.js';
+
+// importing index.js would start the HTTP server; only the logger is replaced, LiveKit and ffmpeg stay real.
+vi.mock('../index.js', () => ({ logger: pino({ level: 'silent' }) }));
+
+const LIVEKIT_URL = process.env.LIVEKIT_URL ?? '';
+const LIVEKIT_API_KEY = process.env.LIVEKIT_API_KEY ?? '';
+const LIVEKIT_API_SECRET = process.env.LIVEKIT_API_SECRET ?? '';
+
+let tmpDir = '';
+let clipPath = '';
+let notVideoPath = '';
+const publishers: LivekitPublisher[] = [];
+const receiverRooms: Room[] = [];
+
+function makeCommand(): { command: NpcSpawnCommand; roomName: string; participantIdentity: string } {
+ const suffix = randomUUID();
+ const tenantSlug = `test-${suffix}`;
+ const identity = `test-npc-${suffix}`;
+ const command = {
+ npc: { identity },
+ livekitUrl: LIVEKIT_URL,
+ livekitApiKey: LIVEKIT_API_KEY,
+ livekitApiSecret: LIVEKIT_API_SECRET,
+ tenantSlug,
+ } as unknown as NpcSpawnCommand;
+ return { command, roomName: `${tenantSlug}:world`, participantIdentity: `npc-${identity}` };
+}
+
+async function connectReceiver(roomName: string): Promise {
+ const token = new AccessToken(LIVEKIT_API_KEY, LIVEKIT_API_SECRET, {
+ identity: `receiver-${randomUUID()}`,
+ });
+ token.addGrant({ room: roomName, roomJoin: true, canSubscribe: true, canPublish: false });
+ const room = new Room();
+ await room.connect(LIVEKIT_URL, await token.toJwt(), { autoSubscribe: true });
+ receiverRooms.push(room);
+ return room;
+}
+
+async function waitForVideoTrack(
+ room: Room,
+ participantIdentity: string,
+ timeoutMs = 20000,
+): Promise {
+ const publication = await new Promise((resolve, reject) => {
+ const timer = setTimeout(() => {
+ room.off(RoomEvent.TrackSubscribed, onTrack);
+ reject(new Error(`timed out waiting for a video track of ${participantIdentity}`));
+ }, timeoutMs);
+ const onTrack = (track: RemoteTrack, pub: RemoteTrackPublication, participant: RemoteParticipant): void => {
+ if (participant.identity !== participantIdentity) return;
+ if (track.kind !== TrackKind.KIND_VIDEO) return;
+ clearTimeout(timer);
+ room.off(RoomEvent.TrackSubscribed, onTrack);
+ resolve(pub);
+ };
+ room.on(RoomEvent.TrackSubscribed, onTrack);
+ });
+ const source = publication.source;
+ const track = publication.track;
+ if (!track) throw new Error(`video publication of ${participantIdentity} has no track`);
+ const stream = new VideoStream(track);
+ const reader = stream.getReader();
+ const first = await reader.read();
+ if (first.done || !first.value)
+ throw new Error(`video stream of ${participantIdentity} ended before the first frame`);
+ await reader.cancel();
+ return source;
+}
+
+describe.skipIf(!LIVEKIT_URL || !LIVEKIT_API_KEY || !LIVEKIT_API_SECRET)(
+ 'LivekitPublisher video against a real LiveKit server',
+ () => {
+ beforeAll(async () => {
+ tmpDir = await mkdtemp(join(tmpdir(), 'npc-video-test-'));
+ clipPath = join(tmpDir, 'clip.mp4');
+ notVideoPath = join(tmpDir, 'not-video.txt');
+ await writeFile(notVideoPath, 'not a video');
+ await new Promise((resolve, reject) => {
+ const child = spawn(
+ 'ffmpeg',
+ [
+ '-hide_banner',
+ '-loglevel',
+ 'error',
+ '-f',
+ 'lavfi',
+ '-i',
+ 'testsrc=size=320x240:rate=30:duration=2',
+ '-pix_fmt',
+ 'yuv420p',
+ clipPath,
+ ],
+ { stdio: 'ignore' },
+ );
+ child.on('error', reject);
+ child.on('close', (code) => {
+ if (code === 0) resolve();
+ else reject(new Error(`ffmpeg exited with code ${code}`));
+ });
+ });
+ }, 60000);
+
+ afterEach(async () => {
+ for (const room of receiverRooms.splice(0)) {
+ try {
+ await room.disconnect();
+ } catch {
+ // Already gone; cleanup must not fail the test.
+ }
+ }
+ for (const publisher of publishers.splice(0)) {
+ try {
+ await publisher.disconnect();
+ } catch {
+ // Already gone; cleanup must not fail the test.
+ }
+ }
+ });
+
+ afterAll(async () => {
+ await rm(tmpDir, { recursive: true, force: true });
+ });
+
+ it('publishes camera video until stopAllMedia stops it', async () => {
+ const { command, roomName, participantIdentity } = makeCommand();
+ const publisher = new LivekitPublisher(command);
+ publishers.push(publisher);
+ const room = await connectReceiver(roomName);
+ const publishing = publisher.publishVideo(clipPath, true);
+ const source = await waitForVideoTrack(room, participantIdentity);
+ expect(source).toBe(TrackSource.SOURCE_CAMERA);
+ await publisher.stopAllMedia();
+ await expect(publishing).resolves.toBeUndefined();
+ }, 60000);
+
+ it('publishes screenshare video until stopAllMedia stops it', async () => {
+ const { command, roomName, participantIdentity } = makeCommand();
+ const publisher = new LivekitPublisher(command);
+ publishers.push(publisher);
+ const room = await connectReceiver(roomName);
+ const publishing = publisher.publishScreenshare(clipPath, true);
+ const source = await waitForVideoTrack(room, participantIdentity);
+ expect(source).toBe(TrackSource.SOURCE_SCREENSHARE);
+ await publisher.stopAllMedia();
+ await expect(publishing).resolves.toBeUndefined();
+ }, 60000);
+
+ it('resolves on its own when the clip ends without loop', async () => {
+ const { command } = makeCommand();
+ const publisher = new LivekitPublisher(command);
+ publishers.push(publisher);
+ await publisher.publishVideo(clipPath);
+ }, 60000);
+
+ it('rejects for a file that is not a video', async () => {
+ const { command } = makeCommand();
+ const publisher = new LivekitPublisher(command);
+ publishers.push(publisher);
+ await expect(publisher.publishVideo(notVideoPath)).rejects.toThrow();
+ }, 60000);
+ },
+);
diff --git a/apps/npc-service/src/bot/videoFrames.test.ts b/apps/npc-service/src/bot/videoFrames.test.ts
new file mode 100644
index 00000000..bcda0d07
--- /dev/null
+++ b/apps/npc-service/src/bot/videoFrames.test.ts
@@ -0,0 +1,130 @@
+import { spawn } from 'node:child_process';
+import { mkdtemp, rm, writeFile } from 'node:fs/promises';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { afterAll, beforeAll, describe, expect, it } from 'vitest';
+import { decodeVideoFrames, fitVideoSize, probeVideoSize } from './videoFrames.js';
+
+function runFfmpeg(args: string[]): Promise {
+ return new Promise((resolve, reject) => {
+ const child = spawn('ffmpeg', args, { stdio: ['ignore', 'pipe', 'pipe'] });
+ child.on('error', reject);
+ child.on('close', (code) => {
+ if (code === 0) {
+ resolve();
+ } else {
+ reject(new Error(`ffmpeg exited with code ${code}`));
+ }
+ });
+ });
+}
+
+let tmp = '';
+let large = '';
+let small = '';
+let notVideo = '';
+let missing = '';
+
+beforeAll(async () => {
+ tmp = await mkdtemp(join(tmpdir(), 'npc-video-'));
+ large = join(tmp, 'large.mp4');
+ small = join(tmp, 'small.mp4');
+ notVideo = join(tmp, 'not-video.txt');
+ missing = join(tmp, 'missing.mp4');
+ await runFfmpeg([
+ '-hide_banner',
+ '-loglevel',
+ 'error',
+ '-f',
+ 'lavfi',
+ '-i',
+ 'testsrc=size=1920x1080:rate=30:duration=1',
+ '-pix_fmt',
+ 'yuv420p',
+ large,
+ ]);
+ await runFfmpeg([
+ '-hide_banner',
+ '-loglevel',
+ 'error',
+ '-f',
+ 'lavfi',
+ '-i',
+ 'testsrc=size=320x240:rate=30:duration=1',
+ '-pix_fmt',
+ 'yuv420p',
+ small,
+ ]);
+ await writeFile(notVideo, 'not a video');
+}, 60000);
+
+afterAll(() => rm(tmp, { recursive: true, force: true }));
+
+describe('videoFrames', () => {
+ it('fits video sizes into the maximum bounds', () => {
+ expect(fitVideoSize(1920, 1080)).toEqual({ width: 1280, height: 720 });
+ expect(fitVideoSize(320, 240)).toEqual({ width: 320, height: 240 });
+ expect(fitVideoSize(1080, 1920)).toEqual({ width: 404, height: 720 });
+ expect(fitVideoSize(641, 481)).toEqual({ width: 640, height: 480 });
+ expect(() => fitVideoSize(0, 100)).toThrow();
+ expect(() => fitVideoSize(NaN, 100)).toThrow();
+ });
+
+ it('probes video dimensions', async () => {
+ await expect(probeVideoSize(large)).resolves.toEqual({ width: 1920, height: 1080 });
+ await expect(probeVideoSize(missing)).rejects.toThrow();
+ await expect(probeVideoSize(notVideo)).rejects.toThrow();
+ });
+
+ it('decodes raw I420 frames with independent buffers', async () => {
+ const frames: Uint8Array[] = [];
+ for await (const frame of decodeVideoFrames(small, { width: 320, height: 240 })) {
+ frames.push(frame);
+ }
+ expect(frames.length).toBeGreaterThanOrEqual(13);
+ expect(frames.length).toBeLessThanOrEqual(17);
+ for (const frame of frames) {
+ expect(frame.length).toBe(115200);
+ expect(frame.byteOffset).toBe(0);
+ }
+ expect(frames[0]?.buffer).not.toBe(frames[1]?.buffer);
+ });
+
+ it('stops decoding when the abort signal fires', async () => {
+ const controller = new AbortController();
+ const frames: Uint8Array[] = [];
+ for await (const frame of decodeVideoFrames(small, {
+ width: 320,
+ height: 240,
+ loop: true,
+ signal: controller.signal,
+ })) {
+ frames.push(frame);
+ if (frames.length === 3) {
+ controller.abort();
+ }
+ }
+ expect(frames.length).toBeGreaterThanOrEqual(3);
+ }, 15000);
+
+ it('stops the ffmpeg process when the consumer breaks early', async () => {
+ const frames: Uint8Array[] = [];
+ for await (const frame of decodeVideoFrames(small, { width: 320, height: 240, loop: true })) {
+ frames.push(frame);
+ if (frames.length === 2) {
+ break;
+ }
+ }
+ expect(frames.length).toBe(2);
+ });
+
+ it('rejects when ffmpeg cannot decode the input', async () => {
+ const frames: Uint8Array[] = [];
+ const decode = (async () => {
+ for await (const frame of decodeVideoFrames(notVideo, { width: 320, height: 240 })) {
+ frames.push(frame);
+ }
+ })();
+ await expect(decode).rejects.toThrow(/ffmpeg exited with code/);
+ });
+});
diff --git a/apps/npc-service/src/bot/videoFrames.ts b/apps/npc-service/src/bot/videoFrames.ts
new file mode 100644
index 00000000..e8c082ac
--- /dev/null
+++ b/apps/npc-service/src/bot/videoFrames.ts
@@ -0,0 +1,146 @@
+import { spawn } from 'node:child_process';
+
+/** Maximum width of a decoded video frame in pixels. */
+export const VIDEO_MAX_WIDTH = 1280;
+/** Maximum height of a decoded video frame in pixels. */
+export const VIDEO_MAX_HEIGHT = 720;
+/** Default frame rate for decoded video in frames per second. */
+export const VIDEO_FPS = 15;
+
+/** Width and height of a video in pixels. */
+export interface VideoSize {
+ width: number;
+ height: number;
+}
+
+/** Scale a video size down to fit within the maximum bounds, never up. */
+export function fitVideoSize(width: number, height: number): VideoSize {
+ if (!Number.isFinite(width) || !Number.isFinite(height) || width <= 0 || height <= 0) {
+ throw new Error(`invalid video size: ${width}x${height}`);
+ }
+ const factor = Math.min(1, VIDEO_MAX_WIDTH / width, VIDEO_MAX_HEIGHT / height);
+ const scaledWidth = Math.floor(width * factor);
+ const scaledHeight = Math.floor(height * factor);
+ return {
+ width: Math.max(2, scaledWidth - (scaledWidth % 2)),
+ height: Math.max(2, scaledHeight - (scaledHeight % 2)),
+ };
+}
+
+/** Probe the width and height of the first video stream in a file. */
+export function probeVideoSize(filePath: string): Promise {
+ return new Promise((resolve, reject) => {
+ const proc = spawn('ffprobe', [
+ '-v',
+ 'error',
+ '-select_streams',
+ 'v:0',
+ '-show_entries',
+ 'stream=width,height',
+ '-of',
+ 'csv=p=0:s=x',
+ filePath,
+ ]);
+ let stdout = '';
+ let stderr = '';
+ proc.stdout?.on('data', (chunk) => {
+ stdout += String(chunk);
+ });
+ proc.stderr?.on('data', (chunk) => {
+ stderr += String(chunk);
+ });
+ proc.on('error', reject);
+ proc.on('close', (code) => {
+ if (code !== 0) {
+ reject(new Error(`ffprobe exited with code ${code}: ${stderr.trim()}`));
+ return;
+ }
+ const firstLine = stdout.split('\n')[0] ?? '';
+ const match = /^(\d+)x(\d+)/.exec(firstLine);
+ if (!match) {
+ reject(new Error(`no video stream in ${filePath}`));
+ return;
+ }
+ resolve({ width: Number(match[1]), height: Number(match[2]) });
+ });
+ });
+}
+
+/** Options for decoding raw video frames. */
+export interface VideoFrameOptions {
+ width: number;
+ height: number;
+ fps?: number;
+ loop?: boolean;
+ signal?: AbortSignal;
+}
+
+/** Decode a video file into raw I420 frames of the given size. */
+export async function* decodeVideoFrames(filePath: string, options: VideoFrameOptions): AsyncGenerator {
+ const fps = options.fps ?? VIDEO_FPS;
+ const frameBytes = (options.width * options.height * 3) / 2;
+ const proc = spawn(
+ 'ffmpeg',
+ [
+ '-hide_banner',
+ '-loglevel',
+ 'error',
+ '-re',
+ ...(options.loop ? ['-stream_loop', '-1'] : []),
+ '-i',
+ filePath,
+ '-an',
+ '-vf',
+ `scale=${options.width}:${options.height},fps=${fps}`,
+ '-pix_fmt',
+ 'yuv420p',
+ '-f',
+ 'rawvideo',
+ 'pipe:1',
+ ],
+ { stdio: ['ignore', 'pipe', 'pipe'], signal: options.signal },
+ );
+ const outcome: { code: number | null; error: Error | null } = { code: null, error: null };
+ let stderrTail = '';
+ const ended = new Promise((resolve) => {
+ proc.on('close', (code) => {
+ outcome.code = code;
+ resolve();
+ });
+ proc.on('error', (error) => {
+ outcome.error = error;
+ resolve();
+ });
+ });
+ proc.stderr?.on('data', (chunk) => {
+ stderrTail = `${stderrTail}${String(chunk)}`.slice(-500);
+ });
+ try {
+ let buffer = Buffer.alloc(0);
+ for await (const chunk of proc.stdout ?? []) {
+ buffer = Buffer.concat([buffer, chunk as Buffer]);
+ let start = 0;
+ while (start + frameBytes <= buffer.length) {
+ // Copy each frame: @livekit/rtc-node VideoFrame reads data.buffer from offset 0,
+ // so every yielded frame needs its own ArrayBuffer.
+ yield new Uint8Array(buffer.subarray(start, start + frameBytes));
+ start += frameBytes;
+ }
+ buffer = buffer.subarray(start);
+ }
+ await ended;
+ if (options.signal?.aborted) {
+ return;
+ }
+ if (outcome.error) {
+ throw new Error(`ffmpeg failed to start: ${outcome.error.message}`);
+ }
+ if (outcome.code !== 0) {
+ throw new Error(`ffmpeg exited with code ${outcome.code}: ${stderrTail.trim()}`);
+ }
+ } finally {
+ if (proc.exitCode === null && proc.signalCode === null) {
+ proc.kill('SIGKILL');
+ }
+ }
+}
diff --git a/apps/npc-service/src/bot/videoTrack.ts b/apps/npc-service/src/bot/videoTrack.ts
new file mode 100644
index 00000000..0e225062
--- /dev/null
+++ b/apps/npc-service/src/bot/videoTrack.ts
@@ -0,0 +1,82 @@
+import type * as RtcNode from '@livekit/rtc-node';
+import { decodeVideoFrames, fitVideoSize, probeVideoSize, VIDEO_FPS } from './videoFrames.js';
+
+/** Playback controls for a published video file. */
+export interface VideoPlayback {
+ stop: () => Promise;
+ done: Promise;
+}
+
+/** Options for publishing a video file as a LiveKit track. */
+export interface VideoTrackOptions {
+ source: RtcNode.TrackSource;
+ trackName: string;
+ loop?: boolean;
+}
+
+/** Runs the given async function at most once, returning the same promise. */
+function once(fn: () => Promise): () => Promise {
+ let pending: Promise | null = null;
+ return () => {
+ if (!pending) pending = fn();
+ return pending;
+ };
+}
+
+/** Publishes a video file as a LiveKit video track, frame by frame. */
+export async function startVideoTrack(
+ lk: typeof RtcNode,
+ participant: RtcNode.LocalParticipant,
+ filePath: string,
+ options: VideoTrackOptions,
+): Promise {
+ const probed = await probeVideoSize(filePath);
+ const size = fitVideoSize(probed.width, probed.height);
+ const videoSource = new lk.VideoSource(size.width, size.height);
+ const track = lk.LocalVideoTrack.createVideoTrack(options.trackName, videoSource);
+ const publication = await participant
+ .publishTrack(track, new lk.TrackPublishOptions({ source: options.source }))
+ .catch(async (err: unknown) => {
+ try {
+ await videoSource.close();
+ } catch {
+ /* already gone */
+ }
+ throw err;
+ });
+ const cleanup = once(async () => {
+ try {
+ if (publication.sid) await participant.unpublishTrack(publication.sid);
+ } catch {
+ /* already gone */
+ }
+ try {
+ await videoSource.close();
+ } catch {
+ /* already gone */
+ }
+ });
+ const controller = new AbortController();
+ const done: Promise = (async () => {
+ try {
+ let index = 0;
+ for await (const data of decodeVideoFrames(filePath, {
+ ...size,
+ fps: VIDEO_FPS,
+ loop: options.loop,
+ signal: controller.signal,
+ })) {
+ const frame = new lk.VideoFrame(data, size.width, size.height, lk.VideoBufferType.I420);
+ videoSource.captureFrame(frame, BigInt(Math.round((index * 1_000_000) / VIDEO_FPS)));
+ index += 1;
+ }
+ } finally {
+ await cleanup();
+ }
+ })();
+ const stop = async (): Promise => {
+ controller.abort();
+ await done.catch(() => undefined);
+ };
+ return { stop, done };
+}
diff --git a/apps/npc-service/src/commandSchemas.ts b/apps/npc-service/src/commandSchemas.ts
new file mode 100644
index 00000000..54875808
--- /dev/null
+++ b/apps/npc-service/src/commandSchemas.ts
@@ -0,0 +1,110 @@
+import { z } from 'zod';
+
+const MAX_IDENTIFIER_LENGTH = 128;
+const MAX_NAME_LENGTH = 200;
+const MAX_AVATAR_ID_LENGTH = 256;
+const MAX_URL_LENGTH = 512;
+const MAX_CREDENTIAL_LENGTH = 512;
+const MAX_STORAGE_PATH_LENGTH = 512;
+const MAX_MIME_TYPE_LENGTH = 128;
+const MAX_MOVE_SPEED = 1000;
+
+const MIME_TYPE_PATTERN = /^[a-zA-Z][a-zA-Z0-9+.-]*\/[a-zA-Z0-9+.-]+$/;
+const WINDOWS_DRIVE_PATTERN = /^[a-zA-Z]:/;
+
+const identifier = z.string().min(1).max(MAX_IDENTIFIER_LENGTH);
+export const tenantSlug = z.string().min(1).max(MAX_IDENTIFIER_LENGTH);
+const finiteNumber = z.number().finite();
+const strictBoolean = z.boolean();
+const npcDirection = z.enum(['up', 'down', 'left', 'right']);
+
+function serviceUrl(protocols: readonly string[]): z.ZodString {
+ return z
+ .string()
+ .min(1)
+ .max(MAX_URL_LENGTH)
+ .refine((value) => {
+ try {
+ return protocols.includes(new URL(value).protocol);
+ } catch {
+ return false;
+ }
+ });
+}
+
+function isConfinedMediaPath(value: string): boolean {
+ if (value.startsWith('/') || value.startsWith('\\') || WINDOWS_DRIVE_PATTERN.test(value)) {
+ return false;
+ }
+ return value
+ .split('/')
+ .every((segment) => segment.length > 0 && segment !== '.' && segment !== '..' && !segment.includes('\\'));
+}
+
+const npcDefinition = z.object({
+ id: identifier,
+ tenantId: identifier,
+ identity: identifier,
+ name: z.string().min(1).max(MAX_NAME_LENGTH),
+ avatarId: z.string().min(1).max(MAX_AVATAR_ID_LENGTH),
+ spawnX: finiteNumber,
+ spawnY: finiteNumber,
+ spawnDirection: npcDirection,
+ enabled: strictBoolean,
+ showBadge: strictBoolean,
+ mapName: z.string().min(1).max(MAX_NAME_LENGTH).nullish(),
+ config: z.record(z.string(), z.unknown()).nullish(),
+});
+
+export const spawnCommand = z.object({
+ npc: npcDefinition,
+ tenantSlug,
+ serverUrl: serviceUrl(['http:', 'https:']),
+ livekitUrl: serviceUrl(['ws:', 'wss:']),
+ livekitApiKey: z.string().min(1).max(MAX_CREDENTIAL_LENGTH),
+ livekitApiSecret: z.string().min(1).max(MAX_CREDENTIAL_LENGTH),
+});
+
+export const despawnCommand = z.object({
+ identity: identifier,
+ tenantSlug,
+});
+
+export const tenantField = z.object({
+ tenantSlug: tenantSlug.optional(),
+});
+
+const movePayload = z.object({
+ x: finiteNumber,
+ y: finiteNumber,
+ speed: z.number().finite().positive().max(MAX_MOVE_SPEED).optional(),
+});
+
+const mediaPayload = z.object({
+ mediaFileId: z.string().min(1).max(MAX_IDENTIFIER_LENGTH),
+ loop: strictBoolean.optional(),
+ storagePath: z.string().min(1).max(MAX_STORAGE_PATH_LENGTH).refine(isConfinedMediaPath).optional(),
+ mimeType: z.string().min(1).max(MAX_MIME_TYPE_LENGTH).regex(MIME_TYPE_PATTERN).optional(),
+});
+
+const dndPayload = z.object({
+ dnd: strictBoolean,
+});
+
+const avatarPayload = z.object({
+ avatarId: z.string().min(1).max(MAX_AVATAR_ID_LENGTH),
+});
+
+export const roomCommand = z.discriminatedUnion('action', [
+ z.object({ action: z.literal('move'), payload: movePayload }),
+ z.object({ action: z.literal('stop_movement') }),
+ z.object({ action: z.literal('play_audio'), payload: mediaPayload }),
+ z.object({ action: z.literal('play_video'), payload: mediaPayload }),
+ z.object({ action: z.literal('play_screenshare'), payload: mediaPayload }),
+ z.object({ action: z.literal('stop_media') }),
+ z.object({ action: z.literal('set_dnd'), payload: dndPayload }),
+ z.object({ action: z.literal('set_avatar'), payload: avatarPayload }),
+]);
+
+export type ValidatedSpawnCommand = z.infer;
+export type ValidatedRoomCommand = z.infer;
diff --git a/apps/npc-service/src/config.ts b/apps/npc-service/src/config.ts
index e4e1827a..81bb49f2 100644
--- a/apps/npc-service/src/config.ts
+++ b/apps/npc-service/src/config.ts
@@ -1,10 +1,26 @@
+// Comparison constant only: this value never passes validation.
+const KNOWN_DEFAULT_SECRET = 'dev-npc-secret';
+
+const MIN_SECRET_LENGTH = 32;
+
+function readNpcServiceSecret(): string {
+ const raw = process.env.NPC_SERVICE_SECRET;
+ if (raw === undefined || raw.length === 0) {
+ throw new Error('NPC_SERVICE_SECRET is missing: set it to a value of at least 32 characters.');
+ }
+ if (raw.trim().length === 0 || raw === KNOWN_DEFAULT_SECRET || raw.length < MIN_SECRET_LENGTH) {
+ throw new Error('NPC_SERVICE_SECRET is invalid: provide at least 32 characters, not the documented placeholder.');
+ }
+ return raw;
+}
+
export const config = {
port: Number(process.env.PORT || 3100),
serverUrl: process.env.SERVER_URL || 'http://server:2567',
livekitUrl: process.env.LIVEKIT_URL || 'ws://livekit:7880',
livekitApiKey: process.env.LIVEKIT_API_KEY || 'devkey',
livekitApiSecret: process.env.LIVEKIT_API_SECRET || 'secret',
- npcServiceSecret: process.env.NPC_SERVICE_SECRET || 'dev-npc-secret',
+ npcServiceSecret: readNpcServiceSecret(),
npcMediaDir: process.env.NPC_MEDIA_DIR || '/data/npc-media',
logLevel: process.env.LOG_LEVEL || 'info',
} as const;
diff --git a/apps/npc-service/src/httpApi.ts b/apps/npc-service/src/httpApi.ts
index ea76da26..c7673c04 100644
--- a/apps/npc-service/src/httpApi.ts
+++ b/apps/npc-service/src/httpApi.ts
@@ -1,19 +1,27 @@
-import type { Request, Response, NextFunction, Application } from 'express';
-import type { NpcSpawnCommand, NpcRoomCommand } from '@meetropolis/shared';
+import crypto from 'crypto';
+import express, { type Application, type NextFunction, type Request, type Response } from 'express';
+import type { NpcRoomCommand, NpcSpawnCommand } from '@meetropolis/shared';
+import { despawnCommand, roomCommand, spawnCommand, tenantSlug } from './commandSchemas.js';
import { config } from './config.js';
import { botManager } from './botManager.js';
import { logger } from './index.js';
-interface DespawnBody {
- identity?: string;
- tenantSlug?: string;
-}
+const NPC_BODY_LIMIT_BYTES = 16 * 1024;
-type CommandBody = Partial & { tenantSlug?: string };
+function timingSafeEqualStrings(a: string, b: string): boolean {
+ const aBuf = Buffer.from(a, 'utf8');
+ const bBuf = Buffer.from(b, 'utf8');
+ return aBuf.length === bBuf.length && crypto.timingSafeEqual(aBuf, bBuf);
+}
function authMiddleware(req: Request, res: Response, next: NextFunction): void {
- const secret = req.headers['x-npc-secret'] as string;
- if (secret !== config.npcServiceSecret) {
+ const distinct = req.headersDistinct?.['x-npc-secret'];
+ const raw = req.headers['x-npc-secret'];
+ if (!Array.isArray(distinct) || distinct.length !== 1 || typeof raw !== 'string') {
+ res.status(401).json({ error: 'unauthorized' });
+ return;
+ }
+ if (!timingSafeEqualStrings(raw, config.npcServiceSecret)) {
res.status(401).json({ error: 'unauthorized' });
return;
}
@@ -21,12 +29,12 @@ function authMiddleware(req: Request, res: Response, next: NextFunction): void {
}
function handleSpawn(req: Request, res: Response): void {
- const body = req.body as Partial | undefined;
- if (!body?.npc?.identity || !body?.tenantSlug) {
+ const parsed = spawnCommand.safeParse(req.body);
+ if (!parsed.success) {
res.status(400).json({ error: 'invalid_payload' });
return;
}
- const command = body as NpcSpawnCommand;
+ const command: NpcSpawnCommand = parsed.data;
botManager
.spawn(command)
.then(() => {
@@ -42,14 +50,14 @@ function handleSpawn(req: Request, res: Response): void {
}
function handleDespawn(req: Request, res: Response): void {
- const body = (req.body || {}) as DespawnBody;
- const { identity, tenantSlug } = body;
- if (!identity || !tenantSlug) {
- res.status(400).json({ error: 'identity and tenantSlug required' });
+ const parsed = despawnCommand.safeParse(req.body ?? {});
+ if (!parsed.success) {
+ res.status(400).json({ error: 'invalid_payload' });
return;
}
+ const { identity, tenantSlug: slug } = parsed.data;
botManager
- .despawn(tenantSlug, identity)
+ .despawn(slug, identity)
.then(() => {
res.json({ ok: true });
})
@@ -62,17 +70,40 @@ function handleDespawn(req: Request, res: Response): void {
});
}
+function resolveTenantSlug(req: Request): string | null {
+ const queryTenant = req.query.tenant;
+ if (Array.isArray(queryTenant)) return null;
+ if (queryTenant !== undefined && typeof queryTenant !== 'string') return null;
+ const bodyTenant = (req.body as { tenantSlug?: unknown } | undefined)?.tenantSlug;
+ if (bodyTenant !== undefined && typeof bodyTenant !== 'string') return null;
+ if (queryTenant !== undefined && bodyTenant !== undefined && queryTenant !== bodyTenant) {
+ return null;
+ }
+ const merged = queryTenant ?? bodyTenant;
+ if (merged === undefined || !tenantSlug.safeParse(merged).success) return null;
+ return merged;
+}
+
function handleCommand(req: Request, res: Response): void {
const identityParam = req.params.identity;
- const identity = Array.isArray(identityParam) ? (identityParam[0] ?? '') : (identityParam ?? '');
- const body = (req.body || {}) as CommandBody;
- const tenantSlug = (req.query.tenant as string) || body.tenantSlug;
- if (!tenantSlug) {
- res.status(400).json({ error: 'tenantSlug required' });
+ if (typeof identityParam !== 'string' || identityParam.length === 0) {
+ res.status(400).json({ error: 'invalid_payload' });
+ return;
+ }
+ const slug = resolveTenantSlug(req);
+ if (slug === null) {
+ res.status(400).json({ error: 'invalid_payload' });
+ return;
+ }
+ const body = (req.body ?? {}) as { action?: unknown; payload?: unknown };
+ const parsed = roomCommand.safeParse({ action: body.action, payload: body.payload });
+ if (!parsed.success) {
+ res.status(400).json({ error: 'invalid_payload' });
return;
}
+ const command: NpcRoomCommand = parsed.data;
try {
- botManager.sendCommand(tenantSlug, identity, body as NpcRoomCommand);
+ botManager.sendCommand(slug, identityParam, command);
res.json({ ok: true });
} catch (e: unknown) {
logger.error({ err: e }, '[HTTP] command error');
@@ -89,6 +120,7 @@ function handleGetAll(_req: Request, res: Response): void {
export function registerHttpApi(app: Application): void {
app.use('/bots', authMiddleware);
+ app.use('/bots', express.json({ limit: NPC_BODY_LIMIT_BYTES }));
app.post('/bots/spawn', handleSpawn);
app.post('/bots/despawn', handleDespawn);
diff --git a/apps/npc-service/src/index.ts b/apps/npc-service/src/index.ts
index ac24a2a2..b2a6ec57 100644
--- a/apps/npc-service/src/index.ts
+++ b/apps/npc-service/src/index.ts
@@ -13,7 +13,9 @@ interface NpcListEntry extends NpcDefinition {
export const logger = pino({ level: config.logLevel });
const app = express();
-app.use(express.json());
+// The config import above already enforces the service secret before the
+// listener, timers, or auto-respawn start. JSON parsing stays scoped to /bots
+// behind authentication (see registerHttpApi).
// Health check
app.get('/healthz', (_req, res) => {
diff --git a/apps/npc-service/src/npcHttpApi.test.ts b/apps/npc-service/src/npcHttpApi.test.ts
new file mode 100644
index 00000000..fb3185d1
--- /dev/null
+++ b/apps/npc-service/src/npcHttpApi.test.ts
@@ -0,0 +1,301 @@
+import { spawn, type ChildProcess } from 'node:child_process';
+import { existsSync } from 'node:fs';
+import { createRequire } from 'node:module';
+import { connect } from 'node:net';
+import { dirname, join } from 'node:path';
+import { fileURLToPath } from 'node:url';
+import { describe, expect, it } from 'vitest';
+
+const serviceDir = dirname(dirname(fileURLToPath(import.meta.url)));
+const authHeader = 'x-npc-secret';
+const validSecret = `test-secret-${'x'.repeat(52)}`;
+const testPortKey = 'NPC_TEST_PORT';
+// Fixed loopback port for the spawned service; override with NPC_TEST_PORT when it is taken.
+const DEFAULT_TEST_PORT = 39731;
+
+function getTestPort(): number {
+ const raw = process.env[testPortKey];
+ if (raw === undefined || raw === '') {
+ return DEFAULT_TEST_PORT;
+ }
+ const port = Number(raw);
+ if (!Number.isInteger(port) || port < 1 || port > 65535) {
+ throw new Error(`${testPortKey} must be set to an integer between 1 and 65535`);
+ }
+ return port;
+}
+
+function assertPortFree(port: number): Promise {
+ return new Promise((resolve, reject) => {
+ const socket = connect({ host: '127.0.0.1', port });
+ const timer = setTimeout(() => {
+ socket.destroy();
+ reject(new Error(`test port ${port} did not refuse a connection in time`));
+ }, 5000);
+ if (typeof timer.unref === 'function') timer.unref();
+ socket.once('connect', () => {
+ clearTimeout(timer);
+ socket.destroy();
+ reject(new Error(`test port ${port} is already in use; refusing a foreign process`));
+ });
+ socket.once('error', (error) => {
+ clearTimeout(timer);
+ if ((error as NodeJS.ErrnoException).code === 'ECONNREFUSED') {
+ resolve();
+ } else {
+ reject(error);
+ }
+ });
+ });
+}
+
+function resolveRunner(): string {
+ const scopedRequire = createRequire(join(serviceDir, 'package.json'));
+ const packagePath = scopedRequire.resolve('tsx/package.json');
+ const cliPath = join(dirname(packagePath), 'dist', 'cli.mjs');
+ if (!existsSync(cliPath)) {
+ throw new Error('tsx runner not found below the service directory');
+ }
+ return cliPath;
+}
+
+interface RunningService {
+ baseUrl: string;
+ stop: () => Promise;
+}
+
+async function waitForHealth(baseUrl: string): Promise {
+ for (let attempt = 0; attempt < 240; attempt += 1) {
+ try {
+ const res = await fetch(`${baseUrl}/healthz`);
+ if (res.ok) return;
+ } catch {
+ // Not listening yet; retry below.
+ }
+ await new Promise((resolve) => setTimeout(resolve, 250));
+ }
+ throw new Error(`service did not become ready at ${baseUrl}`);
+}
+
+function stopChild(child: ChildProcess): Promise {
+ if (child.exitCode !== null) return Promise.resolve();
+ return new Promise((resolve) => {
+ const killTimer = setTimeout(() => {
+ child.kill('SIGKILL');
+ const exitTimer = setTimeout(resolve, 5000);
+ if (typeof exitTimer.unref === 'function') exitTimer.unref();
+ child.once('exit', () => {
+ clearTimeout(exitTimer);
+ resolve();
+ });
+ }, 10000);
+ if (typeof killTimer.unref === 'function') killTimer.unref();
+ child.once('exit', () => {
+ clearTimeout(killTimer);
+ resolve();
+ });
+ child.kill('SIGTERM');
+ });
+}
+
+async function startService(): Promise {
+ const port = getTestPort();
+ await assertPortFree(port);
+ const child = spawn(process.execPath, [resolveRunner(), 'src/index.ts'], {
+ cwd: serviceDir,
+ env: {
+ ...process.env,
+ NODE_ENV: 'production',
+ PORT: String(port),
+ NPC_SERVICE_SECRET: validSecret,
+ SERVER_URL: 'http://127.0.0.1:9',
+ LOG_LEVEL: 'fatal',
+ },
+ stdio: ['ignore', 'pipe', 'pipe'],
+ });
+ child.stdout?.on('data', () => {
+ // Drain output so a chatty child never blocks on a full pipe.
+ });
+ child.stderr?.on('data', () => {
+ // Drain output so a chatty child never blocks on a full pipe.
+ });
+ const baseUrl = `http://127.0.0.1:${port}`;
+ await waitForHealth(baseUrl);
+ return { baseUrl, stop: () => stopChild(child) };
+}
+
+function postJson(
+ baseUrl: string,
+ path: string,
+ body: unknown,
+ secret: string | null = validSecret,
+): Promise {
+ const headers: Record = { 'content-type': 'application/json' };
+ if (secret !== null) headers[authHeader] = secret;
+ return fetch(`${baseUrl}${path}`, { method: 'POST', headers, body: JSON.stringify(body) });
+}
+
+describe('npc service command validation', () => {
+ it('rejects an incomplete spawn payload before execution', async () => {
+ const service = await startService();
+ try {
+ const res = await postJson(service.baseUrl, '/bots/spawn', {
+ npc: { identity: 'incomplete-spawn-probe' },
+ tenantSlug: 'probe-tenant',
+ });
+ expect(res.status).toBe(400);
+ } finally {
+ await service.stop();
+ }
+ }, 120000);
+
+ it('rejects a mistyped despawn payload before execution', async () => {
+ const service = await startService();
+ try {
+ const res = await postJson(service.baseUrl, '/bots/despawn', {
+ identity: 123,
+ tenantSlug: 'probe-tenant',
+ });
+ expect(res.status).toBe(400);
+ } finally {
+ await service.stop();
+ }
+ }, 120000);
+
+ it('rejects an unknown command action before execution', async () => {
+ const service = await startService();
+ try {
+ const res = await postJson(service.baseUrl, '/bots/probe-unknown-action/command', {
+ action: 'teleport',
+ tenantSlug: 'probe-tenant',
+ });
+ expect(res.status).toBe(400);
+ } finally {
+ await service.stop();
+ }
+ }, 120000);
+
+ it('rejects an invalid move payload before execution', async () => {
+ const service = await startService();
+ try {
+ const res = await postJson(service.baseUrl, '/bots/probe-bad-move/command', {
+ action: 'move',
+ payload: { x: 'far', y: 10 },
+ tenantSlug: 'probe-tenant',
+ });
+ expect(res.status).toBe(400);
+ } finally {
+ await service.stop();
+ }
+ }, 120000);
+
+ it('rejects a non-boolean dnd payload before execution', async () => {
+ const service = await startService();
+ try {
+ const res = await postJson(service.baseUrl, '/bots/probe-bad-dnd/command', {
+ action: 'set_dnd',
+ payload: { dnd: 'yes' },
+ tenantSlug: 'probe-tenant',
+ });
+ expect(res.status).toBe(400);
+ } finally {
+ await service.stop();
+ }
+ }, 120000);
+
+ it('rejects an empty avatar payload before execution', async () => {
+ const service = await startService();
+ try {
+ const res = await postJson(service.baseUrl, '/bots/probe-bad-avatar/command', {
+ action: 'set_avatar',
+ payload: { avatarId: '' },
+ tenantSlug: 'probe-tenant',
+ });
+ expect(res.status).toBe(400);
+ } finally {
+ await service.stop();
+ }
+ }, 120000);
+
+ it('rejects a media payload outside the media root before execution', async () => {
+ const service = await startService();
+ try {
+ const res = await postJson(service.baseUrl, '/bots/probe-bad-media/command', {
+ action: 'play_audio',
+ payload: { mediaFileId: 'clip', storagePath: '../../outside.mp3' },
+ tenantSlug: 'probe-tenant',
+ });
+ expect(res.status).toBe(400);
+ } finally {
+ await service.stop();
+ }
+ }, 120000);
+
+ it('rejects a repeated query tenant before execution', async () => {
+ const service = await startService();
+ try {
+ const res = await postJson(service.baseUrl, '/bots/probe-multi-tenant/command?tenant=alpha&tenant=beta', {
+ action: 'stop_movement',
+ });
+ expect(res.status).toBe(400);
+ } finally {
+ await service.stop();
+ }
+ }, 120000);
+
+ it('rejects a conflicting query and body tenant before execution', async () => {
+ const service = await startService();
+ try {
+ const res = await postJson(service.baseUrl, '/bots/probe-split-tenant/command?tenant=alpha', {
+ action: 'stop_movement',
+ tenantSlug: 'beta',
+ });
+ expect(res.status).toBe(400);
+ } finally {
+ await service.stop();
+ }
+ }, 120000);
+
+ it('rejects an overlong tenant slug before execution', async () => {
+ const service = await startService();
+ try {
+ const res = await postJson(service.baseUrl, '/bots/probe-long-tenant/command', {
+ action: 'stop_movement',
+ tenantSlug: 'a'.repeat(129),
+ });
+ expect(res.status).toBe(400);
+ } finally {
+ await service.stop();
+ }
+ }, 120000);
+
+ it('accepts valid auth for status reads', async () => {
+ const service = await startService();
+ try {
+ const res = await fetch(`${service.baseUrl}/bots`, { headers: { [authHeader]: validSecret } });
+ expect(res.status).toBe(200);
+ } finally {
+ await service.stop();
+ }
+ }, 120000);
+
+ it('rejects a wrong secret', async () => {
+ const service = await startService();
+ try {
+ const res = await fetch(`${service.baseUrl}/bots`, { headers: { [authHeader]: 'wrong-secret' } });
+ expect(res.status).toBe(401);
+ } finally {
+ await service.stop();
+ }
+ }, 120000);
+
+ it('rejects a missing secret', async () => {
+ const service = await startService();
+ try {
+ const res = await fetch(`${service.baseUrl}/bots`);
+ expect(res.status).toBe(401);
+ } finally {
+ await service.stop();
+ }
+ }, 120000);
+});
diff --git a/apps/npc-service/src/npcStartupSecret.test.ts b/apps/npc-service/src/npcStartupSecret.test.ts
new file mode 100644
index 00000000..e5f9a2d2
--- /dev/null
+++ b/apps/npc-service/src/npcStartupSecret.test.ts
@@ -0,0 +1,88 @@
+import { spawn } from 'node:child_process';
+import { readFileSync } from 'node:fs';
+import { dirname, join } from 'node:path';
+import { fileURLToPath, pathToFileURL } from 'node:url';
+import { describe, expect, it } from 'vitest';
+
+const moduleDir = dirname(fileURLToPath(import.meta.url));
+const configPath = join(moduleDir, 'config.ts');
+const secretKey = 'NPC_SERVICE_SECRET';
+
+function readKnownDefault(): string {
+ const source = readFileSync(configPath, 'utf8');
+ const direct = source.match(/KNOWN_DEFAULT_SECRET\s*=\s*'([^']+)'/);
+ if (direct) return direct[1];
+ const fallback = source.match(/NPC_SERVICE_SECRET[^\n]*\|\|\s*'([^']+)'/);
+ if (fallback) return fallback[1];
+ throw new Error('known default placeholder not found in config source');
+}
+
+interface StartupProbe {
+ code: number | null;
+ output: string;
+}
+
+function probeStartup(secret: string | undefined, nodeEnv: string): Promise {
+ const loader =
+ `import(${JSON.stringify(pathToFileURL(configPath).href)}).then(` +
+ `() => console.log('config loaded'),` +
+ `(error) => { console.error(error instanceof Error ? error.message : String(error)); process.exit(1); });`;
+ const env: NodeJS.ProcessEnv = { ...process.env, NODE_ENV: nodeEnv };
+ if (secret === undefined) {
+ delete env[secretKey];
+ } else {
+ env[secretKey] = secret;
+ }
+ return new Promise((resolve, reject) => {
+ const child = spawn(process.execPath, ['--input-type=module', '-e', loader], {
+ env,
+ stdio: ['ignore', 'pipe', 'pipe'],
+ });
+ let output = '';
+ child.stdout?.on('data', (chunk) => {
+ output += String(chunk);
+ });
+ child.stderr?.on('data', (chunk) => {
+ output += String(chunk);
+ });
+ child.on('error', reject);
+ const timer = setTimeout(() => {
+ child.kill('SIGKILL');
+ reject(new Error('config probe timed out'));
+ }, 20000);
+ if (typeof timer.unref === 'function') timer.unref();
+ child.on('close', (code) => {
+ clearTimeout(timer);
+ resolve({ code, output });
+ });
+ });
+}
+
+describe('npc service startup secret', () => {
+ const knownDefault = readKnownDefault();
+ const cases: Array<{ name: string; secret: string | undefined }> = [
+ { name: 'rejects a missing secret', secret: undefined },
+ { name: 'rejects an empty secret', secret: '' },
+ { name: 'rejects a whitespace secret', secret: ' \t ' },
+ { name: 'rejects the known default secret', secret: knownDefault },
+ { name: 'rejects a short secret', secret: 'x'.repeat(31) },
+ ];
+ for (const mode of ['development', 'production']) {
+ describe(`in ${mode} mode`, () => {
+ for (const entry of cases) {
+ it(
+ entry.name,
+ async () => {
+ const probe = await probeStartup(entry.secret, mode);
+ expect(probe.code).not.toBe(0);
+ expect(probe.output).toContain(secretKey);
+ if (entry.secret) {
+ expect(probe.output).not.toContain(entry.secret);
+ }
+ },
+ 30000,
+ );
+ }
+ });
+ }
+});
diff --git a/apps/npc-service/tsconfig.lint.json b/apps/npc-service/tsconfig.lint.json
index 40e72b9d..5102fa6e 100644
--- a/apps/npc-service/tsconfig.lint.json
+++ b/apps/npc-service/tsconfig.lint.json
@@ -3,6 +3,6 @@
"compilerOptions": {
"noEmit": true
},
- "include": ["src"],
+ "include": ["src", "vitest.config.ts"],
"exclude": ["dist", "node_modules"]
}
diff --git a/apps/npc-service/vitest.config.ts b/apps/npc-service/vitest.config.ts
new file mode 100644
index 00000000..b0b70489
--- /dev/null
+++ b/apps/npc-service/vitest.config.ts
@@ -0,0 +1,12 @@
+import { defineConfig } from 'vitest/config';
+
+export default defineConfig({
+ test: {
+ environment: 'node',
+ include: ['src/**/*.test.ts'],
+ exclude: ['**/node_modules/**', '**/dist/**'],
+ testTimeout: 60000,
+ hookTimeout: 30000,
+ fileParallelism: false,
+ },
+});
diff --git a/apps/server/Dockerfile b/apps/server/Dockerfile
index fe71b996..a7a43568 100644
--- a/apps/server/Dockerfile
+++ b/apps/server/Dockerfile
@@ -72,6 +72,8 @@ COPY --from=builder /workspace/apps/server/node_modules ./node_modules
# Shared package (workspace symlink target, needed at runtime by zoneLockHandler etc.)
COPY --from=builder /workspace/packages/shared /workspace/packages/shared
COPY --from=builder /workspace/apps/server/prisma ./prisma
+# Prisma 7 reads datasource.url from this file; the schema has no url.
+COPY --from=builder /workspace/apps/server/prisma.config.ts ./prisma.config.ts
COPY --from=builder /workspace/apps/server/dist ./dist
# Copy generated Prisma client to dist/ (compiled code imports from dist/generated)
COPY --from=builder /workspace/apps/server/src/generated ./dist/generated
diff --git a/apps/server/entrypoint.sh b/apps/server/entrypoint.sh
index dcd213ff..977de8f5 100644
--- a/apps/server/entrypoint.sh
+++ b/apps/server/entrypoint.sh
@@ -7,6 +7,16 @@ set -e
# container.
PRISMA_SCHEMA="${PRISMA_SCHEMA:-/workspace/apps/server/prisma/schema.prisma}"
+# Production credential policy: same checker the server runs at startup.
+# Runs before migrations, seeding, or the server command. Fails closed when
+# the compiled checker is missing, so a broken build never starts silently.
+if [ -f dist/ops/startupCredentials.js ]; then
+ node dist/ops/startupCredentials.js || exit 1
+else
+ echo '[entrypoint] credential checker missing at dist/ops/startupCredentials.js; refusing to start' >&2
+ exit 1
+fi
+
if [ "$RUN_MIGRATIONS" = "true" ]; then
echo "[entrypoint] prisma migrate deploy --schema $PRISMA_SCHEMA"
npx prisma migrate deploy --schema "$PRISMA_SCHEMA"
diff --git a/apps/server/package.json b/apps/server/package.json
index 78adec21..3fff222b 100644
--- a/apps/server/package.json
+++ b/apps/server/package.json
@@ -8,9 +8,10 @@
"predev": "prisma generate --schema=./prisma/schema.prisma && prisma db push --schema=./prisma/schema.prisma && prisma db seed --schema=./prisma/schema.prisma",
"dev": "tsx watch src/index.ts",
"build": "tsc -p tsconfig.json && node ./scripts/copy-generated.mjs && node ./scripts/copy-catalog.mjs",
- "typecheck": "tsc -p tsconfig.json --noEmit && tsc -p tsconfig.seed.json",
+ "typecheck": "tsc -p tsconfig.json --noEmit && tsc -p tsconfig.seed.json && tsc -p tsconfig.test.json",
"start": "node dist/index.js",
- "test": "vitest run",
+ "test": "vitest run --project server",
+ "test:db": "vitest run --project server-db --project server-db-exclusive",
"map:import:v2": "tsx src/scripts/importMapV2.ts",
"map:atelier:migrate": "tsx src/scripts/migrateAtelierStandardMap.ts",
"map:autotiles:migrate": "tsx src/scripts/migrateAutotilePalettes.ts",
@@ -23,39 +24,47 @@
"start:dev": "tsx watch src/index.ts"
},
"dependencies": {
- "@colyseus/schema": "^4.0.30",
- "@colyseus/sdk": "^0.17.43",
- "@prisma/adapter-pg": "^7.10.0",
- "@prisma/client": "^7.10.0",
- "altcha-lib": "^2.5.0",
+ "@colyseus/core": "^0.18.28",
+ "@colyseus/redis-driver": "^0.18.7",
+ "@colyseus/redis-presence": "^0.18.6",
+ "@colyseus/schema": "^5.0.49",
+ "@colyseus/sdk": "^0.18.10",
+ "@colyseus/ws-transport": "^0.18.5",
+ "@meetropolis/shared": "*",
+ "@prisma/adapter-pg": "^7.10.1",
+ "@prisma/client": "^7.10.1",
+ "altcha-lib": "^2.9.0",
"bcryptjs": "^3.0.3",
"c12": "^3.3.4",
- "colyseus": "^0.17.10",
"compression": "^1.8.2",
"cookie-parser": "^1.4.7",
"cors": "^2.8.6",
"dotenv": "^17.4.2",
"effect": "^3.22.2",
"empathic": "^2.1.0",
- "express": "^5.2.1",
- "express-rate-limit": "^8.7.0",
+ "express": "^5.3.0",
+ "express-rate-limit": "^8.7.4",
"fast-check": "^4.10.2",
"helmet": "^8.3.0",
+ "ioredis": "^5.11.1",
"jiti": "^2.7.0",
"jsonwebtoken": "^9.0.3",
- "livekit-server-sdk": "^2.19.1",
- "multer": "^2.4.0",
- "nodemailer": "^10.0.11",
+ "livekit-server-sdk": "^2.20.0",
+ "multer": "^2.5.0",
+ "nodemailer": "^10.6.0",
"pathe": "^2.0.3",
- "pg": "^8.23.0",
- "pino": "^10.3.1",
+ "pg": "^8.23.1",
+ "pino": "^10.4.0",
"pngjs": "^7.0.0",
"prom-client": "^15.1.3",
"pure-rand": "^8.4.2",
+ "rate-limit-redis": "^6.0.2",
"unzipper": "^0.12.5",
- "zod": "^4.6.4"
+ "zod": "^4.6.6"
},
"devDependencies": {
+ "@livekit/rtc-node": "^1.2.2",
+ "@playwright/test": "^1.65.1",
"@types/compression": "^1.8.1",
"@types/cookie-parser": "^1.4.10",
"@types/cors": "^2.8.19",
@@ -63,16 +72,17 @@
"@types/express": "^5.0.6",
"@types/jsonwebtoken": "^9.0.10",
"@types/multer": "^2.3.0",
- "@types/node": "^26.6.2",
+ "@types/node": "^26.6.6",
"@types/nodemailer": "^8.0.2",
"@types/pg": "^8.21.0",
"@types/pngjs": "^6.0.5",
"@types/supertest": "^7.2.1",
- "prisma": "^7.10.0",
- "supertest": "^7.3.0",
+ "jszip": "^3.10.2",
+ "prisma": "^7.10.1",
+ "supertest": "^7.3.2",
"tsx": "^4.23.15",
"typescript": "^6.0.3",
- "vitest": "^5.0.2"
+ "vitest": "^5.1.0"
},
"prisma": {
"seed": "tsx prisma/seed.ts"
diff --git a/apps/server/prisma/migrations/20261106120000_invite_lifecycle/migration.sql b/apps/server/prisma/migrations/20261106120000_invite_lifecycle/migration.sql
new file mode 100644
index 00000000..57e73ddf
--- /dev/null
+++ b/apps/server/prisma/migrations/20261106120000_invite_lifecycle/migration.sql
@@ -0,0 +1,6 @@
+ALTER TABLE "Invite" ADD COLUMN "expiresAt" TIMESTAMP(3);
+ALTER TABLE "Invite" ADD COLUMN "lastSentAt" TIMESTAMP(3);
+ALTER TABLE "Invite" ADD COLUMN "sendCount" INTEGER NOT NULL DEFAULT 0;
+ALTER TABLE "Invite" ADD COLUMN "lastSendError" TEXT;
+-- Backfill: open invites get the regular 7-day lifetime from now on; accepted ones stay NULL.
+UPDATE "Invite" SET "expiresAt" = now() + interval '7 days' WHERE "usedAt" IS NULL;
diff --git a/apps/server/prisma/migrations/20261107000000_add_tenant_deletion_journal/migration.sql b/apps/server/prisma/migrations/20261107000000_add_tenant_deletion_journal/migration.sql
new file mode 100644
index 00000000..441fbde4
--- /dev/null
+++ b/apps/server/prisma/migrations/20261107000000_add_tenant_deletion_journal/migration.sql
@@ -0,0 +1,71 @@
+-- CreateEnum
+CREATE TYPE "DeletionJournalStatus" AS ENUM ('blocked', 'requested', 'db_deleted', 'cleanup_pending', 'completed');
+
+-- CreateEnum
+CREATE TYPE "DeletionTaskStatus" AS ENUM ('pending', 'leased', 'retry', 'manual_required', 'done', 'failed');
+
+-- CreateTable
+CREATE TABLE "DeletionJournal" (
+ "id" TEXT NOT NULL,
+ "idempotencyKey" TEXT NOT NULL,
+ "generation" BIGSERIAL NOT NULL,
+ "scope" TEXT NOT NULL,
+ "tenantRef" TEXT,
+ "accountRefs" TEXT[] DEFAULT ARRAY[]::TEXT[],
+ "objectRefs" TEXT[] DEFAULT ARRAY[]::TEXT[],
+ "policyVersion" TEXT NOT NULL,
+ "requestedAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
+ "dbDeletedAt" TIMESTAMP(3),
+ "accessStatus" VARCHAR(64) NOT NULL DEFAULT 'pending',
+ "cleanupStatus" VARCHAR(64) NOT NULL DEFAULT 'pending',
+ "status" "DeletionJournalStatus" NOT NULL DEFAULT 'requested',
+ "completedAt" TIMESTAMP(3),
+ "journalUntil" TIMESTAMP(3) NOT NULL,
+ "lastErrorCode" VARCHAR(64),
+
+ CONSTRAINT "DeletionJournal_pkey" PRIMARY KEY ("id")
+);
+
+-- CreateTable
+CREATE TABLE "DeletionTask" (
+ "id" TEXT NOT NULL,
+ "journalId" TEXT NOT NULL,
+ "kind" VARCHAR(64) NOT NULL,
+ "targetSystem" VARCHAR(64) NOT NULL,
+ "objectId" TEXT NOT NULL,
+ "objectGeneration" TEXT NOT NULL,
+ "storageKey" TEXT,
+ "dedupeKey" TEXT NOT NULL,
+ "status" "DeletionTaskStatus" NOT NULL DEFAULT 'pending',
+ "attempts" INTEGER NOT NULL DEFAULT 0,
+ "nextAttemptAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
+ "leaseToken" TEXT,
+ "leaseUntil" TIMESTAMP(3),
+ "lastErrorCode" VARCHAR(64),
+ "completedAt" TIMESTAMP(3),
+ "receiptCode" VARCHAR(64),
+
+ CONSTRAINT "DeletionTask_pkey" PRIMARY KEY ("id")
+);
+
+-- CreateIndex
+CREATE UNIQUE INDEX "DeletionJournal_idempotencyKey_key" ON "DeletionJournal"("idempotencyKey");
+
+-- CreateIndex
+CREATE UNIQUE INDEX "DeletionJournal_generation_key" ON "DeletionJournal"("generation");
+
+-- CreateIndex
+CREATE INDEX "DeletionJournal_status_journalUntil_idx" ON "DeletionJournal"("status", "journalUntil");
+
+-- CreateIndex
+CREATE UNIQUE INDEX "DeletionTask_dedupeKey_key" ON "DeletionTask"("dedupeKey");
+
+-- CreateIndex
+CREATE INDEX "DeletionTask_journalId_idx" ON "DeletionTask"("journalId");
+
+-- CreateIndex
+CREATE INDEX "DeletionTask_status_nextAttemptAt_idx" ON "DeletionTask"("status", "nextAttemptAt");
+
+-- AddForeignKey
+ALTER TABLE "DeletionTask" ADD CONSTRAINT "DeletionTask_journalId_fkey" FOREIGN KEY ("journalId") REFERENCES "DeletionJournal"("id") ON DELETE RESTRICT ON UPDATE RESTRICT;
+
diff --git a/apps/server/prisma/migrations/20261109080000_add_email_verification_intents/migration.sql b/apps/server/prisma/migrations/20261109080000_add_email_verification_intents/migration.sql
new file mode 100644
index 00000000..d77784d9
--- /dev/null
+++ b/apps/server/prisma/migrations/20261109080000_add_email_verification_intents/migration.sql
@@ -0,0 +1,12 @@
+ALTER TABLE "EmailVerification"
+ ADD COLUMN "purpose" TEXT NOT NULL DEFAULT 'verify',
+ ADD COLUMN "sourceEmail" TEXT,
+ ADD COLUMN "inviteId" TEXT,
+ ADD COLUMN "readyAt" TIMESTAMP(3);
+
+-- Do not reinterpret legacy raw values as new proof of mailbox ownership.
+UPDATE "EmailVerification" SET "expiresAt" = LEAST("expiresAt", CURRENT_TIMESTAMP)
+WHERE "usedAt" IS NULL;
+
+ALTER TABLE "EmailVerification" ADD CONSTRAINT "EmailVerification_inviteId_fkey"
+ FOREIGN KEY ("inviteId") REFERENCES "Invite"("id") ON DELETE CASCADE ON UPDATE CASCADE;
diff --git a/apps/server/prisma/migrations/20261109080001_gate_unverified_invite_memberships/migration.sql b/apps/server/prisma/migrations/20261109080001_gate_unverified_invite_memberships/migration.sql
new file mode 100644
index 00000000..4b035bea
--- /dev/null
+++ b/apps/server/prisma/migrations/20261109080001_gate_unverified_invite_memberships/migration.sql
@@ -0,0 +1,10 @@
+ALTER TABLE "Membership" ADD COLUMN "inviteVerificationRequired" BOOLEAN NOT NULL DEFAULT false;
+
+-- Gate only legacy memberships demonstrably created through an invitation.
+UPDATE "Membership" AS m SET "inviteVerificationRequired" = true
+FROM "User" AS u
+WHERE m."userId" = u."id" AND u."emailVerifiedAt" IS NULL
+ AND EXISTS (
+ SELECT 1 FROM "Invite" AS i
+ WHERE i."usedById" = u."id" AND i."tenantId" = m."tenantId" AND i."usedAt" IS NOT NULL
+ );
diff --git a/apps/server/prisma/migrations/20261116220000_add_auth_events/migration.sql b/apps/server/prisma/migrations/20261116220000_add_auth_events/migration.sql
new file mode 100644
index 00000000..1286037f
--- /dev/null
+++ b/apps/server/prisma/migrations/20261116220000_add_auth_events/migration.sql
@@ -0,0 +1,27 @@
+-- AlterTable
+ALTER TABLE "Membership" ADD COLUMN "lastLoginAt" TIMESTAMP(3);
+
+-- AlterTable
+ALTER TABLE "User" ADD COLUMN "lastLoginAt" TIMESTAMP(3);
+
+-- CreateTable
+CREATE TABLE "AuthEvent" (
+ "id" TEXT NOT NULL,
+ "userId" TEXT,
+ "tenantId" TEXT,
+ "type" TEXT NOT NULL,
+ "success" BOOLEAN NOT NULL,
+ "ipAddress" TEXT,
+ "userAgent" TEXT,
+ "emailHmac" TEXT,
+ "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
+
+ CONSTRAINT "AuthEvent_pkey" PRIMARY KEY ("id")
+);
+
+-- CreateIndex
+CREATE INDEX "AuthEvent_userId_createdAt_idx" ON "AuthEvent"("userId", "createdAt");
+
+-- CreateIndex
+CREATE INDEX "AuthEvent_createdAt_idx" ON "AuthEvent"("createdAt");
+
diff --git a/apps/server/prisma/migrations/20261117090000_add_asset_pack_generation/migration.sql b/apps/server/prisma/migrations/20261117090000_add_asset_pack_generation/migration.sql
new file mode 100644
index 00000000..69cb68ca
--- /dev/null
+++ b/apps/server/prisma/migrations/20261117090000_add_asset_pack_generation/migration.sql
@@ -0,0 +1,5 @@
+-- Nullable pointer to the active asset pack generation. NULL means a
+-- legacy pack whose files live directly under the pack directory. Additive
+-- only: no backfill, no default, existing rows stay NULL by design.
+
+ALTER TABLE "AssetPack" ADD COLUMN "currentGeneration" TEXT;
diff --git a/apps/server/prisma/migrations/20261117090000_unique_open_invite/migration.sql b/apps/server/prisma/migrations/20261117090000_unique_open_invite/migration.sql
new file mode 100644
index 00000000..6a44350a
--- /dev/null
+++ b/apps/server/prisma/migrations/20261117090000_unique_open_invite/migration.sql
@@ -0,0 +1,23 @@
+-- The partial unique index below exists only in SQL because the Prisma
+-- schema language cannot express a unique index with a WHERE clause.
+-- It guarantees at most one open (unused) invite per tenant and email.
+
+-- Keep the newest open invite per (tenantId, email) and delete older open
+-- duplicates. EmailVerification rows of deleted invites are removed through
+-- their ON DELETE CASCADE foreign key.
+DELETE FROM "Invite" AS older
+USING (
+ SELECT
+ "id",
+ ROW_NUMBER() OVER (
+ PARTITION BY "tenantId", "email"
+ ORDER BY "createdAt" DESC, "id" DESC
+ ) AS position
+ FROM "Invite"
+ WHERE "usedAt" IS NULL AND "email" IS NOT NULL
+) AS ranked
+WHERE older."id" = ranked."id" AND ranked.position > 1;
+
+CREATE UNIQUE INDEX "Invite_open_tenantId_email_key"
+ ON "Invite" ("tenantId", "email")
+ WHERE "usedAt" IS NULL AND "email" IS NOT NULL;
diff --git a/apps/server/prisma/migrations/20261117090100_hash_invite_codes/migration.sql b/apps/server/prisma/migrations/20261117090100_hash_invite_codes/migration.sql
new file mode 100644
index 00000000..6f44549d
--- /dev/null
+++ b/apps/server/prisma/migrations/20261117090100_hash_invite_codes/migration.sql
@@ -0,0 +1,6 @@
+-- Invite codes are no longer stored in plaintext: the "code" column now
+-- holds the SHA-256 hex of the raw invite code, and lookups hash the
+-- presented code before comparing. Rewriting the existing values in place
+-- keeps invitation links that were already sent valid, because the raw code
+-- in such a link hashes to the value stored by this update.
+UPDATE "Invite" SET "code" = encode(sha256(convert_to("code", 'UTF8')), 'hex');
diff --git a/apps/server/prisma/migrations/20261117100000_add_avatarpack_archived/migration.sql b/apps/server/prisma/migrations/20261117100000_add_avatarpack_archived/migration.sql
new file mode 100644
index 00000000..df73386a
--- /dev/null
+++ b/apps/server/prisma/migrations/20261117100000_add_avatarpack_archived/migration.sql
@@ -0,0 +1,9 @@
+-- Archiving hides an AvatarPack from picker/registry collection endpoints while
+-- keeping the row, files and every already-selected avatar intact. Direct pack
+-- lookups and wear/resolve reads deliberately remain available.
+--
+-- The default makes this additive migration safe for existing installations:
+-- all current packs remain visible until an internal platform owner explicitly
+-- archives them.
+
+ALTER TABLE "AvatarPack" ADD COLUMN "archived" BOOLEAN NOT NULL DEFAULT false;
diff --git a/apps/server/prisma/migrations/20261117170000_add_api_token_scope/migration.sql b/apps/server/prisma/migrations/20261117170000_add_api_token_scope/migration.sql
new file mode 100644
index 00000000..b4c0c9be
--- /dev/null
+++ b/apps/server/prisma/migrations/20261117170000_add_api_token_scope/migration.sql
@@ -0,0 +1,4 @@
+-- Existing tokens keep full access: backfill them as write, then make read the default for new tokens.
+CREATE TYPE "ApiTokenScope" AS ENUM ('read', 'write');
+ALTER TABLE "ApiToken" ADD COLUMN "scope" "ApiTokenScope" NOT NULL DEFAULT 'write';
+ALTER TABLE "ApiToken" ALTER COLUMN "scope" SET DEFAULT 'read';
diff --git a/apps/server/prisma/schema.prisma b/apps/server/prisma/schema.prisma
index babb2449..e54d9060 100644
--- a/apps/server/prisma/schema.prisma
+++ b/apps/server/prisma/schema.prisma
@@ -75,6 +75,8 @@ model Membership {
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
guestToken GuestToken?
+ inviteVerificationRequired Boolean @default(false)
+ lastLoginAt DateTime?
@@unique([tenantId, userId])
}
@@ -100,6 +102,7 @@ model User {
updatedAt DateTime @updatedAt
onboardingCompleted Boolean @default(false)
locale String @default("de")
+ lastLoginAt DateTime?
presences Presence[]
passwordResets PasswordReset[]
emailVerifications EmailVerification[]
@@ -109,17 +112,26 @@ model User {
customAvatar CustomAvatar?
}
+// A partial unique index on (tenantId, email) for open invites lives only in
+// migration 20261117090000_unique_open_invite, because Prisma cannot express
+// a unique index with a WHERE clause.
model Invite {
id String @id @default(cuid())
+ // stores the SHA-256 hex of the invite code
code String @unique
email String?
createdAt DateTime @default(now())
+ expiresAt DateTime?
+ lastSentAt DateTime?
+ sendCount Int @default(0)
+ lastSendError String?
createdBy String?
usedAt DateTime?
usedById String?
tenant Tenant @relation(fields: [tenantId], references: [id])
tenantId String
role Role @default(member)
+ emailVerifications EmailVerification[]
}
model PasswordReset {
@@ -138,16 +150,28 @@ model EmailVerification {
user User @relation(fields: [userId], references: [id])
userId String
email String
+ purpose String @default("verify")
+ sourceEmail String?
+ invite Invite? @relation(fields: [inviteId], references: [id], onDelete: Cascade)
+ inviteId String?
+ readyAt DateTime?
usedAt DateTime?
expiresAt DateTime
createdAt DateTime @default(now())
}
+enum ApiTokenScope {
+ read
+ write
+}
+
model ApiToken {
id String @id @default(cuid())
user User @relation(fields: [userId], references: [id])
userId String
name String?
+ // read tokens may only use safe methods (GET, HEAD, OPTIONS); write tokens may also change data; neither reaches account, token management or platform administration routes.
+ scope ApiTokenScope @default(read)
hash String @unique
lastUsedAt DateTime?
createdAt DateTime @default(now())
@@ -168,6 +192,21 @@ model Session {
@@index([expiresAt])
}
+model AuthEvent {
+ id String @id @default(cuid())
+ userId String?
+ tenantId String?
+ type String
+ success Boolean
+ ipAddress String?
+ userAgent String?
+ emailHmac String?
+ createdAt DateTime @default(now())
+
+ @@index([userId, createdAt])
+ @@index([createdAt])
+}
+
model Map {
id String @id @default(cuid())
tenant Tenant @relation(fields: [tenantId], references: [id])
@@ -311,6 +350,9 @@ model AssetPack {
objects Json
autotiles Json @default("[]")
archived Boolean @default(false)
+ // Active generation id. NULL = legacy pack whose files live
+ // directly under the pack directory; no backfill by design.
+ currentGeneration String?
tenantId String?
tenant Tenant? @relation(fields: [tenantId], references: [id], onDelete: Cascade)
createdAt DateTime @default(now())
@@ -349,6 +391,17 @@ model AssetPack {
// is SetNull, which would PUBLISH a private pack to the whole platform the
// moment its owning tenant is deleted — a fail-open leak. Restrict would block
// tenant offboarding instead. Cascade is the only fail-closed option.
+//
+// `archived` is independent of ownership. It removes a pack from collection
+// endpoints and therefore from every avatar picker/registry list, including the
+// platform owner's list. Direct lookups stay available, as do wear/resolve
+// reads used to preserve existing selections. Archiving is reversible and never
+// deletes the pack row or its files.
+//
+// The single ownership exception is the platform super-admin (owner of the
+// `internal` tenant), which can administer every pack. The picker list still
+// excludes archived packs for this caller; direct lookup and the archive write
+// route keep them manageable.
model AvatarPack {
id Int @id @default(autoincrement())
uuid String @unique
@@ -358,6 +411,7 @@ model AvatarPack {
version String
type String @default("full")
avatars Json
+ archived Boolean @default(false)
tenantId String?
tenant Tenant? @relation(fields: [tenantId], references: [id], onDelete: Cascade)
createdAt DateTime @default(now())
@@ -577,5 +631,68 @@ model NpcMediaFile {
@@index([npcId])
}
+enum DeletionJournalStatus {
+ blocked
+ requested
+ db_deleted
+ cleanup_pending
+ completed
+}
+
+enum DeletionTaskStatus {
+ pending
+ leased
+ retry
+ manual_required
+ done
+ failed
+}
+
+// References intentionally survive removal of tenant and user rows.
+model DeletionJournal {
+ id String @id @default(cuid())
+ idempotencyKey String @unique
+ generation BigInt @unique @default(autoincrement())
+ scope String
+ tenantRef String?
+ accountRefs String[] @default([])
+ objectRefs String[] @default([])
+ policyVersion String
+ requestedAt DateTime @default(now())
+ dbDeletedAt DateTime?
+ accessStatus String @default("pending") @db.VarChar(64)
+ cleanupStatus String @default("pending") @db.VarChar(64)
+ status DeletionJournalStatus @default(requested)
+ completedAt DateTime?
+ journalUntil DateTime
+ lastErrorCode String? @db.VarChar(64)
+ tasks DeletionTask[]
+
+ @@index([status, journalUntil])
+}
+
+model DeletionTask {
+ id String @id @default(cuid())
+ journalId String
+ journal DeletionJournal @relation(fields: [journalId], references: [id], onDelete: Restrict, onUpdate: Restrict)
+ kind String @db.VarChar(64)
+ targetSystem String @db.VarChar(64)
+ objectId String
+ objectGeneration String
+ storageKey String?
+ dedupeKey String @unique
+ status DeletionTaskStatus @default(pending)
+ attempts Int @default(0)
+ nextAttemptAt DateTime @default(now())
+ leaseToken String?
+ leaseUntil DateTime?
+ lastErrorCode String? @db.VarChar(64)
+ completedAt DateTime?
+ receiptCode String? @db.VarChar(64)
+
+ @@index([journalId])
+ @@index([status, nextAttemptAt])
+}
+
// Optional commercial modules can extend this schema at build time via
-// their own tooling. See docs/enterprise.md.
+// their own tooling.
diff --git a/apps/server/prisma/seed-data/default-avatars/atelier-v1.json b/apps/server/prisma/seed-data/default-avatars/atelier-v1.json
index 5ac1a114..e31ddc38 100644
--- a/apps/server/prisma/seed-data/default-avatars/atelier-v1.json
+++ b/apps/server/prisma/seed-data/default-avatars/atelier-v1.json
@@ -9,8 +9,8 @@
"key": "business_man",
"displayName": "Business Man",
"type": "full",
- "spriteUrl": "/assets/sprites/atelier-v1/business_man.d1d7a78d7e68.png",
- "sha256": "d1d7a78d7e68bd3c34e9cee921a6ba6d1d21ab220572ba30148c3bc6372c8d0b",
+ "spriteUrl": "/assets/sprites/atelier-v1/business_man.36311df39e9f.png",
+ "sha256": "36311df39e9f900d23b046476073b66d8d22cf64fe045c420f69c44da78a0956",
"frameWidth": 32,
"frameHeight": 32,
"columns": 4,
@@ -52,8 +52,8 @@
"key": "business_woman",
"displayName": "Business Woman",
"type": "full",
- "spriteUrl": "/assets/sprites/atelier-v1/business_woman.f01546e80735.png",
- "sha256": "f01546e80735e2cfd1996e59dc21bc866373ab3221078e392c6f62054a0b2013",
+ "spriteUrl": "/assets/sprites/atelier-v1/business_woman.45dca8a84981.png",
+ "sha256": "45dca8a84981c71422488e8bee680388ac497139af607471de111ecb831fd4a7",
"frameWidth": 32,
"frameHeight": 32,
"columns": 4,
@@ -95,8 +95,8 @@
"key": "casual_woman",
"displayName": "Casual Woman",
"type": "full",
- "spriteUrl": "/assets/sprites/atelier-v1/casual_woman.348f4f49cbd0.png",
- "sha256": "348f4f49cbd02ae4b9671bc3453f83cc9d79aa217d8651624da3068f88951068",
+ "spriteUrl": "/assets/sprites/atelier-v1/casual_woman.ab39c8c31f0c.png",
+ "sha256": "ab39c8c31f0c3785d2489b99baca1b46a76493ddae7875afa76a518729eeaf3d",
"frameWidth": 32,
"frameHeight": 32,
"columns": 4,
@@ -138,8 +138,8 @@
"key": "dev_hoodie",
"displayName": "Developer",
"type": "full",
- "spriteUrl": "/assets/sprites/atelier-v1/dev_hoodie.8b424e037c79.png",
- "sha256": "8b424e037c79d1072fd650ce2fec7771068f69dd7ecdbf0668312de16a8b5579",
+ "spriteUrl": "/assets/sprites/atelier-v1/dev_hoodie.d4774f6a8b1a.png",
+ "sha256": "d4774f6a8b1a73a0775023dadc20b06173085b304904504ef8784f7710866114",
"frameWidth": 32,
"frameHeight": 32,
"columns": 4,
@@ -181,8 +181,8 @@
"key": "manager_woman",
"displayName": "Manager",
"type": "full",
- "spriteUrl": "/assets/sprites/atelier-v1/manager_woman.af80ed75d4ab.png",
- "sha256": "af80ed75d4abf5fd56a4718f1001dc578a69ca6b9ab8c89caf9d4ea463541aa0",
+ "spriteUrl": "/assets/sprites/atelier-v1/manager_woman.df14c70aed86.png",
+ "sha256": "df14c70aed863a9c675aef1f5b3af288634eefad8d4b681b3b1dd9fbab1b68c2",
"frameWidth": 32,
"frameHeight": 32,
"columns": 4,
@@ -224,8 +224,8 @@
"key": "suit_man",
"displayName": "Suit Man",
"type": "full",
- "spriteUrl": "/assets/sprites/atelier-v1/suit_man.4dc2fcec15cd.png",
- "sha256": "4dc2fcec15cd6bdee06b7c8e7708dd93b6c1c00816487360c72e1ce198bbbe8a",
+ "spriteUrl": "/assets/sprites/atelier-v1/suit_man.6594b26689d8.png",
+ "sha256": "6594b26689d8de3f1ea86597905e9dce1632e55dafae35a6cfc19b1d9d2373e1",
"frameWidth": 32,
"frameHeight": 32,
"columns": 4,
diff --git a/apps/server/prisma/seed.ts b/apps/server/prisma/seed.ts
index c8c07dbc..fa67cd78 100644
--- a/apps/server/prisma/seed.ts
+++ b/apps/server/prisma/seed.ts
@@ -1,13 +1,19 @@
+import crypto from 'crypto';
import fs from 'fs';
import path from 'path';
import { fileURLToPath } from 'url';
import { PrismaClient } from '../src/generated/prisma/index.js';
import { PrismaPg } from '@prisma/adapter-pg';
-import bcrypt from 'bcryptjs';
+import { applySeedAdminCredentials, enforceSeedAdminCredentials } from '../src/ops/seedAdminCredentials.js';
import { importTmjIntoMap } from '../src/scripts/importMapV2.lib.js';
import { resolveTemplateTenantSlug } from '../src/services/templateTenant.js';
import { ATELIER_STANDARD_MAP_FILE, ATELIER_STANDARD_MAP_NAME } from '../src/services/atelierStandardMap.js';
import { ATELIER_PACK_UUID, loadAtelierProductData } from './atelierCatalog.js';
+import { acquirePackAdvisoryLock } from '../src/api/utils/advisoryLocks.js';
+
+// Production seed-admin policy: fail closed on missing or public-template
+// credentials before the driver adapter is constructed and before any write.
+enforceSeedAdminCredentials(process.env);
// Prisma 7 requires a driver-adapter. The seed runs via `prisma db seed`
// (outside the application's normal entrypoint) so we construct one here.
@@ -123,25 +129,7 @@ async function main() {
update: {},
});
- // Seed Root Admin (env-configurable)
- const adminEmail = process.env.SEED_ADMIN_EMAIL || 'admin@meetropolis.local';
- const adminPass = process.env.SEED_ADMIN_PASSWORD || 'admin123';
- const adminName = process.env.SEED_ADMIN_NAME || 'Root Admin';
-
- let admin = await prisma.user.findUnique({ where: { email: adminEmail } });
- const hash = await bcrypt.hash(adminPass, 10);
- if (!admin) {
- admin = await prisma.user.create({
- data: { email: adminEmail, name: adminName, passwordHash: hash, emailVerifiedAt: new Date() },
- });
-
- console.log('Seeded admin user:', adminEmail);
- } else {
- // Update password hash (so seed always sets the expected password)
- admin = await prisma.user.update({ where: { email: adminEmail }, data: { passwordHash: hash } });
-
- console.log('Admin user exists, password updated:', adminEmail);
- }
+ const admin = await applySeedAdminCredentials(prisma, process.env);
// Ensure memberships
if (admin) {
@@ -308,56 +296,62 @@ async function main() {
'Check that the image build copies apps/web/public into the seed stage.',
);
}
- await prisma.assetPack.upsert({
- where: { uuid: 'pixel-agents-furniture' },
- create: {
- uuid: 'pixel-agents-furniture',
- name: 'Pixel Agents Furniture',
- description:
- 'Built-in office furniture set snapshotted from pablodelucca/pixel-agents (MIT). See THIRD_PARTY_LICENSES/MIT-pixel-agents.txt and tools/map-builder/ for the build pipeline.',
- author: 'pablodelucca (snapshotted by Meetropolis)',
- version: '1.0.0',
- terrain: [],
- structures: [],
- objects: furnitureItems,
- autotiles: [],
- },
- update: {
- version: '1.0.0',
- // Refresh the shipped object list — but never overwrite a populated pack
- // with an empty one. If the asset directory is absent (a build stage that
- // does not copy apps/web/public), an unconditional write would wipe every
- // furniture entry on the very next deploy and orphan all placed objects.
- ...(furnitureItems.length > 0 ? { objects: furnitureItems } : {}),
- },
+ await prisma.$transaction(async (tx) => {
+ await acquirePackAdvisoryLock(tx, 'pixel-agents-furniture');
+ await tx.assetPack.upsert({
+ where: { uuid: 'pixel-agents-furniture' },
+ create: {
+ uuid: 'pixel-agents-furniture',
+ name: 'Pixel Agents Furniture',
+ description:
+ 'Built-in office furniture set snapshotted from pablodelucca/pixel-agents (MIT). See THIRD_PARTY_LICENSES/MIT-pixel-agents.txt and tools/map-builder/ for the build pipeline.',
+ author: 'pablodelucca (snapshotted by Meetropolis)',
+ version: '1.0.0',
+ terrain: [],
+ structures: [],
+ objects: furnitureItems,
+ autotiles: [],
+ },
+ update: {
+ version: '1.0.0',
+ // Refresh the shipped object list — but never overwrite a populated pack
+ // with an empty one. If the asset directory is absent (a build stage that
+ // does not copy apps/web/public), an unconditional write would wipe every
+ // furniture entry on the very next deploy and orphan all placed objects.
+ ...(furnitureItems.length > 0 ? { objects: furnitureItems } : {}),
+ },
+ });
});
// Atelier v1 is shipped catalog content. Existing operator customizations
// remain untouched except for the one-time A28 autotile backfill: the old
// seed intentionally wrote an empty list while walls_auto identities were
// unstable, so an empty list is the unambiguous pre-A28 state.
- const existingAtelierPack = await prisma.assetPack.findUnique({ where: { uuid: ATELIER_PACK_UUID } });
const { catalog, pack } = loadAtelierProductData(repoRoot);
- if (!existingAtelierPack) {
- await prisma.assetPack.create({
- data: {
- uuid: ATELIER_PACK_UUID,
- name: `${catalog.palette.name} (Atelier v1)`,
- description: 'Eigene Pixelgrafiken der Atelier-Generation v1 für helle Bürowelten.',
- author: pack.author,
- version: catalog.palette.packVersion,
- terrain: pack.terrain,
- structures: pack.structures,
- objects: pack.objects,
- autotiles: pack.autotiles,
- },
- });
- } else if (Array.isArray(existingAtelierPack.autotiles) && existingAtelierPack.autotiles.length === 0) {
- await prisma.assetPack.update({
- where: { uuid: ATELIER_PACK_UUID },
- data: { autotiles: pack.autotiles },
- });
- }
+ await prisma.$transaction(async (tx) => {
+ await acquirePackAdvisoryLock(tx, ATELIER_PACK_UUID);
+ const current = await tx.assetPack.findUnique({ where: { uuid: ATELIER_PACK_UUID } });
+ if (!current) {
+ await tx.assetPack.create({
+ data: {
+ uuid: ATELIER_PACK_UUID,
+ name: `${catalog.palette.name} (Atelier v1)`,
+ description: 'Eigene Pixelgrafiken der Atelier-Generation v1 für helle Bürowelten.',
+ author: pack.author,
+ version: catalog.palette.packVersion,
+ terrain: pack.terrain,
+ structures: pack.structures,
+ objects: pack.objects,
+ autotiles: pack.autotiles,
+ },
+ });
+ } else if (Array.isArray(current.autotiles) && current.autotiles.length === 0) {
+ await tx.assetPack.update({
+ where: { uuid: ATELIER_PACK_UUID },
+ data: { autotiles: pack.autotiles },
+ });
+ }
+ });
// ---------------------------------------------------------------------
// Starter map for the `default` tenant. Without a Map row the frontend's
@@ -436,14 +430,15 @@ async function main() {
}
// Create a default invite (for onboarding teammates)
- const existingInvite = await prisma.invite.findFirst({ where: { email: adminEmail, tenantId: def.id } });
+ const existingInvite = await prisma.invite.findFirst({ where: { email: admin.email, tenantId: def.id } });
if (!existingInvite) {
const code = Math.random().toString(36).slice(2, 10) + Math.random().toString(36).slice(2, 10);
+ const codeHash = crypto.createHash('sha256').update(code).digest('hex');
await prisma.invite.create({
- data: { code, email: adminEmail, createdBy: admin.id, tenantId: def.id, role: 'admin' as any },
+ data: { code: codeHash, email: admin.email, createdBy: admin.id, tenantId: def.id, role: 'admin' as any },
});
- console.log('Seeded invite for admin email (can be shared to teammates):', code);
+ console.log('Seeded invite for admin email');
}
}
diff --git a/apps/server/src/adminLoader.ts b/apps/server/src/adminLoader.ts
index f2d3be6d..fe0ceb4d 100644
--- a/apps/server/src/adminLoader.ts
+++ b/apps/server/src/adminLoader.ts
@@ -1,17 +1,47 @@
import type { Application, Request, Response } from 'express';
-import type { PrismaClient } from './generated/prisma/index.js';
+import type { Prisma, PrismaClient } from './generated/prisma/index.js';
+import type {
+ TenantDeletionContext,
+ TenantDeletionOptions,
+ TenantDeletionPlanInput,
+ TenantDeletionPreparationContext,
+ TenantDeletionTaskPlan,
+} from './services/tenantDeletionContract.js';
+import type { EnterpriseExportResult, TenantExportSink } from './services/tenantExport/types.js';
+import type { AuthEventInput } from './services/authEvents.js';
+import type { PublicAdsConfig } from './api/adsPublicConfig.js';
+import {
+ TENANT_DELETION_PROTOCOL,
+ TenantDeletionContractError,
+ TenantDeletionJournalUnavailableError,
+ assertTenantDeletionProtocol,
+} from './services/tenantDeletionContract.js';
import { z } from 'zod';
import { logger } from './logger.js';
+export {
+ TENANT_DELETION_PROTOCOL,
+ TenantDeletionContractError,
+ TenantDeletionJournalUnavailableError,
+ assertTenantDeletionProtocol,
+};
+export type {
+ TenantDeletionContext,
+ TenantDeletionOptions,
+ TenantDeletionPlanInput,
+ TenantDeletionPreparationContext,
+ TenantDeletionTaskPlan,
+};
+
/**
* Expected `version` of the shared `@meetropolis/billing` module.
*
* The enterprise admin routes ship inside the SAME closed-source
* `@meetropolis/billing` package as the billing routes (see `billingLoader.ts`).
* That package exposes a single `version` const, so this literal MUST equal
- * `EXPECTED_BILLING_MODULE_VERSION` and evolve in lockstep. Bumping one loader
- * without the other makes `adminEnterpriseSchema.parse()` throw, which silently
- * drops every admin route on a full enterprise deployment.
+ * `EXPECTED_BILLING_MODULE_VERSION` and evolve in lockstep. A version mismatch
+ * no longer drops every admin route silently: the loader aborts startup with a
+ * clear error naming the broken package and the expected loader contract.
*
* Raised from 1 to 2 together with the package, when the billing loader
* interface lost the Stripe-typed config slot and gained
@@ -92,6 +122,10 @@ export interface AdminEnterpriseModule {
userId: string;
tenantId: string;
}) => Promise<{ token: string; sessionId: string; expiresAt: Date }>;
+ // Optional: records one authentication event (see AuthEventInput) on the
+ // host, so the signup can log its login without importing OSS internals.
+ // When absent, no event is recorded.
+ recordAuthEvent?: (input: AuthEventInput) => Promise;
// Optional: kicks off e-mail verification for a freshly created account.
// The verification machinery is OSS-internal and cannot be imported from
// the closed-source package, so the host injects it. Called detached by
@@ -104,6 +138,17 @@ export interface AdminEnterpriseModule {
// optional config field does not change the module's function surface, so
// it stays within schema version 2 (no version bump required).
isNativeClientRequest?: (req: Request) => boolean;
+ // Optional: resolves the managed tenant-deletion plan for one tenant,
+ // persisting the intent to the file journal first. The host wires a
+ // cached resolver only when a journal directory is configured; without
+ // it the field stays undefined and the route answers 409. Optional
+ // field, no version bump.
+ resolveTenantDeletionPlan?: (
+ tx: Prisma.TransactionClient,
+ input: { tenantId: string; transactionTime: Date },
+ ) => Promise;
+ /** Optional: true while the NPC media folder of a deleted tenant with this slug is not cleared yet. */
+ isTenantSlugReserved?: (slug: string) => Promise;
// Optional: host-callback returning the telemetry activation block for
// GET /public/config ({ enabled, environment }) or null when telemetry is
// off. The enterprise /public/config handler wins over the OSS fallback
@@ -113,6 +158,19 @@ export interface AdminEnterpriseModule {
// an optional config field keeps the function surface unchanged, so no
// schema version bump is required.
getTelemetryPublicConfig?: () => { enabled: boolean; environment: string } | null;
+ // Optional: host-callback returning the ads consent block for
+ // GET /public/config ({ googleAdsId, signupConversionLabel, consentMode })
+ // or null when ads tracking is off. The enterprise /public/config handler
+ // wins over the OSS fallback (handleOssPublicConfig), so the host injects
+ // this to keep the ads consent block reaching the wire in enterprise
+ // deployments. Undefined (inert) in OSS-only builds; adding an optional
+ // config field keeps the function surface unchanged, so no schema version
+ // bump is required.
+ getAdsPublicConfig?: () => PublicAdsConfig | null;
+ deleteTenantWithMembers: (
+ tenantId: string,
+ options?: TenantDeletionOptions,
+ ) => Promise<{ deletedAccounts: number }>;
},
): void;
@@ -140,6 +198,7 @@ export interface AdminEnterpriseModule {
};
requireSuperAdmin: (req: Request, prisma: PrismaClient) => Promise<{ userId: string } | null>;
normalizeEmail: (email: string) => string;
+ removeMemberFromTenant: (params: { userId: string; tenantId: string }) => Promise<{ accountDeleted: boolean }>;
},
): void;
@@ -177,6 +236,50 @@ export interface AdminEnterpriseModule {
cacheTtlMs?: number;
},
): void;
+
+ /**
+ * Managed deletion of one tenant outside the HTTP route, with the same
+ * guards and journal path as DELETE /admin/tenants/:id. Used by the restore
+ * replay tool. Optional: older enterprise builds do not export it.
+ */
+ deleteManagedTenant?(
+ config: {
+ prisma: PrismaClient;
+ logger: {
+ info(obj: object): void;
+ error(obj: object): void;
+ warn(obj: object): void;
+ };
+ deleteTenantWithMembers: (
+ tenantId: string,
+ options?: TenantDeletionOptions,
+ ) => Promise<{ deletedAccounts: number }>;
+ resolveTenantDeletionPlan?: (
+ tx: Prisma.TransactionClient,
+ input: { tenantId: string; transactionTime: Date },
+ ) => Promise;
+ },
+ id: string,
+ options: { actor: string },
+ ): Promise<{ ok: true } | { ok: false; status: number; error: string }>;
+
+ /**
+ * Codes of preconditions that must hold before a restored database may
+ * serve again; empty when none is open. Optional like deleteManagedTenant.
+ */
+ pendingRestorePreconditions?(): string[];
+
+ /**
+ * Exports the enterprise-owned tables of one tenant into the sink. Used by
+ * the operator tenant export. Optional: older enterprise builds do not
+ * export it, and then the export aborts with `enterprise_export_unavailable`.
+ * Declared as a property so passing it on never loses its receiver.
+ */
+ exportManagedTenant?: (
+ config: { prisma: PrismaClient },
+ tenantId: string,
+ sink: TenantExportSink,
+ ) => Promise;
}
export const adminEnterpriseSchema = z.object({
@@ -190,6 +293,11 @@ export const adminEnterpriseSchema = z.object({
setupPackMarketplaceRoutes: z.function(),
// Optional: older enterprise builds may not ship the desktop update routes.
setupDesktopUpdateRoutes: z.function().optional(),
+ // Optional: restore replay hooks, absent in older enterprise builds.
+ deleteManagedTenant: z.function().optional(),
+ pendingRestorePreconditions: z.function().optional(),
+ // Optional: tenant export hook, absent in older enterprise builds.
+ exportManagedTenant: z.function().optional(),
});
let cached: AdminEnterpriseModule | null = null;
@@ -216,19 +324,25 @@ export async function hasAdminEnterpriseModule(): Promise {
}
}
-/**
- * Loads the optional enterprise admin module if present.
- * Returns null for OSS builds without enterprise features.
- */
-export async function getAdminEnterpriseModule(): Promise {
- if (loadAttempted) return cached;
- loadAttempted = true;
+function isAbsentBillingPackage(error: unknown): boolean {
+ if (!error || typeof error !== 'object') return false;
+ const code = 'code' in error ? error.code : undefined;
+ const message = 'message' in error ? error.message : undefined;
+ if (code !== 'ERR_MODULE_NOT_FOUND' && code !== 'MODULE_NOT_FOUND') return false;
+ return typeof message === 'string' && /Cannot find (?:package|module) ['"]@meetropolis\/billing['"]/.test(message);
+}
+
+const importBillingPackage = (): Promise => import('@meetropolis/billing');
+/** Load and validate the optional module, distinguishing absence from breakage. */
+export async function loadAdminEnterpriseModule(
+ importModule: () => Promise = importBillingPackage,
+): Promise {
try {
- const modUnknown: unknown = await import('@meetropolis/billing');
+ const modUnknown: unknown = await importModule();
const mod = adminEnterpriseSchema.parse(unwrapDefaultExport(modUnknown));
- cached = {
+ const loaded: AdminEnterpriseModule = {
version: EXPECTED_ADMIN_MODULE_VERSION,
setupAdminRoutes: mod.setupAdminRoutes as AdminEnterpriseModule['setupAdminRoutes'],
setupTenantAdminRoutes: mod.setupTenantAdminRoutes as AdminEnterpriseModule['setupTenantAdminRoutes'],
@@ -236,17 +350,44 @@ export async function getAdminEnterpriseModule(): Promise {
+ if (loadAttempted) return cached;
+ const loaded = await loadAdminEnterpriseModule();
+ loadAttempted = true;
+ cached = loaded;
+ return cached;
+}
+
/**
* Get admin enterprise module synchronously (returns null if not loaded yet)
*/
diff --git a/apps/server/src/api.enterpriseDeletionConfig.test.ts b/apps/server/src/api.enterpriseDeletionConfig.test.ts
new file mode 100644
index 00000000..7fc4e1f2
--- /dev/null
+++ b/apps/server/src/api.enterpriseDeletionConfig.test.ts
@@ -0,0 +1,197 @@
+import fs from 'node:fs/promises';
+import os from 'node:os';
+import path from 'node:path';
+import cookieParser from 'cookie-parser';
+import express from 'express';
+import { afterEach, describe, expect, it, vi } from 'vitest';
+
+process.env.JWT_SECRET = process.env.JWT_SECRET || 'test-secret-enterprise-deletion-config';
+process.env.API_TOKEN_PEPPER = process.env.API_TOKEN_PEPPER || 'test-pepper-enterprise-deletion-config';
+
+const { captured, billingFixture } = vi.hoisted(() => {
+ const captured: { config: object | undefined } = { config: undefined };
+ const noop = (): void => undefined;
+ const billingFixture = {
+ version: 3 as const,
+ setupBillingRoutes: noop,
+ installEarlyMiddleware: noop,
+ getTrialStatus: noop,
+ startTrial: noop,
+ getDunningStatus: noop,
+ TRIAL_DAYS: 7,
+ GRACE_PERIOD_DAYS: 7,
+ CANCELLATION_DAYS: 14,
+ setupAdminRoutes: noop,
+ setupTenantAdminRoutes: (_app: unknown, config: object) => {
+ captured.config = config;
+ },
+ setupPricingPlanRoutes: noop,
+ setupTenantUserRoutes: noop,
+ setupPackMarketplaceRoutes: noop,
+ setupDesktopUpdateRoutes: noop,
+ };
+ return { captured, billingFixture };
+});
+
+vi.mock('@meetropolis/billing', () => ({
+ ...billingFixture,
+ default: billingFixture,
+}));
+
+vi.mock('./db.js', () => ({
+ createPrismaClient: () => ({}),
+}));
+
+const { journalResolver } = vi.hoisted(() => ({
+ journalResolver: vi.fn(),
+}));
+
+// The resolver factory is wiring, not the tested logic: it is
+// counted and controllably rejected or resolved.
+vi.mock('./services/tenantDeletionPlanning.js', async (importOriginal) => {
+ const actual = await importOriginal();
+ return { ...actual, createJournalPlanResolver: journalResolver };
+});
+
+// Warm the transform cache: each test re-imports a fresh api.js, and the
+// first cold import of the route graph exceeds the per-test timeout.
+import './api.js';
+
+type ResolvePlan = (tx: unknown, input: { tenantId: string; transactionTime: Date }) => Promise;
+
+interface PlanInput {
+ idempotencyKey: string;
+ policyVersion: string;
+ journalUntil: Date;
+ tasks: unknown[];
+}
+
+function resolveTenantDeletionPlanOf(config: object): unknown {
+ return Reflect.get(config, 'resolveTenantDeletionPlan');
+}
+
+async function captureTenantAdminConfig(): Promise