From 2ac6c76086ee56121008b51c18f35267e42e1595 Mon Sep 17 00:00:00 2001 From: jubnl Date: Sun, 2 Aug 2026 15:07:55 +0200 Subject: [PATCH] chore: move admin backend to proper DI MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The 851-line services/adminService folds into the wrapper AdminService over DatabaseService plus injected Settings/Addons/Passkey/Packing/Auth/Permissions/ Notifications services; the auth, notifications and permissions bridge imports all become injections, PERMISSION_ACTIONS stays a plain const, and the mcp/sessionManager deep import keeps its anti-cycle comment. Ahead of the fold the 11 packing-template functions move to PackingService, which already owned all three template tables — resolving the admin-2 residual with no bridge. The pure and module-scoped half moves to admin.helpers.ts, the version cache staying module-scoped so admin.bridge's instance and the container singleton share one GitHub fetch. A 1-export admin.bridge.ts serves scheduler.ts's cron, the only out-of-container consumer. Recipe steps 3 and 4 are no-ops: no src/mcp/tools/ admin.ts has ever existed and the plugin host never imported the domain. Four lines are non-verbatim, all path re-anchoring one directory deeper, both resolved paths verified against the emitted dist layout. admin.dto.ts clears all twenty AdminController allow-list entries, retiring the three 'enabled must be a boolean' checks plus 'permissions object required' and 'Object body required' for the pipe envelope. The module e2e goes DI-native: the 3-method whole-module mock dies, 6 cases become 15 over real SQL. Quirk fixes on top, each pinned: the three places toggles go fail-closed with an append-only backfill migration; the template item routes honour :templateId; updateUser rejects an empty username/email; createInvite 404s an unresolvable trip_id; listOAuthSessions guards its scopes parse; GitHub fetches gain a timeout and size cap and failures cache briefly; updateOidcSettings/updateAddon/updateUser become transactional; admin.oauth_session.revoke is renamed to match its siblings; two mutations gain their missing audit rows; getAuditLog drops the _parse_error sentinel. Tests move with IDs preserved (ADMIN-SVC-001..069 incl. the pre-existing 029/030 gap and duplicated 069, VNOTIF-001..007), plus ADMIN-BR-001 and ADMIN-SVC-070..076. --- server/src/db/migrations.ts | 11 + server/src/nest/admin/admin.bridge.ts | 47 + server/src/nest/admin/admin.controller.ts | 84 +- server/src/nest/admin/admin.dto.ts | 38 + server/src/nest/admin/admin.helpers.ts | 95 ++ server/src/nest/admin/admin.module.ts | 9 +- server/src/nest/admin/admin.service.ts | 874 +++++++++++++++- .../nest/common/body-contract-allow-list.ts | 20 - server/src/nest/packing/packing.mcp.ts | 3 +- server/src/nest/packing/packing.service.ts | 121 +++ server/src/scheduler.ts | 2 +- server/src/services/adminService.ts | 968 ------------------ server/tests/e2e/admin.e2e.test.ts | 169 ++- .../tests/unit/nest/admin.controller.test.ts | 18 +- .../admin.service.test.ts} | 386 +++---- .../admin.version-notification.test.ts} | 43 +- .../tests/unit/nest/packing.service.test.ts | 211 +++- 17 files changed, 1755 insertions(+), 1344 deletions(-) create mode 100644 server/src/nest/admin/admin.bridge.ts create mode 100644 server/src/nest/admin/admin.dto.ts create mode 100644 server/src/nest/admin/admin.helpers.ts delete mode 100644 server/src/services/adminService.ts rename server/tests/unit/{services/adminService.test.ts => nest/admin.service.test.ts} (67%) rename server/tests/unit/{services/versionNotification.test.ts => nest/admin.version-notification.test.ts} (73%) diff --git a/server/src/db/migrations.ts b/server/src/db/migrations.ts index 7719d4e2a..bbf68c0d2 100644 --- a/server/src/db/migrations.ts +++ b/server/src/db/migrations.ts @@ -3830,6 +3830,17 @@ function runMigrations(db: Database.Database): void { const hasRouteColor = db.prepare("SELECT 1 FROM pragma_table_info('places') WHERE name = 'route_color'").get(); if (!hasRouteColor) db.exec('ALTER TABLE places ADD COLUMN route_color TEXT'); }, + + // Backfill the three places feature toggles before their read flips from + // fail-open (`value !== 'false'`) to fail-closed (`value === 'true'`), so + // existing installs that never touched the admin switches keep the features + // they have today. A row that already says 'false' is left alone. + () => { + const insert = db.prepare("INSERT OR IGNORE INTO app_settings (key, value) VALUES (?, 'true')"); + for (const key of ['places_photos_enabled', 'places_autocomplete_enabled', 'places_details_enabled']) { + insert.run(key); + } + }, ]; if (currentVersion < migrations.length) { diff --git a/server/src/nest/admin/admin.bridge.ts b/server/src/nest/admin/admin.bridge.ts new file mode 100644 index 000000000..592f92d2b --- /dev/null +++ b/server/src/nest/admin/admin.bridge.ts @@ -0,0 +1,47 @@ +import { db } from '../../db/database'; +import { DatabaseService } from '../database/database.service'; +import { RealtimeService } from '../realtime/realtime.service'; +import { AddonsService } from '../addons/addons.service'; +import { SettingsService } from '../settings/settings.service'; +import { AuthService } from '../auth/auth.service'; +import { PasskeyService } from '../auth/passkey.service'; +import { AtlasService } from '../atlas/atlas.service'; +import { PackingService } from '../packing/packing.service'; +import { PermissionsService } from '../permissions/permissions.service'; +import { NotificationsService } from '../notifications/notifications.service'; +import { AdminService } from './admin.service'; + +/** + * Non-Nest entry point for the admin domain — for code running OUTSIDE the Nest + * container. Exactly one consumer: the daily version-check cron in + * scheduler.ts, which lazy-requires this instead of the retired + * services/adminService. Exports the legacy name 1:1 so the repoint was an + * import-path-only diff. Inside the container, inject AdminService instead. + * Delete this file if the scheduler ever moves into Nest's @nestjs/schedule. + * + * The 5-minute version cache is module-scoped in admin.helpers.ts, so this + * instance and the container singleton share it — the cron and + * GET /api/admin/version-check hit GitHub once between them, as they did before + * the fold. + * + * Module-level construction is safe: `db` is the reinitialize-proof Proxy onto + * the shared better-sqlite3 singleton. + */ +const dbs = new DatabaseService(db); +const realtime = new RealtimeService(); +const permissions = new PermissionsService(dbs); +const auth = new AuthService(dbs, permissions, new AtlasService(dbs)); +const admin = new AdminService( + dbs, + new SettingsService(dbs), + new AddonsService(dbs), + new PasskeyService(dbs, auth), + new PackingService(dbs, permissions, realtime), + auth, + permissions, + new NotificationsService(dbs, realtime), +); + +export function checkAndNotifyVersion(): Promise { + return admin.checkAndNotifyVersion(); +} diff --git a/server/src/nest/admin/admin.controller.ts b/server/src/nest/admin/admin.controller.ts index cb7a943e3..64e5f12cf 100644 --- a/server/src/nest/admin/admin.controller.ts +++ b/server/src/nest/admin/admin.controller.ts @@ -2,6 +2,20 @@ import { Body, Controller, Delete, Get, HttpCode, HttpException, NotFoundExcepti import type { Request } from 'express'; import { readEnv } from '../../app-config'; import { AdminService } from './admin.service'; +import { + AdminUserCreateDto, + AdminUserUpdateDto, + AdminPermissionsDto, + AdminInviteCreateDto, + AdminFeatureToggleDto, + AdminTemplateNameDto, + AdminOidcUpdateDto, + AdminAddonUpdateDto, + AdminCollabFeaturesDto, + AdminNotificationPreferencesDto, + AdminDefaultUserSettingsDto, + AdminTestNotificationDto, +} from './admin.dto'; import { PluginRuntimeService } from '../plugins/plugin-runtime.service'; import { JwtAuthGuard } from '../auth/jwt-auth.guard'; import { AdminGuard } from '../auth/admin.guard'; @@ -30,6 +44,12 @@ function ok(result: T): Exclude { * admin-gated, the {error,status} envelopes, the audit-log writes, the MCP * session invalidation on addon/collab changes, create-201 vs the rest 200, and * the dev-only test-notification endpoint (404 outside development). + * + * Bodies validate via admin.dto.ts (@trek/shared schemas through the global + * ZodValidationPipe) — malformed bodies now get the pipe's standard + * { error: 'field: message; …' } envelope instead of the old inline typeof + * checks (the sanctioned ratchet behavior); valid bodies behave identically, + * and every bespoke service-level 400 is untouched. */ @Controller('api/admin') @UseGuards(JwtAuthGuard, AdminGuard) @@ -47,14 +67,14 @@ export class AdminController { @Post('users') @HttpCode(201) - createUser(@CurrentUser() user: User, @Body() body: unknown, @Req() req: Request) { - const result = ok(this.admin.createUser(body)); + createUser(@CurrentUser() user: User, @Body() body: AdminUserCreateDto, @Req() req: Request) { + const result = ok(this.admin.createUser(body as Parameters[0])); this.audit.writeAudit({ userId: user.id, action: 'admin.user_create', resource: String(result.insertedId), ip: getClientIp(req), details: result.auditDetails }); return { user: result.user }; } @Put('users/:id') - updateUser(@CurrentUser() user: User, @Param('id') id: string, @Body() body: unknown, @Req() req: Request) { + updateUser(@CurrentUser() user: User, @Param('id') id: string, @Body() body: AdminUserUpdateDto, @Req() req: Request) { const result = ok(this.admin.updateUser(id, body)); this.audit.writeAudit({ userId: user.id, action: 'admin.user_update', resource: String(id), ip: getClientIp(req), details: { targetUser: result.previousEmail, fields: result.changed } }); logInfo(`Admin ${user.email} edited user ${result.previousEmail} (fields: ${result.changed.join(', ')})`); @@ -84,10 +104,7 @@ export class AdminController { permissions() { return this.admin.getPermissions(); } @Put('permissions') - savePermissions(@CurrentUser() user: User, @Body() body: { permissions?: unknown }, @Req() req: Request) { - if (!body.permissions || typeof body.permissions !== 'object') { - throw new HttpException({ error: 'permissions object required' }, 400); - } + savePermissions(@CurrentUser() user: User, @Body() body: AdminPermissionsDto, @Req() req: Request) { const result = this.admin.savePermissions(body.permissions as unknown as Parameters[0]); this.audit.writeAudit({ userId: user.id, action: 'admin.permissions_update', resource: 'permissions', ip: getClientIp(req), details: body.permissions as Record }); return { success: true, permissions: result.permissions, ...(result.skipped.length ? { skipped: result.skipped } : {}) }; @@ -101,7 +118,7 @@ export class AdminController { getOidc() { return this.admin.getOidcSettings(); } @Put('oidc') - updateOidc(@CurrentUser() user: User, @Body() body: { issuer?: string } & Record, @Req() req: Request) { + 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); @@ -135,7 +152,7 @@ export class AdminController { getNotificationPrefs(@CurrentUser() user: User) { return this.admin.getPreferencesMatrix(user.id, user.role); } @Put('notification-preferences') - setNotificationPrefs(@CurrentUser() user: User, @Body() body: unknown) { + setNotificationPrefs(@CurrentUser() user: User, @Body() body: AdminNotificationPreferencesDto) { this.admin.setAdminPreferences(user.id, body); return this.admin.getPreferencesMatrix(user.id, user.role); } @@ -150,7 +167,7 @@ export class AdminController { @Post('invites') @HttpCode(201) - createInvite(@CurrentUser() user: User, @Body() body: unknown, @Req() req: Request) { + createInvite(@CurrentUser() user: User, @Body() body: AdminInviteCreateDto, @Req() req: Request) { const result = this.admin.createInvite(user.id, body); this.audit.writeAudit({ userId: user.id, action: 'admin.invite_create', resource: String(result.inviteId), ip: getClientIp(req), details: { max_uses: result.uses, expires_in_days: result.expiresInDays, trip_id: result.tripId } }); return { invite: result.invite }; @@ -168,7 +185,7 @@ export class AdminController { getBagTracking() { return this.admin.getBagTracking(); } @Put('bag-tracking') - updateBagTracking(@CurrentUser() user: User, @Body() body: { enabled?: unknown }, @Req() req: Request) { + updateBagTracking(@CurrentUser() user: User, @Body() body: AdminFeatureToggleDto, @Req() req: Request) { const result = this.admin.updateBagTracking(body.enabled); this.audit.writeAudit({ userId: user.id, action: 'admin.bag_tracking', ip: getClientIp(req), details: { enabled: result.enabled } }); return result; @@ -178,8 +195,7 @@ export class AdminController { getPlacesPhotos() { return this.admin.getPlacesPhotos(); } @Put('places-photos') - updatePlacesPhotos(@CurrentUser() user: User, @Body() body: { enabled?: unknown }, @Req() req: Request) { - if (typeof body.enabled !== 'boolean') throw new HttpException({ error: 'enabled must be a boolean' }, 400); + updatePlacesPhotos(@CurrentUser() user: User, @Body() body: AdminFeatureToggleDto, @Req() req: Request) { const result = this.admin.updatePlacesPhotos(body.enabled); this.audit.writeAudit({ userId: user.id, action: 'admin.places_photos', ip: getClientIp(req), details: { enabled: result.enabled } }); return result; @@ -189,8 +205,7 @@ export class AdminController { getPlacesAutocomplete() { return this.admin.getPlacesAutocomplete(); } @Put('places-autocomplete') - updatePlacesAutocomplete(@CurrentUser() user: User, @Body() body: { enabled?: unknown }, @Req() req: Request) { - if (typeof body.enabled !== 'boolean') throw new HttpException({ error: 'enabled must be a boolean' }, 400); + updatePlacesAutocomplete(@CurrentUser() user: User, @Body() body: AdminFeatureToggleDto, @Req() req: Request) { const result = this.admin.updatePlacesAutocomplete(body.enabled); this.audit.writeAudit({ userId: user.id, action: 'admin.places_autocomplete', ip: getClientIp(req), details: { enabled: result.enabled } }); return result; @@ -200,8 +215,7 @@ export class AdminController { getPlacesDetails() { return this.admin.getPlacesDetails(); } @Put('places-details') - updatePlacesDetails(@CurrentUser() user: User, @Body() body: { enabled?: unknown }, @Req() req: Request) { - if (typeof body.enabled !== 'boolean') throw new HttpException({ error: 'enabled must be a boolean' }, 400); + updatePlacesDetails(@CurrentUser() user: User, @Body() body: AdminFeatureToggleDto, @Req() req: Request) { const result = this.admin.updatePlacesDetails(body.enabled); this.audit.writeAudit({ userId: user.id, action: 'admin.places_details', ip: getClientIp(req), details: { enabled: result.enabled } }); return result; @@ -211,7 +225,7 @@ export class AdminController { getCollabFeatures() { return this.admin.getCollabFeatures(); } @Put('collab-features') - updateCollabFeatures(@CurrentUser() user: User, @Body() body: unknown, @Req() req: Request) { + updateCollabFeatures(@CurrentUser() user: User, @Body() body: AdminCollabFeaturesDto, @Req() req: Request) { const { features, changed } = this.admin.updateCollabFeatures(body); // Collab flags gate MCP registration, but a no-op save must not tear down // every live MCP session (#1414). @@ -229,12 +243,14 @@ export class AdminController { @Post('packing-templates') @HttpCode(201) - createPackingTemplate(@CurrentUser() user: User, @Body() body: { name?: unknown }) { - return ok(this.admin.createPackingTemplate(body.name, user.id)); + createPackingTemplate(@CurrentUser() user: User, @Body() body: AdminTemplateNameDto, @Req() req: Request) { + const result = ok(this.admin.createPackingTemplate(body.name, user.id)); + this.audit.writeAudit({ userId: user.id, action: 'admin.packing_template_create', resource: String((result.template as { id?: number } | undefined)?.id ?? ''), ip: getClientIp(req), details: { name: body.name } }); + return result; } @Put('packing-templates/:id') - updatePackingTemplate(@Param('id') id: string, @Body() body: unknown) { return ok(this.admin.updatePackingTemplate(id, body)); } + updatePackingTemplate(@Param('id') id: string, @Body() body: AdminTemplateNameDto) { return ok(this.admin.updatePackingTemplate(id, body)); } @Delete('packing-templates/:id') deletePackingTemplate(@CurrentUser() user: User, @Param('id') id: string, @Req() req: Request) { @@ -245,12 +261,12 @@ export class AdminController { @Post('packing-templates/:id/categories') @HttpCode(201) - createTemplateCategory(@Param('id') id: string, @Body() body: { name?: unknown }) { + createTemplateCategory(@Param('id') id: string, @Body() body: AdminTemplateNameDto) { return ok(this.admin.createTemplateCategory(id, body.name)); } @Put('packing-templates/:templateId/categories/:catId') - updateTemplateCategory(@Param('templateId') templateId: string, @Param('catId') catId: string, @Body() body: unknown) { + updateTemplateCategory(@Param('templateId') templateId: string, @Param('catId') catId: string, @Body() body: AdminTemplateNameDto) { return ok(this.admin.updateTemplateCategory(templateId, catId, body)); } @@ -262,16 +278,16 @@ export class AdminController { @Post('packing-templates/:templateId/categories/:catId/items') @HttpCode(201) - createTemplateItem(@Param('templateId') templateId: string, @Param('catId') catId: string, @Body() body: { name?: unknown }) { + createTemplateItem(@Param('templateId') templateId: string, @Param('catId') catId: string, @Body() body: AdminTemplateNameDto) { return ok(this.admin.createTemplateItem(templateId, catId, body.name)); } @Put('packing-templates/:templateId/items/:itemId') - updateTemplateItem(@Param('itemId') itemId: string, @Body() body: unknown) { return ok(this.admin.updateTemplateItem(itemId, body)); } + updateTemplateItem(@Param('templateId') templateId: string, @Param('itemId') itemId: string, @Body() body: AdminTemplateNameDto) { return ok(this.admin.updateTemplateItem(templateId, itemId, body)); } @Delete('packing-templates/:templateId/items/:itemId') - deleteTemplateItem(@Param('itemId') itemId: string) { - ok(this.admin.deleteTemplateItem(itemId)); + deleteTemplateItem(@Param('templateId') templateId: string, @Param('itemId') itemId: string) { + ok(this.admin.deleteTemplateItem(templateId, itemId)); return { success: true }; } @@ -280,7 +296,7 @@ export class AdminController { listAddons() { return { addons: this.admin.listAddons() }; } @Put('addons/:id') - async updateAddon(@CurrentUser() user: User, @Param('id') id: string, @Body() body: unknown, @Req() req: Request) { + async updateAddon(@CurrentUser() user: User, @Param('id') id: string, @Body() body: AdminAddonUpdateDto, @Req() req: Request) { const result = ok(this.admin.updateAddon(id, body)); this.audit.writeAudit({ userId: user.id, action: 'admin.addon_update', resource: String(id), ip: getClientIp(req), details: result.auditDetails }); // Sessions only need re-creating when the registered MCP surface can @@ -301,8 +317,9 @@ export class AdminController { listMcpTokens() { return { tokens: this.admin.listMcpTokens() }; } @Delete('mcp-tokens/:id') - deleteMcpToken(@Param('id') id: string) { + deleteMcpToken(@CurrentUser() user: User, @Param('id') id: string, @Req() req: Request) { ok(this.admin.deleteMcpToken(id)); + this.audit.writeAudit({ userId: user.id, action: 'admin.mcp_token_delete', resource: String(id), ip: getClientIp(req) }); return { success: true }; } @@ -312,7 +329,7 @@ export class AdminController { @Delete('oauth-sessions/:id') revokeOAuthSession(@CurrentUser() user: User, @Param('id') id: string, @Req() req: Request) { ok(this.admin.revokeOAuthSession(id)); - this.audit.writeAudit({ userId: user.id, action: 'admin.oauth_session.revoke', resource: String(id), ip: getClientIp(req) }); + this.audit.writeAudit({ userId: user.id, action: 'admin.oauth_session_revoke', resource: String(id), ip: getClientIp(req) }); return { success: true }; } @@ -333,10 +350,7 @@ export class AdminController { getDefaultUserSettings() { return this.admin.getAdminUserDefaults(); } @Put('default-user-settings') - setDefaultUserSettings(@CurrentUser() user: User, @Body() body: unknown, @Req() req: Request) { - if (!body || typeof body !== 'object' || Array.isArray(body)) { - throw new HttpException({ error: 'Object body required' }, 400); - } + setDefaultUserSettings(@CurrentUser() user: User, @Body() body: AdminDefaultUserSettingsDto, @Req() req: Request) { try { this.admin.setAdminUserDefaults(body as unknown as Record); this.audit.writeAudit({ userId: user.id, action: 'admin.default_user_settings_update', ip: getClientIp(req), details: body as Record }); @@ -349,7 +363,7 @@ export class AdminController { // ── Dev-only: test notification (404 outside development, mirroring the conditional mount) ── @Post('dev/test-notification') @HttpCode(200) - async devTestNotification(@CurrentUser() user: User, @Body() body: { event?: string; scope?: string; targetId?: number; params?: Record; inApp?: boolean }) { + async devTestNotification(@CurrentUser() user: User, @Body() body: AdminTestNotificationDto) { if (!readEnv().app.isDevelopment) { throw new NotFoundException(); } diff --git a/server/src/nest/admin/admin.dto.ts b/server/src/nest/admin/admin.dto.ts new file mode 100644 index 000000000..d795ba011 --- /dev/null +++ b/server/src/nest/admin/admin.dto.ts @@ -0,0 +1,38 @@ +import { createZodDto } from 'nestjs-zod'; +import { + adminUserCreateRequestSchema, + adminUserUpdateRequestSchema, + adminPermissionsRequestSchema, + adminInviteCreateRequestSchema, + adminFeatureToggleRequestSchema, + adminTemplateNameRequestSchema, + adminOidcUpdateRequestSchema, + adminAddonUpdateRequestSchema, + adminCollabFeaturesRequestSchema, + adminNotificationPreferencesRequestSchema, + adminDefaultUserSettingsRequestSchema, + adminTestNotificationRequestSchema, +} from '@trek/shared'; + +/** + * Server-side createZodDto wrappers over the @trek/shared admin contracts. The + * global ZodValidationPipe (APP_PIPE in app.module.ts) validates any @Body() + * parameter typed with one of these classes by metatype — the Zod schemas in + * shared/ remain the single source of truth for the wire contract. + * + * Twelve classes cover the twenty grandfathered AdminController body contracts: + * the four feature toggles share AdminFeatureToggleDto and the six + * packing-template create/update routes share AdminTemplateNameDto. + */ +export class AdminUserCreateDto extends createZodDto(adminUserCreateRequestSchema) {} +export class AdminUserUpdateDto extends createZodDto(adminUserUpdateRequestSchema) {} +export class AdminPermissionsDto extends createZodDto(adminPermissionsRequestSchema) {} +export class AdminInviteCreateDto extends createZodDto(adminInviteCreateRequestSchema) {} +export class AdminFeatureToggleDto extends createZodDto(adminFeatureToggleRequestSchema) {} +export class AdminTemplateNameDto extends createZodDto(adminTemplateNameRequestSchema) {} +export class AdminOidcUpdateDto extends createZodDto(adminOidcUpdateRequestSchema) {} +export class AdminAddonUpdateDto extends createZodDto(adminAddonUpdateRequestSchema) {} +export class AdminCollabFeaturesDto extends createZodDto(adminCollabFeaturesRequestSchema) {} +export class AdminNotificationPreferencesDto extends createZodDto(adminNotificationPreferencesRequestSchema) {} +export class AdminDefaultUserSettingsDto extends createZodDto(adminDefaultUserSettingsRequestSchema) {} +export class AdminTestNotificationDto extends createZodDto(adminTestNotificationRequestSchema) {} diff --git a/server/src/nest/admin/admin.helpers.ts b/server/src/nest/admin/admin.helpers.ts new file mode 100644 index 000000000..c06ed7aff --- /dev/null +++ b/server/src/nest/admin/admin.helpers.ts @@ -0,0 +1,95 @@ +import fs from 'fs'; + +/** + * Pure + module-scoped half of the admin domain, relocated verbatim from + * services/adminService.ts with the 2026-08 fold (auth.helpers / maps.helpers / + * atlas-geo precedent). + * + * The version cache is module-scoped **on purpose** (the permissions-cache + * precedent, permissions.bridge.ts): scheduler.ts reaches checkAndNotifyVersion + * through admin.bridge's instance while GET /api/admin/version-check runs on the + * container singleton, and the legacy module shared one 5-minute cache between + * them. Instance state would double the GitHub traffic and let the scheduler + * notify on a version the UI has not seen yet. + */ + +/** bcrypt cost factor for user passwords — kept in sync with authService. */ +export const BCRYPT_COST = 12; + +export function utcSuffix(ts: string | null | undefined): string | null { + if (!ts) return null; + return ts.endsWith('Z') ? ts : ts.replace(' ', 'T') + 'Z'; +} + +export function compareVersions(a: string, b: string): number { + const parse = (v: string) => { + const [base, pre] = v.split('-pre.'); + const parts = base.split('.').map(Number); + const n = pre !== undefined ? parseInt(pre, 10) : null; + const preN = n !== null && Number.isFinite(n) ? n : null; + return { parts, preN }; + }; + const pa = parse(a), + pb = parse(b); + for (let i = 0; i < Math.max(pa.parts.length, pb.parts.length); i++) { + const na = pa.parts[i] || 0, + nb = pb.parts[i] || 0; + if (na > nb) return 1; + if (na < nb) return -1; + } + // Equal base: stable > prerelease; higher preN wins among prereleases + if (pa.preN === null && pb.preN !== null) return 1; + if (pa.preN !== null && pb.preN === null) return -1; + if (pa.preN !== null && pb.preN !== null) { + if (pa.preN > pb.preN) return 1; + if (pa.preN < pb.preN) return -1; + } + return 0; +} + +/** + * Documented parity exception to the "modules must be importable without side + * effects" rule (auth.helpers.ts's import-time DUMMY_PASSWORD_HASH precedent): + * this probes the filesystem at module evaluation, exactly as the legacy module + * did. Making it lazy would change *when* `fs` is consulted relative to a + * suite's vi.mock setup, and so could shift `is_docker` in checkVersion + * payloads. + */ +export const isDocker = (() => { + try { + return ( + fs.existsSync('/.dockerenv') || + (fs.existsSync('/proc/1/cgroup') && fs.readFileSync('/proc/1/cgroup', 'utf8').includes('docker')) + ); + } catch { + return false; + } +})(); + +export interface VersionInfo { + current: string; + latest: string; + update_available: boolean; + release_url?: string; + is_docker: boolean; + is_prerelease: boolean; +} + +const VERSION_CACHE_TTL = 5 * 60 * 1000; // 5 minutes +let _versionCache: { data: VersionInfo; expiresAt: number } | null = null; + +/** Cached payload while inside the TTL, otherwise null. */ +export function readVersionCache(): VersionInfo | null { + if (_versionCache && Date.now() < _versionCache.expiresAt) return _versionCache.data; + return null; +} + +/** `ttl` overrides the 5-minute default — failed checks cache on a shorter one. */ +export function writeVersionCache(data: VersionInfo, ttl: number = VERSION_CACHE_TTL): void { + _versionCache = { data, expiresAt: Date.now() + ttl }; +} + +/** Test-only: clear the in-memory version cache. */ +export function __clearVersionCacheForTests(): void { + _versionCache = null; +} diff --git a/server/src/nest/admin/admin.module.ts b/server/src/nest/admin/admin.module.ts index 66759c984..95d90efb7 100644 --- a/server/src/nest/admin/admin.module.ts +++ b/server/src/nest/admin/admin.module.ts @@ -9,9 +9,16 @@ import { AddonsModule } from '../addons/addons.module'; import { AuthModule } from '../auth/auth.module'; // NotificationsModule exports NotificationsService for the dev test-notification send. import { NotificationsModule } from '../notifications/notifications.module'; +// PackingModule exports PackingService, which owns the packing-template tables +// backing the admin /packing-templates routes. Cycle-free: PackingModule imports +// only PermissionsModule + AuthModule, neither of which reaches AdminModule. +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'; @Module({ - imports: [PluginsModule, SettingsModule, AuditModule, AddonsModule, AuthModule, NotificationsModule], + imports: [PluginsModule, SettingsModule, AuditModule, AddonsModule, AuthModule, NotificationsModule, PackingModule, PermissionsModule], controllers: [AdminController], providers: [AdminService], }) diff --git a/server/src/nest/admin/admin.service.ts b/server/src/nest/admin/admin.service.ts index 79dd7ce1d..f108b274c 100644 --- a/server/src/nest/admin/admin.service.ts +++ b/server/src/nest/admin/admin.service.ts @@ -1,87 +1,853 @@ import { Injectable } from '@nestjs/common'; -import * as svc from '../../services/adminService'; +import bcrypt from 'bcryptjs'; +import crypto from 'crypto'; +import fs from 'fs'; +import path from 'path'; +import { ADDON_IDS } from '../../addons'; +import { readEnv } from '../../app-config'; +import { updateJwtSecret } from '../../config'; +// Import from sessionManager directly, NOT the ../../mcp barrel: the barrel pulls +// the whole tools fan-out (and via the domain bridges, the Nest services) into +// every consumer of this module — a nest→mcp→nest module cycle. The +// invalidateMcpSessions barrel import below predates the fold and is deliberately +// separate: it is only reached from the controller, never from admin.bridge. +import { revokeUserSessions, revokeUserSessionsForClient } from '../../mcp/sessionManager'; +import { invalidateMcpSessions } from '../../mcp'; +import { emitUserDeleted } from '../../plugin-user-lifecycle'; +import type { User, Addon } from '../../types'; +import { maybe_encrypt_api_key, decrypt_api_key } from '../../services/apiKeyCrypto'; +import { avatarUrl } from '../../services/avatarUrl'; +import { prepareLlmAddonConfigForWrite, maskLlmAddonConfig } from '../../services/llmConfig'; +import { getPhotoProviderConfig } from '../../services/memories/helpersService'; +import { validatePassword } from '../../services/passwordPolicy'; +import { deleteUserCompletely } from '../../services/userCleanupService'; +import { getPreferencesMatrix, setAdminPreferences } from '../../services/notificationPreferencesService'; +import { DatabaseService } from '../database/database.service'; import { AddonsService } from '../addons/addons.service'; import { SettingsService } from '../settings/settings.service'; -import { invalidateMcpSessions } from '../../mcp'; -import { getPreferencesMatrix, setAdminPreferences } from '../../services/notificationPreferencesService'; import { PasskeyService } from '../auth/passkey.service'; +import { AuthService } from '../auth/auth.service'; +import { PackingService } from '../packing/packing.service'; +import { PermissionsService } from '../permissions/permissions.service'; +import { PERMISSION_ACTIONS } from '../permissions/permissions.service'; +import { NotificationsService } from '../notifications/notifications.service'; +import { + BCRYPT_COST, + compareVersions, + isDocker, + readVersionCache, + utcSuffix, + writeVersionCache, + type VersionInfo, +} from './admin.helpers'; + +/** Outbound GitHub calls: hard timeout and response-size cap (server/CLAUDE.md). */ +const GITHUB_TIMEOUT_MS = 10_000; +const GITHUB_MAX_BYTES = 2_000_000; +/** Failed version checks cache briefly so an outage isn't refetched per page load. */ +const VERSION_FAILURE_TTL = 60_000; /** - * Thin Nest wrapper around the existing admin service (+ the settings, - * MCP-session and notification-preference helpers the legacy route used). All - * business logic, audit-relevant return shapes and the addon/MCP invalidation - * reuse the legacy code unchanged. + * Admin domain service — owns the admin SQL (folded from the legacy + * services/adminService.ts with the 2026-08 migration): user CRUD, instance + * stats, the permission matrix, the audit-log read side, OIDC settings, the + * demo baseline, GitHub release/version checks, invite tokens, the three + * places feature toggles, addons + photo providers, MCP tokens, OAuth sessions + * and JWT rotation. + * + * Every quirk relocated byte-for-byte: the `||` falsy defaults (never `??`), + * post-insert/post-update re-selects instead of RETURNING, the COALESCE partial + * update, the #1362 guest exclusions and the exact error strings. The legacy + * `{ error, status }` envelope is the return contract — the controller's `ok()` + * helper turns it into an HttpException, so nothing here throws. + * + * The bag-tracking/collab-feature toggles, user defaults, passkey reset and + * packing templates delegate to the services that own those tables. The pure + * and module-scoped pieces (compareVersions, isDocker, the version cache) live + * in admin.helpers.ts. */ @Injectable() export class AdminService { constructor( + private readonly db: DatabaseService, private readonly settings: SettingsService, private readonly addons: AddonsService, private readonly passkeys: PasskeyService, + private readonly packing: PackingService, + private readonly auth: AuthService, + private readonly permissions: PermissionsService, + private readonly notifications: NotificationsService, ) {} - // Users - listUsers() { return svc.listUsers(); } - createUser(body: unknown) { return svc.createUser(body as Parameters[0]); } - updateUser(id: string, body: unknown) { return svc.updateUser(id, body as Parameters[1]); } - deleteUser(id: string, actingUserId: number) { return svc.deleteUser(id, actingUserId); } + // ── User CRUD ────────────────────────────────────────────────────────────── + + listUsers() { + // Guests (#1362) are accountless trip participants, not real users — keep them out + // of admin user management entirely. + const users = this.db.all< + Pick & { + avatar?: string | null; + } + >( + 'SELECT id, username, email, role, avatar, created_at, updated_at, last_login FROM users WHERE COALESCE(is_guest, 0) = 0 ORDER BY created_at DESC', + ); + let onlineUserIds = new Set(); + try { + // Lazy require: the ws singleton must not become a load-time dependency. + const { getOnlineUserIds } = require('../../websocket'); + onlineUserIds = getOnlineUserIds(); + } catch { + /* */ + } + return users.map((u) => ({ + ...u, + avatar_url: avatarUrl(u), + created_at: utcSuffix(u.created_at), + updated_at: utcSuffix(u.updated_at as string), + last_login: utcSuffix(u.last_login), + online: onlineUserIds.has(u.id), + })); + } + + createUser(data: { username: string; email: string; password: string; role?: string }) { + const username = data.username?.trim(); + const email = data.email?.trim(); + const password = data.password?.trim(); + + if (!username || !email || !password) { + return { error: 'Username, email and password are required', status: 400 }; + } + + const pwCheck = validatePassword(password); + if (!pwCheck.ok) return { error: pwCheck.reason, status: 400 }; + + if (data.role && !['user', 'admin'].includes(data.role)) { + return { error: 'Invalid role', status: 400 }; + } + + // Guests (#1362) live in a reserved synthetic namespace; never let one block a real account. + const existingUsername = this.db.get('SELECT id FROM users WHERE username = ? AND COALESCE(is_guest, 0) = 0', username); + if (existingUsername) return { error: 'Username already taken', status: 409 }; + + const existingEmail = this.db.get('SELECT id FROM users WHERE email = ? AND COALESCE(is_guest, 0) = 0', email); + if (existingEmail) return { error: 'Email already taken', status: 409 }; + + const passwordHash = bcrypt.hashSync(password, BCRYPT_COST); + + const result = this.db.run( + 'INSERT INTO users (username, email, password_hash, role) VALUES (?, ?, ?, ?)', + username, email, passwordHash, data.role || 'user', + ); + + const user = this.db.get( + 'SELECT id, username, email, role, created_at, updated_at FROM users WHERE id = ?', + result.lastInsertRowid, + ); + + return { + user, + insertedId: Number(result.lastInsertRowid), + auditDetails: { username, email, role: data.role || 'user' }, + }; + } + + updateUser(id: string, data: { username?: string; email?: string; role?: string; password?: string }) { + const username = typeof data.username === 'string' ? data.username.trim() : data.username; + const email = typeof data.email === 'string' ? data.email.trim() : data.email; + const { role, password } = data; + const user = this.db.get('SELECT * FROM users WHERE id = ?', id); + + if (!user) return { error: 'User not found', status: 404 }; + + if (role && !['user', 'admin'].includes(role)) { + return { error: 'Invalid role', status: 400 }; + } + + // An empty string used to fall through `username || null` into COALESCE and + // silently mean "leave unchanged". Say so instead of pretending it worked. + if (username === '') return { error: 'Username cannot be empty', status: 400 }; + if (email === '') return { error: 'Email cannot be empty', status: 400 }; + + if (username && username !== user.username) { + const conflict = this.db.get('SELECT id FROM users WHERE username = ? AND id != ? AND COALESCE(is_guest, 0) = 0', username, id); + if (conflict) return { error: 'Username already taken', status: 409 }; + } + if (email && email !== user.email) { + const conflict = this.db.get('SELECT id FROM users WHERE email = ? AND id != ? AND COALESCE(is_guest, 0) = 0', email, id); + if (conflict) return { error: 'Email already taken', status: 409 }; + } + + if (password) { + const pwCheck = validatePassword(password); + if (!pwCheck.ok) return { error: pwCheck.reason, status: 400 }; + } + const passwordHash = password ? bcrypt.hashSync(password, BCRYPT_COST) : null; + + // Don't let the admin UI demote the last remaining admin — that would leave the + // instance with no one able to manage it (and on OIDC-only setups, no recovery). #1274 + if (role && role !== 'admin') { + const current = this.db.get<{ role?: string }>('SELECT role FROM users WHERE id = ?', id); + if (current?.role === 'admin') { + const adminCount = this.db.get<{ count: number }>("SELECT COUNT(*) as count FROM users WHERE role = 'admin'")!.count; + if (adminCount <= 1) return { error: 'Cannot remove the last admin', status: 400 }; + } + } + + this.db.transaction(() => { + this.db.run( + ` + UPDATE users SET + username = COALESCE(?, username), + email = COALESCE(?, email), + role = COALESCE(?, role), + password_hash = COALESCE(?, password_hash), + updated_at = CURRENT_TIMESTAMP + WHERE id = ? + `, + username || null, email || null, role || null, passwordHash, id, + ); + }); + + const updated = this.db.get('SELECT id, username, email, role, created_at, updated_at FROM users WHERE id = ?', id); + + const changed: string[] = []; + if (username) changed.push('username'); + if (email) changed.push('email'); + if (role) changed.push('role'); + if (password) changed.push('password'); + + return { + user: updated, + previousEmail: user.email, + changed, + }; + } + + deleteUser(id: string, currentUserId: number) { + if (parseInt(id) === currentUserId) { + return { error: 'Cannot delete own account', status: 400 }; + } + + const userToDel = this.db.get<{ id: number; email: string }>('SELECT id, email FROM users WHERE id = ?', id); + if (!userToDel) return { error: 'User not found', status: 404 }; + + deleteUserCompletely(userToDel.id); + emitUserDeleted(userToDel.id); // let plugins erase their own per-user data + return { email: userToDel.email }; + } + resetUserPasskeys(id: string) { return this.passkeys.adminResetPasskeys(Number(id)); } - getStats() { return svc.getStats(); } - getPermissions() { return svc.getPermissions(); } - savePermissions(permissions: Parameters[0]) { return svc.savePermissions(permissions); } - getAuditLog(query: { limit?: string; offset?: string }) { return svc.getAuditLog(query); } + // ── Stats ────────────────────────────────────────────────────────────────── - getOidcSettings() { return svc.getOidcSettings(); } - updateOidcSettings(body: unknown) { return svc.updateOidcSettings(body as Parameters[0]); } - saveDemoBaseline() { return svc.saveDemoBaseline(); } + getStats() { + const totalUsers = this.db.get<{ count: number }>('SELECT COUNT(*) as count FROM users WHERE COALESCE(is_guest, 0) = 0')!.count; + const totalTrips = this.db.get<{ count: number }>('SELECT COUNT(*) as count FROM trips')!.count; + const totalPlaces = this.db.get<{ count: number }>('SELECT COUNT(*) as count FROM places')!.count; + const totalFiles = this.db.get<{ count: number }>('SELECT COUNT(*) as count FROM trip_files')!.count; + return { totalUsers, totalTrips, totalPlaces, totalFiles }; + } - getGithubReleases(perPage: string, page: string) { return svc.getGithubReleases(perPage, page); } - checkVersion() { return svc.checkVersion(); } + // ── Permissions ──────────────────────────────────────────────────────────── - // Invites - listInvites() { return svc.listInvites(); } - listTripsForInvite() { return svc.listTripsForInvite(); } - createInvite(userId: number, body: unknown) { return svc.createInvite(userId, body as Parameters[1]); } - deleteInvite(id: string) { return svc.deleteInvite(id); } + getPermissions() { + const current = this.permissions.getAllPermissions(); + const actions = PERMISSION_ACTIONS.map((a) => ({ + key: a.key, + level: current[a.key], + defaultLevel: a.defaultLevel, + allowedLevels: a.allowedLevels, + })); + return { permissions: actions }; + } + + savePermissions(permissions: Record) { + const { skipped } = this.permissions.savePermissions(permissions); + return { permissions: this.permissions.getAllPermissions(), skipped }; + } + + // ── Audit Log ────────────────────────────────────────────────────────────── + + getAuditLog(query: { limit?: string; offset?: string }) { + const limitRaw = parseInt(String(query.limit || '100'), 10); + const offsetRaw = parseInt(String(query.offset || '0'), 10); + const limit = Math.min(Math.max(Number.isFinite(limitRaw) ? limitRaw : 100, 1), 500); + const offset = Math.max(Number.isFinite(offsetRaw) ? offsetRaw : 0, 0); + + type Row = { + id: number; + created_at: string; + user_id: number | null; + username: string | null; + user_email: string | null; + action: string; + resource: string | null; + details: string | null; + ip: string | null; + }; + + const rows = this.db.all( + ` + SELECT a.id, a.created_at, a.user_id, u.username, u.email as user_email, a.action, a.resource, a.details, a.ip + FROM audit_log a + LEFT JOIN users u ON u.id = a.user_id + ORDER BY a.id DESC + LIMIT ? OFFSET ? + `, + limit, offset, + ); + + const total = this.db.get<{ c: number }>('SELECT COUNT(*) as c FROM audit_log')!.c; + + const entries = rows.map((r) => { + // Unparseable details fall back to the raw string rather than the old + // { _parse_error: true } sentinel, which the admin UI rendered literally. + let details: Record | string | null = null; + if (r.details) { + try { + details = JSON.parse(r.details) as Record; + } catch { + details = r.details; + } + } + const created_at = + r.created_at && !r.created_at.endsWith('Z') ? r.created_at.replace(' ', 'T') + 'Z' : r.created_at; + return { ...r, created_at, details }; + }); + + 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 ────────────────────────────────────────────────────────── + + saveDemoBaseline(): { error?: string; status?: number; message?: string } { + if (!readEnv().demo.enabled) { + return { error: 'Not found', status: 404 }; + } + try { + // Lazy require: demo-reset is a demo-only module. + const { saveBaseline } = require('../../demo/demo-reset'); + saveBaseline(); + return { message: 'Demo baseline saved. Hourly resets will restore to this state.' }; + } catch (err: unknown) { + console.error(err); + return { error: 'Failed to save baseline', status: 500 }; + } + } + + // ── GitHub Integration ───────────────────────────────────────────────────── + + /** + * GitHub fetch with the timeout + size cap the outbound-fetch rule requires + * (server/CLAUDE.md). Returns null on any failure; callers decide the fallback. + */ + private async fetchGithub(url: string): Promise { + try { + const resp = await fetch(url, { + headers: { Accept: 'application/vnd.github.v3+json', 'User-Agent': 'TREK-Server' }, + signal: AbortSignal.timeout(GITHUB_TIMEOUT_MS), + }); + if (!resp.ok) return null; + const text = await resp.text(); + if (text.length > GITHUB_MAX_BYTES) { + console.error(`[admin] GitHub response exceeded ${GITHUB_MAX_BYTES} bytes, ignoring`); + return null; + } + return JSON.parse(text); + } catch (err: unknown) { + console.error(`[admin] GitHub request failed: ${err instanceof Error ? err.message : String(err)}`); + return null; + } + } + + async getGithubReleases(perPage: string = '10', page: string = '1') { + const data = await this.fetchGithub( + `https://api.github.com/repos/liketrek/TREK/releases?per_page=${perPage}&page=${page}`, + ); + return Array.isArray(data) ? data : []; + } + + async checkVersion(): Promise { + 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.'); + const fallback: VersionInfo = { + current: currentVersion, + latest: currentVersion, + update_available: false, + is_docker: isDocker, + is_prerelease: isPrerelease, + }; + + // Failures cache too (on a shorter TTL), so a GitHub outage doesn't mean a + // live fetch on every admin page load — the legacy code only cached success. + const fail = () => { + writeVersionCache(fallback, VERSION_FAILURE_TTL); + return fallback; + }; + + let result: VersionInfo; + if (isPrerelease) { + // Fetch release list and find the newest prerelease + const data = await this.fetchGithub('https://api.github.com/repos/liketrek/TREK/releases?per_page=100') as + | Array<{ tag_name?: string; html_url?: string; prerelease?: boolean }> + | null; + if (!data) return fail(); + const prereleases = Array.isArray(data) ? data.filter((r) => r.prerelease) : []; + if (!prereleases.length) return fail(); + // Pre-compute stripped versions, then sort descending + const tagged = prereleases.map((r) => ({ r, v: (r.tag_name || '').replace(/^v/, '') })); + tagged.sort((a, b) => compareVersions(b.v, a.v)); + const latest = tagged[0].v; + const update_available = !!latest && latest !== currentVersion && compareVersions(latest, currentVersion) > 0; + result = { + current: currentVersion, + latest, + update_available, + release_url: tagged[0].r.html_url || '', + is_docker: isDocker, + is_prerelease: true, + }; + } else { + const data = await this.fetchGithub('https://api.github.com/repos/liketrek/TREK/releases/latest') as + | { tag_name?: string; html_url?: string } + | null; + if (!data) return fail(); + const latest = (data.tag_name || '').replace(/^v/, ''); + const update_available = !!latest && latest !== currentVersion && compareVersions(latest, currentVersion) > 0; + result = { + current: currentVersion, + latest, + update_available, + release_url: data.html_url || '', + is_docker: isDocker, + is_prerelease: false, + }; + } + + writeVersionCache(result); + return result; + } + + async checkAndNotifyVersion(): Promise { + try { + const result = await this.checkVersion(); + if (!result.update_available) return; + + const lastNotified = this.db.get<{ value: string }>( + 'SELECT value FROM app_settings WHERE key = ?', 'last_notified_version', + )?.value; + if (lastNotified === result.latest) return; + + this.db.run( + 'INSERT OR REPLACE INTO app_settings (key, value) VALUES (?, ?)', + 'last_notified_version', result.latest, + ); + + await this.notifications.send({ + event: 'version_available', + actorId: null, + scope: 'admin', + targetId: 0, + params: { version: result.latest }, + }); + } catch { + // Silently ignore — version check is non-critical + } + } + + // ── Invite Tokens ────────────────────────────────────────────────────────── + + listInvites() { + return this.db.all(` + SELECT i.*, u.username as created_by_name, t.title as trip_title + FROM invite_tokens i + JOIN users u ON i.created_by = u.id + LEFT JOIN trips t ON i.trip_id = t.id + ORDER BY i.created_at DESC + `); + } + + /** Trips an admin can bind an invite to — id + title only, for the picker (#1402). */ + listTripsForInvite() { + return this.db.all('SELECT id, title FROM trips ORDER BY title COLLATE NOCASE ASC'); + } + + createInvite( + createdBy: number, + data: { max_uses?: string | number; expires_in_days?: string | number; trip_id?: string | number | null }, + ) { + const rawUses = parseInt(String(data.max_uses)); + const uses = rawUses === 0 ? 0 : Math.min(Math.max(rawUses || 1, 1), 5); + const token = crypto.randomBytes(16).toString('hex'); + const expiresAt = data.expires_in_days + ? new Date(Date.now() + parseInt(String(data.expires_in_days)) * 86400000).toISOString() + : null; + + // Optional trip binding: only persist a trip that actually exists, so a stale + // or forged id can never bind (and never auto-adds anyone on registration). + let tripId: number | null = null; + if (data.trip_id != null && String(data.trip_id).trim() !== '') { + const parsed = parseInt(String(data.trip_id)); + if (!Number.isInteger(parsed) || !this.db.get('SELECT id FROM trips WHERE id = ?', parsed)) { + // Used to bind null silently, handing back a plain registration invite + // the admin never asked for. + return { error: 'Trip not found', status: 404 }; + } + tripId = parsed; + } + + const ins = this.db.run( + 'INSERT INTO invite_tokens (token, max_uses, expires_at, created_by, trip_id) VALUES (?, ?, ?, ?, ?)', + token, uses, expiresAt, createdBy, tripId, + ); + + const inviteId = Number(ins.lastInsertRowid); + const invite = this.db.get(` + SELECT i.*, u.username as created_by_name, t.title as trip_title + FROM invite_tokens i + JOIN users u ON i.created_by = u.id + LEFT JOIN trips t ON i.trip_id = t.id + WHERE i.id = ? + `, inviteId); + + return { invite, inviteId, uses, expiresInDays: data.expires_in_days ?? null, tripId }; + } + + deleteInvite(id: string) { + const invite = this.db.get('SELECT id FROM invite_tokens WHERE id = ?', id); + if (!invite) return { error: 'Invite not found', status: 404 }; + this.db.run('DELETE FROM invite_tokens WHERE id = ?', id); + return {}; + } + + // ── Feature toggles ──────────────────────────────────────────────────────── + // Bag-tracking and the collab features are owned by AddonsService (finding + // `admin-1`). The three places flags read `=== 'true'` — fail-closed, matching + // AddonsService.getBagTracking(). They read `!== 'false'` (fail-open) before + // the 2026-08 quirk fix; a migration backfills 'true' for installs that never + // touched the switches, so nobody loses a feature on upgrade. - // Feature toggles getBagTracking() { return this.addons.getBagTracking(); } updateBagTracking(enabled: unknown) { return this.addons.updateBagTracking(enabled as boolean); } - getPlacesPhotos() { return svc.getPlacesPhotos(); } - updatePlacesPhotos(enabled: boolean) { return svc.updatePlacesPhotos(enabled); } - getPlacesAutocomplete() { return svc.getPlacesAutocomplete(); } - updatePlacesAutocomplete(enabled: boolean) { return svc.updatePlacesAutocomplete(enabled); } - getPlacesDetails() { return svc.getPlacesDetails(); } - updatePlacesDetails(enabled: boolean) { return svc.updatePlacesDetails(enabled); } getCollabFeatures() { return this.addons.getCollabFeatures(); } updateCollabFeatures(body: unknown) { return this.addons.updateCollabFeatures(body as Parameters[0]); } - // Packing templates - listPackingTemplates() { return svc.listPackingTemplates(); } - getPackingTemplate(id: string) { return svc.getPackingTemplate(id); } - createPackingTemplate(name: unknown, userId: number) { return svc.createPackingTemplate(name as string, userId); } - updatePackingTemplate(id: string, body: unknown) { return svc.updatePackingTemplate(id, body as Parameters[1]); } - deletePackingTemplate(id: string) { return svc.deletePackingTemplate(id); } - createTemplateCategory(templateId: string, name: unknown) { return svc.createTemplateCategory(templateId, name as string); } - updateTemplateCategory(templateId: string, catId: string, body: unknown) { return svc.updateTemplateCategory(templateId, catId, body as Parameters[2]); } - deleteTemplateCategory(templateId: string, catId: string) { return svc.deleteTemplateCategory(templateId, catId); } - createTemplateItem(templateId: string, catId: string, name: unknown) { return svc.createTemplateItem(templateId, catId, name as string); } - updateTemplateItem(itemId: string, body: unknown) { return svc.updateTemplateItem(itemId, body as Parameters[1]); } - deleteTemplateItem(itemId: string) { return svc.deleteTemplateItem(itemId); } + getPlacesPhotos() { + const row = this.db.get<{ value: string }>("SELECT value FROM app_settings WHERE key = 'places_photos_enabled'"); + return { enabled: row?.value === 'true' }; + } - // Addons + tokens + sessions - listAddons() { return svc.listAddons(); } - updateAddon(id: string, body: unknown) { return svc.updateAddon(id, body as Parameters[1]); } - listMcpTokens() { return svc.listMcpTokens(); } - deleteMcpToken(id: string) { return svc.deleteMcpToken(id); } - listOAuthSessions() { return svc.listOAuthSessions(); } - revokeOAuthSession(id: string) { return svc.revokeOAuthSession(id); } - rotateJwtSecret() { return svc.rotateJwtSecret(); } + updatePlacesPhotos(enabled: boolean) { + this.db.run("INSERT OR REPLACE INTO app_settings (key, value) VALUES ('places_photos_enabled', ?)", enabled ? 'true' : 'false'); + return { enabled: !!enabled }; + } + + getPlacesAutocomplete() { + const row = this.db.get<{ value: string }>("SELECT value FROM app_settings WHERE key = 'places_autocomplete_enabled'"); + return { enabled: row?.value === 'true' }; + } + + updatePlacesAutocomplete(enabled: boolean) { + this.db.run("INSERT OR REPLACE INTO app_settings (key, value) VALUES ('places_autocomplete_enabled', ?)", enabled ? 'true' : 'false'); + return { enabled: !!enabled }; + } + + getPlacesDetails() { + const row = this.db.get<{ value: string }>("SELECT value FROM app_settings WHERE key = 'places_details_enabled'"); + return { enabled: row?.value === 'true' }; + } + + updatePlacesDetails(enabled: boolean) { + this.db.run("INSERT OR REPLACE INTO app_settings (key, value) VALUES ('places_details_enabled', ?)", enabled ? 'true' : 'false'); + return { enabled: !!enabled }; + } + + // ── Packing templates ────────────────────────────────────────────────────── + // The SQL lives in PackingService, which owns all three template tables (see + // its "Admin Template CRUD" block). + + listPackingTemplates() { return this.packing.listPackingTemplates(); } + getPackingTemplate(id: string) { return this.packing.getPackingTemplate(id); } + createPackingTemplate(name: unknown, userId: number) { return this.packing.createPackingTemplate(name as string, userId); } + updatePackingTemplate(id: string, body: unknown) { return this.packing.updatePackingTemplate(id, body as Parameters[1]); } + deletePackingTemplate(id: string) { return this.packing.deletePackingTemplate(id); } + createTemplateCategory(templateId: string, name: unknown) { return this.packing.createTemplateCategory(templateId, name as string); } + updateTemplateCategory(templateId: string, catId: string, body: unknown) { return this.packing.updateTemplateCategory(templateId, catId, body as Parameters[2]); } + deleteTemplateCategory(templateId: string, catId: string) { return this.packing.deleteTemplateCategory(templateId, catId); } + createTemplateItem(templateId: string, catId: string, name: unknown) { return this.packing.createTemplateItem(templateId, catId, name as string); } + updateTemplateItem(templateId: string, itemId: string, body: unknown) { return this.packing.updateTemplateItem(templateId, itemId, body as Parameters[2]); } + deleteTemplateItem(templateId: string, itemId: string) { return this.packing.deleteTemplateItem(templateId, itemId); } + + // ── Addons ───────────────────────────────────────────────────────────────── + + listAddons() { + const addons = this.db.all('SELECT * FROM addons ORDER BY sort_order, id'); + const providers = this.db.all<{ + id: string; + name: string; + description?: string | null; + icon: string; + enabled: number; + sort_order: number; + }>(` + SELECT id, name, description, icon, enabled, sort_order + FROM photo_providers + ORDER BY sort_order, id + `); + const fields = this.db.all<{ + provider_id: string; + field_key: string; + label: string; + input_type: string; + placeholder?: string | null; + required: number; + secret: number; + settings_key?: string | null; + payload_key?: string | null; + sort_order: number; + }>(` + SELECT provider_id, field_key, label, input_type, placeholder, required, secret, settings_key, payload_key, sort_order + FROM photo_provider_fields + ORDER BY sort_order, id + `); + const fieldsByProvider = new Map(); + for (const field of fields) { + const arr = fieldsByProvider.get(field.provider_id) || []; + arr.push(field); + fieldsByProvider.set(field.provider_id, arr); + } + + return [ + ...addons.map((a) => ({ + ...a, + enabled: !!a.enabled, + config: + a.id === ADDON_IDS.LLM_PARSING + ? maskLlmAddonConfig(JSON.parse(a.config || '{}')) + : JSON.parse(a.config || '{}'), + })), + ...providers.map((p) => ({ + id: p.id, + name: p.name, + description: p.description, + type: 'photo_provider', + icon: p.icon, + enabled: !!p.enabled, + config: getPhotoProviderConfig(p.id), + fields: (fieldsByProvider.get(p.id) || []).map((f) => ({ + key: f.field_key, + label: f.label, + input_type: f.input_type, + placeholder: f.placeholder || '', + required: !!f.required, + secret: !!f.secret, + settings_key: f.settings_key || null, + payload_key: f.payload_key || null, + sort_order: f.sort_order, + })), + sort_order: p.sort_order, + })), + ]; + } + + updateAddon(id: string, data: { enabled?: boolean; config?: Record }) { + type ProviderRow = { id: string; name: string; description?: string | null; icon: string; enabled: number; sort_order: number }; + const addon = this.db.get('SELECT * FROM addons WHERE id = ?', id); + const provider = this.db.get('SELECT * FROM photo_providers WHERE id = ?', id); + if (!addon && !provider) return { error: 'Addon not found', status: 404 }; + + this.db.transaction(() => { + if (addon) { + if (data.enabled !== undefined) + this.db.run('UPDATE addons SET enabled = ? WHERE id = ?', data.enabled ? 1 : 0, id); + if (data.config !== undefined) { + // The AI-parsing addon holds an API key — encrypt it at rest and preserve + // the stored key when the client echoes the mask sentinel (see llmConfig.ts). + const configToStore = + id === ADDON_IDS.LLM_PARSING + ? prepareLlmAddonConfigForWrite(data.config, JSON.parse(addon.config || '{}')) + : data.config; + this.db.run('UPDATE addons SET config = ? WHERE id = ?', JSON.stringify(configToStore), id); + } + } else { + if (data.enabled !== undefined) + this.db.run('UPDATE photo_providers SET enabled = ? WHERE id = ?', data.enabled ? 1 : 0, id); + } + }); + + const updatedAddon = this.db.get('SELECT * FROM addons WHERE id = ?', id); + const updatedProvider = this.db.get('SELECT * FROM photo_providers WHERE id = ?', id); + const updated = updatedAddon + ? { + ...updatedAddon, + enabled: !!updatedAddon.enabled, + config: + updatedAddon.id === ADDON_IDS.LLM_PARSING + ? maskLlmAddonConfig(JSON.parse(updatedAddon.config || '{}')) + : JSON.parse(updatedAddon.config || '{}'), + } + : updatedProvider + ? { + id: updatedProvider.id, + name: updatedProvider.name, + description: updatedProvider.description, + type: 'photo_provider', + icon: updatedProvider.icon, + enabled: !!updatedProvider.enabled, + config: getPhotoProviderConfig(updatedProvider.id), + sort_order: updatedProvider.sort_order, + } + : null; + + // Only these addons gate MCP tool/resource/prompt registration (see + // registerTools/registerResources) — and only a real enabled-flip changes + // what a session would register. Config-only saves, photo providers and + // MCP-irrelevant addons must not tear down every live session (#1414). + const MCP_RELEVANT_ADDONS = new Set([ + ADDON_IDS.MCP, + ADDON_IDS.PACKING, + ADDON_IDS.BUDGET, + ADDON_IDS.COLLAB, + ADDON_IDS.ATLAS, + ADDON_IDS.VACAY, + ADDON_IDS.JOURNEY, + ]); + const enabledChanged = !!addon && data.enabled !== undefined && (data.enabled ? 1 : 0) !== addon.enabled; + + return { + addon: updated, + mcpAffected: enabledChanged && MCP_RELEVANT_ADDONS.has(id), + auditDetails: { + enabled: data.enabled !== undefined ? !!data.enabled : undefined, + config_changed: data.config !== undefined, + }, + }; + } + + // ── MCP Tokens ───────────────────────────────────────────────────────────── + + listMcpTokens() { + return this.db.all(` + SELECT t.id, t.name, t.token_prefix, t.created_at, t.last_used_at, t.user_id, u.username + FROM mcp_tokens t + JOIN users u ON u.id = t.user_id + ORDER BY t.created_at DESC + `); + } + + deleteMcpToken(id: string) { + const token = this.db.get<{ id: number; user_id: number }>('SELECT id, user_id FROM mcp_tokens WHERE id = ?', id); + if (!token) return { error: 'Token not found', status: 404 }; + this.db.run('DELETE FROM mcp_tokens WHERE id = ?', id); + revokeUserSessions(token.user_id); + return {}; + } + + // ── OAuth Sessions ───────────────────────────────────────────────────────── + + listOAuthSessions() { + const rows = this.db.all & { scopes: string }>(` + SELECT ot.id, ot.client_id, oc.name AS client_name, ot.user_id, u.username, + ot.scopes, ot.access_token_expires_at, ot.refresh_token_expires_at, ot.created_at + FROM oauth_tokens ot + JOIN oauth_clients oc ON ot.client_id = oc.client_id + JOIN users u ON u.id = ot.user_id + WHERE ot.revoked_at IS NULL + AND ot.refresh_token_expires_at > CURRENT_TIMESTAMP + ORDER BY ot.created_at DESC + `); + // One malformed row must not 500 the whole admin OAuth-sessions panel. + return rows.map((r) => { + let scopes: unknown; + try { + scopes = JSON.parse(r.scopes); + } catch { + scopes = null; + } + return { ...r, scopes }; + }); + } + + revokeOAuthSession(id: string) { + const row = this.db.get<{ id: number; user_id: number; client_id: string }>( + 'SELECT id, user_id, client_id FROM oauth_tokens WHERE id = ?', id, + ); + if (!row) return { error: 'Session not found', status: 404 }; + this.db.run('UPDATE oauth_tokens SET revoked_at = CURRENT_TIMESTAMP WHERE id = ?', id); + revokeUserSessionsForClient(row.user_id, row.client_id); + return {}; + } + + // ── JWT Rotation ─────────────────────────────────────────────────────────── + + rotateJwtSecret(): { error?: string; status?: number } { + const newSecret = crypto.randomBytes(32).toString('hex'); + // Re-anchored one directory deeper for nest/admin/ (was '../../data' in services/). + const dataDir = path.resolve(__dirname, '../../../data'); + const secretFile = path.join(dataDir, '.jwt_secret'); + try { + if (!fs.existsSync(dataDir)) fs.mkdirSync(dataDir, { recursive: true }); + fs.writeFileSync(secretFile, newSecret, { mode: 0o600 }); + } catch { + return { error: 'Failed to persist new JWT secret to disk', status: 500 }; + } + updateJwtSecret(newSecret); + return {}; + } invalidateMcpSessions() { invalidateMcpSessions(); } - // Settings + notification preference helpers (non-admin-service modules) + // ── Settings + notification preference helpers (non-admin-service modules) ── + getAdminUserDefaults() { return this.settings.getAdminUserDefaults(); } setAdminUserDefaults(body: Record) { return this.settings.setAdminUserDefaults(body); } getPreferencesMatrix(userId: number, role: string) { return getPreferencesMatrix(userId, role, 'admin'); } diff --git a/server/src/nest/common/body-contract-allow-list.ts b/server/src/nest/common/body-contract-allow-list.ts index 6692a68da..be1393433 100644 --- a/server/src/nest/common/body-contract-allow-list.ts +++ b/server/src/nest/common/body-contract-allow-list.ts @@ -8,26 +8,6 @@ * here — the gate throws on stale entries, so removal is enforced too. */ export const BODY_CONTRACT_ALLOW_LIST: string[] = [ - 'AdminController.createInvite', - 'AdminController.createPackingTemplate', - 'AdminController.createTemplateCategory', - 'AdminController.createTemplateItem', - 'AdminController.createUser', - 'AdminController.devTestNotification', - 'AdminController.savePermissions', - 'AdminController.setDefaultUserSettings', - 'AdminController.setNotificationPrefs', - 'AdminController.updateAddon', - 'AdminController.updateBagTracking', - 'AdminController.updateCollabFeatures', - 'AdminController.updateOidc', - 'AdminController.updatePackingTemplate', - 'AdminController.updatePlacesAutocomplete', - 'AdminController.updatePlacesDetails', - 'AdminController.updatePlacesPhotos', - 'AdminController.updateTemplateCategory', - 'AdminController.updateTemplateItem', - 'AdminController.updateUser', 'BackupController.updateAutoSettings', 'BookingImportController.confirm', 'BookingImportController.preview', diff --git a/server/src/nest/packing/packing.mcp.ts b/server/src/nest/packing/packing.mcp.ts index a13eb0642..7f1fbeb71 100644 --- a/server/src/nest/packing/packing.mcp.ts +++ b/server/src/nest/packing/packing.mcp.ts @@ -7,7 +7,6 @@ import { import { z } from 'zod'; import { AuthService } from '../auth/auth.service'; import { isAddonEnabled } from '../addons/addons.bridge'; -import { deletePackingTemplate } from '../../services/adminService'; import { ADDON_IDS } from '../../addons'; import { safeBroadcast, noAccess, hasTripPermission, permissionDenied, isAdminUser, adminRequired } from '../../mcp/tools/_shared'; import { PackingService } from './packing.service'; @@ -371,7 +370,7 @@ export class PackingMcp { if (this.auth.isDemoUser(ctx.userId)) return demoDenied(); // Templates are global; the REST route restricts management to admins. Match it. if (!isAdminUser(ctx.userId)) return adminRequired(); - const result = deletePackingTemplate(String(templateId)); + const result = this.packing.deletePackingTemplate(String(templateId)); if ('error' in result) return errorResult(result.error); return ok({ success: true, name: result.name }); } diff --git a/server/src/nest/packing/packing.service.ts b/server/src/nest/packing/packing.service.ts index 6fd1de935..7bb0934ff 100644 --- a/server/src/nest/packing/packing.service.ts +++ b/server/src/nest/packing/packing.service.ts @@ -588,6 +588,127 @@ export class PackingService { }); } + // ── Admin Template CRUD ──────────────────────────────────────────────────── + // Relocated byte-identically from services/adminService.ts with the 2026-08 + // admin fold. These back the admin-only /api/admin/packing-templates routes + // (AdminService delegates here) and the delete_packing_template MCP tool. + // They live in this service because it already owns all three template + // tables — saveAsTemplate above writes packing_templates, + // packing_template_categories and packing_template_items. Note the + // deliberate name split: listTemplates() above is the trip-member read; + // listPackingTemplates() below is the richer admin listing. + // Legacy quirks preserved on purpose: the `data.name?.trim()` truthiness + // guards (a blank name is a silent no-op, not a 400), the post-insert + // re-selects instead of RETURNING, `(max ?? -1) + 1` sort ordering, the + // exact error strings. The item routes originally ignored their :templateId + // path param entirely; since the 2026-08 quirk fix they scope through + // packing_template_categories like the sibling category routes do. + + /** An item looked up through its category, so :templateId actually scopes it. */ + private scopedTemplateItem(templateId: string, itemId: string) { + return this.db.get(` + SELECT ti.* FROM packing_template_items ti + JOIN packing_template_categories tc ON ti.category_id = tc.id + WHERE ti.id = ? AND tc.template_id = ? + `, itemId, templateId); + } + + listPackingTemplates() { + return this.db.all(` + SELECT pt.*, u.username as created_by_name, + (SELECT COUNT(*) FROM packing_template_items ti JOIN packing_template_categories tc ON ti.category_id = tc.id WHERE tc.template_id = pt.id) as item_count, + (SELECT COUNT(*) FROM packing_template_categories WHERE template_id = pt.id) as category_count + FROM packing_templates pt + JOIN users u ON pt.created_by = u.id + ORDER BY pt.created_at DESC + `); + } + + getPackingTemplate(id: string) { + const template = this.db.get('SELECT * FROM packing_templates WHERE id = ?', id); + if (!template) return { error: 'Template not found', status: 404 }; + const categories = this.db.all('SELECT * FROM packing_template_categories WHERE template_id = ? ORDER BY sort_order, id', id); + const items = this.db.all(` + SELECT ti.* FROM packing_template_items ti + JOIN packing_template_categories tc ON ti.category_id = tc.id + WHERE tc.template_id = ? ORDER BY ti.sort_order, ti.id + `, id); + return { template, categories, items }; + } + + createPackingTemplate(name: string, createdBy: number) { + if (!name?.trim()) return { error: 'Name is required', status: 400 }; + const result = this.db.run('INSERT INTO packing_templates (name, created_by) VALUES (?, ?)', name.trim(), createdBy); + const template = this.db.get('SELECT * FROM packing_templates WHERE id = ?', result.lastInsertRowid); + return { template }; + } + + updatePackingTemplate(id: string, data: { name?: string }) { + const template = this.db.get('SELECT * FROM packing_templates WHERE id = ?', id); + if (!template) return { error: 'Template not found', status: 404 }; + if (data.name?.trim()) this.db.run('UPDATE packing_templates SET name = ? WHERE id = ?', data.name.trim(), id); + return { template: this.db.get('SELECT * FROM packing_templates WHERE id = ?', id) }; + } + + deletePackingTemplate(id: string) { + const template = this.db.get<{ name?: string }>('SELECT * FROM packing_templates WHERE id = ?', id); + if (!template) return { error: 'Template not found', status: 404 }; + this.db.run('DELETE FROM packing_templates WHERE id = ?', id); + return { name: template.name }; + } + + // Template categories + + createTemplateCategory(templateId: string, name: string) { + if (!name?.trim()) return { error: 'Category name is required', status: 400 }; + const template = this.db.get('SELECT * FROM packing_templates WHERE id = ?', templateId); + if (!template) return { error: 'Template not found', status: 404 }; + const maxOrder = this.db.get<{ max: number | null }>('SELECT MAX(sort_order) as max FROM packing_template_categories WHERE template_id = ?', templateId)!; + const result = this.db.run('INSERT INTO packing_template_categories (template_id, name, sort_order) VALUES (?, ?, ?)', templateId, name.trim(), (maxOrder.max ?? -1) + 1); + return { category: this.db.get('SELECT * FROM packing_template_categories WHERE id = ?', result.lastInsertRowid) }; + } + + updateTemplateCategory(templateId: string, catId: string, data: { name?: string }) { + const cat = this.db.get('SELECT * FROM packing_template_categories WHERE id = ? AND template_id = ?', catId, templateId); + if (!cat) return { error: 'Category not found', status: 404 }; + if (data.name?.trim()) + this.db.run('UPDATE packing_template_categories SET name = ? WHERE id = ?', data.name.trim(), catId); + return { category: this.db.get('SELECT * FROM packing_template_categories WHERE id = ?', catId) }; + } + + deleteTemplateCategory(templateId: string, catId: string) { + const cat = this.db.get('SELECT * FROM packing_template_categories WHERE id = ? AND template_id = ?', catId, templateId); + if (!cat) return { error: 'Category not found', status: 404 }; + this.db.run('DELETE FROM packing_template_categories WHERE id = ?', catId); + return {}; + } + + // Template items + + createTemplateItem(templateId: string, catId: string, name: string) { + if (!name?.trim()) return { error: 'Item name is required', status: 400 }; + const cat = this.db.get('SELECT * FROM packing_template_categories WHERE id = ? AND template_id = ?', catId, templateId); + if (!cat) return { error: 'Category not found', status: 404 }; + const maxOrder = this.db.get<{ max: number | null }>('SELECT MAX(sort_order) as max FROM packing_template_items WHERE category_id = ?', catId)!; + const result = this.db.run('INSERT INTO packing_template_items (category_id, name, sort_order) VALUES (?, ?, ?)', catId, name.trim(), (maxOrder.max ?? -1) + 1); + return { item: this.db.get('SELECT * FROM packing_template_items WHERE id = ?', result.lastInsertRowid) }; + } + + updateTemplateItem(templateId: string, itemId: string, data: { name?: string }) { + const item = this.scopedTemplateItem(templateId, itemId); + if (!item) return { error: 'Item not found', status: 404 }; + if (data.name?.trim()) + this.db.run('UPDATE packing_template_items SET name = ? WHERE id = ?', data.name.trim(), itemId); + return { item: this.db.get('SELECT * FROM packing_template_items WHERE id = ?', itemId) }; + } + + deleteTemplateItem(templateId: string, itemId: string) { + const item = this.scopedTemplateItem(templateId, itemId); + if (!item) return { error: 'Item not found', status: 404 }; + this.db.run('DELETE FROM packing_template_items WHERE id = ?', itemId); + return {}; + } + /** Fire-and-forget tag notification, mirroring the legacy dynamic import. */ notifyTagged(tripId: string, actor: User, category: string, userIds: unknown): void { if (!Array.isArray(userIds) || userIds.length === 0) return; diff --git a/server/src/scheduler.ts b/server/src/scheduler.ts index 5165308e4..affdd225f 100644 --- a/server/src/scheduler.ts +++ b/server/src/scheduler.ts @@ -271,7 +271,7 @@ function startVersionCheck(): void { const tz = readEnv().app.tz || 'UTC'; versionCheckTask = cron.schedule('0 9 * * *', async () => { try { - const { checkAndNotifyVersion } = require('./services/adminService'); + const { checkAndNotifyVersion } = require('./nest/admin/admin.bridge'); await checkAndNotifyVersion(); } catch (err: unknown) { logError(`Version check: ${err instanceof Error ? err.message : err}`); diff --git a/server/src/services/adminService.ts b/server/src/services/adminService.ts deleted file mode 100644 index fb15ae119..000000000 --- a/server/src/services/adminService.ts +++ /dev/null @@ -1,968 +0,0 @@ -import { ADDON_IDS } from '../addons'; -import { readEnv } from '../app-config'; -import { updateJwtSecret } from '../config'; -import { db } from '../db/database'; -// Import from sessionManager directly, NOT the ../mcp barrel: the barrel pulls -// the whole tools fan-out (and via the domain bridges, the Nest services) into -// every consumer of this module — a services→mcp→nest module cycle. -import { revokeUserSessions, revokeUserSessionsForClient } from '../mcp/sessionManager'; -import { emitUserDeleted } from '../plugin-user-lifecycle'; -import { User, Addon } from '../types'; -import { maybe_encrypt_api_key, decrypt_api_key } from './apiKeyCrypto'; -import { resolveAuthToggles } from '../nest/auth/auth.bridge'; -import { avatarUrl } from './avatarUrl'; -import { prepareLlmAddonConfigForWrite, maskLlmAddonConfig } from './llmConfig'; -import { getPhotoProviderConfig } from './memories/helpersService'; -import { send as sendNotification } from '../nest/notifications/notifications.bridge'; -import { validatePassword } from './passwordPolicy'; -import { getAllPermissions, savePermissions as savePerms, PERMISSION_ACTIONS } from '../nest/permissions/permissions.bridge'; -import { deleteUserCompletely } from './userCleanupService'; - -import bcrypt from 'bcryptjs'; -import crypto from 'crypto'; -import fs from 'fs'; -import path from 'path'; - -// ── Helpers ──────────────────────────────────────────────────────────────── - -// bcrypt cost factor for user passwords — kept in sync with authService. -const BCRYPT_COST = 12; - -function utcSuffix(ts: string | null | undefined): string | null { - if (!ts) return null; - return ts.endsWith('Z') ? ts : ts.replace(' ', 'T') + 'Z'; -} - -export function compareVersions(a: string, b: string): number { - const parse = (v: string) => { - const [base, pre] = v.split('-pre.'); - const parts = base.split('.').map(Number); - const n = pre !== undefined ? parseInt(pre, 10) : null; - const preN = n !== null && Number.isFinite(n) ? n : null; - return { parts, preN }; - }; - const pa = parse(a), - pb = parse(b); - for (let i = 0; i < Math.max(pa.parts.length, pb.parts.length); i++) { - const na = pa.parts[i] || 0, - nb = pb.parts[i] || 0; - if (na > nb) return 1; - if (na < nb) return -1; - } - // Equal base: stable > prerelease; higher preN wins among prereleases - if (pa.preN === null && pb.preN !== null) return 1; - if (pa.preN !== null && pb.preN === null) return -1; - if (pa.preN !== null && pb.preN !== null) { - if (pa.preN > pb.preN) return 1; - if (pa.preN < pb.preN) return -1; - } - return 0; -} - -export const isDocker = (() => { - try { - return ( - fs.existsSync('/.dockerenv') || - (fs.existsSync('/proc/1/cgroup') && fs.readFileSync('/proc/1/cgroup', 'utf8').includes('docker')) - ); - } catch { - return false; - } -})(); - -// ── User CRUD ────────────────────────────────────────────────────────────── - -export function listUsers() { - // Guests (#1362) are accountless trip participants, not real users — keep them out - // of admin user management entirely. - const users = db - .prepare( - 'SELECT id, username, email, role, avatar, created_at, updated_at, last_login FROM users WHERE COALESCE(is_guest, 0) = 0 ORDER BY created_at DESC', - ) - .all() as (Pick & { - avatar?: string | null; - })[]; - let onlineUserIds = new Set(); - try { - const { getOnlineUserIds } = require('../websocket'); - onlineUserIds = getOnlineUserIds(); - } catch { - /* */ - } - return users.map((u) => ({ - ...u, - avatar_url: avatarUrl(u), - created_at: utcSuffix(u.created_at), - updated_at: utcSuffix(u.updated_at as string), - last_login: utcSuffix(u.last_login), - online: onlineUserIds.has(u.id), - })); -} - -export function createUser(data: { username: string; email: string; password: string; role?: string }) { - const username = data.username?.trim(); - const email = data.email?.trim(); - const password = data.password?.trim(); - - if (!username || !email || !password) { - return { error: 'Username, email and password are required', status: 400 }; - } - - const pwCheck = validatePassword(password); - if (!pwCheck.ok) return { error: pwCheck.reason, status: 400 }; - - if (data.role && !['user', 'admin'].includes(data.role)) { - return { error: 'Invalid role', status: 400 }; - } - - // Guests (#1362) live in a reserved synthetic namespace; never let one block a real account. - const existingUsername = db - .prepare('SELECT id FROM users WHERE username = ? AND COALESCE(is_guest, 0) = 0') - .get(username); - if (existingUsername) return { error: 'Username already taken', status: 409 }; - - const existingEmail = db.prepare('SELECT id FROM users WHERE email = ? AND COALESCE(is_guest, 0) = 0').get(email); - if (existingEmail) return { error: 'Email already taken', status: 409 }; - - const passwordHash = bcrypt.hashSync(password, BCRYPT_COST); - - const result = db - .prepare('INSERT INTO users (username, email, password_hash, role) VALUES (?, ?, ?, ?)') - .run(username, email, passwordHash, data.role || 'user'); - - const user = db - .prepare('SELECT id, username, email, role, created_at, updated_at FROM users WHERE id = ?') - .get(result.lastInsertRowid); - - return { - user, - insertedId: Number(result.lastInsertRowid), - auditDetails: { username, email, role: data.role || 'user' }, - }; -} - -export function updateUser(id: string, data: { username?: string; email?: string; role?: string; password?: string }) { - const username = typeof data.username === 'string' ? data.username.trim() : data.username; - const email = typeof data.email === 'string' ? data.email.trim() : data.email; - const { role, password } = data; - const user = db.prepare('SELECT * FROM users WHERE id = ?').get(id) as User | undefined; - - if (!user) return { error: 'User not found', status: 404 }; - - if (role && !['user', 'admin'].includes(role)) { - return { error: 'Invalid role', status: 400 }; - } - - if (username && username !== user.username) { - const conflict = db - .prepare('SELECT id FROM users WHERE username = ? AND id != ? AND COALESCE(is_guest, 0) = 0') - .get(username, id); - if (conflict) return { error: 'Username already taken', status: 409 }; - } - if (email && email !== user.email) { - const conflict = db - .prepare('SELECT id FROM users WHERE email = ? AND id != ? AND COALESCE(is_guest, 0) = 0') - .get(email, id); - if (conflict) return { error: 'Email already taken', status: 409 }; - } - - if (password) { - const pwCheck = validatePassword(password); - if (!pwCheck.ok) return { error: pwCheck.reason, status: 400 }; - } - const passwordHash = password ? bcrypt.hashSync(password, BCRYPT_COST) : null; - - // Don't let the admin UI demote the last remaining admin — that would leave the - // instance with no one able to manage it (and on OIDC-only setups, no recovery). #1274 - if (role && role !== 'admin') { - const current = db.prepare('SELECT role FROM users WHERE id = ?').get(id) as { role?: string } | undefined; - if (current?.role === 'admin') { - const adminCount = ( - db.prepare("SELECT COUNT(*) as count FROM users WHERE role = 'admin'").get() as { count: number } - ).count; - if (adminCount <= 1) return { error: 'Cannot remove the last admin', status: 400 }; - } - } - - db.prepare( - ` - UPDATE users SET - username = COALESCE(?, username), - email = COALESCE(?, email), - role = COALESCE(?, role), - password_hash = COALESCE(?, password_hash), - updated_at = CURRENT_TIMESTAMP - WHERE id = ? - `, - ).run(username || null, email || null, role || null, passwordHash, id); - - const updated = db - .prepare('SELECT id, username, email, role, created_at, updated_at FROM users WHERE id = ?') - .get(id); - - const changed: string[] = []; - if (username) changed.push('username'); - if (email) changed.push('email'); - if (role) changed.push('role'); - if (password) changed.push('password'); - - return { - user: updated, - previousEmail: user.email, - changed, - }; -} - -export function deleteUser(id: string, currentUserId: number) { - if (parseInt(id) === currentUserId) { - return { error: 'Cannot delete own account', status: 400 }; - } - - const userToDel = db.prepare('SELECT id, email FROM users WHERE id = ?').get(id) as - | { id: number; email: string } - | undefined; - if (!userToDel) return { error: 'User not found', status: 404 }; - - deleteUserCompletely(userToDel.id); - emitUserDeleted(userToDel.id); // let plugins erase their own per-user data - return { email: userToDel.email }; -} - -// ── Stats ────────────────────────────────────────────────────────────────── - -export function getStats() { - const totalUsers = ( - db.prepare('SELECT COUNT(*) as count FROM users WHERE COALESCE(is_guest, 0) = 0').get() as { count: number } - ).count; - const totalTrips = (db.prepare('SELECT COUNT(*) as count FROM trips').get() as { count: number }).count; - const totalPlaces = (db.prepare('SELECT COUNT(*) as count FROM places').get() as { count: number }).count; - const totalFiles = (db.prepare('SELECT COUNT(*) as count FROM trip_files').get() as { count: number }).count; - return { totalUsers, totalTrips, totalPlaces, totalFiles }; -} - -// ── Permissions ──────────────────────────────────────────────────────────── - -export function getPermissions() { - const current = getAllPermissions(); - const actions = PERMISSION_ACTIONS.map((a) => ({ - key: a.key, - level: current[a.key], - defaultLevel: a.defaultLevel, - allowedLevels: a.allowedLevels, - })); - return { permissions: actions }; -} - -export function savePermissions(permissions: Record) { - const { skipped } = savePerms(permissions); - return { permissions: getAllPermissions(), skipped }; -} - -// ── Audit Log ────────────────────────────────────────────────────────────── - -export function getAuditLog(query: { limit?: string; offset?: string }) { - const limitRaw = parseInt(String(query.limit || '100'), 10); - const offsetRaw = parseInt(String(query.offset || '0'), 10); - const limit = Math.min(Math.max(Number.isFinite(limitRaw) ? limitRaw : 100, 1), 500); - const offset = Math.max(Number.isFinite(offsetRaw) ? offsetRaw : 0, 0); - - type Row = { - id: number; - created_at: string; - user_id: number | null; - username: string | null; - user_email: string | null; - action: string; - resource: string | null; - details: string | null; - ip: string | null; - }; - - const rows = db - .prepare( - ` - SELECT a.id, a.created_at, a.user_id, u.username, u.email as user_email, a.action, a.resource, a.details, a.ip - FROM audit_log a - LEFT JOIN users u ON u.id = a.user_id - ORDER BY a.id DESC - LIMIT ? OFFSET ? - `, - ) - .all(limit, offset) as Row[]; - - const total = (db.prepare('SELECT COUNT(*) as c FROM audit_log').get() as { c: number }).c; - - const entries = rows.map((r) => { - let details: Record | null = null; - if (r.details) { - try { - details = JSON.parse(r.details) as Record; - } catch { - details = { _parse_error: true }; - } - } - const created_at = - r.created_at && !r.created_at.endsWith('Z') ? r.created_at.replace(' ', 'T') + 'Z' : r.created_at; - return { ...r, created_at, details }; - }); - - return { entries, total, limit, offset }; -} - -// ── OIDC Settings ────────────────────────────────────────────────────────── - -export function getOidcSettings() { - const get = (key: string) => - (db.prepare('SELECT value FROM app_settings WHERE key = ?').get(key) as { value: string } | undefined)?.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'), - }; -} - -export function 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 === '') && !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) => - db.prepare('INSERT OR REPLACE INTO app_settings (key, value) VALUES (?, ?)').run(key, val || ''); - 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 ────────────────────────────────────────────────────────── - -export function saveDemoBaseline(): { error?: string; status?: number; message?: string } { - if (!readEnv().demo.enabled) { - return { error: 'Not found', status: 404 }; - } - try { - const { saveBaseline } = require('../demo/demo-reset'); - saveBaseline(); - return { message: 'Demo baseline saved. Hourly resets will restore to this state.' }; - } catch (err: unknown) { - console.error(err); - return { error: 'Failed to save baseline', status: 500 }; - } -} - -// ── GitHub Integration ───────────────────────────────────────────────────── - -export async function getGithubReleases(perPage: string = '10', page: string = '1') { - try { - const resp = await fetch(`https://api.github.com/repos/liketrek/TREK/releases?per_page=${perPage}&page=${page}`, { - headers: { Accept: 'application/vnd.github.v3+json', 'User-Agent': 'TREK-Server' }, - }); - if (!resp.ok) return []; - const data = await resp.json(); - return Array.isArray(data) ? data : []; - } catch { - return []; - } -} - -interface VersionInfo { - current: string; - latest: string; - update_available: boolean; - release_url?: string; - is_docker: boolean; - is_prerelease: boolean; -} - -const VERSION_CACHE_TTL = 5 * 60 * 1000; // 5 minutes -let _versionCache: { data: VersionInfo; expiresAt: number } | null = null; - -/** Test-only: clear the in-memory version cache. */ -export function __clearVersionCacheForTests(): void { - _versionCache = null; -} - -export async function checkVersion(): Promise { - if (_versionCache && Date.now() < _versionCache.expiresAt) { - return _versionCache.data; - } - - const currentVersion: string = readEnv().app.appVersion || require('../../package.json').version; - const isPrerelease = currentVersion.includes('-pre.'); - const fallback: VersionInfo = { - current: currentVersion, - latest: currentVersion, - update_available: false, - is_docker: isDocker, - is_prerelease: isPrerelease, - }; - let result: VersionInfo; - try { - if (isPrerelease) { - // Fetch release list and find the newest prerelease - const resp = await fetch('https://api.github.com/repos/liketrek/TREK/releases?per_page=100', { - headers: { Accept: 'application/vnd.github.v3+json', 'User-Agent': 'TREK-Server' }, - }); - if (!resp.ok) { - return fallback; - } - const data = (await resp.json()) as Array<{ tag_name?: string; html_url?: string; prerelease?: boolean }>; - const prereleases = Array.isArray(data) ? data.filter((r) => r.prerelease) : []; - if (!prereleases.length) { - return fallback; - } - // Pre-compute stripped versions, then sort descending - const tagged = prereleases.map((r) => ({ r, v: (r.tag_name || '').replace(/^v/, '') })); - tagged.sort((a, b) => compareVersions(b.v, a.v)); - const latest = tagged[0].v; - const update_available = !!latest && latest !== currentVersion && compareVersions(latest, currentVersion) > 0; - result = { - current: currentVersion, - latest, - update_available, - release_url: tagged[0].r.html_url || '', - is_docker: isDocker, - is_prerelease: true, - }; - } else { - const resp = await fetch('https://api.github.com/repos/liketrek/TREK/releases/latest', { - headers: { Accept: 'application/vnd.github.v3+json', 'User-Agent': 'TREK-Server' }, - }); - if (!resp.ok) { - return fallback; - } - const data = (await resp.json()) as { tag_name?: string; html_url?: string }; - const latest = (data.tag_name || '').replace(/^v/, ''); - const update_available = !!latest && latest !== currentVersion && compareVersions(latest, currentVersion) > 0; - result = { - current: currentVersion, - latest, - update_available, - release_url: data.html_url || '', - is_docker: isDocker, - is_prerelease: false, - }; - } - } catch { - return fallback; - } - - _versionCache = { data: result, expiresAt: Date.now() + VERSION_CACHE_TTL }; - return result; -} - -export async function checkAndNotifyVersion(): Promise { - try { - const result = await checkVersion(); - if (!result.update_available) return; - - const lastNotified = ( - db.prepare('SELECT value FROM app_settings WHERE key = ?').get('last_notified_version') as - | { value: string } - | undefined - )?.value; - if (lastNotified === result.latest) return; - - db.prepare('INSERT OR REPLACE INTO app_settings (key, value) VALUES (?, ?)').run( - 'last_notified_version', - result.latest, - ); - - await sendNotification({ - event: 'version_available', - actorId: null, - scope: 'admin', - targetId: 0, - params: { version: result.latest }, - }); - } catch { - // Silently ignore — version check is non-critical - } -} - -// ── Invite Tokens ────────────────────────────────────────────────────────── - -export function listInvites() { - return db - .prepare( - ` - SELECT i.*, u.username as created_by_name, t.title as trip_title - FROM invite_tokens i - JOIN users u ON i.created_by = u.id - LEFT JOIN trips t ON i.trip_id = t.id - ORDER BY i.created_at DESC - `, - ) - .all(); -} - -/** Trips an admin can bind an invite to — id + title only, for the picker (#1402). */ -export function listTripsForInvite() { - return db.prepare('SELECT id, title FROM trips ORDER BY title COLLATE NOCASE ASC').all(); -} - -export function createInvite( - createdBy: number, - data: { max_uses?: string | number; expires_in_days?: string | number; trip_id?: string | number | null }, -) { - const rawUses = parseInt(String(data.max_uses)); - const uses = rawUses === 0 ? 0 : Math.min(Math.max(rawUses || 1, 1), 5); - const token = crypto.randomBytes(16).toString('hex'); - const expiresAt = data.expires_in_days - ? new Date(Date.now() + parseInt(String(data.expires_in_days)) * 86400000).toISOString() - : null; - - // Optional trip binding: only persist a trip that actually exists, so a stale - // or forged id can never bind (and never auto-adds anyone on registration). - let tripId: number | null = null; - if (data.trip_id != null && String(data.trip_id).trim() !== '') { - const parsed = parseInt(String(data.trip_id)); - if (Number.isInteger(parsed) && db.prepare('SELECT id FROM trips WHERE id = ?').get(parsed)) { - tripId = parsed; - } - } - - const ins = db - .prepare('INSERT INTO invite_tokens (token, max_uses, expires_at, created_by, trip_id) VALUES (?, ?, ?, ?, ?)') - .run(token, uses, expiresAt, createdBy, tripId); - - const inviteId = Number(ins.lastInsertRowid); - const invite = db - .prepare( - ` - SELECT i.*, u.username as created_by_name, t.title as trip_title - FROM invite_tokens i - JOIN users u ON i.created_by = u.id - LEFT JOIN trips t ON i.trip_id = t.id - WHERE i.id = ? - `, - ) - .get(inviteId); - - return { invite, inviteId, uses, expiresInDays: data.expires_in_days ?? null, tripId }; -} - -export function deleteInvite(id: string) { - const invite = db.prepare('SELECT id FROM invite_tokens WHERE id = ?').get(id); - if (!invite) return { error: 'Invite not found', status: 404 }; - db.prepare('DELETE FROM invite_tokens WHERE id = ?').run(id); - return {}; -} - -// ── Places Photos ───────────────────────────────────────────────────────── - -export function getPlacesPhotos() { - const row = db.prepare("SELECT value FROM app_settings WHERE key = 'places_photos_enabled'").get() as - | { value: string } - | undefined; - return { enabled: row?.value !== 'false' }; -} - -export function updatePlacesPhotos(enabled: boolean) { - db.prepare("INSERT OR REPLACE INTO app_settings (key, value) VALUES ('places_photos_enabled', ?)").run( - enabled ? 'true' : 'false', - ); - return { enabled: !!enabled }; -} - -// ── Places Autocomplete ──────────────────────────────────────────────────── - -export function getPlacesAutocomplete() { - const row = db.prepare("SELECT value FROM app_settings WHERE key = 'places_autocomplete_enabled'").get() as - | { value: string } - | undefined; - return { enabled: row?.value !== 'false' }; -} - -export function updatePlacesAutocomplete(enabled: boolean) { - db.prepare("INSERT OR REPLACE INTO app_settings (key, value) VALUES ('places_autocomplete_enabled', ?)").run( - enabled ? 'true' : 'false', - ); - return { enabled: !!enabled }; -} - -// ── Places Details ───────────────────────────────────────────────────────── - -export function getPlacesDetails() { - const row = db.prepare("SELECT value FROM app_settings WHERE key = 'places_details_enabled'").get() as - | { value: string } - | undefined; - return { enabled: row?.value !== 'false' }; -} - -export function updatePlacesDetails(enabled: boolean) { - db.prepare("INSERT OR REPLACE INTO app_settings (key, value) VALUES ('places_details_enabled', ?)").run( - enabled ? 'true' : 'false', - ); - return { enabled: !!enabled }; -} - -// ── Packing Templates ────────────────────────────────────────────────────── - -export function listPackingTemplates() { - return db - .prepare( - ` - SELECT pt.*, u.username as created_by_name, - (SELECT COUNT(*) FROM packing_template_items ti JOIN packing_template_categories tc ON ti.category_id = tc.id WHERE tc.template_id = pt.id) as item_count, - (SELECT COUNT(*) FROM packing_template_categories WHERE template_id = pt.id) as category_count - FROM packing_templates pt - JOIN users u ON pt.created_by = u.id - ORDER BY pt.created_at DESC - `, - ) - .all(); -} - -export function getPackingTemplate(id: string) { - const template = db.prepare('SELECT * FROM packing_templates WHERE id = ?').get(id); - if (!template) return { error: 'Template not found', status: 404 }; - const categories = db - .prepare('SELECT * FROM packing_template_categories WHERE template_id = ? ORDER BY sort_order, id') - .all(id) as any[]; - const items = db - .prepare( - ` - SELECT ti.* FROM packing_template_items ti - JOIN packing_template_categories tc ON ti.category_id = tc.id - WHERE tc.template_id = ? ORDER BY ti.sort_order, ti.id - `, - ) - .all(id); - return { template, categories, items }; -} - -export function createPackingTemplate(name: string, createdBy: number) { - if (!name?.trim()) return { error: 'Name is required', status: 400 }; - const result = db - .prepare('INSERT INTO packing_templates (name, created_by) VALUES (?, ?)') - .run(name.trim(), createdBy); - const template = db.prepare('SELECT * FROM packing_templates WHERE id = ?').get(result.lastInsertRowid); - return { template }; -} - -export function updatePackingTemplate(id: string, data: { name?: string }) { - const template = db.prepare('SELECT * FROM packing_templates WHERE id = ?').get(id); - if (!template) return { error: 'Template not found', status: 404 }; - if (data.name?.trim()) db.prepare('UPDATE packing_templates SET name = ? WHERE id = ?').run(data.name.trim(), id); - return { template: db.prepare('SELECT * FROM packing_templates WHERE id = ?').get(id) }; -} - -export function deletePackingTemplate(id: string) { - const template = db.prepare('SELECT * FROM packing_templates WHERE id = ?').get(id) as { name?: string } | undefined; - if (!template) return { error: 'Template not found', status: 404 }; - db.prepare('DELETE FROM packing_templates WHERE id = ?').run(id); - return { name: template.name }; -} - -// Template categories - -export function createTemplateCategory(templateId: string, name: string) { - if (!name?.trim()) return { error: 'Category name is required', status: 400 }; - const template = db.prepare('SELECT * FROM packing_templates WHERE id = ?').get(templateId); - if (!template) return { error: 'Template not found', status: 404 }; - const maxOrder = db - .prepare('SELECT MAX(sort_order) as max FROM packing_template_categories WHERE template_id = ?') - .get(templateId) as { max: number | null }; - const result = db - .prepare('INSERT INTO packing_template_categories (template_id, name, sort_order) VALUES (?, ?, ?)') - .run(templateId, name.trim(), (maxOrder.max ?? -1) + 1); - return { category: db.prepare('SELECT * FROM packing_template_categories WHERE id = ?').get(result.lastInsertRowid) }; -} - -export function updateTemplateCategory(templateId: string, catId: string, data: { name?: string }) { - const cat = db - .prepare('SELECT * FROM packing_template_categories WHERE id = ? AND template_id = ?') - .get(catId, templateId); - if (!cat) return { error: 'Category not found', status: 404 }; - if (data.name?.trim()) - db.prepare('UPDATE packing_template_categories SET name = ? WHERE id = ?').run(data.name.trim(), catId); - return { category: db.prepare('SELECT * FROM packing_template_categories WHERE id = ?').get(catId) }; -} - -export function deleteTemplateCategory(templateId: string, catId: string) { - const cat = db - .prepare('SELECT * FROM packing_template_categories WHERE id = ? AND template_id = ?') - .get(catId, templateId); - if (!cat) return { error: 'Category not found', status: 404 }; - db.prepare('DELETE FROM packing_template_categories WHERE id = ?').run(catId); - return {}; -} - -// Template items - -export function createTemplateItem(templateId: string, catId: string, name: string) { - if (!name?.trim()) return { error: 'Item name is required', status: 400 }; - const cat = db - .prepare('SELECT * FROM packing_template_categories WHERE id = ? AND template_id = ?') - .get(catId, templateId); - if (!cat) return { error: 'Category not found', status: 404 }; - const maxOrder = db - .prepare('SELECT MAX(sort_order) as max FROM packing_template_items WHERE category_id = ?') - .get(catId) as { max: number | null }; - const result = db - .prepare('INSERT INTO packing_template_items (category_id, name, sort_order) VALUES (?, ?, ?)') - .run(catId, name.trim(), (maxOrder.max ?? -1) + 1); - return { item: db.prepare('SELECT * FROM packing_template_items WHERE id = ?').get(result.lastInsertRowid) }; -} - -export function updateTemplateItem(itemId: string, data: { name?: string }) { - const item = db.prepare('SELECT * FROM packing_template_items WHERE id = ?').get(itemId); - if (!item) return { error: 'Item not found', status: 404 }; - if (data.name?.trim()) - db.prepare('UPDATE packing_template_items SET name = ? WHERE id = ?').run(data.name.trim(), itemId); - return { item: db.prepare('SELECT * FROM packing_template_items WHERE id = ?').get(itemId) }; -} - -export function deleteTemplateItem(itemId: string) { - const item = db.prepare('SELECT * FROM packing_template_items WHERE id = ?').get(itemId); - if (!item) return { error: 'Item not found', status: 404 }; - db.prepare('DELETE FROM packing_template_items WHERE id = ?').run(itemId); - return {}; -} - -// ── Addons ───────────────────────────────────────────────────────────────── -// isAddonEnabled and the bag-tracking/collab-features flags moved to -// nest/addons/addons.service.ts (bridge: nest/addons/addons.bridge.ts) — -// finding `admin-1`. listAddons/updateAddon + photo-provider CRUD stay here -// until the Wave-5 admin migration. - -export function listAddons() { - const addons = db.prepare('SELECT * FROM addons ORDER BY sort_order, id').all() as Addon[]; - const providers = db - .prepare( - ` - SELECT id, name, description, icon, enabled, sort_order - FROM photo_providers - ORDER BY sort_order, id - `, - ) - .all() as Array<{ - id: string; - name: string; - description?: string | null; - icon: string; - enabled: number; - sort_order: number; - }>; - const fields = db - .prepare( - ` - SELECT provider_id, field_key, label, input_type, placeholder, required, secret, settings_key, payload_key, sort_order - FROM photo_provider_fields - ORDER BY sort_order, id - `, - ) - .all() as Array<{ - provider_id: string; - field_key: string; - label: string; - input_type: string; - placeholder?: string | null; - required: number; - secret: number; - settings_key?: string | null; - payload_key?: string | null; - sort_order: number; - }>; - const fieldsByProvider = new Map(); - for (const field of fields) { - const arr = fieldsByProvider.get(field.provider_id) || []; - arr.push(field); - fieldsByProvider.set(field.provider_id, arr); - } - - return [ - ...addons.map((a) => ({ - ...a, - enabled: !!a.enabled, - config: - a.id === ADDON_IDS.LLM_PARSING - ? maskLlmAddonConfig(JSON.parse(a.config || '{}')) - : JSON.parse(a.config || '{}'), - })), - ...providers.map((p) => ({ - id: p.id, - name: p.name, - description: p.description, - type: 'photo_provider', - icon: p.icon, - enabled: !!p.enabled, - config: getPhotoProviderConfig(p.id), - fields: (fieldsByProvider.get(p.id) || []).map((f) => ({ - key: f.field_key, - label: f.label, - input_type: f.input_type, - placeholder: f.placeholder || '', - required: !!f.required, - secret: !!f.secret, - settings_key: f.settings_key || null, - payload_key: f.payload_key || null, - sort_order: f.sort_order, - })), - sort_order: p.sort_order, - })), - ]; -} - -export function updateAddon(id: string, data: { enabled?: boolean; config?: Record }) { - const addon = db.prepare('SELECT * FROM addons WHERE id = ?').get(id) as Addon | undefined; - const provider = db.prepare('SELECT * FROM photo_providers WHERE id = ?').get(id) as - | { id: string; name: string; description?: string | null; icon: string; enabled: number; sort_order: number } - | undefined; - if (!addon && !provider) return { error: 'Addon not found', status: 404 }; - - if (addon) { - if (data.enabled !== undefined) - db.prepare('UPDATE addons SET enabled = ? WHERE id = ?').run(data.enabled ? 1 : 0, id); - if (data.config !== undefined) { - // The AI-parsing addon holds an API key — encrypt it at rest and preserve - // the stored key when the client echoes the mask sentinel (see llmConfig.ts). - const configToStore = - id === ADDON_IDS.LLM_PARSING - ? prepareLlmAddonConfigForWrite(data.config, JSON.parse(addon.config || '{}')) - : data.config; - db.prepare('UPDATE addons SET config = ? WHERE id = ?').run(JSON.stringify(configToStore), id); - } - } else { - if (data.enabled !== undefined) - db.prepare('UPDATE photo_providers SET enabled = ? WHERE id = ?').run(data.enabled ? 1 : 0, id); - } - - const updatedAddon = db.prepare('SELECT * FROM addons WHERE id = ?').get(id) as Addon | undefined; - const updatedProvider = db.prepare('SELECT * FROM photo_providers WHERE id = ?').get(id) as - | { id: string; name: string; description?: string | null; icon: string; enabled: number; sort_order: number } - | undefined; - const updated = updatedAddon - ? { - ...updatedAddon, - enabled: !!updatedAddon.enabled, - config: - updatedAddon.id === ADDON_IDS.LLM_PARSING - ? maskLlmAddonConfig(JSON.parse(updatedAddon.config || '{}')) - : JSON.parse(updatedAddon.config || '{}'), - } - : updatedProvider - ? { - id: updatedProvider.id, - name: updatedProvider.name, - description: updatedProvider.description, - type: 'photo_provider', - icon: updatedProvider.icon, - enabled: !!updatedProvider.enabled, - config: getPhotoProviderConfig(updatedProvider.id), - sort_order: updatedProvider.sort_order, - } - : null; - - // Only these addons gate MCP tool/resource/prompt registration (see - // registerTools/registerResources) — and only a real enabled-flip changes - // what a session would register. Config-only saves, photo providers and - // MCP-irrelevant addons must not tear down every live session (#1414). - const MCP_RELEVANT_ADDONS = new Set([ - ADDON_IDS.MCP, - ADDON_IDS.PACKING, - ADDON_IDS.BUDGET, - ADDON_IDS.COLLAB, - ADDON_IDS.ATLAS, - ADDON_IDS.VACAY, - ADDON_IDS.JOURNEY, - ]); - const enabledChanged = !!addon && data.enabled !== undefined && (data.enabled ? 1 : 0) !== addon.enabled; - - return { - addon: updated, - mcpAffected: enabledChanged && MCP_RELEVANT_ADDONS.has(id), - auditDetails: { - enabled: data.enabled !== undefined ? !!data.enabled : undefined, - config_changed: data.config !== undefined, - }, - }; -} - -// ── MCP Tokens ───────────────────────────────────────────────────────────── - -export function listMcpTokens() { - return db - .prepare( - ` - SELECT t.id, t.name, t.token_prefix, t.created_at, t.last_used_at, t.user_id, u.username - FROM mcp_tokens t - JOIN users u ON u.id = t.user_id - ORDER BY t.created_at DESC - `, - ) - .all(); -} - -export function deleteMcpToken(id: string) { - const token = db.prepare('SELECT id, user_id FROM mcp_tokens WHERE id = ?').get(id) as - | { id: number; user_id: number } - | undefined; - if (!token) return { error: 'Token not found', status: 404 }; - db.prepare('DELETE FROM mcp_tokens WHERE id = ?').run(id); - revokeUserSessions(token.user_id); - return {}; -} - -// ── OAuth Sessions ───────────────────────────────────────────────────────── - -export function listOAuthSessions() { - const rows = db - .prepare( - ` - SELECT ot.id, ot.client_id, oc.name AS client_name, ot.user_id, u.username, - ot.scopes, ot.access_token_expires_at, ot.refresh_token_expires_at, ot.created_at - FROM oauth_tokens ot - JOIN oauth_clients oc ON ot.client_id = oc.client_id - JOIN users u ON u.id = ot.user_id - WHERE ot.revoked_at IS NULL - AND ot.refresh_token_expires_at > CURRENT_TIMESTAMP - ORDER BY ot.created_at DESC - `, - ) - .all() as (Record & { scopes: string })[]; - return rows.map((r) => ({ ...r, scopes: JSON.parse(r.scopes) })); -} - -export function revokeOAuthSession(id: string) { - const row = db.prepare('SELECT id, user_id, client_id FROM oauth_tokens WHERE id = ?').get(id) as - | { id: number; user_id: number; client_id: string } - | undefined; - if (!row) return { error: 'Session not found', status: 404 }; - db.prepare('UPDATE oauth_tokens SET revoked_at = CURRENT_TIMESTAMP WHERE id = ?').run(id); - revokeUserSessionsForClient(row.user_id, row.client_id); - return {}; -} - -// ── JWT Rotation ─────────────────────────────────────────────────────────── - -export function rotateJwtSecret(): { error?: string; status?: number } { - const newSecret = crypto.randomBytes(32).toString('hex'); - const dataDir = path.resolve(__dirname, '../../data'); - const secretFile = path.join(dataDir, '.jwt_secret'); - try { - if (!fs.existsSync(dataDir)) fs.mkdirSync(dataDir, { recursive: true }); - fs.writeFileSync(secretFile, newSecret, { mode: 0o600 }); - } catch (err: unknown) { - return { error: 'Failed to persist new JWT secret to disk', status: 500 }; - } - updateJwtSecret(newSecret); - return {}; -} diff --git a/server/tests/e2e/admin.e2e.test.ts b/server/tests/e2e/admin.e2e.test.ts index e0104cb6a..10e8246dd 100644 --- a/server/tests/e2e/admin.e2e.test.ts +++ b/server/tests/e2e/admin.e2e.test.ts @@ -1,9 +1,11 @@ /** * Admin e2e — exercises the migrated /api/admin endpoints through the real - * JwtAuthGuard + AdminGuard against a temp SQLite db. The admin service + - * helpers are mocked (SettingsService is DI-native and runs real SQL); this - * focuses on auth (401), the admin gate (403 for a non-admin), create-201, - * validation 400 and the dev-only 404. + * JwtAuthGuard + AdminGuard against a temp SQLite db, DI-native: no + * services/adminService path mock, so every route below runs its real SQL + * (trips.e2e.test.ts pattern). Only the shared db module is mocked — the auth + * guard reads users through the singleton and DatabaseModule's factory picks up + * the same mocked db. Covers auth (401), the admin gate (403), create-201, + * validation 400, the dev-only 404, and real read/write round trips. */ import { describe, it, expect, beforeAll, afterAll, beforeEach, vi } from 'vitest'; import request from 'supertest'; @@ -19,35 +21,64 @@ const { db } = vi.hoisted(() => { const Database = require('better-sqlite3'); const tmp = new Database(':memory:'); tmp.exec('PRAGMA journal_mode = WAL'); + // `users` carries the columns listUsers/createUser/updateUser select, plus the + // is_guest flag the #1362 COALESCE guards read. tmp.exec(`CREATE TABLE users (id INTEGER PRIMARY KEY AUTOINCREMENT, username TEXT NOT NULL, - email TEXT NOT NULL UNIQUE, role TEXT NOT NULL DEFAULT 'user', password_version INTEGER NOT NULL DEFAULT 0);`); - // The real SettingsService (DI-injected into AdminService, no mock) reads these. + email TEXT NOT NULL UNIQUE, role TEXT NOT NULL DEFAULT 'user', password_version INTEGER NOT NULL DEFAULT 0, + password_hash TEXT, avatar TEXT, is_guest INTEGER DEFAULT 0, + created_at DATETIME DEFAULT CURRENT_TIMESTAMP, updated_at DATETIME DEFAULT CURRENT_TIMESTAMP, + last_login DATETIME);`); tmp.exec(`CREATE TABLE settings (id INTEGER PRIMARY KEY AUTOINCREMENT, user_id INTEGER NOT NULL, key TEXT NOT NULL, value TEXT, UNIQUE(user_id, key));`); tmp.exec('CREATE TABLE app_settings (key TEXT PRIMARY KEY, value TEXT);'); - // AuditService now runs its real INSERT (DI-injected, no mock) — slim - // audit_log mirror (no FKs), same shape as plugin-runtime.test.ts. + // Slim audit_log mirror (no FKs), same shape as plugin-runtime.test.ts. tmp.exec(`CREATE TABLE audit_log ( id INTEGER PRIMARY KEY AUTOINCREMENT, created_at DATETIME DEFAULT CURRENT_TIMESTAMP, user_id INTEGER, action TEXT NOT NULL, resource TEXT, details TEXT, ip TEXT);`); + // getStats counts these three alongside users. + tmp.exec('CREATE TABLE trips (id INTEGER PRIMARY KEY AUTOINCREMENT, title TEXT, user_id INTEGER);'); + tmp.exec('CREATE TABLE places (id INTEGER PRIMARY KEY AUTOINCREMENT, trip_id INTEGER);'); + tmp.exec('CREATE TABLE trip_files (id INTEGER PRIMARY KEY AUTOINCREMENT, trip_id INTEGER);'); + tmp.exec(`CREATE TABLE invite_tokens (id INTEGER PRIMARY KEY AUTOINCREMENT, token TEXT NOT NULL, + max_uses INTEGER, uses INTEGER DEFAULT 0, expires_at TEXT, created_by INTEGER NOT NULL, + trip_id INTEGER, created_at DATETIME DEFAULT CURRENT_TIMESTAMP);`); + tmp.exec(`CREATE TABLE packing_templates (id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT NOT NULL, + created_by INTEGER NOT NULL, created_at DATETIME DEFAULT CURRENT_TIMESTAMP);`); + tmp.exec(`CREATE TABLE packing_template_categories (id INTEGER PRIMARY KEY AUTOINCREMENT, + template_id INTEGER NOT NULL, name TEXT NOT NULL, sort_order INTEGER DEFAULT 0);`); + tmp.exec(`CREATE TABLE packing_template_items (id INTEGER PRIMARY KEY AUTOINCREMENT, + category_id INTEGER NOT NULL, name TEXT NOT NULL, sort_order INTEGER DEFAULT 0);`); + tmp.exec(`CREATE TABLE addons (id TEXT PRIMARY KEY, name TEXT, description TEXT, icon TEXT, + enabled INTEGER DEFAULT 0, config TEXT, sort_order INTEGER DEFAULT 0);`); + tmp.exec(`CREATE TABLE photo_providers (id TEXT PRIMARY KEY, name TEXT, description TEXT, + icon TEXT, enabled INTEGER DEFAULT 0, sort_order INTEGER DEFAULT 0);`); + tmp.exec(`CREATE TABLE photo_provider_fields (id INTEGER PRIMARY KEY AUTOINCREMENT, + provider_id TEXT NOT NULL, field_key TEXT, label TEXT, input_type TEXT, placeholder TEXT, + required INTEGER DEFAULT 0, secret INTEGER DEFAULT 0, settings_key TEXT, payload_key TEXT, + sort_order INTEGER DEFAULT 0);`); + tmp.exec(`CREATE TABLE mcp_tokens (id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT, + token_prefix TEXT, user_id INTEGER NOT NULL, created_at DATETIME DEFAULT CURRENT_TIMESTAMP, + last_used_at DATETIME);`); + tmp.exec('CREATE TABLE oauth_clients (client_id TEXT PRIMARY KEY, name TEXT);'); + tmp.exec(`CREATE TABLE oauth_tokens (id INTEGER PRIMARY KEY AUTOINCREMENT, client_id TEXT NOT NULL, + user_id INTEGER NOT NULL, scopes TEXT, access_token_expires_at DATETIME, + refresh_token_expires_at DATETIME, revoked_at DATETIME, + created_at DATETIME DEFAULT CURRENT_TIMESTAMP);`); return { db: tmp }; }); vi.mock('../../src/db/database', () => ({ db, closeDb: () => {}, reinitialize: () => {} })); -// The audit domain is DI-native now: writeAudit runs for real against the temp -// db's audit_log table; only the file logger is silenced. +// The audit domain is DI-native: writeAudit runs for real against the temp db's +// audit_log table; only the file logger is silenced. vi.mock('../../src/nest/audit/audit-log.logger', () => ({ LOG_LEVEL: 'error', logInfo: vi.fn(), logDebug: vi.fn(), logError: vi.fn(), logWarn: vi.fn() })); vi.mock('../../src/mcp', () => ({ invalidateMcpSessions: vi.fn() })); +vi.mock('../../src/mcp/sessionManager', () => ({ revokeUserSessions: vi.fn(), revokeUserSessionsForClient: vi.fn() })); vi.mock('../../src/services/notificationPreferencesService', () => ({ getPreferencesMatrix: vi.fn(() => ({})), setAdminPreferences: vi.fn() })); vi.mock('../../src/nest/notifications/notifications.bridge', () => ({ send: vi.fn().mockResolvedValue(undefined) })); -const { adminSvc } = vi.hoisted(() => ({ - adminSvc: { listUsers: vi.fn(), createUser: vi.fn(), updatePlacesPhotos: vi.fn() }, -})); -vi.mock('../../src/services/adminService', () => adminSvc); - import { AdminModule } from '../../src/nest/admin/admin.module'; import { TrekExceptionFilter } from '../../src/nest/common/trek-exception.filter'; +import { ZodValidationPipe } from '../../src/nest/common/zod-validation.pipe'; describe('Admin e2e (real auth + admin guard + temp SQLite)', () => { let server: Server; @@ -57,17 +88,19 @@ describe('Admin e2e (real auth + admin guard + temp SQLite)', () => { const moduleRef = await Test.createTestingModule({ imports: [DatabaseModule, RealtimeModule, AdminModule] }).compile(); const nest = moduleRef.createNestApplication(); nest.use(cookieParser()); + // Mirror the production APP_PIPE (app.module.ts): DTO-typed bodies validate + // against their @trek/shared schemas. + nest.useGlobalPipes(new ZodValidationPipe()); nest.useGlobalFilters(new TrekExceptionFilter()); await nest.init(); return nest; } beforeAll(async () => { - seedUser(db as never, { id: 1, role: 'admin', email: 'admin@example.test' }); - seedUser(db as never, { id: 2, role: 'user', email: 'member@example.test' }); + seedUser(db as never, { id: 1, role: 'admin', email: 'admin@example.test', username: 'admin' }); + seedUser(db as never, { id: 2, role: 'user', email: 'member@example.test', username: 'member' }); app = await build(); server = app.getHttpServer(); - adminSvc.listUsers.mockReturnValue([{ id: 1 }]); }); beforeEach(() => { delete process.env.NODE_ENV; }); @@ -86,23 +119,109 @@ describe('Admin e2e (real auth + admin guard + temp SQLite)', () => { expect(res.body).toEqual({ error: 'Admin access required' }); }); - it('200 list for an admin', async () => { + it('200 list for an admin — real rows, guests excluded', async () => { const res = await request(server).get('/api/admin/users').set('Cookie', sessionCookie(1)); expect(res.status).toBe(200); - expect(res.body).toEqual({ users: [{ id: 1 }] }); + expect(res.body.users.map((u: { email: string }) => u.email).sort()) + .toEqual(['admin@example.test', 'member@example.test']); + expect(res.body.users[0]).toHaveProperty('avatar_url'); }); - it('201 on user create', async () => { - adminSvc.createUser.mockReturnValue({ user: { id: 3 }, insertedId: 3, auditDetails: {} }); - const res = await request(server).post('/api/admin/users').set('Cookie', sessionCookie(1)).send({ email: 'new@x.y' }); + it('201 on user create — persists the row and writes an audit entry', async () => { + const res = await request(server).post('/api/admin/users').set('Cookie', sessionCookie(1)) + .send({ username: 'created', email: 'new@x.y', password: 'Str0ng!Pass', role: 'user' }); expect(res.status).toBe(201); - expect(res.body).toEqual({ user: { id: 3 } }); + expect(res.body.user).toMatchObject({ username: 'created', email: 'new@x.y', role: 'user' }); + + const row = db.prepare('SELECT username, role FROM users WHERE email = ?').get('new@x.y'); + expect(row).toEqual({ username: 'created', role: 'user' }); + const audit = db.prepare("SELECT action FROM audit_log WHERE action = 'admin.user_create'").get(); + expect(audit).toBeDefined(); + }); + + it('400 on user create with a weak password', async () => { + const res = await request(server).post('/api/admin/users').set('Cookie', sessionCookie(1)) + .send({ username: 'weak', email: 'weak@x.y', password: 'short' }); + expect(res.status).toBe(400); + expect(res.body).toEqual({ error: 'Password must be at least 8 characters' }); + }); + + it('409 on a duplicate email', async () => { + const res = await request(server).post('/api/admin/users').set('Cookie', sessionCookie(1)) + .send({ username: 'dupe', email: 'admin@example.test', password: 'Str0ng!Pass' }); + expect(res.status).toBe(409); + expect(res.body).toEqual({ error: 'Email already taken' }); }); it('400 on a non-boolean feature toggle', async () => { + // Post-ratchet: the inline typeof check is gone, so this is the pipe's + // standard { error: 'field: message' } envelope. const res = await request(server).put('/api/admin/places-photos').set('Cookie', sessionCookie(1)).send({ enabled: 'yes' }); expect(res.status).toBe(400); - expect(res.body).toEqual({ error: 'enabled must be a boolean' }); + expect(res.body).toEqual({ error: 'enabled: Invalid input: expected boolean, received string' }); + }); + + it('places-photos toggle round-trips through app_settings', async () => { + const off = await request(server).put('/api/admin/places-photos').set('Cookie', sessionCookie(1)).send({ enabled: false }); + expect(off.status).toBe(200); + expect(db.prepare("SELECT value FROM app_settings WHERE key = 'places_photos_enabled'").get()).toEqual({ value: 'false' }); + expect((await request(server).get('/api/admin/places-photos').set('Cookie', sessionCookie(1))).body).toEqual({ enabled: false }); + + await request(server).put('/api/admin/places-photos').set('Cookie', sessionCookie(1)).send({ enabled: true }); + expect((await request(server).get('/api/admin/places-photos').set('Cookie', sessionCookie(1))).body).toEqual({ enabled: true }); + }); + + it('GET /stats counts real rows', async () => { + db.prepare("INSERT INTO trips (title, user_id) VALUES ('T', 1)").run(); + db.prepare('INSERT INTO places (trip_id) VALUES (1)').run(); + const res = await request(server).get('/api/admin/stats').set('Cookie', sessionCookie(1)); + expect(res.status).toBe(200); + expect(res.body).toMatchObject({ totalTrips: 1, totalPlaces: 1, totalFiles: 0 }); + expect(res.body.totalUsers).toBeGreaterThanOrEqual(2); + }); + + it('invite create → list → delete round trip', async () => { + const created = await request(server).post('/api/admin/invites').set('Cookie', sessionCookie(1)).send({ max_uses: 3 }); + expect(created.status).toBe(201); + expect(created.body.invite.max_uses).toBe(3); + expect(created.body.invite.created_by_name).toBe('admin'); + + const listed = await request(server).get('/api/admin/invites').set('Cookie', sessionCookie(1)); + expect(listed.body.invites).toHaveLength(1); + + const del = await request(server).delete(`/api/admin/invites/${created.body.invite.id}`).set('Cookie', sessionCookie(1)); + expect(del.status).toBe(200); + expect(db.prepare('SELECT COUNT(*) as c FROM invite_tokens').get()).toEqual({ c: 0 }); + }); + + it('404 deleting an unknown invite', async () => { + const res = await request(server).delete('/api/admin/invites/9999').set('Cookie', sessionCookie(1)); + expect(res.status).toBe(404); + expect(res.body).toEqual({ error: 'Invite not found' }); + }); + + it('packing-template create → get → delete round trip', async () => { + const created = await request(server).post('/api/admin/packing-templates').set('Cookie', sessionCookie(1)).send({ name: 'Beach' }); + expect(created.status).toBe(201); + const id = created.body.template.id; + + const fetched = await request(server).get(`/api/admin/packing-templates/${id}`).set('Cookie', sessionCookie(1)); + expect(fetched.body.template.name).toBe('Beach'); + expect(fetched.body.categories).toEqual([]); + + expect((await request(server).delete(`/api/admin/packing-templates/${id}`).set('Cookie', sessionCookie(1))).status).toBe(200); + expect(db.prepare('SELECT COUNT(*) as c FROM packing_templates').get()).toEqual({ c: 0 }); + }); + + it('GET /oidc reads app_settings defaults', async () => { + const res = await request(server).get('/api/admin/oidc').set('Cookie', sessionCookie(1)); + expect(res.status).toBe(200); + expect(res.body).toMatchObject({ issuer: '', client_id: '', client_secret_set: false }); + }); + + it('GET /mcp-tokens and /oauth-sessions return empty lists', async () => { + expect((await request(server).get('/api/admin/mcp-tokens').set('Cookie', sessionCookie(1))).body).toEqual({ tokens: [] }); + expect((await request(server).get('/api/admin/oauth-sessions').set('Cookie', sessionCookie(1))).body).toEqual({ sessions: [] }); }); it('404 on the dev-only test-notification outside development', async () => { diff --git a/server/tests/unit/nest/admin.controller.test.ts b/server/tests/unit/nest/admin.controller.test.ts index d8274d632..02617ef44 100644 --- a/server/tests/unit/nest/admin.controller.test.ts +++ b/server/tests/unit/nest/admin.controller.test.ts @@ -59,8 +59,7 @@ describe('AdminController users', () => { }); describe('AdminController permissions + oidc + misc', () => { - it('permissions: 400 without an object, else saves + audits', () => { - expect(thrown(() => adminCtl(svc()).savePermissions(user, {}, req))).toEqual({ status: 400, body: { error: 'permissions object required' } }); + it('permissions: saves + audits', () => { const c = adminCtl(svc({ savePermissions: vi.fn().mockReturnValue({ permissions: { x: 1 }, skipped: [] }) } as Partial)); expect(c.savePermissions(user, { permissions: { x: 1 } }, req)).toEqual({ success: true, permissions: { x: 1 } }); }); @@ -89,8 +88,7 @@ describe('AdminController invites + feature toggles', () => { expect(thrown(() => adminCtl(svc({ deleteInvite: vi.fn().mockReturnValue({ error: 'not found', status: 404 }) } as Partial)).deleteInvite(user, '5', req))).toEqual({ status: 404, body: { error: 'not found' } }); }); - it('places-photos: 400 on a non-boolean, else updates + audits', () => { - expect(thrown(() => adminCtl(svc()).updatePlacesPhotos(user, { enabled: 'yes' }, req))).toEqual({ status: 400, body: { error: 'enabled must be a boolean' } }); + it('places-photos: updates + audits', () => { expect(adminCtl(svc({ updatePlacesPhotos: vi.fn().mockReturnValue({ enabled: true }) } as Partial)).updatePlacesPhotos(user, { enabled: true }, req)).toEqual({ enabled: true }); }); @@ -144,8 +142,7 @@ describe('AdminController addons + sessions + jwt + defaults', () => { expect(adminCtl(svc({ rotateJwtSecret: vi.fn().mockReturnValue({}) } as Partial)).rotateJwtSecret(user, req)).toEqual({ success: true }); }); - it('default-user-settings: 400 on a non-object, else sets + audits', () => { - expect(thrown(() => adminCtl(svc()).setDefaultUserSettings(user, [], req))).toEqual({ status: 400, body: { error: 'Object body required' } }); + it('default-user-settings: sets + audits', () => { const setAdminUserDefaults = vi.fn(); const c = adminCtl(svc({ setAdminUserDefaults, getAdminUserDefaults: vi.fn().mockReturnValue({ theme: 'dark' }) } as Partial)); expect(c.setDefaultUserSettings(user, { theme: 'dark' }, req)).toEqual({ theme: 'dark' }); @@ -214,13 +211,11 @@ describe('AdminController feature toggles + audit', () => { expect(writeAudit).toHaveBeenCalledWith(expect.objectContaining({ action: 'admin.bag_tracking' })); }); - it('places-autocomplete: 400 on a non-boolean, else updates + audits', () => { - expect(thrown(() => adminCtl(svc()).updatePlacesAutocomplete(user, { enabled: 'yes' }, req))).toEqual({ status: 400, body: { error: 'enabled must be a boolean' } }); + it('places-autocomplete: updates + audits', () => { expect(adminCtl(svc({ updatePlacesAutocomplete: vi.fn().mockReturnValue({ enabled: false }) } as Partial)).updatePlacesAutocomplete(user, { enabled: false }, req)).toEqual({ enabled: false }); }); - it('places-details: 400 on a non-boolean, else updates + audits', () => { - expect(thrown(() => adminCtl(svc()).updatePlacesDetails(user, { enabled: 1 }, req))).toEqual({ status: 400, body: { error: 'enabled must be a boolean' } }); + it('places-details: updates + audits', () => { expect(adminCtl(svc({ updatePlacesDetails: vi.fn().mockReturnValue({ enabled: true }) } as Partial)).updatePlacesDetails(user, { enabled: true }, req)).toEqual({ enabled: true }); }); }); @@ -256,9 +251,6 @@ describe('AdminController default-user-settings error path', () => { expect(thrown(() => c.setDefaultUserSettings(user, { theme: 'x' }, req))).toEqual({ status: 400, body: { error: 'plain string' } }); }); - it('400 when the body is null', () => { - expect(thrown(() => adminCtl(svc()).setDefaultUserSettings(user, null, req))).toEqual({ status: 400, body: { error: 'Object body required' } }); - }); }); describe('AdminController dev test-notification', () => { diff --git a/server/tests/unit/services/adminService.test.ts b/server/tests/unit/nest/admin.service.test.ts similarity index 67% rename from server/tests/unit/services/adminService.test.ts rename to server/tests/unit/nest/admin.service.test.ts index 14e40a77b..f295bb5b8 100644 --- a/server/tests/unit/services/adminService.test.ts +++ b/server/tests/unit/nest/admin.service.test.ts @@ -1,7 +1,12 @@ /** - * Unit tests for adminService — ADMIN-SVC-001 through ADMIN-SVC-050. - * Uses a real in-memory SQLite DB. Focuses on validation/error branches - * that the integration tests don't exercise. + * Unit tests for the DI-native AdminService — ADMIN-SVC-001 through + * ADMIN-SVC-069, moved 1:1 from tests/unit/services/adminService.test.ts with + * the 2026-08 fold (IDs preserved, including the pre-existing 029/030 gap and + * the duplicated 069). The packing-template cases (031-044, 056-064) moved with + * their functions to tests/unit/nest/packing.service.test.ts. + * Constructs the service directly over a real in-memory SQLite DB (repo + * convention — no TestingModule). Focuses on validation/error branches that the + * integration tests don't exercise. ADMIN-BR-001 pins the admin.bridge export. */ import { describe, it, expect, vi, beforeAll, beforeEach, afterEach, afterAll } from 'vitest'; @@ -37,6 +42,11 @@ vi.mock('../../../src/services/apiKeyCrypto', () => ({ })); vi.mock('../../../src/mcp', () => ({ revokeUserSessions: vi.fn(), + invalidateMcpSessions: vi.fn(), +})); +vi.mock('../../../src/mcp/sessionManager', () => ({ + revokeUserSessions: vi.fn(), + revokeUserSessionsForClient: vi.fn(), })); vi.mock('../../../src/demo/demo-reset', () => ({ saveBaseline: vi.fn(), @@ -46,39 +56,57 @@ import { createTables } from '../../../src/db/schema'; import { runMigrations } from '../../../src/db/migrations'; import { resetTestDb } from '../../helpers/test-db'; import { createUser, createAdmin, createInviteToken } from '../../helpers/factories'; -import { - listUsers, - createUser as svcCreateUser, - updateUser, - deleteUser, - getStats, - getPermissions, - savePermissions, - getAuditLog, - listInvites, - createInvite, - deleteInvite, - listPackingTemplates, - createPackingTemplate, - updatePackingTemplate, - deletePackingTemplate, - createTemplateCategory, - updateTemplateCategory, - deleteTemplateCategory, - getPackingTemplate, - createTemplateItem, - updateTemplateItem, - deleteTemplateItem, - getOidcSettings, - updateOidcSettings, - saveDemoBaseline, - getGithubReleases, - checkVersion, - listAddons, - updateAddon, - listMcpTokens, - deleteMcpToken, -} from '../../../src/services/adminService'; +import { DatabaseService } from '../../../src/nest/database/database.service'; +import { RealtimeService } from '../../../src/nest/realtime/realtime.service'; +import { AddonsService } from '../../../src/nest/addons/addons.service'; +import { SettingsService } from '../../../src/nest/settings/settings.service'; +import { AtlasService } from '../../../src/nest/atlas/atlas.service'; +import { AuthService } from '../../../src/nest/auth/auth.service'; +import { PasskeyService } from '../../../src/nest/auth/passkey.service'; +import { PackingService } from '../../../src/nest/packing/packing.service'; +import { PermissionsService } from '../../../src/nest/permissions/permissions.service'; +import { NotificationsService } from '../../../src/nest/notifications/notifications.service'; +import { AdminService } from '../../../src/nest/admin/admin.service'; +import { checkAndNotifyVersion as bridgeCheckAndNotifyVersion } from '../../../src/nest/admin/admin.bridge'; +import { __clearVersionCacheForTests } from '../../../src/nest/admin/admin.helpers'; + +const dbs = new DatabaseService(testDb); +const realtime = new RealtimeService(); +const permissions = new PermissionsService(dbs); +const auth = new AuthService(dbs, permissions, new AtlasService(dbs)); +const svc = new AdminService( + dbs, + new SettingsService(dbs), + new AddonsService(dbs), + new PasskeyService(dbs, auth), + new PackingService(dbs, permissions, realtime), + auth, + permissions, + new NotificationsService(dbs, realtime), +); + +// Legacy free-function names bound to the service, so the moved cases below read +// exactly as they did before the fold. +const listUsers = () => svc.listUsers(); +const svcCreateUser = (d: Parameters[0]) => svc.createUser(d); +const updateUser = (id: string, d: Parameters[1]) => svc.updateUser(id, d); +const deleteUser = (id: string, actingId: number) => svc.deleteUser(id, actingId); +const getStats = () => svc.getStats(); +const getPermissions = () => svc.getPermissions(); +const savePermissions = (p: Record) => svc.savePermissions(p); +const getAuditLog = (q: { limit?: string; offset?: string }) => svc.getAuditLog(q); +const listInvites = () => svc.listInvites(); +const createInvite = (by: number, d: Parameters[1]) => svc.createInvite(by, d); +const deleteInvite = (id: string) => svc.deleteInvite(id); +const getOidcSettings = () => svc.getOidcSettings(); +const updateOidcSettings = (d: Parameters[0]) => svc.updateOidcSettings(d); +const saveDemoBaseline = () => svc.saveDemoBaseline(); +const getGithubReleases = (perPage?: string, page?: string) => svc.getGithubReleases(perPage, page); +const checkVersion = () => svc.checkVersion(); +const listAddons = () => svc.listAddons(); +const updateAddon = (id: string, d: Parameters[1]) => svc.updateAddon(id, d); +const listMcpTokens = () => svc.listMcpTokens(); +const deleteMcpToken = (id: string) => svc.deleteMcpToken(id); beforeAll(() => { createTables(testDb); @@ -306,106 +334,6 @@ describe('Invites', () => { }); }); -// ── Packing templates ───────────────────────────────────────────────────────── - -describe('Packing templates', () => { - it('ADMIN-SVC-031 — createPackingTemplate returns template', () => { - const { user: admin } = createAdmin(testDb); - const result = createPackingTemplate('Beach Trip', admin.id) as any; - expect(result.template.name).toBe('Beach Trip'); - }); - - it('ADMIN-SVC-032 — createPackingTemplate returns 400 for empty name', () => { - const { user: admin } = createAdmin(testDb); - const result = createPackingTemplate('', admin.id) as any; - expect(result.status).toBe(400); - }); - - it('ADMIN-SVC-033 — listPackingTemplates returns array', () => { - const { user: admin } = createAdmin(testDb); - createPackingTemplate('Template A', admin.id); - const templates = listPackingTemplates() as any[]; - expect(templates.length).toBeGreaterThanOrEqual(1); - }); - - it('ADMIN-SVC-034 — updatePackingTemplate updates name', () => { - const { user: admin } = createAdmin(testDb); - const created = createPackingTemplate('Old Name', admin.id) as any; - const result = updatePackingTemplate(String(created.template.id), { name: 'New Name' }) as any; - expect(result.template.name).toBe('New Name'); - }); - - it('ADMIN-SVC-035 — updatePackingTemplate returns 404 for non-existent', () => { - const result = updatePackingTemplate('99999', { name: 'Ghost' }) as any; - expect(result.status).toBe(404); - }); - - it('ADMIN-SVC-036 — deletePackingTemplate removes template', () => { - const { user: admin } = createAdmin(testDb); - const created = createPackingTemplate('To Delete', admin.id) as any; - const result = deletePackingTemplate(String(created.template.id)) as any; - expect(result.name).toBe('To Delete'); - }); - - it('ADMIN-SVC-037 — deletePackingTemplate returns 404 for non-existent', () => { - const result = deletePackingTemplate('99999') as any; - expect(result.status).toBe(404); - }); -}); - -// ── Template categories ─────────────────────────────────────────────────────── - -describe('Template categories', () => { - it('ADMIN-SVC-038 — createTemplateCategory creates a category', () => { - const { user: admin } = createAdmin(testDb); - const tpl = createPackingTemplate('Tpl', admin.id) as any; - const result = createTemplateCategory(String(tpl.template.id), 'Clothing') as any; - expect(result.category.name).toBe('Clothing'); - }); - - it('ADMIN-SVC-039 — createTemplateCategory returns 400 for empty name', () => { - const { user: admin } = createAdmin(testDb); - const tpl = createPackingTemplate('Tpl', admin.id) as any; - const result = createTemplateCategory(String(tpl.template.id), '') as any; - expect(result.status).toBe(400); - }); - - it('ADMIN-SVC-040 — createTemplateCategory returns 404 for missing template', () => { - const result = createTemplateCategory('99999', 'Clothing') as any; - expect(result.status).toBe(404); - }); - - it('ADMIN-SVC-041 — updateTemplateCategory updates name', () => { - const { user: admin } = createAdmin(testDb); - const tpl = createPackingTemplate('Tpl', admin.id) as any; - const cat = createTemplateCategory(String(tpl.template.id), 'Old') as any; - const result = updateTemplateCategory(String(tpl.template.id), String(cat.category.id), { name: 'New' }) as any; - expect(result.category.name).toBe('New'); - }); - - it('ADMIN-SVC-042 — updateTemplateCategory returns 404 for missing category', () => { - const { user: admin } = createAdmin(testDb); - const tpl = createPackingTemplate('Tpl', admin.id) as any; - const result = updateTemplateCategory(String(tpl.template.id), '99999', { name: 'X' }) as any; - expect(result.status).toBe(404); - }); - - it('ADMIN-SVC-043 — deleteTemplateCategory removes category', () => { - const { user: admin } = createAdmin(testDb); - const tpl = createPackingTemplate('Tpl', admin.id) as any; - const cat = createTemplateCategory(String(tpl.template.id), 'Remove Me') as any; - const result = deleteTemplateCategory(String(tpl.template.id), String(cat.category.id)) as any; - expect(result.error).toBeUndefined(); - }); - - it('ADMIN-SVC-044 — deleteTemplateCategory returns 404 for missing', () => { - const { user: admin } = createAdmin(testDb); - const tpl = createPackingTemplate('Tpl', admin.id) as any; - const result = deleteTemplateCategory(String(tpl.template.id), '99999') as any; - expect(result.status).toBe(404); - }); -}); - // ── getAuditLog — JSON details parsing ─────────────────────────────────────── describe('getAuditLog — JSON details', () => { @@ -421,7 +349,7 @@ describe('getAuditLog — JSON details', () => { expect(entry.details).toEqual({ key: 'val' }); }); - it('ADMIN-SVC-046 — handles invalid JSON gracefully with _parse_error flag', () => { + it('ADMIN-SVC-046 — falls back to the raw string when details are not valid JSON', () => { const { user } = createUser(testDb); testDb.prepare('INSERT INTO audit_log (user_id, action, details) VALUES (?, ?, ?)').run( user.id, 'bad_json_action', 'not-valid-json{' @@ -429,7 +357,9 @@ describe('getAuditLog — JSON details', () => { const result = getAuditLog({}) as any; const entry = result.entries.find((e: any) => e.action === 'bad_json_action'); expect(entry).toBeDefined(); - expect(entry.details).toEqual({ _parse_error: true }); + // Was { _parse_error: true } before the 2026-08 quirk fix — the admin UI + // rendered that sentinel literally. + expect(entry.details).toBe('not-valid-json{'); }); }); @@ -510,6 +440,7 @@ describe('getGithubReleases', () => { ]; vi.stubGlobal('fetch', vi.fn().mockResolvedValue({ ok: true, + text: async () => JSON.stringify(mockReleases), json: async () => mockReleases, })); const result = await getGithubReleases(); @@ -526,6 +457,10 @@ describe('checkVersion', () => { vi.unstubAllGlobals(); }); + // Since the 2026-08 quirk fix, failures cache too (on a 60s TTL), so each case + // clears the module-scoped cache rather than reading the previous one's result. + beforeEach(() => { __clearVersionCacheForTests(); }); + it('ADMIN-SVC-054 — returns update_available:false when fetch fails', async () => { vi.stubGlobal('fetch', vi.fn().mockRejectedValue(new Error('Network error'))); const result = await checkVersion() as any; @@ -537,6 +472,7 @@ describe('checkVersion', () => { it('ADMIN-SVC-055 — returns update_available:true when latest version is greater than current', async () => { vi.stubGlobal('fetch', vi.fn().mockResolvedValue({ ok: true, + text: async () => JSON.stringify({ tag_name: 'v999.0.0', html_url: 'https://github.com/example/releases/tag/v999.0.0' }), json: async () => ({ tag_name: 'v999.0.0', html_url: 'https://github.com/example/releases/tag/v999.0.0' }), })); const result = await checkVersion() as any; @@ -544,89 +480,13 @@ describe('checkVersion', () => { expect(result.latest).toBe('999.0.0'); expect(result.release_url).toBe('https://github.com/example/releases/tag/v999.0.0'); }); -}); -// ── getPackingTemplate ──────────────────────────────────────────────────────── - -describe('getPackingTemplate', () => { - it('ADMIN-SVC-056 — returns template with categories and items when template exists', () => { - const { user: admin } = createAdmin(testDb); - const tpl = createPackingTemplate('Full Template', admin.id) as any; - const cat = createTemplateCategory(String(tpl.template.id), 'Clothing') as any; - createTemplateItem(String(tpl.template.id), String(cat.category.id), 'T-Shirt'); - - const result = getPackingTemplate(String(tpl.template.id)) as any; - expect(result.template).toBeDefined(); - expect(result.template.name).toBe('Full Template'); - expect(Array.isArray(result.categories)).toBe(true); - expect(result.categories.length).toBeGreaterThanOrEqual(1); - expect(Array.isArray(result.items)).toBe(true); - expect(result.items.length).toBeGreaterThanOrEqual(1); - expect(result.items[0].name).toBe('T-Shirt'); - }); - - it('ADMIN-SVC-057 — returns 404 for non-existent template', () => { - const result = getPackingTemplate('99999') as any; - expect(result.status).toBe(404); - expect(result.error).toBeDefined(); - }); -}); - -// ── Template items ──────────────────────────────────────────────────────────── - -describe('Template items', () => { - it('ADMIN-SVC-058 — createTemplateItem returns item with name', () => { - const { user: admin } = createAdmin(testDb); - const tpl = createPackingTemplate('Tpl', admin.id) as any; - const cat = createTemplateCategory(String(tpl.template.id), 'Gear') as any; - const result = createTemplateItem(String(tpl.template.id), String(cat.category.id), 'Backpack') as any; - expect(result.item).toBeDefined(); - expect(result.item.name).toBe('Backpack'); - }); - - it('ADMIN-SVC-059 — createTemplateItem returns 400 for empty name', () => { - const { user: admin } = createAdmin(testDb); - const tpl = createPackingTemplate('Tpl', admin.id) as any; - const cat = createTemplateCategory(String(tpl.template.id), 'Gear') as any; - const result = createTemplateItem(String(tpl.template.id), String(cat.category.id), '') as any; - expect(result.status).toBe(400); - }); - - it('ADMIN-SVC-060 — createTemplateItem returns 404 for non-existent category', () => { - const { user: admin } = createAdmin(testDb); - const tpl = createPackingTemplate('Tpl', admin.id) as any; - const result = createTemplateItem(String(tpl.template.id), '99999', 'Item') as any; - expect(result.status).toBe(404); - }); - - it('ADMIN-SVC-061 — updateTemplateItem updates name', () => { - const { user: admin } = createAdmin(testDb); - const tpl = createPackingTemplate('Tpl', admin.id) as any; - const cat = createTemplateCategory(String(tpl.template.id), 'Gear') as any; - const item = createTemplateItem(String(tpl.template.id), String(cat.category.id), 'Old Item') as any; - const result = updateTemplateItem(String(item.item.id), { name: 'New Item' }) as any; - expect(result.item.name).toBe('New Item'); - }); - - it('ADMIN-SVC-062 — updateTemplateItem returns 404 for non-existent item', () => { - const result = updateTemplateItem('99999', { name: 'Ghost' }) as any; - expect(result.status).toBe(404); - }); - - it('ADMIN-SVC-063 — deleteTemplateItem removes item', () => { - const { user: admin } = createAdmin(testDb); - const tpl = createPackingTemplate('Tpl', admin.id) as any; - const cat = createTemplateCategory(String(tpl.template.id), 'Gear') as any; - const item = createTemplateItem(String(tpl.template.id), String(cat.category.id), 'To Delete') as any; - const result = deleteTemplateItem(String(item.item.id)) as any; - expect(result.error).toBeUndefined(); - const check = testDb.prepare('SELECT id FROM packing_template_items WHERE id = ?').get(item.item.id); - expect(check).toBeUndefined(); - }); - - it('ADMIN-SVC-064 — deleteTemplateItem returns 404 for non-existent item', () => { - const result = deleteTemplateItem('99999') as any; - expect(result.status).toBe(404); + it('ADMIN-SVC-070 — a failed check is cached briefly instead of refetching per call', async () => { + const fetchMock = vi.fn().mockRejectedValue(new Error('Network error')); + vi.stubGlobal('fetch', fetchMock); + await checkVersion(); + await checkVersion(); + expect(fetchMock).toHaveBeenCalledTimes(1); }); }); @@ -691,3 +551,89 @@ describe('MCP Tokens', () => { expect(result.error).toBeDefined(); }); }); + +// ── admin.bridge ────────────────────────────────────────────────────────────── + +describe('admin.bridge', () => { + it('ADMIN-BR-001 — checkAndNotifyVersion delegates to AdminService over the shared db Proxy', async () => { + createAdmin(testDb); + __clearVersionCacheForTests(); + const fetchMock = vi.fn().mockResolvedValue({ + ok: true, + text: async () => JSON.stringify({ tag_name: 'v99.9.9', html_url: 'https://example.test/r' }), + json: async () => ({ tag_name: 'v99.9.9', html_url: 'https://example.test/r' }), + }); + vi.stubGlobal('fetch', fetchMock); + + await bridgeCheckAndNotifyVersion(); + + const notified = testDb + .prepare('SELECT value FROM app_settings WHERE key = ?') + .get('last_notified_version') as { value: string } | undefined; + expect(notified?.value).toBe('99.9.9'); + + // The version cache is module-scoped in admin.helpers, so the bridge instance + // and the container singleton share it — the second read must not re-fetch. + expect(await svc.checkVersion()).toMatchObject({ latest: '99.9.9' }); + expect(fetchMock).toHaveBeenCalledTimes(1); + vi.unstubAllGlobals(); + __clearVersionCacheForTests(); + }); +}); + +// ── Quirk fixes landed after the 2026-08 fold ───────────────────────────────── + +describe('admin quirk fixes (post-fold)', () => { + it('ADMIN-SVC-071 — the three places toggles are fail-closed (=== true), matching bag-tracking', () => { + // Unset used to read as ON (`!== 'false'`); a migration backfills 'true' for + // existing installs so nobody loses a feature on upgrade. + expect(svc.getPlacesPhotos()).toEqual({ enabled: false }); + expect(svc.getPlacesAutocomplete()).toEqual({ enabled: false }); + expect(svc.getPlacesDetails()).toEqual({ enabled: false }); + + svc.updatePlacesPhotos(true); + expect(svc.getPlacesPhotos()).toEqual({ enabled: true }); + + testDb.prepare("INSERT OR REPLACE INTO app_settings (key, value) VALUES ('places_details_enabled', 'garbage')").run(); + expect(svc.getPlacesDetails()).toEqual({ enabled: false }); + }); + + it('ADMIN-SVC-072 — updateUser rejects an empty username/email instead of silently no-opping', () => { + const { user } = createUser(testDb); + expect(updateUser(String(user.id), { username: '' }) as any).toMatchObject({ status: 400, error: 'Username cannot be empty' }); + expect(updateUser(String(user.id), { email: ' ' }) as any).toMatchObject({ status: 400, error: 'Email cannot be empty' }); + // The row is untouched. + const row = testDb.prepare('SELECT username FROM users WHERE id = ?').get(user.id) as { username: string }; + expect(row.username).toBe(user.username); + }); + + it('ADMIN-SVC-073 — createInvite 404s on a trip_id that does not resolve', () => { + const { user: admin } = createAdmin(testDb); + expect(createInvite(admin.id, { trip_id: 99999 }) as any).toMatchObject({ status: 404, error: 'Trip not found' }); + expect(createInvite(admin.id, { trip_id: 'not-a-number' }) as any).toMatchObject({ status: 404 }); + expect(testDb.prepare('SELECT COUNT(*) as c FROM invite_tokens').get()).toEqual({ c: 0 }); + // An absent/blank binding is still a plain registration invite. + expect((createInvite(admin.id, {}) as any).tripId).toBeNull(); + }); + + it('ADMIN-SVC-074 — listOAuthSessions survives a row with malformed scopes JSON', () => { + const { user } = createUser(testDb); + testDb.prepare("INSERT INTO oauth_clients (client_id, client_secret_hash, name) VALUES ('c1', 'hash', 'Client')").run(); + testDb.prepare(` + INSERT INTO oauth_tokens (client_id, user_id, access_token_hash, refresh_token_hash, scopes, + access_token_expires_at, refresh_token_expires_at) + VALUES ('c1', ?, 'ahash', 'rhash', 'not-json{', datetime('now', '+1 hour'), datetime('now', '+1 day')) + `).run(user.id); + + const sessions = svc.listOAuthSessions() as any[]; + expect(sessions).toHaveLength(1); + expect(sessions[0].scopes).toBeNull(); + }); + + it('ADMIN-SVC-075 — updateOidcSettings applies all five writes atomically', () => { + const result = svc.updateOidcSettings({ issuer: 'https://idp', client_id: 'cid', display_name: 'IdP' }) as any; + expect(result.success).toBe(true); + const settings = svc.getOidcSettings(); + expect(settings).toMatchObject({ issuer: 'https://idp', client_id: 'cid', display_name: 'IdP' }); + }); +}); diff --git a/server/tests/unit/services/versionNotification.test.ts b/server/tests/unit/nest/admin.version-notification.test.ts similarity index 73% rename from server/tests/unit/services/versionNotification.test.ts rename to server/tests/unit/nest/admin.version-notification.test.ts index 5a2bdf7d7..b264f44ac 100644 --- a/server/tests/unit/services/versionNotification.test.ts +++ b/server/tests/unit/nest/admin.version-notification.test.ts @@ -1,10 +1,14 @@ /** - * Unit tests for checkAndNotifyVersion() in adminService. - * Covers VNOTIF-001 to VNOTIF-007. + * Unit tests for AdminService.checkAndNotifyVersion() — VNOTIF-001 to + * VNOTIF-007, moved from tests/unit/services/versionNotification.test.ts with + * the 2026-08 admin fold, IDs preserved. Kept separate from admin.service.test.ts + * because it stubs global fetch and drives the module-scoped version cache per + * case, which would leak into the ADMIN-SVC-* suite. The notification path runs + * for real against the temp db's notifications table. */ import { runMigrations } from '../../../src/db/migrations'; import { createTables } from '../../../src/db/schema'; -import { checkAndNotifyVersion, __clearVersionCacheForTests } from '../../../src/services/adminService'; +import { __clearVersionCacheForTests } from '../../../src/nest/admin/admin.helpers'; import { createAdmin } from '../../helpers/factories'; import { resetTestDb } from '../../helpers/test-db'; @@ -34,7 +38,36 @@ vi.mock('../../../src/config', () => ({ })); vi.mock('../../../src/websocket', () => ({ broadcastToUser: vi.fn() })); // Mock MCP to avoid session side-effects -vi.mock('../../../src/mcp', () => ({ revokeUserSessions: vi.fn() })); +vi.mock('../../../src/mcp', () => ({ revokeUserSessions: vi.fn(), invalidateMcpSessions: vi.fn() })); +vi.mock('../../../src/mcp/sessionManager', () => ({ revokeUserSessions: vi.fn(), revokeUserSessionsForClient: vi.fn() })); + +import { DatabaseService } from '../../../src/nest/database/database.service'; +import { RealtimeService } from '../../../src/nest/realtime/realtime.service'; +import { AddonsService } from '../../../src/nest/addons/addons.service'; +import { SettingsService } from '../../../src/nest/settings/settings.service'; +import { AtlasService } from '../../../src/nest/atlas/atlas.service'; +import { AuthService } from '../../../src/nest/auth/auth.service'; +import { PasskeyService } from '../../../src/nest/auth/passkey.service'; +import { PackingService } from '../../../src/nest/packing/packing.service'; +import { PermissionsService } from '../../../src/nest/permissions/permissions.service'; +import { NotificationsService } from '../../../src/nest/notifications/notifications.service'; +import { AdminService } from '../../../src/nest/admin/admin.service'; + +const dbs = new DatabaseService(testDb); +const realtime = new RealtimeService(); +const permissions = new PermissionsService(dbs); +const auth = new AuthService(dbs, permissions, new AtlasService(dbs)); +const svc = new AdminService( + dbs, + new SettingsService(dbs), + new AddonsService(dbs), + new PasskeyService(dbs, auth), + new PackingService(dbs, permissions, realtime), + auth, + permissions, + new NotificationsService(dbs, realtime), +); +const checkAndNotifyVersion = () => svc.checkAndNotifyVersion(); // Helper: mock the GitHub releases/latest endpoint function mockGitHubLatest(tagName: string, ok = true): void { @@ -42,6 +75,8 @@ function mockGitHubLatest(tagName: string, ok = true): void { 'fetch', vi.fn().mockResolvedValue({ ok, + // fetchGithub reads text() and parses it itself (size cap), so stub both. + text: async () => JSON.stringify({ tag_name: tagName, html_url: `https://github.com/liketrek/TREK/releases/tag/${tagName}` }), json: async () => ({ tag_name: tagName, html_url: `https://github.com/liketrek/TREK/releases/tag/${tagName}` }), }), ); diff --git a/server/tests/unit/nest/packing.service.test.ts b/server/tests/unit/nest/packing.service.test.ts index cb1aa85ab..d2324254d 100644 --- a/server/tests/unit/nest/packing.service.test.ts +++ b/server/tests/unit/nest/packing.service.test.ts @@ -7,6 +7,12 @@ * against real SQL — PACK-SVC-050 pinning the packing.bridge delegation, and * PACK-SVC-051..053 pinning the post-migration fixes over the legacy quirks * ('Other' category default, bodyKeys-gated weight_limit_grams, quantity clamp). + * + * The trailing "Admin template CRUD" blocks carry ADMIN-SVC-031..044 and + * ADMIN-SVC-056..064 over from tests/unit/services/adminService.test.ts with + * their IDs preserved — those functions moved into PackingService with the + * 2026-08 admin fold, since this service already owned all three template + * tables. */ import { describe, it, expect, vi, beforeAll, beforeEach, afterAll } from 'vitest'; @@ -54,7 +60,7 @@ vi.mock('../../../src/nest/notifications/notifications.bridge', () => ({ send }) import { createTables } from '../../../src/db/schema'; import { runMigrations } from '../../../src/db/migrations'; import { resetTestDb } from '../../helpers/test-db'; -import { createUser, createTrip } from '../../helpers/factories'; +import { createUser, createAdmin, createTrip } from '../../helpers/factories'; import { DatabaseService } from '../../../src/nest/database/database.service'; import type { PermissionsService } from '../../../src/nest/permissions/permissions.service'; import { PackingService } from '../../../src/nest/packing/packing.service'; @@ -725,3 +731,206 @@ describe('packing.bridge', () => { expect((bridgeListItems(trip.id, other.id) as { name: string }[]).map(i => i.name)).toEqual(['Shared']); }); }); + +// ── Admin template CRUD (moved from adminService, IDs preserved) ────────────── + +describe('Packing templates', () => { + it('ADMIN-SVC-031 — createPackingTemplate returns template', () => { + const { user: admin } = createAdmin(testDb); + const result = svc.createPackingTemplate('Beach Trip', admin.id) as any; + expect(result.template.name).toBe('Beach Trip'); + }); + + it('ADMIN-SVC-032 — createPackingTemplate returns 400 for empty name', () => { + const { user: admin } = createAdmin(testDb); + const result = svc.createPackingTemplate('', admin.id) as any; + expect(result.status).toBe(400); + }); + + it('ADMIN-SVC-033 — listPackingTemplates returns array', () => { + const { user: admin } = createAdmin(testDb); + svc.createPackingTemplate('Template A', admin.id); + const templates = svc.listPackingTemplates() as any[]; + expect(templates.length).toBeGreaterThanOrEqual(1); + }); + + it('ADMIN-SVC-034 — updatePackingTemplate updates name', () => { + const { user: admin } = createAdmin(testDb); + const created = svc.createPackingTemplate('Old Name', admin.id) as any; + const result = svc.updatePackingTemplate(String(created.template.id), { name: 'New Name' }) as any; + expect(result.template.name).toBe('New Name'); + }); + + it('ADMIN-SVC-035 — updatePackingTemplate returns 404 for non-existent', () => { + const result = svc.updatePackingTemplate('99999', { name: 'Ghost' }) as any; + expect(result.status).toBe(404); + }); + + it('ADMIN-SVC-036 — deletePackingTemplate removes template', () => { + const { user: admin } = createAdmin(testDb); + const created = svc.createPackingTemplate('To Delete', admin.id) as any; + const result = svc.deletePackingTemplate(String(created.template.id)) as any; + expect(result.name).toBe('To Delete'); + }); + + it('ADMIN-SVC-037 — deletePackingTemplate returns 404 for non-existent', () => { + const result = svc.deletePackingTemplate('99999') as any; + expect(result.status).toBe(404); + }); +}); + +describe('Template categories', () => { + it('ADMIN-SVC-038 — createTemplateCategory creates a category', () => { + const { user: admin } = createAdmin(testDb); + const tpl = svc.createPackingTemplate('Tpl', admin.id) as any; + const result = svc.createTemplateCategory(String(tpl.template.id), 'Clothing') as any; + expect(result.category.name).toBe('Clothing'); + }); + + it('ADMIN-SVC-039 — createTemplateCategory returns 400 for empty name', () => { + const { user: admin } = createAdmin(testDb); + const tpl = svc.createPackingTemplate('Tpl', admin.id) as any; + const result = svc.createTemplateCategory(String(tpl.template.id), '') as any; + expect(result.status).toBe(400); + }); + + it('ADMIN-SVC-040 — createTemplateCategory returns 404 for missing template', () => { + const result = svc.createTemplateCategory('99999', 'Clothing') as any; + expect(result.status).toBe(404); + }); + + it('ADMIN-SVC-041 — updateTemplateCategory updates name', () => { + const { user: admin } = createAdmin(testDb); + const tpl = svc.createPackingTemplate('Tpl', admin.id) as any; + const cat = svc.createTemplateCategory(String(tpl.template.id), 'Old') as any; + const result = svc.updateTemplateCategory(String(tpl.template.id), String(cat.category.id), { name: 'New' }) as any; + expect(result.category.name).toBe('New'); + }); + + it('ADMIN-SVC-042 — updateTemplateCategory returns 404 for missing category', () => { + const { user: admin } = createAdmin(testDb); + const tpl = svc.createPackingTemplate('Tpl', admin.id) as any; + const result = svc.updateTemplateCategory(String(tpl.template.id), '99999', { name: 'X' }) as any; + expect(result.status).toBe(404); + }); + + it('ADMIN-SVC-043 — deleteTemplateCategory removes category', () => { + const { user: admin } = createAdmin(testDb); + const tpl = svc.createPackingTemplate('Tpl', admin.id) as any; + const cat = svc.createTemplateCategory(String(tpl.template.id), 'Remove Me') as any; + const result = svc.deleteTemplateCategory(String(tpl.template.id), String(cat.category.id)) as any; + expect(result.error).toBeUndefined(); + }); + + it('ADMIN-SVC-044 — deleteTemplateCategory returns 404 for missing', () => { + const { user: admin } = createAdmin(testDb); + const tpl = svc.createPackingTemplate('Tpl', admin.id) as any; + const result = svc.deleteTemplateCategory(String(tpl.template.id), '99999') as any; + expect(result.status).toBe(404); + }); +}); + +describe('getPackingTemplate', () => { + it('ADMIN-SVC-056 — returns template with categories and items when template exists', () => { + const { user: admin } = createAdmin(testDb); + const tpl = svc.createPackingTemplate('Full Template', admin.id) as any; + const cat = svc.createTemplateCategory(String(tpl.template.id), 'Clothing') as any; + svc.createTemplateItem(String(tpl.template.id), String(cat.category.id), 'T-Shirt'); + + const result = svc.getPackingTemplate(String(tpl.template.id)) as any; + expect(result.template).toBeDefined(); + expect(result.template.name).toBe('Full Template'); + expect(Array.isArray(result.categories)).toBe(true); + expect(result.categories.length).toBeGreaterThanOrEqual(1); + expect(Array.isArray(result.items)).toBe(true); + expect(result.items.length).toBeGreaterThanOrEqual(1); + expect(result.items[0].name).toBe('T-Shirt'); + }); + + it('ADMIN-SVC-057 — returns 404 for non-existent template', () => { + const result = svc.getPackingTemplate('99999') as any; + expect(result.status).toBe(404); + expect(result.error).toBeDefined(); + }); +}); + +describe('Template items', () => { + it('ADMIN-SVC-058 — createTemplateItem returns item with name', () => { + const { user: admin } = createAdmin(testDb); + const tpl = svc.createPackingTemplate('Tpl', admin.id) as any; + const cat = svc.createTemplateCategory(String(tpl.template.id), 'Gear') as any; + const result = svc.createTemplateItem(String(tpl.template.id), String(cat.category.id), 'Backpack') as any; + expect(result.item).toBeDefined(); + expect(result.item.name).toBe('Backpack'); + }); + + it('ADMIN-SVC-059 — createTemplateItem returns 400 for empty name', () => { + const { user: admin } = createAdmin(testDb); + const tpl = svc.createPackingTemplate('Tpl', admin.id) as any; + const cat = svc.createTemplateCategory(String(tpl.template.id), 'Gear') as any; + const result = svc.createTemplateItem(String(tpl.template.id), String(cat.category.id), '') as any; + expect(result.status).toBe(400); + }); + + it('ADMIN-SVC-060 — createTemplateItem returns 404 for non-existent category', () => { + const { user: admin } = createAdmin(testDb); + const tpl = svc.createPackingTemplate('Tpl', admin.id) as any; + const result = svc.createTemplateItem(String(tpl.template.id), '99999', 'Item') as any; + expect(result.status).toBe(404); + }); + + it('ADMIN-SVC-061 — updateTemplateItem updates name', () => { + const { user: admin } = createAdmin(testDb); + const tpl = svc.createPackingTemplate('Tpl', admin.id) as any; + const cat = svc.createTemplateCategory(String(tpl.template.id), 'Gear') as any; + const item = svc.createTemplateItem(String(tpl.template.id), String(cat.category.id), 'Old Item') as any; + const result = svc.updateTemplateItem(String(tpl.template.id), String(item.item.id), { name: 'New Item' }) as any; + expect(result.item.name).toBe('New Item'); + }); + + it('ADMIN-SVC-062 — updateTemplateItem returns 404 for non-existent item', () => { + const result = svc.updateTemplateItem('1', '99999', { name: 'Ghost' }) as any; + expect(result.status).toBe(404); + }); + + it('ADMIN-SVC-063 — deleteTemplateItem removes item', () => { + const { user: admin } = createAdmin(testDb); + const tpl = svc.createPackingTemplate('Tpl', admin.id) as any; + const cat = svc.createTemplateCategory(String(tpl.template.id), 'Gear') as any; + const item = svc.createTemplateItem(String(tpl.template.id), String(cat.category.id), 'To Delete') as any; + const result = svc.deleteTemplateItem(String(tpl.template.id), String(item.item.id)) as any; + expect(result.error).toBeUndefined(); + const check = testDb.prepare('SELECT id FROM packing_template_items WHERE id = ?').get(item.item.id); + expect(check).toBeUndefined(); + }); + + it('ADMIN-SVC-064 — deleteTemplateItem returns 404 for non-existent item', () => { + const result = svc.deleteTemplateItem('1', '99999') as any; + expect(result.status).toBe(404); + }); +}); + +// ── Quirk fix landed after the 2026-08 admin fold ───────────────────────────── + +describe('Template item scoping (post-fold quirk fix)', () => { + it('ADMIN-SVC-076 — update/deleteTemplateItem honour :templateId instead of ignoring it', () => { + const { user: admin } = createAdmin(testDb); + const tplA = svc.createPackingTemplate('A', admin.id) as any; + const tplB = svc.createPackingTemplate('B', admin.id) as any; + const catA = svc.createTemplateCategory(String(tplA.template.id), 'Gear') as any; + const item = svc.createTemplateItem(String(tplA.template.id), String(catA.category.id), 'Tent') as any; + + // Template B does not own the item — both routes must 404 rather than act. + expect(svc.updateTemplateItem(String(tplB.template.id), String(item.item.id), { name: 'Hijacked' }) as any) + .toMatchObject({ status: 404 }); + expect(svc.deleteTemplateItem(String(tplB.template.id), String(item.item.id)) as any) + .toMatchObject({ status: 404 }); + expect((testDb.prepare('SELECT name FROM packing_template_items WHERE id = ?').get(item.item.id) as any).name) + .toBe('Tent'); + + // The owning template still works. + expect((svc.updateTemplateItem(String(tplA.template.id), String(item.item.id), { name: 'Tarp' }) as any).item.name) + .toBe('Tarp'); + expect(svc.deleteTemplateItem(String(tplA.template.id), String(item.item.id)) as any).toEqual({}); + }); +});