refactor(server): extract addon enablement into the addons domain

This commit is contained in:
jubnl
2026-07-28 20:22:01 +02:00
parent cafff003a3
commit ee2ea1d065
64 changed files with 486 additions and 277 deletions
+8 -7
View File
@@ -1,8 +1,9 @@
/**
* GET /api/addons e2e — exercises the AddonsController through the real
* JwtAuthGuard against a temp SQLite db. getCollabFeatures + getPhotoProviderConfig
* are mocked; the addons/photo_providers/photo_provider_fields reads run against
* the temp db. Asserts the byte-identical body the legacy inline handler produced.
* JwtAuthGuard against a temp SQLite db. getPhotoProviderConfig is
* mocked; the addons/photo_providers/photo_provider_fields/app_settings reads
* run against the temp db (the collab/bag-tracking flags are real AddonsService
* reads since the admin-1 extraction). Asserts the byte-identical body the legacy inline handler produced.
*/
import { describe, it, expect, beforeAll, afterAll, vi } from 'vitest';
import request from 'supertest';
@@ -24,6 +25,7 @@ const { db } = vi.hoisted(() => {
tmp.exec(`CREATE TABLE photo_provider_fields (id INTEGER PRIMARY KEY AUTOINCREMENT, provider_id TEXT, field_key TEXT,
label TEXT, input_type TEXT, placeholder TEXT, hint TEXT, required INTEGER, secret INTEGER,
settings_key TEXT, payload_key TEXT, sort_order INTEGER);`);
tmp.exec(`CREATE TABLE app_settings (key TEXT PRIMARY KEY, value TEXT);`);
return { db: tmp };
});
@@ -31,12 +33,9 @@ vi.mock('../../src/db/database', () => ({
db, canAccessTrip: vi.fn(), isOwner: vi.fn(), getPlaceWithTags: vi.fn(), closeDb: () => {}, reinitialize: () => {},
}));
const { getCollabFeatures, getBagTracking, getPhotoProviderConfig } = vi.hoisted(() => ({
getCollabFeatures: vi.fn(() => ({ chat: true, notes: true, polls: true, whatsnext: true })),
getBagTracking: vi.fn(() => ({ enabled: true })),
const { getPhotoProviderConfig } = vi.hoisted(() => ({
getPhotoProviderConfig: vi.fn(() => ({ url: 'https://immich.example' })),
}));
vi.mock('../../src/services/adminService', () => ({ getCollabFeatures, getBagTracking }));
vi.mock('../../src/services/memories/helpersService', () => ({ getPhotoProviderConfig }));
import { AddonsModule } from '../../src/nest/addons/addons.module';
@@ -57,6 +56,8 @@ describe('GET /api/addons e2e (real auth guard + temp SQLite)', () => {
beforeAll(async () => {
seedUser(db as never, { id: 1 });
// bag tracking is opt-in (=== 'true'); collab flags default ON with no rows
db.prepare("INSERT INTO app_settings (key, value) VALUES ('bag_tracking_enabled', 'true')").run();
db.prepare("INSERT INTO addons (id, name, type, icon, enabled, sort_order) VALUES ('packing','Packing','trip','Backpack',1,1)").run();
db.prepare("INSERT INTO addons (id, name, type, icon, enabled, sort_order) VALUES ('disabled','Disabled','trip','X',0,2)").run();
db.prepare("INSERT INTO photo_providers (id, name, icon, enabled, sort_order) VALUES ('immich','Immich','Image',1,1)").run();
+5 -2
View File
@@ -32,7 +32,6 @@ vi.mock('../../src/db/database', () => ({
}));
const { isAddonEnabled } = vi.hoisted(() => ({ isAddonEnabled: vi.fn(() => true) }));
vi.mock('../../src/services/adminService', () => ({ isAddonEnabled }));
vi.mock('../../src/websocket', () => ({ broadcastToUser: vi.fn(), broadcast: vi.fn() }));
vi.mock('../../src/services/notificationService', () => ({ send: vi.fn().mockResolvedValue(undefined) }));
@@ -40,6 +39,7 @@ import { createTables } from '../../src/db/schema';
import { runMigrations } from '../../src/db/migrations';
import { createUser, createTrip, createCategory } from '../helpers/factories';
import { CollectionsModule } from '../../src/nest/collections/collections.module';
import { AddonsService } from '../../src/nest/addons/addons.service';
import { TrekExceptionFilter } from '../../src/nest/common/trek-exception.filter';
import { ZodValidationPipe } from '../../src/nest/common/zod-validation.pipe';
@@ -51,7 +51,10 @@ describe('Collections e2e (real auth guard + real service + temp SQLite)', () =>
let tripId: number;
async function build() {
const moduleRef = await Test.createTestingModule({ imports: [CollectionsModule] }).compile();
const moduleRef = await Test.createTestingModule({ imports: [CollectionsModule] })
.overrideProvider(AddonsService)
.useValue({ isAddonEnabled })
.compile();
const nest = moduleRef.createNestApplication();
nest.use(cookieParser());
nest.useGlobalFilters(new TrekExceptionFilter());
+5 -2
View File
@@ -26,7 +26,6 @@ const { db } = vi.hoisted(() => {
vi.mock('../../src/db/database', () => ({ db, closeDb: () => {}, reinitialize: () => {} }));
const { isAddonEnabled } = vi.hoisted(() => ({ isAddonEnabled: vi.fn(() => true) }));
vi.mock('../../src/services/adminService', () => ({ isAddonEnabled }));
// The controller's pure helpers (isVideoExtension/isVideoMime/MAX_VIDEO_SIZE)
// now come from the real files.constants; only the request-time app_settings
// read is mocked, preserving the old '*'-allowlist semantics for the fixtures.
@@ -43,6 +42,7 @@ const { sharesvc } = vi.hoisted(() => ({ sharesvc: { getPublicJourney: vi.fn() }
vi.mock('../../src/services/journeyShareService', () => sharesvc);
import { JourneyModule } from '../../src/nest/journey/journey.module';
import { AddonsService } from '../../src/nest/addons/addons.service';
import { TrekExceptionFilter } from '../../src/nest/common/trek-exception.filter';
describe('Journey e2e (real auth guard + temp SQLite)', () => {
@@ -50,7 +50,10 @@ describe('Journey e2e (real auth guard + temp SQLite)', () => {
let app: Awaited<ReturnType<typeof build>>;
async function build() {
const moduleRef = await Test.createTestingModule({ imports: [DatabaseModule, JourneyModule] }).compile();
const moduleRef = await Test.createTestingModule({ imports: [DatabaseModule, JourneyModule] })
.overrideProvider(AddonsService)
.useValue({ isAddonEnabled })
.compile();
const nest = moduleRef.createNestApplication();
nest.use(cookieParser());
nest.useGlobalFilters(new TrekExceptionFilter());
+5 -2
View File
@@ -37,7 +37,6 @@ vi.mock('../../src/app-config', async (importOriginal) => {
});
const { isAddonEnabled } = vi.hoisted(() => ({ isAddonEnabled: vi.fn(() => true) }));
vi.mock('../../src/services/adminService', () => ({ isAddonEnabled }));
const { oauthSvc } = vi.hoisted(() => ({
oauthSvc: {
@@ -51,6 +50,7 @@ const { oauthSvc } = vi.hoisted(() => ({
vi.mock('../../src/services/oauthService', () => oauthSvc);
import { OauthModule } from '../../src/nest/oauth/oauth.module';
import { AddonsService } from '../../src/nest/addons/addons.service';
import { DatabaseModule } from '../../src/nest/database/database.module';
import { TrekExceptionFilter } from '../../src/nest/common/trek-exception.filter';
@@ -59,7 +59,10 @@ describe('OAuth e2e (real guards + temp SQLite)', () => {
let app: Awaited<ReturnType<typeof build>>;
async function build() {
const moduleRef = await Test.createTestingModule({ imports: [DatabaseModule, OauthModule] }).compile();
const moduleRef = await Test.createTestingModule({ imports: [DatabaseModule, OauthModule] })
.overrideProvider(AddonsService)
.useValue({ isAddonEnabled })
.compile();
const nest = moduleRef.createNestApplication();
nest.use(cookieParser());
nest.useGlobalFilters(new TrekExceptionFilter());
+5 -2
View File
@@ -20,6 +20,7 @@ import { CollabService } from '../../src/nest/collab/collab.service';
import { VacayService } from '../../src/nest/vacay/vacay.service';
import { PermissionsService } from '../../src/nest/permissions/permissions.service';
import { AuditService } from '../../src/nest/audit/audit.service';
import { AddonsService } from '../../src/nest/addons/addons.service';
/**
* Hand-wired counterpart of the PluginsModule DI graph for no-Nest tests
@@ -31,6 +32,7 @@ export function createHostDepsFactory(dbs: DatabaseService): PluginHostDepsFacto
const permissions = new PermissionsService(dbs);
const exchangeRates = new ExchangeRatesService();
const budget = new BudgetService(dbs, permissions, exchangeRates);
const addons = new AddonsService(dbs);
return new PluginHostDepsFactory(
budget,
new ReservationsService(dbs, permissions, budget),
@@ -41,7 +43,7 @@ export function createHostDepsFactory(dbs: DatabaseService): PluginHostDepsFacto
new PluginOAuthService(dbs),
new DayNotesService(dbs, permissions),
new AssignmentsService(dbs, permissions),
new LlmConfigResolver(new SettingsService(dbs), dbs),
new LlmConfigResolver(new SettingsService(dbs), dbs, addons),
dbs,
new FilesService(dbs, permissions),
new CollabService(dbs, permissions),
@@ -49,10 +51,11 @@ export function createHostDepsFactory(dbs: DatabaseService): PluginHostDepsFacto
new DaysService(dbs, permissions),
permissions,
exchangeRates,
addons,
);
}
/** A PluginRuntimeService constructed the way Nest would: with a real host-deps factory. */
export function createPluginRuntime(dbs: DatabaseService, registry?: PluginRegistryService): PluginRuntimeService {
return new PluginRuntimeService(dbs, new AuditService(dbs), registry, createHostDepsFactory(dbs));
return new PluginRuntimeService(dbs, new AuditService(dbs), new AddonsService(dbs), registry, createHostDepsFactory(dbs));
}
+4 -15
View File
@@ -44,15 +44,6 @@ vi.mock('../../src/config', () => ({
DEFAULT_LANGUAGE: 'en',
}));
const { isAddonEnabledMock } = vi.hoisted(() => {
const isAddonEnabledMock = vi.fn().mockReturnValue(true);
return { isAddonEnabledMock };
});
vi.mock('../../src/services/adminService', async (importOriginal) => {
const actual = await importOriginal<typeof import('../../src/services/adminService')>();
return { ...actual, isAddonEnabled: isAddonEnabledMock };
});
vi.mock('../../src/app-config', async (importOriginal) => {
const actual = await importOriginal<typeof import('../../src/app-config')>();
return { ...actual, getMcpSafeUrl: () => 'https://trek.example.com' };
@@ -79,13 +70,11 @@ function makePkce() {
return { verifier, challenge };
}
// A7: under the unified Nest app the adminService mock only reaches the directly
// imported isAddonEnabled (OauthService.mcpEnabled); oauthService.ts reads the
// addon state through its own import that the Nest module graph loads unmocked,
// so it falls back to the real DB row. Drive BOTH so the MCP-enabled state is
// consistent across mcpEnabled() AND validateAuthorizeRequest()/token/revoke.
// Since the admin-1 extraction, both OauthService (injected AddonsService) and
// the legacy oauthService (addons.bridge) resolve the MCP addon from the real
// addons row, so driving the DB row keeps mcpEnabled() AND
// validateAuthorizeRequest()/token/revoke consistent from one source.
function setMcpEnabled(enabled: boolean) {
isAddonEnabledMock.mockReturnValue(enabled);
testDb.prepare(
"INSERT OR REPLACE INTO addons (id, name, description, type, icon, enabled, sort_order) VALUES ('mcp', 'MCP', 'AI assistant integration', 'integration', 'Terminal', ?, 12)"
).run(enabled ? 1 : 0);
@@ -36,7 +36,7 @@ const { isAddonEnabledMock } = vi.hoisted(() => {
const isAddonEnabledMock = vi.fn().mockReturnValue(true);
return { isAddonEnabledMock };
});
vi.mock('../../../src/services/adminService', () => ({
vi.mock('../../../src/nest/addons/addons.bridge', () => ({
isAddonEnabled: isAddonEnabledMock,
getCollabFeatures: vi.fn().mockReturnValue({ chat: true, notes: true, polls: true, whatsnext: true }),
}));
@@ -35,7 +35,7 @@ vi.mock('../../../src/config', () => ({
const { broadcastMock } = vi.hoisted(() => ({ broadcastMock: vi.fn() }));
vi.mock('../../../src/websocket', () => ({ broadcast: broadcastMock }));
vi.mock('../../../src/services/adminService', () => ({
vi.mock('../../../src/nest/addons/addons.bridge', () => ({
isAddonEnabled: vi.fn().mockReturnValue(true),
getCollabFeatures: vi.fn().mockReturnValue({ chat: true, notes: true, polls: true, whatsnext: true }),
}));
@@ -37,7 +37,7 @@ vi.mock('../../../src/config', () => ({
const { broadcastMock } = vi.hoisted(() => ({ broadcastMock: vi.fn() }));
vi.mock('../../../src/websocket', () => ({ broadcast: broadcastMock }));
vi.mock('../../../src/services/adminService', () => ({
vi.mock('../../../src/nest/addons/addons.bridge', () => ({
isAddonEnabled: vi.fn().mockReturnValue(true),
getCollabFeatures: vi.fn().mockReturnValue({ chat: true, notes: true, polls: true, whatsnext: true }),
}));
+1 -1
View File
@@ -34,7 +34,7 @@ vi.mock('../../../src/config', () => ({
const { broadcastMock } = vi.hoisted(() => ({ broadcastMock: vi.fn() }));
vi.mock('../../../src/websocket', () => ({ broadcast: broadcastMock, broadcastToUser: broadcastMock }));
vi.mock('../../../src/services/adminService', async (importOriginal) => {
vi.mock('../../../src/nest/addons/addons.bridge', async (importOriginal) => {
const original = await importOriginal() as Record<string, unknown>;
return { ...original, isAddonEnabled: vi.fn().mockReturnValue(true) };
});
+1 -1
View File
@@ -42,7 +42,7 @@ const { isAddonEnabledMock } = vi.hoisted(() => {
const isAddonEnabledMock = vi.fn().mockReturnValue(true);
return { isAddonEnabledMock };
});
vi.mock('../../../src/services/adminService', () => ({
vi.mock('../../../src/nest/addons/addons.bridge', () => ({
isAddonEnabled: isAddonEnabledMock,
getCollabFeatures: vi.fn().mockReturnValue({ chat: true, notes: true, polls: true, whatsnext: true }),
}));
+1 -1
View File
@@ -42,7 +42,7 @@ vi.mock('../../../src/config', () => ({
const { broadcastMock } = vi.hoisted(() => ({ broadcastMock: vi.fn() }));
vi.mock('../../../src/websocket', () => ({ broadcast: broadcastMock }));
vi.mock('../../../src/services/adminService', () => ({
vi.mock('../../../src/nest/addons/addons.bridge', () => ({
isAddonEnabled: vi.fn().mockReturnValue(true),
getCollabFeatures: vi.fn().mockReturnValue({ chat: true, notes: true, polls: true, whatsnext: true }),
}));
@@ -0,0 +1,61 @@
/**
* addons.bridge delegation — one case per bridged export (the permissions
* bridge-test precedent). The bridge constructs a module-level AddonsService
* over the reinitialize-proof db Proxy, so a real in-memory SQLite exercises
* the byte-identical SQL relocated from services/adminService (`admin-1`),
* including the polarity quirks: isAddonEnabled reads the addons integer
* column, bag tracking is opt-in (=== 'true'), collab flags opt-out
* (!== 'false').
*/
import { describe, it, expect, vi, beforeAll, beforeEach } from 'vitest';
// ── DB setup ──────────────────────────────────────────────────────────────────
// The db/database mock builds a real in-memory SQLite; the test body reaches it
// straight through the mocked `db` export (no hoisted require needed).
vi.mock('../../../src/db/database', async () => {
const { default: Database } = await import('better-sqlite3');
const db = new Database(':memory:');
db.exec('PRAGMA journal_mode = WAL');
db.exec('PRAGMA foreign_keys = ON');
db.exec('PRAGMA busy_timeout = 5000');
return { db, closeDb: () => {}, reinitialize: () => {} };
});
import { db as testDb } from '../../../src/db/database';
import { createTables } from '../../../src/db/schema';
import { runMigrations } from '../../../src/db/migrations';
import { isAddonEnabled, getBagTracking, getCollabFeatures } from '../../../src/nest/addons/addons.bridge';
beforeAll(() => {
createTables(testDb);
runMigrations(testDb);
});
beforeEach(() => {
testDb.prepare("DELETE FROM app_settings WHERE key IN ('bag_tracking_enabled', 'collab_chat_enabled', 'collab_notes_enabled', 'collab_polls_enabled', 'collab_whatsnext_enabled')").run();
});
describe('addons.bridge', () => {
it('isAddonEnabled reflects the addons row and is false for an unknown id', () => {
testDb
.prepare("INSERT OR REPLACE INTO addons (id, name, type, icon, enabled, sort_order) VALUES ('test-addon', 'Test', 'page', 'star', 1, 99)")
.run();
expect(isAddonEnabled('test-addon')).toBe(true);
testDb.prepare('UPDATE addons SET enabled = 0 WHERE id = ?').run('test-addon');
expect(isAddonEnabled('test-addon')).toBe(false);
expect(isAddonEnabled('no-such-addon')).toBe(false);
});
it('getBagTracking is opt-in: absent row is OFF, only the string true enables', () => {
expect(getBagTracking()).toEqual({ enabled: false });
testDb.prepare("INSERT OR REPLACE INTO app_settings (key, value) VALUES ('bag_tracking_enabled', 'true')").run();
expect(getBagTracking()).toEqual({ enabled: true });
});
it('getCollabFeatures is opt-out: absent rows are ON, only the string false disables', () => {
expect(getCollabFeatures()).toEqual({ chat: true, notes: true, polls: true, whatsnext: true });
testDb.prepare("INSERT OR REPLACE INTO app_settings (key, value) VALUES ('collab_polls_enabled', 'false')").run();
expect(getCollabFeatures()).toEqual({ chat: true, notes: true, polls: false, whatsnext: true });
});
});
+80 -16
View File
@@ -10,12 +10,6 @@ vi.mock('../../../src/db/database', () => ({ db: dbMock, closeDb: () => {}, rein
import { db as dbConn } from '../../../src/db/database';
import { DatabaseService } from '../../../src/nest/database/database.service';
const { getBagTracking, getCollabFeatures } = vi.hoisted(() => ({
getBagTracking: vi.fn(() => ({ enabled: false })),
getCollabFeatures: vi.fn(() => ({})),
}));
vi.mock('../../../src/services/adminService', () => ({ getBagTracking, getCollabFeatures }));
const { getPhotoProviderConfig } = vi.hoisted(() => ({ getPhotoProviderConfig: vi.fn(() => ({})) }));
vi.mock('../../../src/services/memories/helpersService', () => ({ getPhotoProviderConfig }));
@@ -25,30 +19,36 @@ function svc() {
return new AddonsService(new DatabaseService(dbConn));
}
// Feed the three reads in order: addons, providers, fields.
function feedReads(addons: unknown[], providers: unknown[], fields: unknown[]) {
// Feed list()'s reads in call order: addons, providers, fields (.all), then the
// collab-features rows (.all) and the bag-tracking row (.get) from app_settings.
function feedReads(
addons: unknown[],
providers: unknown[],
fields: unknown[],
collabRows: unknown[] = [],
bagRow: { value: string } | undefined = undefined,
) {
dbMock._stmt.all
.mockReturnValueOnce(addons)
.mockReturnValueOnce(providers)
.mockReturnValueOnce(fields);
.mockReturnValueOnce(fields)
.mockReturnValueOnce(collabRows);
dbMock._stmt.get.mockReturnValueOnce(bagRow);
}
beforeEach(() => {
vi.clearAllMocks();
dbMock._stmt.all.mockReturnValue([]);
getCollabFeatures.mockReturnValue({});
getBagTracking.mockReturnValue({ enabled: false });
dbMock._stmt.get.mockReturnValue(undefined);
getPhotoProviderConfig.mockReturnValue({});
});
describe('AddonsService.list', () => {
it('returns the collab features and the bag-tracking flag from the admin service', () => {
getCollabFeatures.mockReturnValue({ comments: true });
getBagTracking.mockReturnValue({ enabled: true });
feedReads([], [], []);
it('returns the collab features and the bag-tracking flag from app_settings', () => {
feedReads([], [], [], [{ key: 'collab_chat_enabled', value: 'false' }], { value: 'true' });
const res = svc().list();
expect(res.collabFeatures).toEqual({ comments: true });
expect(res.collabFeatures).toEqual({ chat: false, notes: true, polls: true, whatsnext: true });
expect(res.bagTracking).toBe(true);
expect(res.addons).toEqual([]);
});
@@ -232,3 +232,67 @@ describe('AddonsService.list', () => {
expect((res.addons[1] as { type: string }).type).toBe('photo_provider');
});
});
// Direct coverage of the enablement reads/writers relocated from
// services/adminService (finding `admin-1`). The polarity asymmetry is on
// purpose: bag tracking is opt-in (=== 'true'), collab flags opt-out (!== 'false').
describe('AddonsService addon/feature flags', () => {
it('isAddonEnabled coerces the enabled column (1/0/missing row)', () => {
dbMock._stmt.get.mockReturnValueOnce({ enabled: 1 });
expect(svc().isAddonEnabled('budget')).toBe(true);
dbMock._stmt.get.mockReturnValueOnce({ enabled: 0 });
expect(svc().isAddonEnabled('budget')).toBe(false);
dbMock._stmt.get.mockReturnValueOnce(undefined);
expect(svc().isAddonEnabled('nope')).toBe(false);
});
it('getBagTracking is opt-in: only the literal string true enables it', () => {
dbMock._stmt.get.mockReturnValueOnce({ value: 'true' });
expect(svc().getBagTracking()).toEqual({ enabled: true });
dbMock._stmt.get.mockReturnValueOnce({ value: 'false' });
expect(svc().getBagTracking()).toEqual({ enabled: false });
dbMock._stmt.get.mockReturnValueOnce(undefined); // absent row → OFF
expect(svc().getBagTracking()).toEqual({ enabled: false });
});
it('updateBagTracking persists true/false strings and echoes the flag (ADMIN-SVC-030)', () => {
expect(svc().updateBagTracking(true)).toEqual({ enabled: true });
expect(dbMock._stmt.run).toHaveBeenCalledWith('true');
expect(svc().updateBagTracking(false)).toEqual({ enabled: false });
expect(dbMock._stmt.run).toHaveBeenCalledWith('false');
});
it('getCollabFeatures is opt-out: absent rows default ON, only false disables', () => {
dbMock._stmt.all.mockReturnValueOnce([
{ key: 'collab_chat_enabled', value: 'false' },
{ key: 'collab_polls_enabled', value: 'true' },
]);
expect(svc().getCollabFeatures()).toEqual({ chat: false, notes: true, polls: true, whatsnext: true });
});
it('updateCollabFeatures writes only the provided flags and reports changed (#1414, ADMIN-SVC-070)', () => {
// before-read: all default ON; after-read: chat flipped off → changed
dbMock._stmt.all.mockReturnValueOnce([]).mockReturnValueOnce([{ key: 'collab_chat_enabled', value: 'false' }]);
const first = svc().updateCollabFeatures({ chat: false });
expect(first.changed).toBe(true);
expect(first.features.chat).toBe(false);
expect(dbMock._stmt.run).toHaveBeenCalledTimes(1);
expect(dbMock._stmt.run).toHaveBeenCalledWith('collab_chat_enabled', 'false');
// identical save → before and after read the same → no change, MCP sessions must survive
dbMock._stmt.run.mockClear();
dbMock._stmt.all
.mockReturnValueOnce([{ key: 'collab_chat_enabled', value: 'false' }])
.mockReturnValueOnce([{ key: 'collab_chat_enabled', value: 'false' }]);
const second = svc().updateCollabFeatures({ chat: false });
expect(second.changed).toBe(false);
expect(dbMock._stmt.run).toHaveBeenCalledWith('collab_chat_enabled', 'false');
// undefined flags are not written
dbMock._stmt.run.mockClear();
dbMock._stmt.all.mockReturnValueOnce([]).mockReturnValueOnce([]);
const third = svc().updateCollabFeatures({});
expect(third.changed).toBe(false);
expect(dbMock._stmt.run).not.toHaveBeenCalled();
});
});
@@ -6,12 +6,12 @@ const { dbMock } = vi.hoisted(() => {
});
vi.mock('../../../../src/db/database', () => ({ db: dbMock, closeDb: () => {}, reinitialize: () => {} }));
const { isAddonEnabled } = vi.hoisted(() => ({ isAddonEnabled: vi.fn() }));
vi.mock('../../../../src/services/adminService', () => ({ isAddonEnabled }));
const isAddonEnabled = vi.fn();
import { LlmConfigResolver } from '../../../../src/nest/llm-parse/llm-config.resolver';
import { DatabaseService } from '../../../../src/nest/database/database.service';
import type { SettingsService } from '../../../../src/nest/settings/settings.service';
import type { AddonsService } from '../../../../src/nest/addons/addons.service';
// The resolver injects SettingsService — a stub instance instead of the old
// legacy-module path mock (same behaviors as before the DI move). The
@@ -20,7 +20,8 @@ const getUserSettings = vi.fn(() => ({}) as Record<string, unknown>);
const getDecryptedUserSetting = vi.fn(() => null as string | null);
const settingsStub = { getUserSettings, getDecryptedUserSetting } as unknown as SettingsService;
const resolver = new LlmConfigResolver(settingsStub, new DatabaseService(dbMock as never));
const addonsStub = { isAddonEnabled } as unknown as AddonsService;
const resolver = new LlmConfigResolver(settingsStub, new DatabaseService(dbMock as never), addonsStub);
function setInstanceConfig(config: unknown) {
dbMock._stmt.get.mockReturnValue(config === undefined ? undefined : { config: JSON.stringify(config) });
+3 -2
View File
@@ -26,7 +26,6 @@ const { oauth } = vi.hoisted(() => ({
vi.mock('../../../src/services/oauthService', () => oauth);
const { isAddonEnabled } = vi.hoisted(() => ({ isAddonEnabled: vi.fn() }));
vi.mock('../../../src/services/adminService', () => ({ isAddonEnabled }));
const { getMcpSafeUrl } = vi.hoisted(() => ({ getMcpSafeUrl: vi.fn() }));
vi.mock('../../../src/app-config', async (importOriginal) => {
@@ -35,9 +34,11 @@ vi.mock('../../../src/app-config', async (importOriginal) => {
});
import { OauthService } from '../../../src/nest/oauth/oauth.service';
import type { AddonsService } from '../../../src/nest/addons/addons.service';
import { ADDON_IDS } from '../../../src/addons';
function svc() { return new OauthService(); }
const addonsStub = { isAddonEnabled } as unknown as AddonsService;
function svc() { return new OauthService(addonsStub); }
beforeEach(() => vi.clearAllMocks());
@@ -20,7 +20,7 @@ vi.mock('../../../src/middleware/auth', () => ({ verifyJwtAndLoadUser: h.verifyJ
vi.mock('../../../src/db/database', () => ({ db: { prepare: h.dbPrepare } }));
vi.mock('../../../src/mcp', () => ({ mcpHandler: h.mcpHandler }));
vi.mock('../../../src/mcp/oauthProvider', () => ({ trekOAuthProvider: {}, trekClientsStore: {} }));
vi.mock('../../../src/services/adminService', () => ({ isAddonEnabled: h.isAddonEnabled }));
vi.mock('../../../src/nest/addons/addons.bridge', () => ({ isAddonEnabled: h.isAddonEnabled }));
vi.mock('../../../src/app-config', async (importOriginal) => {
const actual = await importOriginal<typeof import('../../../src/app-config')>();
return { ...actual, getMcpSafeUrl: h.getMcpSafeUrl };
@@ -20,11 +20,13 @@ vi.mock('../../../src/db/database', () => ({
import { db as dbConn } from '../../../src/db/database';
import { DatabaseService } from '../../../src/nest/database/database.service';
vi.mock('../../../src/services/journeyService', () => ({ canAccessJourney }));
vi.mock('../../../src/services/adminService', () => ({ isAddonEnabled }));
vi.mock('../../../src/nest/plugins/kill-switch', () => ({ pluginsEnabled }));
import { JournalEntryRowsController } from '../../../src/nest/plugins/journal-entry-rows.controller';
import type { PluginRuntimeService } from '../../../src/nest/plugins/plugin-runtime.service';
import type { AddonsService } from '../../../src/nest/addons/addons.service';
const addonsStub = { isAddonEnabled } as unknown as AddonsService;
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const req = (id?: number) => ({ user: id === undefined ? undefined : { id } }) as any;
@@ -33,7 +35,7 @@ function controller(invoke: (id: string) => unknown, providers = ['p1']) {
providersOf: vi.fn(() => providers),
invokeHook: vi.fn(async (id: string) => invoke(id)),
} as unknown as PluginRuntimeService;
return { c: new JournalEntryRowsController(runtime, new DatabaseService(dbConn)), runtime };
return { c: new JournalEntryRowsController(runtime, new DatabaseService(dbConn), addonsStub), runtime };
}
const row = (over: Record<string, unknown> = {}) => ({ label: 'Distance', value: '12 km', ...over });
@@ -47,7 +47,6 @@ vi.mock('../../../src/db/database', () => {
vi.mock('../../../src/websocket', () => ({ broadcast, broadcastToUser }));
// Addon gate — flip per test to exercise the "addon disabled" branch of the reads.
const { isAddonEnabled } = vi.hoisted(() => ({ isAddonEnabled: vi.fn(() => true as boolean) }));
vi.mock('../../../src/services/adminService', () => ({ isAddonEnabled }));
// DI-native services are constructor-injected into PluginHostDepsFactory below —
// stub instances instead of path mocks (same behaviors as before the DI move).
const budgetStub = {
@@ -324,7 +323,8 @@ import { DatabaseService } from '../../../src/nest/database/database.service';
// The factory under test, wired exactly like PluginsModule does — but with the
// DI-native domain services replaced by the stubs above. The shim keeps the
// ~45 historical call sites unchanged and supplies a default no-op router.
const factory = new PluginHostDepsFactory(budgetStub, reservationsStub, tagsStub, categoriesStub, todoStub, packingStub, oauthStub, dayNotesStub, assignmentsStub, llmConfigStub, new DatabaseService(mockDb), filesStub, collabStub, vacayStub, daysStub, permissionsStub, exchangeRatesStub);
const addonsStub = { isAddonEnabled } as unknown as import('../../../src/nest/addons/addons.service').AddonsService;
const factory = new PluginHostDepsFactory(budgetStub, reservationsStub, tagsStub, categoriesStub, todoStub, packingStub, oauthStub, dayNotesStub, assignmentsStub, llmConfigStub, new DatabaseService(mockDb), filesStub, collabStub, vacayStub, daysStub, permissionsStub, exchangeRatesStub, addonsStub);
const stubRouter: PluginCallRouter = { callPlugin: async () => undefined, emitPluginEvent: () => {} };
const createRealRpcHost = (id: string, granted: ReadonlySet<string>, router: PluginCallRouter = stubRouter) => factory.create(id, granted, router);
@@ -20,6 +20,7 @@ vi.mock('../../../src/db/database', () => dbMock);
import { db as dbConn } from '../../../src/db/database';
import { DatabaseService } from '../../../src/nest/database/database.service';
import { AuditService } from '../../../src/nest/audit/audit.service';
import { AddonsService } from '../../../src/nest/addons/addons.service';
vi.mock('../../../src/config', () => ({ JWT_SECRET: 'x'.repeat(40), ENCRYPTION_KEY: 'a'.repeat(64), updateJwtSecret: () => {} }));
import { createTables } from '../../../src/db/schema';
@@ -123,7 +124,7 @@ describe('a plugin channel label is bounded by the host', () => {
VALUES ('loud', 'Loud', 'active', 1, '1.0.0', '[]', '[]', ?, '{}')`,
).run(JSON.stringify({ notificationChannel: { title: '🎉'.repeat(5) + 'A'.repeat(500) } }));
const rt = new PluginRuntimeService(new DatabaseService(dbConn), new AuditService(new DatabaseService(dbConn)));
const rt = new PluginRuntimeService(new DatabaseService(dbConn), new AuditService(new DatabaseService(dbConn)), new AddonsService(new DatabaseService(dbConn)));
// Stand the plugin up as a granted, active notificationChannel provider.
(rt as unknown as { supervisor: { running: Map<string, unknown> } }).supervisor.running.set('loud', {
id: 'loud', status: 'active', hooks: ['notificationChannel'], granted: new Set(['hook:notification-channel']),
@@ -58,8 +58,6 @@ import {
listInvites,
createInvite,
deleteInvite,
getBagTracking,
updateBagTracking,
listPackingTemplates,
createPackingTemplate,
updatePackingTemplate,
@@ -78,7 +76,6 @@ import {
checkVersion,
listAddons,
updateAddon,
updateCollabFeatures,
listMcpTokens,
deleteMcpToken,
} from '../../../src/services/adminService';
@@ -309,22 +306,6 @@ describe('Invites', () => {
});
});
// ── Bag tracking ──────────────────────────────────────────────────────────────
describe('Bag tracking', () => {
it('ADMIN-SVC-029 — getBagTracking returns enabled state', () => {
const result = getBagTracking() as any;
expect(typeof result.enabled).toBe('boolean');
});
it('ADMIN-SVC-030 — updateBagTracking persists the value', () => {
updateBagTracking(true);
expect((getBagTracking() as any).enabled).toBe(true);
updateBagTracking(false);
expect((getBagTracking() as any).enabled).toBe(false);
});
});
// ── Packing templates ─────────────────────────────────────────────────────────
describe('Packing templates', () => {
@@ -695,19 +676,6 @@ describe('updateAddon', () => {
});
});
describe('updateCollabFeatures', () => {
it('ADMIN-SVC-070 — reports whether a flag actually flipped (#1414)', () => {
const first = updateCollabFeatures({ chat: false });
expect(first.changed).toBe(true);
expect(first.features.chat).toBe(false);
// identical save → no change, MCP sessions must survive
const second = updateCollabFeatures({ chat: false });
expect(second.changed).toBe(false);
const third = updateCollabFeatures({ chat: true });
expect(third.changed).toBe(true);
});
});
// ── MCP Tokens ────────────────────────────────────────────────────────────────
describe('MCP Tokens', () => {
@@ -7,7 +7,7 @@ import { describe, it, expect, vi, beforeEach } from 'vitest';
*/
vi.mock('../../../src/db/database', () => ({ db: { prepare: vi.fn() } }));
vi.mock('../../../src/services/adminService', () => ({ isAddonEnabled: vi.fn(() => true) }));
vi.mock('../../../src/nest/addons/addons.bridge', () => ({ isAddonEnabled: vi.fn(() => true) }));
vi.mock('../../../src/nest/audit/audit-log.logger', () => ({ logError: vi.fn(), logInfo: vi.fn() }));
vi.mock('../../../src/websocket', () => ({ broadcast: vi.fn() }));
vi.mock('../../../src/nest/reservations/reservations.bridge', () => ({
@@ -37,7 +37,7 @@ vi.mock('../../../src/services/apiKeyCrypto', () => ({
vi.mock('../../../src/mcp/sessionManager', () => ({ revokeUserSessions: vi.fn(), revokeUserSessionsForClient: vi.fn(), sessions: new Map() }));
import { revokeUserSessionsForClient } from '../../../src/mcp/sessionManager';
vi.mock('../../../src/demo/demo-reset', () => ({ saveBaseline: vi.fn() }));
vi.mock('../../../src/services/adminService', () => ({
vi.mock('../../../src/nest/addons/addons.bridge', () => ({
isAddonEnabled: vi.fn().mockReturnValue(true),
getCollabFeatures: vi.fn().mockReturnValue({ chat: true, notes: true, polls: true, whatsnext: true }),
}));
@@ -73,7 +73,7 @@ import {
getConsent,
isConsentSufficient,
} from '../../../src/services/oauthService';
import { isAddonEnabled } from '../../../src/services/adminService';
import { isAddonEnabled } from '../../../src/nest/addons/addons.bridge';
beforeAll(() => {
createTables(testDb);