refactor(memories): unified, immich and synology photo sync through repositories

This commit is contained in:
jubnl
2026-09-23 18:38:36 +02:00
parent 5453836a06
commit bceaf4b134
14 changed files with 857 additions and 128 deletions
+22 -6
View File
@@ -68,6 +68,7 @@ import { TripPhotos } from '../../src/db/entities/TripPhotos.entity';
import { TripAlbumLinks } from '../../src/db/entities/TripAlbumLinks.entity';
import { Trips } from '../../src/db/entities/Trips.entity';
import { TrekPhotoCacheMeta } from '../../src/db/entities/TrekPhotoCacheMeta.entity';
import { PhotoProviders } from '../../src/db/entities/PhotoProviders.entity';
import { UnsplashService } from '../../src/nest/unsplash/unsplash.service';
import { UserCleanupService } from '../../src/nest/auth/user-cleanup.service';
import { WebauthnConfigService } from '../../src/nest/auth/webauthn-config.service';
@@ -132,6 +133,7 @@ import {
createTestUsersRepo,
} from './test-uow';
import { createTestOrm } from './test-orm';
import { createTestTripFilesRepo, createTestFileLinksRepo, createTestBudgetItemsRepo } from './files-repos';
import { AppSettings } from '../../src/db/entities/AppSettings.entity';
import { AuditLog } from '../../src/db/entities/AuditLog.entity';
import { Users } from '../../src/db/entities/Users.entity';
@@ -182,7 +184,7 @@ export async function createMcpTestRegistry(): Promise<McpRegistry> {
new UserCleanupService(dbService, budgetService, await createTestUnitOfWork(dbService.connection), usersRepo),
new MailerService(dbService),
new EphemeralTokenService(),
new AllowedFileTypesService(dbService), await createTestUnitOfWork(dbService.connection),
new AllowedFileTypesService(appSettings), await createTestUnitOfWork(dbService.connection),
appSettings, usersRepo, inviteTokensRepo, mcpTokensRepoForAuth, oauthTokensRepo, webauthnCredentialsRepoForAuth, passwordResetTokensRepo,
);
const queryHelpersService = new QueryHelpersService(await createTestTagsRepo(dbService.connection), await createTestPlaceRatingsRepo(dbService.connection), await createTestAssignmentParticipantsRepo(dbService.connection));
@@ -265,10 +267,24 @@ export async function createMcpTestRegistry(): Promise<McpRegistry> {
await createTestUnitOfWork(dbService.connection),
mcpOrm.em,
);
// Plan 3e Task 1 (files): FilesService now also takes uow + the repositories
// its R2 transactions and R12 cross-object trip-scoping guard need. Built
// once and shared by both consumers below (readModelService, FilesMcp)
// rather than reconstructed twice with the same seven-repository tail.
const filesService = new FilesService(
dbService, permissionsService, realtimeService, new EphemeralTokenService(), generalStorage, mcpOrm.em,
await createTestUnitOfWork(dbService.connection),
await createTestTripFilesRepo(dbService.connection),
await createTestFileLinksRepo(dbService.connection),
await createTestReservationsRepo(dbService.connection),
await createTestPlacesRepo(dbService.connection),
await createTestDayAssignmentsRepo(dbService.connection),
await createTestBudgetItemsRepo(dbService.connection),
);
const readModelService = new TripReadModelService(
await createTestTripsRepo(dbService.connection), membersService, daysService, accommodationsService, budgetService,
packingService, reservationsService, collabService, placesService, todoService,
new FilesService(dbService, permissionsService, realtimeService, new EphemeralTokenService(), generalStorage, mcpOrm.em),
filesService,
);
const calendarService = new CalendarService(
reservationsService,
@@ -286,8 +302,8 @@ export async function createMcpTestRegistry(): Promise<McpRegistry> {
// 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 memoriesAccess = new MemoriesAccessService(dbService, mcpOrm.repo(TripPhotos), mcpOrm.repo(TrekPhotos), mcpOrm.repo(TripAlbumLinks), mcpOrm.repo(Trips));
const immichService = new ImmichService(dbService, new AuditService(auditLogRepo, usersRepo), memoriesAccess, generalStorage);
const synologyService = new SynologyService(dbService, memoriesAccess, notificationsStub());
const immichService = new ImmichService(new AuditService(auditLogRepo, usersRepo), memoriesAccess, generalStorage, usersRepo);
const synologyService = new SynologyService(memoriesAccess, notificationsStub(), usersRepo);
const trekPhotos = new TrekPhotoRegistrationService(mcpOrm.repo(TrekPhotos), mcpOrm.repo(TripPhotos), dbService);
const captureBackfill = new PhotoCaptureBackfillService(new PhotoResolverService(trekPhotos, new ThumbnailService(addonsService, generalStorage, mcpOrm.repo(TrekPhotos)), new TrekPhotoCacheService(mcpOrm.repo(TrekPhotoCacheMeta), generalStorage), new PhotoProviderRegistry([new ImmichPhotoProvider(immichService), new SynologyPhotoProvider(synologyService)]), generalStorage), trekPhotos, generalStorage);
return createTestRegistry(
@@ -318,7 +334,7 @@ export async function createMcpTestRegistry(): Promise<McpRegistry> {
authService,
addonsService,
),
new FilesMcp(new FilesService(dbService, permissionsService, realtimeService, new EphemeralTokenService(), generalStorage, mcpOrm.em), authService, guards),
new FilesMcp(filesService, authService, guards),
new AccommodationsMcp(accommodationsService, placesService, authService, guards, await createTestUnitOfWork(dbService.connection)),
new AssignmentsMcp(assignmentsService, daysService, authService, guards),
new CollabMcp(collabService, authService, addonsService, guards),
@@ -335,7 +351,7 @@ export async function createMcpTestRegistry(): Promise<McpRegistry> {
new TransitMcp(new TransitService(new GoogleTransitProvider(dbService, appSettings, usersRepo)), daysService, reservationsService, dbService, authService, guards),
new AtlasMcp(new AtlasService(dbService, await createTestUnitOfWork(dbService.connection)), addonsService, authService),
new JourneyMcp(journeyDomain, new JourneyShareService(dbService, journeyDomain, new SettingsService(await createTestUnitOfWork(dbService.connection), appSettings, await createTestSettingsRepo(dbService.connection))), addonsService, authService, captureBackfill),
new MemoriesMcp(immichService, synologyService, dbService, addonsService),
new MemoriesMcp(immichService, synologyService, addonsService, mcpOrm.repo(PhotoProviders)),
new NotificationsMcp(await makeNotificationsService(dbService, realtimeService), authService),
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),
+14 -2
View File
@@ -89,6 +89,7 @@ import {
import { AppSettings } from '../../src/db/entities/AppSettings.entity';
import { AuditLog } from '../../src/db/entities/AuditLog.entity';
import { Users } from '../../src/db/entities/Users.entity';
import { createTestTripFilesRepo, createTestFileLinksRepo, createTestBudgetItemsRepo } from './files-repos';
/**
* Hand-wired counterpart of the PluginsModule DI graph for no-Nest tests
@@ -112,7 +113,18 @@ export async function createPluginRpcHostFactory(dbs: DatabaseService): Promise<
const queryHelpers = new QueryHelpersService(await createTestTagsRepo(dbs.connection), await createTestPlaceRatingsRepo(dbs.connection), await createTestAssignmentParticipantsRepo(dbs.connection));
const todos = new TodoService(dbs, permissions, realtime, await createTestUnitOfWork(dbs.connection));
const packing = new PackingService(dbs, permissions, realtime, notificationsStub(), await createTestUnitOfWork(dbs.connection));
const files = new FilesService(dbs, permissions, realtime, new EphemeralTokenService(), generalStorage, (await sharedTestOrm(dbs.connection)).em);
// Plan 3e Task 1 (files): FilesService now also takes uow + the repositories
// its R2 transactions and R12 cross-object trip-scoping guard need.
const files = new FilesService(
dbs, permissions, realtime, new EphemeralTokenService(), generalStorage, (await sharedTestOrm(dbs.connection)).em,
await createTestUnitOfWork(dbs.connection),
await createTestTripFilesRepo(dbs.connection),
await createTestFileLinksRepo(dbs.connection),
await createTestReservationsRepo(dbs.connection),
await createTestPlacesRepo(dbs.connection),
await createTestDayAssignmentsRepo(dbs.connection),
await createTestBudgetItemsRepo(dbs.connection),
);
const collab = new CollabService(dbs, permissions, realtime, notificationsStub(), generalStorage, new RateLimitService(), await createTestUnitOfWork(dbs.connection));
const vacay = new VacayService(dbs, realtime, notificationsStub(), await createTestUnitOfWork(dbs.connection));
const days = new DaysService(
@@ -182,7 +194,7 @@ export async function createPluginRpcHostFactory(dbs: DatabaseService): Promise<
new TodoRpc(todos, realtime, guards),
new DayNotesRpc(dayNotes, realtime, guards),
new PackingRpc(packing, realtime, guards),
new FilesRpc(files, realtime, dbs, guards, generalStorage),
new FilesRpc(files, realtime, usersRepo, guards, generalStorage),
new PlacesRpc(places, journey, realtime, guards),
new DaysRpc(days, realtime, guards),
new AccommodationsRpc(accommodations, realtime, guards),
+31 -6
View File
@@ -25,11 +25,14 @@ vi.mock('../../../src/config', () => ({
updateJwtSecret: () => {},
}));
const { decryptMock } = vi.hoisted(() => ({ decryptMock: vi.fn((v: string) => v) }));
const { decryptMock, maybeEncryptMock } = vi.hoisted(() => ({
decryptMock: vi.fn((v: string) => v),
maybeEncryptMock: vi.fn((v: string) => v),
}));
vi.mock('../../../src/nest/common/crypto/apiKeyCrypto', () => ({
decrypt_api_key: decryptMock,
encrypt_api_key: (v: string) => v,
maybe_encrypt_api_key: (v: string) => v,
maybe_encrypt_api_key: maybeEncryptMock,
}));
const { safeFetch, checkSsrf } = vi.hoisted(() => ({ safeFetch: vi.fn(), checkSsrf: vi.fn() }));
@@ -42,19 +45,18 @@ vi.mock('../../../src/utils/ssrfGuard', () => ({
import { createTables } from '../../../src/db/schema';
import { runMigrations } from '../../../src/db/migrations';
import { DatabaseService } from '../../../src/nest/database/database.service';
import { ImmichService } from '../../../src/nest/memories/immich.service';
import type { AuditService } from '../../../src/nest/audit/audit.service';
import type { MemoriesAccessService } from '../../../src/nest/memories/memories-access.service';
import fs from 'node:fs';
import path from 'node:path';
import { makeStorageFixture } from '../../helpers/storage-fixture';
import { createTestUsersRepo } from '../../helpers/test-uow';
const audit = { writeAudit: vi.fn() };
const access = { getAlbumIdFromLink: vi.fn() };
const dbs = new DatabaseService(testDb);
const journeyFx = makeStorageFixture('journey/');
const svc = new ImmichService(dbs, audit as unknown as AuditService, access as unknown as MemoriesAccessService, journeyFx.storage);
let svc: ImmichService;
const USER = 1;
@@ -75,14 +77,17 @@ function upstream(opts: { ok?: boolean; status?: number; json?: unknown; url?: s
};
}
beforeAll(() => {
beforeAll(async () => {
createTables(testDb);
runMigrations(testDb);
const users = await createTestUsersRepo(testDb);
svc = new ImmichService(audit as unknown as AuditService, access as unknown as MemoriesAccessService, journeyFx.storage, users);
});
beforeEach(() => {
vi.clearAllMocks();
decryptMock.mockImplementation((v: string) => v);
maybeEncryptMock.mockImplementation((v: string) => v);
checkSsrf.mockResolvedValue({ allowed: true, isPrivate: false, resolvedIp: '1.2.3.4' });
testDb.prepare('DELETE FROM users').run();
seedUser(USER, 'https://immich.test', 'key-1');
@@ -175,6 +180,26 @@ describe('saveImmichSettings', () => {
expect(checkSsrf).not.toHaveBeenCalled();
expect(await svc.getImmichCredentials(USER)).toBeNull();
});
// R6 — the encrypt call still runs; this file mocks `maybe_encrypt_api_key`
// as identity everywhere else (so cases above can assert on the plaintext
// round-trip), so this one case swaps in the REAL crypto for the duration
// of a single call and reads the raw column back — proving
// `UsersRepository.setImmichSettings` never bypasses the service's encrypt
// step. `beforeEach` restores the identity stub for every other case.
it('IMMICH-051 (R6): the stored immich_api_key is the encrypted envelope, never the plaintext', async () => {
const real = await vi.importActual<typeof import('../../../src/nest/common/crypto/apiKeyCrypto')>(
'../../../src/nest/common/crypto/apiKeyCrypto',
);
maybeEncryptMock.mockImplementation(real.maybe_encrypt_api_key);
const plaintext = 'synthetic-test-immich-key-001';
await svc.saveImmichSettings(USER, 'https://immich.test', plaintext, null);
const row = testDb.prepare('SELECT immich_api_key FROM users WHERE id = ?').get(USER) as { immich_api_key: string };
expect(row.immich_api_key).not.toBe(plaintext);
expect(row.immich_api_key.startsWith('enc:v1:')).toBe(true);
});
});
describe('testConnection', () => {
@@ -27,11 +27,14 @@ vi.mock('../../../src/config', () => ({
updateJwtSecret: () => {},
}));
const { decryptMock } = vi.hoisted(() => ({ decryptMock: vi.fn((v: string) => v) }));
const { decryptMock, maybeEncryptMock } = vi.hoisted(() => ({
decryptMock: vi.fn((v: string) => v),
maybeEncryptMock: vi.fn((v: string) => v),
}));
vi.mock('../../../src/nest/common/crypto/apiKeyCrypto', () => ({
decrypt_api_key: decryptMock,
encrypt_api_key: (v: string) => v,
maybe_encrypt_api_key: (v: string) => v,
maybe_encrypt_api_key: maybeEncryptMock,
}));
const { safeFetch, checkSsrf, SsrfBlockedError } = vi.hoisted(() => {
@@ -46,13 +49,13 @@ vi.mock('../../../src/utils/ssrfGuard', () => ({
import { createTables } from '../../../src/db/schema';
import { runMigrations } from '../../../src/db/migrations';
import { DatabaseService } from '../../../src/nest/database/database.service';
import { SynologyService } from '../../../src/nest/memories/synology.service';
import type { MemoriesAccessService } from '../../../src/nest/memories/memories-access.service';
import { notificationsStub } from '../../helpers/notifications';
import { createTestUsersRepo } from '../../helpers/test-uow';
const access = { getAlbumLinkForSync: vi.fn(), updateSyncTimeForAlbumLink: vi.fn() };
const svc = new SynologyService(new DatabaseService(testDb), access as unknown as MemoriesAccessService, notificationsStub());
let svc: SynologyService;
const USER = 1;
@@ -76,14 +79,17 @@ function httpError(status: number) {
return { ok: false, status, headers: { get: () => null }, json: async () => ({}), arrayBuffer: async () => Buffer.from('x') };
}
beforeAll(() => {
beforeAll(async () => {
createTables(testDb);
runMigrations(testDb);
const users = await createTestUsersRepo(testDb);
svc = new SynologyService(access as unknown as MemoriesAccessService, notificationsStub(), users);
});
beforeEach(() => {
vi.clearAllMocks();
decryptMock.mockImplementation((v: string) => v);
maybeEncryptMock.mockImplementation((v: string) => v);
checkSsrf.mockResolvedValue({ allowed: true, isPrivate: false, resolvedIp: '1.2.3.4' });
testDb.prepare('DELETE FROM users').run();
seedUser(USER);
@@ -223,6 +229,27 @@ describe('updateSynologySettings', () => {
expect(row.synology_password).toBe('pw');
expect(row.synology_url).toBe('https://nas2.test');
});
// R6 — this file mocks `maybe_encrypt_api_key` as identity elsewhere (so
// the cases above can assert on the plaintext round-trip); this one case
// swaps in the REAL crypto for the duration of a single call and reads the
// raw column back — proving `UsersRepository.setSynologySettings` never
// bypasses the service's encrypt step. `beforeEach` restores the identity
// stub for every other case.
it('SYNO-U032 (R6): the stored synology_password is the encrypted envelope, never the plaintext', async () => {
safeFetch.mockResolvedValue(api({ sid: 's' }));
const real = await vi.importActual<typeof import('../../../src/nest/common/crypto/apiKeyCrypto')>(
'../../../src/nest/common/crypto/apiKeyCrypto',
);
maybeEncryptMock.mockImplementation(real.maybe_encrypt_api_key);
const plaintext = 'synthetic-test-synology-pw-001';
await svc.updateSynologySettings(USER, 'https://nas3.test', 'ada', plaintext);
const row = testDb.prepare('SELECT synology_password FROM users WHERE id = ?').get(USER) as { synology_password: string };
expect(row.synology_password).not.toBe(plaintext);
expect(row.synology_password.startsWith('enc:v1:')).toBe(true);
});
});
describe('testSynologyConnection', () => {
@@ -36,7 +36,6 @@ vi.mock('../../../src/config', () => ({
ENCRYPTION_KEY: 'a1b2c3d4e5f6a7b8c9d0e1f2a3b4c5d6a7b8c9d0e1f2a3b4c5d6a7b8c9d0e1f2',
updateJwtSecret: () => {},
}));
vi.mock('../../../src/websocket', () => ({ broadcast: vi.fn() }));
import { createTables } from '../../../src/db/schema';
import { runMigrations } from '../../../src/db/migrations';
@@ -51,16 +50,43 @@ import { TrekPhotos } from '../../../src/db/entities/TrekPhotos.entity';
import { TripPhotos } from '../../../src/db/entities/TripPhotos.entity';
import { TripAlbumLinks } from '../../../src/db/entities/TripAlbumLinks.entity';
import { Trips } from '../../../src/db/entities/Trips.entity';
import { PhotoProviders } from '../../../src/db/entities/PhotoProviders.entity';
import type { ServiceResult } from '../../../src/nest/memories/memories.helpers';
import { DatabaseService } from '../../../src/nest/database/database.service';
import type { ImmichService } from '../../../src/nest/memories/immich.service';
import type { SynologyService } from '../../../src/nest/memories/synology.service';
import type { RealtimeService } from '../../../src/nest/realtime/realtime.service';
import type { TripPhotosRepository } from '../../../src/db/repositories/TripPhotos.repository';
import type { TripAlbumLinksRepository } from '../../../src/db/repositories/TripAlbumLinks.repository';
import type { UsersRepository } from '../../../src/db/repositories/Users.repository';
import { notificationsStub } from '../../helpers/notifications';
import { createTestUnitOfWork, sharedTestOrm } from '../../helpers/test-uow';
import { createTestUnitOfWork, sharedTestOrm, createTestUsersRepo } from '../../helpers/test-uow';
// The album-sync paths are the providers' half and have their own suites; these
// cases never reach them, so stubs keep the graph small.
const dbs = new DatabaseService(testDb);
let svc: UnifiedMemoriesService;
const realtimeMock = { broadcast: vi.fn() };
let tripPhotosRepo: TripPhotosRepository;
let tripAlbumLinksRepo: TripAlbumLinksRepository;
let usersRepo: UsersRepository;
// Narrows the `ServiceResult` discriminated union without an `as any` cast —
// used by the new (Task 7) cases below only; the pre-existing cases above
// keep their original `(result as any)` shape unchanged.
function expectFailure<T>(result: ServiceResult<T>): { message: string; status: number } {
// `'error' in result`, not `result.success` — discriminant narrowing over a
// union with a generic member (`{ success: true; data: T }`) doesn't
// resolve here (a TS control-flow limitation on generic discriminated
// unions); `in` narrows correctly, the same idiom `handleServiceResult`
// (`memories.helpers.ts`) already uses.
if (!('error' in result)) throw new Error('expected a ServiceResult failure, got success');
return result.error;
}
function expectSuccess<T>(result: ServiceResult<T>): T {
if ('error' in result) throw new Error(`expected a ServiceResult success, got: ${result.error.message}`);
return result.data;
}
// Legacy free-function names forwarding to the service, so the moved cases read
// as before. Typed forwarders rather than `.bind` aliases: a bound alias is
@@ -86,6 +112,9 @@ beforeAll(async () => {
const t = await sharedTestOrm(testDb);
const real = new DatabaseService(testDb, t.em);
vi.spyOn(dbs, 'canAccessTrip').mockImplementation((...a) => real.canAccessTrip(...a));
tripPhotosRepo = t.repo(TripPhotos);
tripAlbumLinksRepo = t.repo(TripAlbumLinks);
usersRepo = await createTestUsersRepo(testDb);
svc = new UnifiedMemoriesService(
dbs,
new TrekPhotoRegistrationService(t.repo(TrekPhotos), t.repo(TripPhotos), dbs),
@@ -95,6 +124,12 @@ beforeAll(async () => {
notificationsStub(),
await createTestAddonsService(testDb, dbs),
await createTestUnitOfWork(testDb),
realtimeMock as unknown as RealtimeService,
t.repo(PhotoProviders),
tripPhotosRepo,
tripAlbumLinksRepo,
usersRepo,
t.repo(Trips),
);
});
@@ -104,6 +139,7 @@ beforeEach(() => {
testDb.prepare('UPDATE photo_providers SET enabled = 1').run();
// Providers only count as enabled under an enabled journey addon (migration 84 seeds it off).
setAddonEnabled(testDb, ADDON_IDS.JOURNEY, true);
realtimeMock.broadcast.mockClear();
});
afterAll(() => {
@@ -256,6 +292,20 @@ describe('createTripAlbumLink', () => {
expect(result.success).toBe(false);
expect((result as any).error.status).toBe(400);
});
it('MEM-UNIFIED-019: UM7 insertIgnore reports the 409 "already linked" on a re-link (duplicate-ignore, not a crash)', async () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
const first = await createTripAlbumLink(String(trip.id), user.id, 'immich', 'album-dup-1', 'First Name');
expectSuccess(first);
const second = await createTripAlbumLink(String(trip.id), user.id, 'immich', 'album-dup-1', 'Second Name');
expect(expectFailure(second).status).toBe(409);
const rows = testDb.prepare('SELECT COUNT(*) as c FROM trip_album_links WHERE trip_id = ? AND user_id = ?').get(trip.id, user.id) as { c: number };
expect(rows.c).toBe(1);
});
});
// ── removeAlbumLink ───────────────────────────────────────────────────────────
@@ -266,4 +316,173 @@ describe('removeAlbumLink', () => {
expect(result.success).toBe(false);
expect((result as any).error.status).toBe(404);
});
it('MEM-UNIFIED-020: UM8/UM9/UM10 — the transaction removes the link and every trip_photos row it owned', async () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
const linked = await createTripAlbumLink(String(trip.id), user.id, 'immich', 'album-rm-1', 'To Remove');
expect(linked.success).toBe(true);
const linkRow = testDb.prepare('SELECT id FROM trip_album_links WHERE trip_id = ? AND user_id = ? AND album_id = ?').get(trip.id, user.id, 'album-rm-1') as { id: number };
await addTripPhotos(String(trip.id), user.id, true, [{ provider: 'immich', asset_ids: ['asset-rm-1'] }], 'sid-6', String(linkRow.id));
const photoRow = testDb.prepare('SELECT photo_id FROM trip_photos WHERE trip_id = ? AND album_link_id = ?').get(trip.id, linkRow.id) as { photo_id: number };
expect(photoRow).toBeDefined();
const result = await removeAlbumLink(String(trip.id), String(linkRow.id), user.id);
expect(result.success).toBe(true);
const remainingLink = testDb.prepare('SELECT * FROM trip_album_links WHERE id = ?').get(linkRow.id);
expect(remainingLink).toBeUndefined();
const remainingPhoto = testDb.prepare('SELECT * FROM trip_photos WHERE trip_id = ? AND album_link_id = ?').get(trip.id, linkRow.id);
expect(remainingPhoto).toBeUndefined();
// The orphaned trek_photos row is reclaimed too (TrekPhotoRegistrationService.deleteIfOrphan, PH10/PH11).
const orphan = testDb.prepare('SELECT * FROM trek_photos WHERE id = ?').get(photoRow.photo_id);
expect(orphan).toBeUndefined();
});
});
// ── UM2/UM3 parity — full-key toEqual against the legacy statement run raw ────
describe('listTripPhotos / listTripAlbumLinks — parity', () => {
it('PARITY-UM2: matches the legacy join, enabled/disabled providers mixed', async () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
// A photo under a disabled provider must not appear — the legacy `tkp.provider IN (...)`
// only ever names the enabled set.
testDb.prepare(
'INSERT OR IGNORE INTO photo_providers (id, name, description, icon, enabled, sort_order) VALUES (?, ?, ?, ?, 0, 50)'
).run('disabled-x', 'Disabled X', 'desc', 'Image');
const enabledPhoto = testDb.prepare('INSERT INTO trek_photos (provider, asset_id, owner_id) VALUES (?, ?, ?)').run('immich', 'asset-enabled', user.id).lastInsertRowid as number;
const disabledPhoto = testDb.prepare('INSERT INTO trek_photos (provider, asset_id, owner_id) VALUES (?, ?, ?)').run('disabled-x', 'asset-disabled', user.id).lastInsertRowid as number;
testDb.prepare('INSERT INTO trip_photos (trip_id, user_id, photo_id, shared) VALUES (?, ?, ?, 1)').run(trip.id, user.id, enabledPhoto);
testDb.prepare('INSERT INTO trip_photos (trip_id, user_id, photo_id, shared) VALUES (?, ?, ?, 1)').run(trip.id, user.id, disabledPhoto);
const enabledProviders = testDb.prepare('SELECT id FROM photo_providers WHERE enabled = 1').all().map((r: { id: string }) => r.id);
const oracle = testDb.prepare(`
SELECT tp.photo_id, tkp.asset_id, tkp.provider, tp.user_id, tp.shared, tp.added_at,
u.username, u.avatar
FROM trip_photos tp
JOIN trek_photos tkp ON tkp.id = tp.photo_id
JOIN users u ON tp.user_id = u.id
WHERE tp.trip_id = ?
AND (tp.user_id = ? OR tp.shared = 1)
AND tkp.provider IN (${enabledProviders.map(() => '?').join(',')})
ORDER BY tp.added_at ASC
`).all(trip.id, user.id, ...enabledProviders);
const result = await listTripPhotos(String(trip.id), user.id);
const data = expectSuccess(result);
expect(data).toEqual(oracle);
expect(data.some((r: { provider: string }) => r.provider === 'disabled-x')).toBe(false);
});
it('PARITY-UM3: matches the legacy join for an album link with a passphrase', async () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
await createTripAlbumLink(String(trip.id), user.id, 'synologyphotos', 'album-p1', 'Passphrase Album', 'secret-pass');
const enabledProviders = testDb.prepare('SELECT id FROM photo_providers WHERE enabled = 1').all().map((r: { id: string }) => r.id);
const oracle = testDb.prepare(`
SELECT tal.id,
tal.trip_id,
tal.user_id,
tal.provider,
tal.album_id,
tal.album_name,
tal.sync_enabled,
tal.last_synced_at,
tal.created_at,
u.username
FROM trip_album_links tal
JOIN users u ON tal.user_id = u.id
WHERE tal.trip_id = ?
AND tal.provider IN (${enabledProviders.map(() => '?').join(',')})
ORDER BY tal.created_at ASC
`).all(trip.id, ...enabledProviders);
const result = await listTripAlbumLinks(String(trip.id), user.id);
const data = expectSuccess(result);
expect(data).toEqual(oracle);
// The passphrase column round-trips through the repository encrypted, same
// as it always was — not part of this listing's SELECT list either way.
expect(data[0].album_id).toBe('album-p1');
});
});
// ── Access-check mutation proof — a non-member (not "trip missing") ───────────
describe('access check — non-member refusal', () => {
it('MEM-UNIFIED-014: a real trip, a real non-member user, still 404s (red if the gate is loosened)', async () => {
const { user: owner } = createUser(testDb);
const { user: stranger } = createUser(testDb);
const trip = createTrip(testDb, owner.id);
const result = await listTripPhotos(String(trip.id), stranger.id);
expect(expectFailure(result).status).toBe(404);
});
});
// ── R8 — RealtimeService.broadcast pins ────────────────────────────────────────
describe('R8 — injected RealtimeService, not the legacy module broadcast', () => {
it('MEM-UNIFIED-015: addTripPhotos calls this.realtime.broadcast with the exact legacy event/payload/arity', async () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
const result = await addTripPhotos(String(trip.id), user.id, false, [{ provider: 'immich', asset_ids: ['asset-r8-1'] }], 'sid-1');
expect(expectSuccess(result).added).toBe(1);
expect(realtimeMock.broadcast).toHaveBeenCalledTimes(1);
expect(realtimeMock.broadcast).toHaveBeenCalledWith(String(trip.id), 'memories:updated', { userId: user.id }, 'sid-1');
});
it('MEM-UNIFIED-016: setTripPhotoSharing calls this.realtime.broadcast', async () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
const photoId = testDb.prepare('INSERT INTO trek_photos (provider, asset_id, owner_id) VALUES (?, ?, ?)').run('immich', 'asset-r8-2', user.id).lastInsertRowid as number;
testDb.prepare('INSERT INTO trip_photos (trip_id, user_id, photo_id, shared) VALUES (?, ?, ?, 0)').run(trip.id, user.id, photoId);
const result = await setTripPhotoSharing(String(trip.id), user.id, photoId, true, 'sid-2');
expect(result.success).toBe(true);
expect(realtimeMock.broadcast).toHaveBeenCalledTimes(1);
expect(realtimeMock.broadcast).toHaveBeenCalledWith(String(trip.id), 'memories:updated', { userId: user.id }, 'sid-2');
const row = testDb.prepare('SELECT shared FROM trip_photos WHERE trip_id = ? AND user_id = ? AND photo_id = ?').get(trip.id, user.id, photoId) as { shared: number };
expect(row.shared).toBe(1);
});
it('MEM-UNIFIED-018: UM4 insertIgnore reports 0 added on a re-add of the same photo (duplicate-ignore, not a crash)', async () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
const first = await addTripPhotos(String(trip.id), user.id, false, [{ provider: 'immich', asset_ids: ['asset-dup-1'] }], 'sid-4');
expect(expectSuccess(first).added).toBe(1);
realtimeMock.broadcast.mockClear();
const second = await addTripPhotos(String(trip.id), user.id, false, [{ provider: 'immich', asset_ids: ['asset-dup-1'] }], 'sid-5');
expect(expectSuccess(second).added).toBe(0);
const rows = testDb.prepare('SELECT COUNT(*) as c FROM trip_photos WHERE trip_id = ? AND user_id = ?').get(trip.id, user.id) as { c: number };
expect(rows.c).toBe(1);
});
it('MEM-UNIFIED-017: removeTripPhoto calls this.realtime.broadcast and deletes the row', async () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
const photoId = testDb.prepare('INSERT INTO trek_photos (provider, asset_id, owner_id) VALUES (?, ?, ?)').run('immich', 'asset-r8-3', user.id).lastInsertRowid as number;
testDb.prepare('INSERT INTO trip_photos (trip_id, user_id, photo_id, shared) VALUES (?, ?, ?, 0)').run(trip.id, user.id, photoId);
const result = await removeTripPhoto(String(trip.id), user.id, photoId, 'sid-3');
expect(result.success).toBe(true);
expect(realtimeMock.broadcast).toHaveBeenCalledTimes(1);
expect(realtimeMock.broadcast).toHaveBeenCalledWith(String(trip.id), 'memories:updated', { userId: user.id }, 'sid-3');
const row = testDb.prepare('SELECT * FROM trip_photos WHERE trip_id = ? AND user_id = ? AND photo_id = ?').get(trip.id, user.id, photoId);
expect(row).toBeUndefined();
});
});