Give three more admin surfaces back to the domains that own them

default-user-settings, notification-preferences and oidc leave AdminController.
The first two were pure pass-throughs on AdminService that did nothing but
forward and cast; the third had its SQL there for a domain that already had a
module of its own. AdminService loses SettingsService and
NotificationPreferencesService entirely.

Two things came out of the move rather than going into it.

The OIDC lockout guard now has tests. It refuses to clear the SSO config while
password login is disabled — otherwise the instance has no SSO to log in through
and no password form either — and nothing covered that branch before, because it
sat among admin tests that only exercised the happy path.

The admin e2e app had to learn about the split. It assembles AdminModule alone,
so the moved routes 404'd there while working in production; it now imports the
three domains too. That is the same failure mode the module-provider guards
catch for RPC classes, and it is worth knowing that an e2e app which builds a
subset will find it first.

Also fixes the audit route note: audit-log stays on AdminController on purpose.
AuthModule imports AuditModule, so an admin-gated controller in AuditModule
closes a cycle — the same trap the addons toggles hit.
This commit is contained in:
Maurice
2026-08-09 20:54:13 +02:00
committed by Maurice
parent d4a1601855
commit 8a09f55571
17 changed files with 393 additions and 179 deletions
-2
View File
@@ -44,14 +44,12 @@ const notifPrefs = new NotificationPreferencesService(dbs, mailer);
const auth = new AuthService(dbs, permissions, new AtlasService(dbs), new TripMembershipService(dbs), webauthn, userCleanup, mailer);
const admin = new AdminService(
dbs,
new SettingsService(dbs),
new AddonsService(dbs),
new PasskeyService(dbs, auth, webauthn),
auth,
permissions,
new NotificationsService(dbs, realtime, mailer, new WebhookService(dbs), new NtfyService(dbs), notifPrefs),
userCleanup,
notifPrefs,
);
export function checkAndNotifyVersion(): Promise<void> {
-39
View File
@@ -115,20 +115,6 @@ export class AdminController {
@Get('audit-log')
auditLog(@Query() query: { limit?: string; offset?: string }) { return this.admin.getAuditLog(query); }
// ── OIDC ──
@Get('oidc')
getOidc() { return this.admin.getOidcSettings(); }
@Put('oidc')
updateOidc(@CurrentUser() user: User, @Body() body: AdminOidcUpdateDto, @Req() req: Request) {
const result = this.admin.updateOidcSettings(body);
if (result.error) {
throw new HttpException({ error: result.error }, result.status || 400);
}
this.audit.writeAudit({ userId: user.id, action: 'admin.oidc_update', ip: getClientIp(req), details: { issuer_set: !!body.issuer } });
return { success: true };
}
@Post('save-demo-baseline')
@HttpCode(200)
saveDemoBaseline(@CurrentUser() user: User, @Req() req: Request) {
@@ -149,16 +135,6 @@ export class AdminController {
@Get('version-check')
async versionCheck() { return this.admin.checkVersion(); }
// ── Admin notification preferences ──
@Get('notification-preferences')
getNotificationPrefs(@CurrentUser() user: User) { return this.admin.getPreferencesMatrix(user.id, user.role); }
@Put('notification-preferences')
setNotificationPrefs(@CurrentUser() user: User, @Body() body: AdminNotificationPreferencesDto) {
this.admin.setAdminPreferences(user.id, body);
return this.admin.getPreferencesMatrix(user.id, user.role);
}
// ── Invites ──
@Get('invites')
listInvites() { return { invites: this.admin.listInvites() }; }
@@ -182,7 +158,6 @@ export class AdminController {
return { success: true };
}
// ── Feature toggles ──
// ── Feature toggles ──
// Straight to AddonsService, which owns every one of these flags. They used to go
// through eleven-plus pass-through methods on AdminService, and the three places
@@ -300,20 +275,6 @@ export class AdminController {
}
// ── Default user settings ──
@Get('default-user-settings')
getDefaultUserSettings() { return this.admin.getAdminUserDefaults(); }
@Put('default-user-settings')
setDefaultUserSettings(@CurrentUser() user: User, @Body() body: AdminDefaultUserSettingsDto, @Req() req: Request) {
try {
this.admin.setAdminUserDefaults(body as unknown as Record<string, unknown>);
this.audit.writeAudit({ userId: user.id, action: 'admin.default_user_settings_update', ip: getClientIp(req), details: body as Record<string, unknown> });
return this.admin.getAdminUserDefaults();
} catch (err) {
throw new HttpException({ error: err instanceof Error ? err.message : String(err) }, 400);
}
}
// ── Dev-only: test notification (404 outside development, mirroring the conditional mount) ──
@Post('dev/test-notification')
@HttpCode(200)
-52
View File
@@ -21,10 +21,8 @@ import { prepareLlmAddonConfigForWrite, maskLlmAddonConfig } from '../llm-parse/
import { getPhotoProviderConfig } from '../memories/memories.helpers';
import { validatePassword } from '../common/passwordPolicy';
import { UserCleanupService } from '../auth/user-cleanup.service';
import { NotificationPreferencesService } from '../notifications/notification-preferences.service';
import { DatabaseService } from '../database/database.service';
import { AddonsService } from '../addons/addons.service';
import { SettingsService } from '../settings/settings.service';
import { PasskeyService } from '../auth/passkey.service';
import { AuthService } from '../auth/auth.service';
import { PermissionsService } from '../permissions/permissions.service';
@@ -69,14 +67,12 @@ const VERSION_FAILURE_TTL = 60_000;
export class AdminService {
constructor(
private readonly db: DatabaseService,
private readonly settings: SettingsService,
private readonly addons: AddonsService,
private readonly passkeys: PasskeyService,
private readonly auth: AuthService,
private readonly permissions: PermissionsService,
private readonly notifications: NotificationsService,
private readonly userCleanup: UserCleanupService,
private readonly notifPrefs: NotificationPreferencesService,
) {}
// ── User CRUD ──────────────────────────────────────────────────────────────
@@ -318,50 +314,6 @@ export class AdminService {
return { entries, total, limit, offset };
}
// ── OIDC Settings ──────────────────────────────────────────────────────────
getOidcSettings() {
const get = (key: string) =>
this.db.get<{ value: string }>('SELECT value FROM app_settings WHERE key = ?', key)?.value || '';
const secret = decrypt_api_key(get('oidc_client_secret'));
return {
issuer: get('oidc_issuer'),
client_id: get('oidc_client_id'),
client_secret_set: !!secret,
display_name: get('oidc_display_name'),
oidc_only: get('oidc_only') === 'true',
discovery_url: get('oidc_discovery_url'),
};
}
updateOidcSettings(data: {
issuer?: string;
client_id?: string;
client_secret?: string;
display_name?: string;
discovery_url?: string;
}): { error?: string; status?: number; success?: boolean } {
// Lockout prevention: can't remove OIDC config when password login is disabled
if ((data.issuer === '' || data.client_id === '') && !this.auth.resolveAuthToggles().password_login) {
return {
error: 'Cannot remove SSO configuration while password login is disabled. Enable password login first.',
status: 400,
};
}
const set = (key: string, val: string) =>
this.db.run('INSERT OR REPLACE INTO app_settings (key, value) VALUES (?, ?)', key, val || '');
// All five writes are one SSO config — a partial apply would leave the
// instance with an issuer but no client id (or vice versa).
this.db.transaction(() => {
set('oidc_issuer', data.issuer ?? '');
set('oidc_client_id', data.client_id ?? '');
if (data.client_secret !== undefined) set('oidc_client_secret', maybe_encrypt_api_key(data.client_secret) ?? '');
set('oidc_display_name', data.display_name ?? '');
set('oidc_discovery_url', data.discovery_url ?? '');
});
return { success: true };
}
// ── Demo Baseline ──────────────────────────────────────────────────────────
@@ -790,8 +742,4 @@ export class AdminService {
// ── Settings + notification preference helpers (non-admin-service modules) ──
getAdminUserDefaults() { return this.settings.getAdminUserDefaults(); }
setAdminUserDefaults(body: Record<string, unknown>) { return this.settings.setAdminUserDefaults(body); }
getPreferencesMatrix(userId: number, role: string) { return this.notifPrefs.getPreferencesMatrix(userId, role, 'admin'); }
setAdminPreferences(userId: number, body: unknown) { return this.notifPrefs.setAdminPreferences(userId, body as Parameters<NotificationPreferencesService['setAdminPreferences']>[1]); }
}
@@ -22,6 +22,9 @@ import {
NotificationRespondDto,
} from './notifications.dto';
import { JwtAuthGuard } from '../auth/jwt-auth.guard';
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';
// The masked placeholder the client sends instead of a stored secret (8× U+2022).
@@ -199,3 +202,30 @@ export class NotificationsController {
return id;
}
}
/**
* /api/admin/notification-preferences — the admin-scope row of the preference matrix.
*
* Two routes that sat on AdminController and reached NotificationPreferencesService
* through a pair of pass-through methods on AdminService. The owner is here; the
* 'admin' scope argument they always passed is now written once, at the only place
* that uses it.
*/
@Controller('api/admin/notification-preferences')
@UseGuards(JwtAuthGuard, AdminGuard)
export class AdminNotificationPreferencesController {
constructor(private readonly prefs: NotificationPreferencesService) {}
@Get()
get(@CurrentUser() user: User) {
return this.prefs.getPreferencesMatrix(user.id, user.role, 'admin');
}
@Put()
set(@CurrentUser() user: User, @Body() body: AdminNotificationPreferencesDto) {
this.prefs.setAdminPreferences(user.id, body);
// Answer with the refreshed matrix rather than the raw write result — the admin
// panel renders straight from this response.
return this.prefs.getPreferencesMatrix(user.id, user.role, 'admin');
}
}
@@ -1,5 +1,5 @@
import { Module } from '@nestjs/common';
import { NotificationsController } from './notifications.controller';
import { AdminNotificationPreferencesController, NotificationsController } from './notifications.controller';
import { NotificationsMcp } from './notifications.mcp';
import { NotificationsService } from './notifications.service';
import { NotificationPreferencesService } from './notification-preferences.service';
@@ -17,7 +17,7 @@ import { AuthModule } from '../auth/auth.module';
* the plugin RPC surface, HostSurfaceRpc). */
@Module({
imports: [AuthModule, MailerModule],
controllers: [NotificationsController],
controllers: [NotificationsController, AdminNotificationPreferencesController],
providers: [NotificationsService, NotificationPreferencesService, WebhookService, NtfyService, NotificationsMcp],
exports: [NotificationsService, NotificationPreferencesService],
})
+49 -1
View File
@@ -1,8 +1,15 @@
import { Controller, Get, Query, Req, Res } from '@nestjs/common';
import { Body, Controller, Get, HttpException, Put, Query, Req, Res, UseGuards } from '@nestjs/common';
import type { Request, Response } from 'express';
import { readEnv } from '../../app-config';
import { OidcService, OIDC_STATE_TTL_MS } from './oidc.service';
import { cookieOptions } from '../common/cookie';
import { AdminGuard } from '../auth/admin.guard';
import { JwtAuthGuard } from '../auth/jwt-auth.guard';
import { CurrentUser } from '../auth/current-user.decorator';
import type { User } from '../../types';
import { AuditService } from '../audit/audit.service';
import { getClientIp } from '../audit/client-ip';
import { AdminOidcUpdateDto } from '../admin/admin.dto';
const OIDC_STATE_COOKIE = 'trek_oidc_state';
@@ -165,3 +172,44 @@ export class OidcController {
res.json({ token: result.token });
}
}
/**
* /api/admin/oidc — the SSO configuration.
*
* Two routes that sat on AdminController with their SQL in AdminService, for a domain
* that already had a module. They read and write the same five app_settings keys the
* login flow next door consumes, so they belong here; the lockout guard that refuses
* to remove the config while password login is off lives with them in OidcService.
*
* The path, the {error,status} envelope and the audit action are unchanged.
*/
@Controller('api/admin/oidc')
@UseGuards(JwtAuthGuard, AdminGuard)
export class AdminOidcController {
constructor(
private readonly oidc: OidcService,
private readonly audit: AuditService,
) {}
@Get()
get() {
return this.oidc.getOidcSettings();
}
@Put()
update(@CurrentUser() user: User, @Body() body: AdminOidcUpdateDto, @Req() req: Request) {
const result = this.oidc.updateOidcSettings(body);
if (result.error) {
throw new HttpException({ error: result.error }, result.status || 400);
}
// Only whether an issuer was set, never the value: the details column is readable
// by every admin and the issuer identifies the customer's IdP tenant.
this.audit.writeAudit({
userId: user.id,
action: 'admin.oidc_update',
ip: getClientIp(req),
details: { issuer_set: !!body.issuer },
});
return { success: true };
}
}
+4 -3
View File
@@ -1,12 +1,13 @@
import { Module } from '@nestjs/common';
import { OidcController } from './oidc.controller';
import { AdminOidcController, OidcController } from './oidc.controller';
import { AuditModule } from '../audit/audit.module';
import { OidcService } from './oidc.service';
import { AuthModule } from '../auth/auth.module';
import { TripMembershipModule } from '../trip-membership/trip-membership.module';
@Module({
imports: [AuthModule, TripMembershipModule],
controllers: [OidcController],
imports: [AuthModule, TripMembershipModule, AuditModule],
controllers: [OidcController, AdminOidcController],
providers: [OidcService],
})
export class OidcModule {}
+50 -1
View File
@@ -8,7 +8,7 @@ import type { Request, Response } from 'express';
import { readEnv, getAppUrl } from '../../app-config';
import { JWT_SECRET, SESSION_DURATION_SECONDS } from '../../config';
import { User } from '../../types';
import { decrypt_api_key } from '../common/crypto/apiKeyCrypto';
import { decrypt_api_key, maybe_encrypt_api_key } from '../common/crypto/apiKeyCrypto';
import { TripMembershipService } from '../trip-membership/trip-membership.service';
import { setAuthCookie } from '../common/cookie';
import { AuthService } from '../auth/auth.service';
@@ -620,4 +620,53 @@ export class OidcService implements OnModuleDestroy {
touchLastLogin(userId: number): void {
this.db.prepare('UPDATE users SET last_login = CURRENT_TIMESTAMP, login_count = login_count + 1 WHERE id = ?').run(userId);
}
// ── OIDC settings ──────────────────────────────────────────────────────────
// Moved here from AdminService, which held the SQL for a domain that already had a
// module of its own. The lockout guard below is the reason this cannot be a plain
// settings write: removing the SSO config while password login is off would lock
// every user out of the instance.
getOidcSettings() {
const get = (key: string) =>
this.db.get<{ value: string }>('SELECT value FROM app_settings WHERE key = ?', key)?.value || '';
const secret = decrypt_api_key(get('oidc_client_secret'));
return {
issuer: get('oidc_issuer'),
client_id: get('oidc_client_id'),
client_secret_set: !!secret,
display_name: get('oidc_display_name'),
oidc_only: get('oidc_only') === 'true',
discovery_url: get('oidc_discovery_url'),
};
}
updateOidcSettings(data: {
issuer?: string;
client_id?: string;
client_secret?: string;
display_name?: string;
discovery_url?: string;
}): { error?: string; status?: number; success?: boolean } {
// Lockout prevention: can't remove OIDC config when password login is disabled
if ((data.issuer === '' || data.client_id === '') && !this.auth.resolveAuthToggles().password_login) {
return {
error: 'Cannot remove SSO configuration while password login is disabled. Enable password login first.',
status: 400,
};
}
const set = (key: string, val: string) =>
this.db.run('INSERT OR REPLACE INTO app_settings (key, value) VALUES (?, ?)', key, val || '');
// All five writes are one SSO config — a partial apply would leave the
// instance with an issuer but no client id (or vice versa).
this.db.transaction(() => {
set('oidc_issuer', data.issuer ?? '');
set('oidc_client_id', data.client_id ?? '');
if (data.client_secret !== undefined) set('oidc_client_secret', maybe_encrypt_api_key(data.client_secret) ?? '');
set('oidc_display_name', data.display_name ?? '');
set('oidc_discovery_url', data.discovery_url ?? '');
});
return { success: true };
}
}
@@ -1,9 +1,14 @@
import { Body, Controller, Get, HttpCode, HttpException, Post, Put, UseGuards } from '@nestjs/common';
import { Body, Controller, Get, HttpCode, HttpException, Post, Put, Req, UseGuards } from '@nestjs/common';
import type { Request } from 'express';
import { MASKED_SETTING_VALUE } from '@trek/shared';
import type { User } from '../../types';
import { SettingsService } from './settings.service';
import { SettingUpsertDto, SettingsBulkDto } from './settings.dto';
import { AdminDefaultUserSettingsDto } from '../admin/admin.dto';
import { JwtAuthGuard } from '../auth/jwt-auth.guard';
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';
/**
@@ -46,3 +51,42 @@ export class SettingsController {
}
}
}
/**
* /api/admin/default-user-settings — the defaults a new account starts with.
*
* These two routes sat on AdminController and reached SettingsService through a pair
* of pass-through methods on AdminService that did nothing but forward. The owner is
* here, so the routes are too; the path and both response shapes are unchanged.
*/
@Controller('api/admin/default-user-settings')
@UseGuards(JwtAuthGuard, AdminGuard)
export class AdminDefaultUserSettingsController {
constructor(
private readonly settings: SettingsService,
private readonly audit: AuditService,
) {}
@Get()
get() {
return this.settings.getAdminUserDefaults();
}
@Put()
update(@CurrentUser() user: User, @Body() body: AdminDefaultUserSettingsDto, @Req() req: Request) {
try {
this.settings.setAdminUserDefaults(body as unknown as Record<string, unknown>);
this.audit.writeAudit({
userId: user.id,
action: 'admin.default_user_settings_update',
ip: getClientIp(req),
details: body as Record<string, unknown>,
});
// Answer with the stored defaults, not the request body: the service normalises
// and drops unknown keys, and the admin panel renders straight from this.
return this.settings.getAdminUserDefaults();
} catch (err) {
throw new HttpException({ error: err instanceof Error ? err.message : String(err) }, 400);
}
}
}
+6 -2
View File
@@ -1,10 +1,14 @@
import { Module } from '@nestjs/common';
import { SettingsController } from './settings.controller';
import { AdminDefaultUserSettingsController, SettingsController } from './settings.controller';
import { AuthModule } from '../auth/auth.module';
import { AuditModule } from '../audit/audit.module';
import { SettingsService } from './settings.service';
/** Exports SettingsService for in-container consumers (admin, share, llm-parse). */
@Module({
controllers: [SettingsController],
// AuthModule for the admin gate on the defaults routes.
imports: [AuthModule, AuditModule],
controllers: [SettingsController, AdminDefaultUserSettingsController],
providers: [SettingsService],
exports: [SettingsService],
})