feat(config): put the operator-owned surfaces behind TREK_MANAGED (#1946)

* feat(config): put the operator-owned surfaces behind TREK_MANAGED

The switch landed last release with nothing behind it. This is what it turns
off, plus the four fixes that came out of walking every one of these surfaces.

Nothing here changes anything for an install that does not set the flag. That
is not a hope, it is what managed-inert.test.ts asserts: the mode stays off for
any unparseable value, no other variable can turn it on, every settings key
stays writable, and splitManagedKeys hands back the same object rather than a
copy so no write path can quietly diverge on self-hosted installs only.

WHAT THE MODE WITHHOLDS

Fourteen routes carry @ManagedForbidden: key validation, static MCP tokens, JWT
rotation, the OIDC admin pair, restore and auto-backup, plugin sideload and
reload, the Ollama model list and pull, and the SMTP test send. Each names the
reason it is not the instance admin's, and the reason is mandatory.

Eighteen settings keys are filtered instead of refused. SMTP, the OIDC toggles
and the WebAuthn pair share one handler with keys the admin does own, and the
llm_* family is reachable through per-user settings, the instance defaults and
the addon config alike, so a route-level refusal would be both too coarse and
incomplete. A locked key is skipped and reported as managed_keys; the rest of
the save goes through. Refusing the request would take the registration toggles
down with the SMTP block.

GET /api/auth/me/settings stops returning the three API keys in the clear. It
is the only endpoint that decrypts a stored credential back to the caller, which
is fine when the admin pasted it in and wrong when the operator supplied it.

Two multipart routes check in the handler rather than the guard: a guard throws
before the parser drains the body and the client gets an ECONNRESET instead of
the 403 (PROFILE-015). They still carry the marker so the boot gate sees them.

WHAT KEEPS IT FROM DRIFTING

validate-managed-routes.ts refuses to boot on a marking that is not on the
reviewed list, a list entry whose route lost its marking, or a marking with no
reason. The third case has no equivalent in the guard gate next door and is the
one that matters most: a blank reason destroys the only record of why a control
was taken away, and nothing recovers that later. It found two wrong entries in
my own list while I was writing this.

managed-keys.test.ts asserts that every key in ADMIN_SETTINGS_KEYS and
DEFAULTABLE_USER_SETTING_KEYS belongs to exactly one of two sets. A key added to
either list belongs to neither until somebody decides, and that is the failure
this prevents: the lists grow, the mode does not.

PLACES_API_BASE AND PLACES_API_KEY

The nine Places endpoints spell out googleapis.com, so an install that wants
those calls to leave through something of its own has no way to say so. One
variable, substituted where every call already funnels through. A second one
supplies the key, and when it is set the users table is not consulted at all —
a per-user key would route around whatever the endpoint counts, and those
columns are readable by any admin of the instance.

FOUR FIXES THAT ARE NOT ABOUT THE MODE

An admin setting somebody's password now bumps password_version and clears
their MCP tokens. An admin sets a password for one reason, and until now
verifyJwtAndLoadUser kept accepting every cookie the intruder already had: the
one action taken to lock them out was the one action that did not.

The four OIDC provider calls go through the SSRF guard. Three are worse than
they look — the token, userinfo and JWKS URLs come out of the discovery
response, so they are chosen by the other end, not by an admin. safeFetchLlm is
renamed safeFetchAdminConfigured and keeps its old name as an alias, because it
is the variant that allows loopback and LAN: a self-hoster with Authentik on
localhost:9000 must keep working. The token exchange follows no redirect at all,
since one would hand client_secret to a second host.

DELETE /api/admin/users/:id/mfa clears another account's TOTP. The passkey half
has existed since passkeys landed; the TOTP half never did, which left
"somebody on the trip lost their phone" with no answer short of an operator in
the database. Never for the caller themselves.

TREK_PLUGIN_PERMISSIONS=off refuses to boot when the install is centrally
administered. A warning is right for a machine its owner chose to trust; where
the person who set the flag and the people whose data is in the database are
not the same person, fail closed.

TEXTS

Four strings lose the phrase "self-hosted" because they describe somebody
else's software — an Ollama endpoint, an AirTrail instance, a service a plugin
talks to — and read better without it in both modes. The one string that
describes TREK itself keeps it, and the mode picks a second key instead, so
self-hosters lose nothing.

A grep gate in shared/ keeps the canonical locale honest, because the parity
check compares the file set and the top-level keys and never looks at a value:
re-wording a string is invisible to CI today, and so is putting it back.

* feat(maps): supply the map credential with the instance when centrally administered

MAPBOX_ACCESS_TOKEN joins PLACES_API_KEY as an operator-supplied value.
SettingsService injects it when the settings are read, and picks GL as the
provider if the reader is still on Leaflet, since a token is always present.

The key moves from the customer set to the locked set. It is the one locked key
whose value is public by design — a pk.* token has to reach the browser to be
useful — so this is not about secrecy: a per-user save landing on top of the
instance token would only break the map for that user. Both settings fields for
it go away with it.

* fix(auth): count the operator key when reporting whether Google features work

has_maps_key only looked at the users table, but getMapsKey prefers the
PLACES_API_KEY env over anything stored there. On an install that supplies the
key that way and has an empty column, every lookup worked while the client was
told there was no key and hid the search, the autocomplete and the place photos.

Found by walking the running instance rather than the code: the map came up,
the search box did not.

* feat(admin): hide the settings a centrally administered install cannot act on

A control that answers 403 is worse than no control: the AI section rendered the
refusal as "Request failed with status code 403", which tells an admin they broke
something rather than that the decision is not theirs.

So the surfaces go rather than being disabled in place:

- AI parsing and AirTrail leave the addon list, and the AI addon route now
  refuses outright. The endpoint, the model and what a document costs come with
  the instance, so there is no instance decision left — not even whether it runs.
- Immich and Synology Photos leave it too. Both connect to a server the reader
  runs at home, and there is no route from here to one.
- The SMTP block, the admin webhook and ntfy targets, and the passkey RP ID and
  origins follow the same rule: they configure something the operator owns, and
  a wrong RP ID on a shared parent domain reaches past this instance entirely.
- The About tab goes. It is about the project — what TREK is, where to file a
  bug, where to support it — and is aimed at the person running the software.
  The version and the link to the source move to the sidebar footer, on both the
  desktop page and the mobile twin, because AGPL 13 wants that offer wherever
  people reach the software over a network.
- The update check stops asking GitHub and reports nothing available.

Separately, the version footers lose the "self-hosted" suffix everywhere, not
just here. It read as a label on the software rather than on the install, and
the version alone says what it needs to.

* feat(config): refuse to boot centrally administered without an at-rest key

Measured on a running instance rather than assumed: with ENCRYPTION_KEY unset,
the at-rest key falls back to a file in the data volume, and backupService
bundles that file into every archive it builds. The archive is downloadable by
any instance admin, so the encryption ships with its own key in the same zip.

The skip in backupService already handles this — it only omits the file when the
key came from the env — but nothing made sure the env actually carried one.
Provisioning sets it; forgetting it was silent.

validateEnvAtBoot now carries a second kind of check next to the schema: cross-
field rules that only apply with the flag set, for combinations where every value
is individually valid and the result is wrong. Empty without the flag, so an
install that never asked to be centrally administered cannot meet it.

* feat(client): add an attachment point for install-specific screens

Two empty exports on the client, an empty module on the server, and the four
places that read them. Nothing here adds a route, a nav entry or an endpoint —
the arrays are empty and the module contributes nothing, which managed-ext.test
pins so it stays that way.

Read unconditionally, never behind a flag. On the server a conditional import
would tie the module graph to an environment variable, and the graph is built
once per app while the flag is read live; on the client an empty array costs
nothing to spread, so every build walks the same path instead of one build
walking a path nobody tests.

Anything attached here follows the same rules as the rest of src/nest and
src/components: a real module with a controller and a provider, bodies through
the Zod pipe, routes under the global guards, tests.

* test(shared): move the wording gate out of src so shared typechecks again

CI installs shared with its own dependencies only (npm ci --workspace shared),
so there is no @types/node and the `node:fs` import inside src/ failed to
compile. The tests passed the whole time — vitest supplies the module — which is
why this only showed up in the typecheck step.

The walk moves to scripts/, next to i18n-parity.mjs, and the spec imports it the
same way that one does. It also runs on its own now
(`node scripts/i18n-selfhost-wording.mjs`), which is what you want when CI names
a line you have to go find.

* test(server): repair the call sites typecheck:tests caught

tests/ sits outside the build tsconfig, so none of this showed up in a green
test run — which is exactly the gap `npm run typecheck:tests` exists to close.
Three kinds, all mine:

- Seven `import type` paths for RuntimeEnvService carried one `../` too many.
  Type-only imports are erased, so vitest never resolved them and nothing failed.
- VersionCheckJob and PluginsController grew a constructor parameter and eleven
  hand-wired `new` calls kept passing the old count. The argument arrived as
  undefined and no assertion happened to read it.
- ConditionContext grew `managed`, and the shared context object in the
  conditions suite did not.

The condition also had no test of its own, so it has one now: both directions,
since the registry uses `is: false` to keep a notice away and a notice that only
belongs on a centrally administered install would use `is: true`.
This commit is contained in:
Maurice
2026-08-15 16:42:27 +02:00
committed by GitHub
parent bfb3bcd63c
commit 3a0604b3f5
108 changed files with 1926 additions and 111 deletions
+10 -4
View File
@@ -31,12 +31,18 @@ export class ManagedGuard implements CanActivate {
canActivate(context: ExecutionContext): boolean {
if (!this.env.isManaged()) return true;
const marked = this.reflector.getAllAndOverride(MANAGED_FORBIDDEN, [
context.getHandler(),
context.getClass(),
]);
const marked = this.reflector.getAllAndOverride<{ enforcedInHandler?: boolean } | undefined>(
MANAGED_FORBIDDEN,
[context.getHandler(), context.getClass()],
);
if (!marked) return true;
// A multipart handler checks for itself, after the interceptor has drained
// the upload. Throwing here would leave the body unread and the client would
// see an ECONNRESET rather than the 403 (PROFILE-015). The marker still sits
// on the route so the boot gate can inventory it.
if (marked.enforcedInHandler) return true;
throw new HttpException(MANAGED_FORBIDDEN_ERROR, 403);
}
}
+127 -1
View File
@@ -28,8 +28,15 @@ export const MANAGED_FORBIDDEN_ERROR = {
* 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.
*
* `enforcedInHandler` is for multipart routes. A guard throws before the parser
* has drained the body and the client gets an ECONNRESET instead of the 403
* (PROFILE-015), so those handlers call `isManagedBlocked` themselves. They
* still carry the marker, because the boot gate inventories markers and a route
* missing from that inventory is exactly what nobody notices.
*/
export const ManagedForbidden = (reason: string) => SetMetadata(MANAGED_FORBIDDEN, { reason });
export const ManagedForbidden = (reason: string, opts?: { enforcedInHandler?: true }) =>
SetMetadata(MANAGED_FORBIDDEN, { reason, enforcedInHandler: opts?.enforcedInHandler === true });
/**
* The handler-side flavour of the guard below.
@@ -42,3 +49,122 @@ export const ManagedForbidden = (reason: string) => SetMetadata(MANAGED_FORBIDDE
export function isManagedBlocked(env: RuntimeEnvService): boolean {
return env.isManaged();
}
/**
* The settings a centrally administered install does not hand to its admin,
* because the value belongs to whoever operates it.
*
* One list rather than a condition repeated at each write path. Several of
* these are reachable through more than one route — the SMTP block and the
* WebAuthn pair share a handler with keys the admin does own, and the llm_*
* family is writable through per-user settings, the instance defaults and the
* addon config alike — so a route-level refusal would be both too coarse and
* incomplete.
*
* The three users-table columns are in here too. They are not settings keys,
* but the filter matches on name and they are the same kind of value, so
* splitting them into a second mechanism would only mean two things to forget.
*
* mapbox_access_token is in here for the same reason as the rest, though it is
* the one that reaches the browser: a managed instance ships with the operator's
* public pk.* token, injected when the settings are read, and a per-user value
* saved over it would only break the map for that user.
*/
export const MANAGED_LOCKED_SETTING_KEYS = [
'llm_api_key',
'llm_base_url',
'llm_model',
'llm_multimodal',
'llm_provider',
'mapbox_access_token',
'maps_api_key',
'oidc_login',
'oidc_registration',
'openweather_api_key',
'smtp_from',
'smtp_host',
'smtp_pass',
'smtp_port',
'smtp_skip_tls_verify',
'smtp_user',
'unsplash_api_key',
'webauthn_origins',
'webauthn_rp_id',
] as const;
/**
* The locked names that are columns on `users` rather than settings keys, so
* the assignment test can tell "deliberately outside both source lists" from
* "somebody removed a key and left the assignment behind".
*/
export const MANAGED_LOCKED_PROFILE_KEYS = [
'maps_api_key',
'openweather_api_key',
'unsplash_api_key',
] as const;
/**
* The settings that stay with the instance admin in every mode.
*
* Listed explicitly rather than derived as "everything not locked", so that a
* key added to either source list belongs to neither set until somebody
* decides. That is what MANAGED-KEYS-001 checks, and it is the only mechanism
* here that still works a year from now.
*/
export const MANAGED_CUSTOMER_KEYS = [
'admin_ntfy_server',
'admin_ntfy_token',
'admin_ntfy_topic',
'admin_webhook_url',
'allow_registration',
'allowed_file_types',
'blur_booking_codes',
'dark_mode',
'default_currency',
'distance_unit',
'map_provider',
'map_tile_url',
'mapbox_3d_enabled',
'mapbox_quality_mode',
'mapbox_style',
'maplibre_style',
'notification_channels',
'notify_trip_reminder',
'passkey_login',
'password_login',
'password_registration',
'require_mfa',
'temperature_unit',
'time_format',
] as const;
const LOCKED = new Set<string>(MANAGED_LOCKED_SETTING_KEYS);
/** Whether this single key is the operator's to set. */
export function isManagedLockedKey(key: string): boolean {
return LOCKED.has(key);
}
/**
* Splits a write body into what the caller may set and what the operator owns.
*
* Reports the blocked names instead of throwing, and that is the whole point:
* the admin settings tab saves SMTP and the registration toggles in one
* request, so refusing the request would take the toggles away with the SMTP
* block. The caller keeps working, the locked values keep their stored value,
* and the response says which names were skipped.
*/
export function splitManagedKeys<T extends Record<string, unknown>>(
body: T,
managed: boolean,
): { allowed: Partial<T>; blocked: string[] } {
if (!managed) return { allowed: body, blocked: [] };
const allowed: Partial<T> = {};
const blocked: string[] = [];
for (const [key, value] of Object.entries(body)) {
if (LOCKED.has(key)) blocked.push(key);
else (allowed as Record<string, unknown>)[key] = value;
}
return { allowed, blocked: blocked.sort() };
}
@@ -0,0 +1,127 @@
import { METHOD_METADATA } from '@nestjs/common/constants';
import { ModulesContainer } from '@nestjs/core';
import type { INestApplication } from '@nestjs/common';
import { MANAGED_FORBIDDEN } from './managed';
export interface ManagedRouteEntry {
/** `ControllerClass.methodName` */
id: string;
/** Why this surface is not the instance admin's, for the next reader. */
reason: string;
/** Multipart routes refuse inside the handler; the guard steps aside for them. */
enforcedInHandler: boolean;
}
/**
* Collects every route marked with `@ManagedForbidden`.
*
* Same walk as `collectRouteGuards`, and deliberately so: a route is anything
* carrying an HTTP method decorator, and metadata is read from the handler with
* the class as fallback.
*/
export function collectManagedRoutes(app: INestApplication): ManagedRouteEntry[] {
const container = app.get(ModulesContainer, { strict: false });
const entries: ManagedRouteEntry[] = [];
for (const module of container.values()) {
for (const wrapper of module.controllers.values()) {
const ctor = wrapper.metatype as (new (...args: never[]) => object) | undefined;
if (!ctor?.prototype) continue;
const classMark = Reflect.getMetadata(MANAGED_FORBIDDEN, ctor) as
| { reason?: string; enforcedInHandler?: boolean }
| undefined;
for (const name of Object.getOwnPropertyNames(ctor.prototype)) {
if (name === 'constructor') continue;
const handler = (ctor.prototype as Record<string, unknown>)[name];
if (typeof handler !== 'function') continue;
if (Reflect.getMetadata(METHOD_METADATA, handler) === undefined) continue;
const mark =
(Reflect.getMetadata(MANAGED_FORBIDDEN, handler) as typeof classMark) ?? classMark;
if (!mark) continue;
entries.push({
id: `${ctor.name}.${name}`,
reason: mark.reason ?? '',
enforcedInHandler: mark.enforcedInHandler === true,
});
}
}
}
return entries.sort((a, b) => a.id.localeCompare(b.id));
}
/**
* The surfaces a centrally administered install withholds from its own admin.
*
* Reviewed as a list on purpose, exactly like the anonymous-route list next
* door. Each entry takes a control away from somebody who would have it on a
* self-hosted install, so a diff that grows this list is a diff that narrows
* what a customer may do, and that should never happen by accident.
*
* Entries are `ControllerClass.methodName`. Sorted, no duplicates.
*/
export const MANAGED_ROUTE_ALLOW_LIST: string[] = [
'AdminController.rotateJwtSecret',
'AdminOidcController.get',
'AdminOidcController.update',
'AuthController.createMcpToken',
'AuthController.validateKeys',
'BackupController.restore',
'BackupController.updateAutoSettings',
'BackupController.uploadRestore',
'LlmLocalController.models',
'LlmLocalController.pull',
'NotificationsController.testSmtp',
'PluginsController.link',
'PluginsController.reload',
'PluginsController.upload',
];
/**
* Throws when a route carries `@ManagedForbidden` without being listed above,
* when a listed route no longer carries it, or when a marker has no reason.
*
* The third case has no equivalent in the guard gate and is the one that keeps
* this list worth reading: a marker whose reason is blank tells the next person
* nothing about why the control was taken away, and there is no way to recover
* that intent afterwards.
*/
export function validateManagedRoutes(
app: INestApplication,
allowList: string[] = MANAGED_ROUTE_ALLOW_LIST,
): void {
const entries = collectManagedRoutes(app);
const ids = entries.map((e) => e.id);
const allowed = new Set(allowList);
const undeclared = ids.filter((id) => !allowed.has(id));
const stale = allowList.filter((id) => !ids.includes(id));
const unexplained = entries.filter((e) => e.reason.trim() === '').map((e) => e.id);
const problems: string[] = [];
if (undeclared.length > 0) {
problems.push(
`route(s) marked @ManagedForbidden() but not in MANAGED_ROUTE_ALLOW_LIST:\n ${undeclared.join('\n ')}`,
);
}
if (stale.length > 0) {
problems.push(
`MANAGED_ROUTE_ALLOW_LIST entries that are no longer marked:\n ${stale.join('\n ')}`,
);
}
if (unexplained.length > 0) {
problems.push(`@ManagedForbidden() without a reason:\n ${unexplained.join('\n ')}`);
}
if (problems.length > 0) {
throw new Error(
`Managed surface changed.\n\n${problems.join('\n\n')}\n\n` +
'Every entry is a control a centrally administered install withholds from its ' +
'own admin. Add it deliberately, with the reason the decorator requires, or ' +
'remove the stale line.',
);
}
}