feat(config): mark an install as centrally administered

Some installs are run by somebody other than the person who administers them.
The operator owns the credentials, the configuration and the upgrade schedule,
and the admin of the instance is a user of the result rather than the one who
set it up. Nothing in the app knows that today, so it keeps offering settings
whose values are not the admin's to change, and the honest answer to half of
them would be a 403 the UI never anticipated.

TREK_MANAGED says it once. It is a single boolean and the surfaces that care
read it themselves, so adding one never comes back to the config layer.

Runtime-toggled, in the same class as DEMO_MODE, rather than a registerAs
token: roughly sixty tests mutate env mid-lifetime, and a value frozen per
built app breaks all of them. `=== true` on the way in, so an unset, empty or
misspelled value means off — a managed install sets it deliberately, and a typo
must not quietly take settings away from an admin who never asked for it.

The guard keys on a decorator, not on a path. MfaPolicyGuard documents where
the two literal path lists it replaced ended up: they stopped being maintained,
and every endpoint added afterwards silently fell on the wrong side. A marker
on the handler cannot drift away from the handler. It carries a mandatory
reason, which is for the next reader of the source rather than for the client,
so the marks stay auditable.

It registers third, after the auth and MFA guards, so a stranger still gets the
401 those two would have given them instead of a 403 that would confirm the
route exists. And it checks the mode before it touches metadata, because it
runs on every request of every install and almost all of them are self-hosted.

One 403 body, shared by REST and MCP. DEMO_MODE grew two texts for the same
condition and neither can be changed now without hunting for the other.

The flag reaches the client through app-config so the UI can stop offering what
the server would refuse anyway, but it is deliberately not persisted the way
demo_mode is: two installs can share a browser profile, and a stale "this one
is managed" would take settings away on an install that never set it.

No route carries the marker yet. The per-domain marks follow. Unset, which is
every self-hosted install, nothing about this changes anything.
This commit is contained in:
Maurice
2026-08-15 11:41:19 +02:00
committed by Maurice
parent c9193e0621
commit bfb3bcd63c
18 changed files with 352 additions and 3 deletions
+1 -1
View File
@@ -69,7 +69,7 @@ override these set them at file top, before the SUT import.)
**Runtime-toggled** (read live on every access via `readEnv()` /
`RuntimeEnvService`; tests mutate these mid-lifetime):
DEMO_MODE, NODE_ENV, APP_VERSION, APP_URL, TREK_API_DOCS_ENABLED,
TREK_MANAGED, DEMO_MODE, NODE_ENV, APP_VERSION, APP_URL, TREK_API_DOCS_ENABLED,
TREK_PLUGINS_ENABLED / _DEV_LINK / _DIR / _DATA_DIR / TREK_PLUGIN_PERMISSIONS,
OIDC_*, SMTP_*, FORCE_HTTPS, COOKIE_SECURE, HSTS_INCLUDE_SUBDOMAINS,
ALLOWED_ORIGINS, UNSPLASH_ACCESS_KEY, WEBAUTHN_*, TZ, ADMIN_EMAIL,
+19
View File
@@ -102,6 +102,24 @@ export function deriveSession(raw: RawEnv) {
};
}
/**
* Whether this instance is centrally administered: somebody other than its
* admin user owns the configuration, the credentials and the upgrade schedule.
*
* Only a boolean, on purpose. It answers "who configures this install", and the
* surfaces that care read it themselves rather than being listed here, so adding
* one never touches this file.
*
* `=== true` so an unset, empty or unparseable value means off. A managed
* install sets it deliberately; nothing should be able to switch it on by
* accident, and a typo must not silently take settings away from an admin.
*/
export function deriveManaged(raw: RawEnv) {
return {
enabled: parseBool(raw.TREK_MANAGED) === true,
};
}
export function deriveDemo(raw: RawEnv) {
return {
enabled: parseBool(raw.DEMO_MODE) === true,
@@ -236,6 +254,7 @@ export function deriveAll(raw: RawEnv) {
app: deriveApp(raw),
http: deriveHttp(raw),
session: deriveSession(raw),
managed: deriveManaged(raw),
demo: deriveDemo(raw),
adminBootstrap: deriveAdminBootstrap(raw),
oidc: deriveOidc(raw),
+1
View File
@@ -130,6 +130,7 @@ export const envSchema = z.object({
// Admin / demo
ADMIN_EMAIL: anyString,
ADMIN_PASSWORD: anyString,
TREK_MANAGED: boolStr,
DEMO_MODE: boolStr,
DEMO_ADMIN_USER: anyString,
DEMO_ADMIN_EMAIL: anyString,
+1
View File
@@ -6,6 +6,7 @@ export {
deriveApp,
deriveHttp,
deriveSession,
deriveManaged,
deriveDemo,
deriveAdminBootstrap,
deriveOidc,
@@ -21,6 +21,14 @@ export class RuntimeEnvService {
return readEnv().demo.enabled;
}
/**
* True when somebody other than this instance's admin owns its configuration.
* Runtime-toggled like DEMO_MODE, so never cache the result in a field.
*/
isManaged(): boolean {
return readEnv().managed.enabled;
}
/** True only under exactly NODE_ENV='test' (case-sensitive, like the :memory: DB pick). */
isTest(): boolean {
return readEnv().app.isTest;
+5
View File
@@ -9,6 +9,7 @@ import { PlatformModule } from './platform/platform.module';
import { McpTransportModule } from './mcp-transport/mcp-transport.module';
import { GlobalAuthGuard } from './auth/global-auth.guard';
import { MfaPolicyGuard } from './auth/mfa-policy.guard';
import { ManagedGuard } from './common/managed.guard';
import { WeatherModule } from './weather/weather.module';
import { HelpModule } from './help/help.module';
import { AirportsModule } from './airports/airports.module';
@@ -81,6 +82,10 @@ import { RealtimeGatewayModule } from './realtime/realtime-gateway.module';
// instead of verifying the token a second time, which is what the Express
// middleware it replaces did on every /api request.
{ provide: APP_GUARD, useClass: MfaPolicyGuard },
// Third, and only third: a stranger gets the 401 the two above would have
// given them rather than a 403 that confirms the route exists. Inert unless
// the instance is centrally administered AND the route carries the marker.
{ provide: APP_GUARD, useClass: ManagedGuard },
// Global error-envelope normaliser (DI-registered so it also catches
// framework-level exceptions like the not-found handler).
{ provide: APP_FILTER, useClass: TrekExceptionFilter },
+5
View File
@@ -280,6 +280,11 @@ export class AuthService {
oidc_display_name: oidcConfigured ? (oidcDisplayName || 'SSO') : undefined,
require_mfa: requireMfaRow?.value === 'true',
allowed_file_types: this.db.get<{ value: string }>("SELECT value FROM app_settings WHERE key = 'allowed_file_types'")?.value || 'jpg,jpeg,png,gif,webp,heic,pdf,doc,docx,xls,xlsx,txt,csv',
// Whether the configuration belongs to whoever operates this install
// rather than to its admin. The client uses it to stop offering settings
// the server would refuse anyway — it is an honesty flag for the UI, never
// the boundary itself, which is the guard and the operator's network.
managed: readEnv().managed.enabled,
demo_mode: isDemo,
demo_email: isDemo ? DEMO_EMAIL_PRIMARY : undefined,
demo_password: isDemo ? 'demo12345' : undefined,
+42
View File
@@ -0,0 +1,42 @@
import { CanActivate, ExecutionContext, HttpException, Injectable } from '@nestjs/common';
import { Reflector } from '@nestjs/core';
import { RuntimeEnvService } from '../app-config/runtime-env.service';
import { MANAGED_FORBIDDEN, MANAGED_FORBIDDEN_ERROR } from './managed';
/**
* Refuses the routes a centrally administered instance does not hand to its own
* admin: the ones whose value comes from whoever operates the install.
*
* Registered as the third APP_GUARD, after GlobalAuthGuard and MfaPolicyGuard.
* The order is the whole point — a stranger has to get the 401 the other two
* would have given them, not a 403 that confirms the route exists and tells them
* something about how this install is run.
*
* Marked routes only. An unmarked route is untouched in every mode, so the
* guard is inert on a self-hosted install and stays that way even if somebody
* sets the flag there.
*
* Explicitly not a path list. `MfaPolicyGuard` documents where the two literal
* path lists it replaced ended up: they stopped being maintained, and every
* endpoint added afterwards silently fell on the wrong side. A decorator lives
* on the handler it describes and cannot drift away from it.
*/
@Injectable()
export class ManagedGuard implements CanActivate {
constructor(
private readonly env: RuntimeEnvService,
private readonly reflector: Reflector,
) {}
canActivate(context: ExecutionContext): boolean {
if (!this.env.isManaged()) return true;
const marked = this.reflector.getAllAndOverride(MANAGED_FORBIDDEN, [
context.getHandler(),
context.getClass(),
]);
if (!marked) return true;
throw new HttpException(MANAGED_FORBIDDEN_ERROR, 403);
}
}
+44
View File
@@ -0,0 +1,44 @@
import { SetMetadata } from '@nestjs/common';
import { RuntimeEnvService } from '../app-config/runtime-env.service';
/** Metadata key `@ManagedForbidden()` writes. */
export const MANAGED_FORBIDDEN = 'trek:managed-forbidden';
/**
* The one 403 body a managed instance returns, shared by REST and MCP.
*
* Deliberately a single constant rather than a per-route message. DEMO_MODE grew
* two texts for the same condition — 'Uploads are disabled in demo mode. Self-host
* TREK for full functionality.' on REST and 'Write operations are disabled in demo
* mode.' on MCP — and now neither can be changed without hunting for the other.
*
* It says who owns the setting and stops there. A caller learns that the value is
* not theirs to change, which is all they can act on; the reason belongs to
* whoever runs the install, not in an API response.
*/
export const MANAGED_FORBIDDEN_ERROR = {
error: 'This is configured by the operator of this instance.',
code: 'MANAGED_FORBIDDEN',
} as const;
/**
* Marks a route as unavailable while the instance is centrally administered.
*
* The reason is mandatory and is for the next reader of the source, not for the
* client: it records why this particular surface cannot be left to the instance
* admin. Without it the marks turn into a list nobody can audit, which is how
* the path lists this codebase has already replaced once went stale.
*/
export const ManagedForbidden = (reason: string) => SetMetadata(MANAGED_FORBIDDEN, { reason });
/**
* The handler-side flavour of the guard below.
*
* Needed because a guard throws before the multipart parser has drained the
* request body, which leaves the client with an ECONNRESET instead of the 403
* (PROFILE-015, and the reason `isDemoWriteBlocked` is a function too). Upload
* routes call this after the interceptor instead of carrying the decorator.
*/
export function isManagedBlocked(env: RuntimeEnvService): boolean {
return env.isManaged();
}