Files
TREK/server/tests/unit/nest/admin.version-notification.test.ts
T
Maurice d17457de56 fix(storage): delete what a delete or a replace left unnamed right away again
Leaving every replaced cover, place image and deleted journey photo to the
nightly pass kept them publicly fetchable by URL for a week at least, and
for good while deletion was off. Owners now hand the values a delete or a
replace left behind to StorageReleaseService once their write committed.
It asks every registered reference source, with the same parser as the
nightly pass, and deletes at once what no row names any more: an object a
trip copy, a journey or a saved place still shows stays, which the old
inline deletes got wrong.

The release holds the pass's guards (reclaimable categories at their root
only, never an owner marker, never while a restore runs, never with a
required source missing or an overlapping location), never fails the
request and logs at debug. It runs for trip covers (update, upload, trip
delete), collection covers and saved-place images, place images (update,
bulk update, delete), journey covers and journey or gallery photos
(their thumbnail goes with a file that went), avatars (change, delete,
account deletion), trip files (permanent delete, empty trash) and collab
note and chat attachments. A trip file row now goes before its bytes, so a
failing backend no longer fails the delete. The objects of a deleted trip's
places and files are left to the nightly pass: their rows are other
domains'.

PlacesService drops the collection places repository nothing read any
more. Size, warning and boundary baselines follow the shrunk files.
2026-11-01 16:18:21 +01:00

331 lines
14 KiB
TypeScript

/**
* Unit tests for AdminService.checkAndNotifyVersion() — VNOTIF-001 to
* VNOTIF-007, moved from tests/unit/services/versionNotification.test.ts with
* the 2026-08 admin fold, IDs preserved. Kept separate from admin.service.test.ts
* because it stubs global fetch and drives the module-scoped version cache per
* case, which would leak into the ADMIN-SVC-* suite. The notification path runs
* for real against the temp db's notifications table.
*/
import { db as testDb } from '../../../src/db/database';
import { Addons } from '../../../src/db/entities/Addons.entity';
import { AuditLog } from '../../../src/db/entities/AuditLog.entity';
import { DocumentProviders } from '../../../src/db/entities/DocumentProviders.entity';
import { Notifications } from '../../../src/db/entities/Notifications.entity';
import { PhotoProviderFields } from '../../../src/db/entities/PhotoProviderFields.entity';
import { PhotoProviders } from '../../../src/db/entities/PhotoProviders.entity';
import { PushSubscriptions } from '../../../src/db/entities/PushSubscriptions.entity';
import { TripFiles } from '../../../src/db/entities/TripFiles.entity';
import { MaintenanceRepository } from '../../../src/db/repositories/MaintenanceRepository';
import { __clearVersionCacheForTests } from '../../../src/nest/admin/admin.helpers';
import { AdminService } from '../../../src/nest/admin/admin.service';
import { DataPathsService } from '../../../src/nest/app-config/data-paths.service';
import { EphemeralTokenService } from '../../../src/nest/auth-core/ephemeral-token.service';
import { AuthService } from '../../../src/nest/auth/auth.service';
import { PasskeyService } from '../../../src/nest/auth/passkey.service';
import { UserCleanupService } from '../../../src/nest/auth/user-cleanup.service';
import { WebauthnConfigService } from '../../../src/nest/auth/webauthn-config.service';
import { BudgetService } from '../../../src/nest/budget/budget.service';
import { ExchangeRatesService } from '../../../src/nest/budget/exchange-rates.service';
import type { DatabaseBackupStrategy } from '../../../src/nest/database/database-backup.interface';
import { AllowedFileTypesService } from '../../../src/nest/files/allowed-file-types.service';
import { MailerService } from '../../../src/nest/notifications/mailer/mailer.service';
import { NotificationsService } from '../../../src/nest/notifications/notifications.service';
import { PackingService } from '../../../src/nest/packing/packing.service';
import { PermissionsService } from '../../../src/nest/permissions/permissions.service';
import { RealtimeService } from '../../../src/nest/realtime/realtime.service';
import { SettingsService } from '../../../src/nest/settings/settings.service';
import { TripMembershipService } from '../../../src/nest/trip-membership/trip-membership.service';
import { budgetRepoArgs } from '../../helpers/budget-repos';
import { createTestBudgetSettlementsRepo } from '../../helpers/budget-repos';
import { createAdmin } from '../../helpers/factories';
import { countRows, findRow, findRows } from '../../helpers/factories/rows';
import { readAppSetting, setAppSetting } from '../../helpers/factories/settings';
import { createTestBudgetItemsRepo } from '../../helpers/files-repos';
import {
createTestJourneysRepo,
createTestJourneyEntriesRepo,
createTestJourneyContributorsRepo,
} from '../../helpers/journey-repos';
import { createTestJourneyShareTokensRepo } from '../../helpers/journey-share-repos';
import { makeNotificationsService, makeNotificationPreferencesService } from '../../helpers/notifications';
import { createTestPushSubscriptionsRepo } from '../../helpers/notifications-repos';
import { createTestSessionsService } from '../../helpers/sessions';
import {
createTestShareTokensRepo,
createTestPluginsRepo,
createTestPluginUserErasureQueueRepo,
} from '../../helpers/share-repos';
import { createTestAddonsService } from '../../helpers/test-addons';
import { resetTestDb } from '../../helpers/test-db';
import {
createTestUnitOfWork,
createTestAppSettingsRepo,
createTestUsersRepo,
createTestWebauthnCredentialsRepo,
createTestWebauthnChallengesRepo,
createTestInviteTokensRepo,
createTestMcpTokensRepo,
createTestOauthTokensRepo,
createTestPasswordResetTokensRepo,
createTestTripsRepo,
createTestTripMembersRepo,
createTestSettingsRepo,
createTestPlacesRepo,
sharedTestOrm,
} from '../../helpers/test-uow';
import { describe, it, expect, vi, beforeAll, beforeEach, afterAll } from 'vitest';
vi.mock('../../../src/db/database', async () => {
const { createSnapshotTestDb } = await import('../../helpers/db-mock');
const db = createSnapshotTestDb();
const mock = {
db,
closeDb: () => {},
reinitialize: () => {},
getPlaceWithTags: () => null,
canAccessTrip: () => null,
isOwner: () => false,
};
return mock;
});
// Mock MCP to avoid session side-effects
vi.mock('../../../src/mcp', () => ({ revokeUserSessions: vi.fn(), invalidateMcpSessions: vi.fn() }));
vi.mock('../../../src/mcp/sessionManager', () => ({
revokeUserSessions: vi.fn(),
revokeUserSessionsForClient: vi.fn(),
}));
const realtime = new RealtimeService();
let webauthn: WebauthnConfigService;
// Positional and previously wrong: an AtlasService sat in the membership slot
// and the mailer was missing entirely, so `auth` was built with its last four
// collaborators shifted by one. Nothing failed, because the version-check path
// below never reaches them.
let permissions: PermissionsService;
let userCleanup: UserCleanupService;
let auth: AuthService;
let svc: AdminService;
// The demo baseline route's database port; nothing here reaches it.
const databaseBackupStub = {} as unknown as DatabaseBackupStrategy;
beforeAll(async () => {
webauthn = new WebauthnConfigService(await createTestAppSettingsRepo(testDb));
permissions = new PermissionsService(await createTestAppSettingsRepo(testDb), await createTestUnitOfWork(testDb));
userCleanup = new UserCleanupService(
new MaintenanceRepository((await sharedTestOrm(testDb)).em),
new BudgetService(
permissions,
new ExchangeRatesService(),
realtime,
await createTestUnitOfWork(testDb),
...(await budgetRepoArgs(testDb)),
),
await createTestUnitOfWork(testDb),
await createTestUsersRepo(testDb),
await createTestTripMembersRepo(testDb),
await createTestBudgetItemsRepo(testDb),
await createTestBudgetSettlementsRepo(testDb),
await createTestJourneyShareTokensRepo(testDb),
await createTestJourneysRepo(testDb),
await createTestJourneyEntriesRepo(testDb),
await createTestJourneyContributorsRepo(testDb),
await createTestShareTokensRepo(testDb),
await createTestPluginsRepo(testDb),
await createTestPluginUserErasureQueueRepo(testDb),
{ releaseValues: async () => [] } as never,
);
auth = new AuthService(
permissions,
new TripMembershipService(await createTestTripsRepo(testDb), await createTestTripMembersRepo(testDb)),
webauthn,
userCleanup,
new MailerService(
await createTestUsersRepo(testDb),
await createTestSettingsRepo(testDb),
await createTestAppSettingsRepo(testDb),
),
new EphemeralTokenService(),
new AllowedFileTypesService(await createTestAppSettingsRepo(testDb)),
await createTestUnitOfWork(testDb),
await createTestAppSettingsRepo(testDb),
await createTestUsersRepo(testDb),
await createTestInviteTokensRepo(testDb),
await createTestMcpTokensRepo(testDb),
await createTestOauthTokensRepo(testDb),
await createTestWebauthnCredentialsRepo(testDb),
await createTestPasswordResetTokensRepo(testDb),
await createTestPushSubscriptionsRepo(testDb),
await createTestSessionsService(testDb),
);
const t = await sharedTestOrm(testDb);
svc = new AdminService(
await createTestUsersRepo(testDb),
t.repo(AuditLog),
await createTestAppSettingsRepo(testDb),
t.repo(Addons),
t.repo(PhotoProviders),
t.repo(PhotoProviderFields),
t.repo(DocumentProviders),
await createTestMcpTokensRepo(testDb),
await createTestOauthTokensRepo(testDb),
await createTestTripsRepo(testDb),
await createTestPlacesRepo(testDb),
t.repo(TripFiles),
t.repo(PushSubscriptions),
await createTestAddonsService(testDb),
new PasskeyService(
auth,
webauthn,
await createTestUnitOfWork(testDb),
await createTestWebauthnCredentialsRepo(testDb),
await createTestWebauthnChallengesRepo(testDb),
await createTestUsersRepo(testDb),
),
auth,
permissions,
await makeNotificationsService(testDb, realtime),
userCleanup,
realtime,
await createTestUnitOfWork(testDb),
databaseBackupStub,
new DataPathsService(),
await createTestSessionsService(testDb),
);
});
const checkAndNotifyVersion = () => svc.checkAndNotifyVersion();
// Helper: mock the GitHub releases/latest endpoint
function mockGitHubLatest(tagName: string, ok = true): void {
vi.stubGlobal(
'fetch',
vi.fn().mockResolvedValue({
ok,
// fetchGithub reads text() and parses it itself (size cap), so stub both.
text: async () =>
JSON.stringify({ tag_name: tagName, html_url: `https://github.com/liketrek/TREK/releases/tag/${tagName}` }),
json: async () => ({ tag_name: tagName, html_url: `https://github.com/liketrek/TREK/releases/tag/${tagName}` }),
}),
);
}
function mockGitHubFetchFailure(): void {
vi.stubGlobal('fetch', vi.fn().mockRejectedValue(new Error('Network error')));
}
async function getLastNotifiedVersion(): Promise<string | undefined> {
return (await readAppSetting(await sharedTestOrm(testDb), 'last_notified_version')) ?? undefined;
}
async function getNotificationCount(): Promise<number> {
return countRows(await sharedTestOrm(testDb), Notifications);
}
beforeEach(() => {
resetTestDb(testDb);
__clearVersionCacheForTests();
vi.unstubAllGlobals();
});
afterAll(() => {
testDb.close();
vi.unstubAllGlobals();
});
// ─────────────────────────────────────────────────────────────────────────────
// checkAndNotifyVersion
// ─────────────────────────────────────────────────────────────────────────────
describe('checkAndNotifyVersion', () => {
it('VNOTIF-001 — does nothing when no update is available', async () => {
createAdmin(testDb);
// GitHub reports same version as package.json (or older) → update_available: false
const { version } = require('../../../package.json');
mockGitHubLatest(`v${version}`);
await checkAndNotifyVersion();
expect(await getNotificationCount()).toBe(0);
expect(await getLastNotifiedVersion()).toBeUndefined();
});
it('VNOTIF-002 — creates a navigate notification for all admins when update available', async () => {
const { user: admin1 } = createAdmin(testDb);
const { user: admin2 } = createAdmin(testDb);
mockGitHubLatest('v99.0.0');
await checkAndNotifyVersion();
const notifications = await findRows(await sharedTestOrm(testDb), Notifications, {}, { id: 'asc' });
expect(notifications.length).toBe(2);
const recipientIds = notifications.map((n) => n.recipient_id);
expect(recipientIds).toContain(admin1.id);
expect(recipientIds).toContain(admin2.id);
expect(notifications[0].type).toBe('navigate');
expect(notifications[0].scope).toBe('admin');
});
it('VNOTIF-003 — sets last_notified_version in app_settings after notifying', async () => {
createAdmin(testDb);
mockGitHubLatest('v99.1.0');
await checkAndNotifyVersion();
expect(await getLastNotifiedVersion()).toBe('99.1.0');
});
it('VNOTIF-004 — does NOT create duplicate notification if last_notified_version matches', async () => {
createAdmin(testDb);
mockGitHubLatest('v99.2.0');
// First call notifies
await checkAndNotifyVersion();
const countAfterFirst = await getNotificationCount();
expect(countAfterFirst).toBe(1);
// Second call with same version — should not create another
await checkAndNotifyVersion();
expect(await getNotificationCount()).toBe(countAfterFirst);
});
it('VNOTIF-005 — creates new notification when last_notified_version is an older version', async () => {
createAdmin(testDb);
// Simulate having been notified about an older version
await setAppSetting(await sharedTestOrm(testDb), 'last_notified_version', '98.0.0');
mockGitHubLatest('v99.3.0');
await checkAndNotifyVersion();
expect(await getNotificationCount()).toBe(1);
expect(await getLastNotifiedVersion()).toBe('99.3.0');
});
it('VNOTIF-006 — notification has correct type, scope, and navigate_target', async () => {
createAdmin(testDb);
mockGitHubLatest('v99.4.0');
await checkAndNotifyVersion();
const notif = (await findRow(await sharedTestOrm(testDb), Notifications, {}))!;
expect(notif.type).toBe('navigate');
expect(notif.scope).toBe('admin');
expect(notif.navigate_target).toBe('/admin');
expect(notif.title_key).toBe('notif.version_available.title');
expect(notif.text_key).toBe('notif.version_available.text');
expect(notif.navigate_text_key).toBe('notif.action.view_admin');
});
it('VNOTIF-007 — silently handles GitHub API fetch failure (no crash, no notification)', async () => {
createAdmin(testDb);
mockGitHubFetchFailure();
// Should not throw
await expect(checkAndNotifyVersion()).resolves.toBeUndefined();
expect(await getNotificationCount()).toBe(0);
expect(await getLastNotifiedVersion()).toBeUndefined();
});
});