From ba1504d6e991a8ef60c9f00540180ba7108175db Mon Sep 17 00:00:00 2001 From: Maurice Date: Thu, 8 Oct 2026 15:12:07 +0200 Subject: [PATCH] refactor(server): give every environment variable one config owner Eight registerAs tokens existed while every consumer read the same values through readEnv() instead, so the boot-stable layer the repo rules describe was unused and nothing said which path owned a variable. FORCE_HTTPS, for instance, was frozen by the middleware through the http token and read live by the cookie code at the same time. A variable is now owned by exactly one side. TRUST_PROXY and HSTS_INCLUDE_SUBDOMAINS belong to httpConfig, which buildApp() already injects into the pre-init middleware, and TREK_PLACE_PHOTO_DIR to the new storageConfig, which the storage registry now injects instead of reading it through RuntimeEnvService. Their derive functions moved to boot-derive.ts, which deriveAll() never calls. The six tokens nothing injected are gone: their values are needed before the container exists (config.ts, the database, src/mcp, the SSRF guard) and stay on readEnv(). config-ownership.test.ts records the keys each side reads through a Proxy and fails on a variable read through both, on a token nothing injects and on a variable the schema does not validate. env-reference.test.ts holds server/.env.example to the schema, which had drifted by 34 variables (SMTP, WebAuthn, plugins, MCP session tuning, TREK_MANAGED and others); they are documented now. jwt-verify.ts no longer cites a middleware file that is gone. --- server/.env.example | 46 +++++++- server/CLAUDE.md | 3 +- server/src/app-config/README.md | 34 +++++- server/src/app-config/boot-derive.ts | 39 +++++++ server/src/app-config/derive.ts | 13 ++- server/src/middleware/globalMiddleware.ts | 19 ++-- server/src/nest/README.md | 8 +- server/src/nest/app-config/index.ts | 12 +-- server/src/nest/app-config/tokens.ts | 66 ++++-------- server/src/nest/auth/jwt-verify.ts | 8 +- .../nest/storage/storage-registry.service.ts | 12 ++- server/tests/integration/app-config.test.ts | 22 ++-- .../storage-restore-reload.test.ts | 5 +- .../unit/app-config/config-ownership.test.ts | 101 ++++++++++++++++++ server/tests/unit/app-config/derive.test.ts | 21 ++-- .../unit/app-config/env-reference.test.ts | 55 ++++++++++ .../middleware/globalMiddleware.cors.test.ts | 13 ++- server/tests/unit/nest/app-config.test.ts | 29 +++-- .../storage/storage-admin.service.test.ts | 3 +- .../nest/storage/storage-jobs.service.test.ts | 11 +- .../storage/storage-registry.service.test.ts | 8 +- .../storage/storage-stats.service.test.ts | 3 +- 22 files changed, 389 insertions(+), 142 deletions(-) create mode 100644 server/src/app-config/boot-derive.ts create mode 100644 server/tests/unit/app-config/config-ownership.test.ts create mode 100644 server/tests/unit/app-config/env-reference.test.ts diff --git a/server/.env.example b/server/.env.example index b5d33f49c..cafd6c12a 100644 --- a/server/.env.example +++ b/server/.env.example @@ -41,10 +41,14 @@ OIDC_USERNAME_CLAIM= # Claim a new account's username comes from, e.g. preferred OIDC_DISCOVERY_URL= # Override the auto-constructed OIDC discovery endpoint. Useful for providers (e.g. Authentik) that expose it at a non-standard path. Example: https://auth.example.com/application/o/trek/.well-known/openid-configuration OIDC_SCOPE=openid email profile # Fully overrides the default. Add extra scopes as needed (e.g. add groups if using OIDC_ADMIN_CLAIM) -DEMO_MODE=false # Demo mode - resets data hourly +DEMO_MODE=false # Demo mode: resets data hourly +# DEMO_ADMIN_USER=admin # Username of the admin account a demo instance seeds on its first start. (default: admin) +# DEMO_ADMIN_EMAIL=admin@trek.app # Email of that seeded demo admin. (default: admin@trek.app) +# DEMO_ADMIN_PASS=admin12345 # Initial password of that seeded demo admin. Change it on a public demo. (default: admin12345) # RESTORE_FROM_BACKUP=/app/data/backup.zip # Restore this backup on the first start, before any setup. Ignored once a database exists. # FILE_UPLOAD_LIMIT_MB=50 # Max size (MB) of a file uploaded to a trip, a booking or a note. Videos keep their own 500 MB cap. Raise your reverse proxy's upload limit too. +# BACKUP_MAX_DECOMPRESSED_MB=5120 # Max size (MB) a restore archive may unpack to, on both restore paths: the zip-bomb guard. Raise it if a large backup is refused with "Backup exceeds the maximum decompressed size". (default: 5120) # BACKUP_UPLOAD_LIMIT_MB=500 # Max size (MB) of a backup archive you can upload when restoring. Raise it if your backup exceeds 500 MB. If you sit behind a reverse proxy, raise its upload limit too (e.g. nginx client_max_body_size). # TREK_DB_JOURNAL_MODE=WAL # SQLite journal mode (DELETE, TRUNCATE, PERSIST, MEMORY, WAL, OFF). WAL is fastest and the right choice on local disk. Set DELETE if the data directory lives on network storage (Azure App Service, an SMB/NFS volume on a NAS) — WAL coordinates writers through a shared-memory file that those filesystems do not implement reliably. The mode is stored inside the database file, so it survives a restart; changing this applies on the next boot. @@ -54,6 +58,9 @@ DEMO_MODE=false # Demo mode - resets data hourly # MCP_RATE_LIMIT=300 # Max MCP API requests per user per minute (default: 300) # MCP_MAX_SESSION_PER_USER=20 # Max concurrent MCP sessions per user (default: 20) +# MCP_SESSION_TTL=3600 # Idle timeout of an MCP session in seconds, at most 86400. (default: 3600) +# MCP_SSE_KEEPALIVE=25 # Seconds between keep-alive pings on an open MCP event stream, so a reverse proxy does not cut it. 0 turns the pings off. (default: 25) +# IDEMPOTENCY_TTL_SECONDS=2592000 # How long the server remembers an X-Idempotency-Key. The offline client replays queued changes with their key on reconnect, so keep this longer than the longest time a device stays offline. (default: 2592000, 30 days) # NOMINATIM_URL=https://nominatim.openstreetmap.org # Custom HTTP(S) Nominatim base URL for every geocoding call the server makes: place search, reverse lookup, place details and the Atlas region fill. When set it REPLACES the public service with no fallback, so whatever answers has to speak the Nominatim API (/search, /reverse, /lookup) and hold the coverage you expect. TREK keeps its ~1 request per second spacing whichever instance answers. Unset/blank uses the public default. @@ -63,12 +70,20 @@ DEMO_MODE=false # Demo mode - resets data hourly # TREK_PLACES_ENABLED=false # Whether place search asks the TREK Places API at https://places.liketrek.com: suggestions, the full search, the category buttons on the map, the Road trip search along the route, import geocoding and offline downloads. It is on by default and has no switch in the admin panel, because whether searches leave the instance is a deployment decision. Set false to search the way it did before 4.3.0 (OpenStreetMap, or your Google/Amap key) and send nothing to that host. (default: true) # TREK_PLACES_URL=https://places.liketrek.com # Base URL of a copy of the Places API you run yourself; it has to answer the same /v1 API. Read from configuration rather than typed by a user, so an address on your LAN or Docker network works without ALLOW_INTERNAL_NETWORK. (default: https://places.liketrek.com) +# PLACES_API_BASE= # Send the Google Places calls through an egress proxy, a cache or a gateway that speaks the same API instead of places.googleapis.com directly. Unset: Google's own endpoints. # PLACES_API_KEY= # Google Maps API key (Places API (New) enabled) for place search, photos, details and Google transit. Overrides the key set in Admin > Settings > API Keys, whose field then shows this variable read-only. The value never reaches the browser. # AMAP_API_KEY= # Amap (高德地图) Web 服务 key for place search and geocoding inside mainland China. Overrides the key set in Admin > Settings > API Keys. A Web 端 (JS API) key is a different credential and is rejected with INVALID_USER_KEY. # AMAP_API_SECRET= # The private secret (数字签名) of that key. Required exactly when the key was created with signing enabled, because such a key rejects every unsigned request. Leave unset otherwise. # AMAP_API_BASE=https://restapi.amap.com # Send the Amap calls through an egress proxy, a cache or a gateway that speaks the same API instead of restapi.amap.com directly. (default: https://restapi.amap.com) +# TRANSIT_API_URL=https://api.transitous.org # Base URL of the transit routing API the server proxies to. Point it at your own MOTIS instance to keep transit searches off third-party servers. A trailing slash is stripped. (default: https://api.transitous.org) + +# MAPBOX_ACCESS_TOKEN= # Only read with TREK_MANAGED: the public Mapbox token (pk.*) a managed instance ships with, in place of the one in Admin > Settings. It reaches the browser by design, so never a secret token. +# CARTO_API_KEY= # Only read with TREK_MANAGED: the CARTO basemap key a managed instance ships with. Without a key the CARTO tiles carry a watermark. Public like the Mapbox token. + +# TREK_PLACE_PHOTO_DIR= # Directory for cached Google place photos, e.g. a dedicated volume. Unset, they live in uploads/photos/google. Read once at startup. (default: uploads/photos/google) + # KITINERARY_EXTRACTOR_PATH= # Full path to the kitinerary-extractor binary. Unset, TREK searches /usr/lib/*/libexec/kf6/ and then PATH; the official image pins it. Set it to run a newer extractor than your distribution packages — the version in use is in the startup log and in GET /api/admin/system-info. (default: auto-detected) # LLM_TIMEOUT_MS=900000 # Ceiling (ms) for one AI-parsing call before it is abandoned. One value for every provider, and the underlying HTTP client is held to it too. Generous by default so heavier parsing work fits without a code change; lower it on a cloud provider to fail fast. (default: 900000) @@ -77,6 +92,35 @@ DEMO_MODE=false # Demo mode - resets data hourly # VAPID_PRIVATE_KEY= # Web Push: the private half (base64url, 32 bytes). Only used together with VAPID_PUBLIC_KEY; a pair whose halves do not belong together, or only one half, turns push off with an error in the log until the pair is fixed. A pair stored in the database is not used in its place, and every device stays registered. # VAPID_SUBJECT=mailto:admin@example.com # Web Push: the contact push services see with every message, a mailto: address or an https:// URL. Unset, TREK uses APP_URL when it is https, else the TREK project page. +# SMTP_HOST=smtp.example.com # Outgoing mail server. SMTP_HOST, SMTP_PORT and SMTP_FROM are all needed for email; each SMTP_* variable overrides its field in Admin > Settings > Notifications. +# SMTP_PORT=587 # Port 465 uses implicit TLS; every other port uses STARTTLS or plain. +# SMTP_USER= # SMTP login, if the server wants one. +# SMTP_PASS= # SMTP password, if the server wants one. +# SMTP_FROM=TREK # Sender address of every email TREK sends. +# SMTP_SKIP_TLS_VERIFY=false # true accepts a self-signed certificate on an internal relay. Not for production. + +# WEBAUTHN_RP_ID=trek.example.com # The domain passkeys are bound to. Overrides the setting in the admin panel; unset, it comes from the hostname of APP_URL. An IP address is refused. +# WEBAUTHN_ORIGINS=https://trek.example.com # Comma-separated origins allowed for passkey sign-in. Overrides the setting in the admin panel; unset, the origin of APP_URL is used. + +# TREK_API_DOCS_ENABLED=false # Serve the OpenAPI docs at /api/docs (raw spec at /api/docs-json). Off by default because the spec lists every route, the admin ones included. + +# TREK_PLUGINS_ENABLED=true # false turns the whole plugin system off: no plugin runs and the admin panel says so. (default: true) +# TREK_PLUGINS_DIR= # Where installed plugin code is kept. Persist it as a volume if you use plugins. (default: data/plugins) +# TREK_PLUGINS_DATA_DIR= # Where each plugin keeps its own data. Persist it too. (default: data/plugins-data) +# TREK_PLUGIN_REGISTRY_URL=https://raw.githubusercontent.com/liketrek/TREK-Plugins/main/dist/index.json # The plugin index the Discover tab browses. Point it at your own mirror or fork. +# TREK_PLUGIN_PERMISSIONS=true # false takes plugin processes out of Node's OS permission sandbox. Not recommended. (default: true) +# TREK_PLUGIN_ALLOW_PRIVATE_EGRESS=false # true lets a plugin's declared hosts resolve to private addresses, e.g. a service on your LAN. (default: false) +# TREK_PLUGINS_IGNORE_TREK_RANGE=false # true turns the plugin TREK-version check into a warning, so a plugin outside its declared range can be installed anyway. (default: false) +# TREK_PLUGINS_DEV_LINK=false # true shows "Link a local plugin" in the admin panel, for plugin authors. Development only. (default: false) +# TREK_PLUGIN_MAX_RSS_MB=300 # Memory ceiling of one plugin process in MB; a plugin past it is stopped. (default: 300) +# TREK_PLUGIN_RPC_BURST=60 # Host calls a plugin may make back to back before the per-second limit applies. (default: 60) +# TREK_PLUGIN_RPC_PER_SEC=20 # Sustained host calls per second per plugin. (default: 20) +# TREK_PLUGIN_RPC_INFLIGHT=16 # Host calls one plugin may have running at once. (default: 16) +# TREK_PLUGIN_LOG_BURST=50 # Log lines a plugin may write back to back before the per-second limit applies. (default: 50) +# TREK_PLUGIN_LOG_PER_SEC=10 # Sustained log lines per second per plugin. (default: 10) + +# TREK_MANAGED=false # Set by hosting providers that administer an instance for its owner. It withholds the settings the provider controls from the instance admin and requires ENCRYPTION_KEY. Leave it unset on a self-hosted install. (default: false) + # UNSPLASH_ACCESS_KEY= # Optional Unsplash Access Key for trip-cover and place-image search. Without one, TREK uses Unsplash's unauthenticated endpoint, which some datacenter/VPS IPs get blocked from (#1449). Get a free key at unsplash.com/developers. Overrides any key set per-admin in Admin > Settings. Can also be configured there instead of here. # Initial admin account — ONLY applied on the first boot, when the database has no diff --git a/server/CLAUDE.md b/server/CLAUDE.md index c3eaf546d..8f8d2f091 100644 --- a/server/CLAUDE.md +++ b/server/CLAUDE.md @@ -84,7 +84,8 @@ SQLite is the engine today and Postgres is the planned second one. Code under `s **Never read `process.env` in `src/**`** — ESLint errors on it. All env access goes through `src/app-config/`: -- Nest classes inject a boot-stable namespace token from `src/nest/app-config/` for values frozen per app build, or use `RuntimeEnvService` / `readEnv()` for runtime-toggled values (DEMO_MODE, NODE_ENV, OIDC_*, …) that tests mutate mid-lifetime. +- Every variable has exactly one owner. Nest classes inject a boot-stable namespace token from `src/nest/app-config/` (`httpConfig`, `storageConfig`) for values frozen per app build, or use `RuntimeEnvService` / `readEnv()` for everything else (DEMO_MODE, NODE_ENV, OIDC_*, ...). A token-owned variable is derived in `boot-derive.ts` and never by `readEnv()`; `tests/unit/app-config/config-ownership.test.ts` fails on a variable read through both, and on a token nothing injects. +- `server/.env.example` documents every variable `env.schema.ts` validates; `env-reference.test.ts` fails on drift either way. - Everything else calls `readEnv()` — live, uncached, per call. - Validation is fail-fast at boot only (`boot-validate.ts`, imported by `index.ts` right after dotenv): malformed values abort startup; unset/blank defaults. Never wire validation into `buildApp()` or `ConfigModule.forRoot`, and never `cache`/snapshot a runtime-toggled value (it breaks the env-mutating tests). - Booleans go through `parseBool` (true/1/on/yes vs false/0/off/no). Everything else pins its exact legacy coercion — quirks and the ESLint exemption list are in `src/app-config/README.md`. diff --git a/server/src/app-config/README.md b/server/src/app-config/README.md index 334b7f050..ae2504c43 100644 --- a/server/src/app-config/README.md +++ b/server/src/app-config/README.md @@ -76,11 +76,37 @@ invariant 1: `readEnv()` per call, live, never cached. The invalid-URL silent fallthrough and the strip-ALL-slashes quirk (see `parsers.ts` `stripTrailingSlashes`) are parity-pinned — do not "fix" them here. +## Ownership: one door per variable + +Every variable has exactly one owner, and the owner decides how it is read: + +- **A registerAs token** (`src/nest/app-config/tokens.ts`, derived by + `boot-derive.ts`): boot-stable values that only Nest classes need. The token + is snapshotted per built app and injected (`@Inject(storageConfig.KEY)`, or + `app.get(httpConfig.KEY)` for the pre-init Express layer). Today: + `httpConfig` (TRUST_PROXY, HSTS_INCLUDE_SUBDOMAINS) and `storageConfig` + (TREK_PLACE_PHOTO_DIR). +- **`readEnv()` / `RuntimeEnvService`** (`derive.ts`): everything else, both + the runtime-toggled values and the boot-stable ones that code outside the + container needs (config.ts, the database, src/mcp, the SSRF guard), which + freeze them in module-top consts. + +`deriveAll()` never reads a variable a token owns, and a token is dropped once +nothing injects it. `tests/unit/app-config/config-ownership.test.ts` records +the keys each side reads through a Proxy and fails on an overlap, on a token +without a consumer and on a variable the schema does not validate. Moving a +variable to a token means moving its field from `derive.ts` to +`boot-derive.ts` and converting every reader in the same change. + +`server/.env.example` names every variable the schema validates except the +few in `env-reference.test.ts`'s `NOT_OPERATOR_SETTINGS`; that test fails on +drift in either direction. + ## Classification: boot-stable vs runtime-toggled -**Boot-stable** (frozen at app/module creation; snapshot `registerAs`/`ConfigType` -DI in Nest, module-top `readEnv()` consts elsewhere): -PORT, HOST, TRUST_PROXY, SESSION_DURATION(_REMEMBER), MCP_SESSION_TTL, +**Boot-stable** (frozen at app/module creation; a `registerAs` token where the +variable is token-owned, module-top `readEnv()` consts elsewhere): +PORT, HOST, TRUST_PROXY, HSTS_INCLUDE_SUBDOMAINS, SESSION_DURATION(_REMEMBER), MCP_SESSION_TTL, MCP_MAX_SESSION_PER_USER, MCP_SSE_KEEPALIVE, TREK_PLUGIN_RPC_*/LOG_*/MAX_RSS_MB, TREK_PLUGIN_REGISTRY_URL, TREK_WIKI_DIR*, TREK_PLACE_PHOTO_DIR, BACKUP_*, TRANSIT_API_URL, LOG_LEVEL*, ALLOW_INTERNAL_NETWORK*, ALLOW_LINK_LOCAL_IPS*, DEFAULT_LANGUAGE, @@ -95,7 +121,7 @@ below.) `RuntimeEnvService`; tests mutate these mid-lifetime): TREK_MANAGED, PLACES_API_BASE, PLACES_API_KEY, AMAP_API_BASE, AMAP_API_KEY, AMAP_API_SECRET, MAPBOX_ACCESS_TOKEN, CARTO_API_KEY, DEMO_MODE, NODE_ENV, APP_VERSION, APP_URL, TREK_API_DOCS_ENABLED, TREK_PLUGINS_ENABLED / _DEV_LINK / _IGNORE_TREK_RANGE / _DIR / _DATA_DIR / TREK_PLUGIN_PERMISSIONS, -OIDC_*, SMTP_*, FORCE_HTTPS, COOKIE_SECURE, HSTS_INCLUDE_SUBDOMAINS, +OIDC_*, SMTP_*, FORCE_HTTPS, COOKIE_SECURE, ALLOWED_ORIGINS, UNSPLASH_ACCESS_KEY, WEBAUTHN_*, TZ, ADMIN_EMAIL, TREK_DB_PRE_MIGRATE_SNAPSHOT(_KEEP) (read when a migration run starts; the legacy-upgrade suites set it per file), diff --git a/server/src/app-config/boot-derive.ts b/server/src/app-config/boot-derive.ts new file mode 100644 index 000000000..99a163152 --- /dev/null +++ b/server/src/app-config/boot-derive.ts @@ -0,0 +1,39 @@ +/** + * Derive functions for the BOOT-STABLE values that Nest injects through a + * registerAs token (src/nest/app-config/tokens.ts) and nothing else reads. + * + * Every environment variable has exactly one owner. A variable derived here is + * owned by its token: `deriveAll()` (and so `readEnv()`) never reads it, which + * tests/unit/app-config/config-ownership.test.ts checks by recording the keys + * each side touches. A value that pre-container code needs, or that tests + * mutate mid-lifetime, belongs in derive.ts instead. + */ +import { parseBool } from './parsers'; +import type { RawEnv } from './derive'; + +/** What the pre-init Express layer and the HTTP server freeze when buildApp() runs. */ +export function deriveHttpBoot(raw: RawEnv) { + // env.schema.ts accepts 0 as a valid hop count, so `|| 1` would quietly turn + // "trust nothing" into "trust one hop" and let a forged X-Forwarded-For through. + const trustProxyHops = Number.parseInt(raw.TRUST_PROXY ?? '', 10); + return { + trustProxyRaw: raw.TRUST_PROXY, + trustProxy: Number.isFinite(trustProxyHops) ? trustProxyHops : 1, + hstsIncludeSubdomains: parseBool(raw.HSTS_INCLUDE_SUBDOMAINS) === true, + }; +} + +/** Where the storage registry puts its conditional place-photo backend. */ +export function deriveStorage(raw: RawEnv) { + return { + placePhotoDir: raw.TREK_PLACE_PHOTO_DIR, + }; +} + +/** One entry per token: the namespace it registers under and the function it derives with. */ +export const BOOT_DERIVERS = { + http: deriveHttpBoot, + storage: deriveStorage, +} as const; + +export type BootNamespace = keyof typeof BOOT_DERIVERS; diff --git a/server/src/app-config/derive.ts b/server/src/app-config/derive.ts index 46671dbba..6a9b5490f 100644 --- a/server/src/app-config/derive.ts +++ b/server/src/app-config/derive.ts @@ -69,20 +69,19 @@ function resolveDefaultLanguage(raw: string | undefined): string { return canonical ?? 'en'; } +/** + * The live half of the HTTP settings. TRUST_PROXY and HSTS_INCLUDE_SUBDOMAINS + * are not here: they are boot-stable and owned by the `httpConfig` token + * (boot-derive.ts), so they cannot be read through two doors. + */ export function deriveHttp(raw: RawEnv) { - // env.schema.ts accepts 0 as a valid hop count, so `|| 1` would quietly turn - // "trust nothing" into "trust one hop" and let a forged X-Forwarded-For through. - const trustProxyHops = Number.parseInt(raw.TRUST_PROXY ?? '', 10); return { allowedOriginsRaw: raw.ALLOWED_ORIGINS, /** globalMiddleware CORS variant: trim + drop empty entries. */ corsOrigins: csvListFiltered(raw.ALLOWED_ORIGINS), /** websocket variant: trim only — an empty entry stays (and can never match an Origin header). */ wsOrigins: csvList(raw.ALLOWED_ORIGINS), - trustProxyRaw: raw.TRUST_PROXY, - trustProxy: Number.isFinite(trustProxyHops) ? trustProxyHops : 1, forceHttps: parseBool(raw.FORCE_HTTPS) === true, - hstsIncludeSubdomains: parseBool(raw.HSTS_INCLUDE_SUBDOMAINS) === true, /** COOKIE_SECURE is tri-state: an explicit falsy value disables secure cookies; anything else means auto-detect. */ cookieSecureDisabled: parseBool(raw.COOKIE_SECURE) === false, apiDocsEnabled: parseBool(raw.TREK_API_DOCS_ENABLED) === true, @@ -346,10 +345,10 @@ export function deriveDb(raw: RawEnv) { }; } +/** TREK_PLACE_PHOTO_DIR is boot-stable and owned by the `storageConfig` token (boot-derive.ts). */ export function derivePaths(raw: RawEnv) { return { wikiDir: raw.TREK_WIKI_DIR, - placePhotoDir: raw.TREK_PLACE_PHOTO_DIR, }; } diff --git a/server/src/middleware/globalMiddleware.ts b/server/src/middleware/globalMiddleware.ts index e6e67656a..71cb1317e 100644 --- a/server/src/middleware/globalMiddleware.ts +++ b/server/src/middleware/globalMiddleware.ts @@ -3,7 +3,9 @@ import compression from 'compression'; import cors from 'cors'; import helmet from 'helmet'; import cookieParser from 'cookie-parser'; -import { readEnv, type AppEnv } from '../app-config'; +import type { ConfigType } from '@nestjs/config'; +import { readEnv } from '../app-config'; +import { httpConfig } from '../nest/app-config/tokens'; import { logDebug, logWarn, logError } from '../nest/audit/audit-log.logger'; import { isSameHostOrigin } from '../nest/common/same-origin'; @@ -124,7 +126,8 @@ export function routingCspOrigins(baseUrls: (string | null | undefined)[]): stri export function applyGlobalMiddleware( app: express.Application, opts: { - http?: AppEnv['http']; + /** The boot-stable half (trust proxy, HSTS subdomains), from the `httpConfig` token. */ + http?: ConfigType; /** * Extra origins the browser may talk to, from the instance's own settings — today the * self-hosted routing engine (#1797). Read once at apply time like everything else @@ -136,9 +139,11 @@ export function applyGlobalMiddleware( ): void { // The whole pipeline is configured at APPLY time (the per-request closures // capture these values), so a snapshot is the correct semantic. bootstrap - // threads in the DI-loaded httpConfig; direct callers fall back to an - // apply-time readEnv() — same values, same freeze point. - const { http = readEnv().http, extraConnectSrc = [] } = opts; + // threads in the DI-loaded httpConfig; a direct caller gets the same token + // factory evaluated now. The live half (origins, forced HTTPS) is read here + // too, once, so both halves freeze at the same point. + const { http = httpConfig(), extraConnectSrc = [] } = opts; + const liveHttp = readEnv().http; const { nodeEnv, isProduction } = readEnv().app; // Trust first proxy (nginx/Docker) for correct req.ip @@ -161,7 +166,7 @@ export function applyGlobalMiddleware( }), ); - const allowedOrigins = http.corsOrigins; + const allowedOrigins = liveHttp.corsOrigins; // With ALLOWED_ORIGINS set, a request from anywhere else is refused outright. // Two things keep that from hitting the instance's own pages (#2543): a request @@ -186,7 +191,7 @@ export function applyGlobalMiddleware( } : { origin: isProduction ? false : true, credentials: true }; - const shouldForceHttps = http.forceHttps; + const shouldForceHttps = liveHttp.forceHttps; // HSTS is worth enabling any time we're serving production traffic, // not only when FORCE_HTTPS is set. Self-hosters behind Traefik / // Caddy / Cloudflare Tunnel typically leave FORCE_HTTPS unset (the diff --git a/server/src/nest/README.md b/server/src/nest/README.md index 384fce8d1..914eb9cf5 100644 --- a/server/src/nest/README.md +++ b/server/src/nest/README.md @@ -374,10 +374,12 @@ no-Nest test harnesses still construct instances; CHOVR-015 pins the sharing). - `app-config/` — the `@nestjs/config` binding (`AppConfigModule`, global). Never read `process.env` in a module (ESLint enforces this): inject a boot-stable - namespace via its `registerAs` token (`@Inject(mcpConfig.KEY) … ConfigType<…>`) + namespace via its `registerAs` token (`@Inject(storageConfig.KEY) … ConfigType<…>`) or read runtime-toggled values live through `RuntimeEnvService` / `readEnv()` - from `src/app-config`. The classification and invariants live in - `src/app-config/README.md`. + from `src/app-config`. Every variable has exactly one owner, a token or + `readEnv()`, and `config-ownership.test.ts` fails on a variable read through + both. Data paths come from `DataPathsService`. The classification and + invariants live in `src/app-config/README.md`. ## Parity gotchas worth remembering diff --git a/server/src/nest/app-config/index.ts b/server/src/nest/app-config/index.ts index 6ca4d859d..7575353eb 100644 --- a/server/src/nest/app-config/index.ts +++ b/server/src/nest/app-config/index.ts @@ -1,14 +1,4 @@ export { AppConfigModule } from './app-config.module'; export { RuntimeEnvService } from './runtime-env.service'; export { DataPathsService } from './data-paths.service'; -export { - httpConfig, - sessionConfig, - mcpConfig, - integrationsConfig, - backupConfig, - dbConfig, - pathsConfig, - netConfig, - BOOT_STABLE_TOKENS, -} from './tokens'; +export { httpConfig, storageConfig, BOOT_STABLE_TOKENS } from './tokens'; diff --git a/server/src/nest/app-config/tokens.ts b/server/src/nest/app-config/tokens.ts index 2d1adda9e..63be767f4 100644 --- a/server/src/nest/app-config/tokens.ts +++ b/server/src/nest/app-config/tokens.ts @@ -1,57 +1,31 @@ /** - * registerAs tokens over the app-config derive functions, for the BOOT-STABLE - * namespaces only (see src/app-config/README.md for the classification). + * registerAs tokens for the BOOT-STABLE values Nest injects, one per namespace + * in `BOOT_DERIVERS` (src/app-config/boot-derive.ts). * * A token's factory runs during NestFactory.create(), so the injected object is - * a SNAPSHOT per built app — integration tests that mutate env and then rebuild - * buildApp() get fresh values automatically. Runtime-toggled values (DEMO_MODE, - * NODE_ENV, OIDC_*, …) must NOT get tokens here; they go through - * RuntimeEnvService / readEnv() so mid-lifetime env mutations stay visible. + * a SNAPSHOT per built app: integration tests that set env and then build an + * app get fresh values automatically. + * + * Every environment variable has exactly one owner. The variables a token + * derives are read nowhere else, and `readEnv()` never derives them + * (tests/unit/app-config/config-ownership.test.ts records both sides and fails + * on an overlap, and on a token nothing injects). A value that code outside + * the container needs, or that tests mutate mid-lifetime, stays on + * `readEnv()` / `RuntimeEnvService` instead. * * Consumption pattern: - * constructor(@Inject(httpConfig.KEY) private readonly http: ConfigType) {} - * - * NOTE: today only httpConfig has a DI consumer (bootstrap.ts threads it into - * the pre-init middleware); the migrated call sites otherwise read through - * readEnv() because they live in classes whose unit tests instantiate them - * directly. The full token set is provisioned deliberately — it is the - * sanctioned pattern for NEW Nest consumers of boot-stable config, not dead - * scaffolding to prune. + * constructor(@Inject(storageConfig.KEY) private readonly storage: ConfigType) {} + * or, for the pre-init Express layer in bootstrap.ts, `app.get(httpConfig.KEY)`. */ import { registerAs } from '@nestjs/config'; -import { - deriveBackup, - deriveDb, - deriveHttp, - deriveIntegrations, - deriveMcp, - deriveNet, - derivePaths, - deriveSession, -} from '../../app-config'; +import { BOOT_DERIVERS } from '../../app-config/boot-derive'; /** - * http is snapshot-consumed only by the pre-init Express layer (bootstrap - * threads it into applyGlobalMiddleware) — apply-time freeze per built app. - * Request-time reads of the same vars (cookie.ts FORCE_HTTPS checks) stay live - * via readEnv(). + * The pre-init Express layer (trust proxy, HSTS) reads this once per built app + * through `app.get(httpConfig.KEY)` in bootstrap.ts. */ -export const httpConfig = registerAs('http', () => deriveHttp(process.env)); -export const sessionConfig = registerAs('session', () => deriveSession(process.env)); -export const mcpConfig = registerAs('mcp', () => deriveMcp(process.env)); -export const integrationsConfig = registerAs('integrations', () => deriveIntegrations(process.env)); -export const backupConfig = registerAs('backup', () => deriveBackup(process.env)); -export const dbConfig = registerAs('db', () => deriveDb(process.env)); -export const pathsConfig = registerAs('paths', () => derivePaths(process.env)); -export const netConfig = registerAs('net', () => deriveNet(process.env)); +export const httpConfig = registerAs('http', () => BOOT_DERIVERS.http(process.env)); +/** The storage registry's conditional place-photo backend (TREK_PLACE_PHOTO_DIR). */ +export const storageConfig = registerAs('storage', () => BOOT_DERIVERS.storage(process.env)); -export const BOOT_STABLE_TOKENS = [ - httpConfig, - sessionConfig, - mcpConfig, - integrationsConfig, - backupConfig, - dbConfig, - pathsConfig, - netConfig, -]; +export const BOOT_STABLE_TOKENS = [httpConfig, storageConfig]; diff --git a/server/src/nest/auth/jwt-verify.ts b/server/src/nest/auth/jwt-verify.ts index 99e6a143c..b26301536 100644 --- a/server/src/nest/auth/jwt-verify.ts +++ b/server/src/nest/auth/jwt-verify.ts @@ -10,10 +10,10 @@ import type { UsersRepository } from '../../db/repositories/Users.repository'; * photo-serving route and the global MFA policy — so the secret, the * password_version gate and the loaded user cannot drift between them. * - * Free functions rather than a provider: the MFA policy in - * middleware/mfaPolicy.ts and the platform routes run outside the container and - * would have no way to inject one. Note JWT_SECRET is deliberately a live - * binding from src/config, not an app-config value: the admin panel rotates it + * Free functions rather than a provider: the platform routes run outside the + * container and would have no way to inject one, and the guards that call this + * (the MFA policy is nest/auth/mfa-policy.guard.ts now) share the one copy. + * Note JWT_SECRET is deliberately a live binding from src/config, not an app-config value: the admin panel rotates it * at runtime and `export let` is what makes a rotation take effect in-process. * * `verifyJwtAndLoadUser` stays a free function (Plan 3b Task 1 RULING) and diff --git a/server/src/nest/storage/storage-registry.service.ts b/server/src/nest/storage/storage-registry.service.ts index fbcad0918..a0bc515ef 100644 --- a/server/src/nest/storage/storage-registry.service.ts +++ b/server/src/nest/storage/storage-registry.service.ts @@ -1,11 +1,12 @@ import fs from 'node:fs'; -import { Injectable, Logger, type OnModuleInit } from '@nestjs/common'; +import { Inject, Injectable, Logger, type OnModuleInit } from '@nestjs/common'; +import type { ConfigType } from '@nestjs/config'; import { InjectRepository } from '@mikro-orm/nestjs'; import { MikroORM } from '@mikro-orm/core'; import { STORAGE_BACKEND_TYPES, storageConfigSchema } from '@trek/shared'; import { UnitOfWork } from '../database/unit-of-work'; import { withRequestContext } from '../database/request-context'; -import { RuntimeEnvService } from '../app-config/runtime-env.service'; +import { storageConfig } from '../app-config/tokens'; import { decrypt_api_key } from '../common/crypto/apiKeyCrypto'; import { AppSettings } from '../../db/entities/AppSettings.entity'; import type { AppSettingsRepository } from '../../db/repositories/AppSettings.repository'; @@ -136,7 +137,7 @@ export class StorageRegistryService implements OnModuleInit { constructor( @InjectRepository(AppSettings) private readonly appSettings: AppSettingsRepository, - private readonly env: RuntimeEnvService, + @Inject(storageConfig.KEY) private readonly storageEnv: ConfigType, private readonly events: StorageEventsService, private readonly uow: UnitOfWork, private readonly orm: MikroORM, @@ -400,8 +401,9 @@ export class StorageRegistryService implements OnModuleInit { categoryBackends: Map; categorySources: Map; } { - // 1. Env is read fresh on every load (never snapshotted — RuntimeEnvService rule). - const placePhotoDir = this.env.env().paths.placePhotoDir; + // 1. TREK_PLACE_PHOTO_DIR is boot-stable: the storageConfig token owns it and + // every load of one built app sees the same value. + const placePhotoDir = this.storageEnv.placePhotoDir; // 2. Built-in defaults; settings entries with the same name/category override. // uploads-local's root is the computed default; relocation is a settings diff --git a/server/tests/integration/app-config.test.ts b/server/tests/integration/app-config.test.ts index ef9418fbd..d7126a170 100644 --- a/server/tests/integration/app-config.test.ts +++ b/server/tests/integration/app-config.test.ts @@ -30,47 +30,47 @@ import type { ConfigType } from '@nestjs/config'; describe('AppConfigModule in the real buildApp()', () => { let app: INestApplication | undefined; - let prevForceHttps: string | undefined; + let prevHsts: string | undefined; let prevDemo: string | undefined; beforeAll(() => { resetTestDb(testDb); - prevForceHttps = process.env.FORCE_HTTPS; + prevHsts = process.env.HSTS_INCLUDE_SUBDOMAINS; prevDemo = process.env.DEMO_MODE; }); afterEach(async () => { await app?.close(); app = undefined; - if (prevForceHttps === undefined) delete process.env.FORCE_HTTPS; - else process.env.FORCE_HTTPS = prevForceHttps; + if (prevHsts === undefined) delete process.env.HSTS_INCLUDE_SUBDOMAINS; + else process.env.HSTS_INCLUDE_SUBDOMAINS = prevHsts; if (prevDemo === undefined) delete process.env.DEMO_MODE; else process.env.DEMO_MODE = prevDemo; }); it('boot-stable snapshots re-derive per app build (mutate → rebuild → new value)', async () => { - process.env.FORCE_HTTPS = 'true'; + process.env.HSTS_INCLUDE_SUBDOMAINS = 'true'; app = await buildApp(); let http = app.get>(httpConfig.KEY); - expect(http.forceHttps).toBe(true); + expect(http.hstsIncludeSubdomains).toBe(true); await app.close(); - process.env.FORCE_HTTPS = 'off'; + process.env.HSTS_INCLUDE_SUBDOMAINS = 'off'; app = await buildApp(); http = app.get>(httpConfig.KEY); - expect(http.forceHttps).toBe(false); + expect(http.hstsIncludeSubdomains).toBe(false); }); it('a snapshot does NOT move within one app lifetime, RuntimeEnvService does', async () => { - delete process.env.FORCE_HTTPS; + delete process.env.HSTS_INCLUDE_SUBDOMAINS; delete process.env.DEMO_MODE; app = await buildApp(); const http = app.get>(httpConfig.KEY); const runtime = app.get(RuntimeEnvService); - process.env.FORCE_HTTPS = 'true'; + process.env.HSTS_INCLUDE_SUBDOMAINS = 'true'; process.env.DEMO_MODE = 'true'; - expect(http.forceHttps).toBe(false); // frozen at build — by design + expect(http.hstsIncludeSubdomains).toBe(false); // frozen at build, by design expect(runtime.isDemoMode()).toBe(true); // live — by design }); }); diff --git a/server/tests/integration/storage-restore-reload.test.ts b/server/tests/integration/storage-restore-reload.test.ts index 3255f3c75..cf299cf94 100644 --- a/server/tests/integration/storage-restore-reload.test.ts +++ b/server/tests/integration/storage-restore-reload.test.ts @@ -27,7 +27,6 @@ import os from 'node:os'; import path from 'node:path'; import { createSnapshotTestDb } from '../helpers/db-mock'; -import type { RuntimeEnvService } from '../../src/nest/app-config/runtime-env.service'; import { StorageEventsService } from '../../src/nest/storage/storage-events.service'; import { BACKENDS_KEY, CATEGORIES_KEY, StorageRegistryService } from '../../src/nest/storage/storage-registry.service'; import { StorageService } from '../../src/nest/storage/storage.service'; @@ -42,8 +41,8 @@ function makeTmpDir(): string { return dir; } -function envStub(): RuntimeEnvService { - return { env: () => ({ paths: {} }) } as unknown as RuntimeEnvService; +function envStub(): { placePhotoDir: string | undefined } { + return { placePhotoDir: undefined }; } function setSetting(key: string, value: unknown): void { diff --git a/server/tests/unit/app-config/config-ownership.test.ts b/server/tests/unit/app-config/config-ownership.test.ts new file mode 100644 index 000000000..b724efff3 --- /dev/null +++ b/server/tests/unit/app-config/config-ownership.test.ts @@ -0,0 +1,101 @@ +/** + * Every environment variable has exactly one owner: either `readEnv()` (live, + * per call, reachable from anywhere) or one registerAs token (boot-stable, + * injected). A variable read through both drifts the moment one side's + * semantics change, and its dependency is invisible to whoever reads the + * other. These cases record which keys each side actually touches, through a + * Proxy over the raw environment, so a new field in the wrong derive function + * fails here rather than in review. + */ +import { describe, it, expect } from 'vitest'; +import fs from 'node:fs'; +import path from 'node:path'; +import { deriveAll, type RawEnv } from '../../../src/app-config/derive'; +import { BOOT_DERIVERS, type BootNamespace } from '../../../src/app-config/boot-derive'; +import { envSchema } from '../../../src/app-config/env.schema'; +import { BOOT_STABLE_TOKENS } from '../../../src/nest/app-config/tokens'; + +const SRC = path.join(__dirname, '..', '..', '..', 'src'); +const TOKENS_FILE = path.join(SRC, 'nest', 'app-config', 'tokens.ts'); + +/** + * Variables Node itself and the outbound proxy support read. They are not TREK + * configuration, so the schema does not list them; deriveNet passes them on. + */ +const PLATFORM_VARIABLES = new Set(['HTTP_PROXY', 'http_proxy', 'HTTPS_PROXY', 'https_proxy', 'NO_PROXY', 'no_proxy']); + +/** The keys `derive` reads from an empty environment, in the order it reads them. */ +function keysReadBy(derive: (raw: RawEnv) => unknown): Set { + const read = new Set(); + const raw = new Proxy({} as RawEnv, { + get(_target, key) { + if (typeof key === 'string') read.add(key); + return undefined; + }, + }); + derive(raw); + return read; +} + +function sourceFiles(dir: string): string[] { + return fs.readdirSync(dir, { withFileTypes: true }).flatMap((entry) => { + const full = path.join(dir, entry.name); + if (entry.isDirectory()) return sourceFiles(full); + return entry.name.endsWith('.ts') ? [full] : []; + }); +} + +const namespaces = Object.keys(BOOT_DERIVERS) as BootNamespace[]; +const liveKeys = keysReadBy(deriveAll); + +describe('config ownership', () => { + it('CONFIG-OWN-001: the recorder sees what readEnv() derives (sanity)', () => { + expect(liveKeys.has('DEMO_MODE')).toBe(true); + expect(liveKeys.has('ALLOWED_ORIGINS')).toBe(true); + expect(keysReadBy(BOOT_DERIVERS.http).has('TRUST_PROXY')).toBe(true); + }); + + it.each(namespaces)('CONFIG-OWN-002: no variable the %s token owns is also derived by readEnv()', (ns) => { + const both = [...keysReadBy(BOOT_DERIVERS[ns])].filter((key) => liveKeys.has(key)); + expect(both).toEqual([]); + }); + + it('CONFIG-OWN-003: no variable is owned by two tokens', () => { + const owner = new Map(); + const clashes: string[] = []; + for (const ns of namespaces) { + for (const key of keysReadBy(BOOT_DERIVERS[ns])) { + const previous = owner.get(key); + if (previous) clashes.push(`${key}: ${previous} and ${ns}`); + owner.set(key, ns); + } + } + expect(clashes).toEqual([]); + }); + + it('CONFIG-OWN-004: every token registers under its namespace and derives with its BOOT_DERIVERS entry', () => { + expect(BOOT_STABLE_TOKENS.map((token) => String(token.KEY)).sort()).toEqual( + namespaces.map((ns) => `CONFIGURATION(${ns})`).sort(), + ); + for (const token of BOOT_STABLE_TOKENS) { + const ns = /^CONFIGURATION\((.+)\)$/.exec(String(token.KEY))![1] as BootNamespace; + expect(token()).toEqual(BOOT_DERIVERS[ns](process.env as RawEnv)); + } + }); + + it('CONFIG-OWN-005: every token is injected somewhere, so none is dead scaffolding', () => { + const consumers = sourceFiles(SRC) + .filter((file) => file !== TOKENS_FILE) + .map((file) => fs.readFileSync(file, 'utf8')) + .join('\n'); + const unused = namespaces.filter((ns) => !consumers.includes(`${ns}Config.KEY`)); + expect(unused).toEqual([]); + }); + + it('CONFIG-OWN-006: every variable either side reads is in the validated schema', () => { + const schemaKeys = new Set(Object.keys(envSchema.shape)); + const read = new Set([...liveKeys, ...namespaces.flatMap((ns) => [...keysReadBy(BOOT_DERIVERS[ns])])]); + const unvalidated = [...read].filter((key) => !schemaKeys.has(key) && !PLATFORM_VARIABLES.has(key)); + expect(unvalidated).toEqual([]); + }); +}); diff --git a/server/tests/unit/app-config/derive.test.ts b/server/tests/unit/app-config/derive.test.ts index 7e9ebe67b..648d517a7 100644 --- a/server/tests/unit/app-config/derive.test.ts +++ b/server/tests/unit/app-config/derive.test.ts @@ -21,6 +21,7 @@ import { derivePush, deriveAll, } from '../../../src/app-config/derive'; +import { deriveHttpBoot, deriveStorage } from '../../../src/app-config/boot-derive'; // These tests PIN the exact legacy coercions each derived field replaced. // If one fails after an edit, the edit changed runtime behavior — fix the @@ -67,20 +68,20 @@ describe('deriveHttp', () => { expect(deriveHttp({}).wsOrigins).toBeNull(); }); - it('TRUST_PROXY: numeric hop count wins, 1 only as fallback (globalMiddleware)', () => { - expect(deriveHttp({ TRUST_PROXY: '2' }).trustProxy).toBe(2); + it('TRUST_PROXY: numeric hop count wins, 1 only as fallback (globalMiddleware, httpConfig token)', () => { + expect(deriveHttpBoot({ TRUST_PROXY: '2' }).trustProxy).toBe(2); // 0 is a valid hop count ("trust no proxy"), not a missing value. - expect(deriveHttp({ TRUST_PROXY: '0' }).trustProxy).toBe(0); - expect(deriveHttp({ TRUST_PROXY: 'abc' }).trustProxy).toBe(1); - expect(deriveHttp({}).trustProxy).toBe(1); + expect(deriveHttpBoot({ TRUST_PROXY: '0' }).trustProxy).toBe(0); + expect(deriveHttpBoot({ TRUST_PROXY: 'abc' }).trustProxy).toBe(1); + expect(deriveHttpBoot({}).trustProxy).toBe(1); }); it('boolean switches accept the whole boolean-like family (unified semantics)', () => { expect(deriveHttp({ FORCE_HTTPS: 'TRUE' }).forceHttps).toBe(true); expect(deriveHttp({ FORCE_HTTPS: 'on' }).forceHttps).toBe(true); - expect(deriveHttp({ HSTS_INCLUDE_SUBDOMAINS: 'TRUE' }).hstsIncludeSubdomains).toBe(true); - expect(deriveHttp({ HSTS_INCLUDE_SUBDOMAINS: '1' }).hstsIncludeSubdomains).toBe(true); - expect(deriveHttp({ HSTS_INCLUDE_SUBDOMAINS: 'off' }).hstsIncludeSubdomains).toBe(false); + expect(deriveHttpBoot({ HSTS_INCLUDE_SUBDOMAINS: 'TRUE' }).hstsIncludeSubdomains).toBe(true); + expect(deriveHttpBoot({ HSTS_INCLUDE_SUBDOMAINS: '1' }).hstsIncludeSubdomains).toBe(true); + expect(deriveHttpBoot({ HSTS_INCLUDE_SUBDOMAINS: 'off' }).hstsIncludeSubdomains).toBe(false); }); it('COOKIE_SECURE is tri-state: explicit falsy disables, anything else auto-detects', () => { @@ -301,9 +302,9 @@ describe('deriveNet', () => { describe('derivePaths', () => { it('passes the path vars through raw — defaulting stays at the consumer', () => { expect(derivePaths({ TREK_WIKI_DIR: '/w' }).wikiDir).toBe('/w'); - expect(derivePaths({ TREK_PLACE_PHOTO_DIR: '/p' }).placePhotoDir).toBe('/p'); + expect(deriveStorage({ TREK_PLACE_PHOTO_DIR: '/p' }).placePhotoDir).toBe('/p'); expect(derivePaths({}).wikiDir).toBeUndefined(); - expect(derivePaths({}).placePhotoDir).toBeUndefined(); + expect(deriveStorage({}).placePhotoDir).toBeUndefined(); }); }); diff --git a/server/tests/unit/app-config/env-reference.test.ts b/server/tests/unit/app-config/env-reference.test.ts new file mode 100644 index 000000000..baae1f295 --- /dev/null +++ b/server/tests/unit/app-config/env-reference.test.ts @@ -0,0 +1,55 @@ +/** + * server/.env.example is the env-var reference (root CLAUDE.md), and the Zod + * schema in env.schema.ts is what the server actually validates. Nothing tied + * the two together, so about forty variables the server reads were missing + * from the reference. These cases fail on drift in either direction. + */ +import { describe, it, expect } from 'vitest'; +import fs from 'node:fs'; +import path from 'node:path'; +import { envSchema } from '../../../src/app-config/env.schema'; + +const ENV_EXAMPLE = path.join(__dirname, '..', '..', '..', '.env.example'); + +/** + * Schema entries an operator never sets, with the reason. Everything else in + * the schema has a line in .env.example, commented out when it is optional. + */ +const NOT_OPERATOR_SETTINGS: Record = { + PATH: 'the OS search path, validated only so the kitinerary probe can resolve its binary', + Path: 'the Windows spelling of PATH', + APP_VERSION: 'set by the image build; the VERSION file wins over it', + TREK_DB_FILE: 'points the Playwright harness at a throwaway database', +}; + +/** Every variable named on a `KEY=` line, set or commented out. */ +function documentedVariables(): Set { + const names = new Set(); + for (const line of fs.readFileSync(ENV_EXAMPLE, 'utf8').split(/\r?\n/)) { + const match = /^#?\s*([A-Za-z][A-Za-z0-9_]*)=/.exec(line); + if (match) names.add(match[1]); + } + return names; +} + +const schemaKeys = Object.keys(envSchema.shape); +const documented = documentedVariables(); + +describe('server/.env.example against the validated schema', () => { + it('ENV-REF-001: documents every variable the schema validates', () => { + const missing = schemaKeys.filter((key) => !documented.has(key) && !(key in NOT_OPERATOR_SETTINGS)); + expect(missing).toEqual([]); + }); + + it('ENV-REF-002: names no variable the server does not validate', () => { + const schema = new Set(schemaKeys); + expect([...documented].filter((key) => !schema.has(key))).toEqual([]); + }); + + it('ENV-REF-003: the exceptions are real schema entries that the reference leaves out', () => { + for (const key of Object.keys(NOT_OPERATOR_SETTINGS)) { + expect(schemaKeys).toContain(key); + expect(documented.has(key)).toBe(false); + } + }); +}); diff --git a/server/tests/unit/middleware/globalMiddleware.cors.test.ts b/server/tests/unit/middleware/globalMiddleware.cors.test.ts index 80561025f..12d7b26e0 100644 --- a/server/tests/unit/middleware/globalMiddleware.cors.test.ts +++ b/server/tests/unit/middleware/globalMiddleware.cors.test.ts @@ -2,7 +2,7 @@ import { describe, it, expect } from 'vitest'; import express, { type NextFunction, type Request, type Response } from 'express'; import request from 'supertest'; import { applyGlobalMiddleware } from '../../../src/middleware/globalMiddleware'; -import { readEnv } from '../../../src/app-config'; +import { httpConfig } from '../../../src/nest/app-config/tokens'; import { isSameHostOrigin } from '../../../src/nest/common/same-origin'; /** @@ -11,7 +11,16 @@ import { isSameHostOrigin } from '../../../src/nest/common/same-origin'; */ function appWithAllowlist(corsOrigins: string[] | null) { const app = express(); - applyGlobalMiddleware(app, { http: { ...readEnv().http, corsOrigins } }); + // The middleware reads ALLOWED_ORIGINS once, when it is applied. + const before = process.env.ALLOWED_ORIGINS; + if (corsOrigins) process.env.ALLOWED_ORIGINS = corsOrigins.join(','); + else delete process.env.ALLOWED_ORIGINS; + try { + applyGlobalMiddleware(app, { http: httpConfig() }); + } finally { + if (before === undefined) delete process.env.ALLOWED_ORIGINS; + else process.env.ALLOWED_ORIGINS = before; + } app.post('/api/auth/login', (_req, res) => res.json({ ok: true })); app.use((err: { statusCode?: number; message?: string }, _req: Request, res: Response, _next: NextFunction) => { const status = err.statusCode || 500; diff --git a/server/tests/unit/nest/app-config.test.ts b/server/tests/unit/nest/app-config.test.ts index bb06bd012..d97bacacc 100644 --- a/server/tests/unit/nest/app-config.test.ts +++ b/server/tests/unit/nest/app-config.test.ts @@ -6,7 +6,8 @@ import { ConfigService, ConfigType } from '@nestjs/config'; import { AppConfigModule } from '../../../src/nest/app-config/app-config.module'; import { RuntimeEnvService } from '../../../src/nest/app-config/runtime-env.service'; -import { httpConfig, mcpConfig, BOOT_STABLE_TOKENS } from '../../../src/nest/app-config/tokens'; +import { httpConfig, storageConfig, BOOT_STABLE_TOKENS } from '../../../src/nest/app-config/tokens'; +import { DataPathsService } from '../../../src/nest/app-config/data-paths.service'; describe('RuntimeEnvService', () => { const service = new RuntimeEnvService(); @@ -38,15 +39,15 @@ describe('RuntimeEnvService', () => { describe('boot-stable tokens', () => { it('factories re-derive from the current env on each invocation', () => { - const prev = process.env.FORCE_HTTPS; + const prev = process.env.HSTS_INCLUDE_SUBDOMAINS; try { - process.env.FORCE_HTTPS = 'on'; - expect(httpConfig().forceHttps).toBe(true); - process.env.FORCE_HTTPS = 'off'; - expect(httpConfig().forceHttps).toBe(false); + process.env.HSTS_INCLUDE_SUBDOMAINS = 'on'; + expect(httpConfig().hstsIncludeSubdomains).toBe(true); + process.env.HSTS_INCLUDE_SUBDOMAINS = 'off'; + expect(httpConfig().hstsIncludeSubdomains).toBe(false); } finally { - if (prev === undefined) delete process.env.FORCE_HTTPS; - else process.env.FORCE_HTTPS = prev; + if (prev === undefined) delete process.env.HSTS_INCLUDE_SUBDOMAINS; + else process.env.HSTS_INCLUDE_SUBDOMAINS = prev; } }); @@ -58,14 +59,20 @@ describe('boot-stable tokens', () => { }); describe('AppConfigModule', () => { - it('provides ConfigService, RuntimeEnvService and the loaded namespaces', async () => { + it('provides ConfigService, RuntimeEnvService, DataPathsService and the loaded namespaces', async () => { + const prev = process.env.TREK_PLACE_PHOTO_DIR; + process.env.TREK_PLACE_PHOTO_DIR = '/srv/place-photos'; const moduleRef = await Test.createTestingModule({ imports: [AppConfigModule] }).compile(); + if (prev === undefined) delete process.env.TREK_PLACE_PHOTO_DIR; + else process.env.TREK_PLACE_PHOTO_DIR = prev; try { const config = moduleRef.get(ConfigService); const runtime = moduleRef.get(RuntimeEnvService); - const mcp = moduleRef.get>(mcpConfig.KEY); + const storage = moduleRef.get>(storageConfig.KEY); expect(runtime).toBeInstanceOf(RuntimeEnvService); - expect(mcp.rateLimitMax).toBe(300); + expect(moduleRef.get(DataPathsService)).toBeInstanceOf(DataPathsService); + // A snapshot taken when the module was built, not a live read. + expect(storage.placePhotoDir).toBe('/srv/place-photos'); // Plain get() falls through to live process.env (cache: false). expect(config.get('NODE_ENV')).toBe('test'); } finally { diff --git a/server/tests/unit/nest/storage/storage-admin.service.test.ts b/server/tests/unit/nest/storage/storage-admin.service.test.ts index 30c0f7e8a..72cba1f03 100644 --- a/server/tests/unit/nest/storage/storage-admin.service.test.ts +++ b/server/tests/unit/nest/storage/storage-admin.service.test.ts @@ -15,7 +15,6 @@ import os from 'node:os'; import path from 'node:path'; import { Logger } from '@nestjs/common'; import { MASKED_SETTING_VALUE, type StorageConfig } from '@trek/shared'; -import type { RuntimeEnvService } from '../../../../src/nest/app-config/runtime-env.service'; import { encrypt_api_key } from '../../../../src/nest/common/crypto/apiKeyCrypto'; import { StorageAdminService } from '../../../../src/nest/storage/storage-admin.service'; import { StorageEventsService } from '../../../../src/nest/storage/storage-events.service'; @@ -55,7 +54,7 @@ const S3_OPTIONS = { async function makeService(opts: { uploadsRoot?: string } = {}) { const uploadsRoot = opts.uploadsRoot ?? makeTmpDir(); setSetting(BACKENDS_KEY, JSON.stringify([{ name: 'uploads-local', type: 'local', options: { root: uploadsRoot } }])); - const env = { env: () => ({ paths: {} }) } as unknown as RuntimeEnvService; + const env = { placePhotoDir: undefined }; const uow = await createTestUnitOfWork(testDb); const appSettings = await createTestAppSettingsRepo(testDb); const registry = new StorageRegistryService( diff --git a/server/tests/unit/nest/storage/storage-jobs.service.test.ts b/server/tests/unit/nest/storage/storage-jobs.service.test.ts index 6c6f47f2e..0378df6d0 100644 --- a/server/tests/unit/nest/storage/storage-jobs.service.test.ts +++ b/server/tests/unit/nest/storage/storage-jobs.service.test.ts @@ -15,7 +15,6 @@ import os from 'node:os'; import path from 'node:path'; import { Readable } from 'node:stream'; import { Logger } from '@nestjs/common'; -import type { RuntimeEnvService } from '../../../../src/nest/app-config/runtime-env.service'; import { MirrorDriver } from '../../../../src/nest/storage/drivers/mirror.driver'; import { StorageEventsService } from '../../../../src/nest/storage/storage-events.service'; import { CATEGORIES_KEY, StorageRegistryService } from '../../../../src/nest/storage/storage-registry.service'; @@ -61,7 +60,7 @@ async function makeWorld() { ]), ); setSetting('storage.categories', JSON.stringify({ backups: 'm' })); - const env = { env: () => ({ paths: {} }) } as unknown as RuntimeEnvService; + const env = { placePhotoDir: undefined }; const registry = new StorageRegistryService( await createTestAppSettingsRepo(testDb), env, @@ -97,7 +96,7 @@ async function makeMigrationWorld() { ]), ); setSetting('storage.categories', JSON.stringify({ files: 'uploads-local' })); - const env = { env: () => ({ paths: {} }) } as unknown as RuntimeEnvService; + const env = { placePhotoDir: undefined }; const registry = new StorageRegistryService( await createTestAppSettingsRepo(testDb), env, @@ -130,7 +129,7 @@ async function makePhotosGoogleMigrationWorld() { { name: 'dest-local', type: 'local', options: { root: destRoot } }, ]), ); - const env = { env: () => ({ paths: { placePhotoDir: placePhotoRoot } }) } as unknown as RuntimeEnvService; + const env = { placePhotoDir: placePhotoRoot }; const registry = new StorageRegistryService( await createTestAppSettingsRepo(testDb), env, @@ -161,7 +160,7 @@ async function makeMigrationBackfillWorld() { ]), ); setSetting('storage.categories', JSON.stringify({ backups: 'm', files: 'uploads-local' })); - const env = { env: () => ({ paths: {} }) } as unknown as RuntimeEnvService; + const env = { placePhotoDir: undefined }; const registry = new StorageRegistryService( await createTestAppSettingsRepo(testDb), env, @@ -543,7 +542,7 @@ describe('StorageJobsService.cancelJobsForMissingBackends', () => { ]), ); setSetting('storage.categories', JSON.stringify({ files: 'nas' })); - const env = { env: () => ({ paths: {} }) } as unknown as RuntimeEnvService; + const env = { placePhotoDir: undefined }; const registry = new StorageRegistryService( await createTestAppSettingsRepo(testDb), env, diff --git a/server/tests/unit/nest/storage/storage-registry.service.test.ts b/server/tests/unit/nest/storage/storage-registry.service.test.ts index 00c6f45a2..81c2a003b 100644 --- a/server/tests/unit/nest/storage/storage-registry.service.test.ts +++ b/server/tests/unit/nest/storage/storage-registry.service.test.ts @@ -19,7 +19,6 @@ import fs from 'node:fs'; import os from 'node:os'; import path from 'node:path'; import { Readable } from 'node:stream'; -import type { RuntimeEnvService } from '../../../../src/nest/app-config/runtime-env.service'; import { encrypt_api_key } from '../../../../src/nest/common/crypto/apiKeyCrypto'; import { StorageEventsService } from '../../../../src/nest/storage/storage-events.service'; import { StorageRegistryService } from '../../../../src/nest/storage/storage-registry.service'; @@ -49,11 +48,8 @@ interface EnvPaths { placePhotoDir?: string; } -function makeEnvStub(initial: EnvPaths): { env: RuntimeEnvService } { - const paths = initial; - return { - env: { env: () => ({ paths }) } as unknown as RuntimeEnvService, - }; +function makeEnvStub(initial: EnvPaths): { env: { placePhotoDir: string | undefined } } { + return { env: { placePhotoDir: initial.placePhotoDir } }; } function setSetting(key: string, value: string): void { diff --git a/server/tests/unit/nest/storage/storage-stats.service.test.ts b/server/tests/unit/nest/storage/storage-stats.service.test.ts index bc8cb0356..a6bcf371a 100644 --- a/server/tests/unit/nest/storage/storage-stats.service.test.ts +++ b/server/tests/unit/nest/storage/storage-stats.service.test.ts @@ -14,7 +14,6 @@ import fs from 'node:fs'; import os from 'node:os'; import path from 'node:path'; import { Readable } from 'node:stream'; -import type { RuntimeEnvService } from '../../../../src/nest/app-config/runtime-env.service'; import { StorageEventsService } from '../../../../src/nest/storage/storage-events.service'; import { StorageRegistryService } from '../../../../src/nest/storage/storage-registry.service'; import { StorageService } from '../../../../src/nest/storage/storage.service'; @@ -48,7 +47,7 @@ async function makeWorld() { { name: 'backups-local', type: 'local', options: { root: backupsRoot } }, ]), ); - const env = { env: () => ({ paths: {} }) } as unknown as RuntimeEnvService; + const env = { placePhotoDir: undefined }; const appSettings = await createTestAppSettingsRepo(testDb); const registry = new StorageRegistryService( appSettings,