refactor(permissions): permission flags through AppSettingsRepository

This commit is contained in:
jubnl
2026-09-22 12:30:20 +02:00
parent f460ae4fcb
commit 7908914345
44 changed files with 233 additions and 155 deletions
@@ -1,15 +1,20 @@
import { Module } from '@nestjs/common';
import { MikroOrmModule } from '@mikro-orm/nestjs';
import { PermissionsService } from './permissions.service';
import { TripAccessGuard } from './trip-access.guard';
import { TripOwnerGuard } from './trip-owner.guard';
import { AppSettings } from '../../db/entities/AppSettings.entity';
/** Cross-cutting permissions domain (Wave 2). No controller/MCP surface of its
* own — the admin HTTP surface stays with AdminModule. Exports
* PermissionsService for the 17 in-container consumers and TripAccessGuard/TripOwnerGuard
* for every trip-scoped controller; deliberately NOT @Global so e2e TestingModules
* resolve it transitively through each consumer's explicit import. Registered in
* AppModule. */
* AppModule. MikroOrmModule.forFeature registers AppSettingsRepository for
* PermissionsService's @InjectRepository — the two guards keep DatabaseService's
* canAccessTrip (Plan 3c), unaffected by this. */
@Module({
imports: [MikroOrmModule.forFeature([AppSettings])],
providers: [PermissionsService, TripAccessGuard, TripOwnerGuard],
exports: [PermissionsService, TripAccessGuard, TripOwnerGuard],
})
@@ -1,7 +1,9 @@
import { Injectable } from '@nestjs/common';
import { DatabaseService } from '../database/database.service';
import { InjectRepository } from '@mikro-orm/nestjs';
import { UnitOfWork } from '../database/unit-of-work';
import { logError } from '../audit/audit-log.logger';
import { AppSettings } from '../../db/entities/AppSettings.entity';
import type { AppSettingsRepository } from '../../db/repositories/AppSettings.repository';
import {
getPermissionsCache,
setPermissionsCache,
@@ -75,7 +77,7 @@ const ACTIONS_MAP = new Map(PERMISSION_ACTIONS.map(a => [a.key, a]));
@Injectable()
export class PermissionsService {
constructor(
private readonly dbs: DatabaseService,
@InjectRepository(AppSettings) private readonly appSettings: AppSettingsRepository,
private readonly uow: UnitOfWork,
) {}
@@ -84,10 +86,9 @@ export class PermissionsService {
if (cached) return cached;
const cache = new Map<string, PermissionLevel>();
try {
const rows = this.dbs.all<{ key: string; value: string }>(
"SELECT key, value FROM app_settings WHERE key LIKE 'perm_%'"
);
const rows = await this.appSettings.findByKeyPrefix('perm_');
for (const row of rows) {
if (row.key == null || row.value == null) continue;
const actionKey = row.key.replace('perm_', '');
const action = ACTIONS_MAP.get(actionKey);
// Only cache values the action actually allows: a corrupt/empty stored
@@ -99,10 +100,15 @@ export class PermissionsService {
}
}
} catch (e) {
// Missing table is expected during first-boot init; anything else is a
// real DB failure that must not stay invisible (we still serve defaults).
// Under the legacy better-sqlite3 path a "no such table" error meant
// first-boot init racing this read, before the table existed, and was
// swallowed silently. Under the ORM, migrations run to completion in
// buildApp() before any request (or MCP/WS/cron entrypoint) can reach
// this service — there is no window left where app_settings can be
// missing — so that message match is dropped and every failure here is
// now a real, loggable DB error; defaults are still served either way.
const msg = e instanceof Error ? e.message : String(e);
if (!msg.includes('no such table')) logError(`Permissions load failed: ${msg}`);
logError(`Permissions load failed: ${msg}`);
// Serve defaults for THIS call, but do not install them: a half-built
// cache would freeze every later reader on the defaults until somebody
// invalidates by hand, which is how a stricter admin setting silently
@@ -147,10 +153,9 @@ export class PermissionsService {
}
// Nothing valid to write → no prepare, no transaction, no cache flush.
if (valid.length === 0) return { skipped };
const upsert = this.dbs.prepare('INSERT OR REPLACE INTO app_settings (key, value) VALUES (?, ?)');
await this.uow.transactional(async () => {
for (const [actionKey, level] of valid) {
upsert.run(`perm_${actionKey}`, level);
await this.appSettings.setValue(`perm_${actionKey}`, level);
}
});
this.invalidatePermissionsCache();
+2 -1
View File
@@ -47,6 +47,7 @@ import { ExchangeRatesService } from '../../src/nest/budget/exchange-rates.servi
import { TrekExceptionFilter } from '../../src/nest/common/trek-exception.filter';
import { ZodValidationPipe } from '../../src/nest/common/zod-validation.pipe';
import { TestUnitOfWorkModule } from '../helpers/test-uow';
import { createTestMikroOrmModule } from '../helpers/test-orm';
describe('Budget e2e (real auth guard + temp SQLite, real budget SQL)', () => {
let server: Server;
@@ -54,7 +55,7 @@ describe('Budget e2e (real auth guard + temp SQLite, real budget SQL)', () => {
let tripId: number;
async function build() {
const moduleRef = await Test.createTestingModule({ imports: [await TestUnitOfWorkModule.forRoot(db), DatabaseModule, RealtimeModule, BudgetModule] })
const moduleRef = await Test.createTestingModule({ imports: [await TestUnitOfWorkModule.forRoot(db), await createTestMikroOrmModule(db), DatabaseModule, RealtimeModule, BudgetModule] })
// The settlement read awaits live FX rates; the trip here is all-EUR, so a
// null result is the identity — and the test never touches the network.
.overrideProvider(ExchangeRatesService)
+2 -1
View File
@@ -38,6 +38,7 @@ import { RealtimeModule } from '../../src/nest/realtime/realtime.module';
import { TrekExceptionFilter } from '../../src/nest/common/trek-exception.filter';
import { ZodValidationPipe } from '../../src/nest/common/zod-validation.pipe';
import { TestUnitOfWorkModule } from '../helpers/test-uow';
import { createTestMikroOrmModule } from '../helpers/test-orm';
function insertCategory(name: string, color = '#6366f1', icon = '📍', userId = 1): number {
const res = db
@@ -54,7 +55,7 @@ describe('Categories e2e (real JwtAuthGuard + AdminGuard + temp SQLite)', () =>
// RealtimeModule is @Global in the app graph but not in a partial container,
// and CategoriesModule now pulls McpSharedModule in for the admin tools, whose
// guard service takes it. days.e2e.test.ts imports it for the same reason.
const moduleRef = await Test.createTestingModule({ imports: [await TestUnitOfWorkModule.forRoot(db), DatabaseModule, RealtimeModule, CategoriesModule] }).compile();
const moduleRef = await Test.createTestingModule({ imports: [await TestUnitOfWorkModule.forRoot(db), await createTestMikroOrmModule(db), DatabaseModule, RealtimeModule, CategoriesModule] }).compile();
const nest = moduleRef.createNestApplication();
nest.use(cookieParser());
nest.useGlobalFilters(new TrekExceptionFilter());
+2 -1
View File
@@ -126,6 +126,7 @@ import { RealtimeModule } from '../../src/nest/realtime/realtime.module';
import { TrekExceptionFilter } from '../../src/nest/common/trek-exception.filter';
import { ZodValidationPipe } from '../../src/nest/common/zod-validation.pipe';
import { TestUnitOfWorkModule } from '../helpers/test-uow';
import { createTestMikroOrmModule } from '../helpers/test-orm';
function insertItem(tripId: number, name: string, extra: Partial<{ sort_order: number; category: string; is_private: number; owner_id: number }> = {}): number {
const res = db
@@ -140,7 +141,7 @@ describe('Packing e2e (real auth guard + real SQL over temp SQLite)', () => {
let tripId: number;
async function build() {
const moduleRef = await Test.createTestingModule({ imports: [await TestUnitOfWorkModule.forRoot(db), DatabaseModule, RealtimeModule, PackingModule] }).compile();
const moduleRef = await Test.createTestingModule({ imports: [await TestUnitOfWorkModule.forRoot(db), await createTestMikroOrmModule(db), DatabaseModule, RealtimeModule, PackingModule] }).compile();
const nest = moduleRef.createNestApplication();
nest.use(cookieParser());
nest.useGlobalFilters(new TrekExceptionFilter());
+2 -1
View File
@@ -23,6 +23,7 @@ import { validateBodyContracts } from '../../src/nest/common/validate-body-contr
import { createTestRegistry } from '../../src/nest-mcp';
import { trekMcpAccessPolicy, trekMcpValidateAccess } from '../../src/mcp/nest-mcp-policy';
import { TestUnitOfWorkModule } from '../helpers/test-uow';
import { createTestMikroOrmModule } from '../helpers/test-orm';
const base = '/api/school-holiday-catalog';
const winter = { name: 'Winter break', startDate: '2026-12-20', endDate: '2027-01-06' };
@@ -33,7 +34,7 @@ beforeAll(async () => {
createTables(db);
runMigrations(db);
db.prepare("INSERT INTO users (id, username, email, password_hash, role) VALUES (1, 'admin', 'admin@test.local', '', 'admin'), (2, 'member', 'member@test.local', '', 'user')").run();
const module = await Test.createTestingModule({ imports: [await TestUnitOfWorkModule.forRoot(db), DatabaseModule, RealtimeModule, SchoolHolidaysModule] }).compile();
const module = await Test.createTestingModule({ imports: [await TestUnitOfWorkModule.forRoot(db), await createTestMikroOrmModule(db), DatabaseModule, RealtimeModule, SchoolHolidaysModule] }).compile();
app = module.createNestApplication();
app.use(cookieParser());
app.useGlobalPipes(new ZodValidationPipe());
+2 -1
View File
@@ -78,6 +78,7 @@ import { RealtimeModule } from '../../src/nest/realtime/realtime.module';
import { TrekExceptionFilter } from '../../src/nest/common/trek-exception.filter';
import { ZodValidationPipe } from '../../src/nest/common/zod-validation.pipe';
import { TestUnitOfWorkModule } from '../helpers/test-uow';
import { createTestMikroOrmModule } from '../helpers/test-orm';
function insertItem(tripId: number, name: string, extra: Partial<{ sort_order: number; due_date: string }> = {}): number {
const res = db
@@ -92,7 +93,7 @@ describe('To-do e2e (real auth guard + real SQL over temp SQLite)', () => {
let tripId: number;
async function build() {
const moduleRef = await Test.createTestingModule({ imports: [await TestUnitOfWorkModule.forRoot(db), DatabaseModule, RealtimeModule, TodoModule] }).compile();
const moduleRef = await Test.createTestingModule({ imports: [await TestUnitOfWorkModule.forRoot(db), await createTestMikroOrmModule(db), DatabaseModule, RealtimeModule, TodoModule] }).compile();
const nest = moduleRef.createNestApplication();
nest.use(cookieParser());
nest.useGlobalFilters(new TrekExceptionFilter());
+2 -1
View File
@@ -63,13 +63,14 @@ import { TripMembershipService } from '../../src/nest/trip-membership/trip-membe
import { TrekExceptionFilter } from '../../src/nest/common/trek-exception.filter';
import { ZodValidationPipe } from '../../src/nest/common/zod-validation.pipe';
import { TestUnitOfWorkModule } from '../helpers/test-uow';
import { createTestMikroOrmModule } from '../helpers/test-orm';
describe('Trip invite-link e2e (real auth guard + temp SQLite)', () => {
let server: Server;
let app: Awaited<ReturnType<typeof build>>;
async function build() {
const moduleRef = await Test.createTestingModule({ imports: [await TestUnitOfWorkModule.forRoot(db), DatabaseModule, TripInviteModule] })
const moduleRef = await Test.createTestingModule({ imports: [await TestUnitOfWorkModule.forRoot(db), await createTestMikroOrmModule(db), DatabaseModule, TripInviteModule] })
.overrideProvider(TripMembershipService).useValue({ joinTripAsMember })
.compile();
const nest = moduleRef.createNestApplication();
@@ -7,7 +7,7 @@ import { PermissionsService } from '../../src/nest/permissions/permissions.servi
import { QueryHelpersService } from '../../src/nest/query-helpers/query-helpers.service';
import { RealtimeService } from '../../src/nest/realtime/realtime.service';
import { TrekPhotosRepository } from '../../src/nest/photos/trek-photos.repository';
import { createTestUnitOfWork } from './test-uow';
import { createTestUnitOfWork, createTestAppSettingsRepo } from './test-uow';
/**
* AccommodationsService over a test connection.
@@ -29,7 +29,7 @@ export async function makeAccommodationsService(conn: Database): Promise<Accommo
* that service by hand needs one to hand it.
*/
export async function accommodationsOver(dbs: DatabaseService): Promise<AccommodationsService> {
const permissions = new PermissionsService(dbs, await createTestUnitOfWork(dbs.connection));
const permissions = new PermissionsService(await createTestAppSettingsRepo(dbs.connection), await createTestUnitOfWork(dbs.connection));
const realtime = new RealtimeService();
const assignments = new AssignmentsService(
dbs, permissions, realtime,
+13 -6
View File
@@ -114,10 +114,14 @@ import { AirtrailImportService } from '../../src/nest/integrations/airtrail-impo
import { ReservationImportMcp } from '../../src/nest/reservation-import/reservation-import.mcp';
import { HelpMcp } from '../../src/nest/help/help.mcp';
import { AddonsMcp } from '../../src/nest/addons/addons.mcp';
import { createTestUnitOfWork } from './test-uow';
import { createTestUnitOfWork, createTestAppSettingsRepo } from './test-uow';
import { createTestOrm } from './test-orm';
import { AppSettings } from '../../src/db/entities/AppSettings.entity';
import type { AppSettingsRepository } from '../../src/db/repositories/AppSettings.repository';
import { AuditLog } from '../../src/db/entities/AuditLog.entity';
import type { AuditLogRepository } from '../../src/db/repositories/AuditLog.repository';
import { Users } from '../../src/db/entities/Users.entity';
import type { UsersRepository } from '../../src/db/repositories/Users.repository';
/**
* Hand-wired counterpart of the boot-time discovery in McpRegistryService,
@@ -130,7 +134,10 @@ export async function createMcpTestRegistry(): Promise<McpRegistry> {
const dbService = new DatabaseService(db);
const generalStorage = makeStorageFixture('').storage;
const appSettings = (await createTestOrm(dbService.connection)).repo(AppSettings) as AppSettingsRepository;
const permissionsService = new PermissionsService(dbService, await createTestUnitOfWork(dbService.connection));
const mcpOrm = await createTestOrm(dbService.connection);
const auditLogRepo = mcpOrm.repo(AuditLog) as AuditLogRepository;
const usersRepo = mcpOrm.repo(Users) as UsersRepository;
const permissionsService = new PermissionsService(await createTestAppSettingsRepo(dbService.connection), await createTestUnitOfWork(dbService.connection));
// Same argument list as auth.bridge.ts. AtlasService used to sit in third
// place; when getTravelStats moved onto AtlasService itself the edge was
// dropped and four collaborators took its place, but this call site kept the
@@ -209,7 +216,7 @@ export async function createMcpTestRegistry(): Promise<McpRegistry> {
// (which asks them when and where it was taken). Built for real rather than
// stubbed: an empty provider registry would make the backfill answer "unknown
// provider" for every id and hide a wiring mistake behind a caught error.
const immichService = new ImmichService(dbService, new AuditService(dbService), new MemoriesAccessService(dbService), generalStorage);
const immichService = new ImmichService(dbService, new AuditService(auditLogRepo, usersRepo), new MemoriesAccessService(dbService), generalStorage);
const synologyService = new SynologyService(dbService, new MemoriesAccessService(dbService), notificationsStub());
const trekPhotos = new TrekPhotosRepository(dbService);
const captureBackfill = new PhotoCaptureBackfillService(new PhotoResolverService(trekPhotos, new ThumbnailService(addonsService, generalStorage, dbService), new TrekPhotoCacheService(dbService, generalStorage), new PhotoProviderRegistry([new ImmichPhotoProvider(immichService), new SynologyPhotoProvider(synologyService)]), generalStorage), trekPhotos, generalStorage);
@@ -238,7 +245,7 @@ export async function createMcpTestRegistry(): Promise<McpRegistry> {
new TripPromptsMcp(tripsService, readModelService, packingService, addonsService),
new ShareMcp(new ShareService(dbService, new SettingsService(dbService, await createTestUnitOfWork(dbService.connection), appSettings), permissionsService, queryHelpersService, placePhotoCache, await createTestUnitOfWork(dbService.connection)), authService, guards),
new FeedsMcp(new FeedsService(dbService, calendarService), dbService, new RuntimeEnvService(), guards),
new TripInviteMcp(new TripInviteService(dbService, permissionsService, new TripMembershipService(dbService), await createTestUnitOfWork(dbService.connection)), dbService, new RuntimeEnvService(), guards, new AuditService(dbService)),
new TripInviteMcp(new TripInviteService(dbService, permissionsService, new TripMembershipService(dbService), await createTestUnitOfWork(dbService.connection)), dbService, new RuntimeEnvService(), guards, new AuditService(auditLogRepo, usersRepo)),
new MapsMcp(mapsService),
new PlacesMcp(placesService, mapsService, dbService, authService, journeyDomain, assignmentsService, guards, await createTestUnitOfWork(dbService.connection)),
new CollectionsMcp(new CollectionsService(dbService, permissionsService, realtimeService, notificationsStub(), generalStorage, await createTestUnitOfWork(dbService.connection)), dbService, authService, addonsService),
@@ -247,8 +254,8 @@ export async function createMcpTestRegistry(): Promise<McpRegistry> {
new JourneyMcp(journeyDomain, new JourneyShareService(dbService, journeyDomain, new SettingsService(dbService, await createTestUnitOfWork(dbService.connection), appSettings)), addonsService, authService, captureBackfill),
new MemoriesMcp(immichService, synologyService, dbService, addonsService),
new NotificationsMcp(await makeNotificationsService(dbService, realtimeService), authService),
new AirtrailMcp(new AirtrailService(dbService, new AuditService(dbService), new AirtrailClient()), addonsService),
new ReservationImportMcp(new AirtrailImportService(dbService, realtimeService, reservationsService, new AirtrailClient(), new AirtrailService(dbService, new AuditService(dbService), new AirtrailClient())), dbService, authService, guards, addonsService),
new AirtrailMcp(new AirtrailService(dbService, new AuditService(auditLogRepo, usersRepo), new AirtrailClient()), addonsService),
new ReservationImportMcp(new AirtrailImportService(dbService, realtimeService, reservationsService, new AirtrailClient(), new AirtrailService(dbService, new AuditService(auditLogRepo, usersRepo), new AirtrailClient())), dbService, authService, guards, addonsService),
new SettingsMcp(new SettingsService(dbService, await createTestUnitOfWork(dbService.connection), appSettings), authService),
new HelpMcp(), new AddonsMcp(addonsService),
new TripWarningsMcp(new PluginHooks({ providersOf: () => [], invokeHook: async () => [] } as unknown as PluginRuntimeService), dbService),
+8 -3
View File
@@ -72,10 +72,14 @@ import { PlacePhotoCacheService } from '../../src/nest/place-photos/place-photo-
import { TrekPhotosRepository } from '../../src/nest/photos/trek-photos.repository';
import { RuntimeEnvService } from '../../src/nest/app-config/runtime-env.service';
import { makeStorageFixture } from './storage-fixture';
import { createTestUnitOfWork } from './test-uow';
import { createTestUnitOfWork, createTestAppSettingsRepo } from './test-uow';
import { createTestOrm } from './test-orm';
import { AppSettings } from '../../src/db/entities/AppSettings.entity';
import type { AppSettingsRepository } from '../../src/db/repositories/AppSettings.repository';
import { AuditLog } from '../../src/db/entities/AuditLog.entity';
import type { AuditLogRepository } from '../../src/db/repositories/AuditLog.repository';
import { Users } from '../../src/db/entities/Users.entity';
import type { UsersRepository } from '../../src/db/repositories/Users.repository';
/**
* Hand-wired counterpart of the PluginsModule DI graph for no-Nest tests
@@ -90,7 +94,7 @@ import type { AppSettingsRepository } from '../../src/db/repositories/AppSetting
export async function createPluginRpcHostFactory(dbs: DatabaseService): Promise<PluginRpcHostFactory> {
const generalStorage = makeStorageFixture('').storage;
const appSettings = (await createTestOrm(dbs.connection)).repo(AppSettings) as AppSettingsRepository;
const permissions = new PermissionsService(dbs, await createTestUnitOfWork(dbs.connection));
const permissions = new PermissionsService(await createTestAppSettingsRepo(dbs.connection), await createTestUnitOfWork(dbs.connection));
const exchangeRates = new ExchangeRatesService();
const realtime = new RealtimeService();
const budget = new BudgetService(dbs, permissions, exchangeRates, realtime, await createTestUnitOfWork(dbs.connection));
@@ -155,9 +159,10 @@ export async function createPluginRpcHostFactory(dbs: DatabaseService): Promise<
/** A PluginRuntimeService constructed the way Nest would: with a real host factory. */
export async function createPluginRuntime(dbs: DatabaseService, registry?: PluginRegistryService): Promise<PluginRuntimeService> {
const orm = await createTestOrm(dbs.connection);
return new PluginRuntimeService(
dbs,
new AuditService(dbs),
new AuditService(orm.repo(AuditLog) as AuditLogRepository, orm.repo(Users) as UsersRepository),
new AddonsService(dbs),
new PluginUserSettingsService(dbs),
registry,
+20
View File
@@ -2,8 +2,11 @@ import { Module, type DynamicModule } from '@nestjs/common';
import type Database from 'better-sqlite3';
import { UnitOfWork } from '../../src/nest/database/unit-of-work';
import { createTestOrm } from './test-orm';
import { AppSettings } from '../../src/db/entities/AppSettings.entity';
import type { AppSettingsRepository } from '../../src/db/repositories/AppSettings.repository';
const perHandle = new WeakMap<Database.Database, Promise<UnitOfWork>>();
const appSettingsPerHandle = new WeakMap<Database.Database, Promise<AppSettingsRepository>>();
/**
* The `UnitOfWork` a hand-constructed service needs, bound to the suite's own
@@ -24,6 +27,23 @@ export function createTestUnitOfWork(db: Database.Database): Promise<UnitOfWork>
return pending;
}
/**
* The `AppSettingsRepository` a hand-constructed service needs (`PermissionsService`,
* mirroring `SettingsService`'s own `t.repo(AppSettings)` in its unit test), bound to
* the suite's own better-sqlite3 handle the same way `createTestUnitOfWork` is.
*
* Memoised per handle for the same reason: many suites build several services (and
* `PermissionsService` specifically, being 20+ domains' guard dependency) off the
* same test DB, and each would otherwise open its own `MikroORM.init`.
*/
export function createTestAppSettingsRepo(db: Database.Database): Promise<AppSettingsRepository> {
const existing = appSettingsPerHandle.get(db);
if (existing !== undefined) return existing;
const pending = createTestOrm(db).then((t) => t.repo(AppSettings) as AppSettingsRepository);
appSettingsPerHandle.set(db, pending);
return pending;
}
/**
* The same `UnitOfWork`, as a **global** Nest module.
*
+2 -2
View File
@@ -25,11 +25,11 @@ import { PermissionsService } from '../../src/nest/permissions/permissions.servi
import { DaysService, DayReorderError } from '../../src/nest/days/days.service';
import { RealtimeService } from '../../src/nest/realtime/realtime.service';
import { QueryHelpersService } from '../../src/nest/query-helpers/query-helpers.service';
import { createTestUnitOfWork } from '../helpers/test-uow';
import { createTestUnitOfWork, createTestAppSettingsRepo } from '../helpers/test-uow';
let svc: DaysService;
beforeAll(async () => {
svc = new DaysService(new DatabaseService(testDb), new PermissionsService(new DatabaseService(testDb), await createTestUnitOfWork(testDb)), new RealtimeService(), new QueryHelpersService(new DatabaseService(testDb)), await createTestUnitOfWork(testDb));
svc = new DaysService(new DatabaseService(testDb), new PermissionsService(await createTestAppSettingsRepo(testDb), await createTestUnitOfWork(testDb)), new RealtimeService(), new QueryHelpersService(new DatabaseService(testDb)), await createTestUnitOfWork(testDb));
});
const reorderDays = async (tripId: number, orderedIds: number[]) => await svc.reorder(tripId, orderedIds);
const insertDay = async (tripId: number, position?: number) => await svc.insert(tripId, position);
+2 -2
View File
@@ -49,7 +49,7 @@ import { AirtrailClient, AirtrailRequestError, type AirtrailFlightRaw } from '..
import { AirtrailImportService } from '../../../src/nest/integrations/airtrail-import.service';
import { PermissionsService } from '../../../src/nest/permissions/permissions.service';
import { DatabaseService } from '../../../src/nest/database/database.service';
import { createTestUnitOfWork } from '../../helpers/test-uow';
import { createTestUnitOfWork, createTestAppSettingsRepo } from '../../helpers/test-uow';
// The permissions cache is module-scoped, so a write through any instance is
// what the tool's own checkPermission call reads back.
@@ -57,7 +57,7 @@ import { createTestUnitOfWork } from '../../helpers/test-uow';
let permissionsService: PermissionsService;
let savePermissions: typeof permissionsService.savePermissions;
beforeAll(async () => {
permissionsService = new PermissionsService(new DatabaseService(testDb), await createTestUnitOfWork(testDb));
permissionsService = new PermissionsService(await createTestAppSettingsRepo(testDb), await createTestUnitOfWork(testDb));
savePermissions = permissionsService.savePermissions.bind(permissionsService);
});
@@ -47,7 +47,7 @@ import { PermissionsService } from '../../../src/nest/permissions/permissions.se
import { RealtimeService } from '../../../src/nest/realtime/realtime.service';
import type { TripAccess } from '../../../src/nest/database/database.service';
import type { User } from '../../../src/types';
import { createTestUnitOfWork } from '../../helpers/test-uow';
import { createTestUnitOfWork, createTestAppSettingsRepo } from '../../helpers/test-uow';
beforeAll(() => {
createTables(testDb);
@@ -357,7 +357,7 @@ describe('Settlement tools', () => {
const dbService = new DatabaseService(testDb);
const controller = new BudgetController(
new BudgetService(dbService, new PermissionsService(dbService, await createTestUnitOfWork(dbService.connection)), new ExchangeRatesService(), new RealtimeService(), await createTestUnitOfWork(dbService.connection)),
new BudgetService(dbService, new PermissionsService(await createTestAppSettingsRepo(dbService.connection), await createTestUnitOfWork(dbService.connection)), new ExchangeRatesService(), new RealtimeService(), await createTestUnitOfWork(dbService.connection)),
);
const rest = await controller.settlement(
{ id: user.id } as User,
@@ -50,7 +50,7 @@ import { RuntimeEnvService } from '../../../src/nest/app-config/runtime-env.serv
import { PermissionsService } from '../../../src/nest/permissions/permissions.service';
import { RealtimeService } from '../../../src/nest/realtime/realtime.service';
import { McpToolGuardsService } from '../../../src/nest/mcp-shared/mcp-tool-guards.service';
import { createTestUnitOfWork } from '../../helpers/test-uow';
import { createTestUnitOfWork, createTestAppSettingsRepo } from '../../helpers/test-uow';
beforeAll(() => {
createTables(testDb);
@@ -86,7 +86,7 @@ beforeAll(async () => {
new CategoriesService(categoriesDb),
categoriesDb,
new RuntimeEnvService(),
new McpToolGuardsService(categoriesDb, new PermissionsService(categoriesDb, await createTestUnitOfWork(categoriesDb.connection)), new RealtimeService()),
new McpToolGuardsService(categoriesDb, new PermissionsService(await createTestAppSettingsRepo(categoriesDb.connection), await createTestUnitOfWork(categoriesDb.connection)), new RealtimeService()),
);
});
+4 -4
View File
@@ -87,7 +87,7 @@ import type { TodoService } from '../../../src/nest/todo/todo.service';
import type { CollabService } from '../../../src/nest/collab/collab.service';
import { AddonsService } from '../../../src/nest/addons/addons.service';
import { notificationsStub } from '../../helpers/notifications';
import { createTestUnitOfWork } from '../../helpers/test-uow';
import { createTestUnitOfWork, createTestAppSettingsRepo } from '../../helpers/test-uow';
// The trip-summary prompt moved to the DI-discovered TripsMcp — its cases below
// exercise it through a hand-built registry over a stub TripsService whose
@@ -120,7 +120,7 @@ let packingMcp: PackingMcp;
let budgetMcp: BudgetMcp;
let tripPromptsMcp: TripPromptsMcp;
beforeAll(async () => {
promptGuards = new McpToolGuardsService(new DatabaseService(testDb), new PermissionsService(new DatabaseService(testDb), await createTestUnitOfWork(testDb)), new RealtimeService());
promptGuards = new McpToolGuardsService(new DatabaseService(testDb), new PermissionsService(await createTestAppSettingsRepo(testDb), await createTestUnitOfWork(testDb)), new RealtimeService());
tripsMcp = new TripsMcp(
tripsStub,
{ listItems: () => [] } as unknown as TodoService,
@@ -132,10 +132,10 @@ beforeAll(async () => {
addonsStub,
promptGuards,
);
promptPackingService = new PackingService(promptDbs(), new PermissionsService(promptDbs(), await createTestUnitOfWork(promptDbs().connection)), new RealtimeService(), notificationsStub(), await createTestUnitOfWork(promptDbs().connection));
promptPackingService = new PackingService(promptDbs(), new PermissionsService(await createTestAppSettingsRepo(promptDbs().connection), await createTestUnitOfWork(promptDbs().connection)), new RealtimeService(), notificationsStub(), await createTestUnitOfWork(promptDbs().connection));
packingMcp = new PackingMcp(promptPackingService, authStub, addonsStub, promptGuards);
budgetMcp = new BudgetMcp(
new BudgetService(promptDbs(), new PermissionsService(promptDbs(), await createTestUnitOfWork(promptDbs().connection)), new ExchangeRatesService(), new RealtimeService(), await createTestUnitOfWork(promptDbs().connection)),
new BudgetService(promptDbs(), new PermissionsService(await createTestAppSettingsRepo(promptDbs().connection), await createTestUnitOfWork(promptDbs().connection)), new ExchangeRatesService(), new RealtimeService(), await createTestUnitOfWork(promptDbs().connection)),
new ExchangeRatesService(),
promptDbs(),
new RuntimeEnvService(),
+2 -2
View File
@@ -48,13 +48,13 @@ import { addTripMember } from '../../helpers/factories';
import { PermissionsService } from '../../../src/nest/permissions/permissions.service';
import { DatabaseService } from '../../../src/nest/database/database.service';
import { DEMO_EMAIL_PRIMARY } from '../../../src/nest/common/demo';
import { createTestUnitOfWork } from '../../helpers/test-uow';
import { createTestUnitOfWork, createTestAppSettingsRepo } from '../../helpers/test-uow';
// The permissions cache is module-scoped, so a write through any instance is
// what the tool's own check reads back.
let savePermissions: PermissionsService['savePermissions'];
beforeAll(async () => {
const permissionsService = new PermissionsService(new DatabaseService(testDb), await createTestUnitOfWork(testDb));
const permissionsService = new PermissionsService(await createTestAppSettingsRepo(testDb), await createTestUnitOfWork(testDb));
savePermissions = permissionsService.savePermissions.bind(permissionsService);
});
+2 -2
View File
@@ -45,7 +45,7 @@ vi.mock('../../../src/config', () => ({
import { ReservationsService } from '../../../src/nest/reservations/reservations.service';
import type { TransitPlace } from '../../../src/nest/transit/transit.helpers';
import { TransitService } from '../../../src/nest/transit/transit.service';
import { createTestUnitOfWork } from '../../helpers/test-uow';
import { createTestUnitOfWork, createTestAppSettingsRepo } from '../../helpers/test-uow';
// savePermissions is no longer bridged; write through a service instance — the
// permissions cache is module-scoped, so the MCP _shared checkPermission path
@@ -54,7 +54,7 @@ import { createTestUnitOfWork } from '../../helpers/test-uow';
let permissionsService: PermissionsService;
let savePermissions: typeof permissionsService.savePermissions;
beforeAll(async () => {
permissionsService = new PermissionsService(new DatabaseService(testDb), await createTestUnitOfWork(testDb));
permissionsService = new PermissionsService(await createTestAppSettingsRepo(testDb), await createTestUnitOfWork(testDb));
savePermissions = permissionsService.savePermissions.bind(permissionsService);
});
@@ -49,7 +49,7 @@ import { AccommodationsModule } from '../../../src/nest/accommodations/accommoda
import { AccommodationsDomainModule } from '../../../src/nest/accommodations/accommodations-domain.module';
import { AccommodationsController } from '../../../src/nest/accommodations/accommodations.controller';
import { expectRegisteredProvider, expectRegisteredController } from '../../helpers/module-providers';
import { createTestUnitOfWork } from '../../helpers/test-uow';
import { createTestUnitOfWork, createTestAppSettingsRepo } from '../../helpers/test-uow';
// Named `svc` so the moved cases read exactly as they did on DaysService.
let svc: Awaited<ReturnType<typeof makeAccommodationsService>>;
@@ -558,7 +558,7 @@ describe('trip access and edit permission', () => {
const { user: member } = createUser(testDb);
const trip = createTrip(testDb, owner.id);
addTripMember(testDb, trip.id, member.id);
const permissions = new PermissionsService(new DatabaseService(testDb), await createTestUnitOfWork(testDb));
const permissions = new PermissionsService(await createTestAppSettingsRepo(testDb), await createTestUnitOfWork(testDb));
try {
await permissions.savePermissions({ day_edit: 'trip_owner' });
+2 -2
View File
@@ -82,7 +82,7 @@ import { __clearVersionCacheForTests } from '../../../src/nest/admin/admin.helpe
import { makeNotificationsService, makeNotificationPreferencesService } from '../../helpers/notifications';
import { EphemeralTokenService } from '../../../src/nest/auth/ephemeral-token.service';
import { AllowedFileTypesService } from '../../../src/nest/files/allowed-file-types.service';
import { createTestUnitOfWork } from '../../helpers/test-uow';
import { createTestUnitOfWork, createTestAppSettingsRepo } from '../../helpers/test-uow';
const dbs = new DatabaseService(testDb);
const realtime = new RealtimeService();
@@ -99,7 +99,7 @@ let userCleanup: UserCleanupService;
let auth: AuthService;
let svc: AdminService;
beforeAll(async () => {
permissions = new PermissionsService(dbs, await createTestUnitOfWork(dbs.connection));
permissions = new PermissionsService(await createTestAppSettingsRepo(dbs.connection), await createTestUnitOfWork(dbs.connection));
userCleanup = new UserCleanupService(dbs, new BudgetService(dbs, permissions, new ExchangeRatesService(), realtime, await createTestUnitOfWork(dbs.connection)), await createTestUnitOfWork(dbs.connection));
auth = new AuthService(dbs, permissions, new TripMembershipService(dbs), webauthn, userCleanup, new MailerService(dbs), new EphemeralTokenService(), new AllowedFileTypesService(dbs), await createTestUnitOfWork(dbs.connection));
svc = new AdminService(
@@ -60,7 +60,7 @@ import { AdminService } from '../../../src/nest/admin/admin.service';
import { makeNotificationsService, makeNotificationPreferencesService } from '../../helpers/notifications';
import { EphemeralTokenService } from '../../../src/nest/auth/ephemeral-token.service';
import { AllowedFileTypesService } from '../../../src/nest/files/allowed-file-types.service';
import { createTestUnitOfWork } from '../../helpers/test-uow';
import { createTestUnitOfWork, createTestAppSettingsRepo } from '../../helpers/test-uow';
const dbs = new DatabaseService(testDb);
const realtime = new RealtimeService();
@@ -77,7 +77,7 @@ let userCleanup: UserCleanupService;
let auth: AuthService;
let svc: AdminService;
beforeAll(async () => {
permissions = new PermissionsService(dbs, await createTestUnitOfWork(dbs.connection));
permissions = new PermissionsService(await createTestAppSettingsRepo(dbs.connection), await createTestUnitOfWork(dbs.connection));
userCleanup = new UserCleanupService(dbs, new BudgetService(dbs, permissions, new ExchangeRatesService(), realtime, await createTestUnitOfWork(dbs.connection)), await createTestUnitOfWork(dbs.connection));
auth = new AuthService(dbs, permissions, new TripMembershipService(dbs), webauthn, userCleanup, new MailerService(dbs), new EphemeralTokenService(), new AllowedFileTypesService(dbs), await createTestUnitOfWork(dbs.connection));
svc = new AdminService(
@@ -55,7 +55,7 @@ import { RealtimeService } from '../../../src/nest/realtime/realtime.service';
import { QueryHelpersService } from '../../../src/nest/query-helpers/query-helpers.service';
import { JourneyDomainService } from '../../../src/nest/journey/journey-domain.service';
import { TrekPhotosRepository } from '../../../src/nest/photos/trek-photos.repository';
import { createTestUnitOfWork } from '../../helpers/test-uow';
import { createTestUnitOfWork, createTestAppSettingsRepo } from '../../helpers/test-uow';
const dbs = new DatabaseService(testDb);
const realtime = new RealtimeService();
@@ -63,7 +63,7 @@ let svc: AssignmentsService;
beforeAll(async () => {
svc = new AssignmentsService(
dbs,
new PermissionsService(dbs, await createTestUnitOfWork(dbs.connection)),
new PermissionsService(await createTestAppSettingsRepo(dbs.connection), await createTestUnitOfWork(dbs.connection)),
realtime,
new QueryHelpersService(dbs),
// Real collaborator rather than a stub: reconcile() runs after every mutation
+3 -3
View File
@@ -84,7 +84,7 @@ import { MailerService } from '../../../src/nest/notifications/mailer/mailer.ser
import { EphemeralTokenService } from '../../../src/nest/auth/ephemeral-token.service';
import { AllowedFileTypesService } from '../../../src/nest/files/allowed-file-types.service';
import { DEFAULT_ALLOWED_EXTENSIONS } from '../../../src/nest/files/files.constants';
import { createTestUnitOfWork } from '../../helpers/test-uow';
import { createTestUnitOfWork, createTestAppSettingsRepo } from '../../helpers/test-uow';
// MailerService is injected since the notifications fold — a stub instead of a
// module mock. sendPasswordResetEmail is the only thing auth reaches for.
@@ -102,10 +102,10 @@ let svc: AuthService;
beforeAll(async () => {
svc = new AuthService(
new DatabaseService(testDb),
new PermissionsService(new DatabaseService(testDb), await createTestUnitOfWork(testDb)),
new PermissionsService(await createTestAppSettingsRepo(testDb), await createTestUnitOfWork(testDb)),
membershipStub,
new WebauthnConfigService(new DatabaseService(testDb)),
new UserCleanupService(new DatabaseService(testDb), new BudgetService(new DatabaseService(testDb), new PermissionsService(new DatabaseService(testDb), await createTestUnitOfWork(testDb)), new ExchangeRatesService(), new RealtimeService(), await createTestUnitOfWork(testDb)), await createTestUnitOfWork(testDb)),
new UserCleanupService(new DatabaseService(testDb), new BudgetService(new DatabaseService(testDb), new PermissionsService(await createTestAppSettingsRepo(testDb), await createTestUnitOfWork(testDb)), new ExchangeRatesService(), new RealtimeService(), await createTestUnitOfWork(testDb)), await createTestUnitOfWork(testDb)),
mailerStub,
new EphemeralTokenService(),
new AllowedFileTypesService(new DatabaseService(testDb)), await createTestUnitOfWork(testDb),
@@ -72,7 +72,7 @@ import { CollabService } from '../../../src/nest/collab/collab.service';
import { VacayService } from '../../../src/nest/vacay/vacay.service';
import { QueryHelpersService } from '../../../src/nest/query-helpers/query-helpers.service';
import { notificationsStub } from '../../helpers/notifications';
import { createTestUnitOfWork } from '../../helpers/test-uow';
import { createTestUnitOfWork, createTestAppSettingsRepo } from '../../helpers/test-uow';
@@ -90,7 +90,7 @@ let deleteGuest: typeof membersSvc.deleteGuest;
beforeAll(async () => {
budget = new BudgetService(
new DatabaseService(testDb),
new PermissionsService(new DatabaseService(testDb), await createTestUnitOfWork(testDb)),
new PermissionsService(await createTestAppSettingsRepo(testDb), await createTestUnitOfWork(testDb)),
new ExchangeRatesService(),
new RealtimeService(),
await createTestUnitOfWork(testDb),
@@ -99,7 +99,7 @@ beforeAll(async () => {
dbs(),
budget,
new UserCleanupService(dbs(), budget, await createTestUnitOfWork(testDb)),
new PermissionsService(dbs(), await createTestUnitOfWork(dbs().connection)),
new PermissionsService(await createTestAppSettingsRepo(dbs().connection), await createTestUnitOfWork(dbs().connection)),
new RealtimeService(),
notificationsStub(),
await createTestUnitOfWork(testDb),
@@ -57,7 +57,7 @@ import { CalendarModule } from '../../../src/nest/calendar/calendar.module';
import { expectRegisteredProvider } from '../../helpers/module-providers';
import { notificationsStub } from '../../helpers/notifications';
import { accommodationsOver } from '../../helpers/accommodations-service';
import { createTestUnitOfWork } from '../../helpers/test-uow';
import { createTestUnitOfWork, createTestAppSettingsRepo } from '../../helpers/test-uow';
const dbs = () => new DatabaseService(testDb);
@@ -66,10 +66,10 @@ const dbs = () => new DatabaseService(testDb);
let budgetSvc: BudgetService;
let svc: CalendarService;
beforeAll(async () => {
budgetSvc = new BudgetService(dbs(), new PermissionsService(dbs(), await createTestUnitOfWork(dbs().connection)), new ExchangeRatesService(), new RealtimeService(), await createTestUnitOfWork(dbs().connection));
budgetSvc = new BudgetService(dbs(), new PermissionsService(await createTestAppSettingsRepo(dbs().connection), await createTestUnitOfWork(dbs().connection)), new ExchangeRatesService(), new RealtimeService(), await createTestUnitOfWork(dbs().connection));
svc = new CalendarService(
dbs(),
new ReservationsService(dbs(), new PermissionsService(dbs(), await createTestUnitOfWork(dbs().connection)), budgetSvc, new RealtimeService(), notificationsStub(), new ReservationsReadRepository(dbs()), await accommodationsOver(dbs()), await createTestUnitOfWork(dbs().connection)),
new ReservationsService(dbs(), new PermissionsService(await createTestAppSettingsRepo(dbs().connection), await createTestUnitOfWork(dbs().connection)), budgetSvc, new RealtimeService(), notificationsStub(), new ReservationsReadRepository(dbs()), await accommodationsOver(dbs()), await createTestUnitOfWork(dbs().connection)),
);
});
@@ -87,17 +87,17 @@ import { RealtimeService } from '../../../src/nest/realtime/realtime.service';
import { notificationsStub } from '../../helpers/notifications';
import { makeStorageFixture } from '../../helpers/storage-fixture';
import { RateLimitService } from '../../../src/nest/common/rate-limit.service';
import { createTestUnitOfWork } from '../../helpers/test-uow';
import { createTestUnitOfWork, createTestAppSettingsRepo } from '../../helpers/test-uow';
const collabFx = makeStorageFixture('files/');
const rateLimit = new RateLimitService();
let svc: CollabService;
beforeAll(async () => {
svc = new CollabService(new DatabaseService(testDb), new PermissionsService(new DatabaseService(testDb), await createTestUnitOfWork(testDb)), new RealtimeService(), notificationsStub(), collabFx.storage, rateLimit, await createTestUnitOfWork(testDb));
svc = new CollabService(new DatabaseService(testDb), new PermissionsService(await createTestAppSettingsRepo(testDb), await createTestUnitOfWork(testDb)), new RealtimeService(), notificationsStub(), collabFx.storage, rateLimit, await createTestUnitOfWork(testDb));
});
/** A CollabService with its own preview cache and budget, for the tests that fill either. */
const freshSvc = async () => new CollabService(new DatabaseService(testDb), new PermissionsService(new DatabaseService(testDb), await createTestUnitOfWork(testDb)), new RealtimeService(), notificationsStub(), collabFx.storage, new RateLimitService(), await createTestUnitOfWork(testDb));
const freshSvc = async () => new CollabService(new DatabaseService(testDb), new PermissionsService(await createTestAppSettingsRepo(testDb), await createTestUnitOfWork(testDb)), new RealtimeService(), notificationsStub(), collabFx.storage, new RateLimitService(), await createTestUnitOfWork(testDb));
beforeAll(() => {
createTables(testDb);
@@ -688,7 +688,7 @@ describe('hardening', () => {
it('COLLAB-SVC-034: votePoll switch is atomic — prior vote survives a failed INSERT', async () => {
const { user1, trip } = setup();
const dbs = new DatabaseService(testDb);
const failing = new CollabService(dbs, new PermissionsService(dbs, await createTestUnitOfWork(dbs.connection)), new RealtimeService(), notificationsStub(), collabFx.storage, new RateLimitService(), await createTestUnitOfWork(dbs.connection));
const failing = new CollabService(dbs, new PermissionsService(await createTestAppSettingsRepo(dbs.connection), await createTestUnitOfWork(dbs.connection)), new RealtimeService(), notificationsStub(), collabFx.storage, new RateLimitService(), await createTestUnitOfWork(dbs.connection));
const poll = await failing.createPoll(trip.id, user1.id, { question: 'Q?', options: ['A', 'B'] });
await failing.votePoll(trip.id, poll!.id, user1.id, 0);
@@ -709,7 +709,7 @@ describe('hardening', () => {
it('COLLAB-SVC-035: deleteNote is atomic — trip_files rows survive a failed note DELETE', async () => {
const { user1, trip } = setup();
const dbs = new DatabaseService(testDb);
const failing = new CollabService(dbs, new PermissionsService(dbs, await createTestUnitOfWork(dbs.connection)), new RealtimeService(), notificationsStub(), collabFx.storage, new RateLimitService(), await createTestUnitOfWork(dbs.connection));
const failing = new CollabService(dbs, new PermissionsService(await createTestAppSettingsRepo(dbs.connection), await createTestUnitOfWork(dbs.connection)), new RealtimeService(), notificationsStub(), collabFx.storage, new RateLimitService(), await createTestUnitOfWork(dbs.connection));
const note = await failing.createNote(trip.id, user1.id, { title: 'With file' });
testDb.prepare('INSERT INTO trip_files (trip_id, note_id, filename, original_name) VALUES (?, ?, ?, ?)')
.run(trip.id, note.id, 'files/a.pdf', 'a.pdf');
@@ -730,7 +730,7 @@ describe('hardening', () => {
const { user1, trip } = setup();
const dbs = new DatabaseService(testDb);
const failingStorage = { delete: vi.fn().mockRejectedValue(new Error('EACCES')) };
const failing = new CollabService(dbs, new PermissionsService(dbs, await createTestUnitOfWork(dbs.connection)), new RealtimeService(), notificationsStub(), failingStorage as unknown as import('../../../src/nest/storage/storage.service').StorageService, new RateLimitService(), await createTestUnitOfWork(dbs.connection));
const failing = new CollabService(dbs, new PermissionsService(await createTestAppSettingsRepo(dbs.connection), await createTestUnitOfWork(dbs.connection)), new RealtimeService(), notificationsStub(), failingStorage as unknown as import('../../../src/nest/storage/storage.service').StorageService, new RateLimitService(), await createTestUnitOfWork(dbs.connection));
const note = await failing.createNote(trip.id, user1.id, { title: 'Sticky file' });
testDb.prepare('INSERT INTO trip_files (trip_id, note_id, filename, original_name) VALUES (?, ?, ?, ?)')
.run(trip.id, note.id, 'stuck.pdf', 'stuck.pdf');
@@ -55,12 +55,12 @@ import { CollectionsService } from '../../../src/nest/collections/collections.se
import { PlacePhotoCacheService } from '../../../src/nest/place-photos/place-photo-cache.service';
import { makeStorageFixture } from '../../helpers/storage-fixture';
import { notificationsStub } from '../../helpers/notifications';
import { createTestUnitOfWork } from '../../helpers/test-uow';
import { createTestUnitOfWork, createTestAppSettingsRepo } from '../../helpers/test-uow';
const storageFx = makeStorageFixture('');
let svc: CollectionsService;
beforeAll(async () => {
svc = new CollectionsService(new DatabaseService(testDb), new PermissionsService(new DatabaseService(testDb), await createTestUnitOfWork(testDb)), new RealtimeService(), notificationsStub(notifSend), storageFx.storage, await createTestUnitOfWork(testDb));
svc = new CollectionsService(new DatabaseService(testDb), new PermissionsService(await createTestAppSettingsRepo(testDb), await createTestUnitOfWork(testDb)), new RealtimeService(), notificationsStub(notifSend), storageFx.storage, await createTestUnitOfWork(testDb));
});
// The real cache: these cases assert what removeIfUnreferenced actually does
// about collection_places (#1081), so a stub would assert nothing.
@@ -51,11 +51,11 @@ import { PermissionsService } from '../../../src/nest/permissions/permissions.se
import { DayNotesService } from '../../../src/nest/day-notes/day-notes.service';
import type { DayNote } from '../../../src/types';
import { RealtimeService } from '../../../src/nest/realtime/realtime.service';
import { createTestUnitOfWork } from '../../helpers/test-uow';
import { createTestUnitOfWork, createTestAppSettingsRepo } from '../../helpers/test-uow';
let svc: DayNotesService;
beforeAll(async () => {
svc = new DayNotesService(new DatabaseService(testDb), new PermissionsService(new DatabaseService(testDb), await createTestUnitOfWork(testDb)), new RealtimeService());
svc = new DayNotesService(new DatabaseService(testDb), new PermissionsService(await createTestAppSettingsRepo(testDb), await createTestUnitOfWork(testDb)), new RealtimeService());
});
beforeAll(() => {
+2 -2
View File
@@ -64,11 +64,11 @@ import { RealtimeService } from '../../../src/nest/realtime/realtime.service';
import { QueryHelpersService } from '../../../src/nest/query-helpers/query-helpers.service';
import { makeAccommodationsService } from '../../helpers/accommodations-service';
import type { Day } from '../../../src/types';
import { createTestUnitOfWork } from '../../helpers/test-uow';
import { createTestUnitOfWork, createTestAppSettingsRepo } from '../../helpers/test-uow';
let svc: DaysService;
beforeAll(async () => {
svc = new DaysService(new DatabaseService(testDb), new PermissionsService(new DatabaseService(testDb), await createTestUnitOfWork(testDb)), new RealtimeService(), new QueryHelpersService(new DatabaseService(testDb)), await createTestUnitOfWork(testDb));
svc = new DaysService(new DatabaseService(testDb), new PermissionsService(await createTestAppSettingsRepo(testDb), await createTestUnitOfWork(testDb)), new RealtimeService(), new QueryHelpersService(new DatabaseService(testDb)), await createTestUnitOfWork(testDb));
});
let accommodations: Awaited<ReturnType<typeof makeAccommodationsService>>;
beforeAll(async () => {
@@ -25,12 +25,12 @@ import { McpSharedModule } from '../../../src/nest/mcp-shared/mcp-shared.module'
import { DatabaseService } from '../../../src/nest/database/database.service';
import { PermissionsService } from '../../../src/nest/permissions/permissions.service';
import { RealtimeService } from '../../../src/nest/realtime/realtime.service';
import { createTestUnitOfWork } from '../../helpers/test-uow';
import { createTestUnitOfWork, createTestAppSettingsRepo } from '../../helpers/test-uow';
const dbs = new DatabaseService(testDb);
let svc: McpToolGuardsService;
beforeAll(async () => {
svc = new McpToolGuardsService(dbs, new PermissionsService(dbs, await createTestUnitOfWork(dbs.connection)), new RealtimeService());
svc = new McpToolGuardsService(dbs, new PermissionsService(await createTestAppSettingsRepo(dbs.connection), await createTestUnitOfWork(dbs.connection)), new RealtimeService());
});
function createTrip(ownerId: number): number {
+3 -3
View File
@@ -106,7 +106,7 @@ import { EphemeralTokenService } from '../../../src/nest/auth/ephemeral-token.se
import { AllowedFileTypesService } from '../../../src/nest/files/allowed-file-types.service';
import { OidcService } from '../../../src/nest/oidc/oidc.service';
import { MailerService } from '../../../src/nest/notifications/mailer/mailer.service';
import { createTestUnitOfWork } from '../../helpers/test-uow';
import { createTestUnitOfWork, createTestAppSettingsRepo } from '../../helpers/test-uow';
// MailerService is injected since the notifications fold — a stub instead of a
// module mock. sendPasswordResetEmail is the only thing auth reaches for.
@@ -123,10 +123,10 @@ let svc: OidcService;
beforeAll(async () => {
auth = new AuthService(
new DatabaseService(testDb),
new PermissionsService(new DatabaseService(testDb), await createTestUnitOfWork(testDb)),
new PermissionsService(await createTestAppSettingsRepo(testDb), await createTestUnitOfWork(testDb)),
membership,
new WebauthnConfigService(new DatabaseService(testDb)),
new UserCleanupService(new DatabaseService(testDb), new BudgetService(new DatabaseService(testDb), new PermissionsService(new DatabaseService(testDb), await createTestUnitOfWork(testDb)), new ExchangeRatesService(), new RealtimeService(), await createTestUnitOfWork(testDb)), await createTestUnitOfWork(testDb)),
new UserCleanupService(new DatabaseService(testDb), new BudgetService(new DatabaseService(testDb), new PermissionsService(await createTestAppSettingsRepo(testDb), await createTestUnitOfWork(testDb)), new ExchangeRatesService(), new RealtimeService(), await createTestUnitOfWork(testDb)), await createTestUnitOfWork(testDb)),
mailerStub,
new EphemeralTokenService(),
new AllowedFileTypesService(new DatabaseService(testDb)), await createTestUnitOfWork(testDb),
@@ -89,7 +89,7 @@ import { UserCleanupService } from '../../../src/nest/auth/user-cleanup.service'
import { EphemeralTokenService } from '../../../src/nest/auth/ephemeral-token.service';
import { AllowedFileTypesService } from '../../../src/nest/files/allowed-file-types.service';
import { MailerService } from '../../../src/nest/notifications/mailer/mailer.service';
import { createTestUnitOfWork } from '../../helpers/test-uow';
import { createTestUnitOfWork, createTestAppSettingsRepo } from '../../helpers/test-uow';
// MailerService is injected since the notifications fold — a stub instead of a
// module mock. sendPasswordResetEmail is the only thing auth reaches for.
@@ -116,10 +116,10 @@ let svc: PasskeyService;
beforeAll(async () => {
auth = new AuthService(
new DatabaseService(testDb),
new PermissionsService(new DatabaseService(testDb), await createTestUnitOfWork(testDb)),
new PermissionsService(await createTestAppSettingsRepo(testDb), await createTestUnitOfWork(testDb)),
new TripMembershipService(new DatabaseService(testDb)),
new WebauthnConfigService(new DatabaseService(testDb)),
new UserCleanupService(new DatabaseService(testDb), new BudgetService(new DatabaseService(testDb), new PermissionsService(new DatabaseService(testDb), await createTestUnitOfWork(testDb)), new ExchangeRatesService(), new RealtimeService(), await createTestUnitOfWork(testDb)), await createTestUnitOfWork(testDb)),
new UserCleanupService(new DatabaseService(testDb), new BudgetService(new DatabaseService(testDb), new PermissionsService(await createTestAppSettingsRepo(testDb), await createTestUnitOfWork(testDb)), new ExchangeRatesService(), new RealtimeService(), await createTestUnitOfWork(testDb)), await createTestUnitOfWork(testDb)),
mailerStub,
new EphemeralTokenService(),
new AllowedFileTypesService(new DatabaseService(testDb)), await createTestUnitOfWork(testDb),
@@ -1,6 +1,6 @@
/**
* Unit tests for the DI-native PermissionsService — PERM-SVC-001 through
* PERM-SVC-023 (001–013 moved 1:1 from the legacy
* PERM-SVC-024 (001–013 moved 1:1 from the legacy
* tests/unit/services/permissions.test.ts, which had no case IDs — the IDs are
* introduced with the move; 014–016 pin the cache semantics the real DB now
* makes testable; 017–020 pin the permissions.bridge delegation and the
@@ -8,6 +8,13 @@
* pin the quirk-fix pass: load-time level validation, the narrowed load-error
* swallow, and the no-op-save early return). Uses a real in-memory SQLite DB
* so the app_settings SQL is exercised faithfully.
*
* Repository conversion (ORM Phase 3a, Task 2): PermissionsService no longer
* holds a DatabaseService — it is built from AppSettingsRepository +
* UnitOfWork, the same `t.repo(AppSettings)` pattern SettingsService's own
* unit test established. 022/024 (the two load-failure cases) now drive the
* failure through `vi.spyOn(appSettings, 'findByKeyPrefix')` instead of a
* hand-rolled DatabaseService/all() stub.
*/
import { describe, it, expect, vi, beforeAll, beforeEach, afterAll } from 'vitest';
@@ -37,35 +44,43 @@ vi.mock('../../../src/nest/audit/audit-log.logger', () => ({
logWarn: vi.fn(),
}));
import Database from 'better-sqlite3';
import { createTables } from '../../../src/db/schema';
import { runMigrations } from '../../../src/db/migrations';
import { logError } from '../../../src/nest/audit/audit-log.logger';
import { DatabaseService } from '../../../src/nest/database/database.service';
import { PermissionsService, PERMISSION_ACTIONS } from '../../../src/nest/permissions/permissions.service';
import {
getPermissionsCache,
invalidatePermissionsCache as invalidateSharedCache,
} from '../../../src/nest/permissions/permissions-cache';
import { createTestUnitOfWork } from '../../helpers/test-uow';
import { createTestOrm, type TestOrm } from '../../helpers/test-orm';
import { AppSettings } from '../../../src/db/entities/AppSettings.entity';
import type { AppSettingsRepository } from '../../../src/db/repositories/AppSettings.repository';
let svc: PermissionsService;
beforeAll(async () => {
svc = new PermissionsService(new DatabaseService(testDb), await createTestUnitOfWork(testDb));
});
let t: TestOrm;
let appSettings: AppSettingsRepository;
beforeAll(() => {
createTables(testDb);
runMigrations(testDb);
});
beforeAll(async () => {
t = await createTestOrm(testDb);
appSettings = t.repo(AppSettings) as AppSettingsRepository;
svc = new PermissionsService(appSettings, await createTestUnitOfWork(testDb));
});
beforeEach(() => {
vi.clearAllMocks();
testDb.prepare("DELETE FROM app_settings WHERE key LIKE 'perm_%'").run();
t.clear();
svc.invalidatePermissionsCache();
});
afterAll(() => {
afterAll(async () => {
await t.close();
testDb.close();
});
@@ -185,36 +200,43 @@ describe('corrupt stored levels', () => {
});
describe('load failures', () => {
it('PERM-SVC-022: a missing app_settings table stays silent and serves defaults; other DB failures are logged', async () => {
const bareDb = new Database(':memory:');
const bareSvc = new PermissionsService(new DatabaseService(bareDb), await createTestUnitOfWork(bareDb));
bareSvc.invalidatePermissionsCache();
expect(await bareSvc.getPermissionLevel('trip_edit')).toBe('trip_owner');
expect(logError).not.toHaveBeenCalled();
// An unexpected failure (closed connection) must leave a trace.
bareDb.close();
bareSvc.invalidatePermissionsCache();
expect(await bareSvc.getPermissionLevel('trip_edit')).toBe('trip_owner');
expect(logError).toHaveBeenCalledWith(expect.stringMatching(/^Permissions load failed: /));
svc.invalidatePermissionsCache(); // don't leak the bare-DB cache to later tests
it('PERM-SVC-022: a "no such table" read failure is no longer swallowed — migrations guarantee the table exists, so it is logged like any other failure, and defaults are still served', async () => {
// Under the legacy better-sqlite3 path this exact message meant first-boot
// init racing the read, before app_settings existed, and was swallowed
// silently. Under the ORM, buildApp() runs migrations to completion
// before any request/MCP/WS/cron entrypoint can reach this service, so
// that race no longer exists — the message-specific swallow is dropped
// and this failure now takes the same "log and serve defaults" path as
// every other repository error.
const spy = vi
.spyOn(appSettings, 'findByKeyPrefix')
.mockRejectedValueOnce(new Error('no such table: app_settings'));
svc.invalidatePermissionsCache();
expect(await svc.getPermissionLevel('trip_edit')).toBe('trip_owner');
expect(logError).toHaveBeenCalledWith('Permissions load failed: no such table: app_settings');
spy.mockRestore();
svc.invalidatePermissionsCache(); // don't leak the failed-read (uncached) state
});
it('PERM-SVC-024: a failed read serves defaults without installing them, and a later read populates the cache', async () => {
const failing = { all: vi.fn((): { key: string; value: string }[] => { throw new Error('database connection is closed'); }) };
// The stub never opens a transaction, so the suite's own UnitOfWork is the
// honest thing to hand it.
const flakySvc = new PermissionsService(failing as unknown as DatabaseService, await createTestUnitOfWork(testDb));
flakySvc.invalidatePermissionsCache();
const spy = vi
.spyOn(appSettings, 'findByKeyPrefix')
.mockRejectedValueOnce(new Error('database connection is closed'));
svc.invalidatePermissionsCache();
expect(await flakySvc.getPermissionLevel('trip_edit')).toBe('trip_owner');
expect(await svc.getPermissionLevel('trip_edit')).toBe('trip_owner');
expect(logError).toHaveBeenCalledWith('Permissions load failed: database connection is closed');
// Nothing installed: an admin's stricter stored level would otherwise stay
// invisible until somebody invalidated by hand.
expect(getPermissionsCache()).toBe(null);
failing.all.mockReturnValue([{ key: 'perm_trip_edit', value: 'trip_member' }]);
expect(await flakySvc.getPermissionLevel('trip_edit')).toBe('trip_member');
// The mock is exhausted after the one queued rejection — the next call
// falls through to the real (now-working) repository read.
testDb.prepare('INSERT OR REPLACE INTO app_settings (key, value) VALUES (?, ?)').run('perm_trip_edit', 'trip_member');
expect(await svc.getPermissionLevel('trip_edit')).toBe('trip_member');
expect(getPermissionsCache()).not.toBe(null);
svc.invalidatePermissionsCache(); // don't leak the stub cache to later tests
spy.mockRestore();
svc.invalidatePermissionsCache(); // don't leak this test's cache to later tests
});
it('PERM-SVC-023: an all-skipped save writes nothing and leaves the cache untouched', async () => {
@@ -264,8 +286,16 @@ describe('stored overrides + cache', () => {
// ── module-scoped cache across instances ──────────────────────────────────────
describe('module-scoped permissions cache', async () => {
const secondInstance = new PermissionsService(new DatabaseService(testDb), await createTestUnitOfWork(testDb));
describe('module-scoped permissions cache', () => {
let secondInstance: PermissionsService;
// A nested beforeAll, not a top-level await in the describe callback (the
// legacy file's shape): `appSettings` comes from the file-level beforeAll
// above, which vitest guarantees has already run by the time any nested
// beforeAll here executes, but would still be undefined during collection.
beforeAll(async () => {
secondInstance = new PermissionsService(appSettings, await createTestUnitOfWork(testDb));
});
it('PERM-SVC-017: checkPermission agrees across independently built instances', async () => {
expect(await secondInstance.checkPermission('trip_create', 'user', null, 42, false)).toBe(true);
@@ -54,7 +54,7 @@ import type { PlacePhotoCacheService } from '../../../src/nest/place-photos/plac
import { JourneyDomainService } from '../../../src/nest/journey/journey-domain.service';
import { TrekPhotosRepository } from '../../../src/nest/photos/trek-photos.repository';
import { makeStorageFixture } from '../../helpers/storage-fixture';
import { createTestUnitOfWork } from '../../helpers/test-uow';
import { createTestUnitOfWork, createTestAppSettingsRepo } from '../../helpers/test-uow';
const dbs = new DatabaseService(testDb);
const photoCacheStub = { removeIfUnreferenced: vi.fn() } as unknown as PlacePhotoCacheService;
@@ -69,7 +69,7 @@ const hit = (name: string, lat: number, lng: number) => ({
async function svc(searchNominatim: MapsService['searchNominatim']): Promise<PlacesService> {
return new PlacesService(
dbs,
new PermissionsService(dbs, await createTestUnitOfWork(dbs.connection)),
new PermissionsService(await createTestAppSettingsRepo(dbs.connection), await createTestUnitOfWork(dbs.connection)),
new RealtimeService(),
// The address backfill runs fire-and-forget after every import, so the stub answers
// it too — otherwise every passing test prints a rejected promise.
@@ -78,7 +78,7 @@ import { QueryHelpersService } from '../../../src/nest/query-helpers/query-helpe
import { JourneyDomainService } from '../../../src/nest/journey/journey-domain.service';
import { TrekPhotosRepository } from '../../../src/nest/photos/trek-photos.repository';
import { makeStorageFixture } from '../../helpers/storage-fixture';
import { createTestUnitOfWork } from '../../helpers/test-uow';
import { createTestUnitOfWork, createTestAppSettingsRepo } from '../../helpers/test-uow';
const GPX_FIXTURE = path.join(__dirname, '../../fixtures/test.gpx');
const KML_FIXTURE = path.join(__dirname, '../../fixtures/test.kml');
@@ -99,7 +99,7 @@ const placesStorageFx = makeStorageFixture('');
async function makePlacesService(maps: MapsService = new MapsService(dbs, photoCacheStub)): Promise<PlacesService> {
return new PlacesService(
dbs,
new PermissionsService(dbs, await createTestUnitOfWork(dbs.connection)),
new PermissionsService(await createTestAppSettingsRepo(dbs.connection), await createTestUnitOfWork(dbs.connection)),
new RealtimeService(),
maps,
new QueryHelpersService(dbs),
+2 -2
View File
@@ -48,12 +48,12 @@ import { DatabaseService } from '../../../src/nest/database/database.service';
import { PermissionsService } from '../../../src/nest/permissions/permissions.service';
import { TodoService } from '../../../src/nest/todo/todo.service';
import { RealtimeService } from '../../../src/nest/realtime/realtime.service';
import { createTestUnitOfWork } from '../../helpers/test-uow';
import { createTestUnitOfWork, createTestAppSettingsRepo } from '../../helpers/test-uow';
let svc: TodoService;
beforeAll(async () => {
const uow = await createTestUnitOfWork(testDb);
svc = new TodoService(new DatabaseService(testDb), new PermissionsService(new DatabaseService(testDb), uow), new RealtimeService(), uow);
svc = new TodoService(new DatabaseService(testDb), new PermissionsService(await createTestAppSettingsRepo(testDb), uow), new RealtimeService(), uow);
});
beforeAll(() => {
@@ -40,7 +40,7 @@ import { DatabaseService } from '../../../src/nest/database/database.service';
import { PermissionsService } from '../../../src/nest/permissions/permissions.service';
import { TripMembershipService } from '../../../src/nest/trip-membership/trip-membership.service';
import { TripInviteService } from '../../../src/nest/trip-invite/trip-invite.service';
import { createTestUnitOfWork } from '../../helpers/test-uow';
import { createTestUnitOfWork, createTestAppSettingsRepo } from '../../helpers/test-uow';
// One DatabaseService over the shared in-memory handle, so every collaborator
// reads and writes the same rows.
@@ -48,7 +48,7 @@ const dbs = new DatabaseService(testDb);
let svc: TripInviteService;
beforeAll(async () => {
const uow = await createTestUnitOfWork(dbs.connection);
svc = new TripInviteService(dbs, new PermissionsService(dbs, uow), new TripMembershipService(dbs), uow);
svc = new TripInviteService(dbs, new PermissionsService(await createTestAppSettingsRepo(dbs.connection), uow), new TripMembershipService(dbs), uow);
});
beforeAll(() => { createTables(testDb); runMigrations(testDb); });
@@ -65,15 +65,15 @@ import { TripMembersService } from '../../../src/nest/trip-members/trip-members.
import { NotFoundError, ValidationError } from '../../../src/nest/common/domain-errors';
import type { User } from '../../../src/types';
import { notificationsStub } from '../../helpers/notifications';
import { createTestUnitOfWork } from '../../helpers/test-uow';
import { createTestUnitOfWork, createTestAppSettingsRepo } from '../../helpers/test-uow';
const dbs = () => new DatabaseService(testDb);
let budgetSvc: BudgetService;
let roster: TripMembersService;
beforeAll(async () => {
budgetSvc = new BudgetService(dbs(), new PermissionsService(dbs(), await createTestUnitOfWork(dbs().connection)), new ExchangeRatesService(), new RealtimeService(), await createTestUnitOfWork(dbs().connection));
roster = new TripMembersService(dbs(), budgetSvc, new UserCleanupService(dbs(), budgetSvc, await createTestUnitOfWork(dbs().connection)), new PermissionsService(dbs(), await createTestUnitOfWork(dbs().connection)), new RealtimeService(), notificationsStub(notifySend), await createTestUnitOfWork(dbs().connection));
budgetSvc = new BudgetService(dbs(), new PermissionsService(await createTestAppSettingsRepo(dbs().connection), await createTestUnitOfWork(dbs().connection)), new ExchangeRatesService(), new RealtimeService(), await createTestUnitOfWork(dbs().connection));
roster = new TripMembersService(dbs(), budgetSvc, new UserCleanupService(dbs(), budgetSvc, await createTestUnitOfWork(dbs().connection)), new PermissionsService(await createTestAppSettingsRepo(dbs().connection), await createTestUnitOfWork(dbs().connection)), new RealtimeService(), notificationsStub(notifySend), await createTestUnitOfWork(dbs().connection));
});
/**
@@ -104,7 +104,7 @@ async function rosterWithMissingRow(match: string) {
},
});
const frozen = { connection: conn, canAccessTrip: dbMock.canAccessTrip, isOwner: dbMock.isOwner } as unknown as DatabaseService;
return new TripMembersService(frozen, budgetSvc, new UserCleanupService(dbs(), budgetSvc, await createTestUnitOfWork(dbs().connection)), new PermissionsService(dbs(), await createTestUnitOfWork(dbs().connection)), new RealtimeService(), notificationsStub(notifySend), await createTestUnitOfWork(dbs().connection));
return new TripMembersService(frozen, budgetSvc, new UserCleanupService(dbs(), budgetSvc, await createTestUnitOfWork(dbs().connection)), new PermissionsService(await createTestAppSettingsRepo(dbs().connection), await createTestUnitOfWork(dbs().connection)), new RealtimeService(), notificationsStub(notifySend), await createTestUnitOfWork(dbs().connection));
}
beforeAll(() => {
@@ -78,7 +78,7 @@ import { RuntimeEnvService } from '../../../src/nest/app-config/runtime-env.serv
import { makeStorageFixture } from '../../helpers/storage-fixture';
import { JourneyDomainService } from '../../../src/nest/journey/journey-domain.service';
import { TrekPhotosRepository } from '../../../src/nest/photos/trek-photos.repository';
import { createTestUnitOfWork } from '../../helpers/test-uow';
import { createTestUnitOfWork, createTestAppSettingsRepo } from '../../helpers/test-uow';
// Real sibling services over the same in-memory DB — the aggregation runs the
// actual SQL of every domain it fans out to, so a shape change downstream shows
@@ -99,28 +99,28 @@ let daysSvc: DaysService;
let placesSvc: PlacesService;
let membersSvc: TripMembersService;
beforeAll(async () => {
budgetSvc = new BudgetService(dbs(), new PermissionsService(dbs(), await createTestUnitOfWork(dbs().connection)), new ExchangeRatesService(), new RealtimeService(), await createTestUnitOfWork(dbs().connection));
daysSvc = new DaysService(dbs(), new PermissionsService(dbs(), await createTestUnitOfWork(dbs().connection)), new RealtimeService(), new QueryHelpersService(dbs()), await createTestUnitOfWork(dbs().connection));
budgetSvc = new BudgetService(dbs(), new PermissionsService(await createTestAppSettingsRepo(dbs().connection), await createTestUnitOfWork(dbs().connection)), new ExchangeRatesService(), new RealtimeService(), await createTestUnitOfWork(dbs().connection));
daysSvc = new DaysService(dbs(), new PermissionsService(await createTestAppSettingsRepo(dbs().connection), await createTestUnitOfWork(dbs().connection)), new RealtimeService(), new QueryHelpersService(dbs()), await createTestUnitOfWork(dbs().connection));
placesSvc = new PlacesService(
dbs(), new PermissionsService(dbs(), await createTestUnitOfWork(dbs().connection)), new RealtimeService(),
dbs(), new PermissionsService(await createTestAppSettingsRepo(dbs().connection), await createTestUnitOfWork(dbs().connection)), new RealtimeService(),
new MapsService(dbs(), photoCache), new QueryHelpersService(dbs()),
new UnsplashService(dbs(), new RuntimeEnvService(), makeStorageFixture('').storage), photoCache,
new JourneyDomainService(dbs(), new RealtimeService(), new TrekPhotosRepository(dbs()), await createTestUnitOfWork(dbs().connection)),
makeStorageFixture('').storage,
await accommodationsOver(dbs()), await createTestUnitOfWork(dbs().connection),
);
membersSvc = new TripMembersService(dbs(), budgetSvc, new UserCleanupService(dbs(), budgetSvc, await createTestUnitOfWork(dbs().connection)), new PermissionsService(dbs(), await createTestUnitOfWork(dbs().connection)), new RealtimeService(), notificationsStub(), await createTestUnitOfWork(dbs().connection));
membersSvc = new TripMembersService(dbs(), budgetSvc, new UserCleanupService(dbs(), budgetSvc, await createTestUnitOfWork(dbs().connection)), new PermissionsService(await createTestAppSettingsRepo(dbs().connection), await createTestUnitOfWork(dbs().connection)), new RealtimeService(), notificationsStub(), await createTestUnitOfWork(dbs().connection));
});
const buildReadModel = async (database: DatabaseService, roster: TripMembersService = membersSvc) =>
new TripReadModelService(
database, roster, daysSvc, accommodationsSvc, budgetSvc,
new PackingService(dbs(), new PermissionsService(dbs(), await createTestUnitOfWork(dbs().connection)), new RealtimeService(), notificationsStub(), await createTestUnitOfWork(dbs().connection)),
new ReservationsService(dbs(), new PermissionsService(dbs(), await createTestUnitOfWork(dbs().connection)), budgetSvc, new RealtimeService(), notificationsStub(), new ReservationsReadRepository(dbs()), await accommodationsOver(dbs()), await createTestUnitOfWork(dbs().connection)),
new CollabService(dbs(), new PermissionsService(dbs(), await createTestUnitOfWork(dbs().connection)), new RealtimeService(), notificationsStub(), makeStorageFixture('').storage, new RateLimitService(), await createTestUnitOfWork(dbs().connection)),
new PackingService(dbs(), new PermissionsService(await createTestAppSettingsRepo(dbs().connection), await createTestUnitOfWork(dbs().connection)), new RealtimeService(), notificationsStub(), await createTestUnitOfWork(dbs().connection)),
new ReservationsService(dbs(), new PermissionsService(await createTestAppSettingsRepo(dbs().connection), await createTestUnitOfWork(dbs().connection)), budgetSvc, new RealtimeService(), notificationsStub(), new ReservationsReadRepository(dbs()), await accommodationsOver(dbs()), await createTestUnitOfWork(dbs().connection)),
new CollabService(dbs(), new PermissionsService(await createTestAppSettingsRepo(dbs().connection), await createTestUnitOfWork(dbs().connection)), new RealtimeService(), notificationsStub(), makeStorageFixture('').storage, new RateLimitService(), await createTestUnitOfWork(dbs().connection)),
placesSvc,
new TodoService(dbs(), new PermissionsService(dbs(), await createTestUnitOfWork(dbs().connection)), new RealtimeService(), await createTestUnitOfWork(dbs().connection)),
new FilesService(dbs(), new PermissionsService(dbs(), await createTestUnitOfWork(dbs().connection)), new RealtimeService(), new EphemeralTokenService(), makeStorageFixture('').storage),
new TodoService(dbs(), new PermissionsService(await createTestAppSettingsRepo(dbs().connection), await createTestUnitOfWork(dbs().connection)), new RealtimeService(), await createTestUnitOfWork(dbs().connection)),
new FilesService(dbs(), new PermissionsService(await createTestAppSettingsRepo(dbs().connection), await createTestUnitOfWork(dbs().connection)), new RealtimeService(), new EphemeralTokenService(), makeStorageFixture('').storage),
);
let svc: Awaited<ReturnType<typeof buildReadModel>>;
+15 -15
View File
@@ -88,7 +88,7 @@ import fs from 'fs';
import path from 'path';
import { notificationsStub } from '../../helpers/notifications';
import { EphemeralTokenService } from '../../../src/nest/auth/ephemeral-token.service';
import { createTestUnitOfWork } from '../../helpers/test-uow';
import { createTestUnitOfWork, createTestAppSettingsRepo } from '../../helpers/test-uow';
// Real sibling services over the same in-memory DB — updateTrip's date-shift
// resyncs and the summary/bundle aggregation run their actual SQL.
@@ -122,11 +122,11 @@ let svc: TripsService;
let membersSvc: TripMembersService;
let readModelSvc: TripReadModelService;
beforeAll(async () => {
budgetSvc = new BudgetService(dbs(), new PermissionsService(dbs(), await createTestUnitOfWork(dbs().connection)), new ExchangeRatesService(), new RealtimeService(), await createTestUnitOfWork(dbs().connection));
daysSvc = new DaysService(dbs(), new PermissionsService(dbs(), await createTestUnitOfWork(dbs().connection)), new RealtimeService(), new QueryHelpersService(dbs()), await createTestUnitOfWork(dbs().connection));
budgetSvc = new BudgetService(dbs(), new PermissionsService(await createTestAppSettingsRepo(dbs().connection), await createTestUnitOfWork(dbs().connection)), new ExchangeRatesService(), new RealtimeService(), await createTestUnitOfWork(dbs().connection));
daysSvc = new DaysService(dbs(), new PermissionsService(await createTestAppSettingsRepo(dbs().connection), await createTestUnitOfWork(dbs().connection)), new RealtimeService(), new QueryHelpersService(dbs()), await createTestUnitOfWork(dbs().connection));
placesSvc = new PlacesService(
dbs(),
new PermissionsService(dbs(), await createTestUnitOfWork(dbs().connection)),
new PermissionsService(await createTestAppSettingsRepo(dbs().connection), await createTestUnitOfWork(dbs().connection)),
new RealtimeService(),
new MapsService(dbs(), photoCache),
new QueryHelpersService(dbs()),
@@ -138,9 +138,9 @@ beforeAll(async () => {
);
svc = new TripsService(
dbs(),
new ReservationsService(dbs(), new PermissionsService(dbs(), await createTestUnitOfWork(dbs().connection)), budgetSvc, new RealtimeService(), notificationsStub(), new ReservationsReadRepository(dbs()), accommodationsSvc, await createTestUnitOfWork(dbs().connection)),
new ReservationsService(dbs(), new PermissionsService(await createTestAppSettingsRepo(dbs().connection), await createTestUnitOfWork(dbs().connection)), budgetSvc, new RealtimeService(), notificationsStub(), new ReservationsReadRepository(dbs()), accommodationsSvc, await createTestUnitOfWork(dbs().connection)),
daysSvc,
new PermissionsService(dbs(), await createTestUnitOfWork(dbs().connection)),
new PermissionsService(await createTestAppSettingsRepo(dbs().connection), await createTestUnitOfWork(dbs().connection)),
budgetSvc,
new VacayService(dbs(), new RealtimeService(), notificationsStub(), await createTestUnitOfWork(dbs().connection)),
new RealtimeService(),
@@ -148,15 +148,15 @@ beforeAll(async () => {
coversFx.storage,
await createTestUnitOfWork(dbs().connection),
);
membersSvc = new TripMembersService(dbs(), budgetSvc, new UserCleanupService(dbs(), budgetSvc, await createTestUnitOfWork(dbs().connection)), new PermissionsService(dbs(), await createTestUnitOfWork(dbs().connection)), new RealtimeService(), notificationsStub(), await createTestUnitOfWork(dbs().connection));
membersSvc = new TripMembersService(dbs(), budgetSvc, new UserCleanupService(dbs(), budgetSvc, await createTestUnitOfWork(dbs().connection)), new PermissionsService(await createTestAppSettingsRepo(dbs().connection), await createTestUnitOfWork(dbs().connection)), new RealtimeService(), notificationsStub(), await createTestUnitOfWork(dbs().connection));
readModelSvc = new TripReadModelService(
dbs(), membersSvc, daysSvc, accommodationsSvc, budgetSvc,
new PackingService(dbs(), new PermissionsService(dbs(), await createTestUnitOfWork(dbs().connection)), new RealtimeService(), notificationsStub(), await createTestUnitOfWork(dbs().connection)),
new ReservationsService(dbs(), new PermissionsService(dbs(), await createTestUnitOfWork(dbs().connection)), budgetSvc, new RealtimeService(), notificationsStub(), new ReservationsReadRepository(dbs()), accommodationsSvc, await createTestUnitOfWork(dbs().connection)),
new CollabService(dbs(), new PermissionsService(dbs(), await createTestUnitOfWork(dbs().connection)), new RealtimeService(), notificationsStub(), coversFx.storage, new RateLimitService(), await createTestUnitOfWork(dbs().connection)),
new PackingService(dbs(), new PermissionsService(await createTestAppSettingsRepo(dbs().connection), await createTestUnitOfWork(dbs().connection)), new RealtimeService(), notificationsStub(), await createTestUnitOfWork(dbs().connection)),
new ReservationsService(dbs(), new PermissionsService(await createTestAppSettingsRepo(dbs().connection), await createTestUnitOfWork(dbs().connection)), budgetSvc, new RealtimeService(), notificationsStub(), new ReservationsReadRepository(dbs()), accommodationsSvc, await createTestUnitOfWork(dbs().connection)),
new CollabService(dbs(), new PermissionsService(await createTestAppSettingsRepo(dbs().connection), await createTestUnitOfWork(dbs().connection)), new RealtimeService(), notificationsStub(), coversFx.storage, new RateLimitService(), await createTestUnitOfWork(dbs().connection)),
placesSvc,
new TodoService(dbs(), new PermissionsService(dbs(), await createTestUnitOfWork(dbs().connection)), new RealtimeService(), await createTestUnitOfWork(dbs().connection)),
new FilesService(dbs(), new PermissionsService(dbs(), await createTestUnitOfWork(dbs().connection)), new RealtimeService(), new EphemeralTokenService(), coversFx.storage),
new TodoService(dbs(), new PermissionsService(await createTestAppSettingsRepo(dbs().connection), await createTestUnitOfWork(dbs().connection)), new RealtimeService(), await createTestUnitOfWork(dbs().connection)),
new FilesService(dbs(), new PermissionsService(await createTestAppSettingsRepo(dbs().connection), await createTestUnitOfWork(dbs().connection)), new RealtimeService(), new EphemeralTokenService(), coversFx.storage),
);
});
@@ -1205,9 +1205,9 @@ describe('quirk fixes', () => {
const fdbs = failingConnection(match);
return new TripsService(
fdbs,
new ReservationsService(dbs(), new PermissionsService(dbs(), await createTestUnitOfWork(dbs().connection)), budgetSvc, new RealtimeService(), notificationsStub(), new ReservationsReadRepository(dbs()), accommodationsSvc, await createTestUnitOfWork(dbs().connection)),
new ReservationsService(dbs(), new PermissionsService(await createTestAppSettingsRepo(dbs().connection), await createTestUnitOfWork(dbs().connection)), budgetSvc, new RealtimeService(), notificationsStub(), new ReservationsReadRepository(dbs()), accommodationsSvc, await createTestUnitOfWork(dbs().connection)),
daysSvc,
new PermissionsService(dbs(), await createTestUnitOfWork(dbs().connection)),
new PermissionsService(await createTestAppSettingsRepo(dbs().connection), await createTestUnitOfWork(dbs().connection)),
budgetSvc,
new VacayService(dbs(), new RealtimeService(), notificationsStub(), await createTestUnitOfWork(dbs().connection)),
new RealtimeService(),
@@ -1221,7 +1221,7 @@ describe('quirk fixes', () => {
async function failingMembers(match: string) {
return new TripMembersService(
failingConnection(match), budgetSvc, new UserCleanupService(dbs(), budgetSvc, await createTestUnitOfWork(dbs().connection)),
new PermissionsService(dbs(), await createTestUnitOfWork(dbs().connection)), new RealtimeService(),
new PermissionsService(await createTestAppSettingsRepo(dbs().connection), await createTestUnitOfWork(dbs().connection)), new RealtimeService(),
notificationsStub(), await createTestUnitOfWork(dbs().connection),
);
}
@@ -49,14 +49,14 @@ import { ExchangeRatesService } from '../../../src/nest/budget/exchange-rates.se
import { RealtimeService } from '../../../src/nest/realtime/realtime.service';
import { BudgetService } from '../../../src/nest/budget/budget.service';
import { UserCleanupService } from '../../../src/nest/auth/user-cleanup.service';
import { createTestUnitOfWork } from '../../helpers/test-uow';
import { createTestUnitOfWork, createTestAppSettingsRepo } from '../../helpers/test-uow';
const dbs = new DatabaseService(testDb);
let budget: BudgetService;
let svc: UserCleanupService;
beforeAll(async () => {
budget = new BudgetService(dbs, new PermissionsService(dbs, await createTestUnitOfWork(dbs.connection)), new ExchangeRatesService(), new RealtimeService(), await createTestUnitOfWork(dbs.connection));
budget = new BudgetService(dbs, new PermissionsService(await createTestAppSettingsRepo(dbs.connection), await createTestUnitOfWork(dbs.connection)), new ExchangeRatesService(), new RealtimeService(), await createTestUnitOfWork(dbs.connection));
svc = new UserCleanupService(dbs, budget, await createTestUnitOfWork(dbs.connection));
});
@@ -23,7 +23,7 @@ import type { AirtrailClient } from '../../../src/nest/integrations/airtrail.cli
import type { AirtrailService } from '../../../src/nest/integrations/airtrail.service';
import { notificationsStub } from '../../helpers/notifications';
import { accommodationsOver } from '../../helpers/accommodations-service';
import { createTestUnitOfWork } from '../../helpers/test-uow';
import { createTestUnitOfWork, createTestAppSettingsRepo } from '../../helpers/test-uow';
// The client and the per-user credentials are the only stubs; the reservation
// writes go through the real service against the real test DB, as before. They
@@ -33,7 +33,7 @@ const broadcast = vi.fn();
async function makeImportService(): Promise<AirtrailImportService> {
const dbs = () => new DatabaseService(db);
const permissions = new PermissionsService(dbs(), await createTestUnitOfWork(dbs().connection));
const permissions = new PermissionsService(await createTestAppSettingsRepo(dbs().connection), await createTestUnitOfWork(dbs().connection));
const realtime = { broadcast } as unknown as RealtimeService;
return new AirtrailImportService(
dbs(),
@@ -54,7 +54,7 @@ import { TrekPhotosRepository } from '../../../src/nest/photos/trek-photos.repos
import { RuntimeEnvService } from '../../../src/nest/app-config/runtime-env.service';
import { notificationsStub } from '../../helpers/notifications';
import { makeStorageFixture } from '../../helpers/storage-fixture';
import { createTestUnitOfWork } from '../../helpers/test-uow';
import { createTestUnitOfWork, createTestAppSettingsRepo } from '../../helpers/test-uow';
const dbs = new DatabaseService(testDb);
const realtime = new RealtimeService();
@@ -67,10 +67,10 @@ const photoCache = new PlacePhotoCacheService(dbs, makeStorageFixture('photos/go
let packing: PackingService;
let places: PlacesService;
beforeAll(async () => {
packing = new PackingService(dbs, new PermissionsService(dbs, await createTestUnitOfWork(dbs.connection)), realtime, notificationsStub(), await createTestUnitOfWork(dbs.connection));
packing = new PackingService(dbs, new PermissionsService(await createTestAppSettingsRepo(dbs.connection), await createTestUnitOfWork(dbs.connection)), realtime, notificationsStub(), await createTestUnitOfWork(dbs.connection));
places = new PlacesService(
dbs,
new PermissionsService(dbs, await createTestUnitOfWork(dbs.connection)),
new PermissionsService(await createTestAppSettingsRepo(dbs.connection), await createTestUnitOfWork(dbs.connection)),
realtime,
new MapsService(dbs, photoCache),
new QueryHelpersService(dbs),