From 407e50c29559f4dbc6639205383114673ce8e95a Mon Sep 17 00:00:00 2001 From: jubnl Date: Wed, 23 Sep 2026 23:09:13 +0200 Subject: [PATCH] refactor(journey): public share links, TREK Studio books and the journal facades through repositories --- .../repositories/JourneyBooks.repository.ts | 103 ++++- .../JourneyShareTokens.repository.ts | 369 +++++++++++++++++- server/src/nest/journey/journal-rpc.module.ts | 9 +- server/src/nest/journey/journal.rpc.ts | 12 +- .../src/nest/journey/journey-book.service.ts | 85 ++-- .../src/nest/journey/journey-domain.module.ts | 41 +- .../src/nest/journey/journey-share.service.ts | 119 +++--- server/src/nest/journey/journey.module.ts | 12 +- server/src/nest/journey/journey.service.ts | 16 +- server/tests/helpers/journey-share-repos.ts | 26 ++ server/tests/helpers/mcp-test-controllers.ts | 17 +- server/tests/helpers/plugin-host.ts | 12 +- .../unit/nest/journey-book.service.test.ts | 50 ++- .../unit/nest/journey-share.service.test.ts | 272 ++++++++++++- .../unit/plugins/addon-gates.rpc.test.ts | 4 +- .../unit/plugins/journal-photo.rpc.test.ts | 4 +- 16 files changed, 994 insertions(+), 157 deletions(-) create mode 100644 server/tests/helpers/journey-share-repos.ts diff --git a/server/src/db/repositories/JourneyBooks.repository.ts b/server/src/db/repositories/JourneyBooks.repository.ts index 37a9575cd..e7f3489aa 100644 --- a/server/src/db/repositories/JourneyBooks.repository.ts +++ b/server/src/db/repositories/JourneyBooks.repository.ts @@ -1,4 +1,105 @@ +import { columnIncrementedBy, currentTimestamp } from '../dialect/sql-functions'; import type { JourneyBooks } from '../entities/JourneyBooks.entity'; import { TrekRepository } from './_shared/trek-repository'; -export class JourneyBooksRepository extends TrekRepository {} +/** JB1's list-view row — `listBooks`, no `document`. */ +export interface JourneyBookSummaryRow { + id: number; + journey_id: number; + title: string; + version: number; + updated_at: string | null; + updated_by: number | null; +} + +/** JB2/JB3/JB7's full-row shape (adds `document`). */ +export interface JourneyBookRow extends JourneyBookSummaryRow { + document: string; +} + +/** + * `journey_books` — TREK Studio books (Plan 3g Task 3, R2). JB5's save is + * the one place in this whole plan where "convert the statement" and + * "preserve the exact control-flow contract" are the same instruction: it + * stays ONE conditional `nativeUpdate` returning the affected-row count, + * never a MikroORM `@OptimisticLock`/version-decorated entity path — the + * service branches on `changes === 0` and re-reads for the `{conflict}` + * response, exactly as today. + */ +export class JourneyBooksRepository extends TrekRepository { + /** JB1 — `listBooks`: `SELECT id, journey_id, title, version, updated_at, updated_by FROM journey_books WHERE journey_id=? ORDER BY updated_at DESC, id DESC`. */ + async listForJourney(journeyId: number): Promise { + return await this.qb('jb') + .select(['jb.id', 'jb.journey', 'jb.title', 'jb.version', 'jb.updated_at', 'jb.updatedByRef']) + .where({ journey: journeyId }) + .orderBy({ updated_at: 'desc', id: 'desc' }) + .execute('all', false); + } + + /** + * JB2/JB3 — `getBook`'s full read and `saveBook`'s pre-check share the + * identical `WHERE journey_id=? ORDER BY id ASC LIMIT 1`, differing only + * in column list (JB3 reads just `id`/`version`); this returns JB2's wider + * shape and `saveBook` reads the two fields it needs off it, rather than + * hand-duplicating a second near-identical statement (see + * task-3-report.md). + */ + async findFirstForJourney(journeyId: number): Promise { + return await this.qb('jb') + .select(['jb.id', 'jb.journey', 'jb.title', 'jb.document', 'jb.version', 'jb.updated_at', 'jb.updatedByRef']) + .where({ journey: journeyId }) + .orderBy({ id: 'asc' }) + .limit(1) + .execute('get', false); + } + + /** JB7 — `byId` (called from JB4's insert result and JB5's success/conflict paths): `SELECT id, journey_id, title, document, version, updated_at, updated_by FROM journey_books WHERE id=?`. */ + async findById(id: number): Promise { + return await this.qb('jb') + .select(['jb.id', 'jb.journey', 'jb.title', 'jb.document', 'jb.version', 'jb.updated_at', 'jb.updatedByRef']) + .where({ id }) + .execute('get', false); + } + + /** JB4 — `saveBook`'s first write (no existing row): `INSERT INTO journey_books (journey_id, title, document, version, created_by, updated_by, updated_at) VALUES (?, ?, ?, 1, ?, ?, CURRENT_TIMESTAMP)`. */ + async insertBook(journeyId: number, title: string, document: string, userId: number): Promise { + const platform = this.getEntityManager().getPlatform(); + return await this.insert({ + journey: journeyId, + title, + document, + version: 1, + createdByRef: userId, + updatedByRef: userId, + updated_at: currentTimestamp(platform), + }); + } + + /** + * JB5 (R2) — the optimistic-concurrency save: `UPDATE journey_books SET + * title=?, document=?, version=version+1, updated_by=?, + * updated_at=CURRENT_TIMESTAMP WHERE id=? AND version=?`, ONE conditional + * statement (the version check stays IN the WHERE clause, never a + * read-then-compare), returning the affected-row count. `changes === 0` + * means a conflict — the service re-reads via {@link findById} for the + * `{conflict}` response, it does not throw. + */ + async casUpdate(id: number, baseVersion: number, data: { title: string; document: string; updatedBy: number }): Promise { + const platform = this.getEntityManager().getPlatform(); + return await this.nativeUpdate( + { id, version: baseVersion }, + { + title: data.title, + document: data.document, + version: columnIncrementedBy(platform, 'version', 1), + updatedByRef: data.updatedBy, + updated_at: currentTimestamp(platform), + }, + ); + } + + /** JB6 — `deleteBook`: `DELETE FROM journey_books WHERE journey_id=?`, returning the affected-row count so the service can report whether anything was removed. */ + async deleteByJourneyId(journeyId: number): Promise { + return await this.nativeDelete({ journey: journeyId }); + } +} diff --git a/server/src/db/repositories/JourneyShareTokens.repository.ts b/server/src/db/repositories/JourneyShareTokens.repository.ts index 14589c483..dbe6b1791 100644 --- a/server/src/db/repositories/JourneyShareTokens.repository.ts +++ b/server/src/db/repositories/JourneyShareTokens.repository.ts @@ -1,4 +1,371 @@ +import type { Platform } from '@mikro-orm/core'; +import type { ExpressionBuilder } from 'kysely'; +import type { JourneyEntry } from '../../types'; +import { concatKysely, unixEpochToIsoKysely } from '../dialect/sql-functions'; import type { JourneyShareTokens } from '../entities/JourneyShareTokens.entity'; import { TrekRepository } from './_shared/trek-repository'; -export class JourneyShareTokensRepository extends TrekRepository {} +/** JS1's narrow projection — `createOrUpdateJourneyShareLink`'s existing-link read. */ +export interface JourneyShareLinkFlagsRow { + token: string; + share_timeline: number | null; + share_gallery: number | null; + share_map: number | null; + newest_first: number; +} + +/** JS4/JS11's full-row shape (`getJourneyShareLink`, `getPublicJourney`'s entrypoint read). */ +export interface JourneyShareTokenRow { + id: number; + journey_id: number; + token: string; + created_by: number; + share_timeline: number | null; + share_gallery: number | null; + share_map: number | null; + created_at: string | null; + newest_first: number; +} + +/** JS6/JS9's narrow token-lookup projection — the anonymous photo/asset validators. */ +export interface JourneyShareTokenAccessRow { + journey_id: number; + share_gallery: number | null; +} + +/** JS7 — the photo-validation join's row (`journey_photos` + `trek_photos`). */ +export interface JourneyPublicPhotoValidationRow { + photo_id: number; + owner_id: number | null; + journey_id: number; +} + +/** JS10 — the asset-validation join's row (`journey_photos` + `trek_photos` + `journeys`). */ +export interface JourneyPublicAssetValidationRow { + owner_id: number | null; + journey_owner_id: number; +} + +/** JS14 — the public per-entry photo read. Column-for-column identical to `journey-domain.service.ts`'s `JP_SELECT` (only the `trek_photos` join alias differs, `tkp` vs `tp`) — see task-3-report.md for the reuse decision. */ +export interface JourneyPublicEntryPhotoRow { + id: number; + entry_id: number; + photo_id: number; + caption: string | null; + sort_order: number | null; + shared: number; + created_at: number; + provider: string; + asset_id: string | null; + owner_id: number | null; + file_path: string | null; + thumbnail_path: string | null; + width: number | null; + height: number | null; + media_type: string | null; + duration_ms: number | null; + taken_at: string | null; + lat: number | null; + lng: number | null; +} + +/** JS15 — the public gallery read (`GALLERY_SELECT` shape, `GALLERY_CHRONOLOGICAL_ORDER` applied). */ +export interface JourneyPublicGalleryRow { + id: number; + journey_id: number; + photo_id: number; + caption: string | null; + shared: number; + sort_order: number | null; + created_at: number; + provider: string; + asset_id: string | null; + owner_id: number | null; + file_path: string | null; + thumbnail_path: string | null; + width: number | null; + height: number | null; + media_type: string | null; + duration_ms: number | null; + taken_at: string | null; + lat: number | null; + lng: number | null; +} + +/** + * The narrow Kysely shape the public-surface methods below need. `journeys`, + * `journey_photos`, `journey_entry_photos`, `journey_entries` and + * `trek_photos` are NOT this repository's own tables — Task 2's + * `JourneyPhotosRepository`/`JourneyEntryPhotosRepository`/ + * `JourneyEntriesRepository` own them, but Task 2 was still mid-flight + * (uncommitted) when this task ran, so per the brief's own fallback + * instruction these six public/anonymous statements (JS7/JS10/JS13/JS14/ + * JS15, plus JS8/JS12 which reuse Task 1's already-stable + * `JourneysRepository.findById` instead) get a typed Kysely read here + * rather than depending on an in-flight repository. Flagged in + * task-3-report.md for a possible later relocation once Task 2 lands. + */ +interface JourneyPublicKyselyDB { + journey_entries: { + id: number; + journey_id: number; + source_trip_id: number | null; + source_place_id: number | null; + source_assignment_id: number | null; + author_id: number; + type: string; + title: string | null; + story: string | null; + entry_date: string; + entry_time: string | null; + location_name: string | null; + location_lat: number | null; + location_lng: number | null; + mood: string | null; + weather: string | null; + tags: string | null; + pros_cons: string | null; + visibility: string | null; + sort_order: number | null; + created_at: number; + updated_at: number; + stats_excluded: number; + dismissed: number; + country_code: string | null; + }; + journey_photos: { + id: number; + journey_id: number; + photo_id: number; + caption: string | null; + shared: number; + sort_order: number | null; + created_at: number; + }; + journey_entry_photos: { + entry_id: number; + journey_photo_id: number; + sort_order: number | null; + }; + journeys: { + id: number; + user_id: number; + }; + trek_photos: { + id: number; + provider: string; + asset_id: string | null; + owner_id: number | null; + file_path: string | null; + thumbnail_path: string | null; + width: number | null; + height: number | null; + media_type: string | null; + duration_ms: number | null; + taken_at: string | null; + lat: number | null; + lng: number | null; + }; +} + +/** + * R1's SECOND `GALLERY_CHRONOLOGICAL_ORDER` consumer (`getPublicJourney`'s + * gallery read, JS15) — Task 0's worked example (`task-0-report.md`), pasted + * verbatim against this file's own `JourneyPublicKyselyDB` shape rather than + * re-derived. Fixed to the `gp`/`tp` alias contract `.selectFrom('journey_photos + * as gp').innerJoin('trek_photos as tp', ...)` produces, same as the + * `publicStayExists`/SQLF-070 precedent: a table's alias is a property of the + * QUERY, not of the `DB` interface, so this is not generic over an arbitrary + * caller `DB`/`TB`. + */ +function galleryChronologicalOrderExpr( + platform: Platform, + eb: ExpressionBuilder, +) { + return eb.fn.coalesce( + eb.fn('nullif', [eb.ref('tp.taken_at'), eb.val('')]), + eb + .selectFrom('journey_entry_photos as jep') + .innerJoin('journey_entries as je', 'je.id', 'jep.entry_id') + .select((eb2) => + eb2.fn + .min( + concatKysely( + platform, + eb2, + { column: 'je.entry_date' }, + { value: 'T' }, + { expression: eb2.fn.coalesce(eb2.fn('nullif', [eb2.ref('je.entry_time'), eb2.val('')]), eb2.val('00:00')) }, + ), + ) + .as('min_dt'), + ) + .whereRef('jep.journey_photo_id', '=', 'gp.id'), + unixEpochToIsoKysely(platform, eb, 'gp.created_at'), + ); +} + +/** + * `journey_share_tokens` — public share links (Plan 3g Task 3, R4). Six of + * its methods (`findAccessByToken`, `findByToken` and the five cross-table + * public reads below) are reachable from `JourneyPublicController` with NO + * authentication at all, gated purely by the unguessable token. Every token + * lookup here is a plain `.where({token})`/`.where('token', '=', token)` + * equality — no `LIKE`, no `COLLATE NOCASE`, no case-folding of any kind + * (R4) — and every one of these returns `undefined` on a miss, never throws, + * so a missing/revoked/wrong-case/NUL token 404s through the controller + * instead of 500ing. + */ +export class JourneyShareTokensRepository extends TrekRepository { + /** JS1 — `createOrUpdateJourneyShareLink`'s existing-link read: `SELECT token, share_timeline, share_gallery, share_map, newest_first FROM journey_share_tokens WHERE journey_id = ?`. */ + async findFlagsByJourneyId(journeyId: number): Promise { + return await this.qb('jst') + .select(['jst.token', 'jst.share_timeline', 'jst.share_gallery', 'jst.share_map', 'jst.newest_first']) + .where({ journey: journeyId }) + .execute('get', false); + } + + /** + * JS2 — the update branch: `UPDATE journey_share_tokens SET + * share_timeline=?, share_gallery=?, share_map=?, newest_first=? WHERE + * journey_id=?`. A plain 4-column write, NOT a `presenceSet` call — the + * service resolves every flag's final value (the `permissions.X ?? !! + * existing.X` fallback merge) before calling this, so every call writes + * all four columns, present or not. + */ + async updateFlags( + journeyId: number, + flags: { share_timeline: number; share_gallery: number; share_map: number; newest_first: number }, + ): Promise { + await this.nativeUpdate({ journey: journeyId }, flags); + } + + /** JS3 — the create branch: `INSERT INTO journey_share_tokens (journey_id, token, created_by, share_timeline, share_gallery, share_map, newest_first) VALUES (?,?,?,?,?,?,?)`. */ + async insertLink( + journeyId: number, + token: string, + createdBy: number, + flags: { share_timeline: number; share_gallery: number; share_map: number; newest_first: number }, + ): Promise { + await this.insert({ journey: journeyId, token, createdByRef: createdBy, ...flags }); + } + + /** JS4 — `getJourneyShareLink`: `SELECT * FROM journey_share_tokens WHERE journey_id = ?`. */ + async findByJourneyId(journeyId: number): Promise { + return await this.qb('jst').select(['jst.*']).where({ journey: journeyId }).execute('get', false); + } + + /** JS5 — `deleteJourneyShareLink`: `DELETE FROM journey_share_tokens WHERE journey_id = ?`. */ + async deleteByJourneyId(journeyId: number): Promise { + await this.nativeDelete({ journey: journeyId }); + } + + /** + * JS6/JS9 — the public photo/asset validators' token lookup: `SELECT + * journey_id, share_gallery FROM journey_share_tokens WHERE token = ?`. + * Exact-match only (R4) — a differently-cased or NUL-truncated token binds + * as a distinct value and simply misses. + */ + async findAccessByToken(token: string): Promise { + return await this.qb('jst') + .select(['jst.journey', 'jst.share_gallery']) + .where({ token }) + .execute('get', false); + } + + /** JS11 — `getPublicJourney`'s entrypoint read: `SELECT * FROM journey_share_tokens WHERE token = ?`. Exact-match only (R4), same as {@link findAccessByToken}. */ + async findByToken(token: string): Promise { + return await this.qb('jst').select(['jst.*']).where({ token }).execute('get', false); + } + + /** JS7 — `validateShareTokenForPhoto`'s photo/journey resolution: `SELECT gp.photo_id, tkp.owner_id, gp.journey_id FROM journey_photos gp JOIN trek_photos tkp ON tkp.id=gp.photo_id WHERE gp.photo_id=? AND gp.journey_id=?`. */ + async findGalleryPhotoForValidation(photoId: number, journeyId: number): Promise { + return await this.kysely() + .selectFrom('journey_photos as gp') + .innerJoin('trek_photos as tkp', 'tkp.id', 'gp.photo_id') + .select(['gp.photo_id', 'tkp.owner_id', 'gp.journey_id']) + .where('gp.photo_id', '=', photoId) + .where('gp.journey_id', '=', journeyId) + .executeTakeFirst(); + } + + /** + * JS10 — `validateShareTokenForAsset`'s owner resolution: `SELECT + * tkp.owner_id, j.user_id AS journey_owner_id FROM journey_photos gp JOIN + * trek_photos tkp ON tkp.id=gp.photo_id JOIN journeys j ON j.id=gp.journey_id + * WHERE tkp.asset_id=? AND gp.journey_id=?`. Security-critical (the + * service never trusts a caller-supplied owner id — this join is the only + * source of the resolved `ownerId`). + */ + async findAssetForValidation(assetId: string, journeyId: number): Promise { + return await this.kysely() + .selectFrom('journey_photos as gp') + .innerJoin('trek_photos as tkp', 'tkp.id', 'gp.photo_id') + .innerJoin('journeys as j', 'j.id', 'gp.journey_id') + .select(['tkp.owner_id', 'j.user_id as journey_owner_id']) + .where('tkp.asset_id', '=', assetId) + .where('gp.journey_id', '=', journeyId) + .executeTakeFirst(); + } + + /** JS13 — `getPublicJourney`'s entry list: `SELECT je.* FROM journey_entries je WHERE je.journey_id=? AND je.type != 'skeleton' AND je.dismissed=0 ORDER BY je.entry_date, je.sort_order`. Skeletons never appear publicly. */ + async listPublicEntries(journeyId: number): Promise { + const rows = await this.kysely() + .selectFrom('journey_entries as je') + .selectAll('je') + .where('je.journey_id', '=', journeyId) + .where('je.type', '!=', 'skeleton') + .where('je.dismissed', '=', 0) + .orderBy('je.entry_date', 'asc') + .orderBy('je.sort_order', 'asc') + .execute(); + return rows as unknown as JourneyEntry[]; + } + + /** + * JS14 — `getPublicJourney`'s per-entry photo read. The select list is + * byte-for-byte the same columns, in the same order, as `JP_SELECT` + * (`journey-domain.service.ts`) — only the `trek_photos` join alias + * differs (`tkp` here, `tp` there). See task-3-report.md for why this + * stays a separate, hand-kept query rather than reusing Task 2's + * `JourneyEntryPhotosRepository` (not yet landed when this task ran). + */ + async listEntryPhotosForPublicJourney(journeyId: number): Promise { + return await this.kysely() + .selectFrom('journey_entry_photos as jep') + .innerJoin('journey_photos as gp', 'gp.id', 'jep.journey_photo_id') + .innerJoin('trek_photos as tkp', 'tkp.id', 'gp.photo_id') + .select([ + 'gp.id', 'jep.entry_id', 'gp.photo_id', 'gp.caption', 'jep.sort_order', 'gp.shared', 'gp.created_at', + 'tkp.provider', 'tkp.asset_id', 'tkp.owner_id', 'tkp.file_path', 'tkp.thumbnail_path', 'tkp.width', 'tkp.height', + 'tkp.media_type', 'tkp.duration_ms', 'tkp.taken_at', 'tkp.lat', 'tkp.lng', + ]) + .where('gp.journey_id', '=', journeyId) + .orderBy('jep.sort_order', 'asc') + .execute(); + } + + /** + * JS15 — `getPublicJourney`'s gallery read (R1's second + * `GALLERY_CHRONOLOGICAL_ORDER` site). The select list is byte-for-byte + * `GALLERY_SELECT` (`journey-domain.service.ts`), hand-duplicated here the + * same way the legacy statement hand-duplicated it (that module const is + * not imported by `journey-share.service.ts` at HEAD either). + */ + async listGalleryForPublicJourney(journeyId: number): Promise { + const platform = this.getEntityManager().getPlatform(); + return await this.kysely() + .selectFrom('journey_photos as gp') + .innerJoin('trek_photos as tp', 'tp.id', 'gp.photo_id') + .select([ + 'gp.id', 'gp.journey_id', 'gp.photo_id', 'gp.caption', 'gp.shared', 'gp.sort_order', 'gp.created_at', + 'tp.provider', 'tp.asset_id', 'tp.owner_id', 'tp.file_path', 'tp.thumbnail_path', 'tp.width', 'tp.height', + 'tp.media_type', 'tp.duration_ms', 'tp.taken_at', 'tp.lat', 'tp.lng', + ]) + .where('gp.journey_id', '=', journeyId) + .orderBy((eb) => galleryChronologicalOrderExpr(platform, eb), 'asc') + .orderBy('gp.sort_order', 'asc') + .orderBy('gp.id', 'asc') + .execute(); + } +} diff --git a/server/src/nest/journey/journal-rpc.module.ts b/server/src/nest/journey/journal-rpc.module.ts index d11e363d8..2b898e8a1 100644 --- a/server/src/nest/journey/journal-rpc.module.ts +++ b/server/src/nest/journey/journal-rpc.module.ts @@ -1,10 +1,12 @@ import { Module } from '@nestjs/common'; +import { MikroOrmModule } from '@mikro-orm/nestjs'; import { AllowedFileTypesModule } from '../files/allowed-file-types.module'; import { MemoriesModule } from '../memories/memories.module'; import { PluginGuardsModule } from '../plugins/host/plugin-guards.module'; import { StorageModule } from '../storage/storage.module'; import { JourneyDomainModule } from './journey-domain.module'; import { JournalRpc } from './journal.rpc'; +import { Users } from '../../db/entities/Users.entity'; /** * The journal plugin surface, in its own container. @@ -19,9 +21,14 @@ import { JournalRpc } from './journal.rpc'; * * JourneyDomainModule is re-exported so importing this one is a superset of * importing that one, and nothing that already depended on it has to change. + * + * `MikroOrmModule.forFeature([Users])` — Plan 3g Task 3: `JournalRpc`'s + * demo-mode gate (JR1) now injects `UsersRepository.getEmail`, and + * `@InjectRepository` resolves from THIS module's own `forFeature` graph, + * not `AuthModule`'s (which this module does not import). */ @Module({ - imports: [JourneyDomainModule, StorageModule, AllowedFileTypesModule, MemoriesModule, PluginGuardsModule], + imports: [JourneyDomainModule, StorageModule, AllowedFileTypesModule, MemoriesModule, PluginGuardsModule, MikroOrmModule.forFeature([Users])], providers: [JournalRpc], exports: [JourneyDomainModule], }) diff --git a/server/src/nest/journey/journal.rpc.ts b/server/src/nest/journey/journal.rpc.ts index a36fca81a..e941aac56 100644 --- a/server/src/nest/journey/journal.rpc.ts +++ b/server/src/nest/journey/journal.rpc.ts @@ -2,6 +2,7 @@ import pathMod from 'node:path'; import { randomUUID } from 'node:crypto'; import { Readable } from 'node:stream'; import { journalPluginPhotoInputSchema } from '@trek/shared'; +import { InjectRepository } from '@mikro-orm/nestjs'; import { PluginController, PluginMethod } from '../plugins/host/rpc-kit/decorators'; import { PluginGuards } from '../plugins/host/plugin-guards.service'; import { BadParams, ForbiddenResource } from '../plugins/host/rpc-errors'; @@ -12,8 +13,9 @@ import { readEnv } from '../../app-config'; import { isDemoEmail } from '../common/demo'; import { AllowedFileTypesService } from '../files/allowed-file-types.service'; import { PhotoCaptureBackfillService } from '../memories/photo-capture-backfill.service'; -import { DatabaseService } from '../database/database.service'; import { StorageService } from '../storage/storage.service'; +import { Users } from '../../db/entities/Users.entity'; +import type { UsersRepository } from '../../db/repositories/Users.repository'; import { JourneyDomainService } from './journey-domain.service'; /** 10MB decoded, the same cap the file surface applies to plugin uploads. */ @@ -46,7 +48,7 @@ export class JournalRpc { private readonly storage: StorageService, private readonly allowedTypes: AllowedFileTypesService, private readonly captureBackfill: PhotoCaptureBackfillService, - private readonly db: DatabaseService, + @InjectRepository(Users) private readonly usersRepo: UsersRepository, ) {} @PluginMethod('journal.listMine', { permission: 'db:read:journal' }) @@ -145,9 +147,11 @@ export class JournalRpc { // Mirrors the REST upload guard: a demo user must not write bytes to the // shared demo instance, not even through a plugin's db:write:journal. + // JR1 — reuses `UsersRepository.getEmail` (already built by another + // domain's demo-mode-check conversion), not a near-duplicate. if (readEnv().demo.enabled) { - const uploader = this.db.prepare('SELECT email FROM users WHERE id = ?').get(userId) as { email?: string } | undefined; - if (isDemoEmail(uploader?.email)) throw new ForbiddenResource('Uploads are disabled in demo mode.'); + const uploaderEmail = await this.usersRepo.getEmail(userId); + if (isDemoEmail(uploaderEmail)) throw new ForbiddenResource('Uploads are disabled in demo mode.'); } // basename first: a name is a name, never a path. diff --git a/server/src/nest/journey/journey-book.service.ts b/server/src/nest/journey/journey-book.service.ts index c21dc0fd6..d5c0e52b7 100644 --- a/server/src/nest/journey/journey-book.service.ts +++ b/server/src/nest/journey/journey-book.service.ts @@ -1,8 +1,10 @@ import { Injectable } from '@nestjs/common'; +import { InjectRepository } from '@mikro-orm/nestjs'; import type { BookRecord, BookSummary } from '@trek/shared'; import { normalizeBookDocument } from '@trek/shared'; -import { DatabaseService } from '../database/database.service'; import { JourneyDomainService } from './journey-domain.service'; +import { JourneyBooks } from '../../db/entities/JourneyBooks.entity'; +import type { JourneyBookRow, JourneyBooksRepository } from '../../db/repositories/JourneyBooks.repository'; /** * Storing TREK Studio books. @@ -29,8 +31,8 @@ import { JourneyDomainService } from './journey-domain.service'; @Injectable() export class JourneyBookService { constructor( - private readonly db: DatabaseService, private readonly journey: JourneyDomainService, + @InjectRepository(JourneyBooks) private readonly booksRepo: JourneyBooksRepository, ) {} /** Null when the journey does not exist or the user cannot reach it. */ @@ -57,7 +59,7 @@ export class JourneyBookService { return this.canAccess(journeyId, userId); } - private toRecord(row: BookRow): BookRecord { + private toRecord(row: JourneyBookRow): BookRecord { return { id: row.id, journeyId: row.journey_id, @@ -74,14 +76,8 @@ export class JourneyBookService { async listBooks(journeyId: number, userId: number): Promise { if (!(await this.canAccess(journeyId, userId))) return null; - const rows = this.db - .prepare(` - SELECT id, journey_id, title, version, updated_at, updated_by - FROM journey_books - WHERE journey_id = ? - ORDER BY updated_at DESC, id DESC - `) - .all(journeyId) as Omit[]; + // JB1. + const rows = await this.booksRepo.listForJourney(journeyId); return rows.map(r => ({ id: r.id, journeyId: r.journey_id, @@ -101,15 +97,8 @@ export class JourneyBookService { */ async getBook(journeyId: number, userId: number): Promise { if (!(await this.canAccess(journeyId, userId))) return null; - const row = this.db - .prepare(` - SELECT id, journey_id, title, document, version, updated_at, updated_by - FROM journey_books - WHERE journey_id = ? - ORDER BY id ASC - LIMIT 1 - `) - .get(journeyId) as BookRow | undefined; + // JB2. + const row = await this.booksRepo.findFirstForJourney(journeyId); return row ? this.toRecord(row) : null; } @@ -128,18 +117,13 @@ export class JourneyBookService { if (!(await this.canWrite(journeyId, userId))) return null; const document = JSON.stringify(normalizeBookDocument(input.document)); - const existing = this.db - .prepare('SELECT id, version FROM journey_books WHERE journey_id = ? ORDER BY id ASC LIMIT 1') - .get(journeyId) as { id: number; version: number } | undefined; + // JB3. + const existing = await this.booksRepo.findFirstForJourney(journeyId); if (!existing) { - const result = this.db - .prepare(` - INSERT INTO journey_books (journey_id, title, document, version, created_by, updated_by, updated_at) - VALUES (?, ?, ?, 1, ?, ?, CURRENT_TIMESTAMP) - `) - .run(journeyId, input.title, document, userId, userId); - return { record: (await this.byId(Number(result.lastInsertRowid)))! }; + // JB4. + const id = await this.booksRepo.insertBook(journeyId, input.title, document, userId); + return { record: (await this.byId(id))! }; } /* @@ -154,16 +138,14 @@ export class JourneyBookService { * arrive. */ const base = input.baseVersion ?? existing.version; - const result = this.db - .prepare(` - UPDATE journey_books - SET title = ?, document = ?, version = version + 1, - updated_by = ?, updated_at = CURRENT_TIMESTAMP - WHERE id = ? AND version = ? - `) - .run(input.title, document, userId, existing.id, base); + // JB5 (R2) — one conditional UPDATE, returning the affected-row count. + const changes = await this.booksRepo.casUpdate(existing.id, base, { + title: input.title, + document, + updatedBy: userId, + }); - if (result.changes === 0) { + if (changes === 0) { return { conflict: (await this.byId(existing.id))! }; } return { record: (await this.byId(existing.id))! }; @@ -171,10 +153,9 @@ export class JourneyBookService { async deleteBook(journeyId: number, userId: number): Promise { if (!(await this.canWrite(journeyId, userId))) return null; - const result = this.db - .prepare('DELETE FROM journey_books WHERE journey_id = ?') - .run(journeyId); - return result.changes > 0; + // JB6. + const changes = await this.booksRepo.deleteByJourneyId(journeyId); + return changes > 0; } /** @@ -197,27 +178,13 @@ export class JourneyBookService { ); } + /** JB7. */ private async byId(id: number): Promise { - const row = this.db - .prepare(` - SELECT id, journey_id, title, document, version, updated_at, updated_by - FROM journey_books WHERE id = ? - `) - .get(id) as BookRow | undefined; + const row = await this.booksRepo.findById(id); return row ? this.toRecord(row) : null; } } -interface BookRow { - id: number; - journey_id: number; - title: string; - document: string; - version: number; - updated_at: string | null; - updated_by: number | null; -} - /** JSON that will not parse is an empty document, never an exception. */ function safeParse(raw: string): unknown { try { diff --git a/server/src/nest/journey/journey-domain.module.ts b/server/src/nest/journey/journey-domain.module.ts index 8784d678c..102537d85 100644 --- a/server/src/nest/journey/journey-domain.module.ts +++ b/server/src/nest/journey/journey-domain.module.ts @@ -10,7 +10,11 @@ import { Journeys } from '../../db/entities/Journeys.entity'; import { JourneyContributors } from '../../db/entities/JourneyContributors.entity'; import { JourneyTrips } from '../../db/entities/JourneyTrips.entity'; import { JourneyEntries } from '../../db/entities/JourneyEntries.entity'; +import { JourneyPhotos } from '../../db/entities/JourneyPhotos.entity'; +import { JourneyEntryPhotos } from '../../db/entities/JourneyEntryPhotos.entity'; +import { JourneyShareTokens } from '../../db/entities/JourneyShareTokens.entity'; import { Trips } from '../../db/entities/Trips.entity'; +import { Places } from '../../db/entities/Places.entity'; /** * Leaf module holding the journey domain itself, without the controllers. @@ -33,17 +37,30 @@ import { Trips } from '../../db/entities/Trips.entity'; * job rather than a second copy of its SQL here. * * `MikroOrmModule.forFeature([Journeys, JourneyContributors, JourneyTrips, - * JourneyEntries, Trips])` registers `JourneysRepository`/ - * `JourneyContributorsRepository`/`JourneyTripsRepository`/ - * `JourneyEntriesRepository`/`TripsRepository` for `JourneyDomainService`'s - * `@InjectRepository` constructor params (Plan 3g Task 1, Part A — the FIRST - * `forFeature` array this module declares; no other module injects a - * `Journey*Repository` directly, every downstream consumer reaches this - * cluster only through `JourneyDomainService`/`JourneyShareService`, per the - * program's own boot-gate note for this task). `Trips` is included the same - * way `days.module.ts`/`memories.module.ts` each register it locally for - * their own `@InjectRepository(Trips)` param — every module that constructs - * a service needing a repository lists that entity in its own `forFeature`. + * JourneyEntries, Trips, JourneyPhotos, JourneyEntryPhotos, Places])` + * registers `JourneysRepository`/`JourneyContributorsRepository`/ + * `JourneyTripsRepository`/`JourneyEntriesRepository`/`TripsRepository` for + * `JourneyDomainService`'s `@InjectRepository` constructor params (Plan 3g + * Task 1, Part A — the FIRST `forFeature` array this module declares; no + * other module injects a `Journey*Repository` directly, every downstream + * consumer reaches this cluster only through `JourneyDomainService`/ + * `JourneyShareService`, per the program's own boot-gate note for this + * task). `Trips` is included the same way `days.module.ts`/ + * `memories.module.ts` each register it locally for their own + * `@InjectRepository(Trips)` param — every module that constructs a service + * needing a repository lists that entity in its own `forFeature`. + * `JourneyPhotos`/`JourneyEntryPhotos`/`Places` are Plan 3g Task 2's own + * additions: `JourneyDomainService`'s Part B (journey stats, entries CRUD, + * the full photos surface, contributors CRUD, suggestions) needed + * `JourneyPhotosRepository`/`JourneyEntryPhotosRepository` (JG19/JG87-116, + * finishing JG15/JG19 too) and `PlacesRepository` (JG44's `findRaw`) — a + * genuine new-constructor-parameter case the task brief's own contingency + * covers (flagged in `task-2-report.md`). + * `JourneyShareTokens` is Plan 3g Task 3's own addition: `JourneyShareService` + * (also provided here) now injects `JourneyShareTokensRepository` directly + * for JS1-JS15, plus reuses the already-registered `JourneysRepository` for + * JS8/JS12 — no other module needed touching since both were already in + * this array or this module's own provider graph. */ @Module({ imports: [ @@ -51,7 +68,7 @@ import { Trips } from '../../db/entities/Trips.entity'; TrekPhotosModule, PluginGuardsModule, SettingsModule, - MikroOrmModule.forFeature([Journeys, JourneyContributors, JourneyTrips, JourneyEntries, Trips]), + MikroOrmModule.forFeature([Journeys, JourneyContributors, JourneyTrips, JourneyEntries, Trips, JourneyPhotos, JourneyEntryPhotos, Places, JourneyShareTokens]), ], providers: [JourneyDomainService, JourneyShareService], exports: [JourneyDomainService, JourneyShareService], diff --git a/server/src/nest/journey/journey-share.service.ts b/server/src/nest/journey/journey-share.service.ts index f02c1bbcf..2ac5ccb5b 100644 --- a/server/src/nest/journey/journey-share.service.ts +++ b/server/src/nest/journey/journey-share.service.ts @@ -1,10 +1,16 @@ import { Injectable } from '@nestjs/common'; +import { InjectRepository } from '@mikro-orm/nestjs'; import crypto from 'crypto'; -import { DatabaseService } from '../database/database.service'; import { JourneyDomainService } from './journey-domain.service'; import { decodeEntryRow } from './journey-entry-row'; -import { GALLERY_CHRONOLOGICAL_ORDER } from './journey-gallery-order'; import { SettingsService } from '../settings/settings.service'; +import { Journeys } from '../../db/entities/Journeys.entity'; +import type { JourneysRepository } from '../../db/repositories/Journeys.repository'; +import { JourneyShareTokens } from '../../db/entities/JourneyShareTokens.entity'; +import type { + JourneyPublicEntryPhotoRow, + JourneyShareTokensRepository, +} from '../../db/repositories/JourneyShareTokens.repository'; interface JourneySharePermissions { share_timeline?: boolean; @@ -16,7 +22,7 @@ interface JourneySharePermissions { interface JourneyShareTokenInfo { token: string; - created_at: string; + created_at: string | null; share_timeline: boolean; share_gallery: boolean; share_map: boolean; @@ -34,9 +40,13 @@ interface JourneyShareTokenInfo { @Injectable() export class JourneyShareService { constructor( - private readonly db: DatabaseService, private readonly journey: JourneyDomainService, private readonly settings: SettingsService, + @InjectRepository(JourneyShareTokens) private readonly shareTokensRepo: JourneyShareTokensRepository, + // JS8/JS12's unscoped `SELECT * FROM journeys WHERE id = ?` reuses Task 1's + // already-stable `JourneysRepository.findById` (the JG5 dup group) rather + // than a second, hand-kept copy of the same statement. + @InjectRepository(Journeys) private readonly journeysRepo: JourneysRepository, ) {} async createOrUpdateJourneyShareLink( @@ -48,8 +58,8 @@ export class JourneyShareService { // able to publish the journey or change which screens are shared. if (!(await this.journey.isOwner(journeyId, createdBy))) return null; - const existing = this.db.prepare('SELECT token, share_timeline, share_gallery, share_map, newest_first FROM journey_share_tokens WHERE journey_id = ?') - .get(journeyId) as { token: string; share_timeline: number; share_gallery: number; share_map: number; newest_first: number } | undefined; + // JS1 — `JourneyShareTokensRepository.findFlagsByJourneyId`. + const existing = await this.shareTokensRepo.findFlagsByJourneyId(journeyId); if (existing) { // An update only changes the flags it was actually given. Falling back to @@ -59,8 +69,15 @@ export class JourneyShareService { const share_gallery = permissions.share_gallery ?? !!existing.share_gallery; const share_map = permissions.share_map ?? !!existing.share_map; const newest_first = permissions.newest_first ?? !!existing.newest_first; - this.db.prepare('UPDATE journey_share_tokens SET share_timeline = ?, share_gallery = ?, share_map = ?, newest_first = ? WHERE journey_id = ?') - .run(share_timeline ? 1 : 0, share_gallery ? 1 : 0, share_map ? 1 : 0, newest_first ? 1 : 0, journeyId); + // JS2 — the SERVICE resolves the final value of every flag (above); the + // repository writes exactly those four already-resolved booleans, a + // plain 4-column UPDATE, not a presence-sentinel one. + await this.shareTokensRepo.updateFlags(journeyId, { + share_timeline: share_timeline ? 1 : 0, + share_gallery: share_gallery ? 1 : 0, + share_map: share_map ? 1 : 0, + newest_first: newest_first ? 1 : 0, + }); return { token: existing.token, created: false }; } @@ -72,8 +89,13 @@ export class JourneyShareService { } = permissions; const token = crypto.randomBytes(24).toString('base64url'); - this.db.prepare('INSERT INTO journey_share_tokens (journey_id, token, created_by, share_timeline, share_gallery, share_map, newest_first) VALUES (?, ?, ?, ?, ?, ?, ?)') - .run(journeyId, token, createdBy, share_timeline ? 1 : 0, share_gallery ? 1 : 0, share_map ? 1 : 0, newest_first ? 1 : 0); + // JS3. + await this.shareTokensRepo.insertLink(journeyId, token, createdBy, { + share_timeline: share_timeline ? 1 : 0, + share_gallery: share_gallery ? 1 : 0, + share_map: share_map ? 1 : 0, + newest_first: newest_first ? 1 : 0, + }); return { token, created: true }; } @@ -96,7 +118,8 @@ export class JourneyShareService { } async getJourneyShareLink(journeyId: number): Promise { - const row = this.db.prepare('SELECT * FROM journey_share_tokens WHERE journey_id = ?').get(journeyId) as any; + // JS4. + const row = await this.shareTokensRepo.findByJourneyId(journeyId); if (!row) return null; return { token: row.token, @@ -110,89 +133,69 @@ export class JourneyShareService { async deleteJourneyShareLink(journeyId: number, userId: number): Promise { if (!(await this.journey.isOwner(journeyId, userId))) return false; - this.db.prepare('DELETE FROM journey_share_tokens WHERE journey_id = ?').run(journeyId); + // JS5. + await this.shareTokensRepo.deleteByJourneyId(journeyId); return true; } async validateShareTokenForPhoto(token: string, photoId: number): Promise<{ journeyId: number; ownerId: number } | null> { - const row = this.db.prepare('SELECT journey_id, share_gallery FROM journey_share_tokens WHERE token = ?').get(token) as any; + // JS6 — exact-match token lookup, no LIKE/COLLATE (R4). + const row = await this.shareTokensRepo.findAccessByToken(token); if (!row) return null; // Photos only ever surface (inline or in the gallery) when share_gallery is on, // so the byte proxy must honour the flag server-side too — the JSON payload // already strips photos when it is off. Enumerable photo ids otherwise stay // fetchable after the owner disables the gallery. if (!row.share_gallery) return null; - const photo = this.db.prepare(` - SELECT gp.photo_id, tkp.owner_id, gp.journey_id - FROM journey_photos gp - JOIN trek_photos tkp ON tkp.id = gp.photo_id - WHERE gp.photo_id = ? AND gp.journey_id = ? - `).get(photoId, row.journey_id) as any; + // JS7. + const photo = await this.shareTokensRepo.findGalleryPhotoForValidation(photoId, row.journey_id); if (!photo) return null; - const journey = this.db.prepare('SELECT user_id FROM journeys WHERE id = ?').get(row.journey_id) as any; + // JS8 — reuses `JourneysRepository.findById` (JG5's dup group), no + // `canAccessJourney` involved: public means public. + const journey = await this.journeysRepo.findById(row.journey_id); return journey ? { journeyId: row.journey_id, ownerId: photo.owner_id || journey.user_id } : null; } async validateShareTokenForAsset(token: string, assetId: string): Promise<{ ownerId: number } | null> { - const row = this.db.prepare('SELECT journey_id, share_gallery FROM journey_share_tokens WHERE token = ?').get(token) as any; + // JS9 — exact-match token lookup, no LIKE/COLLATE (R4). + const row = await this.shareTokensRepo.findAccessByToken(token); if (!row) return null; // Same as the unified photo proxy: no asset bytes leave the host unless the // owner shared the gallery. if (!row.share_gallery) return null; - const photo = this.db.prepare(` - SELECT tkp.owner_id, j.user_id AS journey_owner_id - FROM journey_photos gp - JOIN trek_photos tkp ON tkp.id = gp.photo_id - JOIN journeys j ON j.id = gp.journey_id - WHERE tkp.asset_id = ? AND gp.journey_id = ? - `).get(assetId, row.journey_id) as any; + // JS10 — security-critical: whose provider credentials get tried must + // never come from a number an anonymous caller put in the URL. Only this + // join resolves `ownerId`; a caller-supplied value never reaches it. + const photo = await this.shareTokensRepo.findAssetForValidation(assetId, row.journey_id); // Only resolve assets that actually belong to this shared journey. if (!photo) return null; // trek_photos.owner_id can be NULL. The journey's owner is the fallback, the - // same one the photo proxy uses. Whose provider credentials get tried must - // never come from a number an anonymous caller put in the URL. + // same one the photo proxy uses. return { ownerId: photo.owner_id || photo.journey_owner_id }; } async getPublicJourney(token: string) { - const row = this.db.prepare('SELECT * FROM journey_share_tokens WHERE token = ?').get(token) as any; + // JS11 — exact-match token lookup, no LIKE/COLLATE (R4). + const row = await this.shareTokensRepo.findByToken(token); if (!row) return null; - const journey = this.db.prepare('SELECT * FROM journeys WHERE id = ?').get(row.journey_id) as any; + // JS12 — reuses `JourneysRepository.findById`, same as JS8. + const journey = await this.journeysRepo.findById(row.journey_id); if (!journey) return null; - // Entries with photos - const entries = this.db.prepare(` - SELECT je.* FROM journey_entries je - WHERE je.journey_id = ? AND je.type != 'skeleton' AND je.dismissed = 0 - ORDER BY je.entry_date, je.sort_order - `).all(row.journey_id) as any[]; + // Entries with photos — JS13. + const entries = await this.shareTokensRepo.listPublicEntries(row.journey_id); - const photos = this.db.prepare(` - SELECT gp.id, jep.entry_id, gp.photo_id, gp.caption, jep.sort_order, gp.shared, gp.created_at, - tkp.provider, tkp.asset_id, tkp.owner_id, tkp.file_path, tkp.thumbnail_path, tkp.width, tkp.height, - tkp.media_type, tkp.duration_ms, tkp.taken_at, tkp.lat, tkp.lng - FROM journey_entry_photos jep - JOIN journey_photos gp ON gp.id = jep.journey_photo_id - JOIN trek_photos tkp ON tkp.id = gp.photo_id - WHERE gp.journey_id = ? - ORDER BY jep.sort_order - `).all(row.journey_id) as any[]; + // JS14. + const photos = await this.shareTokensRepo.listEntryPhotosForPublicJourney(row.journey_id); - const photosByEntry: Record = {}; + const photosByEntry: Record = {}; for (const p of photos) { (photosByEntry[p.entry_id] ||= []).push(p); } - const gallery = this.db.prepare(` - SELECT gp.id, gp.journey_id, gp.photo_id, gp.caption, gp.shared, gp.sort_order, gp.created_at, - tp.provider, tp.asset_id, tp.owner_id, tp.file_path, tp.thumbnail_path, tp.width, tp.height, - tp.media_type, tp.duration_ms, tp.taken_at, tp.lat, tp.lng - FROM journey_photos gp - JOIN trek_photos tp ON tp.id = gp.photo_id - WHERE gp.journey_id = ? - ${GALLERY_CHRONOLOGICAL_ORDER} - `).all(row.journey_id) as any[]; + // JS15 (R1's second `GALLERY_CHRONOLOGICAL_ORDER` site). + const gallery = await this.shareTokensRepo.listGalleryForPublicJourney(row.journey_id); const enrichedEntries = entries .map(e => ({ diff --git a/server/src/nest/journey/journey.module.ts b/server/src/nest/journey/journey.module.ts index 706182d3b..b59e5d4c0 100644 --- a/server/src/nest/journey/journey.module.ts +++ b/server/src/nest/journey/journey.module.ts @@ -1,4 +1,5 @@ import { Module } from '@nestjs/common'; +import { MikroOrmModule } from '@mikro-orm/nestjs'; import { JourneyController } from './journey.controller'; import { JourneyPublicController } from './journey-public.controller'; import { JourneyService } from './journey.service'; @@ -15,6 +16,8 @@ import { StorageModule } from '../storage/storage.module'; import { StorageService } from '../storage/storage.service'; import { buildStorageUploadOptions } from '../storage/storage-upload.factory'; import { journeyImageFileFilter, journeyUploadFilename } from './journey.controller'; +import { Users } from '../../db/entities/Users.entity'; +import { JourneyBooks } from '../../db/entities/JourneyBooks.entity'; @Module({ // MemoriesModule: the journey gallery streams provider assets and uploads to Immich. @@ -33,7 +36,14 @@ import { journeyImageFileFilter, journeyUploadFilename } from './journey.control }), }), StorageModule, - AuthModule, AddonsModule, MemoriesModule, JourneyDomainModule], + AuthModule, AddonsModule, MemoriesModule, JourneyDomainModule, + // Plan 3g Task 3: `JourneyService` (JV1, `UsersRepository.getImmichAutoUpload`) + // and `JourneyBookService` (JB1-JB7, `JourneyBooksRepository`) both + // constructed HERE — `@InjectRepository` resolves from this module's own + // `forFeature` graph, not from `AuthModule`'s (which registers `Users` + // for its own providers only, per that module's own docstring). + MikroOrmModule.forFeature([Users, JourneyBooks]), + ], controllers: [JourneyController, JourneyPublicController], providers: [JourneyService, JourneyBookService, JourneyMcp], }) diff --git a/server/src/nest/journey/journey.service.ts b/server/src/nest/journey/journey.service.ts index 63f94449e..354db681a 100644 --- a/server/src/nest/journey/journey.service.ts +++ b/server/src/nest/journey/journey.service.ts @@ -1,5 +1,5 @@ import { Injectable } from '@nestjs/common'; -import { DatabaseService } from '../database/database.service'; +import { InjectRepository } from '@mikro-orm/nestjs'; import { JourneyDomainService } from './journey-domain.service'; import { JourneyShareService } from './journey-share.service'; import { ImmichService } from '../memories/immich.service'; @@ -7,6 +7,8 @@ import { PhotoProviderRegistry } from '../memories/photo-provider.registry'; import { PhotoResolverService } from '../memories/photo-resolver.service'; import { AddonsService } from '../addons/addons.service'; import { ADDON_IDS } from '../../addons'; +import { Users } from '../../db/entities/Users.entity'; +import type { UsersRepository } from '../../db/repositories/Users.repository'; import type { Response } from 'express'; /** @@ -18,19 +20,15 @@ import type { Response } from 'express'; @Injectable() export class JourneyService { constructor( - private readonly dbs: DatabaseService, private readonly addons: AddonsService, private readonly immich: ImmichService, private readonly providers: PhotoProviderRegistry, private readonly photoResolver: PhotoResolverService, private readonly journey: JourneyDomainService, private readonly share: JourneyShareService, + @InjectRepository(Users) private readonly usersRepo: UsersRepository, ) {} - private get db() { - return this.dbs.connection; - } - async journeyAddonEnabled(): Promise { return this.addons.isAddonEnabled(ADDON_IDS.JOURNEY); } @@ -87,9 +85,11 @@ export class JourneyService { deleteJourneyShareLink(id: number, userId: number) { return this.share.deleteJourneyShareLink(id, userId); } // Immich mirror (only when the user opted in via integration settings) + // JV1 — reuses `UsersRepository.getImmichAutoUpload` (already built for + // `ImmichService.getConnectionSettings`'s IM2, the same statement text), + // not a near-duplicate. async immichAutoUploadEnabled(userId: number): Promise { - const prefs = this.db.prepare('SELECT immich_auto_upload FROM users WHERE id = ?').get(userId) as { immich_auto_upload?: number } | undefined; - return !!prefs?.immich_auto_upload; + return !!(await this.usersRepo.getImmichAutoUpload(userId)); } uploadToImmich(userId: number, relativePath: string, originalName: string) { return this.immich.uploadToImmich(userId, relativePath, originalName); } diff --git a/server/tests/helpers/journey-share-repos.ts b/server/tests/helpers/journey-share-repos.ts new file mode 100644 index 000000000..c2de457d9 --- /dev/null +++ b/server/tests/helpers/journey-share-repos.ts @@ -0,0 +1,26 @@ +import type Database from 'better-sqlite3'; +import { sharedTestOrm } from './test-uow'; +import { JourneyShareTokens } from '../../src/db/entities/JourneyShareTokens.entity'; +import type { JourneyShareTokensRepository } from '../../src/db/repositories/JourneyShareTokens.repository'; +import { JourneyBooks } from '../../src/db/entities/JourneyBooks.entity'; +import type { JourneyBooksRepository } from '../../src/db/repositories/JourneyBooks.repository'; + +/** + * Plan 3g Task 3 (`JourneyShareService`/`JourneyBookService`) test-only + * repository factories, bound to a suite's own better-sqlite3 handle via the + * SAME memoised `sharedTestOrm` (`test-uow.ts`) — same precedent + * `journey-repos.ts` (Task 1) documents for itself. + * + * A NEW file rather than an addition to `journey-repos.ts`: that file is + * Task 1/2's own (`JourneysRepository`/`JourneyContributorsRepository`/ + * `JourneyTripsRepository`/`JourneyEntriesRepository`/`JourneyPhotosRepository`/ + * `JourneyEntryPhotosRepository`), concurrently in flight when this task ran + * — this file only adds the two share/book-owned tables' factories. + */ +export function createTestJourneyShareTokensRepo(db: Database.Database): Promise { + return sharedTestOrm(db).then((t) => t.repo(JourneyShareTokens)); +} + +export function createTestJourneyBooksRepo(db: Database.Database): Promise { + return sharedTestOrm(db).then((t) => t.repo(JourneyBooks)); +} diff --git a/server/tests/helpers/mcp-test-controllers.ts b/server/tests/helpers/mcp-test-controllers.ts index b97a06fd5..3e08e1c3d 100644 --- a/server/tests/helpers/mcp-test-controllers.ts +++ b/server/tests/helpers/mcp-test-controllers.ts @@ -160,7 +160,9 @@ import { } from './atlas-repos'; import { createTestJourneysRepo, createTestJourneyContributorsRepo, createTestJourneyTripsRepo, createTestJourneyEntriesRepo, + createTestJourneyPhotosRepo, createTestJourneyEntryPhotosRepo, } from './journey-repos'; +import { createTestJourneyShareTokensRepo } from './journey-share-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'; @@ -255,6 +257,13 @@ export async function createMcpTestRegistry(): Promise { await createTestJourneysRepo(dbService.connection), await createTestJourneyContributorsRepo(dbService.connection), await createTestJourneyTripsRepo(dbService.connection), await createTestJourneyEntriesRepo(dbService.connection), await createTestTripsRepo(dbService.connection), + // Plan 3g Task 2 — a genuine follow-up constructor-ripple (git status + // confirmed this file clean before editing, per the task brief's own + // allowance): `JourneyPhotosRepository`/`JourneyEntryPhotosRepository` + // (the photos surface, JG19/JG87-116) + `PlacesRepository` (JG44's + // `findRaw`, already imported below for other MCP controllers). + await createTestJourneyPhotosRepo(dbService.connection), await createTestJourneyEntryPhotosRepo(dbService.connection), + await createTestPlacesRepo(dbService.connection), ); // The last three were previously omitted, which left them `undefined` at // runtime — silently fine while nothing called them, a TypeError the moment @@ -429,7 +438,13 @@ export async function createMcpTestRegistry(): Promise { await createTestTripsRepo(dbService.connection), await createTestPlacesRepo(dbService.connection), await createTestReservationEndpointsRepo(dbService.connection), 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 JourneyMcp(journeyDomain, new JourneyShareService( + journeyDomain, + new SettingsService(await createTestUnitOfWork(dbService.connection), appSettings, await createTestSettingsRepo(dbService.connection)), + // Plan 3g Task 3 — the constructor-ripple fix: `JourneyShareTokensRepository` + // (JS1-JS15) + the already-shared `JourneysRepository` (JS8/JS12). + await createTestJourneyShareTokensRepo(dbService.connection), await createTestJourneysRepo(dbService.connection), + ), addonsService, authService, captureBackfill), 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), diff --git a/server/tests/helpers/plugin-host.ts b/server/tests/helpers/plugin-host.ts index b0f49b251..dd5b9d148 100644 --- a/server/tests/helpers/plugin-host.ts +++ b/server/tests/helpers/plugin-host.ts @@ -113,6 +113,7 @@ import { } from './atlas-repos'; import { createTestJourneysRepo, createTestJourneyContributorsRepo, createTestJourneyTripsRepo, createTestJourneyEntriesRepo, + createTestJourneyPhotosRepo, createTestJourneyEntryPhotosRepo, } from './journey-repos'; /** @@ -192,6 +193,13 @@ export async function createPluginRpcHostFactory(dbs: DatabaseService): Promise< await createTestJourneysRepo(dbs.connection), await createTestJourneyContributorsRepo(dbs.connection), await createTestJourneyTripsRepo(dbs.connection), await createTestJourneyEntriesRepo(dbs.connection), await createTestTripsRepo(dbs.connection), + // Plan 3g Task 2 — a genuine follow-up constructor-ripple (git status + // confirmed this file clean before editing, per the task brief's own + // allowance): `JourneyPhotosRepository`/`JourneyEntryPhotosRepository` + // (the photos surface, JG19/JG87-116) + `PlacesRepository` (JG44's + // `findRaw`, already imported above for `PlacePhotoCacheService`). + await createTestJourneyPhotosRepo(dbs.connection), await createTestJourneyEntryPhotosRepo(dbs.connection), + await createTestPlacesRepo(dbs.connection), ); const collections = new CollectionsService(dbs, permissions, realtime, notificationsStub(), generalStorage, await createTestUnitOfWork(dbs.connection)); const atlas = new AtlasService( @@ -264,7 +272,9 @@ export async function createPluginRpcHostFactory(dbs: DatabaseService): Promise< new VacayRpc(vacay, guards), // The photo half needs storage plus the allowed-types setting and the EXIF // backfill; none of the tests on this harness write bytes, so they are stubs. - new JournalRpc(journey, guards, generalStorage, { get: () => '*' } as never, { schedule: () => {} } as never, dbs), + // Plan 3g Task 3 — the constructor-ripple fix: `JournalRpc`'s demo-mode + // gate (JR1) now injects `UsersRepository.getEmail`, not `DatabaseService`. + new JournalRpc(journey, guards, generalStorage, { get: () => '*' } as never, { schedule: () => {} } as never, usersRepo), new CollectionsRpc(collections, guards), new DbRpc(new PluginUserSettingsService(dbs)), new MetaRpc(dbs, guards), diff --git a/server/tests/unit/nest/journey-book.service.test.ts b/server/tests/unit/nest/journey-book.service.test.ts index 1db3f98af..513cda7af 100644 --- a/server/tests/unit/nest/journey-book.service.test.ts +++ b/server/tests/unit/nest/journey-book.service.test.ts @@ -47,10 +47,12 @@ import { TripPhotos } from '../../../src/db/entities/TripPhotos.entity'; import { JourneyDomainService } from '../../../src/nest/journey/journey-domain.service'; import { JourneyBookService } from '../../../src/nest/journey/journey-book.service'; import { db as dbConn } from '../../../src/db/database'; -import { createTestUnitOfWork, sharedTestOrm, createTestTripsRepo } from '../../helpers/test-uow'; +import { createTestUnitOfWork, sharedTestOrm, createTestTripsRepo, createTestPlacesRepo } from '../../helpers/test-uow'; import { createTestJourneysRepo, createTestJourneyContributorsRepo, createTestJourneyTripsRepo, createTestJourneyEntriesRepo, + createTestJourneyPhotosRepo, createTestJourneyEntryPhotosRepo, } from '../../helpers/journey-repos'; +import { createTestJourneyBooksRepo } from '../../helpers/journey-share-repos'; const dbs = new DatabaseService(dbConn); let domain: JourneyDomainService; @@ -75,8 +77,11 @@ beforeAll(async () => { dbs, new RealtimeService(), new TrekPhotoRegistrationService(t.repo(TrekPhotos), t.repo(TripPhotos), dbs), uow, await createTestJourneysRepo(testDb), await createTestJourneyContributorsRepo(testDb), await createTestJourneyTripsRepo(testDb), await createTestJourneyEntriesRepo(testDb), await createTestTripsRepo(testDb), + // Plan 3g Task 2 constructor-ripple: JourneyPhotosRepository/JourneyEntryPhotosRepository/PlacesRepository. + await createTestJourneyPhotosRepo(testDb), await createTestJourneyEntryPhotosRepo(testDb), await createTestPlacesRepo(testDb), ); - books = new JourneyBookService(dbs, domain); + // Plan 3g Task 3: JourneyBooksRepository (JB1-JB7), not `dbs` any more. + books = new JourneyBookService(domain, await createTestJourneyBooksRepo(testDb)); }); beforeEach(() => { @@ -305,6 +310,47 @@ describe('concurrency', () => { expect(stale && 'conflict' in stale).toBe(true); expect((await books.getBook(other.id, user.id))!.version).toBe(1); }); + + // JB5 (R2) — the brief's exact named tests: the one statement in the whole + // plan whose control-flow contract ("convert the statement" AND "preserve + // the exact branching") is the same instruction. + it('journey-book-svc: concurrent save with a stale baseVersion returns {conflict}, does not throw', async () => { + const { user, journey } = await seed(); + await books.saveBook(journey.id, user.id, { title: 'T', document: doc('two'), baseVersion: 1 }); + + const stale = await books.saveBook(journey.id, user.id, { title: 'T', document: doc('three'), baseVersion: 1 }); + + expect(stale).not.toBeNull(); + expect(stale && 'conflict' in stale).toBe(true); + }); + + it('journey-book-svc: the conflict payload is the freshly re-read record, not the stale one the caller sent', async () => { + const { user, journey } = await seed(); + await books.saveBook(journey.id, user.id, { title: 'Theirs', document: doc('two'), baseVersion: 1 }); + + const stale = await books.saveBook(journey.id, user.id, { title: 'Mine', document: doc('three'), baseVersion: 1 }); + + expect(stale && 'conflict' in stale && stale.conflict.title).toBe('Theirs'); + expect(stale && 'conflict' in stale && stale.conflict.document.title).toBe('two'); + expect(stale && 'conflict' in stale && stale.conflict.version).toBe(2); + }); + + it('journey-book-svc: mutation proof — an UPDATE without the WHERE version guard would silently clobber a concurrent save', async () => { + const { user, journey } = await seed(); + await books.saveBook(journey.id, user.id, { title: 'T', document: doc('two'), baseVersion: 1 }); + // The real, version-guarded save correctly refuses the stale write: + const stale = await books.saveBook(journey.id, user.id, { title: 'T', document: doc('three'), baseVersion: 1 }); + expect(stale && 'conflict' in stale).toBe(true); + + // The same statement with the `AND version = ?` guard stripped — proving + // that guard, not something else, is what makes the refusal above real. + const row = testDb.prepare('SELECT id FROM journey_books WHERE journey_id = ?').get(journey.id) as { id: number }; + testDb + .prepare('UPDATE journey_books SET title = ?, document = ?, version = version + 1 WHERE id = ?') + .run('Clobbered', JSON.stringify(doc('clobbered')), row.id); + const afterMutation = testDb.prepare('SELECT title FROM journey_books WHERE id = ?').get(row.id) as { title: string }; + expect(afterMutation.title).toBe('Clobbered'); + }); }); // -- Broadcasting ------------------------------------------------------------- diff --git a/server/tests/unit/nest/journey-share.service.test.ts b/server/tests/unit/nest/journey-share.service.test.ts index 39dcdf114..6e8b174ce 100644 --- a/server/tests/unit/nest/journey-share.service.test.ts +++ b/server/tests/unit/nest/journey-share.service.test.ts @@ -43,11 +43,15 @@ import { JourneyDomainService } from '../../../src/nest/journey/journey-domain.s import { JourneyShareService } from '../../../src/nest/journey/journey-share.service'; import { SettingsService } from '../../../src/nest/settings/settings.service'; import { db as dbConn } from '../../../src/db/database'; -import { sharedTestOrm, createTestUnitOfWork, createTestAppSettingsRepo, createTestSettingsRepo, createTestTripsRepo } from '../../helpers/test-uow'; +import { sharedTestOrm, createTestUnitOfWork, createTestAppSettingsRepo, createTestSettingsRepo, createTestTripsRepo, createTestPlacesRepo } from '../../helpers/test-uow'; import type { TestOrm } from '../../helpers/test-orm'; import { createTestJourneysRepo, createTestJourneyContributorsRepo, createTestJourneyTripsRepo, createTestJourneyEntriesRepo, + createTestJourneyPhotosRepo, createTestJourneyEntryPhotosRepo, } from '../../helpers/journey-repos'; +import { createTestJourneyShareTokensRepo } from '../../helpers/journey-share-repos'; +import type { JourneyPublicGalleryRow, JourneyShareTokensRepository } from '../../../src/db/repositories/JourneyShareTokens.repository'; +import { GALLERY_CHRONOLOGICAL_ORDER } from '../../../src/nest/journey/journey-gallery-order'; const dbs = new DatabaseService(dbConn); let svc: JourneyShareService; @@ -63,14 +67,20 @@ beforeAll(async () => { runMigrations(testDb); const uow = await createTestUnitOfWork(testDb); t = await sharedTestOrm(testDb); + const journeysRepo = await createTestJourneysRepo(testDb); svc = new JourneyShareService( - dbs, new JourneyDomainService( dbs, new RealtimeService(), new TrekPhotoRegistrationService(t.repo(TrekPhotos), t.repo(TripPhotos), dbs), uow, - await createTestJourneysRepo(testDb), await createTestJourneyContributorsRepo(testDb), + journeysRepo, await createTestJourneyContributorsRepo(testDb), await createTestJourneyTripsRepo(testDb), await createTestJourneyEntriesRepo(testDb), await createTestTripsRepo(testDb), + // Plan 3g Task 2 constructor-ripple: JourneyPhotosRepository/JourneyEntryPhotosRepository/PlacesRepository. + await createTestJourneyPhotosRepo(testDb), await createTestJourneyEntryPhotosRepo(testDb), await createTestPlacesRepo(testDb), ), new SettingsService(uow, await createTestAppSettingsRepo(testDb), await createTestSettingsRepo(testDb)), + // Plan 3g Task 3: JourneyShareTokensRepository (JS1-JS15) + the + // already-built JourneysRepository (JS8/JS12), same instance the domain + // service above uses. + await createTestJourneyShareTokensRepo(testDb), journeysRepo, ); }); @@ -627,7 +637,7 @@ describe('getPublicJourney', () => { }); const result = (await svc.getPublicJourney(token))!; - const gallery = result.gallery as Record[]; + const gallery = result.gallery as JourneyPublicGalleryRow[]; expect(gallery).toHaveLength(1); expect(gallery[0].lat).toBeNull(); expect(gallery[0].lng).toBeNull(); @@ -653,7 +663,7 @@ describe('getPublicJourney', () => { share_timeline: true, share_gallery: true, share_map: true, }); - const gallery = (await svc.getPublicJourney(token))!.gallery as Record[]; + const gallery = (await svc.getPublicJourney(token))!.gallery as JourneyPublicGalleryRow[]; expect(gallery[0].lat).toBe(48.8584); expect(gallery[0].lng).toBe(2.2945); }); @@ -695,7 +705,7 @@ describe('getPublicJourney', () => { share_timeline: true, share_gallery: true, share_map: true, }); - const gallery = (await svc.getPublicJourney(token))!.gallery as Record[]; + const gallery = (await svc.getPublicJourney(token))!.gallery as JourneyPublicGalleryRow[]; expect(gallery.map(p => p.file_path)).toEqual(['/photos/day1.jpg', '/photos/day2.jpg']); }); @@ -711,3 +721,253 @@ describe('getPublicJourney', () => { expect((await svc.getPublicJourney(token))!.cartoApiKey).toBe('owner-key'); }); }); + +// -- Parity: JourneyShareTokensRepository reads vs. the legacy raw statement -- + +describe('parity — JourneyShareTokensRepository reads match the legacy statement run raw', () => { + let shareTokensRepo: JourneyShareTokensRepository; + + beforeAll(async () => { + shareTokensRepo = await createTestJourneyShareTokensRepo(testDb); + }); + + it('JOURNEY-SHARE-P01: findFlagsByJourneyId (JS1) matches the legacy 5-column read', async () => { + const { user } = createUser(testDb); + const journey = createJourney(testDb, user.id); + await svc.createOrUpdateJourneyShareLink(journey.id, user.id, { + share_timeline: false, share_gallery: true, share_map: false, newest_first: true, + }); + + const legacy = testDb + .prepare('SELECT token, share_timeline, share_gallery, share_map, newest_first FROM journey_share_tokens WHERE journey_id = ?') + .get(journey.id); + + expect(await shareTokensRepo.findFlagsByJourneyId(journey.id)).toEqual(legacy); + }); + + it('JOURNEY-SHARE-P02: findByJourneyId (JS4) and findByToken (JS11) match the legacy `SELECT *` reads', async () => { + const { user } = createUser(testDb); + const journey = createJourney(testDb, user.id); + const { token } = await svc.createOrUpdateJourneyShareLink(journey.id, user.id, { + share_timeline: true, share_gallery: false, share_map: true, newest_first: false, + }); + + const legacyByJourney = testDb.prepare('SELECT * FROM journey_share_tokens WHERE journey_id = ?').get(journey.id); + const legacyByToken = testDb.prepare('SELECT * FROM journey_share_tokens WHERE token = ?').get(token); + + expect(await shareTokensRepo.findByJourneyId(journey.id)).toEqual(legacyByJourney); + expect(await shareTokensRepo.findByToken(token)).toEqual(legacyByToken); + }); + + it('JOURNEY-SHARE-P03: findAccessByToken (JS6/JS9) matches the legacy narrow projection', async () => { + const { user } = createUser(testDb); + const journey = createJourney(testDb, user.id); + const { token } = await svc.createOrUpdateJourneyShareLink(journey.id, user.id, { share_gallery: false }); + + const legacy = testDb.prepare('SELECT journey_id, share_gallery FROM journey_share_tokens WHERE token = ?').get(token); + + expect(await shareTokensRepo.findAccessByToken(token)).toEqual(legacy); + }); + + it('JOURNEY-SHARE-P04: listPublicEntries (JS13) matches the legacy statement for entries with and without GPS', async () => { + const { user } = createUser(testDb); + const journey = createJourney(testDb, user.id); + createJourneyEntry(testDb, journey.id, user.id, { type: 'entry', entry_date: '2026-01-01', location_name: 'No GPS' }); + const withGps = createJourneyEntry(testDb, journey.id, user.id, { type: 'entry', entry_date: '2026-01-02', location_name: 'Has GPS' }); + testDb.prepare('UPDATE journey_entries SET location_lat = ?, location_lng = ? WHERE id = ?').run(48.85, 2.35, withGps.id); + // A skeleton and a dismissed entry — both must be excluded, same as the legacy WHERE. + createJourneyEntry(testDb, journey.id, user.id, { type: 'skeleton', entry_date: '2026-01-03' }); + const dismissed = createJourneyEntry(testDb, journey.id, user.id, { type: 'entry', entry_date: '2026-01-04' }); + testDb.prepare('UPDATE journey_entries SET dismissed = 1 WHERE id = ?').run(dismissed.id); + + const legacy = testDb + .prepare(` + SELECT je.* FROM journey_entries je + WHERE je.journey_id = ? AND je.type != 'skeleton' AND je.dismissed = 0 + ORDER BY je.entry_date, je.sort_order + `) + .all(journey.id); + + expect(await shareTokensRepo.listPublicEntries(journey.id)).toEqual(legacy); + }); + + it('JOURNEY-SHARE-P05: listEntryPhotosForPublicJourney (JS14) matches the legacy JP_SELECT-shaped statement', async () => { + const { user } = createUser(testDb); + const journey = createJourney(testDb, user.id); + const entry = createJourneyEntry(testDb, journey.id, user.id, { type: 'entry', entry_date: '2026-01-01' }); + insertJourneyPhoto(entry.id, { ownerId: user.id }); + + const legacy = testDb + .prepare(` + SELECT gp.id, jep.entry_id, gp.photo_id, gp.caption, jep.sort_order, gp.shared, gp.created_at, + tkp.provider, tkp.asset_id, tkp.owner_id, tkp.file_path, tkp.thumbnail_path, tkp.width, tkp.height, + tkp.media_type, tkp.duration_ms, tkp.taken_at, tkp.lat, tkp.lng + FROM journey_entry_photos jep + JOIN journey_photos gp ON gp.id = jep.journey_photo_id + JOIN trek_photos tkp ON tkp.id = gp.photo_id + WHERE gp.journey_id = ? + ORDER BY jep.sort_order + `) + .all(journey.id); + + expect(await shareTokensRepo.listEntryPhotosForPublicJourney(journey.id)).toEqual(legacy); + }); + + it('JOURNEY-SHARE-P06: listGalleryForPublicJourney (JS15, GALLERY_CHRONOLOGICAL_ORDER) matches the legacy statement — a photo linked to an entry AND an unattached gallery photo', async () => { + const { user } = createUser(testDb); + const journey = createJourney(testDb, user.id); + const entry = createJourneyEntry(testDb, journey.id, user.id, { type: 'entry', entry_date: '2026-01-01' }); + insertJourneyPhoto(entry.id, { ownerId: user.id, filePath: '/photos/linked.jpg' }); // linked to an entry + // An unattached gallery photo — uploaded straight to the gallery, no journey_entry_photos row. + const unattachedTrekId = testDb + .prepare('INSERT INTO trek_photos (provider, asset_id, owner_id, file_path, created_at) VALUES (?, ?, ?, ?, ?)') + .run('local', null, user.id, '/photos/unattached.jpg', Date.now()).lastInsertRowid as number; + testDb + .prepare('INSERT INTO journey_photos (journey_id, photo_id, sort_order, created_at) VALUES (?, ?, ?, ?)') + .run(journey.id, unattachedTrekId, 1, Date.now()); + + const legacy = testDb + .prepare(` + SELECT gp.id, gp.journey_id, gp.photo_id, gp.caption, gp.shared, gp.sort_order, gp.created_at, + tp.provider, tp.asset_id, tp.owner_id, tp.file_path, tp.thumbnail_path, tp.width, tp.height, + tp.media_type, tp.duration_ms, tp.taken_at, tp.lat, tp.lng + FROM journey_photos gp + JOIN trek_photos tp ON tp.id = gp.photo_id + WHERE gp.journey_id = ? + ${GALLERY_CHRONOLOGICAL_ORDER} + `) + .all(journey.id); + + expect(await shareTokensRepo.listGalleryForPublicJourney(journey.id)).toEqual(legacy); + expect(legacy).toHaveLength(2); + }); + + it('JOURNEY-SHARE-P07: every true/false combination of the three share flags (+ newest_first) round-trips through the converted read exactly', async () => { + const { user } = createUser(testDb); + for (const share_timeline of [true, false]) { + for (const share_gallery of [true, false]) { + for (const share_map of [true, false]) { + for (const newest_first of [true, false]) { + const journey = createJourney(testDb, user.id); + await svc.createOrUpdateJourneyShareLink(journey.id, user.id, { share_timeline, share_gallery, share_map, newest_first }); + const link = await svc.getJourneyShareLink(journey.id); + expect(link).toEqual({ + token: link!.token, + created_at: link!.created_at, + share_timeline, share_gallery, share_map, newest_first, + }); + } + } + } + } + }); +}); + +// -- R4: the six anonymous share-token statements — exact-match only --------- + +describe('R4 — JS6/JS9/JS11 are exact-match token lookups (revoked / wrong-case / NUL)', () => { + it('JOURNEY-SHARE-R01: validateShareTokenForPhoto 404s (null) for a revoked token', async () => { + const { user } = createUser(testDb); + const journey = createJourney(testDb, user.id); + const entry = createJourneyEntry(testDb, journey.id, user.id, { type: 'entry', entry_date: '2026-01-01' }); + const photoId = insertJourneyPhoto(entry.id, { ownerId: user.id }); + const { token } = await svc.createOrUpdateJourneyShareLink(journey.id, user.id, {}); + await svc.deleteJourneyShareLink(journey.id, user.id); + + expect(await svc.validateShareTokenForPhoto(token, photoId)).toBeNull(); + }); + + it('JOURNEY-SHARE-R02: validateShareTokenForAsset 404s (null) for a revoked token', async () => { + const { user } = createUser(testDb); + const journey = createJourney(testDb, user.id); + const entry = createJourneyEntry(testDb, journey.id, user.id, { type: 'entry', entry_date: '2026-01-01' }); + insertJourneyPhoto(entry.id, { assetId: 'revoked-asset', ownerId: user.id }); + const { token } = await svc.createOrUpdateJourneyShareLink(journey.id, user.id, {}); + await svc.deleteJourneyShareLink(journey.id, user.id); + + expect(await svc.validateShareTokenForAsset(token, 'revoked-asset')).toBeNull(); + }); + + it('JOURNEY-SHARE-R03: getPublicJourney 404s (null) for a revoked token, not a stale cached response', async () => { + const { user } = createUser(testDb); + const journey = createJourney(testDb, user.id); + const { token } = await svc.createOrUpdateJourneyShareLink(journey.id, user.id, {}); + expect(await svc.getPublicJourney(token)).not.toBeNull(); + + await svc.deleteJourneyShareLink(journey.id, user.id); + + expect(await svc.getPublicJourney(token)).toBeNull(); + }); + + it('JOURNEY-SHARE-R04: validateShareTokenForPhoto does not match a differently-cased token', async () => { + const { user } = createUser(testDb); + const journey = createJourney(testDb, user.id); + const entry = createJourneyEntry(testDb, journey.id, user.id, { type: 'entry', entry_date: '2026-01-01' }); + const photoId = insertJourneyPhoto(entry.id, { ownerId: user.id }); + const { token } = await svc.createOrUpdateJourneyShareLink(journey.id, user.id, {}); + const wrongCase = flipCase(token); + + expect(await svc.validateShareTokenForPhoto(wrongCase, photoId)).toBeNull(); + // Mutation proof (loosen → red): a COLLATE NOCASE lookup on the SAME row + // WOULD wrongly match — proving the null above depends on the real + // exact-match WHERE, not a coincidence of the fixture. + expect(testDb.prepare('SELECT 1 FROM journey_share_tokens WHERE token = ? COLLATE NOCASE').get(wrongCase)).toBeTruthy(); + }); + + it('JOURNEY-SHARE-R05: validateShareTokenForAsset does not match a differently-cased token', async () => { + const { user } = createUser(testDb); + const journey = createJourney(testDb, user.id); + const entry = createJourneyEntry(testDb, journey.id, user.id, { type: 'entry', entry_date: '2026-01-01' }); + insertJourneyPhoto(entry.id, { assetId: 'case-asset', ownerId: user.id }); + const { token } = await svc.createOrUpdateJourneyShareLink(journey.id, user.id, {}); + const wrongCase = flipCase(token); + + expect(await svc.validateShareTokenForAsset(wrongCase, 'case-asset')).toBeNull(); + expect(testDb.prepare('SELECT 1 FROM journey_share_tokens WHERE token = ? COLLATE NOCASE').get(wrongCase)).toBeTruthy(); + }); + + it('JOURNEY-SHARE-R06: getPublicJourney does not match a differently-cased token', async () => { + const { user } = createUser(testDb); + const journey = createJourney(testDb, user.id); + const { token } = await svc.createOrUpdateJourneyShareLink(journey.id, user.id, {}); + const wrongCase = flipCase(token); + + expect(await svc.getPublicJourney(wrongCase)).toBeNull(); + expect(testDb.prepare('SELECT 1 FROM journey_share_tokens WHERE token = ? COLLATE NOCASE').get(wrongCase)).toBeTruthy(); + }); + + it('JOURNEY-SHARE-R07: validateShareTokenForPhoto does not match a token with an embedded NUL byte', async () => { + const { user } = createUser(testDb); + const journey = createJourney(testDb, user.id); + const entry = createJourneyEntry(testDb, journey.id, user.id, { type: 'entry', entry_date: '2026-01-01' }); + const photoId = insertJourneyPhoto(entry.id, { ownerId: user.id }); + const { token } = await svc.createOrUpdateJourneyShareLink(journey.id, user.id, {}); + + expect(await svc.validateShareTokenForPhoto(`${token}\0trailing`, photoId)).toBeNull(); + expect(await svc.validateShareTokenForPhoto(`${token.slice(0, 5)}\0${token.slice(5)}`, photoId)).toBeNull(); + }); + + it('JOURNEY-SHARE-R08: validateShareTokenForAsset does not match a token with an embedded NUL byte', async () => { + const { user } = createUser(testDb); + const journey = createJourney(testDb, user.id); + const entry = createJourneyEntry(testDb, journey.id, user.id, { type: 'entry', entry_date: '2026-01-01' }); + insertJourneyPhoto(entry.id, { assetId: 'nul-asset', ownerId: user.id }); + const { token } = await svc.createOrUpdateJourneyShareLink(journey.id, user.id, {}); + + expect(await svc.validateShareTokenForAsset(`${token}\0trailing`, 'nul-asset')).toBeNull(); + }); + + it('JOURNEY-SHARE-R09: getPublicJourney does not match a token with an embedded NUL byte', async () => { + const { user } = createUser(testDb); + const journey = createJourney(testDb, user.id); + const { token } = await svc.createOrUpdateJourneyShareLink(journey.id, user.id, {}); + + expect(await svc.getPublicJourney(`${token}\0trailing`)).toBeNull(); + }); +}); + +/** A token with at least one letter flipped in case — base64url alphabet, near-certain to differ. */ +function flipCase(token: string): string { + const upper = token.toUpperCase(); + return upper !== token ? upper : token.toLowerCase(); +} diff --git a/server/tests/unit/plugins/addon-gates.rpc.test.ts b/server/tests/unit/plugins/addon-gates.rpc.test.ts index efa6cdf61..c4a7d2533 100644 --- a/server/tests/unit/plugins/addon-gates.rpc.test.ts +++ b/server/tests/unit/plugins/addon-gates.rpc.test.ts @@ -74,7 +74,9 @@ function build(addonOn: boolean) { { put: async () => undefined, delete: async () => undefined } as never, { get: () => '*' } as never, { schedule: () => undefined } as never, - { prepare: () => ({ get: () => ({ email: 'u@example.test' }) }) } as never), + // Plan 3g Task 3: JR1's demo-mode gate reads through `UsersRepository + // .getEmail`, not `DatabaseService.prepare`. + { getEmail: async () => 'u@example.test' } as never), new CollectionsRpc(spyService(calls, 'collections'), guards), new CostsRpc(spyService(calls, 'budget'), db, { broadcast: vi.fn() } as never, guards, spyService(calls, 'membership')), ]); diff --git a/server/tests/unit/plugins/journal-photo.rpc.test.ts b/server/tests/unit/plugins/journal-photo.rpc.test.ts index 675b5fd46..891789d3e 100644 --- a/server/tests/unit/plugins/journal-photo.rpc.test.ts +++ b/server/tests/unit/plugins/journal-photo.rpc.test.ts @@ -44,7 +44,9 @@ function build(overrides: { { put, delete: del } as never, { get: () => overrides.allowed ?? '*' } as never, { schedule } as never, - { prepare: () => ({ get: () => ({ email: overrides.email ?? 'user@example.test' }) }) } as never, + // Plan 3g Task 3: JR1's demo-mode gate reads through `UsersRepository + // .getEmail`, not `DatabaseService.prepare`. + { getEmail: async () => overrides.email ?? 'user@example.test' } as never, ); return { rpc, put, del, schedule, addPhoto }; }