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
+7 -2
View File
@@ -25,7 +25,12 @@ tokens, `RuntimeEnvService`) and consumes the SAME derive functions.
2. **Validation runs once, at boot, from the production entrypoint only.**
Never wire the schema into `buildApp()`, `ConfigModule.forRoot({ validate })`
or a request path. Unset/blank variables always pass (defaults apply); only
present-but-malformed values abort startup.
present-but-malformed values abort startup. The one addition on top of the
schema is `managedPreconditions()` in `env.ts`: cross-field rules that only
apply with `TREK_MANAGED`, for combinations that are individually valid and
together wrong. It is empty without the switch, so a self-hoster never meets
it. Put a rule there only if booting anyway would be a security or data
problem — not to enforce a preference.
3. **Parity is law — with one deliberate exception.** Every derived field pins
the exact coercion of the call site(s) it replaced (`Number(x) || d`
treating `"0"` as unset, per-site defaults for the same variable, …). Do not
@@ -69,7 +74,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):
TREK_MANAGED, DEMO_MODE, NODE_ENV, APP_VERSION, APP_URL, TREK_API_DOCS_ENABLED,
TREK_MANAGED, PLACES_API_BASE, PLACES_API_KEY, MAPBOX_ACCESS_TOKEN, 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,
+18
View File
@@ -120,6 +120,23 @@ export function deriveManaged(raw: RawEnv) {
};
}
/**
* Where the Places calls go and which credential they carry.
*
* Both unset on a self-hosted install, which is the path the code has always
* taken: the endpoints stay Google's and the key comes from the users table.
* Set them and the calls leave through something the operator runs, with a
* credential no instance admin can read back.
*/
export function deriveMaps(raw: RawEnv) {
return {
placesApiBase: raw.PLACES_API_BASE || undefined,
placesApiKey: raw.PLACES_API_KEY || undefined,
/** Public pk.* token shipped with a managed instance; reaches the browser by design. */
mapboxToken: raw.MAPBOX_ACCESS_TOKEN || undefined,
};
}
export function deriveDemo(raw: RawEnv) {
return {
enabled: parseBool(raw.DEMO_MODE) === true,
@@ -255,6 +272,7 @@ export function deriveAll(raw: RawEnv) {
http: deriveHttp(raw),
session: deriveSession(raw),
managed: deriveManaged(raw),
maps: deriveMaps(raw),
demo: deriveDemo(raw),
adminBootstrap: deriveAdminBootstrap(raw),
oidc: deriveOidc(raw),
+3
View File
@@ -131,6 +131,9 @@ export const envSchema = z.object({
ADMIN_EMAIL: anyString,
ADMIN_PASSWORD: anyString,
TREK_MANAGED: boolStr,
PLACES_API_BASE: url,
PLACES_API_KEY: anyString,
MAPBOX_ACCESS_TOKEN: anyString,
DEMO_MODE: boolStr,
DEMO_ADMIN_USER: anyString,
DEMO_ADMIN_EMAIL: anyString,
+38 -5
View File
@@ -24,14 +24,47 @@ export function readEnv(): AppEnv {
*/
export function validateEnvAtBoot(raw: RawEnv = process.env as RawEnv): void {
const result = envSchema.safeParse(raw);
if (result.success) return;
const lines = result.error.issues.map((issue) => {
const key = String(issue.path[0]);
return ` - ${key}=${JSON.stringify(raw[key])}: ${issue.message}`;
});
const lines = result.success
? []
: result.error.issues.map((issue) => {
const key = String(issue.path[0]);
return ` - ${key}=${JSON.stringify(raw[key])}: ${issue.message}`;
});
lines.push(...managedPreconditions(raw));
if (lines.length === 0) return;
console.error(`Invalid environment configuration:\n${lines.join('\n')}`);
throw new Error(
`Invalid environment configuration (${lines.length} problem${lines.length === 1 ? '' : 's'}). ` +
'Fix the variables listed above, or unset them to use their defaults.',
);
}
/**
* Cross-field rules that only apply to a centrally administered install.
*
* These are not schema problems — every value here is individually valid, and
* blank always means "use the default" everywhere else in this file. They are
* combinations that would boot happily and be wrong, which is the case the
* schema cannot express and the one worth refusing (fail closed, see
* server/CLAUDE.md).
*
* Deliberately unreachable for a self-hoster: without TREK_MANAGED the list is
* empty and nothing changes.
*/
function managedPreconditions(raw: RawEnv): string[] {
if (deriveAll(raw).managed.enabled !== true) return [];
const problems: string[] = [];
// Without it the key is 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 at-rest encryption would come with its own key in the
// same zip. Provisioning sets this; forgetting it is silent otherwise.
if (!raw.ENCRYPTION_KEY) {
problems.push(
' - ENCRYPTION_KEY is unset: required with TREK_MANAGED, because otherwise the ' +
'at-rest key lives in the data volume and is bundled into every backup download.',
);
}
return problems;
}
+1
View File
@@ -7,6 +7,7 @@ export {
deriveHttp,
deriveSession,
deriveManaged,
deriveMaps,
deriveDemo,
deriveAdminBootstrap,
deriveOidc,
+6
View File
@@ -14,6 +14,7 @@ import { setupApiDocs } from './nest/platform/api-docs';
import { MCP_METADATA_MIDDLEWARE } from './nest/platform/mcp-metadata.middleware';
import { validateBodyContracts } from './nest/common/validate-body-contracts';
import { validateRouteGuards } from './nest/common/validate-route-guards';
import { validateManagedRoutes } from './nest/common/validate-managed-routes';
import { TrekWsAdapter } from './nest/realtime/trek-ws.adapter';
/**
@@ -129,5 +130,10 @@ export async function buildApp(): Promise<INestApplication> {
// session must carry @Public() with a reason AND be on the reviewed list.
// Default-deny protects what exists; this is what keeps the exemptions honest.
validateRouteGuards(app);
// And on the other direction of the same question: a route that a centrally
// administered install withholds from its own admin must say why, and be on a
// list somebody reviewed. Runs in every e2e harness because they share this
// builder, so a forgotten marker fails in CI rather than at a customer.
validateManagedRoutes(app);
return app;
}
@@ -29,6 +29,7 @@ import { logInfo } from '../audit/audit-log.logger';
import { AuditService } from '../audit/audit.service';
import { NotificationsService } from '../notifications/notifications.service';
import type { User } from '../../types';
import { ManagedForbidden } from '../common/managed';
/** Throw the legacy {error,status} envelope when a service call reports failure. */
function ok<T>(result: T): Exclude<T, { error: string }> {
@@ -104,6 +105,13 @@ export class AdminController {
return { success: true, deleted: result.deleted };
}
@Delete('users/:id/mfa')
resetUserMfa(@CurrentUser() user: User, @Param('id') id: string, @Req() req: Request) {
const result = ok(this.admin.resetUserMfa(id, user.id));
this.audit.writeAudit({ userId: user.id, action: 'admin.user_mfa_reset', resource: String(id), ip: getClientIp(req), details: { targetUser: result.email } });
return { success: true };
}
// ── Stats / permissions / audit ──
@Get('stats')
stats() { return this.admin.getStats(); }
@@ -279,6 +287,7 @@ export class AdminController {
}
// ── JWT rotation ──
@ManagedForbidden('rotating the secret signs every user out and fixes nothing the admin can reach')
@Post('rotate-jwt-secret')
@HttpCode(200)
rotateJwtSecret(@CurrentUser() user: User, @Req() req: Request) {
+2 -1
View File
@@ -21,9 +21,10 @@ import { PackingModule } from '../packing/packing.module';
// PermissionsModule exports PermissionsService for the permission matrix — it is
// not @Global, so the import must be explicit.
import { PermissionsModule } from '../permissions/permissions.module';
import { AppConfigModule } from '../app-config/app-config.module';
@Module({
imports: [PluginsRuntimeModule, SettingsModule, AuditModule, AddonsModule, AuthModule, NotificationsModule, PackingModule, PermissionsModule, TokensModule, OauthModule, SchedulingModule],
imports: [AppConfigModule, PluginsRuntimeModule, SettingsModule, AuditModule, AddonsModule, AuthModule, NotificationsModule, PackingModule, PermissionsModule, TokensModule, OauthModule, SchedulingModule],
controllers: [AdminController],
providers: [AdminService, VersionCheckJob, DemoResetJob],
})
+109 -6
View File
@@ -38,6 +38,7 @@ import {
writeVersionCache,
type VersionInfo,
} from './admin.helpers';
import { MANAGED_FORBIDDEN_ERROR } from '../common/managed';
/** Outbound GitHub calls: hard timeout and response-size cap (server/CLAUDE.md). */
const GITHUB_TIMEOUT_MS = 10_000;
@@ -192,6 +193,13 @@ export class AdminService {
}
}
// An admin sets a password for exactly one reason: the account is believed
// compromised. Without bumping password_version, verifyJwtAndLoadUser keeps
// accepting every cookie the intruder already holds, so the one action taken
// to lock them out was the one action that did not. Both self-service paths
// (changePassword, resetPassword) have always done this; this one had not.
const newPv = password ? ((user as User & { password_version?: number }).password_version ?? 0) + 1 : null;
this.db.transaction(() => {
this.db.run(
`
@@ -200,13 +208,31 @@ export class AdminService {
email = COALESCE(?, email),
role = COALESCE(?, role),
password_hash = COALESCE(?, password_hash),
password_version = COALESCE(?, password_version),
updated_at = CURRENT_TIMESTAMP
WHERE id = ?
`,
username || null, email || null, role || null, passwordHash, id,
username || null, email || null, role || null, passwordHash, newPv, id,
);
if (password) {
// The version bump only invalidates JWT cookies. These two stores carry
// their own credentials and are revoked separately, exactly as the
// self-service paths do it.
this.db.run('DELETE FROM mcp_tokens WHERE user_id = ?', id);
try {
this.db.run(
'UPDATE oauth_tokens SET revoked_at = CURRENT_TIMESTAMP WHERE user_id = ? AND revoked_at IS NULL',
id,
);
} catch { /* very old installs predate oauth_tokens */ }
}
});
if (password) {
try { revokeUserSessions(Number(id)); } catch { /* best-effort, same as elsewhere */ }
}
const updated = this.db.get('SELECT id, username, email, role, created_at, updated_at FROM users WHERE id = ?', id);
const changed: string[] = [];
@@ -237,6 +263,40 @@ export class AdminService {
resetUserPasskeys(id: string) { return this.passkeys.adminResetPasskeys(Number(id)); }
/**
* Clear another account's TOTP so its owner can enrol again.
*
* The passkey half of this has existed since passkeys landed; the TOTP half
* never did, which left one ordinary event with no answer: somebody on a trip
* loses their phone. Without this the only ways out are an operator reaching
* into the database or the account being deleted and rebuilt.
*
* Never for the caller themselves. An admin who wants their own MFA gone
* disables it through Settings, where the current password is required —
* making that reachable from here would turn a stolen admin session into a
* way to strip the second factor off the very account it came from.
*/
resetUserMfa(id: string, actingUserId: number): { error?: string; status?: number; success?: boolean; email?: string } {
const targetId = Number(id);
if (targetId === actingUserId) {
return { error: 'Use Settings to change your own two-factor setup', status: 400 };
}
const target = this.db.get<{ id: number; email: string; mfa_enabled: number | boolean }>(
'SELECT id, email, mfa_enabled FROM users WHERE id = ?',
targetId,
);
if (!target) return { error: 'User not found', status: 404 };
// Same three columns disableMfa clears, so an admin reset and a self-service
// disable leave the account in exactly one state rather than two.
this.db.run(
'UPDATE users SET mfa_enabled = 0, mfa_secret = NULL, mfa_backup_codes = NULL, updated_at = CURRENT_TIMESTAMP WHERE id = ?',
targetId,
);
return { success: true, email: target.email };
}
// ── Stats ──────────────────────────────────────────────────────────────────
getStats() {
@@ -368,12 +428,26 @@ export class AdminService {
}
async checkVersion(): Promise<VersionInfo> {
const cached = readVersionCache();
if (cached) return cached;
// Lazy require, re-anchored for nest/admin/ (was ../../package.json in services/).
const currentVersion: string = readEnv().app.appVersion || require('../../../package.json').version;
const isPrerelease = currentVersion.includes('-pre.');
// Answered rather than refused on a centrally administered install: the admin
// page calls this on open, and a 403 there would be an error message where a
// quiet surface belongs. The operator decides when to upgrade, so from inside
// the instance there is nothing available.
if (readEnv().managed.enabled) {
return {
current: currentVersion,
latest: currentVersion,
update_available: false,
is_docker: isDocker,
is_prerelease: isPrerelease,
};
}
const cached = readVersionCache();
if (cached) return cached;
const fallback: VersionInfo = {
current: currentVersion,
latest: currentVersion,
@@ -462,7 +536,24 @@ export class AdminService {
// ── Addons ─────────────────────────────────────────────────────────────────
listAddons() {
const addons = this.db.all<Addon>('SELECT * FROM addons ORDER BY sort_order, id');
const addons = this.db
.all<Addon>('SELECT * FROM addons ORDER BY sort_order, id')
// Hidden rather than shown-and-refused, because a toggle that answers 403
// is worse than no toggle.
//
// AI parsing: the endpoint, the model and what a document costs all belong
// to the operator, so there is no instance decision left to make — not even
// whether it runs.
//
// AirTrail: the addon exists to reach a server the admin runs themselves,
// and a managed instance has no route to one.
.filter(
(a) =>
!(
readEnv().managed.enabled &&
(a.id === ADDON_IDS.LLM_PARSING || a.id === ADDON_IDS.AIRTRAIL)
),
);
const providers = this.db.all<{
id: string;
name: string;
@@ -474,7 +565,11 @@ export class AdminService {
SELECT id, name, description, icon, enabled, sort_order
FROM photo_providers
ORDER BY sort_order, id
`);
`)
// Immich and Synology Photos are servers the admin runs at home. A managed
// instance cannot reach one (its egress does not go there, and it should
// not), so offering the connection would only produce a timeout.
.filter(() => !readEnv().managed.enabled);
const fields = this.db.all<{
provider_id: string;
field_key: string;
@@ -537,6 +632,14 @@ export class AdminService {
const provider = this.db.get<ProviderRow>('SELECT * FROM photo_providers WHERE id = ?', id);
if (!addon && !provider) return { error: 'Addon not found', status: 404 };
// The whole addon, not just its config: on a centrally administered install
// the operator owns the endpoint, the model and the per-document cost, so
// there is nothing here for an instance admin to set — including whether it
// runs at all. listAddons hides the row; this closes the route behind it.
if (readEnv().managed.enabled && id === ADDON_IDS.LLM_PARSING) {
return { error: MANAGED_FORBIDDEN_ERROR.error, status: 403 };
}
this.db.transaction(() => {
if (addon) {
if (data.enabled !== undefined)
@@ -2,6 +2,7 @@ import { Injectable, type OnApplicationBootstrap } from '@nestjs/common';
import { logError } from '../audit/audit-log.logger';
import { AdminService } from './admin.service';
import { CronRegistrarService } from '../scheduling/cron-registrar.service';
import { RuntimeEnvService } from '../app-config/runtime-env.service';
/**
* Daily version check (moved from src/scheduler.ts — it was the only consumer
@@ -15,10 +16,15 @@ export class VersionCheckJob implements OnApplicationBootstrap {
constructor(
private readonly admin: AdminService,
private readonly registrar: CronRegistrarService,
private readonly env: RuntimeEnvService,
) {}
onApplicationBootstrap(): void {
if (!this.registrar.isEnabled()) return;
// A centrally administered install never registers it. The upgrade schedule
// is the operator's, so the daily call to github.com would only ever produce
// a notification telling the admin to do something they cannot do.
if (this.env.isManaged()) return;
this.registrar.register('version-check', '0 9 * * *', () => this.tick());
}
+2 -1
View File
@@ -15,6 +15,7 @@ import { HelpModule } from './help/help.module';
import { AirportsModule } from './airports/airports.module';
import { ConfigModule } from './config/config.module';
import { SystemNoticesModule } from './system-notices/system-notices.module';
import { ManagedExtModule } from './managed/managed-ext.module';
import { MapsModule } from './maps/maps.module';
import { GeoModule } from './geo/geo.module';
import { PlaceEnrichmentModule } from './place-enrichment/place-enrichment.module';
@@ -72,7 +73,7 @@ import { RealtimeGatewayModule } from './realtime/realtime-gateway.module';
* migrated.
*/
@Module({
imports: [AppConfigModule, DatabaseModule, RealtimeModule, RealtimeGatewayModule, SchedulingModule, McpModule.forRoot({ accessPolicy: trekMcpAccessPolicy, validateAccess: trekMcpValidateAccess }), HealthModule, PlatformModule, McpTransportModule, WeatherModule, HelpModule, AirportsModule, ConfigModule, SystemNoticesModule, GeoModule, MapsModule, PlaceEnrichmentModule, CategoriesModule, TagsModule, NotificationsModule, AtlasModule, VacayModule, PackingModule, TodoModule, BudgetModule, ReservationsModule, DaysModule, DayNotesModule, AccommodationsModule, AssignmentsModule, PlacesModule, TripsModule, CollabModule, FilesModule, PhotosModule, MemoriesModule, AirtrailModule, JourneyModule, CollectionsModule, ShareModule, TripInviteModule, TransitModule, FeedsModule, SettingsModule, BackupModule, AuthModule, OidcModule, OauthModule, AdminModule, AddonsModule, AuditModule, PermissionsModule, PluginsModule, BookingImportModule, ReservationImportModule, LlmParseModule],
imports: [AppConfigModule, DatabaseModule, RealtimeModule, RealtimeGatewayModule, SchedulingModule, McpModule.forRoot({ accessPolicy: trekMcpAccessPolicy, validateAccess: trekMcpValidateAccess }), HealthModule, PlatformModule, McpTransportModule, WeatherModule, HelpModule, AirportsModule, ConfigModule, SystemNoticesModule, GeoModule, MapsModule, PlaceEnrichmentModule, CategoriesModule, TagsModule, NotificationsModule, AtlasModule, VacayModule, PackingModule, TodoModule, BudgetModule, ReservationsModule, DaysModule, DayNotesModule, AccommodationsModule, AssignmentsModule, PlacesModule, TripsModule, CollabModule, FilesModule, PhotosModule, MemoriesModule, AirtrailModule, JourneyModule, CollectionsModule, ShareModule, TripInviteModule, TransitModule, FeedsModule, SettingsModule, BackupModule, AuthModule, OidcModule, OauthModule, AdminModule, AddonsModule, AuditModule, PermissionsModule, PluginsModule, BookingImportModule, ReservationImportModule, LlmParseModule, ManagedExtModule],
providers: [
// Default-deny: a route is authenticated unless it carries @Public() or
// @OptionalAuth(), or declares its own @UseGuards chain. Protection used to
+6 -1
View File
@@ -44,6 +44,7 @@ import { getClientIp } from '../audit/client-ip';
import { AuditService } from '../audit/audit.service';
import type { User } from '../../types';
import { MfaExempt } from './mfa-policy.guard';
import { ManagedForbidden } from '../common/managed';
const WINDOW = 15 * 60 * 1000;
const ALLOWED_AVATAR_EXTS = ['.jpg', '.jpeg', '.png', '.gif', '.webp'];
@@ -168,6 +169,7 @@ export class AuthController {
return { users: this.profile.listUsers(user.id) };
}
@ManagedForbidden('validating a key spends the operator quota on a test click')
@Get('validate-keys')
async validateKeys(@CurrentUser() user: User) {
const result = await this.profile.validateKeys(user.id);
@@ -195,7 +197,9 @@ export class AuthController {
throw new HttpException({ error: result.error }, result.status!);
}
this.audit.writeAudit({ userId: user.id, action: 'settings.app_update', ip: getClientIp(req), details: result.auditSummary, debugDetails: result.auditDebugDetails });
return { success: true };
// Named so the settings tab can say which fields the operator holds rather
// than showing a saved value that silently did not save.
return { success: true, ...(result.managedKeys?.length ? { managed_keys: result.managedKeys } : {}) };
}
// GET travel-stats moved to atlas/travel-stats.controller.ts. Same path, same
@@ -249,6 +253,7 @@ export class AuthController {
return { tokens: this.tokens.listMcpTokens(user.id) };
}
@ManagedForbidden('a static token never expires and carries every scope; OAuth covers the same ground')
@Post('mcp-tokens')
@HttpCode(201)
createMcpToken(@CurrentUser() user: User, @Body() body: McpTokenCreateDto, @Req() req: Request) {
+19 -3
View File
@@ -20,6 +20,7 @@ import { EphemeralTokenService } from './ephemeral-token.service';
// every consumer of this module — a nest→mcp→nest module cycle.
import { revokeUserSessions } from '../../mcp/sessionManager';
import { UserCleanupService } from './user-cleanup.service';
import { splitManagedKeys } from '../common/managed';
import { emitUserDeleted } from '../../plugin-user-lifecycle';
import { verifyJwtAndLoadUser } from './jwt-verify';
import { User } from '../../types';
@@ -230,7 +231,13 @@ export class AuthService {
// One directory deeper than the legacy src/services location — the extra
// '../' keeps resolving to the workspace package.json.
const version: string = readEnv().app.appVersion ?? require('../../../package.json').version;
const hasGoogleKey = !!this.db.get("SELECT maps_api_key FROM users WHERE role = 'admin' AND maps_api_key IS NOT NULL AND maps_api_key != '' LIMIT 1");
// The operator's key counts too. getMapsKey prefers it over anything in the
// users table, so asking the table alone would report "no key" on an install
// where every lookup works, and the client would hide the Google features it
// is actually able to use.
const hasGoogleKey =
!!readEnv().maps.placesApiKey ||
!!this.db.get("SELECT maps_api_key FROM users WHERE role = 'admin' AND maps_api_key IS NOT NULL AND maps_api_key != '' LIMIT 1");
const oidcDisplayName = readEnv().oidc.displayName ||
this.db.get<{ value: string }>("SELECT value FROM app_settings WHERE key = 'oidc_display_name'")?.value || null;
const oidcConfigured = !!(
@@ -602,6 +609,8 @@ export class AuthService {
success?: boolean;
auditSummary?: Record<string, unknown>;
auditDebugDetails?: Record<string, unknown>;
/** Names the operator holds, skipped rather than written. Empty when self-hosted. */
managedKeys?: string[];
} {
const body = rawBody as Record<string, unknown>;
const user = this.db.get<{ role: string }>('SELECT role FROM users WHERE id = ?', userId);
@@ -635,7 +644,14 @@ export class AuthService {
}
}
// SMTP, the OIDC toggles and the WebAuthn pair share this handler with keys
// the admin does own, so a managed install skips those names and keeps the
// rest of the save working. Reported, never thrown: the settings tab sends
// the whole form in one request.
const { blocked } = splitManagedKeys(body as Record<string, unknown>, readEnv().managed.enabled);
for (const key of ADMIN_SETTINGS_KEYS) {
if (blocked.includes(key)) continue;
if (body[key] !== undefined) {
let val = String(body[key]);
if (key === 'require_mfa') {
@@ -651,7 +667,7 @@ export class AuthService {
}
}
const changedKeys = ADMIN_SETTINGS_KEYS.filter(k => body[k] !== undefined && !(k === 'smtp_pass' && String(body[k]) === '••••••••'));
const changedKeys = ADMIN_SETTINGS_KEYS.filter(k => !blocked.includes(k) && body[k] !== undefined && !(k === 'smtp_pass' && String(body[k]) === '••••••••'));
const summary: Record<string, unknown> = {};
const smtpChanged = changedKeys.some(k => k.startsWith('smtp_'));
@@ -670,7 +686,7 @@ export class AuthService {
// The reminder crons read their enable gates and channels per tick, so a
// notification-settings change takes effect at the next run — no restart.
return { success: true, auditSummary: summary, auditDebugDetails: debugDetails };
return { success: true, auditSummary: summary, auditDebugDetails: debugDetails, managedKeys: blocked };
}
// -------------------------------------------------------------------------
+46 -3
View File
@@ -6,6 +6,7 @@ import { DatabaseService } from '../database/database.service';
import { decrypt_api_key, maybe_encrypt_api_key } from '../common/crypto/apiKeyCrypto';
import { avatarUrl } from '../common/avatarUrl';
import { EMAIL_REGEX, avatarDir, mask_stored_api_key } from './auth.helpers';
import { splitManagedKeys, MANAGED_LOCKED_PROFILE_KEYS } from '../common/managed';
import { User } from '../../types';
/**
@@ -26,8 +27,25 @@ import { User } from '../../types';
export class UserProfileService {
constructor(private readonly db: DatabaseService) {}
/**
* On a centrally administered install the three key columns belong to the
* operator, and there are four ways to reach them: this method, updateApiKeys,
* updateSettings and the read in getSettings. Sealing one route would leave
* the other three open, so all four ask here.
*
* Read live rather than injected: the unit tests construct this service by
* hand with a single argument, and tests/ sits outside the tsconfig, so a new
* constructor parameter would only surface at runtime.
*/
private get managed(): boolean {
return readEnv().managed.enabled;
}
updateMapsKey(userId: number, key: unknown) {
const maps_api_key = key as string | null | undefined;
if (this.managed) {
return { success: true, maps_api_key: null, managed_keys: ['maps_api_key'] };
}
this.db.run(
'UPDATE users SET maps_api_key = ?, updated_at = CURRENT_TIMESTAMP WHERE id = ?',
maybe_encrypt_api_key(maps_api_key), userId
@@ -37,6 +55,8 @@ export class UserProfileService {
updateApiKeys(userId: number, rawBody: unknown) {
const body = rawBody as { maps_api_key?: string; openweather_api_key?: string; unsplash_api_key?: string };
const { blocked } = splitManagedKeys(body, this.managed);
for (const key of blocked) delete body[key as keyof typeof body];
const current = this.db.get<Pick<User, 'maps_api_key' | 'openweather_api_key' | 'unsplash_api_key'>>('SELECT maps_api_key, openweather_api_key, unsplash_api_key FROM users WHERE id = ?', userId);
// `?? null` instead of the former non-null assertions: a user row deleted
@@ -57,6 +77,7 @@ export class UserProfileService {
const u = updated ? { ...updated, mfa_enabled: !!(updated.mfa_enabled === 1 || updated.mfa_enabled === true) } : undefined;
return {
success: true,
...(blocked.length ? { managed_keys: blocked } : {}),
user: { ...u, maps_api_key: mask_stored_api_key(u?.maps_api_key), openweather_api_key: mask_stored_api_key(u?.openweather_api_key), unsplash_api_key: mask_stored_api_key(u?.unsplash_api_key), avatar_url: avatarUrl(updated || {}) },
};
}
@@ -92,9 +113,14 @@ export class UserProfileService {
const updates: string[] = [];
const params: (string | number | null)[] = [];
if (maps_api_key !== undefined) { updates.push('maps_api_key = ?'); params.push(maybe_encrypt_api_key(maps_api_key)); }
if (openweather_api_key !== undefined) { updates.push('openweather_api_key = ?'); params.push(maybe_encrypt_api_key(openweather_api_key)); }
if (unsplash_api_key !== undefined) { updates.push('unsplash_api_key = ?'); params.push(maybe_encrypt_api_key(unsplash_api_key)); }
// The name and email half of this body stays the user's own in every mode;
// only the three key columns answer to the operator.
const { blocked } = splitManagedKeys(body, this.managed);
const keyLocked = blocked.length > 0;
if (maps_api_key !== undefined && !keyLocked) { updates.push('maps_api_key = ?'); params.push(maybe_encrypt_api_key(maps_api_key)); }
if (openweather_api_key !== undefined && !keyLocked) { updates.push('openweather_api_key = ?'); params.push(maybe_encrypt_api_key(openweather_api_key)); }
if (unsplash_api_key !== undefined && !keyLocked) { updates.push('unsplash_api_key = ?'); params.push(maybe_encrypt_api_key(unsplash_api_key)); }
if (username !== undefined) { updates.push('username = ?'); params.push(username.trim()); }
if (email !== undefined) { updates.push('email = ?'); params.push(email.trim()); }
@@ -112,6 +138,7 @@ export class UserProfileService {
const u = updated ? { ...updated, mfa_enabled: !!(updated.mfa_enabled === 1 || updated.mfa_enabled === true) } : undefined;
return {
success: true,
...(blocked.length ? { managed_keys: blocked } : {}),
user: { ...u, maps_api_key: mask_stored_api_key(u?.maps_api_key), openweather_api_key: mask_stored_api_key(u?.openweather_api_key), unsplash_api_key: mask_stored_api_key(u?.unsplash_api_key), avatar_url: avatarUrl(updated || {}) },
};
}
@@ -123,6 +150,22 @@ export class UserProfileService {
);
if (user?.role !== 'admin') return { error: 'Admin access required', status: 403 };
// The one endpoint in the codebase that hands back a stored key in the
// clear. That is fine when the admin pasted it in themselves and wrong when
// the operator supplied it, so a managed install answers with the shape and
// not the values. Keys kept, values null, because the client reads them as
// `settings?.maps_api_key || ''`.
if (this.managed) {
return {
settings: {
maps_api_key: null,
openweather_api_key: null,
unsplash_api_key: null,
managed_keys: [...MANAGED_LOCKED_PROFILE_KEYS],
},
};
}
return {
settings: {
maps_api_key: decrypt_api_key(user.maps_api_key),
@@ -28,6 +28,8 @@ import { AutoBackupSettingsDto } from './backup.dto';
import { getClientIp } from '../audit/client-ip';
import { AuditService } from '../audit/audit.service';
import { getUploadTmpDir, MAX_BACKUP_UPLOAD_SIZE } from './backup.impl';
import { ManagedForbidden, isManagedBlocked, MANAGED_FORBIDDEN_ERROR } from '../common/managed';
import { RuntimeEnvService } from '../app-config/runtime-env.service';
const UPLOAD = {
dest: getUploadTmpDir(),
@@ -54,6 +56,7 @@ export class BackupController {
private readonly backup: BackupService,
private readonly audit: AuditService,
private readonly autoBackup: AutoBackupJob,
private readonly env: RuntimeEnvService,
) {}
@Get('list')
@@ -91,6 +94,7 @@ export class BackupController {
res.download(this.backup.backupFilePath(filename), filename);
}
@ManagedForbidden('a restore replaces database and uploads, and the operator owns the recovery point')
@Post('restore/:filename')
@HttpCode(200) // Express answers restore with res.json (200).
async restore(@CurrentUser() user: User, @Param('filename') filename: string, @Req() req: Request) {
@@ -113,10 +117,21 @@ export class BackupController {
}
}
@ManagedForbidden(
'restoring from an uploaded archive replaces the database and the encryption key',
{ enforcedInHandler: true },
)
@Post('upload-restore')
@HttpCode(200) // Express answers upload-restore with res.json (200).
@UseInterceptors(FileInterceptor('backup', UPLOAD))
async uploadRestore(@CurrentUser() user: User, @UploadedFile() file: Express.Multer.File | undefined, @Req() req: Request) {
// Checked here rather than in the guard: a guard runs before the multipart
// parser, so throwing there leaves the body unread and the client sees an
// ECONNRESET instead of this 403 (PROFILE-015). The marker above still puts
// the route in the boot-gate inventory.
if (isManagedBlocked(this.env)) {
throw new HttpException(MANAGED_FORBIDDEN_ERROR, 403);
}
if (!file) {
throw new HttpException({ error: 'No file uploaded' }, 400);
}
@@ -147,6 +162,7 @@ export class BackupController {
}
}
@ManagedForbidden('the operator schedules backups off-volume; a second schedule inside it is not one')
@Put('auto-settings')
updateAutoSettings(@CurrentUser() user: User, @Body() body: AutoBackupSettingsDto, @Req() req: Request) {
try {
+2 -1
View File
@@ -4,9 +4,10 @@ import { BackupService } from './backup.service';
import { AutoBackupJob } from './auto-backup.job';
import { AuditModule } from '../audit/audit.module';
import { SchedulingModule } from '../scheduling/scheduling.module';
import { AppConfigModule } from '../app-config/app-config.module';
@Module({
imports: [AuditModule, SchedulingModule],
imports: [AppConfigModule, AuditModule, SchedulingModule],
controllers: [BackupController],
providers: [BackupService, AutoBackupJob],
})
+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.',
);
}
}
@@ -4,6 +4,7 @@ import { JwtAuthGuard } from '../auth/jwt-auth.guard';
import { AdminGuard } from '../auth/admin.guard';
import { LlmLocalService } from './llm-local.service';
import { LlmLocalPullDto } from './llm-local.dto';
import { ManagedForbidden } from '../common/managed';
/**
* Admin-only management of a local LLM server (Ollama): list installed models and
@@ -14,6 +15,7 @@ import { LlmLocalPullDto } from './llm-local.dto';
export class LlmLocalController {
constructor(private readonly local: LlmLocalService) {}
@ManagedForbidden('the model list belongs to the operator runtime, not to one instance')
@Get('models')
models(@Query('baseUrl') baseUrl?: string) {
return this.local.listModels(baseUrl);
@@ -24,6 +26,7 @@ export class LlmLocalController {
* ({ status, total?, completed? }) straight to the client, which reads the
* response body to render a progress bar. Uses @Res() to stream manually.
*/
@ManagedForbidden('pulling a model spends the operator disk and GPU from inside a customer instance')
@Post('pull')
async pull(@Body() body: LlmLocalPullDto, @Res() res: Response): Promise<void> {
const stream = await this.local.pull(body?.baseUrl, body?.model ?? '');
@@ -5,13 +5,14 @@ import { LlmLocalController } from './llm-local.controller';
import { LlmConfigResolver } from './llm-config.resolver';
import { SettingsModule } from '../settings/settings.module';
import { AddonsModule } from '../addons/addons.module';
import { AppConfigModule } from '../app-config/app-config.module';
/**
* Provides the LLM booking-import fallback; imported by BookingImportModule.
* Exports LlmConfigResolver for the plugin host surface (HostSurfaceRpc).
*/
@Module({
imports: [SettingsModule, AddonsModule],
imports: [AppConfigModule, SettingsModule, AddonsModule],
controllers: [LlmLocalController],
providers: [LlmParseService, LlmLocalService, LlmConfigResolver],
exports: [LlmParseService, LlmConfigResolver],
+16 -3
View File
@@ -7,6 +7,7 @@ import { isPdf, extractText } from './text-extract';
import { routeExtraction, detectFlightNumbers } from './router/extraction-router';
import { Injectable } from '@nestjs/common';
import { kiReservationSchema } from '@trek/shared';
import { RuntimeEnvService } from '../app-config/runtime-env.service';
const MIME_BY_EXT: Record<string, string> = {
'.pdf': 'application/pdf',
@@ -26,7 +27,10 @@ export interface LlmParseResult {
*/
@Injectable()
export class LlmParseService {
constructor(private readonly llmConfig: LlmConfigResolver) {}
constructor(
private readonly llmConfig: LlmConfigResolver,
private readonly env: RuntimeEnvService,
) {}
/** True when the addon is enabled AND a usable config resolves for this user. */
isAvailable(userId: number): boolean {
@@ -64,7 +68,14 @@ export class LlmParseService {
const MAX_EXTRACT_CHARS =
config.provider !== 'local' ? 4000 : detectFlightNumbers(input.text).length > 0 ? 16000 : 6000;
if (input.text.length > MAX_EXTRACT_CHARS) input.text = input.text.slice(0, MAX_EXTRACT_CHARS);
console.debug(`[DEBUG] Extracted text from ${file.originalName} (${input.text.length} chars):\n`, input.text);
// The extracted text IS the booking: traveller name, address, booking
// reference. On a centrally administered install that would land in the
// operator's log, which is a processing nobody asked for and nobody needs.
if (this.env.isManaged()) {
console.debug(`[DEBUG] Extracted text from ${file.originalName} (${input.text.length} chars)`);
} else {
console.debug(`[DEBUG] Extracted text from ${file.originalName} (${input.text.length} chars):\n`, input.text);
}
if (!input.text.trim()) {
return {
kiItems: [],
@@ -104,7 +115,9 @@ export class LlmParseService {
let raw: Record<string, unknown>[];
try {
raw = await createLlmClient(config).extract(input);
console.debug('[DEBUG] Raw LLM Response: ', raw);
// Same reason: the model answers with the fields it read out of the document.
if (this.env.isManaged()) console.debug(`[DEBUG] LLM response: ${raw.length} item(s)`);
else console.debug('[DEBUG] Raw LLM Response: ', raw);
} catch (err) {
console.error(`[llm-parse] AI parsing failed for "${file.originalName}" (provider=${config.provider}):`, err instanceof Error ? err.message : err);
return {
@@ -0,0 +1,24 @@
import { Module } from '@nestjs/common';
/**
* The attachment point for server surfaces that only exist on a centrally
* administered install.
*
* Empty here, and empty in every build of this repository: no controllers, no
* providers, no routes. An installation whose operator ships additional
* endpoints replaces this file at build time.
*
* app.module.ts imports it unconditionally, which is the point. A conditional
* import would make the module graph depend on an environment variable, and the
* graph is built once per app while TREK_MANAGED is read live — the two do not
* belong in the same expression (see app-config/README.md on the boot-stable vs
* runtime-toggled split). An empty module costs nothing to import, so the flag
* never has to reach this far.
*
* Anything added here follows the same rules as the rest of src/nest: a real
* module with a controller and a provider, bodies through the Zod pipe, routes
* covered by the global guards, and its own tests. Being outside this repository
* is not a reason to be outside its standards.
*/
@Module({})
export class ManagedExtModule {}
+30 -1
View File
@@ -39,7 +39,28 @@ import {
let googleApiCallCount = 0;
function googleFetch(endpoint: string, label: string, init?: RequestInit): Promise<Response> {
/** The upstream every Places call is written against. */
const PLACES_UPSTREAM = 'https://places.googleapis.com';
/**
* Sends the call somewhere else when PLACES_API_BASE is set.
*
* The nine Places endpoints below all spell out the upstream host, so an install
* that wants these calls to leave through something of its own — an egress proxy,
* a cache, a gateway holding the key — has no way to say so today. One variable,
* substituted at the one place every call funnels through.
*
* Path and query are untouched, so the replacement has to speak the same API.
* Unset, which is every install today, the string is returned as it came in.
*/
function placesEndpoint(endpoint: string): string {
const base = readEnv().maps.placesApiBase;
if (!base || !endpoint.startsWith(PLACES_UPSTREAM)) return endpoint;
return base.replace(/\/+$/, '') + endpoint.slice(PLACES_UPSTREAM.length);
}
function googleFetch(rawEndpoint: string, label: string, init?: RequestInit): Promise<Response> {
const endpoint = placesEndpoint(rawEndpoint);
googleApiCallCount++;
console.debug(`[Google API] #${googleApiCallCount} ${label} → ${endpoint}`);
const referer = readEnv().app.appUrl ? getAppUrl() : undefined;
@@ -528,6 +549,14 @@ export class MapsService {
// ── API key retrieval ──────────────────────────────────────────────────────
getMapsKey(userId: number): string | null {
// When the operator supplies the credential, the database is not asked at
// all. Two reasons, and the second is the load-bearing one: a per-user key
// would route around whatever the operator's endpoint counts, and the key
// columns are readable by any admin of this instance, so a shared key stored
// there would be a key handed out. Unset, this branch never runs.
const operatorKey = readEnv().maps.placesApiKey;
if (operatorKey) return operatorKey;
const user = this.database.get<{ maps_api_key: string | null }>(
'SELECT maps_api_key FROM users WHERE id = ?',
userId,
@@ -26,6 +26,7 @@ import { AdminGuard } from '../auth/admin.guard';
import { NotificationPreferencesService } from './notification-preferences.service';
import { AdminNotificationPreferencesDto } from '../admin/admin.dto';
import { CurrentUser } from '../auth/current-user.decorator';
import { ManagedForbidden } from '../common/managed';
// The masked placeholder the client sends instead of a stored secret (8× U+2022).
const MASKED = '••••••••';
@@ -62,6 +63,7 @@ export class NotificationsController {
return this.notifications.getPreferences(user.id, user.role);
}
@ManagedForbidden('the relay is the operator credential; a test send would use their reputation')
@Post('test-smtp')
@HttpCode(200)
async testSmtp(@CurrentUser() user: User, @Body() body: TestSmtpDto): Promise<ChannelTestResult> {
+6
View File
@@ -11,6 +11,7 @@ import { AuditService } from '../audit/audit.service';
import { getClientIp } from '../audit/client-ip';
import { AdminOidcUpdateDto } from '../admin/admin.dto';
import { Public } from '../auth/public.decorator';
import { ManagedForbidden } from '../common/managed';
const OIDC_STATE_COOKIE = 'trek_oidc_state';
@@ -193,11 +194,16 @@ export class AdminOidcController {
private readonly audit: AuditService,
) {}
// Both halves, not just the write: reading back the issuer, client id and the
// discovery URL tells a caller how the identity of this install is wired, and
// on a managed install that wiring is not theirs.
@ManagedForbidden('the identity provider is part of what the operator runs')
@Get()
get() {
return this.oidc.getOidcSettings();
}
@ManagedForbidden('an instance-supplied issuer could assert any address as verified')
@Put()
update(@CurrentUser() user: User, @Body() body: AdminOidcUpdateDto, @Req() req: Request) {
const result = this.oidc.updateOidcSettings(body);
+8 -5
View File
@@ -13,6 +13,7 @@ import { TripMembershipService } from '../trip-membership/trip-membership.servic
import { setAuthCookie } from '../common/cookie';
import { AuthService } from '../auth/auth.service';
import { DatabaseService } from '../database/database.service';
import { safeFetchAdminConfigured } from '../../utils/ssrfGuard';
// ---------------------------------------------------------------------------
// Types
@@ -271,7 +272,7 @@ export class OidcService implements OnModuleDestroy {
if (cached && Date.now() - cached.fetchedAt < DISCOVERY_TTL) {
return cached.doc;
}
const res = await fetch(url, { signal: AbortSignal.timeout(FETCH_TIMEOUT_MS) });
const res = await safeFetchAdminConfigured(url, { signal: AbortSignal.timeout(FETCH_TIMEOUT_MS) });
if (!res.ok) throw new Error('Failed to fetch OIDC discovery document');
assertResponseSize(res);
const parsed: unknown = await res.json();
@@ -355,12 +356,14 @@ export class OidcService implements OnModuleDestroy {
client_secret: clientSecret,
});
if (codeVerifier) body.set('code_verifier', codeVerifier);
const tokenRes = await fetch(doc.token_endpoint, {
// maxRedirects 0: following one would hand client_secret to a second host,
// and the platform default of 'follow' does exactly that today.
const tokenRes = await safeFetchAdminConfigured(doc.token_endpoint, {
method: 'POST',
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
body,
signal: AbortSignal.timeout(FETCH_TIMEOUT_MS),
});
}, 0);
assertResponseSize(tokenRes);
// Error responses are still parsed on purpose — callers branch on _ok/_status.
const parsed: unknown = await tokenRes.json();
@@ -375,7 +378,7 @@ export class OidcService implements OnModuleDestroy {
// -------------------------------------------------------------------------
async getUserInfo(userinfoEndpoint: string, accessToken: string): Promise<OidcUserInfo> {
const res = await fetch(userinfoEndpoint, {
const res = await safeFetchAdminConfigured(userinfoEndpoint, {
headers: { Authorization: `Bearer ${accessToken}` },
signal: AbortSignal.timeout(FETCH_TIMEOUT_MS),
});
@@ -393,7 +396,7 @@ export class OidcService implements OnModuleDestroy {
private async fetchJwks(jwksUri: string): Promise<Array<Record<string, unknown>>> {
const cached = this.jwksCache.get(jwksUri);
if (cached && Date.now() - cached.fetchedAt < JWKS_TTL_MS) return cached.keys;
const res = await fetch(jwksUri, { signal: AbortSignal.timeout(FETCH_TIMEOUT_MS) });
const res = await safeFetchAdminConfigured(jwksUri, { signal: AbortSignal.timeout(FETCH_TIMEOUT_MS) });
if (!res.ok) throw new Error(`JWKS fetch failed: HTTP ${res.status}`);
assertResponseSize(res);
const json: unknown = await res.json();
+11
View File
@@ -114,6 +114,17 @@ export function serverCodeRoot(): string {
let warnedPermissionsOff = false;
export function pluginPermissionArgs(pluginId: string): string[] {
if (readEnv().plugins.permissionsOff) {
// Refuse outright when somebody other than this install's admin runs it. A
// warning is the right answer for a machine its owner chose to trust; here
// the person who set the flag and the people whose data is in the database
// are not the same person, and "fail closed" is the repo rule for exactly
// that case. Nothing spawns rather than spawning without the jail.
if (readEnv().managed.enabled) {
throw new Error(
'TREK_PLUGIN_PERMISSIONS=off is refused on a centrally administered install: ' +
'the OS permission jail is what keeps an installed plugin out of trek.db and the secret files.',
);
}
// The OS permission jail is the boundary that stops an installed plugin from
// reading trek.db / the secret files / shelling out. Turning it off makes plugin
// isolation crash-only — surface that loudly once so an operator can't leave it
@@ -12,6 +12,8 @@ import { getClientIp } from '../audit/client-ip';
import { pluginsEnabled } from './kill-switch';
import { devLinkEnabled } from './dev-link';
import { PluginActivateDto, PluginConfigDto, PluginEgressHostsDto, PluginInstallDto, PluginLinkDto, PluginRetrustDto, PluginUninstallDto } from './plugins.dto';
import { ManagedForbidden, isManagedBlocked, MANAGED_FORBIDDEN_ERROR } from '../common/managed';
import { RuntimeEnvService } from '../app-config/runtime-env.service';
/**
* Flatten a registry/install failure into the error envelope — CARRYING THE CODE.
@@ -48,6 +50,7 @@ export class PluginsController {
private readonly plugins: PluginsService,
private readonly runtime: PluginRuntimeService,
private readonly registry: PluginRegistryService,
private readonly env: RuntimeEnvService,
) {}
@Get()
@@ -86,10 +89,19 @@ export class PluginsController {
}
/** Sideload a plugin from an uploaded .zip/.tar.gz (registers INACTIVE). */
@ManagedForbidden(
'a sideloaded archive skips the signature check every registry install performs',
{ enforcedInHandler: true },
)
@Post('upload')
@HttpCode(200)
@UseInterceptors(FileInterceptor('file', { limits: { fileSize: 50 * 1024 * 1024 + 4096 } }))
async upload(@UploadedFile() file?: Express.Multer.File) {
// In the handler, not the guard: guards run before the multipart parser and
// the client would get an ECONNRESET rather than this 403 (PROFILE-015).
if (isManagedBlocked(this.env)) {
throw new HttpException(MANAGED_FORBIDDEN_ERROR, 403);
}
if (!pluginsEnabled()) throw new HttpException({ error: 'Plugins are disabled by server configuration' }, 503);
if (!file?.buffer?.length) throw new HttpException({ error: 'no file uploaded' }, 400);
try {
@@ -103,6 +115,7 @@ export class PluginsController {
* DEV-ONLY: register a plugin from a LOCAL built directory and hot-reload it
* against real data. Gated by TREK_PLUGINS_DEV_LINK on top of admin + kill-switch.
*/
@ManagedForbidden('a linked directory skips the signature check the registry install performs')
@Post('link')
@HttpCode(200)
async link(@Body() body: PluginLinkDto) {
@@ -184,6 +197,7 @@ export class PluginsController {
}
/** DEV-ONLY: re-fork a dev-linked plugin so it picks up rebuilt code. */
@ManagedForbidden('reloading from disk reintroduces whatever a sideload put there')
@Post(':id/reload')
@HttpCode(200)
async reload(@Param('id') id: string) {
+2 -1
View File
@@ -8,6 +8,7 @@ import { PluginUserSettingsController } from './plugin-user-settings.controller'
import { PluginsRuntimeModule } from './plugins-runtime.module';
import { PluginOAuthModule } from './oauth/plugin-oauth.module';
import { PluginContributionsModule } from './contributions/plugin-contributions.module';
import { AppConfigModule } from '../app-config/app-config.module';
/**
* Plugin system (#plugins), composition root.
@@ -27,7 +28,7 @@ import { PluginContributionsModule } from './contributions/plugin-contributions.
* that serves page and widget assets.
*/
@Module({
imports: [PluginsRuntimeModule, PluginOAuthModule, PluginContributionsModule],
imports: [AppConfigModule, PluginsRuntimeModule, PluginOAuthModule, PluginContributionsModule],
controllers: [
PluginsController,
PluginsFeedController,
@@ -10,6 +10,8 @@ import { AdminGuard } from '../auth/admin.guard';
import { AuditService } from '../audit/audit.service';
import { getClientIp } from '../audit/client-ip';
import { CurrentUser } from '../auth/current-user.decorator';
import { RuntimeEnvService } from '../app-config/runtime-env.service';
import { isManagedLockedKey, splitManagedKeys } from '../common/managed';
/**
* /api/settings — per-user key/value preferences: get-all, single upsert
@@ -26,7 +28,10 @@ import { CurrentUser } from '../auth/current-user.decorator';
@Controller('api/settings')
@UseGuards(JwtAuthGuard)
export class SettingsController {
constructor(private readonly settings: SettingsService) {}
constructor(
private readonly settings: SettingsService,
private readonly env: RuntimeEnvService,
) {}
/**
* #1772: the write half of the rule that the endpoint is instance
@@ -57,6 +62,12 @@ export class SettingsController {
@Put()
upsert(@CurrentUser() user: User, @Body() body: SettingUpsertDto) {
this.assertMayWriteLlmEndpoint({ [body.key]: body.value });
// assertMayWriteLlmEndpoint only covers llm_base_url and provider 'local'.
// llm_api_key and llm_model are writable by every user, and on a managed
// install both cost the operator money, so the key list decides here.
if (isManagedLockedKey(body.key) && this.env.isManaged()) {
return { success: true, key: body.key, managed: true };
}
// The client echoes a redacted secret back unchanged — treat as a no-op.
if (body.value === MASKED_SETTING_VALUE) {
return { success: true, key: body.key, unchanged: true };
@@ -69,9 +80,10 @@ export class SettingsController {
@HttpCode(200) // Express answers bulk with res.json (200), not the POST-default 201.
bulk(@CurrentUser() user: User, @Body() body: SettingsBulkDto) {
this.assertMayWriteLlmEndpoint(body.settings);
const { allowed, blocked } = splitManagedKeys(body.settings, this.env.isManaged());
try {
const updated = this.settings.bulkUpsertSettings(user.id, body.settings);
return { success: true, updated };
const updated = this.settings.bulkUpsertSettings(user.id, allowed);
return { success: true, updated, ...(blocked.length ? { managed_keys: blocked } : {}) };
} catch (err) {
console.error('Error saving settings:', err);
throw new HttpException({ error: 'Error saving settings' }, 500);
@@ -92,6 +104,7 @@ export class AdminDefaultUserSettingsController {
constructor(
private readonly settings: SettingsService,
private readonly audit: AuditService,
private readonly env: RuntimeEnvService,
) {}
@Get()
@@ -102,7 +115,15 @@ export class AdminDefaultUserSettingsController {
@Put()
update(@CurrentUser() user: User, @Body() body: AdminDefaultUserSettingsDto, @Req() req: Request) {
try {
this.settings.setAdminUserDefaults(body as unknown as Record<string, unknown>);
// Deliberately no managed_keys in the response here: the route answers
// with the raw defaults map the admin panel renders from, so an extra
// field would sit inside the key namespace. The audit row below and the
// client's capability filter carry the message instead.
const { allowed } = splitManagedKeys(
body as unknown as Record<string, unknown>,
this.env.isManaged(),
);
this.settings.setAdminUserDefaults(allowed);
this.audit.writeAudit({
userId: user.id,
action: 'admin.default_user_settings_update',
+2 -1
View File
@@ -3,11 +3,12 @@ import { AdminDefaultUserSettingsController, SettingsController } from './settin
import { AuthModule } from '../auth/auth.module';
import { AuditModule } from '../audit/audit.module';
import { SettingsService } from './settings.service';
import { AppConfigModule } from '../app-config/app-config.module';
/** Exports SettingsService for in-container consumers (admin, share, llm-parse). */
@Module({
// AuthModule for the admin gate on the defaults routes.
imports: [AuthModule, AuditModule],
imports: [AppConfigModule, AuthModule, AuditModule],
controllers: [SettingsController, AdminDefaultUserSettingsController],
providers: [SettingsService],
exports: [SettingsService],
@@ -2,6 +2,7 @@ import { Injectable } from '@nestjs/common';
import { DatabaseService } from '../database/database.service';
import { decrypt_api_key, maybe_encrypt_api_key } from '../common/crypto/apiKeyCrypto';
import { MASKED_SETTING_VALUE, normalizeAppearance } from '@trek/shared';
import { readEnv } from '../../app-config';
const ENCRYPTED_SETTING_KEYS = new Set(['webhook_url', 'ntfy_token', 'mapbox_access_token', 'llm_api_key']);
// Encrypted keys that are masked (••••••••) when returned to the client.
@@ -202,6 +203,20 @@ export class SettingsService {
}
merged[key] = value;
}
// On a centrally administered install the map credential comes with the
// instance, so it is injected here rather than stored per user: the token is
// the operator's, it is a public pk.* that has to reach the browser anyway,
// and nobody should be able to save a different one over it. GL is the
// default there too, since a token is always present.
const managedMaps = readEnv().maps;
if (readEnv().managed.enabled && managedMaps.mapboxToken) {
merged.mapbox_access_token = managedMaps.mapboxToken;
if (!merged.map_provider || merged.map_provider === 'leaflet') {
merged.map_provider = 'mapbox-gl';
}
}
return merged;
}
@@ -2,10 +2,11 @@ import { Module } from '@nestjs/common';
import { AddonsModule } from '../addons/addons.module';
import { SystemNoticesController } from './system-notices.controller';
import { SystemNoticesService } from './system-notices.service';
import { AppConfigModule } from '../app-config/app-config.module';
/** System-notices domain. Registered in AppModule. */
@Module({
imports: [AddonsModule],
imports: [AppConfigModule, AddonsModule],
controllers: [SystemNoticesController],
providers: [SystemNoticesService],
})
@@ -2,6 +2,7 @@ import { Injectable } from '@nestjs/common';
import type { SystemNoticeDto } from '@trek/shared';
import { getActiveNoticesFor, dismissNotice } from '../../systemNotices/service';
import { AddonsService } from '../addons/addons.service';
import { RuntimeEnvService } from '../app-config/runtime-env.service';
/**
* Thin Nest wrapper around the existing system-notices service. The condition
@@ -12,10 +13,17 @@ import { AddonsService } from '../addons/addons.service';
*/
@Injectable()
export class SystemNoticesService {
constructor(private readonly addons: AddonsService) {}
constructor(
private readonly addons: AddonsService,
private readonly env: RuntimeEnvService,
) {}
getActiveFor(userId: number): SystemNoticeDto[] {
return getActiveNoticesFor(userId, (addonId) => this.addons.isAddonEnabled(addonId)) as SystemNoticeDto[];
return getActiveNoticesFor(
userId,
(addonId) => this.addons.isAddonEnabled(addonId),
this.env.isManaged(),
) as SystemNoticeDto[];
}
dismiss(userId: number, noticeId: string): boolean {
+5
View File
@@ -10,6 +10,8 @@ interface ConditionContext {
* its injected AddonsService) so this plain module carries no bridge import.
*/
addonEnabled: (addonId: string) => boolean;
/** True when somebody other than this install's admin owns its configuration. */
managed: boolean;
}
// Custom predicate registry — extensible without modifying this file
@@ -54,6 +56,9 @@ function evaluateOne(condition: NoticeCondition, ctx: ConditionContext): boolean
case 'addonEnabled':
return ctx.addonEnabled(condition.addonId);
case 'managed':
return ctx.managed === condition.is;
case 'custom': {
const fn = customPredicates.get(condition.id);
if (!fn) {
+8 -1
View File
@@ -61,7 +61,11 @@ export const SYSTEM_NOTICES: SystemNotice[] = [
dismissible: true,
// Desktop-only: the support modal is suppressed on small/mobile viewports.
desktopOnly: true,
conditions: [],
// Not on a centrally administered install. The body thanks the reader for
// installing TREK and asks them to fund it, and there the reader installed
// nothing and already pays whoever runs it. Gated rather than reworded: the
// text is right for everyone it was written for.
conditions: [{ kind: 'managed', is: false }],
publishedAt: '2026-06-27T00:00:00Z',
priority: 100,
recurring: 'per-version',
@@ -82,6 +86,9 @@ export const SYSTEM_NOTICES: SystemNotice[] = [
{ kind: 'existingUserBeforeVersion', version: '3.0.14' },
{ kind: 'role', roles: ['admin'] },
{ kind: 'custom', id: 'whitespace-collision-detected' },
// The body says to check the server logs. On a managed install the reader
// has none, and the operator sees the same collision in theirs.
{ kind: 'managed', is: false },
],
publishedAt: '2026-05-03T00:00:00Z',
priority: 85,
+3 -2
View File
@@ -38,7 +38,8 @@ function severityWeight(s: string): number {
export function getActiveNoticesFor(
userId: number,
addonEnabled: (addonId: string) => boolean
addonEnabled: (addonId: string) => boolean,
managed = false
): SystemNoticeDTO[] {
const user = db.prepare(
'SELECT login_count, first_seen_version, role FROM users WHERE id = ?'
@@ -59,7 +60,7 @@ export function getActiveNoticesFor(
const now = new Date();
const currentAppVersion = getCurrentAppVersion();
const ctx = { user: { ...user, noTrips: tripCount }, currentAppVersion, now, addonEnabled };
const ctx = { user: { ...user, noTrips: tripCount }, currentAppVersion, now, addonEnabled, managed };
const appVer = semver.coerce(currentAppVersion)?.version ?? '0.0.0';
const isStillDismissed = (n: SystemNotice): boolean => {
+4
View File
@@ -9,6 +9,10 @@ export type NoticeCondition =
| { kind: 'dateWindow'; startsAt: string; endsAt?: string }
| { kind: 'role'; roles: Array<'admin' | 'user'> }
| { kind: 'addonEnabled'; addonId: string }
// Whether the operator of this install owns its configuration. A notice that
// asks the reader to update, to check a log or to fund the project assumes
// they run it themselves.
| { kind: 'managed'; is: boolean }
| { kind: 'custom'; id: string };
export interface NoticeMedia {
+9 -1
View File
@@ -151,7 +151,7 @@ function isLinkLocal(ip: string): boolean {
* and re-pinned. An http→https upgrade or a proxy redirect between LAN hosts still
* works because the check re-runs per hop rather than locking to the first IP.
*/
export async function safeFetchLlm(url: string, init?: RequestInit, maxRedirects = 5): Promise<Response> {
export async function safeFetchAdminConfigured(url: string, init?: RequestInit, maxRedirects = 5): Promise<Response> {
let currentUrl = url;
for (let hop = 0; ; hop++) {
@@ -201,6 +201,14 @@ export async function safeFetchLlm(url: string, init?: RequestInit, maxRedirects
}
}
/**
* The original name. Kept so no LLM call site has to change, and because the
* shape of the problem is identical: an endpoint an admin configured, which may
* legitimately live on loopback or the LAN, and must still never reach
* link-local or a cloud metadata service.
*/
export const safeFetchLlm = safeFetchAdminConfigured;
/**
* Thrown by safeFetch() when the URL is blocked by the SSRF guard.
*/