fix(share): keep private data and photo locations out of public trip and journey links

Public trip and journey share links handed out more than the owner chose to
share:

- A travel-only trip link still returned every day's title, and every link with
  the map returned the free-text day notes the shared page never shows. Days now
  go out through a public projection without notes, and travel-only links carry
  no day titles. Day notes, packing, budget and chat use explicit field lists
  too, and the category list holds only the categories the shared places use,
  without creator ids.
- The public journey payload spread whole entry and photo rows, including
  storage keys (file_path, thumbnail_path) and internal fields. It is now built
  from allow-lists and pinned by a strict response contract.
- /uploads/journey served every entry photo, original and video to anyone who
  knew the file name, so a URL kept working after a share link was revoked or
  the gallery switched off. It now serves journey covers and other non-entry
  objects only; entry media go through the token-checked proxy.
- Anonymous byte paths served stored originals unchanged, so EXIF GPS left the
  server even with map sharing off. Every public path (journey share proxy,
  covers, trip share photos, public uploads) now sends a copy with location
  data blanked in place (EXIF GPS, XMP and IPTC location, MP4/MOV location
  atoms), falling back to a metadata-free re-encode or a 404, never the raw
  file. Owners and members still get their originals.
- An entry's visibility field never decided the share link but was offered by
  MCP and the assistant as if it did. It is now documented as having no effect
  and no longer shown as a privacy label; is_draft keeps an entry off the link.
This commit is contained in:
Maurice
2026-11-20 18:18:50 +01:00
parent ec7f5e0585
commit 411ec4af59
89 changed files with 3206 additions and 427 deletions
-1
View File
@@ -1542,7 +1542,6 @@
"src/pages/journeyDetail/useJourneyDetail.ts",
"src/pages/journeyDetail/useProviderPhotoAdds.test.tsx",
"src/pages/journeyDetail/useProviderPhotoAdds.ts",
"src/pages/journeyPublic/journeyPublicModel.ts",
"src/pages/journeyPublic/useJourneyPublic.ts",
"src/pages/journeyStudio/useJourneyStudio.test.tsx",
"src/pages/journeyStudio/useJourneyStudio.ts",
@@ -47,7 +47,6 @@ function look(over: Partial<JourneyEntryLook> = {}): JourneyEntryLook {
photoId: 7,
video: false,
photoCount: 1,
visibility: 'private',
draft: false,
fromTripPlace: false,
dayIndex: 0,
@@ -86,13 +85,15 @@ afterEach(() => {
describe('the journal entries card', () => {
it('FE-AI-JOURNEY-001: one entry reads as a row with its photo, facts, marks and text under the journal', () => {
const { container } = block([card([look({ visibility: 'public', draft: true, photoCount: 4, video: true })])]);
// A card stored while entries carried a visibility: it reads, and says nothing of it.
const stored = { ...look({ draft: true, photoCount: 4, video: true }), visibility: 'public' };
const { container } = block([card([stored])]);
expect(screen.getByRole('region', { name: 'Journal entries' })).toBeInTheDocument();
expect(screen.getByText('Sunset at the Spree')).toBeInTheDocument();
expect(screen.getByText('14:30')).toBeInTheDocument();
expect(screen.getByText('Berlin')).toBeInTheDocument();
expect(screen.getByText('The light over the river was unreal.')).toBeInTheDocument();
expect(screen.getByText('Public')).toBeInTheDocument();
expect(screen.queryByText('Public')).toBeNull();
expect(screen.getByText('Draft')).toBeInTheDocument();
expect(screen.getByText('4 photos')).toBeInTheDocument();
expect(screen.getByText('Opens with a video')).toBeInTheDocument();
@@ -225,13 +226,12 @@ describe('a change row of a journal entry', () => {
}
it('FE-AI-JOURNEY-008: a waiting delete shows the photo, the text and that it goes back to a suggestion; a receipt opens it', () => {
const entry = look({ fromTripPlace: true, visibility: 'shared' });
const entry = look({ fromTripPlace: true });
const held = card([entry], { change: 'willDelete', tripJournal: true });
const onOpen = vi.fn();
const first = inView(<AssistantChangeCard items={[item('pending', held)]} />, { onOpen });
expect(screen.getByText('Delete the journal entry')).toBeInTheDocument();
expect(screen.getByText('The light over the river was unreal.')).toBeInTheDocument();
expect(screen.getByText('Shared')).toBeInTheDocument();
expect(screen.getByText('Goes back to a suggestion')).toBeInTheDocument();
expect(screen.getByText('Tue, Oct 21')).toBeInTheDocument();
expect(screen.getByText('Museum Island')).toBeInTheDocument();
@@ -255,7 +255,6 @@ describe('a change row of a journal entry', () => {
{ op: 'change', labelKey: 'name', before: 'Sunset', after: 'Sunset at the Spree' },
{ op: 'change', labelKey: 'time', before: '14:30', after: '' },
{ op: 'change', labelKey: 'text', before: 'Old story', after: 'New story' },
{ op: 'change', labelKey: 'field', field: 'visibility', before: 'private', after: 'public' },
{ op: 'change', labelKey: 'field', field: 'mood', before: 'good', after: '' },
{ op: 'change', labelKey: 'field', field: 'weather', before: 'sunny', after: 'Drizzle' },
{ op: 'change', labelKey: 'field', field: 'is_draft', before: '✓', after: '✗' },
@@ -267,8 +266,6 @@ describe('a change row of a journal entry', () => {
expect(screen.getByText('14:30')).toHaveClass('line-through');
expect(screen.getByText('Old story')).toHaveClass('line-through');
expect(screen.getByText('New story')).toBeInTheDocument();
expect(screen.getByText('Private')).toHaveClass('line-through');
expect(screen.getByText('Public')).toBeInTheDocument();
expect(screen.getByText('Good')).toHaveClass('line-through');
expect(screen.getByText('Sunny')).toHaveClass('line-through');
expect(screen.getByText('Drizzle')).toBeInTheDocument();
@@ -28,7 +28,6 @@ const ENTRY: JourneyEntryLook = {
photoId: null,
video: false,
photoCount: 0,
visibility: 'private',
draft: false,
fromTripPlace: false,
dayIndex: null,
@@ -1,5 +1,5 @@
import type { JourneyEntryLook } from '@trek/shared';
import { CalendarDays, Globe, Images, MapPin, Play, Tag, ThumbsDown, ThumbsUp, Users } from 'lucide-react';
import { CalendarDays, Images, MapPin, Play, Tag, ThumbsDown, ThumbsUp } from 'lucide-react';
import { useTranslation } from '../../../../i18n';
import { cardDateLabel, cardPlace } from '../../../Journey/journeyCard';
@@ -12,8 +12,8 @@ import { moodOf, weatherOf } from './journeyTones';
/**
* The pieces a journal entry is drawn from in the chat, the same in an
* answer, a change row and a receipt: its photo, the facts of when and where
* as the planner's badges, the marks of how it reads (shared, draft, mood,
* weather, more photos) and the start of its text. Every fact wraps, none is
* as the planner's badges, the marks of how it reads (draft, mood, weather,
* more photos) and the start of its text. Every fact wraps, none is
* cut.
*/
@@ -63,19 +63,6 @@ export function EntryWhen({ look }: { look: JourneyEntryLook }) {
);
}
/** Shared or public; nothing for a private entry. */
function VisibilityMark({ visibility }: { visibility: JourneyEntryLook['visibility'] }) {
const { t } = useTranslation();
if (visibility === 'private') return null;
const shared = visibility === 'shared';
const Icon = shared ? Users : Globe;
return (
<SoftPill tone="info" icon={<Icon size={10} strokeWidth={2.2} aria-hidden="true" />}>
{shared ? t('journey.visibility.shared') : t('journey.visibility.public')}
</SoftPill>
);
}
/** A mood the journal knows, in its own colour; nothing for any other. */
function MoodMark({ id }: { id: string | null }) {
const { t } = useTranslation();
@@ -129,17 +116,16 @@ function ListMarks({ look }: { look: JourneyEntryLook }) {
);
}
/** How the entry reads: shared or public, a draft, its mood and weather, its photos past the first, its tags and verdict. */
/** How the entry reads: a draft, its mood and weather, its photos past the first, its tags and verdict. */
export function EntryMarks({ look }: { look: JourneyEntryLook }) {
const { t } = useTranslation();
const mood = moodOf(look.mood) !== null;
const lists = (look.tags?.length ?? 0) > 0 || !!look.verdict;
if (look.visibility === 'private' && !look.draft && !mood && !look.weather && look.photoCount < 2 && !lists) {
if (!look.draft && !mood && !look.weather && look.photoCount < 2 && !lists) {
return null;
}
return (
<CardFacts>
<VisibilityMark visibility={look.visibility} />
{look.draft && <SoftPill tone="warning">{t('journey.entry.draft')}</SoftPill>}
<MoodMark id={look.mood} />
<WeatherMark weather={look.weather} />
@@ -31,7 +31,6 @@ function look(over: Partial<JourneyEntryLook> = {}): JourneyEntryLook {
photoId: null,
video: false,
photoCount: 0,
visibility: 'private',
draft: false,
fromTripPlace: false,
dayIndex: null,
@@ -97,12 +96,13 @@ describe('journeyCardModel', () => {
});
it('FE-AI-JOURNEY-MODEL-009: the states an update sets are named by field, flags by on and off', () => {
expect(stateOf('visibility', 'public')?.labelKey).toBe('journey.visibility.public');
// The stored visibility keeps nothing off the share link, so it has no name to show.
expect(stateOf('visibility', 'private')).toBeNull();
expect(stateOf('type', 'skeleton')?.labelKey).toBe('journey.entry.suggestion');
expect(stateOf('mood', 'good')?.labelKey).toBe('journey.mood.good');
expect(stateOf('weather', 'cold')?.labelKey).toBe('journey.weather.cold');
expect(stateOf('weather', 'Drizzle')).toBeNull();
expect(stateOf('visibility', 'toString')).toBeNull();
expect(stateOf('type', 'toString')).toBeNull();
expect(stateOf(undefined, 'public')).toBeNull();
expect(flagOf('is_draft', '✓')?.labelKey).toBe('journey.entry.draft');
expect(flagOf('is_draft', '✗')?.labelKey).toBe('assistant.card.journey.notDraft');
@@ -7,8 +7,6 @@ import {
Eye,
EyeOff,
Frown,
Globe,
Lock,
type LucideIcon,
MapPinCheck,
Meh,
@@ -19,14 +17,13 @@ import {
Snowflake,
Sparkles,
Sun,
Users,
} from 'lucide-react';
/**
* How the states of a journal entry read in the chat, the way the journal
* draws them: its moods with the glyphs of its tiles, its weathers, and the
* words for what an update sets beyond the text (who sees the entry, its
* kind, a draft, the route, a waved-away suggestion).
* words for what an update sets beyond the text (its kind, a draft, the
* route, a waved-away suggestion).
*/
/** How a state is drawn: its glyph and the key of its name. */
@@ -57,12 +54,6 @@ const WEATHERS: Readonly<Record<string, EntryTone>> = {
cold: { Icon: Snowflake, labelKey: 'journey.weather.cold' },
};
const VISIBILITIES: Readonly<Record<string, EntryTone>> = {
private: { Icon: Lock, labelKey: 'journey.visibility.private' },
shared: { Icon: Users, labelKey: 'journey.visibility.shared' },
public: { Icon: Globe, labelKey: 'journey.visibility.public' },
};
const TYPES: Readonly<Record<string, EntryTone>> = {
entry: { Icon: BookOpenText, labelKey: 'assistant.card.journey.typeEntry' },
checkin: { Icon: MapPinCheck, labelKey: 'assistant.card.journey.typeCheckin' },
@@ -119,7 +110,6 @@ export function flagOf(field: string | undefined, value: string): EntryTone | nu
export function stateOf(field: string | undefined, value: string | null): EntryTone | null {
if (field === 'mood') return moodOf(value);
if (field === 'weather') return weatherOf(value);
if (field === 'visibility') return own(VISIBILITIES, value);
if (field === 'type') return own(TYPES, value);
return null;
}
+5 -4
View File
@@ -576,8 +576,9 @@ describe('JourneyPublicPage', () => {
// broken-image glyph on every shared layout (#2341).
it('FE-PAGE-PUBLICJOURNEY-023: a shared clip without a poster is a black tile, with a poster its poster', async () => {
const user = userEvent.setup();
const bare = { id: 200, entry_id: 20, photo_id: 200, provider: 'local', asset_id: null, owner_id: null, file_path: 'journey/a.mp4', thumbnail_path: null, media_type: 'video', caption: null };
const withPoster = { id: 201, entry_id: 21, photo_id: 201, provider: 'local', asset_id: null, owner_id: null, file_path: 'journey/b.mp4', thumbnail_path: 'journey/b.jpg', media_type: 'video', caption: null };
// The share link carries no storage key: the server says which clip has no poster.
const bare = { id: 200, photo_id: 200, media_type: 'video', caption: null, posterless: true };
const withPoster = { id: 201, photo_id: 201, media_type: 'video', caption: null, posterless: false };
const entry = (id: number, photo: typeof bare) => ({
id, title: `Clip ${id}`, story: null, entry_date: '2026-03-15', entry_time: null,
location_name: null, location_lat: null, location_lng: null, mood: null, weather: null, pros_cons: null,
@@ -587,8 +588,8 @@ describe('JourneyPublicPage', () => {
...mockJourneyData,
entries: [entry(20, bare), entry(21, withPoster)],
gallery: [
{ ...bare, journey_id: 1, shared: 1, sort_order: 0, created_at: 0 },
{ ...withPoster, journey_id: 1, shared: 1, sort_order: 1, created_at: 0 },
{ ...bare, lat: null, lng: null, taken_at: null },
{ ...withPoster, lat: null, lng: null, taken_at: null },
],
stats: { entries: 2, photos: 2, places: 0 },
})));
@@ -39,7 +39,7 @@ vi.mock('../components/Journey/JournalBody', () => ({
// ── Fixtures ─────────────────────────────────────────────────────────────────
function photo(id: number): PublicEntry['photos'][number] {
return { id, entry_id: 1, photo_id: id * 10, caption: `caption ${id}`, provider: 'local' };
return { id, photo_id: id * 10, caption: `caption ${id}`, posterless: false };
}
function buildEntry(over: Partial<PublicEntry> = {}): PublicEntry {
@@ -260,6 +260,13 @@ describe('posterlessVideo (#2341)', () => {
expect(posterlessVideo({ provider: 'local', thumbnail_path: null })).toBe(false);
expect(posterlessVideo({ media_type: 'video', provider: 'immich', thumbnail_path: null })).toBe(false);
});
it('takes the answer a shared journey sends, which carries no storage key', () => {
expect(posterlessVideo({ media_type: 'video', posterless: true })).toBe(true);
expect(posterlessVideo({ media_type: 'video', posterless: false })).toBe(false);
// The flag wins over the columns, so a public photo never needs them.
expect(posterlessVideo({ media_type: 'video', provider: 'local', thumbnail_path: null, posterless: false })).toBe(false);
});
});
describe('fetchRemainingProviderPages (#1587)', () => {
@@ -95,12 +95,17 @@ export function photoUrl(p: { photo_id: number }, size: 'thumbnail' | 'original'
* purpose rather than streaming the whole file, and an <img> pointed at it
* shows the broken-image glyph (#2341). A provider clip is not one of these,
* its poster comes from the provider whether or not a local path is recorded.
*
* A shared journey carries no storage keys, so the server answers the question
* itself there (`posterless`).
*/
export function posterlessVideo(p: {
media_type?: string | null;
provider?: string | null;
thumbnail_path?: string | null;
posterless?: boolean;
}): boolean {
if (typeof p.posterless === 'boolean') return p.posterless;
return p.media_type === 'video' && p.provider === 'local' && !p.thumbnail_path;
}
@@ -4,68 +4,61 @@
* presentational page.
*/
/**
* An entry as the share link sends it (`journeyPublicEntrySchema` in
* @trek/shared). A map-only share leaves out the story fields and the photos.
*/
export interface PublicEntry {
id: number
type?: string | null
sort_order?: number | null
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
pros_cons?: { pros: string[]; cons: string[] } | null
photos: PublicPhoto[]
id: number;
type?: string | null;
sort_order?: number | null;
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;
country_code?: string | null;
mood?: string | null;
weather?: string | null;
tags?: string[];
pros_cons?: { pros: string[]; cons: string[] } | null;
photos: PublicPhoto[];
}
/**
* A photo of a shared journey (`journeyPublicPhotoSchema`). It carries no
* storage key or asset id: the bytes are fetched by `photo_id` through the
* share token.
*/
export interface PublicPhoto {
id: number
entry_id: number
photo_id: number
provider?: string
asset_id?: string | null
owner_id?: number | null
file_path?: string | null
caption?: string | null
id: number;
photo_id: number;
caption?: string | null;
// 'image' (default) or 'video' (#823)
media_type?: string | null
/** Null on a local clip whose poster frame could not be grabbed; the page
* draws a marked tile instead of an <img> then (#2341). */
thumbnail_path?: string | null
duration_ms?: number | null
media_type?: string | null;
width?: number | null;
height?: number | null;
duration_ms?: number | null;
/** A clip whose poster frame could not be grabbed; the page draws a plain tile instead of an <img> (#2341). */
posterless?: boolean;
}
export interface PublicGalleryPhoto {
id: number
journey_id: number
photo_id: number
provider?: string
asset_id?: string | null
owner_id?: number | null
file_path?: string | null
caption?: string | null
// 'image' (default) or 'video' (#823)
media_type?: string | null
/** Null on a local clip whose poster frame could not be grabbed; the gallery
* draws a marked tile instead of an <img> then (#2341). */
thumbnail_path?: string | null
duration_ms?: number | null
/** Where and when the picture was taken (#1614). Absent for most photos, and the
export interface PublicGalleryPhoto extends PublicPhoto {
/** When and where the picture was taken (#1614). Absent for most photos, and the
* coordinates are withheld entirely unless the owner shared the map. */
taken_at?: string | null
lat?: number | null
lng?: number | null
taken_at?: string | null;
lat?: number | null;
lng?: number | null;
}
export function groupByDate(entries: PublicEntry[]): Map<string, PublicEntry[]> {
const groups = new Map<string, PublicEntry[]>()
const groups = new Map<string, PublicEntry[]>();
for (const e of entries) {
const d = e.entry_date
if (!groups.has(d)) groups.set(d, [])
groups.get(d)!.push(e)
const d = e.entry_date;
if (!groups.has(d)) groups.set(d, []);
groups.get(d)!.push(e);
}
return groups
return groups;
}
+1 -1
View File
@@ -1,6 +1,6 @@
{
"src": {
"@typescript-eslint/no-explicit-any": 84,
"@typescript-eslint/no-explicit-any": 81,
"@typescript-eslint/no-non-null-assertion": 263,
"@typescript-eslint/no-require-imports": 18,
"@typescript-eslint/no-unsafe-function-type": 1,
@@ -365,7 +365,6 @@
"route-usage -> AppSettings (owned by settings)",
"school-holidays -> VacayHolidayCalendars (owned by vacay)",
"share -> BudgetItems (owned by budget)",
"share -> Categories (owned by categories)",
"share -> CollabMessages (owned by collab)",
"share -> DayAssignments (owned by assignments)",
"share -> DayNotes (owned by day-notes)",
@@ -27,7 +27,7 @@
"src/nest/help/help.controller.ts": 4,
"src/nest/integrations/airtrail.controller.ts": 6,
"src/nest/integrations/dawarich.controller.ts": 15,
"src/nest/journey/journey-public.controller.ts": 3,
"src/nest/journey/journey-public.controller.ts": 2,
"src/nest/journey/journey.controller.ts": 20,
"src/nest/llm-parse/llm-capabilities.controller.ts": 1,
"src/nest/llm-parse/llm-local.controller.ts": 2,
+3 -1
View File
@@ -11,6 +11,7 @@ import { PUBLIC_ROUTE_ALLOW_LIST, validateRouteGuards } from './nest/common/vali
import { DatabaseLifecycle } from './nest/database/database-lifecycle.service';
import { withRequestContext } from './nest/database/request-context';
import { MANAGED_PUBLIC_ROUTES } from './nest/managed/managed-ext.module';
import { PublicMediaService } from './nest/memories/public-media.service';
import { setupApiDocs } from './nest/platform/api-docs';
import { MCP_METADATA_MIDDLEWARE } from './nest/platform/mcp-metadata.middleware';
import { applyPlatformUploads, applyPlatformStatic } from './nest/platform/platform.routes';
@@ -146,7 +147,8 @@ export async function buildApp(): Promise<INestApplication> {
// Same pre-init consumption bridge as httpConfig above: the StorageService
// instance is resolvable before init, and the handlers only *register* here —
// per-request resolution runs after app.init() completed the registry load.
applyPlatformUploads(instance, app.get(StorageService), orm);
// PublicMediaService hands anonymous viewers the location-free copies.
applyPlatformUploads(instance, app.get(StorageService), orm, app.get(PublicMediaService));
// The SDK discovery router (+ its addon gate). Container-built so its deps
// are injected (same pre-init consumption bridge as httpConfig above), but
// applied here as a PATHLESS app.use: the SDK router matches absolute
@@ -21,18 +21,6 @@ export class CategoriesRepository extends TrekRepository<Categories> {
return categories.map((category) => toRow(category) as CategoryRow);
}
/**
* `share.service.ts:396` SH15 (`getSharedTripData`) — `SELECT * FROM
* categories`, no `ORDER BY` (unlike `list()` above, which adds `ORDER BY
* name ASC` for the authenticated `/api/categories` list — the legacy
* public-share statement never sorted). Unscoped by trip on purpose: "a
* shared global pool", the same statement the authed list reads from.
*/
async listAllUnordered(): Promise<CategoryRow[]> {
const categories = await this.find({});
return categories.map((category) => toRow(category) as CategoryRow);
}
/**
* PL33 (`PlacesService.importKmlPlaces`) — `SELECT id, name FROM
* categories`, the id/name-only projection the KML importer folds into
@@ -231,6 +231,11 @@ export class JourneysRepository extends TrekRepository<Journeys> {
await this.nativeUpdate({ id }, { cover_image });
}
/** Whether some journey names one of these stored values as its cover (the anonymous /uploads/journey gate). */
async isCoverImage(values: string[]): Promise<boolean> {
return (await this.count({ cover_image: { $in: values } })) > 0;
}
/**
* JG24 — `updateJourney`'s dynamic SET (R6, `presenceSet`). The SERVICE
* resolves every field to its final bound value first (the `ALLOWED_STATUSES`
@@ -50,6 +50,12 @@ export class TrekPhotosRepository extends TrekRepository<TrekPhotos> {
return row ? { id: row.id } : null;
}
/** Whether some row holds one of `paths` as its file or its poster: the journey entry media. */
async referencesLocalPath(paths: string[]): Promise<boolean> {
const count = await this.count({ $or: [{ file_path: { $in: paths } }, { thumbnail_path: { $in: paths } }] });
return count > 0;
}
/** PH5 — `INSERT INTO trek_photos (provider, file_path, thumbnail_path, width, height, media_type, duration_ms)`, always `provider = 'local'`. */
async insertLocal(data: {
file_path: string;
@@ -44,7 +44,6 @@ const ENTRY_FIELDS = [
'location_lng',
'mood',
'weather',
'visibility',
'type',
'is_draft',
'tags',
@@ -52,7 +51,7 @@ const ENTRY_FIELDS = [
] as const;
/** The states of an entry an update can set, each a row of its own when it changes. */
const STATE_FIELDS = ['visibility', 'mood', 'weather', 'type', 'is_draft', 'stats_excluded', 'dismissed'] as const;
const STATE_FIELDS = ['mood', 'weather', 'type', 'is_draft', 'stats_excluded', 'dismissed'] as const;
const FLAG_FIELDS: ReadonlySet<string> = new Set(['is_draft', 'stats_excluded', 'dismissed']);
/** The journal the open trip shows, as `get_trip_journal` answers. */
@@ -3,7 +3,6 @@ import {
compareCodeUnits,
JOURNEY_CARD_LIMITS,
journeyEntryTypeSchema,
journeyEntryVisibilitySchema,
stripMarkdown,
type JourneyEntriesCard,
type JourneyEntryLook,
@@ -113,7 +112,6 @@ export function lookOf(value: unknown, source: LookSource = {}): JourneyEntryLoo
if (!date) return null;
const photos = Array.isArray(row.photos) ? row.photos.map(recordOf) : [];
const type = journeyEntryTypeSchema.safeParse(row.type);
const visibility = journeyEntryVisibilitySchema.safeParse(row.visibility);
const country = typeof row.country_code === 'string' ? row.country_code : '';
const mood = typeof row.mood === 'string' ? row.mood.trim().toLowerCase() : '';
const day = source.days?.indexOf(date) ?? -1;
@@ -131,7 +129,6 @@ export function lookOf(value: unknown, source: LookSource = {}): JourneyEntryLoo
weather: lineOf(row, 'weather', JOURNEY_CARD_LIMITS.weather, source),
...coverOf(photos),
photoCount: Math.min(photos.length, 1_000_000),
visibility: visibility.success ? visibility.data : 'private',
draft: row.is_draft === true || row.is_draft === 1,
fromTripPlace: positiveId(row.source_place_id) !== null && row.type !== 'skeleton',
dayIndex: day >= 0 && day <= 9_999 ? day : null,
@@ -0,0 +1,97 @@
import type { JourneyEntryWire } from './journey-entry-row';
import type { JourneyPublicEntry, JourneyPublicPhoto } from '@trek/shared';
/**
* The public journey payload, built field by field.
*
* The share link used to spread whole rows into its answer, so every column
* the reads selected went out to anyone holding the link: the storage keys of
* local photos (`journey/<uuid>.jpg`), provider asset ids, the photo owner,
* the entry author and its source ids. Each function below names what the
* public page reads and nothing else, so a column added to a read later stays
* on the server unless it is added here on purpose.
*/
/** The photo columns the public reads select; only some of them go out. */
interface PublicPhotoSource {
id: number;
photo_id: number;
caption?: string | null;
provider?: 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;
}
/**
* A photo as the public page shows it. Capture coordinates go out only with
* the map. `posterless` is worked out here, because the storage key it used to
* be read from no longer leaves the server (#2341); a clip also keeps its
* provider, which builds from before that flag still read.
*/
export function publicPhoto(photo: PublicPhotoSource, withLocation: boolean): JourneyPublicPhoto {
const mediaType = photo.media_type ?? null;
return {
id: photo.id,
photo_id: photo.photo_id,
caption: photo.caption ?? null,
media_type: mediaType,
width: photo.width ?? null,
height: photo.height ?? null,
duration_ms: photo.duration_ms ?? null,
taken_at: photo.taken_at ?? null,
lat: withLocation ? (photo.lat ?? null) : null,
lng: withLocation ? (photo.lng ?? null) : null,
posterless: mediaType === 'video' && photo.provider === 'local' && !photo.thumbnail_path,
// Older clients still work `posterless` out from the provider (see the schema).
...(mediaType === 'video' ? { provider: photo.provider ?? null } : {}),
};
}
/** Just enough of an entry to plot its marker: a map-only share tells no story. */
export function publicMapEntry(entry: JourneyEntryWire): JourneyPublicEntry {
return {
id: entry.id,
type: entry.type,
entry_date: entry.entry_date,
sort_order: entry.sort_order ?? null,
title: entry.title ?? null,
location_name: entry.location_name ?? null,
location_lat: entry.location_lat ?? null,
location_lng: entry.location_lng ?? null,
};
}
/**
* An entry of a shared timeline with its photos. The coordinates follow the
* map switch; the photos follow the gallery switch.
*/
export function publicTimelineEntry(
entry: JourneyEntryWire,
photos: readonly PublicPhotoSource[],
share: { map: boolean; gallery: boolean },
): JourneyPublicEntry {
return {
id: entry.id,
type: entry.type,
entry_date: entry.entry_date,
entry_time: entry.entry_time ?? null,
sort_order: entry.sort_order ?? null,
title: entry.title ?? null,
story: entry.story ?? null,
location_name: entry.location_name ?? null,
location_lat: share.map ? (entry.location_lat ?? null) : null,
location_lng: share.map ? (entry.location_lng ?? null) : null,
country_code: entry.country_code ?? null,
mood: entry.mood ?? null,
weather: entry.weather ?? null,
tags: entry.tags,
pros_cons: entry.pros_cons,
photos: share.gallery ? photos.map((p) => publicPhoto(p, share.map)) : [],
};
}
@@ -4,10 +4,11 @@ import { RequireAddon } from '../addons/require-addon.decorator';
import { Public } from '../auth-core/public.decorator';
import { ResponseContract } from '../common/response-contract';
import { rowId } from '../common/row-id.pipe';
import { PublicMediaService } from '../memories/public-media.service';
import { StorageService } from '../storage/storage.service';
import { JourneyService } from './journey.service';
import { Controller, Get, HttpException, Param, Res, UseGuards } from '@nestjs/common';
import { journeyPublicMapLayersResponseSchema } from '@trek/shared';
import { journeyPublicMapLayersResponseSchema, journeyPublicResponseSchema } from '@trek/shared';
import type { Response } from 'express';
import path from 'node:path';
@@ -20,6 +21,8 @@ import path from 'node:path';
* no authentication, every route validates the share token (404 on failure),
* the unified proxy streams by trek_photo_id and the legacy proxy serves local
* files (with the uploads-dir traversal guard) or proxies immich/synology.
* A local file never leaves here as stored: both proxies send its
* location-free copy (PublicMediaService), or nothing.
*
* The addon gate is the one guard here, and it has to be: turning the Journey
* addon off is meant to take the feature away, and without it already-published
@@ -34,9 +37,16 @@ export class JourneyPublicController {
constructor(
private readonly journey: JourneyService,
private readonly storage: StorageService,
private readonly publicMedia: PublicMediaService,
) {}
/**
* The shared journey. Its contract is strict: a column that is not named
* there (a storage key, an asset id, an author) fails every test that reaches
* this route instead of going out to the public.
*/
@Get(':token')
@ResponseContract(journeyPublicResponseSchema)
async get(@Param('token') token: string) {
const data = await this.journey.getPublicJourney(token);
if (!data) {
@@ -96,11 +106,14 @@ export class JourneyPublicController {
if (!(await this.storage.exists('journey', name).catch(() => false))) {
throw new HttpException({ error: 'Not found' }, 404);
}
// The copy without GPS and place tags, never the stored original; a file
// that cannot be cleaned is not served at all.
const rendition = await this.publicMedia.renditionFor('journey', name).catch(() => null);
if (!rendition) {
throw new HttpException({ error: 'Not found' }, 404);
}
res.set('Cache-Control', 'public, max-age=86400');
// The storage layer serves it, whichever driver is configured. dev's fix
// for the absolute-path 404 under the Nest ExpressAdapter does not apply
// here any more: nothing on this path calls sendFile.
await this.storage.sendToResponse('journey', name, res);
await this.storage.sendToResponse('journey', rendition, res);
return;
}
@@ -15,8 +15,10 @@ import { UnitOfWork } from '../database/unit-of-work';
import { SettingsService } from '../settings/settings.service';
import { JourneyDomainService } from './journey-domain.service';
import { decodeEntryRow } from './journey-entry-row';
import { publicMapEntry, publicPhoto, publicTimelineEntry } from './journey-public-payload';
import { InjectRepository } from '@mikro-orm/nestjs';
import { Injectable } from '@nestjs/common';
import type { JourneyPublicEntry, JourneyPublicResponse } from '@trek/shared';
import crypto from 'crypto';
@@ -231,7 +233,7 @@ export class JourneyShareService {
return { ownerId: photo.owner_id || photo.journey_owner_id };
}
async getPublicJourney(token: string) {
async getPublicJourney(token: string): Promise<JourneyPublicResponse | null> {
// JS11 — exact-match token lookup, no LIKE/COLLATE (R4).
const row = await this.shareTokensRepo.findByToken(token);
if (!row) return null;
@@ -257,11 +259,6 @@ export class JourneyShareService {
// A photo whose every entry is a draft stays off the public page (#696).
const gallery = await this.photosRepo.galleryRead(row.journey_id, { hideDraftOnly: true });
const enrichedEntries = entries.map((e) => ({
...decodeEntryRow(e),
photos: photosByEntry[e.id] || [],
}));
// Stats are derived from the full data so the overview pills stay accurate
// even when a section is hidden.
const stats = {
@@ -276,33 +273,16 @@ export class JourneyShareService {
// Honour the share flags server-side so the API only returns the sections the
// owner enabled (the client gates these too, but it must not rely on that).
let publicEntries: Record<string, unknown>[] = [];
// Every entry and photo is built field by field (journey-public-payload.ts):
// a spread row sent storage keys and author ids to anyone with the link.
let publicEntries: JourneyPublicEntry[] = [];
if (shareTimeline) {
// Include the full entry, but drop GPS unless the map is shared and inline
// photos unless the gallery is shared.
publicEntries = enrichedEntries.map((e) => {
const projected: Record<string, unknown> = { ...e };
if (!shareMap) {
projected.location_lat = null;
projected.location_lng = null;
}
if (!shareGallery) projected.photos = [];
else if (!shareMap) projected.photos = stripPhotoGps(e.photos);
return projected;
});
publicEntries = entries.map((e) =>
publicTimelineEntry(decodeEntryRow(e), photosByEntry[e.id] || [], { map: shareMap, gallery: shareGallery }),
);
} else if (shareMap) {
// Map-only share: just enough to plot markers, no story/photos/mood.
publicEntries = enrichedEntries.map((e) => ({
id: e.id,
journey_id: e.journey_id,
type: e.type,
entry_date: e.entry_date,
title: e.title,
location_name: e.location_name,
location_lat: e.location_lat,
location_lng: e.location_lng,
sort_order: e.sort_order,
}));
publicEntries = entries.map((e) => publicMapEntry(decodeEntryRow(e)));
}
// Same reason as the trip share payload: CARTO watermarks every tile fetched
@@ -318,9 +298,9 @@ export class JourneyShareService {
return {
journey: {
title: journey.title,
subtitle: journey.subtitle,
cover_image: journey.cover_image,
status: journey.status,
subtitle: journey.subtitle ?? null,
cover_image: journey.cover_image ?? null,
status: journey.status ?? null,
// The three "this journey does not use that field" switches. A public
// reader was getting mood and weather chips on a journey that had them
// turned off, because the phone card reads these and they were not here
@@ -334,7 +314,7 @@ export class JourneyShareService {
// owner never typed and may not expect to publish. It follows share_map, the
// same switch the entry coordinates follow — otherwise a gallery-only share
// would hand out places the map was deliberately turned off for.
gallery: shareGallery ? (shareMap ? gallery : stripPhotoGps(gallery)) : [],
gallery: shareGallery ? gallery.map((p) => publicPhoto(p, shareMap)) : [],
stats,
cartoApiKey,
permissions: {
@@ -346,8 +326,3 @@ export class JourneyShareService {
};
}
}
/** Drop capture coordinates from a photo list, keeping everything else. */
function stripPhotoGps<T>(photos: T[] | undefined | null): T[] {
return (photos ?? []).map((p) => ({ ...(p as Record<string, unknown>), lat: null, lng: null })) as T[];
}
+11 -9
View File
@@ -36,6 +36,7 @@ import {
type JourneyEntryVisibility,
type JourneyReorderEntriesTool,
type JourneyUpdateTool,
JOURNEY_ENTRY_VISIBILITY_DEPRECATED,
} from '@trek/shared';
import { z } from 'zod';
@@ -72,12 +73,13 @@ function jsonContent(uri: string, data: unknown) {
}
/*
* The entry types, visibilities and the verdict come from @trek/shared
* (journey.schema.ts), where the assistant's cards read them too: a model that
* invents "friends-only" would write a value nothing reads.
* The entry types and the verdict come from @trek/shared (journey.schema.ts),
* where the assistant's cards read them too: a model that invents "note" would
* write a value nothing reads. The entry's stored visibility is deprecated:
* still accepted so older callers are not refused, but read by nothing, and
* is_draft is what keeps an entry off the share link.
*/
const ENTRY_TYPE = journeyEntryTypeSchema;
const ENTRY_VISIBILITY = journeyEntryVisibilitySchema;
const PROS_CONS = journeyEntryProsConsSchema;
/**
@@ -378,9 +380,7 @@ export class JourneyMcp {
.describe('Weather as the traveller recorded it (e.g. "sunny", "24C and windy")'),
tags: z.array(z.string()).optional(),
pros_cons: PROS_CONS.optional().describe('The verdict on the place: what was worth it and what was not'),
visibility: ENTRY_VISIBILITY.optional().describe(
'Stored with the entry, defaults to private. It does not decide the share link: every entry that is not a draft shows on the journey share link. Use is_draft to keep an entry to the contributors',
),
visibility: journeyEntryVisibilitySchema.optional().describe(JOURNEY_ENTRY_VISIBILITY_DEPRECATED),
type: ENTRY_TYPE.optional().describe(
'Defaults to "entry"; "skeleton" is the stub TREK derives from a trip place and hides behind the hide-skeletons preference',
),
@@ -388,7 +388,9 @@ export class JourneyMcp {
is_draft: z
.boolean()
.optional()
.describe('True keeps the entry a draft: contributors see it, the journey share link does not'),
.describe(
'True keeps the entry a draft: contributors see it, the journey share link does not. Every entry that is not a draft shows on the share link',
),
},
annotations: TOOL_ANNOTATIONS_NON_IDEMPOTENT,
when: journeyAddonOn,
@@ -428,7 +430,7 @@ export class JourneyMcp {
@Tool({
name: 'update_journey_entry',
description:
'Update an existing journey entry: its text, date, place, coordinates, weather, tags, verdict, visibility, whether it is a draft, or whether it counts as a stop. Fields left out keep their value; pass null to clear one. To move an entry within its day use reorder_journey_entries rather than setting sort_order here. Answers with the entry and, under previous, what the changed fields held before.',
'Update an existing journey entry: its text, date, place, coordinates, weather, tags, verdict, whether it is a draft (is_draft, the one switch that keeps it off the share link), or whether it counts as a stop. Fields left out keep their value; pass null to clear one. To move an entry within its day use reorder_journey_entries rather than setting sort_order here. Answers with the entry and, under previous, what the changed fields held before.',
inputSchema: { entryId: idSchema, ...journeyEntryUpdateToolSchema.shape },
annotations: TOOL_ANNOTATIONS_WRITE,
when: journeyAddonOn,
+2 -1
View File
@@ -188,8 +188,9 @@ export class JourneyService {
validateShareTokenForAsset(token: string, assetId: string) {
return this.share.validateShareTokenForAsset(token, assetId);
}
/** The public share's photo bytes: local files go out without their location. */
streamPhoto(res: Response, ownerId: number, photoId: number, kind: 'thumbnail' | 'original') {
return this.photoResolver.streamPhoto(res, ownerId, photoId, kind);
return this.photoResolver.streamPublicPhoto(res, ownerId, photoId, kind);
}
/**
* Stream a shared journey asset from whichever backend holds it.
+20 -5
View File
@@ -1,5 +1,6 @@
import { logInfo, logError } from '../audit/audit-log.logger';
import { CronRegistrarService } from '../scheduling/cron-registrar.service';
import { PublicMediaService } from './public-media.service';
import { ThumbnailService } from './thumbnail.service';
import { Injectable, type OnApplicationBootstrap } from '@nestjs/common';
@@ -8,12 +9,14 @@ import { Injectable, type OnApplicationBootstrap } from '@nestjs/common';
* photo row is gone (spec In-scope fix #2: delete sites only started removing
* the derived thumb with this slice, so historical orphans need a sweeper).
* The Journey addon gate lives inside sweepOrphanThumbs, so toggling the
* addon takes effect without a restart.
* addon takes effect without a restart. The same pass drops the location-free
* copies (PublicMediaService) whose source is gone.
*/
@Injectable()
export class JourneyThumbsJob implements OnApplicationBootstrap {
constructor(
private readonly thumbnails: ThumbnailService,
private readonly publicMedia: PublicMediaService,
private readonly registrar: CronRegistrarService,
) {}
@@ -31,11 +34,23 @@ export class JourneyThumbsJob implements OnApplicationBootstrap {
}
async sweep(): Promise<void> {
try {
await contained('Journey thumbnail cleanup', async () => {
const removed = await this.thumbnails.sweepOrphanThumbs();
if (removed > 0) logInfo(`Journey thumbnail cleanup: removed ${removed} orphaned thumbnail(s)`);
} catch (err: unknown) {
logError(`Journey thumbnail cleanup: ${err instanceof Error ? err.message : err}`);
}
});
// Its own pass and log line, so one failing never hides or stops the other.
await contained('Public media cleanup', async () => {
const renditions = await this.publicMedia.sweepOrphans();
if (renditions > 0) logInfo(`Public media cleanup: removed ${renditions} location-free copies of deleted media`);
});
}
}
/** Runs one cleanup pass and logs its failure under `label` instead of throwing. */
async function contained(label: string, pass: () => Promise<void>): Promise<void> {
try {
await pass();
} catch (err: unknown) {
logError(`${label}: ${err instanceof Error ? err.message : err}`);
}
}
+605
View File
@@ -0,0 +1,605 @@
import exifr from 'exifr';
import type { FileHandle } from 'node:fs/promises';
import fsPromises from 'node:fs/promises';
import zlib from 'node:zlib';
/**
* Location redaction for media that leaves the host without an account.
*
* Every edit is length preserving and happens on a copy: the GPS block of an
* embedded EXIF/TIFF structure is emptied, location properties of an XMP packet
* are overwritten with spaces, and the location atoms of a QuickTime/MP4 movie
* are zeroed. Nothing is decoded or re-encoded, so the picture keeps its quality
* and its orientation, and every container the format knows how to skip stays
* valid. A file this cannot vouch for answers false, and the caller serves no
* original in its place.
*/
/** Images are cleaned in memory; a larger one is refused rather than read whole. */
const MAX_IMAGE_BYTES = 128 * 1024 * 1024;
/** XMP boxes inside a movie are read whole as well. */
const MAX_XMP_BYTES = 16 * 1024 * 1024;
const GPS_IFD_TAG = 0x8825;
/** Bytes per value of each TIFF field type (index = type id 1..13). */
const TIFF_TYPE_SIZES = [0, 1, 1, 2, 4, 8, 1, 1, 2, 4, 8, 4, 8, 4];
const EXIF_MARK = Buffer.from('Exif\0\0', 'latin1');
const RDF_OPEN = Buffer.from('<rdf:RDF', 'latin1');
const RDF_CLOSE = Buffer.from('</rdf:RDF>', 'latin1');
const SPACE = 0x20;
/** The uuid box Adobe's XMP spec gives MP4 files. */
const XMP_UUID = Buffer.from('be7acfcb97a942e89c71999491e3afac', 'hex');
/** The QuickTime user-data atom holding an ISO 6709 location string. */
const LOCATION_ATOM = '\u00a9xyz';
/**
* ftyp major brands of a still HEIF/AVIF image. Only these may take the
* in-memory image path; any other ISO BMFF file is a movie and has to be
* walked as one, or it is refused.
*/
const STILL_IMAGE_BRANDS = new Set(['avif', 'heic', 'heim', 'heis', 'heix', 'miaf', 'mif1', 'mif2']);
/** Top-level atoms an old QuickTime file may start with instead of ftyp. */
const QUICKTIME_LEAD_ATOMS = new Set(['free', 'mdat', 'moov', 'pnot', 'skip', 'wide']);
const MOOV = Buffer.from('moov', 'latin1');
const PHOTOSHOP_MARK = Buffer.from('Photoshop 3.0\0', 'latin1');
/** The Photoshop image resource that carries the IPTC-IIM record. */
const IPTC_RESOURCE_ID = 0x0404;
/**
* IPTC-IIM application record (2) datasets that name a place: content
* location code and name, city, sublocation, province/state, country code
* and country.
*/
const IPTC_LOCATION_DATASETS = new Set([26, 27, 90, 92, 95, 100, 101]);
/** Local names (prefix stripped, lower case) of the XMP properties that name a place. */
const XMP_LOCATION_FIELDS = new Set([
'altitude',
'city',
'country',
'countrycode',
'countryname',
'latitude',
'location',
'locationcreated',
'locationshown',
'longitude',
'provincestate',
'state',
'sublocation',
'worldregion',
]);
type MediaFormat = 'jpeg' | 'png' | 'webp' | 'gif' | 'tiff' | 'isobmff' | 'quicktime' | 'ebml' | 'unknown';
function sniffFormat(head: Buffer): MediaFormat {
if (head.length >= 3 && head[0] === 0xff && head[1] === 0xd8 && head[2] === 0xff) return 'jpeg';
if (head.length < 8) return 'unknown';
if (head.readUInt32BE(0) === 0x89504e47) return 'png';
if (head.toString('latin1', 0, 4) === 'GIF8') return 'gif';
if (head.toString('latin1', 4, 8) === 'ftyp') return 'isobmff';
if (QUICKTIME_LEAD_ATOMS.has(head.toString('latin1', 4, 8))) return 'quicktime';
if (head.readUInt32BE(0) === 0x1a45dfa3) return 'ebml';
if (readTiffByteOrder(head, 0, head.length) !== null) return 'tiff';
if (head.length >= 12 && head.toString('latin1', 0, 4) === 'RIFF' && head.toString('latin1', 8, 12) === 'WEBP') {
return 'webp';
}
return 'unknown';
}
// ── EXIF / TIFF ─────────────────────────────────────────────────────────────
/** 'le' or 'be' for a TIFF header at `base`, null when there is none. */
function readTiffByteOrder(buf: Buffer, base: number, limit: number): 'le' | 'be' | null {
if (base + 8 > limit) return null;
if (buf[base] === 0x49 && buf[base + 1] === 0x49 && buf.readUInt16LE(base + 2) === 42) return 'le';
if (buf[base] === 0x4d && buf[base + 1] === 0x4d && buf.readUInt16BE(base + 2) === 42) return 'be';
return null;
}
/**
* Empties the GPS IFD of the TIFF structure at `base`: its out-of-line values
* and its entries are zeroed and its entry count set to 0, which also reads
* as "no next IFD". IFD0 (orientation included) is left as it was.
* False when no plausible TIFF starts at `base`.
*/
function blankTiffGps(buf: Buffer, base: number, limit: number): boolean {
const order = readTiffByteOrder(buf, base, limit);
if (!order) return false;
const u16 = (offset: number) => (order === 'le' ? buf.readUInt16LE(base + offset) : buf.readUInt16BE(base + offset));
const u32 = (offset: number) => (order === 'le' ? buf.readUInt32LE(base + offset) : buf.readUInt32BE(base + offset));
const entryCount = (offset: number) => {
if (offset < 8 || base + offset + 2 > limit) return -1;
const count = u16(offset);
return base + offset + 2 + count * 12 + 4 <= limit ? count : -1;
};
const blankGpsIfd = (offset: number) => {
const count = entryCount(offset);
if (count <= 0) return;
for (let i = 0; i < count; i++) {
const entry = offset + 2 + i * 12;
const size = (TIFF_TYPE_SIZES[u16(entry + 2)] ?? 0) * u32(entry + 4);
const valueAt = u32(entry + 8);
if (size > 4 && valueAt >= 8 && base + valueAt + size <= limit)
buf.fill(0, base + valueAt, base + valueAt + size);
}
buf.fill(0, base + offset, base + offset + 2 + count * 12);
};
// IFD0 and the IFDs chained behind it; the GPS pointer lives in IFD0 in practice.
const seen = new Set<number>();
let ifd = u32(4);
for (let depth = 0; depth < 4 && ifd !== 0 && !seen.has(ifd); depth++) {
seen.add(ifd);
const count = entryCount(ifd);
if (count <= 0 || count > 1024) return depth > 0;
for (let i = 0; i < count; i++) {
const entry = ifd + 2 + i * 12;
if (u16(entry) === GPS_IFD_TAG) blankGpsIfd(u32(entry + 8));
}
ifd = u32(ifd + 2 + count * 12);
}
return true;
}
/** Every "Exif\0\0"-prefixed TIFF in the buffer: JPEG APP1 (MPO frames too), HEIC/AVIF Exif items, WebP. */
function blankAllExif(buf: Buffer): void {
let at = buf.indexOf(EXIF_MARK);
while (at !== -1) {
blankTiffGps(buf, at + EXIF_MARK.length, buf.length);
at = buf.indexOf(EXIF_MARK, at + EXIF_MARK.length);
}
}
// ── XMP ─────────────────────────────────────────────────────────────────────
function isXmpLocationName(qualifiedName: string): boolean {
const colon = qualifiedName.indexOf(':');
if (colon === -1) return false;
const local = qualifiedName.slice(colon + 1).toLowerCase();
return local.startsWith('gps') || XMP_LOCATION_FIELDS.has(local);
}
function isXmlSpace(char: string | undefined): boolean {
return char === ' ' || char === '\n' || char === '\r' || char === '\t';
}
/** Index of the `>` closing the tag that starts before `from`, quotes respected. */
function findTagEnd(text: string, from: number): number {
let quote: string | null = null;
for (let i = from; i < text.length; i++) {
const char = text[i];
if (quote) {
if (char === quote) quote = null;
} else if (char === '"' || char === "'") {
quote = char;
} else if (char === '>') {
return i;
}
}
return -1;
}
/** Collects the location attributes between a tag's name and its `>`; false on a malformed tag. */
function collectLocationAttributes(text: string, from: number, to: number, ranges: Array<[number, number]>): boolean {
let i = from;
while (i < to) {
while (i < to && (isXmlSpace(text[i]) || text[i] === '/')) i++;
if (i >= to) break;
const start = i;
while (i < to && text[i] !== '=' && !isXmlSpace(text[i])) i++;
const name = text.slice(start, i);
while (i < to && isXmlSpace(text[i])) i++;
if (text[i] !== '=') return false;
i++;
while (i < to && isXmlSpace(text[i])) i++;
const quote = text[i];
if (quote !== '"' && quote !== "'") return false;
const close = text.indexOf(quote, i + 1);
if (close === -1 || close > to) return false;
if (isXmpLocationName(name)) ranges.push([start, close + 1]);
i = close + 1;
}
return true;
}
/**
* The character ranges of an XMP packet that hold a location: whole elements
* (exif:GPSLatitude, photoshop:City, Iptc4xmpExt:LocationShown …) and
* attributes of the same names. Null when the packet does not parse.
*/
function xmpLocationRanges(text: string): Array<[number, number]> | null {
const ranges: Array<[number, number]> = [];
let i = text.indexOf('<');
while (i !== -1) {
const next = text[i + 1];
if (next === '/' || next === '?' || next === '!') {
i = text.indexOf('<', i + 1);
continue;
}
let nameEnd = i + 1;
while (nameEnd < text.length && !isXmlSpace(text[nameEnd]) && text[nameEnd] !== '>' && text[nameEnd] !== '/') {
nameEnd++;
}
const name = text.slice(i + 1, nameEnd);
const tagEnd = findTagEnd(text, nameEnd);
if (tagEnd === -1) return null;
if (isXmpLocationName(name)) {
let end = tagEnd + 1;
if (text[tagEnd - 1] !== '/') {
const close = text.indexOf(`</${name}`, tagEnd);
const closeEnd = close === -1 ? -1 : text.indexOf('>', close);
if (closeEnd === -1) return null;
end = closeEnd + 1;
}
ranges.push([i, end]);
i = text.indexOf('<', end);
continue;
}
if (!collectLocationAttributes(text, nameEnd, tagEnd, ranges)) return null;
i = text.indexOf('<', tagEnd + 1);
}
return ranges;
}
/** Blanks the location properties of every XMP packet in [from, to); false when one does not parse. */
function blankAllXmp(buf: Buffer, from = 0, to = buf.length): boolean {
let at = buf.indexOf(RDF_OPEN, from);
while (at !== -1 && at < to) {
const close = buf.indexOf(RDF_CLOSE, at);
if (close === -1 || close + RDF_CLOSE.length > to) return false;
const end = close + RDF_CLOSE.length;
// latin1 maps every byte to one character, so string indexes are byte offsets.
const ranges = xmpLocationRanges(buf.toString('latin1', at, end));
if (!ranges) return false;
for (const [start, stop] of ranges) buf.fill(SPACE, at + start, at + stop);
at = buf.indexOf(RDF_OPEN, end);
}
return true;
}
// ── IPTC-IIM (JPEG APP13) ───────────────────────────────────────────────────
/** Overwrites the place datasets of an IIM block with spaces; false when it does not parse. */
function blankIimLocation(buf: Buffer, from: number, to: number): boolean {
let pos = from;
// Writers may pad the block with zeros after the last dataset.
while (pos + 5 <= to && buf[pos] !== 0) {
if (buf[pos] !== 0x1c) return false;
const record = buf[pos + 1];
const dataset = buf[pos + 2];
let length = buf.readUInt16BE(pos + 3);
let value = pos + 5;
// Extended dataset: the low 15 bits give the byte count of the real length.
if (length & 0x8000) {
const lengthBytes = length & 0x7fff;
if (lengthBytes < 1 || lengthBytes > 4 || value + lengthBytes > to) return false;
length = buf.readUIntBE(value, lengthBytes);
value += lengthBytes;
}
if (value + length > to) return false;
if (record === 2 && IPTC_LOCATION_DATASETS.has(dataset)) buf.fill(SPACE, value, value + length);
pos = value + length;
}
return true;
}
/** Walks the 8BIM resources of a Photoshop APP13 block and cleans its IPTC record. */
function blankPhotoshopIptc(buf: Buffer, from: number, to: number): boolean {
let pos = from;
while (pos + 12 <= to) {
if (buf.toString('latin1', pos, pos + 4) !== '8BIM') return false;
const id = buf.readUInt16BE(pos + 4);
// A Pascal name, padded so that its length byte and the name together are even.
const nameLength = buf[pos + 6];
const sizeAt = pos + 7 + nameLength + ((nameLength + 1) % 2);
if (sizeAt + 4 > to) return false;
const size = buf.readUInt32BE(sizeAt);
const data = sizeAt + 4;
if (data + size > to) return false;
if (id === IPTC_RESOURCE_ID && !blankIimLocation(buf, data, data + size)) return false;
pos = data + size + (size % 2);
}
return true;
}
/** Cleans the IPTC place fields of every Photoshop APP13 segment ahead of the image data. */
function blankJpegIptc(buf: Buffer): boolean {
let pos = 2;
while (pos + 4 <= buf.length && buf[pos] === 0xff) {
const marker = buf[pos + 1];
// A fill byte ahead of the marker.
if (marker === 0xff) {
pos++;
continue;
}
// Start of scan or end of image: no metadata segment follows.
if (marker === 0xda || marker === 0xd9) break;
const end = pos + 2 + buf.readUInt16BE(pos + 2);
if (end > buf.length) break;
const markAt = pos + 4;
const isPhotoshop = buf.subarray(markAt, markAt + PHOTOSHOP_MARK.length).equals(PHOTOSHOP_MARK);
if (marker === 0xed && isPhotoshop && !blankPhotoshopIptc(buf, markAt + PHOTOSHOP_MARK.length, end)) return false;
pos = end;
}
return true;
}
// ── Containers held in memory ───────────────────────────────────────────────
/** WebP may carry its EXIF chunk without the "Exif\0\0" prefix the generic scan looks for. */
function blankWebpExifChunk(buf: Buffer): void {
let pos = 12;
while (pos + 8 <= buf.length) {
const size = buf.readUInt32LE(pos + 4);
const data = pos + 8;
if (buf.toString('latin1', pos, pos + 4) === 'EXIF') blankTiffGps(buf, data, Math.min(buf.length, data + size));
pos = data + size + (size % 2);
}
}
/**
* PNG checksums every chunk, so it is walked rather than scanned: eXIf loses
* its GPS block, an uncompressed XMP iTXt its location properties, and a text
* chunk that carries metadata this cannot read in place (compressed XMP, an
* ImageMagick "Raw profile") is renamed to a private ancillary type every
* decoder skips, with its data zeroed. Each changed chunk gets a new CRC.
*/
function redactPng(buf: Buffer): boolean {
let pos = 8;
while (pos + 12 <= buf.length) {
const length = buf.readUInt32BE(pos);
const type = buf.toString('latin1', pos + 4, pos + 8);
const data = pos + 8;
const end = data + length;
if (end + 4 > buf.length) return false;
let changed = false;
if (type === 'eXIf') {
const tiff = buf.subarray(data, data + EXIF_MARK.length).equals(EXIF_MARK) ? data + EXIF_MARK.length : data;
if (!blankTiffGps(buf, tiff, end)) return false;
changed = true;
} else if (type === 'iTXt' || type === 'tEXt' || type === 'zTXt') {
const keywordEnd = buf.indexOf(0, data);
const keyword = buf
.toString('latin1', data, keywordEnd === -1 || keywordEnd > end ? end : keywordEnd)
.toLowerCase();
if (keyword.includes('xmp') || keyword.includes('exif') || keyword.startsWith('raw profile')) {
const plainXmp = type === 'iTXt' && keyword === 'xml:com.adobe.xmp' && buf[keywordEnd + 1] === 0;
if (plainXmp) {
if (!blankAllXmp(buf, keywordEnd, end)) return false;
} else {
buf.write('prIv', pos + 4, 'latin1');
buf.fill(0, data, end);
}
changed = true;
}
}
if (changed) buf.writeUInt32BE(zlib.crc32(buf.subarray(pos + 4, end)), end);
if (type === 'IEND') break;
pos = end + 4;
}
return true;
}
/**
* Redacts an image held in memory, in place. False for a format this does not
* know (BMP, a truncated file) or a metadata block it could not parse.
*/
export function redactLocationInBuffer(buf: Buffer): boolean {
const format = sniffFormat(buf);
switch (format) {
case 'png':
return redactPng(buf);
case 'tiff':
if (!blankTiffGps(buf, 0, buf.length)) return false;
break;
case 'webp':
blankWebpExifChunk(buf);
break;
case 'jpeg':
if (!blankJpegIptc(buf)) return false;
break;
case 'gif':
case 'isobmff':
break;
default:
return false;
}
blankAllExif(buf);
return blankAllXmp(buf);
}
// ── Movies (QuickTime / MP4), patched on disk ───────────────────────────────
interface Box {
type: string;
start: number;
body: number;
end: number;
}
async function readAt(handle: FileHandle, position: number, length: number): Promise<Buffer> {
const buf = Buffer.alloc(length);
const { bytesRead } = await handle.read(buf, 0, length, position);
return buf.subarray(0, bytesRead);
}
/** Runs `step` on each item in order, stopping at the first false. */
function everyInOrder<T>(items: readonly T[], step: (item: T) => Promise<boolean>): Promise<boolean> {
return items.reduce<Promise<boolean>>((done, item) => done.then((ok) => ok && step(item)), Promise.resolve(true));
}
/** The boxes in [from, to), headers only; null when one overruns its parent. */
async function readBoxes(handle: FileHandle, from: number, to: number, found: Box[] = []): Promise<Box[] | null> {
if (from + 8 > to) return found;
const head = await readAt(handle, from, 16);
if (head.length < 8) return null;
let size = head.readUInt32BE(0);
let headerLength = 8;
if (size === 1) {
if (head.length < 16) return null;
size = Number(head.readBigUInt64BE(8));
headerLength = 16;
} else if (size === 0) {
size = to - from;
}
if (size < headerLength || from + size > to) return null;
found.push({ type: head.toString('latin1', 4, 8), start: from, body: from + headerLength, end: from + size });
return readBoxes(handle, from + size, to, found);
}
async function blankXmpRegion(handle: FileHandle, from: number, to: number): Promise<boolean> {
if (to - from > MAX_XMP_BYTES) return false;
const buf = await readAt(handle, from, to - from);
if (!blankAllXmp(buf)) return false;
await handle.write(buf, 0, buf.length, from);
return true;
}
/** Zeroes the value of every `data` box inside an ilst item, keeping their headers. */
async function zeroItemValues(handle: FileHandle, item: Box): Promise<boolean> {
const values = await readBoxes(handle, item.body, item.end);
if (!values) return false;
// data box: size, 'data', type indicator (4), locale (4), then the value.
const data = values.filter((value) => value.type === 'data' && value.end > value.body + 8);
await Promise.all(
data.map((value) =>
handle.write(Buffer.alloc(value.end - value.body - 8), 0, value.end - value.body - 8, value.body + 8),
),
);
return true;
}
/** 1-based indexes of the `keys` entries that name a location (com.apple.quicktime.location.ISO6709 …). */
async function locationKeyIndexes(handle: FileHandle, keys: Box): Promise<Set<number> | null> {
if (keys.end - keys.body > MAX_XMP_BYTES) return null;
const buf = await readAt(handle, keys.body, keys.end - keys.body);
const found = new Set<number>();
if (buf.length < 8) return found;
const count = buf.readUInt32BE(4);
let pos = 8;
for (let index = 1; index <= count; index++) {
if (pos + 8 > buf.length) return null;
const size = buf.readUInt32BE(pos);
if (size < 8 || pos + size > buf.length) return null;
const name = buf.toString('latin1', pos + 8, pos + size).toLowerCase();
if (name.includes('location')) found.add(index);
pos += size;
}
return found;
}
async function redactItemList(handle: FileHandle, ilst: Box, locationKeys: Set<number>): Promise<boolean> {
const items = await readBoxes(handle, ilst.body, ilst.end);
if (!items) return false;
// An item's type is the 1-based index of its key, or an iTunes atom name.
const located = items.filter(
(item) => item.type === LOCATION_ATOM || locationKeys.has(Buffer.from(item.type, 'latin1').readUInt32BE(0)),
);
return everyInOrder(located, (item) => zeroItemValues(handle, item));
}
async function redactMeta(handle: FileHandle, meta: Box): Promise<boolean> {
// ISO meta is a full box (4 bytes of version and flags before its children);
// QuickTime's moov/meta is not. The handler box always comes first.
const peek = await readAt(handle, meta.body, 12);
const childrenFrom = peek.toString('latin1', 4, 8) === 'hdlr' ? meta.body : meta.body + 4;
const children = await readBoxes(handle, childrenFrom, meta.end);
if (!children) return false;
const keys = children.find((child) => child.type === 'keys');
const locationKeys = keys ? await locationKeyIndexes(handle, keys) : new Set<number>();
if (!locationKeys) return false;
return everyInOrder(children, (child) =>
child.type === 'ilst' ? redactItemList(handle, child, locationKeys) : redactMovieBox(handle, child),
);
}
const MOVIE_CONTAINERS = new Set(['moov', 'trak', 'udta']);
/** Whether the ftyp box at the start of `head` names a still HEIF/AVIF image. */
function isStillImageBrand(head: Buffer): boolean {
return head.length >= 12 && STILL_IMAGE_BRANDS.has(head.toString('latin1', 8, 12));
}
async function redactMovieBox(handle: FileHandle, box: Box): Promise<boolean> {
if (MOVIE_CONTAINERS.has(box.type)) {
const children = await readBoxes(handle, box.body, box.end);
return children !== null && everyInOrder(children, (child) => redactMovieBox(handle, child));
}
switch (box.type) {
case 'meta':
return redactMeta(handle, box);
case LOCATION_ATOM:
case 'loci':
// The place atoms phones and cameras write into udta (ISO 6709 string,
// 3GPP location). A free box of the same size is skipped by every
// reader, and its content is zeroed with it.
await handle.write(Buffer.from('free', 'latin1'), 0, 4, box.start + 4);
await handle.write(Buffer.alloc(box.end - box.body), 0, box.end - box.body, box.body);
return true;
case 'XMP_':
return blankXmpRegion(handle, box.body, box.end);
case 'uuid': {
const id = await readAt(handle, box.body, 16);
return id.equals(XMP_UUID) ? blankXmpRegion(handle, box.body + 16, box.end) : true;
}
default:
return true;
}
}
/** exifr as a second opinion on an image: any GPS it still reads fails the file. */
async function exifrFindsGps(buf: Buffer): Promise<boolean> {
try {
const gps = (await exifr.gps(buf)) as { latitude?: number } | undefined;
return gps?.latitude !== undefined && Number.isFinite(gps.latitude);
} catch {
// A file exifr cannot read holds nothing it would hand out either.
return false;
}
}
/**
* Redacts the media file at `file` in place (the caller's own copy). True when
* it now carries no location this knows of; false when the format is unknown
* or a metadata block could not be cleaned, and the file must not be served.
*/
export async function redactLocationInFile(file: string): Promise<boolean> {
const handle = await fsPromises.open(file, 'r+');
try {
const { size } = await handle.stat();
const head = await readAt(handle, 0, 16);
const format = sniffFormat(head);
// WebM/Matroska has no location field a camera or phone writes.
if (format === 'ebml') return true;
let walked = true;
if (format === 'isobmff' || format === 'quicktime') {
const top = await readBoxes(handle, 0, size);
if (top?.some((box) => box.type === 'moov')) return await everyInOrder(top, (box) => redactMovieBox(handle, box));
// The image path never reaches udta atoms, so a movie this cannot walk
// (truncated, junk after mdat) is refused. Only a still HEIF/AVIF image
// goes on to be cleaned in memory.
if (format === 'quicktime' || !isStillImageBrand(head)) return false;
walked = top !== null;
}
if (format === 'unknown' || size > MAX_IMAGE_BYTES) return false;
const buf = await readAt(handle, 0, size);
// An image whose boxes did not parse may still hide a movie header.
if (!walked && buf.includes(MOOV)) return false;
if (!redactLocationInBuffer(buf)) return false;
await handle.write(buf, 0, buf.length, 0);
return !(await exifrFindsGps(buf));
} finally {
await handle.close();
}
}
@@ -29,6 +29,7 @@ import { PhotoProviderRegistry } from './photo-provider.registry';
import { PhotoResolverService } from './photo-resolver.service';
import { ImmichPhotoProvider } from './providers/immich.provider';
import { SynologyPhotoProvider } from './providers/synology.provider';
import { PublicMediaService } from './public-media.service';
import { SynologyCaptureRepairJob } from './synology-capture-repair.job';
import { SynologyMemoriesController } from './synology.controller';
import { SynologyService } from './synology.service';
@@ -108,6 +109,7 @@ import { Module } from '@nestjs/common';
UnifiedMemoriesService,
PhotoResolverService,
PhotoCaptureBackfillService,
PublicMediaService,
ThumbnailService,
TrekPhotoCacheService,
TrekPhotoCacheJob,
@@ -127,6 +129,7 @@ import { Module } from '@nestjs/common';
MemoriesAccessService,
PhotoResolverService,
PhotoCaptureBackfillService,
PublicMediaService,
ImmichService,
SynologyService,
PhotoProviderRegistry,
@@ -5,6 +5,7 @@ import { StorageService } from '../storage/storage.service';
import { fail, success, type AssetInfo, type ServiceResult } from './memories.helpers';
import type { PhotoAssetRef } from './photo-provider';
import { PhotoProviderRegistry } from './photo-provider.registry';
import { PublicMediaService } from './public-media.service';
import { ThumbnailService } from './thumbnail.service';
import { TrekPhotoCacheService } from './trek-photo-cache.service';
import { Injectable } from '@nestjs/common';
@@ -24,6 +25,12 @@ export type PhotoSignalSource =
| { kind: 'none' }
| { kind: 'unavailable' };
/** Who a local file goes to: its owner or a member as stored, the public as a location-free copy. */
type Audience = 'owner' | 'public';
const THUMB_CACHE = 'public, max-age=86400, immutable';
const ORIGINAL_CACHE = 'public, max-age=86400';
/**
* Resolves a stored trek_photo to bytes or metadata by asking whichever provider
* owns it. The storage half of the old photoResolverService lives in
@@ -42,6 +49,7 @@ export class PhotoResolverService {
private readonly cache: TrekPhotoCacheService,
private readonly providers: PhotoProviderRegistry,
private readonly storage: StorageService,
private readonly publicMedia: PublicMediaService,
) {}
/** photos.file_path / thumbnail_path are uploads-relative 'journey/…' by
@@ -83,12 +91,71 @@ export class PhotoResolverService {
await fallback();
}
/** An owner's or member's view: local files go out as stored. */
async streamPhoto(
res: Response,
userId: number,
photoId: number,
kind: 'thumbnail' | 'original',
range?: string,
): Promise<void> {
await this.stream(res, userId, photoId, kind, range, 'owner');
}
/**
* A public share's view. A local file goes out as its location-free copy
* (PublicMediaService) and never as stored; one that cannot be cleaned falls
* back to the thumbnail TREK re-encoded itself, else a 404. Provider assets
* stream as for an owner.
*/
async streamPublicPhoto(
res: Response,
ownerId: number,
photoId: number,
kind: 'thumbnail' | 'original',
): Promise<void> {
await this.stream(res, ownerId, photoId, kind, undefined, 'public');
}
/**
* Sends one local journey object. For the public a re-encoded thumbnail
* (thumbs/, written by ThumbnailService, no metadata) goes out as is, anything
* else as its location-free copy. False when there is nothing safe to send.
*/
private async sendLocal(res: Response, relPath: string, audience: Audience, cacheControl: string): Promise<boolean> {
const name = this.storageName(relPath);
if (!name || !(await this.storage.exists('journey', name).catch(() => false))) return false;
let served = name;
if (audience === 'public' && !name.startsWith('thumbs/')) {
const rendition = await this.publicMedia.renditionFor('journey', name).catch(() => null);
if (!rendition) return false;
served = rendition;
}
res.set('Cache-Control', cacheControl);
res.set('X-Content-Type-Options', 'nosniff');
await this.storage.sendToResponse('journey', served, res);
return true;
}
/** The thumbnail row path, generated for a raster image that has none yet. */
private async localThumbnail(photo: TrekPhoto): Promise<string | null> {
if (photo.thumbnail_path) return photo.thumbnail_path;
// Only raster images get a lazily-generated Jimp thumbnail; Jimp can't decode
// video, so a video relies on the poster captured at upload (#823).
if (photo.media_type === 'video' || !photo.file_path) return null;
const result = await this.thumbnails.ensureLocalThumbnail(photo.file_path);
if (!result) return null;
await this.photos.recordLocalThumbnail(photo.id, result.thumbnailRelPath, result.width, result.height);
return result.thumbnailRelPath;
}
private async stream(
res: Response,
userId: number,
photoId: number,
kind: 'thumbnail' | 'original',
range: string | undefined,
audience: Audience,
): Promise<void> {
const photo = await this.photos.resolve(photoId);
if (!photo) {
@@ -98,41 +165,24 @@ export class PhotoResolverService {
if (photo.file_path) {
if (kind === 'thumbnail') {
const isVideo = photo.media_type === 'video';
let thumbRel = photo.thumbnail_path ?? null;
// Only raster images get a lazily-generated Jimp thumbnail; Jimp can't decode
// video, so a video relies on the poster captured at upload (#823).
if (!thumbRel && !isVideo) {
const result = await this.thumbnails.ensureLocalThumbnail(photo.file_path);
if (result) {
thumbRel = result.thumbnailRelPath;
await this.photos.recordLocalThumbnail(photo.id, thumbRel, result.width, result.height);
}
}
if (thumbRel) {
const thumbName = this.storageName(thumbRel);
if (thumbName && (await this.storage.exists('journey', thumbName).catch(() => false))) {
res.set('Cache-Control', 'public, max-age=86400, immutable');
res.set('X-Content-Type-Options', 'nosniff');
await this.storage.sendToResponse('journey', thumbName, res);
return;
}
}
const thumbRel = await this.localThumbnail(photo);
if (thumbRel && (await this.sendLocal(res, thumbRel, audience, THUMB_CACHE))) return;
// A poster-less video must NOT fall through to streaming the whole file as a
// "thumbnail"; let the client render its own placeholder instead.
if (isVideo) {
if (photo.media_type === 'video') {
res.status(404).json({ error: 'No poster available' });
return;
}
// Images fall through to original if the thumbnail is unavailable.
}
const name = this.storageName(photo.file_path);
if (name && (await this.storage.exists('journey', name).catch(() => false))) {
res.set('Cache-Control', 'public, max-age=86400');
res.set('X-Content-Type-Options', 'nosniff');
await this.storage.sendToResponse('journey', name, res);
return;
if (await this.sendLocal(res, photo.file_path, audience, ORIGINAL_CACHE)) return;
// A public original that could not be cleaned is stood in for by the
// re-encoded thumbnail, never by the stored bytes.
if (audience === 'public' && kind === 'original' && photo.media_type !== 'video') {
const thumbRel = await this.localThumbnail(photo);
if (thumbRel && (await this.sendLocal(res, thumbRel, audience, THUMB_CACHE))) return;
}
}
@@ -0,0 +1,153 @@
import { Journeys } from '../../db/entities/Journeys.entity';
import { TrekPhotos } from '../../db/entities/TrekPhotos.entity';
import type { JourneysRepository } from '../../db/repositories/Journeys.repository';
import type { TrekPhotosRepository } from '../../db/repositories/TrekPhotos.repository';
import { logWarn } from '../audit/audit-log.logger';
import { StorageService } from '../storage/storage.service';
import { StorageNotFoundError, type ServedCategory } from '../storage/storage.types';
import { redactLocationInFile } from './media-redact';
import { InjectRepository } from '@mikro-orm/nestjs';
import { Injectable } from '@nestjs/common';
import { Jimp } from 'jimp';
import crypto from 'node:crypto';
import fsPromises from 'node:fs/promises';
import path from 'node:path';
/** Location-free copies live beside their source, under this prefix, in the source's category. */
const RENDITION_PREFIX = 'public/';
/** The categories whose objects reach a viewer without an account and so get renditions. */
const RENDITION_CATEGORIES: readonly ServedCategory[] = ['avatars', 'covers', 'journey', 'places', 'photos'];
/** Image types Jimp both decodes and writes; it writes no metadata, so a re-encoded copy carries no location. */
const REENCODABLE_EXTENSIONS = new Set(['.bmp', '.gif', '.jpeg', '.jpg', '.png', '.tif', '.tiff']);
/** How many copies the sweep checks at once, so a large instance does not open thousands of handles. */
const SWEEP_BATCH = 32;
/** Runs `step` on each batch of `items` in turn and sums what it returns. */
function sumInBatches<T>(items: readonly T[], size: number, step: (batch: readonly T[]) => Promise<number>) {
const batches: T[][] = [];
for (let i = 0; i < items.length; i += size) batches.push(items.slice(i, i + size));
return batches.reduce<Promise<number>>(
(done, batch) => done.then(async (sum) => sum + (await step(batch))),
Promise.resolve(0),
);
}
/**
* What every byte path without an account serves instead of a stored
* original: a copy with the location taken out (media-redact.ts), made on the
* first request and kept as `public/<name>` in the same category until the
* source changes. When the metadata cannot be cleaned in place, a raster image
* is re-encoded instead, so an upload that rendered before keeps rendering.
* Owners and members keep getting the original itself.
*/
@Injectable()
export class PublicMediaService {
private readonly inFlight = new Map<string, Promise<string | null>>();
constructor(
private readonly storage: StorageService,
@InjectRepository(Journeys) private readonly journeys: JourneysRepository,
@InjectRepository(TrekPhotos) private readonly trekPhotos: TrekPhotosRepository,
) {}
/**
* The storage name of the location-free copy of `name`, or null when none
* can be made safely (a movie or format that can be neither cleaned nor
* re-encoded): the caller then serves nothing rather than the original. A
* missing source throws StorageNotFoundError, an invalid name
* StorageInvalidKeyError.
*/
async renditionFor(category: ServedCategory, name: string): Promise<string | null> {
if (name.startsWith(RENDITION_PREFIX)) return null;
const rendition = RENDITION_PREFIX + name;
const [source, existing] = await Promise.all([
this.storage.stat(category, name),
this.storage.stat(category, rendition),
]);
if (!source) throw new StorageNotFoundError(`${category}/${name}`);
if (existing && existing.mtimeMs >= source.mtimeMs) return rendition;
const key = `${category}/${name}`;
let pending = this.inFlight.get(key);
if (!pending) {
pending = this.build(category, name, rendition).finally(() => this.inFlight.delete(key));
this.inFlight.set(key, pending);
}
return pending;
}
/**
* Whether /uploads/journey may answer for `name`. Journey entry media (a
* trek_photos original or poster, and the thumbs/ TREK derives from them)
* goes only through the token-checked and session-checked proxies, so
* revoking a share link takes it away; a journey cover, and any other
* object a trip cover or place image may point at, stays reachable.
*/
async servesFromJourneyMount(name: string): Promise<boolean> {
const spellings = [`journey/${name}`, `/uploads/journey/${name}`];
if (await this.journeys.isCoverImage(spellings)) return true;
if (name.startsWith('thumbs/')) return false;
return !(await this.trekPhotos.referencesLocalPath(spellings));
}
/** Deletes the renditions whose source is gone. Returns how many went. */
sweepOrphans(): Promise<number> {
// One category after another, each in bounded batches.
return RENDITION_CATEGORIES.reduce<Promise<number>>(
(done, category) => done.then(async (sum) => sum + (await this.sweepCategory(category))),
Promise.resolve(0),
);
}
private async sweepCategory(category: ServedCategory): Promise<number> {
const keys: string[] = [];
for await (const stat of this.storage.list(category, RENDITION_PREFIX)) keys.push(stat.key);
return sumInBatches(keys, SWEEP_BATCH, async (batch) => {
const removed = await Promise.all(batch.map((key) => this.dropIfOrphaned(category, key)));
return removed.filter(Boolean).length;
});
}
private async dropIfOrphaned(category: ServedCategory, key: string): Promise<boolean> {
// A source that cannot be checked right now counts as present.
if (await this.storage.exists(category, key.slice(RENDITION_PREFIX.length)).catch(() => true)) return false;
if (this.storage.keepsOnDelete(category, key)) return false;
return this.storage.delete(category, key).then(
() => true,
() => false,
);
}
private async build(category: ServedCategory, name: string, rendition: string): Promise<string | null> {
const extension = path.extname(name).toLowerCase();
const spool = path.join(this.storage.spoolDirFor(category), `public-${crypto.randomUUID()}${extension}`);
try {
await this.storage.withLocalFile(category, name, (source) => fsPromises.copyFile(source, spool));
if (!(await redactLocationInFile(spool)) && !(await this.reencode(category, name, spool, extension))) {
logWarn(`Public media: ${category}/${name} could not be cleaned of its location and is not served publicly`);
return null;
}
await this.storage.put(category, rendition, { tmpPath: spool });
return rendition;
} finally {
await fsPromises.rm(spool, { force: true });
}
}
/** Writes a fresh, metadata-free encoding of the source to `spool`; false when Jimp cannot handle it. */
private async reencode(category: ServedCategory, name: string, spool: string, extension: string): Promise<boolean> {
if (!REENCODABLE_EXTENSIONS.has(extension)) return false;
try {
// Jimp applies the EXIF orientation on read, so the copy shows upright without it.
const image = await this.storage.withLocalFile(category, name, (source) => Jimp.read(source));
await image.write(spool as Parameters<typeof image.write>[0]);
return true;
} catch {
return false;
}
}
}
+91 -40
View File
@@ -9,6 +9,7 @@ import type { UserSessionsRepository } from '../../db/repositories/UserSessions.
import type { UsersRepository } from '../../db/repositories/Users.repository';
import { verifyJwtAndLoadUser } from '../auth-core/jwt-verify';
import { withRequestContext } from '../database/request-context';
import type { PublicMediaService } from '../memories/public-media.service';
import { StorageService } from '../storage/storage.service';
import { StorageInvalidKeyError, StorageNotFoundError, type StorageCategory } from '../storage/storage.types';
import { precompressedStatic } from './precompressed-static';
@@ -67,6 +68,17 @@ export function answerUnmatchedGet(req: Request, res: Response, message = 'Not F
res.sendFile('index.html', { root: PUBLIC_DIR });
}
/**
* What a public mount may serve and in which form: `allows` gates the name
* (the journey mount refuses journey entry media), `rendition` names the
* location-free copy to send instead of the stored object, or null when there
* is none, which reads as a miss.
*/
interface PublicServing {
allows?: (name: string) => Promise<boolean>;
rendition: (name: string) => Promise<string | null>;
}
/**
* express.static replacement for the four public /uploads mounts (storage
* slice 3). Parity contract (spec §Serving): identical ETag / Last-Modified /
@@ -76,9 +88,14 @@ export function answerUnmatchedGet(req: Request, res: Response, message = 'Not F
* next() so the request falls through to the Nest router's standard 404
* envelope, exactly like express.static's fallthrough. 412/416/5xx go to
* next(err) with send's own http-errors — the same finalhandler path
* express.static uses.
* express.static uses. With `serving`, the handler sends the location-free
* copy it names instead of the object, and a name it refuses is a miss.
*/
export function storageStaticHandler(storage: StorageService, category: StorageCategory): express.RequestHandler {
export function storageStaticHandler(
storage: StorageService,
category: StorageCategory,
serving?: PublicServing,
): express.RequestHandler {
return (req: Request, res: Response, next: NextFunction) => {
// serve-static fallthrough: non-GET/HEAD pass straight through (no 405).
if (req.method !== 'GET' && req.method !== 'HEAD') {
@@ -96,27 +113,36 @@ export function storageStaticHandler(storage: StorageService, category: StorageC
return;
}
const name = decoded.replace(/^\/+/, '');
return storage.sendToResponse(category, name, res).catch((err: unknown) => {
// MISS contract: unknown object, invalid key ('' at the mount root,
// '..', dot segments, control chars) → Nest 404 envelope.
if (err instanceof StorageNotFoundError || err instanceof StorageInvalidKeyError) {
next();
return;
}
const e = err as { status?: number; code?: string; syscall?: string };
// stat→sendFile race (send 404) and directories: static falls through too.
if (e.status === 404 || e.code === 'EISDIR') {
next();
return;
}
// Client gone / bytes already on the wire: nothing useful to send —
// mirrors res.sendFile's own default callback (express response.js:454).
if (e.code === 'ECONNABORTED' || e.syscall === 'write') return;
next(err as Error);
});
return resolveServedName(name, serving)
.then((served) => (served === null ? next() : storage.sendToResponse(category, served, res)))
.catch((err: unknown) => {
// MISS contract: unknown object, invalid key ('' at the mount root,
// '..', dot segments, control chars) → Nest 404 envelope.
if (err instanceof StorageNotFoundError || err instanceof StorageInvalidKeyError) {
next();
return;
}
const e = err as { status?: number; code?: string; syscall?: string };
// stat→sendFile race (send 404) and directories: static falls through too.
if (e.status === 404 || e.code === 'EISDIR') {
next();
return;
}
// Client gone / bytes already on the wire: nothing useful to send —
// mirrors res.sendFile's own default callback (express response.js:454).
if (e.code === 'ECONNABORTED' || e.syscall === 'write') return;
next(err as Error);
});
};
}
/** The object name a static mount sends for `name`, or null for a miss. */
async function resolveServedName(name: string, serving: PublicServing | undefined): Promise<string | null> {
if (!serving) return name;
if (serving.allows && !(await serving.allows(name))) return null;
return serving.rendition(name);
}
async function servePhoto(
storage: StorageService,
req: Request,
@@ -125,6 +151,7 @@ async function servePhoto(
shareTokens: ShareTokensRepository,
photos: PhotosRepository,
sessions: UserSessionsRepository,
publicMedia: PublicMediaService | undefined,
): Promise<void> {
const safeName = path.basename(req.params.filename);
// Parity: after basename(), the old resolve()+startsWith guard could only
@@ -139,8 +166,8 @@ async function servePhoto(
res.status(404).send('Not found');
return;
}
const sendPhoto = () =>
storage.sendToResponse('photos', safeName, res).catch((err: unknown) => {
const sendPhoto = (name = safeName) =>
storage.sendToResponse('photos', name, res).catch((err: unknown) => {
// exists→send delete race: same 404 text as the miss branch.
if ((err instanceof StorageNotFoundError || err instanceof StorageInvalidKeyError) && !res.headersSent) {
res.status(404).send('Not found');
@@ -172,7 +199,15 @@ async function servePhoto(
res.status(401).send('Authentication required');
return;
}
return sendPhoto();
// A share link is no account: it gets the copy without the location, and a
// photo that cannot be cleaned is not sent at all (fail closed, also when no
// PublicMediaService was wired).
const rendition = publicMedia ? await publicMedia.renditionFor('photos', safeName).catch(() => null) : null;
if (!rendition) {
res.status(404).send('Not found');
return;
}
return sendPhoto(rendition);
}
/**
@@ -221,29 +256,44 @@ export function applyPlatformUploads(
app: express.Application,
storage: StorageService,
orm?: { em: EntityManager },
publicMedia?: PublicMediaService,
): void {
// Static: avatars, covers, and journey photos.
// Static: avatars, covers, journey covers and place images.
//
// Security model (audit SEC-M9): these paths are unauthenticated by
// design. All filenames are server-chosen UUID v4 (see `uuid()` in
// the multer storage config for avatars / covers / journey uploads),
// which gives each asset >122 bits of namespace entropy — not
// guessable via enumeration. An attacker would need to have already
// seen the URL (email, shared journey, etc.) to request the file.
//
// Moving these behind auth would also break:
// - Unauthenticated trip-card rendering on public share links
// - Journey public-share pages (/public/journey/:token)
// - Email-embedded avatars
// Security model (audit SEC-M9): these paths are unauthenticated by design,
// because share-link trip cards, journey public pages and email-embedded
// avatars load them without a session. Filenames are server-chosen UUID v4
// (>122 bits), so nothing can be enumerated, but a URL that was seen once
// keeps working, so two rules bound what it can hand out:
// - Every object goes out as its location-free copy (PublicMediaService:
// EXIF GPS, IPTC and XMP place fields and movie location atoms blanked,
// or a fresh re-encode of an image whose metadata cannot be cleaned),
// never as uploaded; only what can be neither is a 404.
// - /uploads/journey does not serve journey entry media (originals,
// posters, thumbs/) unless a journey uses it as its cover. Those go
// through the token-checked /api/public/journey proxy or the
// session-checked ones, so revoking a share link takes them away.
// Covers, and other objects a trip cover or place image points at,
// stay reachable.
// Without PublicMediaService (a partial test wiring) the four mounts serve
// nothing rather than the raw bytes.
//
// The `/uploads/photos/...` route below is DIFFERENT: photo URLs are
// not embedded in unauthenticated UI contexts, so that endpoint IS
// gated (session JWT with pv, or a share token scoped to the photo's
// trip).
app.use('/uploads/avatars', storageStaticHandler(storage, 'avatars'));
app.use('/uploads/covers', storageStaticHandler(storage, 'covers'));
app.use('/uploads/journey', storageStaticHandler(storage, 'journey'));
app.use('/uploads/places', storageStaticHandler(storage, 'places'));
// trip, which gets the location-free copy too).
const serving = (category: StorageCategory, allows?: PublicServing['allows']): PublicServing => ({
allows,
rendition: (name) => (publicMedia ? publicMedia.renditionFor(category, name) : Promise.resolve(null)),
});
const servesFromJourneyMount = (name: string): Promise<boolean> => {
if (!publicMedia || !orm) return Promise.resolve(false);
return withRequestContext(orm, () => publicMedia.servesFromJourneyMount(name));
};
app.use('/uploads/avatars', storageStaticHandler(storage, 'avatars', serving('avatars')));
app.use('/uploads/covers', storageStaticHandler(storage, 'covers', serving('covers')));
app.use('/uploads/journey', storageStaticHandler(storage, 'journey', serving('journey', servesFromJourneyMount)));
app.use('/uploads/places', storageStaticHandler(storage, 'places', serving('places')));
// Photos require either a valid logged-in session (via JWT with the
// password_version gate) OR a share token that covers the SPECIFIC
@@ -264,6 +314,7 @@ export function applyPlatformUploads(
orm.em.getRepository(ShareTokens),
orm.em.getRepository(Photos),
orm.em.getRepository(UserSessions),
publicMedia,
),
).catch(next);
});
@@ -0,0 +1,151 @@
/**
* What each block of the public share payload (GET /api/shared/:token) may
* carry. The repositories hand over full rows; these allow-lists pick the
* columns the shared page reads, so a column added to a table later never
* becomes public by appearing. Names the page does not read stay behind:
* owner and author ids, private notes, ticket data, bookkeeping timestamps.
*/
/** A day as the shared page draws it: its number, date and title, never the owner's day notes. */
export interface PublicDay {
id: number;
day_number: number;
date: string | null;
title: string | null;
}
export function publicDay(d: PublicDay): PublicDay {
return { id: d.id, day_number: d.day_number, date: d.date ?? null, title: d.title ?? null };
}
/** A note on a day: its text, the detail line, the icon and colour, and where it sits among the stops. */
export interface PublicDayNote {
id: number;
day_id: number;
text: string;
time: string | null;
icon: string | null;
color: string | null;
sort_order: number | null;
}
export function publicDayNote(n: PublicDayNote): PublicDayNote {
return {
id: n.id,
day_id: n.day_id,
text: n.text,
time: n.time ?? null,
icon: n.icon ?? null,
color: n.color ?? null,
sort_order: n.sort_order ?? null,
};
}
/** A Common packing item: what it is, how many, and whether it is packed. Never whose it is. */
interface PublicPackingItem {
id: number;
name: string;
category: string | null;
checked: number | null;
quantity: number | null;
sort_order: number | null;
}
export function publicPackingItem(i: PublicPackingItem): PublicPackingItem {
return {
id: i.id,
name: i.name,
category: i.category ?? null,
checked: i.checked ?? null,
quantity: i.quantity ?? null,
sort_order: i.sort_order ?? null,
};
}
/**
* An expense: its name, group and amount with the rate it was entered at, which
* is all the Costs tab needs to convert it. The note, who paid, the linked
* booking and the stored ticket stay with the trip.
*/
interface PublicBudgetItem {
id: number;
name: string;
category: string;
total_price: number;
currency: string | null;
exchange_rate: number;
}
export function publicBudgetItem(i: PublicBudgetItem): PublicBudgetItem {
return {
id: i.id,
name: i.name,
category: i.category,
total_price: i.total_price,
currency: i.currency ?? null,
exchange_rate: i.exchange_rate,
};
}
/** A chat message under its author's name and avatar, without the author's account id. */
interface PublicCollabMessage {
id: number;
text: string;
created_at: string | null;
username: string;
avatar: string | null;
}
export function publicCollabMessage(m: PublicCollabMessage): PublicCollabMessage {
return { id: m.id, text: m.text, created_at: m.created_at ?? null, username: m.username, avatar: m.avatar ?? null };
}
/** A category as the page colours a pin or a stop with it. */
interface PublicCategory {
id: number;
name: string;
color: string | null;
icon: string | null;
}
interface CategorizedPlace {
category_id?: number | null;
category_name?: string | null;
category_color?: string | null;
category_icon?: string | null;
}
interface CategorizedStop {
place?: { category?: { id: number; name?: string | null; color?: string | null; icon?: string | null } | null };
}
/**
* The categories the shared places use, and only those. Categories are a pool
* across all users, so the payload used to carry every one of them, other
* users' own included. Read from the places that actually go out, after the
* narrowing options ran, so a hidden place does not leave its category behind.
*/
export function categoriesInUse(
places: readonly CategorizedPlace[],
assignments: Record<number, readonly CategorizedStop[]>,
): PublicCategory[] {
const byId = new Map<number, PublicCategory>();
const add = (id: number | null | undefined, name: string | null | undefined, color: unknown, icon: unknown) => {
// A dangling id or a category without a name has nothing to draw.
if (id == null || name == null || byId.has(id)) return;
byId.set(id, {
id,
name,
color: typeof color === 'string' ? color : null,
icon: typeof icon === 'string' ? icon : null,
});
};
for (const p of places) add(p.category_id, p.category_name, p.category_color, p.category_icon);
for (const rows of Object.values(assignments)) {
for (const a of rows) {
const c = a.place?.category;
if (c) add(c.id, c.name, c.color, c.icon);
}
}
return [...byId.values()].sort((a, b) => a.id - b.id);
}
+4 -1
View File
@@ -18,6 +18,7 @@ interface ShareSnapshot {
Array<{ accommodation_id?: number | null; place?: { id: number; image_url?: string | null } }>
>;
dayNotes: Record<number, unknown[]>;
days: Array<{ title?: string | null }>;
places: Array<{ id: number; image_url?: string | null }>;
reservations: Array<{ type?: unknown }>;
}
@@ -26,7 +27,8 @@ interface ShareSnapshot {
* "Only travel and stays": what family or an emergency contact needs to know,
* without the museum and the restaurant. A day keeps only the stop its night's
* booking wrote, the notes go, the place pool shrinks to where the trip sleeps,
* and the bookings to transport and hotels.
* and the bookings to transport and hotels. Day titles go too ("Louvre and
* lunch at Marie's" says what the link leaves out); the page then reads "Day N".
*/
export function travelOnly<T extends ShareSnapshot>(data: T, stayPlaceIds: ReadonlySet<number>): T {
const assignments: T['assignments'] = {};
@@ -38,6 +40,7 @@ export function travelOnly<T extends ShareSnapshot>(data: T, stayPlaceIds: Reado
...data,
assignments,
dayNotes: {},
days: data.days.map((d) => ({ ...d, title: null })),
places: data.places.filter((p) => stayPlaceIds.has(p.id)),
reservations: data.reservations.filter((r) => isTravelBooking(r.type)),
};
+1 -3
View File
@@ -1,5 +1,4 @@
import { BudgetItems } from '../../db/entities/BudgetItems.entity';
import { Categories } from '../../db/entities/Categories.entity';
import { CollabMessages } from '../../db/entities/CollabMessages.entity';
import { DayAssignments } from '../../db/entities/DayAssignments.entity';
import { DayNotes } from '../../db/entities/DayNotes.entity';
@@ -24,7 +23,7 @@ import { Module } from '@nestjs/common';
// `MikroOrmModule.forFeature([Reservations, ...])` registers every repository
// `ShareService`'s `@InjectRepository` constructor params need (Plan 3d Task 4
// already registered `Reservations`; Plan 3h Task 6 adds `ShareTokens` — this
// file's own table — plus the nine cross-domain tables its public-share reads
// file's own table — plus the eight cross-domain tables its public-share reads
// (SH7-9,11-16) touch, without importing each owning module: this file stays a
// leaf the way `PublicApiModule`'s own `Trips`-only `forFeature` already does
// for the same reason).
@@ -46,7 +45,6 @@ import { Module } from '@nestjs/common';
Places,
PackingItems,
BudgetItems,
Categories,
CollabMessages,
]),
],
+32 -18
View File
@@ -1,5 +1,4 @@
import { BudgetItems } from '../../db/entities/BudgetItems.entity';
import { Categories } from '../../db/entities/Categories.entity';
import { CollabMessages } from '../../db/entities/CollabMessages.entity';
import { DayAssignments } from '../../db/entities/DayAssignments.entity';
import { DayNotes } from '../../db/entities/DayNotes.entity';
@@ -10,7 +9,6 @@ import { Reservations } from '../../db/entities/Reservations.entity';
import { ShareTokens } from '../../db/entities/ShareTokens.entity';
import { Trips } from '../../db/entities/Trips.entity';
import type { BudgetItemsRepository } from '../../db/repositories/BudgetItems.repository';
import type { CategoriesRepository } from '../../db/repositories/Categories.repository';
import type { CollabMessagesRepository } from '../../db/repositories/CollabMessages.repository';
import type { DayAssignmentsRepository } from '../../db/repositories/DayAssignments.repository';
import type { DayNotesRepository } from '../../db/repositories/DayNotes.repository';
@@ -26,6 +24,16 @@ import { PermissionsService } from '../permissions/permissions.service';
import { PlacePhotoCacheService } from '../place-photos/place-photo-cache.service';
import { QueryHelpersService } from '../query-helpers/query-helpers.service';
import { SettingsService } from '../settings/settings.service';
import {
categoriesInUse,
publicBudgetItem,
publicCollabMessage,
publicDay,
publicDayNote,
publicPackingItem,
type PublicDay,
type PublicDayNote,
} from './share-public.helpers';
import { travelOnly, withoutImages } from './share-view.helpers';
import { InjectRepository } from '@mikro-orm/nestjs';
import { Injectable } from '@nestjs/common';
@@ -205,7 +213,6 @@ export class ShareService {
@InjectRepository(Places) private readonly places: PlacesRepository,
@InjectRepository(PackingItems) private readonly packingItems: PackingItemsRepository,
@InjectRepository(BudgetItems) private readonly budgetItems: BudgetItemsRepository,
@InjectRepository(Categories) private readonly categories: CategoriesRepository,
@InjectRepository(CollabMessages) private readonly collabMessages: CollabMessagesRepository,
) {}
@@ -350,12 +357,14 @@ export class ShareService {
};
// Itinerary — days with assignments/notes, and the place pool
let days: any[] = [];
let days: PublicDay[] = [];
let assignments: Record<number, any[]> = {};
let dayNotes: Record<number, any[]> = {};
let dayNotes: Record<number, PublicDayNote[]> = {};
let places: any[] = [];
if (permissions.share_map) {
days = await this.days.listByTrip(tripId);
// Number, date and title only: the day's own notes are the planner's, and
// the shared page never shows them.
days = (await this.days.listByTrip(tripId)).map(publicDay);
const dayIds = days.map((d) => d.id);
if (dayIds.length > 0) {
@@ -402,10 +411,10 @@ export class ShareService {
assignments = byDay;
const allNotes = await this.dayNotes.listByDayIds(dayIds);
const notesByDay: Record<number, any[]> = {};
const notesByDay: Record<number, PublicDayNote[]> = {};
for (const n of allNotes) {
if (!notesByDay[n.day_id]) notesByDay[n.day_id] = [];
notesByDay[n.day_id].push(n);
notesByDay[n.day_id].push(publicDayNote(n));
}
dayNotes = notesByDay;
}
@@ -453,17 +462,21 @@ export class ShareService {
// Packing — a public viewer is neither owner nor recipient, so only Common items
// may surface; never a co-member's private/personal packing items (#858).
const packing = permissions.share_packing ? await this.packingItems.listPublicForShare(tripId) : [];
// The three lists below go out through their allow-lists (share-public.helpers):
// the rows carry owner ids, private notes and ticket data the page never reads.
const packing = permissions.share_packing
? (await this.packingItems.listPublicForShare(tripId)).map(publicPackingItem)
: [];
// Budget
const budget = permissions.share_budget ? await this.budgetItems.listPublicForShare(tripId) : [];
// Categories are a shared global pool (the authed /api/categories list is
// equally unscoped), so the public payload returns them all too.
const categories = await this.categories.listAllUnordered();
const budget = permissions.share_budget
? (await this.budgetItems.listPublicForShare(tripId)).map(publicBudgetItem)
: [];
// Collab messages (only if owner chose to share)
const collabMessages = permissions.share_collab ? await this.collabMessages.listPublicForShare(tripId) : [];
const collabMessages = permissions.share_collab
? (await this.collabMessages.listPublicForShare(tripId)).map(publicCollabMessage)
: [];
// Display currency the share owner sees in their Costs view. A public viewer has
// no logged-in user, so the owner's per-user `default_currency` (with the admin
@@ -494,7 +507,7 @@ export class ShareService {
// The owner's narrowing options (#1712) apply last, over what the flags
// above already let through.
let view = { assignments, dayNotes, places, reservations };
let view = { assignments, days, dayNotes, places, reservations };
if (permissions.share_travel_only) {
const stayPlaceIds = new Set(await this.reservationsRepo.listPublicStayPlaceIdsForShare(tripId));
view = travelOnly(view, stayPlaceIds);
@@ -505,9 +518,10 @@ export class ShareService {
trip,
baseCurrency,
cartoApiKey,
categories,
// Only the categories of the places that went out, read after the narrowing
// above so a place the link hides does not leave its category behind.
categories: categoriesInUse(view.places, view.assignments),
permissions,
days,
...view,
accommodations,
packing,
+64 -2
View File
@@ -119,6 +119,57 @@ const { backfillRun, backfillSchedule } = vi.hoisted(() => ({ backfillRun: vi.fn
const { sharesvc } = vi.hoisted(() => ({ sharesvc: { getPublicJourney: vi.fn() } }));
// What the share service answers for a link with every section on: the route
// answers under a strict @ResponseContract, so this is also the allow-list.
const publicPhoto = {
id: 3,
photo_id: 30,
caption: null,
media_type: 'image',
width: 800,
height: 600,
duration_ms: null,
taken_at: null,
lat: null,
lng: null,
posterless: false,
};
const publicJourney = {
journey: {
title: 'J',
subtitle: null,
cover_image: null,
status: 'draft',
show_verdict: 1,
show_mood: 1,
show_weather: 1,
},
entries: [
{
id: 7,
type: 'entry',
entry_date: '2026-05-14',
entry_time: null,
sort_order: 0,
title: 'Venice',
story: null,
location_name: null,
location_lat: null,
location_lng: null,
country_code: null,
mood: null,
weather: null,
tags: [],
pros_cons: null,
photos: [publicPhoto],
},
],
gallery: [publicPhoto],
stats: { entries: 1, photos: 1, places: 0 },
cartoApiKey: '',
permissions: { share_timeline: true, share_gallery: true, share_map: false, newest_first: false },
};
const { mapsvc } = vi.hoisted(() => ({ mapsvc: { mapLayers: vi.fn(), publicMapLayers: vi.fn() } }));
const { booksvc } = vi.hoisted(() => ({
@@ -169,7 +220,7 @@ describe('Journey e2e (real auth guard + temp SQLite)', () => {
server = app.getHttpServer();
jsvc.listJourneys.mockReturnValue([journeyListRow]);
jsvc.createJourney.mockReturnValue(journeyRow(9));
sharesvc.getPublicJourney.mockReturnValue({ id: 9 });
sharesvc.getPublicJourney.mockReturnValue(publicJourney);
});
beforeEach(() => {
@@ -442,7 +493,18 @@ describe('Journey e2e (real auth guard + temp SQLite)', () => {
it('public journey read is unguarded (200 with a valid token, no cookie)', async () => {
const res = await request(server).get('/api/public/journey/tok');
expect(res.status).toBe(200);
expect(res.body).toEqual({ id: 9 });
expect(res.body).toEqual(publicJourney);
});
it('public journey read refuses a storage key or an asset id in its answer (strict contract)', async () => {
// The payload used to spread whole rows; the contract is what keeps a
// column added to a read later from reaching the public.
sharesvc.getPublicJourney.mockReturnValueOnce({
...publicJourney,
gallery: [{ ...publicPhoto, file_path: 'journey/abc.jpg', asset_id: 'abc' }],
});
const res = await request(server).get('/api/public/journey/tok');
expect(res.status).toBe(500);
});
it('public journey read still answers the addon gate when Journey is off', async () => {
+38 -1
View File
@@ -18,8 +18,11 @@ import { ZodValidationPipe } from '../../src/nest/common/zod-validation.pipe';
import { PermissionsService } from '../../src/nest/permissions/permissions.service';
import { PlacePhotoCacheService } from '../../src/nest/place-photos/place-photo-cache.service';
import { ShareModule } from '../../src/nest/share/share.module';
import { makeBudgetItem } from '../helpers/factories/budget';
import { makeDayAssignment, makeDayNote } from '../helpers/factories/itinerary';
import { makeCategory, makePlace } from '../helpers/factories/places';
import { deleteRows, findRow, insertRow } from '../helpers/factories/rows';
import { makeTrip } from '../helpers/factories/trips';
import { makeDay, makeTrip } from '../helpers/factories/trips';
import { makeUser } from '../helpers/factories/users';
import { createTestMikroOrmModule, createTestOrm, type TestOrm } from '../helpers/test-orm';
import { TestUnitOfWorkModule } from '../helpers/test-uow';
@@ -160,6 +163,7 @@ describe('Share-link e2e (real auth guard + real SQL over temp SQLite)', () => {
});
it('carries the narrowing options through to the public read (#1712)', async () => {
await makeDay(orm, tripId, { title: 'Museum day' });
const created = await request(server)
.post(`/api/trips/${tripId}/share-link`)
.set('Cookie', sessionCookie(1))
@@ -169,6 +173,7 @@ describe('Share-link e2e (real auth guard + real SQL over temp SQLite)', () => {
const res = await request(server).get(`/api/shared/${created.body.token}`);
expect(res.body.permissions).toEqual(expect.objectContaining({ share_travel_only: true, share_hide_images: true }));
expect(res.body.dayNotes).toEqual({});
expect(res.body.days.map((d: { title: string | null }) => d.title)).toEqual([null]);
const bad = await request(server)
.post(`/api/trips/${tripId}/share-link`)
.set('Cookie', sessionCookie(1))
@@ -187,6 +192,38 @@ describe('Share-link e2e (real auth guard + real SQL over temp SQLite)', () => {
expect(res.body.permissions).toEqual(expect.objectContaining({ share_map: true, share_budget: false }));
});
it('public shared read sends days, notes, categories and costs as allow-lists', async () => {
const used = await makeCategory(orm, { name: 'Museums' });
await makeCategory(orm, { name: 'Private stash', user: 1 });
const day = await makeDay(orm, tripId, { title: 'Louvre day', notes: 'Owner day plan' });
const place = await makePlace(orm, tripId, { name: 'Louvre', category: used.id });
await makeDayAssignment(orm, day.id, place.id);
await makeDayNote(orm, day.id, tripId, { text: 'Meet at noon' });
await makeBudgetItem(orm, tripId, { name: 'Tickets', note: 'Card ending 4242', ticket_json: '{"seat":"12A"}' });
const created = await request(server)
.post(`/api/trips/${tripId}/share-link`)
.set('Cookie', sessionCookie(1))
.send({ share_budget: true });
const res = await request(server).get(`/api/shared/${created.body.token}`);
expect(res.status).toBe(200);
expect(res.body.days).toEqual([{ id: day.id, day_number: day.day_number, date: null, title: 'Louvre day' }]);
expect(res.body.dayNotes[day.id]).toEqual([expect.objectContaining({ text: 'Meet at noon' })]);
expect(res.body.dayNotes[day.id][0]).not.toHaveProperty('trip_id');
expect(res.body.categories).toEqual([{ id: used.id, name: 'Museums', color: used.color, icon: used.icon }]);
expect(res.body.budget).toEqual([
{
id: expect.any(Number),
name: 'Tickets',
category: 'Transport',
total_price: 100,
currency: null,
exchange_rate: 1,
},
]);
for (const secret of ['Owner day plan', '4242', '12A', 'Private stash']) expect(res.text).not.toContain(secret);
});
it('public shared read 404 for an invalid token', async () => {
const res = await request(server).get('/api/shared/bad');
expect(res.status).toBe(404);
+11 -2
View File
@@ -23,12 +23,15 @@ export interface ExifJpegTags {
OffsetTimeDigitized?: string;
/** Decimal degrees, stored as the usual degree/minute/second rationals plus N/S and E/W. */
gps?: { lat: number; lng: number };
/** 0x0112 in IFD0, 1 to 8. */
Orientation?: number;
}
const BASE_JPEG = path.join(__dirname, '../fixtures/small-image.jpg');
const BYTE = 1;
const ASCII = 2;
const SHORT = 3;
const LONG = 4;
const RATIONAL = 5;
@@ -118,12 +121,18 @@ export function jpegWithExif(tags: ExifJpegTags): Buffer {
gpsEntries.push(rationals(0x0004, dms(tags.gps.lng)));
}
// IFD0 holds only the two pointers, so its size is known before the offsets are.
const ifd0Count = (exifEntries.length ? 1 : 0) + (gpsEntries.length ? 1 : 0);
// IFD0 holds the orientation and the two pointers, so its size is known before the offsets are.
const ifd0Count =
(tags.Orientation !== undefined ? 1 : 0) + (exifEntries.length ? 1 : 0) + (gpsEntries.length ? 1 : 0);
const ifd0At = 8;
const exifAt = ifd0At + 2 + ifd0Count * 12 + 4;
const gpsAt = exifAt + (exifEntries.length ? ifdSize(exifEntries) : 0);
const ifd0Entries: Entry[] = [];
if (tags.Orientation !== undefined) {
const data = Buffer.alloc(2);
data.writeUInt16LE(tags.Orientation);
ifd0Entries.push({ tag: 0x0112, type: SHORT, count: 1, data });
}
if (exifEntries.length) ifd0Entries.push(long(0x8769, exifAt));
if (gpsEntries.length) ifd0Entries.push(long(0x8825, gpsAt));
+4 -8
View File
@@ -2,7 +2,6 @@ import { PluginUserErasureQueue } from '../../src/db/entities/PluginUserErasureQ
import { Plugins } from '../../src/db/entities/Plugins.entity';
import { ShareTokens } from '../../src/db/entities/ShareTokens.entity';
import type { BudgetItemsRepository } from '../../src/db/repositories/BudgetItems.repository';
import type { CategoriesRepository } from '../../src/db/repositories/Categories.repository';
import type { CollabMessagesRepository } from '../../src/db/repositories/CollabMessages.repository';
import type { DayAssignmentsRepository } from '../../src/db/repositories/DayAssignments.repository';
import type { DayNotesRepository } from '../../src/db/repositories/DayNotes.repository';
@@ -25,7 +24,6 @@ import {
createTestDayAssignmentsRepo,
createTestDayNotesRepo,
createTestPlacesRepo,
createTestCategoriesRepo,
} from './test-uow';
import type Database from 'better-sqlite3';
@@ -63,13 +61,13 @@ export function createTestPluginUserErasureQueueRepo(db: Database.Database): Pro
}
/**
* The 10 repository arguments `ShareService`'s constructor appends after
* The 9 repository arguments `ShareService`'s constructor appends after
* `uow` (`reservationsRepo`, `shareTokens`, `trips`, `days`, `dayAssignments`,
* `dayNotes`, `places`, `packingItems`, `budgetItems`, `categories`,
* `collabMessages` — 11 total, `reservationsRepo` already had its own 3d
* `dayNotes`, `places`, `packingItems`, `budgetItems`, `collabMessages` —
* 10 total, `reservationsRepo` already had its own 3d
* factory), built over the SAME connection in one call — every hand-built
* `new ShareService(...)` test call site spreads this
* (`...(await shareServiceRepoArgs(conn))`) instead of repeating all 11
* (`...(await shareServiceRepoArgs(conn))`) instead of repeating all 10
* factories, the `budgetRepoArgs` precedent.
*/
export async function shareServiceRepoArgs(
@@ -85,7 +83,6 @@ export async function shareServiceRepoArgs(
PlacesRepository,
PackingItemsRepository,
BudgetItemsRepository,
CategoriesRepository,
CollabMessagesRepository,
]
> {
@@ -99,7 +96,6 @@ export async function shareServiceRepoArgs(
await createTestPlacesRepo(db),
await createTestPackingItemsRepo(db),
await createTestBudgetItemsRepo(db),
await createTestCategoriesRepo(db),
await createTestCollabMessagesRepo(db),
];
}
@@ -0,0 +1,204 @@
/**
* Public byte paths and the location in a photo (PUBMEDIA-*).
*
* A phone photo carries the GPS fix it was taken at. A share link, a journey's
* public page and the anonymous /uploads mounts used to hand out the stored
* bytes, so the location left with them even where the owner had turned the
* map off, and /uploads/journey served every entry photo to whoever had seen
* its URL, share link revoked or not. Here the whole app answers over real
* files: the public gets the location-free copy, the owner the original.
*/
import { buildApp } from '../../src/bootstrap';
import { Addons } from '../../src/db/entities/Addons.entity';
import { Photos } from '../../src/db/entities/Photos.entity';
import { TrekPhotos } from '../../src/db/entities/TrekPhotos.entity';
import { authCookie, generateToken } from '../helpers/auth';
import { jpegWithExif } from '../helpers/exif-jpeg';
import { makeJourney } from '../helpers/factories/journeys';
import { findRow, insertRow, upsertRow } from '../helpers/factories/rows';
import { makeShareToken, makeTrip } from '../helpers/factories/trips';
import { makeUser } from '../helpers/factories/users';
import { resetDatabase } from '../helpers/reset-database';
import { resetRateLimits } from '../helpers/test-db';
import { MikroORM } from '@mikro-orm/core';
import type { INestApplication } from '@nestjs/common';
import exifr from 'exifr';
import type { Application } from 'express';
import fs from 'node:fs';
import path from 'node:path';
import request from 'supertest';
import { afterAll, beforeAll, beforeEach, describe, expect, it } from 'vitest';
let nestApp: INestApplication;
let app: Application;
let orm: MikroORM;
const uploadsDir = path.join(__dirname, '../../uploads');
// Every object this suite leaves behind, original and copy, removed one by one:
// the uploads tree is shared with other integration workers.
const created: string[] = [];
const GPS = { lat: 49.274523, lng: -0.703421 };
const phonePhoto = () => jpegWithExif({ DateTimeOriginal: '2026:05:30 15:52:19', gps: GPS, Orientation: 6 });
function track(category: string, name: string): void {
created.push(path.join(uploadsDir, category, name), path.join(uploadsDir, category, 'public', name));
}
/** Reads any answer whole as bytes, whatever its content type. */
function bytes(req: request.Test): request.Test {
return req.buffer(true).parse((res, done) => {
const chunks: Buffer[] = [];
res.on('data', (chunk: Buffer) => chunks.push(chunk));
res.on('end', () => done(null, Buffer.concat(chunks)));
});
}
async function gpsOf(body: Buffer): Promise<number | undefined> {
return (await exifr.gps(body).catch(() => undefined))?.latitude;
}
async function uploadGalleryPhoto(userId: number, journeyId: number): Promise<{ name: string; photoId: number }> {
const res = await request(app)
.post(`/api/journeys/${journeyId}/gallery/photos`)
.set('Cookie', authCookie(userId))
.attach('photos', phonePhoto(), { filename: 'PXL_20260530_135219.jpg', contentType: 'image/jpeg' });
expect(res.status).toBe(201);
const filePath = res.body.photos[0].file_path as string;
const name = filePath.replace(/^journey\//, '');
track('journey', name);
const row = await findRow(orm, TrekPhotos, { file_path: filePath });
if (!row) throw new Error(`no trek_photos row for ${filePath}`);
return { name, photoId: row.id };
}
async function shareLink(userId: number, journeyId: number, flags: Record<string, boolean>): Promise<string> {
const res = await request(app)
.post(`/api/journeys/${journeyId}/share-link`)
.set('Cookie', authCookie(userId))
.send(flags);
expect(res.status).toBe(200);
return res.body.token as string;
}
beforeAll(async () => {
nestApp = await buildApp();
app = nestApp.getHttpAdapter().getInstance();
orm = nestApp.get(MikroORM);
});
beforeEach(async () => {
await resetDatabase(orm);
await resetRateLimits(nestApp);
await upsertRow(orm, Addons, {
id: 'journey',
name: 'Journey',
description: 'Travel journal',
type: 'global',
icon: 'Compass',
enabled: true,
sort_order: 35,
});
});
afterAll(async () => {
await nestApp.close();
for (const file of created) fs.rmSync(file, { force: true });
});
describe('journey share link', () => {
it('PUBMEDIA-001: with the map not shared, /original carries no GPS, orientation kept; the owner still gets the original', async () => {
const { user } = await makeUser(orm);
const journey = await makeJourney(orm, user.id);
const { photoId } = await uploadGalleryPhoto(user.id, journey.id);
const token = await shareLink(user.id, journey.id, { share_timeline: true, share_gallery: true, share_map: false });
const shared = await bytes(request(app).get(`/api/public/journey/${token}/photos/${photoId}/original`));
expect(shared.status).toBe(200);
const body = shared.body as Buffer;
expect(await gpsOf(body)).toBeUndefined();
expect(await exifr.orientation(body)).toBe(6);
expect(body.length).toBe(phonePhoto().length);
const owned = await bytes(request(app).get(`/api/photos/${photoId}/original`).set('Cookie', authCookie(user.id)));
expect(owned.status).toBe(200);
expect(await gpsOf(owned.body as Buffer)).toBeCloseTo(GPS.lat, 5);
});
it('PUBMEDIA-002: once the share link is deleted, no URL it handed out returns bytes', async () => {
const { user } = await makeUser(orm);
const journey = await makeJourney(orm, user.id);
const { name, photoId } = await uploadGalleryPhoto(user.id, journey.id);
const token = await shareLink(user.id, journey.id, { share_timeline: true, share_gallery: true, share_map: true });
const original = `/api/public/journey/${token}/photos/${photoId}/original`;
const thumbnail = `/api/public/journey/${token}/photos/${photoId}/thumbnail`;
expect((await request(app).get(original)).status).toBe(200);
const revoke = await request(app)
.delete(`/api/journeys/${journey.id}/share-link`)
.set('Cookie', authCookie(user.id));
expect(revoke.status).toBe(200);
expect((await request(app).get(original)).status).toBe(404);
expect((await request(app).get(thumbnail)).status).toBe(404);
expect(
(await request(app).get(`/api/public/journey/${token}/photo/local/${name}/${user.id}/original`)).status,
).toBe(404);
// Nor does the static mount: an entry photo is no cover.
expect((await request(app).get(`/uploads/journey/${name}`)).status).toBe(404);
});
});
describe('/uploads/journey', () => {
it('PUBMEDIA-010: serves a cover, location-free, and 404s an entry photo for everyone', async () => {
const { user } = await makeUser(orm);
const journey = await makeJourney(orm, user.id);
const { name: entryPhoto } = await uploadGalleryPhoto(user.id, journey.id);
const cover = await request(app)
.post(`/api/journeys/${journey.id}/cover`)
.set('Cookie', authCookie(user.id))
.attach('cover', phonePhoto(), { filename: 'cover.jpg', contentType: 'image/jpeg' });
expect(cover.status).toBe(200);
const coverName = (cover.body.cover_image as string).replace(/^journey\//, '');
track('journey', coverName);
const hit = await bytes(request(app).get(`/uploads/journey/${coverName}`));
expect(hit.status).toBe(200);
expect(hit.headers['content-type']).toBe('image/jpeg');
expect(await gpsOf(hit.body as Buffer)).toBeUndefined();
expect(await exifr.orientation(hit.body as Buffer)).toBe(6);
expect((await request(app).get(`/uploads/journey/${entryPhoto}`)).status).toBe(404);
expect((await request(app).get(`/uploads/journey/${entryPhoto}`).set('Cookie', authCookie(user.id))).status).toBe(
404,
);
// The copies are not reachable by their own name either.
expect((await request(app).get(`/uploads/journey/public/${coverName}`)).status).toBe(404);
});
});
describe('/uploads/photos with a trip share token', () => {
it('PUBMEDIA-020: the share token gets the copy without GPS, a session the stored photo', async () => {
const { user } = await makeUser(orm);
const trip = await makeTrip(orm, user.id);
const name = 'pubmedia-trip-photo.integration.jpg';
fs.mkdirSync(path.join(uploadsDir, 'photos'), { recursive: true });
fs.writeFileSync(path.join(uploadsDir, 'photos', name), phonePhoto());
track('photos', name);
await insertRow(orm, Photos, { trip: trip.id, filename: name, original_name: name });
await makeShareToken(orm, trip.id, user.id, { token: 'pubmedia-share-token' });
const shared = await bytes(request(app).get(`/uploads/photos/${name}?token=pubmedia-share-token`));
expect(shared.status).toBe(200);
expect(await gpsOf(shared.body as Buffer)).toBeUndefined();
const owned = await bytes(
request(app)
.get(`/uploads/photos/${name}`)
.set('Authorization', `Bearer ${generateToken(user.id)}`),
);
expect(owned.status).toBe(200);
expect(await gpsOf(owned.body as Buffer)).toBeCloseTo(GPS.lat, 5);
});
});
@@ -71,6 +71,8 @@ afterAll(async () => {
} catch {
/* ignore */
}
// The location-free copy the share-token case made beside it.
fs.rmSync(path.join(path.dirname(photoFile), 'public', photoName), { force: true });
});
beforeEach(async () => {
@@ -12,6 +12,10 @@
* These routes are unauthenticated BY DESIGN (audit SEC-M9): server-chosen
* UUIDv4 filenames; gating them would break share-link trip cards, journey
* public pages, and email-embedded avatars. No auth setup here is deliberate.
* Each hit is the object's location-free copy (PublicMediaService); the PNG
* magic below holds no metadata, so the copy carries the same 8 bytes.
* /uploads/journey refuses journey entry media and its thumbs/ unless a
* journey uses it as its cover (PUBMEDIA-010 in public-media-privacy.test.ts).
*/
import { buildApp } from '../../src/bootstrap';
import type { INestApplication } from '@nestjs/common';
@@ -58,7 +62,11 @@ beforeAll(async () => {
afterAll(async () => {
await nestApp.close();
for (const abs of created) fs.rmSync(abs, { force: true });
for (const abs of created) {
fs.rmSync(abs, { force: true });
// The location-free copy the first hit made beside it.
fs.rmSync(path.join(path.dirname(abs), 'public', path.basename(abs)), { force: true });
}
fs.rmSync(path.join(uploadsDir, 'avatars/.tmp'), { recursive: true, force: true });
fs.rmSync(path.join(uploadsDir, 'journey/parity-subdir'), { recursive: true, force: true });
});
@@ -209,7 +217,7 @@ describe('/uploads static parity — miss falls through to the Nest 404 envelope
});
describe('/uploads static parity — all four mounts', () => {
it('UPLOADS-P21 — covers/journey(nested)/places each serve a hit and 404 a miss', async () => {
it('UPLOADS-P21: covers/journey/places each serve a hit and 404 a miss, journey thumbs are refused', async () => {
// Fixtures are (re)written immediately before each request: other suites
// rm their whole category dir in afterAll (collections/trips → covers,
// collections → places, journey.test → journey), so a beforeAll-written
@@ -221,14 +229,19 @@ describe('/uploads static parity — all four mounts', () => {
expect(coverMiss.status).toBe(404);
expect(coverMiss.body.error).toBe('Cannot GET /uploads/covers/nope.png');
// Nested name — journey thumbs live at journey/thumbs/<hash>.jpg and are
// served through the same mount; pins multi-segment storage keys.
// Journey thumbs live at journey/thumbs/<hash>.jpg and go through the
// share proxy, so the mount answers a miss for the object that exists
// exactly as for one that does not.
writeFixture('journey/thumbs/uploads-static-parity.jpg');
const journeyHit = await request(app).get('/uploads/journey/thumbs/uploads-static-parity.jpg');
expect(journeyHit.status).toBe(200);
expect(journeyHit.headers['content-type']).toBe('image/jpeg');
const journeyThumb = await request(app).get('/uploads/journey/thumbs/uploads-static-parity.jpg');
expect(journeyThumb.status).toBe(404);
expect(journeyThumb.body.error).toBe('Cannot GET /uploads/journey/thumbs/uploads-static-parity.jpg');
const journeyMiss = await request(app).get('/uploads/journey/thumbs/nope.jpg');
expect(journeyMiss.status).toBe(404);
// An object no journey entry holds (a trip cover may point here) is served.
writeFixture(`journey/${NAME}`);
const journeyHit = await request(app).get(`/uploads/journey/${NAME}`);
expect(journeyHit.status).toBe(200);
writeFixture(`places/${NAME}`);
const placeHit = await request(app).get(`/uploads/places/${NAME}`);
@@ -181,8 +181,10 @@ describe('an entry as a card shows it', () => {
expect(lookOf(entry({ entry_time: 'noon' }))?.time).toBeNull();
expect(lookOf(entry({ location_lng: null }))?.point).toBeNull();
expect(lookOf(entry())?.point).toEqual({ lat: 52.52, lng: 13.405 });
const tidy = lookOf(entry({ country_code: 'xyz', mood: 'Very happy', visibility: 'friends', type: 'diary' }));
expect(tidy).toMatchObject({ countryCode: null, mood: null, visibility: 'private', type: 'entry' });
const tidy = lookOf(entry({ country_code: 'xyz', mood: 'Very happy', type: 'diary' }));
expect(tidy).toMatchObject({ countryCode: null, mood: null, type: 'entry' });
// The row's visibility keeps nothing off the share link, so the card does not show it.
expect(lookOf(entry())).not.toHaveProperty('visibility');
expect(lookOf(entry())?.countryCode).toBe('DE');
expect(lookOf(entry({ entry_date: '21.10.2026' }))).toBeNull();
});
@@ -224,7 +226,6 @@ describe('the change cards', () => {
expect(card).toMatchObject({ change: 'new', journalTitle: 'Berlin 2026', tripJournal: true, more: 0 });
expect(card.entries[0]).toMatchObject({
entryId: null,
visibility: 'private',
photoId: null,
photoCount: 0,
title: 'Write to me at bo@example.com',
@@ -312,10 +313,10 @@ describe('the change cards', () => {
expect(updated.rows).toEqual([{ op: 'change', labelKey: 'time', before: '14:30', after: '18:00' }]);
expect(describeToolCall('update_journey_entry', 'c4', {}, ctx).rows).toEqual([]);
// Who sees it, its mood and whether it is a draft each get a row; a state set to what it holds gets none.
// Its mood and whether it is a draft each get a row; a state set to what it holds gets none. A
// visibility from a call held before the tools dropped it is no state the card names.
const states = { entryId: 12, visibility: 'private', mood: null, weather: 'sunny', is_draft: true };
expect(describeToolCall('update_journey_entry', 'c6', states, ctx, loaded).rows).toEqual([
{ op: 'change', labelKey: 'field', field: 'visibility', before: 'public', after: 'private' },
{ op: 'change', labelKey: 'field', field: 'mood', before: 'amazing', after: '' },
{ op: 'change', labelKey: 'field', field: 'is_draft', before: '✗', after: '✓' },
]);
@@ -9,6 +9,7 @@ import type { AppSettingsRepository } from '../../../src/db/repositories/AppSett
import { AirtrailSyncJob } from '../../../src/nest/integrations/airtrail-sync.job';
import type { AirtrailSyncService } from '../../../src/nest/integrations/airtrail-sync.service';
import { JourneyThumbsJob } from '../../../src/nest/memories/journey-thumbs.job';
import type { PublicMediaService } from '../../../src/nest/memories/public-media.service';
import type { ThumbnailService } from '../../../src/nest/memories/thumbnail.service';
import { TrekPhotoCacheJob } from '../../../src/nest/memories/trek-photo-cache.job';
import type { TrekPhotoCacheService } from '../../../src/nest/memories/trek-photo-cache.service';
@@ -122,6 +123,25 @@ describe('PlacePhotoCacheJob', () => {
expect(() => job.sweep()).not.toThrow();
expect(logMock.logError).toHaveBeenCalledWith('Place-photo cache cleanup: fs down');
const thumbsDown = make(
() => {
throw new Error('storage down');
},
true,
4,
);
await thumbsDown.job.sweep();
// The copies are still swept after the thumbnail pass failed.
expect(thumbsDown.publicMedia.sweepOrphans).toHaveBeenCalledTimes(1);
expect(logMock.logInfo).toHaveBeenCalledWith(
'Public media cleanup: removed 4 location-free copies of deleted media',
);
await make(0, true, () => {
throw new Error('bucket throttled');
}).job.sweep();
expect(logMock.logError).toHaveBeenCalledWith('Public media cleanup: bucket throttled');
const gated = make(0, false);
gated.job.onApplicationBootstrap();
expect(gated.cache.sweepOrphans).not.toHaveBeenCalled();
@@ -130,16 +150,20 @@ describe('PlacePhotoCacheJob', () => {
});
describe('JourneyThumbsJob', () => {
function make(removed: number | (() => number) = 0, enabled = true) {
function make(removed: number | (() => number) = 0, enabled = true, renditions: number | (() => number) = 0) {
const registrar = registrarStub(enabled);
const thumbnails = {
sweepOrphanThumbs: vi.fn(typeof removed === 'function' ? removed : () => Promise.resolve(removed)),
};
const publicMedia = {
sweepOrphans: vi.fn(typeof renditions === 'function' ? renditions : () => Promise.resolve(renditions)),
};
const job = new JourneyThumbsJob(
thumbnails as unknown as ThumbnailService,
publicMedia as unknown as PublicMediaService,
registrar as unknown as CronRegistrarService,
);
return { job, registrar, thumbnails };
return { job, registrar, thumbnails, publicMedia };
}
it('CSJOB-010 — boot sweep runs immediately, then the daily app-tz cron registers', async () => {
@@ -156,6 +180,17 @@ describe('JourneyThumbsJob', () => {
expect(logMock.logInfo).toHaveBeenCalledWith('Journey thumbnail cleanup: removed 2 orphaned thumbnail(s)');
});
it('CSJOB-013: the same pass sweeps the location-free copies and logs only when it removed some', async () => {
const quiet = make(0);
await quiet.job.sweep();
expect(quiet.publicMedia.sweepOrphans).toHaveBeenCalledTimes(1);
expect(logMock.logInfo).not.toHaveBeenCalled();
await make(0, true, 3).job.sweep();
expect(logMock.logInfo).toHaveBeenCalledWith(
'Public media cleanup: removed 3 location-free copies of deleted media',
);
});
it('CSJOB-012 — a throwing sweep is contained to the cleanup log line, and the gate skips the boot sweep', async () => {
const { job } = make(() => {
throw new Error('storage down');
@@ -13,10 +13,7 @@ import { TrekPhotos } from '../../../src/db/entities/TrekPhotos.entity';
import { TripPhotos } from '../../../src/db/entities/TripPhotos.entity';
import type { JourneyEntriesRepository } from '../../../src/db/repositories/JourneyEntries.repository';
import type { JourneyEntryPhotosRepository } from '../../../src/db/repositories/JourneyEntryPhotos.repository';
import type {
JourneyPublicGalleryRow,
JourneyShareTokensRepository,
} from '../../../src/db/repositories/JourneyShareTokens.repository';
import type { JourneyShareTokensRepository } from '../../../src/db/repositories/JourneyShareTokens.repository';
import { JourneyDomainService } from '../../../src/nest/journey/journey-domain.service';
import { JourneyShareService } from '../../../src/nest/journey/journey-share.service';
import { TrekPhotoRegistrationService } from '../../../src/nest/photos/trek-photo-registration.service';
@@ -48,6 +45,7 @@ import {
createTestTripsRepo,
createTestPlacesRepo,
} from '../../helpers/test-uow';
import { journeyPublicResponseSchema } from '@trek/shared';
import { describe, it, expect, vi, beforeAll, beforeEach, afterAll } from 'vitest';
@@ -139,6 +137,13 @@ afterAll(async () => {
// -- Helpers ------------------------------------------------------------------
/** The public payload of a share link that is expected to exist. */
async function publicJourney(token: string) {
const result = await svc.getPublicJourney(token);
if (!result) throw new Error('no public payload for the share link');
return result;
}
/** Insert a trek_photos + journey_photos (gallery) + journey_entry_photos row and return the trek_photos id (used as photoId in public URLs). */
async function insertJourneyPhoto(
entryId: number,
@@ -819,7 +824,7 @@ describe('getPublicJourney', () => {
});
const result = (await svc.getPublicJourney(token))!;
const gallery = result.gallery as JourneyPublicGalleryRow[];
const gallery = result.gallery;
expect(gallery).toHaveLength(1);
expect(gallery[0].lat).toBeNull();
expect(gallery[0].lng).toBeNull();
@@ -848,7 +853,7 @@ describe('getPublicJourney', () => {
share_map: true,
});
const gallery = (await svc.getPublicJourney(token))!.gallery as JourneyPublicGalleryRow[];
const gallery = (await svc.getPublicJourney(token))!.gallery;
expect(gallery[0].lat).toBe(48.8584);
expect(gallery[0].lng).toBe(2.2945);
});
@@ -892,7 +897,7 @@ describe('getPublicJourney', () => {
});
const late = await insertJourneyPhoto(day2.id, { filePath: '/photos/day2.jpg' });
await insertJourneyPhoto(day1.id, { filePath: '/photos/day1.jpg' });
const early = await insertJourneyPhoto(day1.id, { filePath: '/photos/day1.jpg' });
await updateRows(t, TrekPhotos, { id: late }, { taken_at: '2026-05-02T16:00:00.000Z' });
const { token } = await svc.createOrUpdateJourneyShareLink(journey.id, user.id, {
@@ -901,8 +906,92 @@ describe('getPublicJourney', () => {
share_map: true,
});
const gallery = (await svc.getPublicJourney(token))!.gallery as JourneyPublicGalleryRow[];
expect(gallery.map((p) => p.file_path)).toEqual(['/photos/day1.jpg', '/photos/day2.jpg']);
const gallery = (await svc.getPublicJourney(token))!.gallery;
expect(gallery.map((p) => p.photo_id)).toEqual([early, late]);
});
it.each([
{ share_timeline: true, share_gallery: true, share_map: true },
{ share_timeline: false, share_gallery: true, share_map: true },
{ share_timeline: false, share_gallery: false, share_map: true },
])('JOURNEY-SHARE-032: no storage key, asset id, owner or author leaves the server (%o)', async (flags) => {
const { user } = createUser(testDb);
const journey = createJourney(testDb, user.id);
const entry = createJourneyEntry(testDb, journey.id, user.id, {
type: 'entry',
title: 'Day 1',
story: 'notes',
entry_date: '2026-05-01',
location_name: 'Paris',
});
await updateRows(t, JourneyEntries, { id: entry.id }, { location_lat: 48.8566, location_lng: 2.3522 });
await insertJourneyPhoto(entry.id, { ownerId: user.id, filePath: 'journey/0b9c2f.jpg' });
await insertJourneyPhoto(entry.id, { ownerId: user.id, assetId: 'immich-asset-1' });
const { token } = await svc.createOrUpdateJourneyShareLink(journey.id, user.id, flags);
const result = await publicJourney(token);
// The route's contract is strict, so a key it does not name fails here.
expect(journeyPublicResponseSchema.safeParse(result).success).toBe(true);
const wire = JSON.stringify(result);
for (const leak of ['journey/0b9c2f.jpg', 'immich-asset-1', 'file_path', 'thumbnail_path', 'asset_id']) {
expect(wire).not.toContain(leak);
}
// Photos here are stills: `provider` only goes out with a clip (JOURNEY-SHARE-033).
for (const column of ['owner_id', 'author_id', 'visibility', 'journey_id', 'source_trip_id', 'provider']) {
expect(wire).not.toContain(`"${column}"`);
}
});
it('JOURNEY-SHARE-033: a local clip without a poster says so, without its storage key (#2341)', async () => {
const { user } = createUser(testDb);
const journey = createJourney(testDb, user.id);
const entry = createJourneyEntry(testDb, journey.id, user.id, { type: 'entry', entry_date: '2026-05-01' });
const clip = await insertJourneyPhoto(entry.id, { ownerId: user.id, filePath: 'journey/clip.mp4' });
const posterClip = await insertJourneyPhoto(entry.id, { ownerId: user.id, filePath: 'journey/poster.mp4' });
const remoteClip = await insertJourneyPhoto(entry.id, { ownerId: user.id, assetId: 'remote-clip' });
await updateRows(t, TrekPhotos, { id: clip }, { media_type: 'video' });
await updateRows(t, TrekPhotos, { id: posterClip }, { media_type: 'video', thumbnail_path: 'journey/poster.jpg' });
await updateRows(t, TrekPhotos, { id: remoteClip }, { media_type: 'video' });
const { token } = await svc.createOrUpdateJourneyShareLink(journey.id, user.id, {});
const result = await publicJourney(token);
const posterless = Object.fromEntries(result.gallery.map((p) => [p.photo_id, p.posterless]));
expect(posterless).toEqual({ [clip]: true, [posterClip]: false, [remoteClip]: false });
const [first] = result.entries;
expect(first?.photos?.find((p) => p.photo_id === clip)?.posterless).toBe(true);
// Clips keep their provider for app builds and cached pages from before
// `posterless`; it is no storage key, and the poster path still stays home.
const providers = Object.fromEntries(result.gallery.map((p) => [p.photo_id, p.provider]));
expect(providers).toEqual({ [clip]: 'local', [posterClip]: 'local', [remoteClip]: 'immich' });
expect(JSON.stringify(result)).not.toContain('journey/poster.jpg');
});
it('JOURNEY-SHARE-034: a map-only share sends the marker fields and nothing of the story', async () => {
const { user } = createUser(testDb);
const journey = createJourney(testDb, user.id);
const entry = createJourneyEntry(testDb, journey.id, user.id, {
type: 'entry',
title: 'Day 1',
story: 'private notes',
entry_date: '2026-05-01',
location_name: 'Paris',
});
await updateRows(
t,
JourneyEntries,
{ id: entry.id },
{ location_lat: 48.8566, location_lng: 2.3522, mood: 'good' },
);
const { token } = await svc.createOrUpdateJourneyShareLink(journey.id, user.id, {
share_timeline: false,
share_gallery: false,
share_map: true,
});
const [first] = (await publicJourney(token)).entries;
expect(Object.keys(first ?? {}).sort()).toEqual(
['entry_date', 'id', 'location_lat', 'location_lng', 'location_name', 'sort_order', 'title', 'type'].sort(),
);
});
it('JOURNEY-SHARE-030: cartoApiKey resolves owner setting → admin instance default → empty (#2054)', async () => {
@@ -8,6 +8,7 @@ import type { JourneyPhotoLinksService } from '../../../src/nest/journey/journey
import { JourneyPublicController } from '../../../src/nest/journey/journey-public.controller';
import { JourneyController } from '../../../src/nest/journey/journey.controller';
import type { JourneyService } from '../../../src/nest/journey/journey.service';
import type { PublicMediaService } from '../../../src/nest/memories/public-media.service';
import type { StorageReleaseService } from '../../../src/nest/storage/storage-release.service';
import type { StorageService } from '../../../src/nest/storage/storage.service';
import type { User } from '../../../src/types';
@@ -33,6 +34,9 @@ const storageStub = {
exists: storageExists,
sendToResponse: storageSendToResponse,
} as unknown as StorageService;
// The public proxies send a location-free copy kept under public/<name>.
const renditionFor = vi.fn(async (_category: string, name: string): Promise<string | null> => `public/${name}`);
const publicMediaStub = { renditionFor } as unknown as PublicMediaService;
// The provider-photo adds, their event and their detached capture refresh are
// JourneyPhotoCaptureService's (#1587), so the routes only shape the batch and
// the answer; the spies pin that shape. Uploads get the backfill without the
@@ -1123,6 +1127,7 @@ describe('JourneyPublicController', () => {
new JourneyPublicController(
svc({ getPublicJourney: vi.fn().mockReturnValue(null) } as Partial<JourneyService>),
storageStub,
publicMediaStub,
).get('tok'),
),
).toEqual({ status: 404, body: { error: 'Not found' } });
@@ -1130,6 +1135,7 @@ describe('JourneyPublicController', () => {
await new JourneyPublicController(
svc({ getPublicJourney: vi.fn().mockReturnValue({ id: 1 }) } as Partial<JourneyService>),
storageStub,
publicMediaStub,
).get('tok'),
).toEqual({ id: 1 });
});
@@ -1140,15 +1146,18 @@ describe('JourneyPublicController', () => {
new JourneyPublicController(
svc({ getPublicMapLayers: vi.fn().mockResolvedValue(null) } as Partial<JourneyService>),
storageStub,
publicMediaStub,
).mapLayers('tok'),
),
).toEqual({ status: 404, body: { error: 'Not found' } });
const layers = { places: { status: 'withheld' } };
const getPublicMapLayers = vi.fn().mockResolvedValue(layers);
expect(
await new JourneyPublicController(svc({ getPublicMapLayers } as Partial<JourneyService>), storageStub).mapLayers(
'tok',
),
await new JourneyPublicController(
svc({ getPublicMapLayers } as Partial<JourneyService>),
storageStub,
publicMediaStub,
).mapLayers('tok'),
).toBe(layers);
expect(getPublicMapLayers).toHaveBeenCalledWith('tok');
});
@@ -1159,6 +1168,7 @@ describe('JourneyPublicController', () => {
new JourneyPublicController(
svc({ validateShareTokenForPhoto: vi.fn().mockReturnValue(null) } as Partial<JourneyService>),
storageStub,
publicMediaStub,
).photo('tok', 7, 'thumbnail', {} as Response),
),
).toEqual({ status: 404, body: { error: 'Not found' } });
@@ -1167,7 +1177,7 @@ describe('JourneyPublicController', () => {
validateShareTokenForPhoto: vi.fn().mockReturnValue({ ownerId: 2 }),
streamPhoto,
} as Partial<JourneyService>);
await new JourneyPublicController(s, storageStub).photo('tok', 7, 'original', {} as Response);
await new JourneyPublicController(s, storageStub, publicMediaStub).photo('tok', 7, 'original', {} as Response);
expect(streamPhoto).toHaveBeenCalledWith({}, 2, 7, 'original');
});
@@ -1177,6 +1187,7 @@ describe('JourneyPublicController', () => {
new JourneyPublicController(
svc({ validateShareTokenForAsset: vi.fn().mockReturnValue(null) } as Partial<JourneyService>),
storageStub,
publicMediaStub,
).legacyPhoto('tok', 'immich', 'a1', 'thumbnail', {} as Response),
),
).toEqual({ status: 404, body: { error: 'Not found' } });
@@ -1187,7 +1198,13 @@ describe('JourneyPublicController', () => {
validateShareTokenForAsset: vi.fn().mockReturnValue({ ownerId: 5 }),
streamProviderAsset,
} as Partial<JourneyService>);
await new JourneyPublicController(s, storageStub).legacyPhoto('tok', 'immich', 'a1', 'original', {} as Response);
await new JourneyPublicController(s, storageStub, publicMediaStub).legacyPhoto(
'tok',
'immich',
'a1',
'original',
{} as Response,
);
expect(streamProviderAsset).toHaveBeenCalledWith(
{},
'immich',
@@ -1202,7 +1219,7 @@ describe('JourneyPublicController', () => {
validateShareTokenForPhoto: vi.fn().mockReturnValue({ ownerId: 3 }),
streamPhoto,
} as Partial<JourneyService>);
await new JourneyPublicController(s, storageStub).photo('tok', 7, 'thumbnail', {} as Response);
await new JourneyPublicController(s, storageStub, publicMediaStub).photo('tok', 7, 'thumbnail', {} as Response);
expect(streamPhoto).toHaveBeenCalledWith({}, 3, 7, 'thumbnail');
});
@@ -1212,7 +1229,7 @@ describe('JourneyPublicController', () => {
validateShareTokenForAsset: vi.fn().mockReturnValue({ ownerId: 5 }),
streamProviderAsset,
} as Partial<JourneyService>);
await new JourneyPublicController(s, storageStub).legacyPhoto(
await new JourneyPublicController(s, storageStub, publicMediaStub).legacyPhoto(
'tok',
'synologyphotos',
'a1',
@@ -1233,7 +1250,13 @@ describe('JourneyPublicController', () => {
validateShareTokenForAsset: vi.fn().mockReturnValue({ ownerId: 0 }),
streamProviderAsset: vi.fn().mockRejectedValue(new Error('no synology')),
} as Partial<JourneyService>);
await new JourneyPublicController(failing, storageStub).legacyPhoto('tok', 'synologyphotos', 'a1', 'original', res);
await new JourneyPublicController(failing, storageStub, publicMediaStub).legacyPhoto(
'tok',
'synologyphotos',
'a1',
'original',
res,
);
expect(status).toHaveBeenCalledWith(404);
expect(json).toHaveBeenCalledWith({ error: 'Provider not supported' });
});
@@ -1250,7 +1273,13 @@ describe('JourneyPublicController', () => {
validateShareTokenForAsset: vi.fn().mockReturnValue({ ownerId: 5 }),
streamProviderAsset,
} as Partial<JourneyService>);
await new JourneyPublicController(s, storageStub).legacyPhoto('tok', 'photoprism', 'a1', 'original', res);
await new JourneyPublicController(s, storageStub, publicMediaStub).legacyPhoto(
'tok',
'photoprism',
'a1',
'original',
res,
);
expect(status).toHaveBeenCalledWith(404);
expect(json).toHaveBeenCalledWith({ error: 'Provider not supported' });
});
@@ -1264,7 +1293,13 @@ describe('JourneyPublicController', () => {
validateShareTokenForAsset: vi.fn().mockReturnValue({ ownerId: 3 }),
streamProviderAsset,
} as Partial<JourneyService>);
await new JourneyPublicController(s, storageStub).legacyPhoto('tok', 'immich', 'a1', 'original', {} as Response);
await new JourneyPublicController(s, storageStub, publicMediaStub).legacyPhoto(
'tok',
'immich',
'a1',
'original',
{} as Response,
);
expect(streamProviderAsset).toHaveBeenCalledWith(
{},
'immich',
@@ -1278,7 +1313,7 @@ describe('JourneyPublicController', () => {
const s = svc({ validateShareTokenForAsset: vi.fn().mockReturnValue({ ownerId: 5 }) } as Partial<JourneyService>);
expect(
await thrownAsync(() =>
new JourneyPublicController(s, storageStub).legacyPhoto(
new JourneyPublicController(s, storageStub, publicMediaStub).legacyPhoto(
'tok',
'local',
'gone.jpg',
@@ -1296,10 +1331,37 @@ describe('JourneyPublicController', () => {
const set = vi.fn();
const res = { set } as unknown as Response;
const s = svc({ validateShareTokenForAsset: vi.fn().mockReturnValue({ ownerId: 5 }) } as Partial<JourneyService>);
await new JourneyPublicController(s, storageStub).legacyPhoto('tok', 'local', 'photo.jpg', 'original', res);
await new JourneyPublicController(s, storageStub, publicMediaStub).legacyPhoto(
'tok',
'local',
'photo.jpg',
'original',
res,
);
expect(storageExists).toHaveBeenCalledWith('journey', 'photo.jpg');
expect(set).toHaveBeenCalledWith('Cache-Control', 'public, max-age=86400');
expect(storageSendToResponse).toHaveBeenCalledWith('journey', 'photo.jpg', res);
// The location-free copy goes out, never the stored original.
expect(renditionFor).toHaveBeenCalledWith('journey', 'photo.jpg');
expect(storageSendToResponse).toHaveBeenCalledWith('journey', 'public/photo.jpg', res);
});
it('legacy photo proxy: a local file that cannot be cleaned is a 404, not the original', async () => {
storageExists.mockResolvedValue(true);
renditionFor.mockResolvedValueOnce(null);
const res = { set: vi.fn() } as unknown as Response;
const s = svc({ validateShareTokenForAsset: vi.fn().mockReturnValue({ ownerId: 5 }) } as Partial<JourneyService>);
expect(
await thrownAsync(() =>
new JourneyPublicController(s, storageStub, publicMediaStub).legacyPhoto(
'tok',
'local',
'a.bmp',
'original',
res,
),
),
).toEqual({ status: 404, body: { error: 'Not found' } });
expect(storageSendToResponse).not.toHaveBeenCalled();
});
it('legacy photo proxy: local provider cannot escape uploads/journey via a traversal asset id', async () => {
@@ -1309,7 +1371,7 @@ describe('JourneyPublicController', () => {
const s = svc({ validateShareTokenForAsset: vi.fn().mockReturnValue({ ownerId: 5 }) } as Partial<JourneyService>);
// Express decodes %2F in a single path param to '/', so the handler sees this.
await new JourneyPublicController(s, storageStub).legacyPhoto(
await new JourneyPublicController(s, storageStub, publicMediaStub).legacyPhoto(
'tok',
'local',
'../../files/secret.pdf',
@@ -1321,7 +1383,7 @@ describe('JourneyPublicController', () => {
// key validation (storage-keys.ts) rejects anything that still carries a
// path — the asset can never address the sibling files/ category.
expect(storageExists).toHaveBeenCalledWith('journey', 'secret.pdf');
expect(storageSendToResponse).toHaveBeenCalledWith('journey', 'secret.pdf', res);
expect(storageSendToResponse).toHaveBeenCalledWith('journey', 'public/secret.pdf', res);
});
it('legacy photo proxy: a bare traversal asset id reads as a miss, not a crash', async () => {
@@ -1331,7 +1393,13 @@ describe('JourneyPublicController', () => {
const s = svc({ validateShareTokenForAsset: vi.fn().mockReturnValue({ ownerId: 5 }) } as Partial<JourneyService>);
expect(
await thrownAsync(() =>
new JourneyPublicController(s, storageStub).legacyPhoto('tok', 'local', '..', 'original', {} as Response),
new JourneyPublicController(s, storageStub, publicMediaStub).legacyPhoto(
'tok',
'local',
'..',
'original',
{} as Response,
),
),
).toEqual({ status: 404, body: { error: 'Not found' } });
expect(storageSendToResponse).not.toHaveBeenCalled();
@@ -10,6 +10,7 @@
import { Addons } from '../../../../src/db/entities/Addons.entity';
import type { RuntimeEnvService } from '../../../../src/nest/app-config/runtime-env.service';
import { JourneyThumbsJob } from '../../../../src/nest/memories/journey-thumbs.job';
import type { PublicMediaService } from '../../../../src/nest/memories/public-media.service';
import type { ThumbnailService } from '../../../../src/nest/memories/thumbnail.service';
import { CronRegistrarService } from '../../../../src/nest/scheduling/cron-registrar.service';
import { createSnapshotTestDb } from '../../../helpers/db-mock';
@@ -57,6 +58,8 @@ function makeThumbnails(): Pick<ThumbnailService, 'sweepOrphanThumbs'> {
};
}
const noRenditions = { sweepOrphans: async () => 0 } as unknown as PublicMediaService;
describe('JourneyThumbsJob boot sweep', () => {
it('JTHUMB-001: onApplicationBootstrap delegates the boot-time sweep through CronRegistrarService.runOnBoot, not a bare void this.sweep()', async () => {
const registered: Array<[string, () => void | Promise<void>]> = [];
@@ -71,6 +74,7 @@ describe('JourneyThumbsJob boot sweep', () => {
};
const job = new JourneyThumbsJob(
makeThumbnails() as ThumbnailService,
noRenditions,
registrar as unknown as CronRegistrarService,
);
job.onApplicationBootstrap();
@@ -84,7 +88,7 @@ describe('JourneyThumbsJob boot sweep', () => {
{ isTest: () => false } as RuntimeEnvService,
t.orm,
);
const job = new JourneyThumbsJob(makeThumbnails() as ThumbnailService, registrar);
const job = new JourneyThumbsJob(makeThumbnails() as ThumbnailService, noRenditions, registrar);
await registrar.runOnBoot('journey-thumbs-boot', () => job.sweep());
expect(logMock.logError).not.toHaveBeenCalled();
});
@@ -99,6 +103,7 @@ describe('JourneyThumbsJob boot sweep', () => {
return 0;
},
} as ThumbnailService,
noRenditions,
registrar,
);
await registrar.runOnBoot('journey-thumbs-boot', () => job.sweep());
@@ -0,0 +1,385 @@
/**
* media-redact: the location-free copies a share link gets (PublicMediaService).
*
* Every case builds its file byte by byte, so no real person's photo lives in
* the repo, and asserts the two halves of the contract: the location is gone
* for the readers that matter (exifr for EXIF/XMP, the raw ISO 6709 string for
* movies), and nothing else moved (same length, orientation and capture time
* kept, a PNG whose checksums still hold and still decodes).
*/
import { redactLocationInBuffer, redactLocationInFile } from '../../../../src/nest/memories/media-redact';
import { jpegWithExif } from '../../../helpers/exif-jpeg';
import exifr from 'exifr';
import { Jimp } from 'jimp';
import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
import zlib from 'node:zlib';
import { afterAll, beforeAll, describe, expect, it } from 'vitest';
const GPS = { lat: 49.274523, lng: -0.703421 };
const ISO6709 = '+48.8577+002.2950+035.000/';
let dir: string;
beforeAll(() => {
dir = fs.mkdtempSync(path.join(os.tmpdir(), 'media-redact-'));
});
afterAll(() => {
fs.rmSync(dir, { recursive: true, force: true });
});
function writeTemp(name: string, bytes: Buffer): string {
const file = path.join(dir, name);
fs.writeFileSync(file, bytes);
return file;
}
function phonePhoto(): Buffer {
return jpegWithExif({ DateTimeOriginal: '2026:05:30 15:52:19', gps: GPS, Orientation: 6 });
}
/** The TIFF block of the phone photo, as a PNG eXIf or a WebP EXIF chunk holds it. */
function phoneTiff(): Buffer {
const jpeg = phonePhoto();
const start = jpeg.indexOf(Buffer.from('Exif\0\0', 'latin1')) + 6;
return jpeg.subarray(start, 4 + jpeg.readUInt16BE(4));
}
/** A JPEG with an XMP APP1 after the Exif one, the way Lightroom and phones write both. */
function withXmp(jpeg: Buffer, xmp: string): Buffer {
const payload = Buffer.concat([Buffer.from('http://ns.adobe.com/xap/1.0/\0', 'latin1'), Buffer.from(xmp, 'latin1')]);
const marker = Buffer.alloc(4);
marker.writeUInt16BE(0xffe1, 0);
marker.writeUInt16BE(payload.length + 2, 2);
return Buffer.concat([jpeg.subarray(0, 2), marker, payload, jpeg.subarray(2)]);
}
const XMP = [
'<x:xmpmeta xmlns:x="adobe:ns:meta/"><rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#">',
'<rdf:Description rdf:about="" xmlns:exif="http://ns.adobe.com/exif/1.0/" xmlns:photoshop="http://ns.adobe.com/photoshop/1.0/"',
' exif:GPSLatitude="49,16.4714N" exif:GPSLongitude="0,42.2053W" photoshop:City="Bayeux">',
'<photoshop:Country>France</photoshop:Country><exif:GPSAltitude>12/1</exif:GPSAltitude>',
'</rdf:Description></rdf:RDF></x:xmpmeta>',
].join('');
function pngChunk(type: string, data: Buffer): Buffer {
const length = Buffer.alloc(4);
length.writeUInt32BE(data.length);
const body = Buffer.concat([Buffer.from(type, 'latin1'), data]);
const crc = Buffer.alloc(4);
crc.writeUInt32BE(zlib.crc32(body));
return Buffer.concat([length, body, crc]);
}
/** A 1x1 grey PNG with the phone photo's TIFF block as eXIf, an XMP iTXt and a compressed raw profile. */
function pngWithMetadata(): Buffer {
const jpeg = phonePhoto();
const tiffStart = jpeg.indexOf(Buffer.from('Exif\0\0', 'latin1')) + 6;
const tiff = jpeg.subarray(tiffStart, 4 + jpeg.readUInt16BE(4));
const ihdr = Buffer.alloc(13);
ihdr.writeUInt32BE(1, 0);
ihdr.writeUInt32BE(1, 4);
ihdr[8] = 8;
const xmp =
'<x:xmpmeta xmlns:x="adobe:ns:meta/"><rdf:RDF><rdf:Description exif:GPSLatitude="49,16N"/></rdf:RDF></x:xmpmeta>';
return Buffer.concat([
Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]),
pngChunk('IHDR', ihdr),
pngChunk('eXIf', Buffer.from(tiff)),
pngChunk('iTXt', Buffer.concat([Buffer.from('XML:com.adobe.xmp\0\0\0\0\0', 'latin1'), Buffer.from(xmp, 'latin1')])),
pngChunk('zTXt', Buffer.concat([Buffer.from('Raw profile type exif\0\0', 'latin1'), zlib.deflateSync('47 50 53')])),
pngChunk('IDAT', zlib.deflateSync(Buffer.from([0, 0]))),
pngChunk('IEND', Buffer.alloc(0)),
]);
}
function box(type: string, ...parts: Buffer[]): Buffer {
const body = Buffer.concat(parts);
const head = Buffer.alloc(8);
head.writeUInt32BE(body.length + 8);
head.write(type, 4, 'latin1');
return Buffer.concat([head, body]);
}
/** A QuickTime movie as an iPhone lays out its location: udta location atom and the mdta keys of moov/meta. */
function iphoneMovie(): Buffer {
const xyz = Buffer.alloc(4 + ISO6709.length);
xyz.writeUInt16BE(ISO6709.length, 0);
xyz.write(ISO6709, 4, 'latin1');
const key = (name: string) => {
const entry = Buffer.alloc(8 + name.length);
entry.writeUInt32BE(8 + name.length, 0);
entry.write('mdta', 4, 'latin1');
entry.write(name, 8, 'latin1');
return entry;
};
const keysHead = Buffer.alloc(8);
keysHead.writeUInt32BE(2, 4);
const item = (index: number, value: string) => {
const data = box('data', Buffer.from([0, 0, 0, 1, 0, 0, 0, 0]), Buffer.from(value, 'latin1'));
const head = Buffer.alloc(8);
head.writeUInt32BE(8 + data.length, 0);
head.writeUInt32BE(index, 4);
return Buffer.concat([head, data]);
};
const meta = box(
'meta',
box('hdlr', Buffer.alloc(8), Buffer.from('mdta', 'latin1'), Buffer.alloc(13)),
box('keys', keysHead, key('com.apple.quicktime.make'), key('com.apple.quicktime.location.ISO6709')),
box('ilst', item(1, 'Apple'), item(2, ISO6709)),
);
return Buffer.concat([
box('ftyp', Buffer.from('qt \0\0\0\0qt ', 'latin1')),
// The frames happen to hold the same text: mdat is never read, so it stays.
box('mdat', Buffer.from(`${ISO6709}frames`, 'latin1')),
box('moov', box('mvhd', Buffer.alloc(100)), box('udta', box('\u00a9xyz', xyz)), meta),
]);
}
/** The head of a box that claims far more bytes than follow, as a cut-off upload leaves one. */
const PARTIAL_BOX = Buffer.from([0, 0x10, 0, 0, 0x6d, 0x64, 0x61, 0x74, 1, 2, 3, 4]);
/** The phone photo with a Photoshop APP13 block holding the given IPTC-IIM record 2 datasets. */
function withIptc(datasets: Array<[number, string]>): Buffer {
const iim = Buffer.concat(
datasets.map(([dataset, value]) => {
const head = Buffer.from([0x1c, 2, dataset, 0, 0]);
head.writeUInt16BE(value.length, 3);
return Buffer.concat([head, Buffer.from(value, 'latin1')]);
}),
);
// 8BIM, resource id 0x0404, an empty Pascal name padded to two bytes, the size.
const resourceHead = Buffer.alloc(12);
resourceHead.write('8BIM', 0, 'latin1');
resourceHead.writeUInt16BE(0x0404, 4);
resourceHead.writeUInt32BE(iim.length, 8);
const payload = Buffer.concat([
Buffer.from('Photoshop 3.0\0', 'latin1'),
resourceHead,
iim,
Buffer.alloc(iim.length % 2),
]);
const marker = Buffer.alloc(4);
marker.writeUInt16BE(0xffed, 0);
marker.writeUInt16BE(payload.length + 2, 2);
const jpeg = phonePhoto();
return Buffer.concat([jpeg.subarray(0, 2), marker, payload, jpeg.subarray(2)]);
}
describe('redactLocationInBuffer', () => {
it('MREDACT-006: IPTC place datasets in a Photoshop APP13 block become spaces, the caption stays', () => {
const original = withIptc([
[90, 'Bayeux'],
[92, 'Rue Saint-Jean'],
[95, 'Normandie'],
[100, 'FRA'],
[101, 'France'],
[120, 'Tapestry museum'],
]);
const copy = Buffer.from(original);
expect(redactLocationInBuffer(copy)).toBe(true);
expect(copy.length).toBe(original.length);
const text = copy.toString('latin1');
for (const gone of ['Bayeux', 'Rue Saint-Jean', 'Normandie', 'FRA', 'France']) expect(text).not.toContain(gone);
expect(text).toContain('Tapestry museum');
});
it('MREDACT-007: an IPTC record that does not parse is refused', () => {
const broken = withIptc([[90, 'Bayeux']]);
// The dataset tag marker of the first (and only) dataset.
broken[broken.indexOf(Buffer.from([0x1c, 2, 90]))] = 0x1d;
expect(redactLocationInBuffer(broken)).toBe(false);
});
it('MREDACT-001: a phone JPEG loses its GPS block and keeps orientation, capture time and length', async () => {
const original = phonePhoto();
expect((await exifr.gps(original))?.latitude).toBeCloseTo(GPS.lat, 5);
const copy = Buffer.from(original);
expect(redactLocationInBuffer(copy)).toBe(true);
expect(copy.length).toBe(original.length);
expect(await exifr.gps(copy)).toBeUndefined();
expect(await exifr.orientation(copy)).toBe(6);
const tags = (await exifr.parse(copy, { reviveValues: false })) as { DateTimeOriginal?: string };
expect(tags.DateTimeOriginal).toBe('2026:05:30 15:52:19');
});
it('MREDACT-002: XMP place properties, as attributes and as elements, become spaces', async () => {
const copy = withXmp(phonePhoto(), XMP);
expect(redactLocationInBuffer(copy)).toBe(true);
const text = copy.toString('latin1');
for (const gone of ['GPSLatitude', 'GPSLongitude', 'GPSAltitude', 'Bayeux', 'France']) {
expect(text).not.toContain(gone);
}
// The packet still parses and the image data behind it is untouched.
const parsed = (await exifr.parse(copy, { xmp: true })) as Record<string, unknown>;
expect(parsed.City).toBeUndefined();
expect(parsed.Orientation).toBeDefined();
});
it('MREDACT-003: a PNG loses eXIf GPS, XMP and the raw profile, with valid checksums, and still decodes', async () => {
const copy = pngWithMetadata();
expect(redactLocationInBuffer(copy)).toBe(true);
expect(await exifr.gps(copy).catch(() => undefined)).toBeUndefined();
const text = copy.toString('latin1');
expect(text).not.toContain('GPSLatitude');
expect(text).not.toContain('Raw profile');
let pos = 8;
while (pos < copy.length) {
const length = copy.readUInt32BE(pos);
expect(zlib.crc32(copy.subarray(pos + 4, pos + 8 + length))).toBe(copy.readUInt32BE(pos + 8 + length));
pos += 12 + length;
}
const image = await Jimp.read(copy);
expect(image.bitmap.width).toBe(1);
});
it('MREDACT-005: a WebP EXIF chunk without the Exif prefix loses its GPS block too', async () => {
const tiff = Buffer.from(phoneTiff());
const chunk = Buffer.alloc(8);
chunk.write('EXIF', 0, 'latin1');
chunk.writeUInt32LE(tiff.length, 4);
const body = Buffer.concat([Buffer.from('WEBP', 'latin1'), chunk, tiff, Buffer.alloc(tiff.length % 2)]);
const riff = Buffer.alloc(8);
riff.write('RIFF', 0, 'latin1');
riff.writeUInt32LE(body.length, 4);
const webp = Buffer.concat([riff, body]);
expect(redactLocationInBuffer(webp)).toBe(true);
// The chunk's TIFF read on its own, the way exifr reads a TIFF file.
const cleaned = webp.subarray(20, 20 + tiff.length);
expect(await exifr.gps(cleaned).catch(() => undefined)).toBeUndefined();
expect(await exifr.orientation(cleaned)).toBe(6);
});
it('MREDACT-004: a format it does not know, or a broken XMP packet, is refused', () => {
expect(redactLocationInBuffer(Buffer.from(`BM${'x'.repeat(40)}`))).toBe(false);
const broken = withXmp(phonePhoto(), '<x:xmpmeta><rdf:RDF><rdf:Description exif:GPSLatitude="49');
expect(redactLocationInBuffer(broken)).toBe(false);
});
});
describe('redactLocationInFile', () => {
it('MREDACT-010: an iPhone movie loses its udta location atom and the ISO6709 key value, frames and other keys stay', async () => {
const original = iphoneMovie();
const file = writeTemp('clip.mov', original);
expect(await redactLocationInFile(file)).toBe(true);
const copy = fs.readFileSync(file);
const text = copy.toString('latin1');
expect(copy.length).toBe(original.length);
// One occurrence left: the one inside mdat.
expect(text.split(ISO6709).length - 1).toBe(1);
expect(text).not.toContain('\u00a9xyz');
expect(text).toContain('Apple');
});
it('MREDACT-014: XMP in a movie (udta XMP_ and the Adobe uuid box) loses its GPS properties', async () => {
const xmp = Buffer.from(XMP, 'latin1');
const movie = Buffer.concat([
box('ftyp', Buffer.from('mp42\0\0\0\0mp42', 'latin1')),
box('uuid', Buffer.from('be7acfcb97a942e89c71999491e3afac', 'hex'), xmp),
box('moov', box('mvhd', Buffer.alloc(100)), box('udta', box('XMP_', xmp))),
]);
const file = writeTemp('xmp.mp4', movie);
expect(await redactLocationInFile(file)).toBe(true);
const text = fs.readFileSync(file).toString('latin1');
expect(text).not.toContain('GPSLatitude');
expect(text).not.toContain('Bayeux');
expect(text.split('<rdf:RDF').length - 1).toBe(2);
});
it('MREDACT-015: a movie whose box sizes overrun their parent is refused', async () => {
const broken = Buffer.concat([
box('ftyp', Buffer.from('qt ', 'latin1')),
box('moov', box('udta', Buffer.alloc(4))),
]);
// udta claims more bytes than moov holds.
broken.writeUInt32BE(400, 20);
expect(await redactLocationInFile(writeTemp('broken.mov', broken))).toBe(false);
});
it('MREDACT-016: a movie whose top level cannot be walked is refused, never cleaned as an image', async () => {
const trailing = Buffer.concat([iphoneMovie(), PARTIAL_BOX]);
expect(await redactLocationInFile(writeTemp('trailing.mov', trailing))).toBe(false);
// An MP4 brand without any movie header.
const headless = Buffer.concat([
box('ftyp', Buffer.from('isom\0\0\0\0isommp42', 'latin1')),
box('mdat', Buffer.from(ISO6709, 'latin1')),
]);
expect(await redactLocationInFile(writeTemp('headless.mp4', headless))).toBe(false);
});
it('MREDACT-017: an old QuickTime file without ftyp is walked as a movie, the 3GPP loci box goes too', async () => {
const loci = Buffer.concat([Buffer.alloc(6), Buffer.from('Bayeux\0', 'latin1'), Buffer.alloc(12)]);
const movie = Buffer.concat([
box('wide'),
box('mdat', Buffer.from('frames', 'latin1')),
box('moov', box('mvhd', Buffer.alloc(100)), box('udta', box('loci', loci))),
]);
const file = writeTemp('old.mov', movie);
expect(await redactLocationInFile(file)).toBe(true);
const text = fs.readFileSync(file).toString('latin1');
expect(text).not.toContain('Bayeux');
expect(text).not.toContain('loci');
expect(text).toContain('frames');
});
it('MREDACT-018: a still HEIC is cleaned in memory, one whose boxes do not parse and hides a moov is refused', async () => {
const exif = Buffer.concat([Buffer.from('Exif\0\0', 'latin1'), Buffer.from(phoneTiff())]);
const heic = Buffer.concat([box('ftyp', Buffer.from('heic\0\0\0\0mif1heic', 'latin1')), box('mdat', exif)]);
const file = writeTemp('still.heic', heic);
expect(await redactLocationInFile(file)).toBe(true);
const cleaned = fs.readFileSync(file);
const tiffAt = cleaned.indexOf(Buffer.from('Exif\0\0', 'latin1')) + 6;
expect(await exifr.gps(cleaned.subarray(tiffAt)).catch(() => undefined)).toBeUndefined();
const disguised = Buffer.concat([
box('ftyp', Buffer.from('heic\0\0\0\0mif1heic', 'latin1')),
box('moov', box('udta', box('©xyz', Buffer.from(ISO6709, 'latin1')))),
PARTIAL_BOX,
]);
expect(await redactLocationInFile(writeTemp('disguised.heic', disguised))).toBe(false);
});
it('MREDACT-011: a JPEG file is cleaned in place and passes the exifr check', async () => {
const file = writeTemp('photo.jpg', phonePhoto());
expect(await redactLocationInFile(file)).toBe(true);
expect(await exifr.gps(fs.readFileSync(file))).toBeUndefined();
});
it('MREDACT-012: an unknown format fails closed, a bare signature with nothing to clean passes', async () => {
expect(await redactLocationInFile(writeTemp('a.bmp', Buffer.from(`BM${'x'.repeat(40)}`)))).toBe(false);
expect(
await redactLocationInFile(writeTemp('b.png', Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]))),
).toBe(true);
expect(await redactLocationInFile(writeTemp('c.webm', Buffer.from([0x1a, 0x45, 0xdf, 0xa3, 0, 0, 0, 0])))).toBe(
true,
);
});
it('MREDACT-013: a bare TIFF (DNG, scanner output) is walked from its first byte and cleaned', async () => {
const jpeg = phonePhoto();
const tiffStart = jpeg.indexOf(Buffer.from('Exif\0\0', 'latin1')) + 6;
const file = writeTemp('raw.tif', Buffer.from(jpeg.subarray(tiffStart, 4 + jpeg.readUInt16BE(4))));
expect((await exifr.gps(fs.readFileSync(file)))?.latitude).toBeCloseTo(GPS.lat, 5);
expect(await redactLocationInFile(file)).toBe(true);
expect(await exifr.gps(fs.readFileSync(file)).catch(() => undefined)).toBeUndefined();
});
});
@@ -0,0 +1,234 @@
/**
* PublicMediaService: the location-free copies every public byte path sends.
*
* Storage is a small stand-in over a temp folder, so the copy, the reuse, the
* rebuild after a change and the sweep all run on real files; the journey
* mount gate reads real journeys and photo rows.
*/
import { Journeys } from '../../../../src/db/entities/Journeys.entity';
import { TrekPhotos } from '../../../../src/db/entities/TrekPhotos.entity';
import { PublicMediaService } from '../../../../src/nest/memories/public-media.service';
import { StorageService } from '../../../../src/nest/storage/storage.service';
import { StorageNotFoundError } from '../../../../src/nest/storage/storage.types';
import { createSnapshotTestDb } from '../../../helpers/db-mock';
import { jpegWithExif } from '../../../helpers/exif-jpeg';
import { makeJourney } from '../../../helpers/factories/journeys';
import { insertRow } from '../../../helpers/factories/rows';
import { makeUser } from '../../../helpers/factories/users';
import { createTestModule, type TestModule } from '../../../helpers/test-module';
import { MikroORM } from '@mikro-orm/core';
import { MikroOrmModule } from '@mikro-orm/nestjs';
import exifr from 'exifr';
import { Jimp } from 'jimp';
import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
import { afterAll, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest';
const db = createSnapshotTestDb();
let t: TestModule;
let service: PublicMediaService;
let root: string;
const at = (category: string, name: string) => path.join(root, category, name);
async function existsOnDisk(category: string, name: string): Promise<boolean> {
return fs.existsSync(at(category, name));
}
/** The slice of StorageService the copies use, over plain files under `root`. */
const storage = {
stat: vi.fn(async (category: string, name: string) => {
const stat = await fs.promises.stat(at(category, name)).catch(() => null);
return stat ? { key: name, size: stat.size, mtimeMs: stat.mtimeMs } : null;
}),
exists: vi.fn(existsOnDisk),
withLocalFile: vi.fn(async (category: string, name: string, fn: (abs: string) => Promise<unknown>) =>
fn(at(category, name)),
),
spoolDirFor: vi.fn(() => path.join(root, '.spool')),
put: vi.fn(async (category: string, name: string, source: { tmpPath: string }) => {
fs.mkdirSync(path.dirname(at(category, name)), { recursive: true });
fs.renameSync(source.tmpPath, at(category, name));
}),
list: vi.fn(async function* (category: string, prefix: string) {
const dir = at(category, prefix);
for (const entry of fs.existsSync(dir) ? fs.readdirSync(dir) : [])
yield { key: prefix + entry, size: 0, mtimeMs: 0 };
}),
keepsOnDelete: vi.fn(() => false),
delete: vi.fn(async (category: string, name: string) => fs.rmSync(at(category, name), { force: true })),
};
function write(category: string, name: string, bytes: Buffer): void {
fs.mkdirSync(path.dirname(at(category, name)), { recursive: true });
fs.writeFileSync(at(category, name), bytes);
}
const phonePhoto = () => jpegWithExif({ gps: { lat: 49.274523, lng: -0.703421 }, Orientation: 6 });
beforeAll(async () => {
t = await createTestModule({
db,
imports: [MikroOrmModule.forFeature([Journeys, TrekPhotos])],
providers: [PublicMediaService, { provide: StorageService, useValue: storage }],
});
service = t.get(PublicMediaService);
});
beforeEach(() => {
root = fs.mkdtempSync(path.join(os.tmpdir(), 'public-media-'));
fs.mkdirSync(path.join(root, '.spool'));
vi.clearAllMocks();
});
afterAll(async () => {
await t.close();
db.close();
});
describe('renditionFor', () => {
it('PMEDIA-001: makes the copy without GPS once, reuses it, and remakes it after the source changes', async () => {
write('journey', 'a.jpg', phonePhoto());
expect(await service.renditionFor('journey', 'a.jpg')).toBe('public/a.jpg');
const copy = fs.readFileSync(at('journey', 'public/a.jpg'));
expect(await exifr.gps(copy)).toBeUndefined();
expect(await exifr.orientation(copy)).toBe(6);
// The original stays as it was.
expect((await exifr.gps(fs.readFileSync(at('journey', 'a.jpg'))))?.latitude).toBeCloseTo(49.274523, 5);
expect(await service.renditionFor('journey', 'a.jpg')).toBe('public/a.jpg');
expect(storage.put).toHaveBeenCalledTimes(1);
const later = new Date(Date.now() + 60_000);
fs.utimesSync(at('journey', 'a.jpg'), later, later);
expect(await service.renditionFor('journey', 'a.jpg')).toBe('public/a.jpg');
expect(storage.put).toHaveBeenCalledTimes(2);
});
it('PMEDIA-002: two requests at once share one copy', async () => {
write('covers', 'b.jpg', phonePhoto());
const both = await Promise.all([service.renditionFor('covers', 'b.jpg'), service.renditionFor('covers', 'b.jpg')]);
expect(both).toEqual(['public/b.jpg', 'public/b.jpg']);
expect(storage.put).toHaveBeenCalledTimes(1);
});
it('PMEDIA-003: refuses what it can neither clean nor re-encode, a copy by its own name, and a source that is gone', async () => {
write('photos', 'c.bmp', Buffer.from(`BM${'x'.repeat(40)}`));
expect(await service.renditionFor('photos', 'c.bmp')).toBeNull();
expect(fs.existsSync(at('photos', 'public/c.bmp'))).toBe(false);
// An old QuickTime file without a movie header TREK could walk: no copy, no re-encode.
const wide = Buffer.alloc(16);
wide.writeUInt32BE(16, 0);
wide.write('wide', 4, 'latin1');
write('journey', 'clip.mov', Buffer.concat([wide, Buffer.from('trailing', 'latin1')]));
expect(await service.renditionFor('journey', 'clip.mov')).toBeNull();
// Nothing is left in the spool either.
expect(fs.readdirSync(path.join(root, '.spool'))).toEqual([]);
expect(await service.renditionFor('photos', 'public/c.bmp')).toBeNull();
await expect(service.renditionFor('photos', 'gone.jpg')).rejects.toBeInstanceOf(StorageNotFoundError);
});
});
describe('renditionFor re-encode fallback', () => {
it('PMEDIA-004: an image whose metadata cannot be cleaned is re-encoded instead of refused', async () => {
const image = new Jimp({ width: 4, height: 2, color: 0x336699ff });
const bmp = await image.getBuffer('image/bmp');
write('avatars', 'old.bmp', bmp);
expect(await service.renditionFor('avatars', 'old.bmp')).toBe('public/old.bmp');
const copy = await Jimp.read(fs.readFileSync(at('avatars', 'public/old.bmp')));
expect(copy.bitmap.width).toBe(4);
expect(copy.bitmap.height).toBe(2);
});
it('PMEDIA-005: a JPEG with a broken XMP packet goes out re-encoded, without its GPS', async () => {
const broken = Buffer.from('<x:xmpmeta><rdf:RDF><rdf:Description exif:GPSLatitude="49', 'latin1');
const app1 = Buffer.alloc(4);
app1.writeUInt16BE(0xffe1, 0);
const payload = Buffer.concat([Buffer.from('http://ns.adobe.com/xap/1.0/\0', 'latin1'), broken]);
app1.writeUInt16BE(payload.length + 2, 2);
const plain = await new Jimp({ width: 3, height: 3, color: 0xffffffff }).getBuffer('image/jpeg');
const photo = Buffer.concat([plain.subarray(0, 2), app1, payload, plain.subarray(2)]);
write('covers', 'xmp.jpg', photo);
expect(await service.renditionFor('covers', 'xmp.jpg')).toBe('public/xmp.jpg');
const copy = fs.readFileSync(at('covers', 'public/xmp.jpg'));
expect(copy.toString('latin1')).not.toContain('GPSLatitude');
expect((await Jimp.read(copy)).bitmap.width).toBe(3);
});
});
describe('servesFromJourneyMount', () => {
it('PMEDIA-010: serves covers in either spelling and other objects, refuses entry media and thumbs', async () => {
const orm = t.get(MikroORM);
const { user } = await makeUser(orm);
await makeJourney(orm, user.id, { cover_image: 'journey/cover-one.jpg' });
await makeJourney(orm, user.id, { cover_image: '/uploads/journey/cover-two.jpg' });
await insertRow(orm, TrekPhotos, {
provider: 'local',
file_path: 'journey/entry-clip.mp4',
thumbnail_path: 'journey/entry-poster.jpg',
});
// An entry photo picked as the journey's cover is served as the cover.
await insertRow(orm, TrekPhotos, { provider: 'local', file_path: 'journey/cover-one.jpg' });
expect(await service.servesFromJourneyMount('cover-one.jpg')).toBe(true);
expect(await service.servesFromJourneyMount('cover-two.jpg')).toBe(true);
// Not a journey's media at all, for example a trip cover pointing here.
expect(await service.servesFromJourneyMount('trip-cover.jpg')).toBe(true);
expect(await service.servesFromJourneyMount('entry-clip.mp4')).toBe(false);
expect(await service.servesFromJourneyMount('entry-poster.jpg')).toBe(false);
expect(await service.servesFromJourneyMount('thumbs/0123456789abcdef.jpg')).toBe(false);
});
});
describe('sweepOrphans', () => {
it('PMEDIA-020: drops the copies whose source is gone and keeps the rest', async () => {
write('avatars', 'kept.jpg', phonePhoto());
write('avatars', 'public/kept.jpg', Buffer.from('copy'));
write('avatars', 'public/orphan.jpg', Buffer.from('copy'));
write('places', 'public/orphan.png', Buffer.from('copy'));
expect(await service.sweepOrphans()).toBe(2);
expect(fs.existsSync(at('avatars', 'public/kept.jpg'))).toBe(true);
expect(fs.existsSync(at('avatars', 'public/orphan.jpg'))).toBe(false);
expect(fs.existsSync(at('places', 'public/orphan.png'))).toBe(false);
});
it('PMEDIA-022: a large sweep checks its copies in bounded batches', async () => {
for (let i = 0; i < 70; i++) write('journey', `public/gone-${i}.jpg`, Buffer.from('copy'));
let running = 0;
let peak = 0;
storage.exists.mockImplementation(async () => {
running++;
peak = Math.max(peak, running);
await new Promise((resolve) => setImmediate(resolve));
running--;
return false;
});
try {
expect(await service.sweepOrphans()).toBe(70);
} finally {
storage.exists.mockImplementation(existsOnDisk);
}
expect(peak).toBeLessThanOrEqual(32);
expect(peak).toBeGreaterThan(1);
});
it('PMEDIA-021: a copy a demo instance keeps, or one whose delete fails, is not counted', async () => {
write('covers', 'public/demo.jpg', Buffer.from('copy'));
storage.keepsOnDelete.mockReturnValueOnce(true);
expect(await service.sweepOrphans()).toBe(0);
expect(fs.existsSync(at('covers', 'public/demo.jpg'))).toBe(true);
storage.delete.mockRejectedValueOnce(new Error('busy'));
expect(await service.sweepOrphans()).toBe(0);
});
});
@@ -18,6 +18,7 @@ import { PhotoProviderRegistry } from '../../../src/nest/memories/photo-provider
import { PhotoResolverService } from '../../../src/nest/memories/photo-resolver.service';
import { ImmichPhotoProvider } from '../../../src/nest/memories/providers/immich.provider';
import { SynologyPhotoProvider } from '../../../src/nest/memories/providers/synology.provider';
import type { PublicMediaService } from '../../../src/nest/memories/public-media.service';
import type { SynologyService } from '../../../src/nest/memories/synology.service';
import type { ThumbnailService } from '../../../src/nest/memories/thumbnail.service';
import type { TrekPhotoCacheService } from '../../../src/nest/memories/trek-photo-cache.service';
@@ -71,6 +72,8 @@ const cache = {
// Local bytes go through the storage facade (slice 3); the resolver only ever
// addresses the 'journey' category with the 'journey/' prefix stripped.
const storage = { exists: vi.fn(), sendToResponse: vi.fn(), stat: vi.fn(), withLocalFile: vi.fn() };
// The location-free copies have their own suite; here a switch for made / refused.
const publicMedia = { renditionFor: vi.fn() };
// Real adapters over the stubbed services, and a real registry: the cases below
// keep asserting on immich.streamImmichAsset/synology.streamSynologyAsset, so
@@ -111,6 +114,7 @@ beforeAll(async () => {
cache as unknown as TrekPhotoCacheService,
providers,
storage as unknown as import('../../../src/nest/storage/storage.service').StorageService,
publicMedia as unknown as PublicMediaService,
);
});
@@ -131,6 +135,7 @@ beforeEach(async () => {
cache.cacheKey.mockReturnValue('k');
storage.exists.mockResolvedValue(false);
storage.sendToResponse.mockResolvedValue(undefined);
publicMedia.renditionFor.mockImplementation(async (_category: string, name: string) => `public/${name}`);
});
afterAll(async () => {
@@ -138,6 +143,84 @@ afterAll(async () => {
testDb.close();
});
describe('streamPublicPhoto: what a share link gets', () => {
it('RESOLVE-030: a local original goes out as its location-free copy, never as stored', async () => {
const id = await insertPhoto({ provider: 'local', file_path: 'journey/x.jpg' });
storage.exists.mockResolvedValue(true);
const res = makeRes();
await svc.streamPublicPhoto(res as never, 1, id, 'original');
expect(publicMedia.renditionFor).toHaveBeenCalledWith('journey', 'x.jpg');
expect(storage.sendToResponse).toHaveBeenCalledWith('journey', 'public/x.jpg', res);
expect(storage.sendToResponse).not.toHaveBeenCalledWith('journey', 'x.jpg', res);
});
it('RESOLVE-031: a thumbnail TREK re-encoded goes out as is, an uploaded poster as its copy', async () => {
const thumbId = await insertPhoto({
provider: 'local',
file_path: 'journey/x.jpg',
thumbnail_path: 'journey/thumbs/h.jpg',
});
const posterId = await insertPhoto({
provider: 'local',
file_path: 'journey/clip.mp4',
thumbnail_path: 'journey/poster.jpg',
media_type: 'video',
});
storage.exists.mockResolvedValue(true);
const res = makeRes();
await svc.streamPublicPhoto(res as never, 1, thumbId, 'thumbnail');
await svc.streamPublicPhoto(res as never, 1, posterId, 'thumbnail');
expect(storage.sendToResponse).toHaveBeenCalledWith('journey', 'thumbs/h.jpg', res);
expect(storage.sendToResponse).toHaveBeenCalledWith('journey', 'public/poster.jpg', res);
expect(publicMedia.renditionFor).toHaveBeenCalledTimes(1);
});
it('RESOLVE-032: an original that cannot be cleaned is stood in for by the re-encoded thumbnail', async () => {
const id = await insertPhoto({
provider: 'local',
file_path: 'journey/x.heic',
thumbnail_path: 'journey/thumbs/h.jpg',
});
storage.exists.mockResolvedValue(true);
publicMedia.renditionFor.mockResolvedValue(null);
const res = makeRes();
await svc.streamPublicPhoto(res as never, 1, id, 'original');
expect(storage.sendToResponse).toHaveBeenCalledTimes(1);
expect(storage.sendToResponse).toHaveBeenCalledWith('journey', 'thumbs/h.jpg', res);
});
it('RESOLVE-033: with neither a clean copy nor a thumbnail the answer is a 404, not the stored file', async () => {
const id = await insertPhoto({ provider: 'local', file_path: 'journey/clip.mp4', media_type: 'video' });
storage.exists.mockResolvedValue(true);
publicMedia.renditionFor.mockRejectedValue(new Error('disk full'));
const res = makeRes();
await svc.streamPublicPhoto(res as never, 1, id, 'original');
expect(storage.sendToResponse).not.toHaveBeenCalled();
expect(res.status).toHaveBeenCalledWith(404);
expect(res.json).toHaveBeenCalledWith({ error: 'File not found' });
expect(res.set).not.toHaveBeenCalled();
});
it('RESOLVE-034: an owner still gets the stored original', async () => {
const id = await insertPhoto({ provider: 'local', file_path: 'journey/x.jpg' });
storage.exists.mockResolvedValue(true);
const res = makeRes();
await svc.streamPhoto(res as never, 1, id, 'original');
expect(publicMedia.renditionFor).not.toHaveBeenCalled();
expect(storage.sendToResponse).toHaveBeenCalledWith('journey', 'x.jpg', res);
});
});
describe('streamPhoto — dispatch', () => {
it('RESOLVE-001: 404s a photo id that does not exist', async () => {
const res = makeRes();
@@ -1,5 +1,6 @@
import { Photos } from '../../../src/db/entities/Photos.entity';
import { ShareTokens } from '../../../src/db/entities/ShareTokens.entity';
import type { PublicMediaService } from '../../../src/nest/memories/public-media.service';
import {
applyPlatformUploads,
applyPlatformSpa,
@@ -35,6 +36,10 @@ vi.mock('../../../src/db/database', () => ({ db: { prepare: h.dbPrepare } }));
// these unit tests only assert routing/auth/error mapping, so a two-method stub
// is the whole storage surface.
const storage = { exists: h.exists, sendToResponse: h.sendToResponse } as unknown as StorageService;
// What a share link gets: the location-free copy under public/<name>.
const renditionFor = vi.fn();
const servesFromJourneyMount = vi.fn();
const publicMedia = { renditionFor, servesFromJourneyMount } as unknown as PublicMediaService;
// Tagged sentinel for express.static — we only need to know it was registered on
// the right path, not run it.
@@ -151,9 +156,9 @@ describe('applyPlatformUploads', () => {
});
describe('GET /uploads/photos/:filename', () => {
function photoHandler() {
function photoHandler(media: PublicMediaService | null = publicMedia) {
const { app, calls } = fakeApp();
applyPlatformUploads(app, storage, uploadsOrm.orm);
applyPlatformUploads(app, storage, uploadsOrm.orm, media ?? undefined);
return calls.find((c) => c.method === 'get' && c.path === '/uploads/photos/:filename')!.handlers[0];
}
const next = vi.fn();
@@ -350,13 +355,14 @@ describe('applyPlatformUploads', () => {
expect(res.statusCode).toBe(401);
});
it('serves the file when the share token covers the photo trip (R1 valid-token case)', async () => {
it('serves the location-free copy when the share token covers the photo trip (R1 valid-token case)', async () => {
const { user } = createUser(uploadsTestDb);
const photoTrip = createTrip(uploadsTestDb, user.id);
await insertShareToken(photoTrip.id, user.id, 'share-valid');
h.exists.mockResolvedValue(true);
h.sendToResponse.mockResolvedValue(undefined);
h.verifyJwtAndLoadUser.mockReturnValue(null);
renditionFor.mockResolvedValue('public/photo-valid.jpg');
await insertPhoto(photoTrip.id, 'photo-valid.jpg');
const res = makeRes();
await photoHandler()(
@@ -364,7 +370,30 @@ describe('applyPlatformUploads', () => {
res,
next,
);
expect(h.sendToResponse).toHaveBeenCalledWith('photos', 'photo-valid.jpg', res);
expect(renditionFor).toHaveBeenCalledWith('photos', 'photo-valid.jpg');
expect(h.sendToResponse).toHaveBeenCalledWith('photos', 'public/photo-valid.jpg', res);
expect(h.sendToResponse).not.toHaveBeenCalledWith('photos', 'photo-valid.jpg', res);
});
it('a share token gets a 404, never the stored photo, when no clean copy can be made or none is wired', async () => {
const { user } = createUser(uploadsTestDb);
const photoTrip = createTrip(uploadsTestDb, user.id);
await insertShareToken(photoTrip.id, user.id, 'share-unclean');
h.exists.mockResolvedValue(true);
h.verifyJwtAndLoadUser.mockReturnValue(null);
await insertPhoto(photoTrip.id, 'photo-unclean.jpg');
const ask = { params: { filename: 'photo-unclean.jpg' }, headers: {}, query: { token: 'share-unclean' } };
renditionFor.mockResolvedValue(null);
const refused = makeRes();
await photoHandler()(ask, refused, next);
expect(refused.statusCode).toBe(404);
expect(refused.body).toBe('Not found');
const unwired = makeRes();
await photoHandler(null)(ask, unwired, next);
expect(unwired.statusCode).toBe(404);
expect(h.sendToResponse).not.toHaveBeenCalled();
});
it('404 when the object vanishes between the exists check and the send', async () => {
@@ -500,6 +529,79 @@ describe('storageStaticHandler', () => {
});
});
describe('storageStaticHandler with public serving', () => {
function run(serving: Parameters<typeof storageStaticHandler>[2]) {
const handler = storageStaticHandler(storage, 'journey', serving);
const res = makeRes();
const next = vi.fn();
const out = handler({ method: 'GET', path: '/a.jpg' } as never, res as never, next as never);
return { res, next, out };
}
it('sends the copy the serving names instead of the object', async () => {
h.sendToResponse.mockResolvedValue(undefined);
const { res, next, out } = run({ rendition: async (name) => 'public/' + name });
await out;
expect(h.sendToResponse).toHaveBeenCalledWith('journey', 'public/a.jpg', res);
expect(next).not.toHaveBeenCalled();
});
it('a name the gate refuses, or one without a clean copy, is a miss', async () => {
const refused = run({ allows: async () => false, rendition: async (name) => 'public/' + name });
await refused.out;
expect(refused.next).toHaveBeenCalledWith();
const unclean = run({ rendition: async () => null });
await unclean.out;
expect(unclean.next).toHaveBeenCalledWith();
expect(h.sendToResponse).not.toHaveBeenCalled();
});
it('a source that is gone is a miss too', async () => {
const { next, out } = run({
rendition: () => Promise.reject(new StorageNotFoundError('journey/a.jpg')),
});
await out;
expect(next).toHaveBeenCalledWith();
});
});
describe('applyPlatformUploads static mounts', () => {
function mount(path: string, media?: PublicMediaService) {
const { app, calls } = fakeApp();
applyPlatformUploads(app, storage, uploadsOrm.orm, media);
return calls.find((c) => c.method === 'use' && c.path === path)?.handlers[0] as Handler;
}
it('/uploads/journey serves an allowed object as its copy and refuses journey entry media', async () => {
h.sendToResponse.mockResolvedValue(undefined);
renditionFor.mockResolvedValue('public/cover.jpg');
servesFromJourneyMount.mockImplementation(async (name: string) => name === 'cover.jpg');
const handler = mount('/uploads/journey', publicMedia);
const res = makeRes();
await handler({ method: 'GET', path: '/cover.jpg' }, res, vi.fn());
expect(h.sendToResponse).toHaveBeenCalledWith('journey', 'public/cover.jpg', res);
const entryNext = vi.fn();
await handler({ method: 'GET', path: '/entry.jpg' }, makeRes(), entryNext);
expect(entryNext).toHaveBeenCalledWith();
expect(renditionFor).toHaveBeenCalledTimes(1);
});
it('without PublicMediaService every mount serves nothing rather than the raw bytes', async () => {
const mounts = ['/uploads/avatars', '/uploads/covers', '/uploads/journey', '/uploads/places'];
const nexts = await Promise.all(
mounts.map(async (path) => {
const next = vi.fn();
await mount(path)({ method: 'GET', path: '/a.jpg' }, makeRes(), next);
return next;
}),
);
for (const next of nexts) expect(next).toHaveBeenCalledWith();
expect(h.sendToResponse).not.toHaveBeenCalled();
});
});
describe('applyPlatformStatic', () => {
const original = process.env.NODE_ENV;
afterEach(() => {
@@ -0,0 +1,171 @@
import {
categoriesInUse,
publicBudgetItem,
publicCollabMessage,
publicDay,
publicDayNote,
publicPackingItem,
} from '../../../src/nest/share/share-public.helpers';
import { describe, it, expect } from 'vitest';
describe('share public rows', () => {
it('SHARE-PUB-001: a day keeps its number, date and title, never its notes', () => {
const row = {
id: 3,
trip_id: 9,
day_number: 2,
date: '2026-09-01',
title: 'Paris',
notes: 'private',
default_transport_mode: 'car',
};
expect(publicDay(row)).toEqual({ id: 3, day_number: 2, date: '2026-09-01', title: 'Paris' });
expect(publicDay({ id: 4, day_number: 3 } as Parameters<typeof publicDay>[0])).toEqual({
id: 4,
day_number: 3,
date: null,
title: null,
});
});
it('SHARE-PUB-002: a day note keeps what the page draws and sorts by', () => {
const row = {
id: 1,
day_id: 3,
trip_id: 9,
text: 'Meet',
time: '12:00',
icon: 'pin',
sort_order: 2,
created_at: 'x',
color: 'blue',
};
expect(publicDayNote(row)).toEqual({
id: 1,
day_id: 3,
text: 'Meet',
time: '12:00',
icon: 'pin',
color: 'blue',
sort_order: 2,
});
expect(publicDayNote({ id: 2, day_id: 3, text: 'Bare' } as Parameters<typeof publicDayNote>[0])).toEqual({
id: 2,
day_id: 3,
text: 'Bare',
time: null,
icon: null,
color: null,
sort_order: null,
});
});
it('SHARE-PUB-003: packing, budget and chat rows lose the owner, the note, the ticket and the author id', () => {
const packing = {
id: 1,
trip_id: 9,
name: 'Socks',
checked: 1,
category: null,
sort_order: 0,
created_at: 'x',
weight_grams: 50,
bag_id: 4,
quantity: 2,
updated_at: 'x',
is_private: 0,
owner_id: 7,
packed_quantity: 1,
};
expect(publicPackingItem(packing)).toEqual({
id: 1,
name: 'Socks',
category: null,
checked: 1,
quantity: 2,
sort_order: 0,
});
const budget = {
id: 2,
trip_id: 9,
category: 'food',
name: 'Dinner',
total_price: 40,
persons: 2,
days: null,
note: 'card 4242',
sort_order: 0,
created_at: 'x',
paid_by_user_id: 7,
expense_date: null,
reservation_id: 5,
currency: null,
exchange_rate: 1,
ticket_json: '{"seat":"1A"}',
place_id: null,
};
expect(publicBudgetItem(budget)).toEqual({
id: 2,
name: 'Dinner',
category: 'food',
total_price: 40,
currency: null,
exchange_rate: 1,
});
const message = {
id: 3,
trip_id: 9,
user_id: 7,
text: 'Hi',
reply_to: null,
created_at: '2026-01-01 10:00:00',
deleted: 0,
origin: null,
username: 'ada',
avatar: null,
};
expect(publicCollabMessage(message)).toEqual({
id: 3,
text: 'Hi',
created_at: '2026-01-01 10:00:00',
username: 'ada',
avatar: null,
});
expect(
publicCollabMessage({ id: 4, text: 'x', username: 'b' } as Parameters<typeof publicCollabMessage>[0]),
).toEqual({
id: 4,
text: 'x',
created_at: null,
username: 'b',
avatar: null,
});
});
it('SHARE-PUB-004: categories come from the shared places and stops, once each, ordered by id', () => {
const places = [
{ category_id: 5, category_name: 'Food', category_color: '#f00', category_icon: 'fork' },
{ category_id: 2, category_name: 'Museum', category_color: null, category_icon: null },
{ category_id: 5, category_name: 'Food', category_color: '#f00', category_icon: 'fork' },
{ category_id: null, category_name: null },
// A dangling id, the category row gone: nothing to draw.
{ category_id: 8, category_name: null },
];
const assignments = {
1: [
{ place: { category: { id: 9, name: 'Hotel', color: '#0f0', icon: 'bed' } } },
{ place: { category: null } },
{},
],
};
expect(categoriesInUse(places, assignments)).toEqual([
{ id: 2, name: 'Museum', color: null, icon: null },
{ id: 5, name: 'Food', color: '#f00', icon: 'fork' },
{ id: 9, name: 'Hotel', color: '#0f0', icon: 'bed' },
]);
expect(categoriesInUse([], {})).toEqual([]);
});
});
@@ -11,6 +11,10 @@ const snapshot = () => ({
2: [{ accommodation_id: null, place: { id: 10, image_url: 'a.jpg' } }],
},
dayNotes: { 1: [{ id: 1 }] },
days: [
{ id: 1, day_number: 1, title: 'Louvre and lunch' },
{ id: 2, day_number: 2, title: null },
],
places: [
{ id: 10, image_url: 'a.jpg' },
{ id: 20, image_url: 'b.jpg' },
@@ -28,6 +32,10 @@ describe('share view helpers (#1712)', () => {
const out = travelOnly(snapshot(), new Set([20]));
expect(out.assignments).toEqual({ 1: [{ accommodation_id: 5, place: { id: 20, image_url: 'b.jpg' } }] });
expect(out.dayNotes).toEqual({});
expect(out.days).toEqual([
{ id: 1, day_number: 1, title: null },
{ id: 2, day_number: 2, title: null },
]);
expect(out.places.map((p) => p.id)).toEqual([20]);
expect(out.reservations.map((r) => r.type)).toEqual(['flight', 'hotel', 'cable_car']);
});
@@ -42,6 +50,7 @@ describe('share view helpers (#1712)', () => {
.every((a) => a.place?.image_url === null),
).toBe(true);
expect(out.reservations).toBe(data.reservations);
expect(out.days).toBe(data.days);
expect(data.places[0].image_url).toBe('a.jpg');
});
});
+63 -1
View File
@@ -8,9 +8,11 @@
*/
import { db as testDb } from '../../../src/db/database';
import { BudgetItems } from '../../../src/db/entities/BudgetItems.entity';
import { Categories } from '../../../src/db/entities/Categories.entity';
import { CollabMessages } from '../../../src/db/entities/CollabMessages.entity';
import { DayAccommodations } from '../../../src/db/entities/DayAccommodations.entity';
import { DayAssignments } from '../../../src/db/entities/DayAssignments.entity';
import { Days } from '../../../src/db/entities/Days.entity';
import { PackingItems } from '../../../src/db/entities/PackingItems.entity';
import { Places } from '../../../src/db/entities/Places.entity';
import { ReservationDayPositions } from '../../../src/db/entities/ReservationDayPositions.entity';
@@ -462,7 +464,7 @@ describe('getSharedTripData', () => {
it('SHARE-SVC-019b: travel and stays only keeps transport, hotels and the stay stops (#1712)', async () => {
const { trip, token } = await seedSharedTrip({ share_travel_only: true });
const day = createDay(testDb, trip.id);
const day = createDay(testDb, trip.id, { title: 'Louvre and lunch' });
const museum = createPlace(testDb, trip.id, { name: 'Museum' });
const hotel = createPlace(testDb, trip.id, { name: 'Hotel' });
const stay = createDayAccommodation(testDb, trip.id, hotel.id, day.id, day.id);
@@ -479,6 +481,9 @@ describe('getSharedTripData', () => {
expect(data.dayNotes).toEqual({});
expect(data.places.map((p: any) => p.name)).toEqual(['Hotel']);
expect(data.reservations.map((r: any) => r.type).sort()).toEqual(['flight', 'hotel']);
// The server drops the title itself; the page falls back to "Day N".
expect(data.days).toEqual([{ id: day.id, day_number: day.day_number, date: null, title: null }]);
expect(JSON.stringify(data)).not.toContain('Louvre and lunch');
});
it('SHARE-SVC-019c: without photos drops every place image and refuses the photo route (#1712)', async () => {
@@ -914,6 +919,63 @@ describe('getSharedTripData redaction (#2320)', () => {
JSON.stringify({ airline: 'OS', legs: [{ from: 'VIE' }] }),
);
});
it('SHARE-SVC-047: days, day notes and the three lists travel as allow-lists; categories are the ones in use', async () => {
const { user, trip, token } = await seedSharedTrip();
const day = createDay(testDb, trip.id, { date: '2026-09-01', title: 'Paris' });
await updateRows(t, Days, { id: day.id }, { notes: 'Owner day plan' });
const used = await insertRow(t, Categories, { name: 'Museums', color: '#ff0000', icon: 'landmark' });
await insertRow(t, Categories, { name: 'Somebody else', user: user.id });
const place = createPlace(testDb, trip.id, { name: 'Louvre', category_id: used });
createDayAssignment(testDb, day.id, place.id);
createDayNote(testDb, day.id, trip.id, { text: 'Meet at noon', time: '12:00' });
await insertRow(t, BudgetItems, {
trip: trip.id,
name: 'Tickets',
category: 'activities',
total_price: 40,
note: 'Card ending 4242',
ticket_json: '{"seat":"12A"}',
paidByUser: user.id,
});
await insertRow(t, PackingItems, { trip: trip.id, name: 'Socks', owner: user.id, quantity: 3 });
await insertRow(t, CollabMessages, { trip: trip.id, user: user.id, text: 'Hello' });
const data = await svc.getSharedTripData(token);
if (!data) throw new Error('no shared payload');
expect(data.days).toEqual([{ id: day.id, day_number: day.day_number, date: '2026-09-01', title: 'Paris' }]);
expect(Object.keys(data.dayNotes[day.id][0]).sort()).toEqual([
'color',
'day_id',
'icon',
'id',
'sort_order',
'text',
'time',
]);
expect(data.dayNotes[day.id][0]).toEqual(expect.objectContaining({ text: 'Meet at noon', time: '12:00' }));
expect(data.categories).toEqual([{ id: used, name: 'Museums', color: '#ff0000', icon: 'landmark' }]);
expect(Object.keys(data.budget[0]).sort()).toEqual([
'category',
'currency',
'exchange_rate',
'id',
'name',
'total_price',
]);
expect(data.packing).toEqual([expect.objectContaining({ name: 'Socks', quantity: 3, checked: 0 })]);
expect(Object.keys(data.packing[0]).sort()).toEqual([
'category',
'checked',
'id',
'name',
'quantity',
'sort_order',
]);
expect(Object.keys(data.collab[0]).sort()).toEqual(['avatar', 'created_at', 'id', 'text', 'username']);
const body = JSON.stringify(data);
for (const secret of ['Owner day plan', '4242', '12A', 'Somebody else']) expect(body).not.toContain(secret);
});
});
// ── getSharedPlacePhotoKey ───────────────────────────────────────────────────
@@ -10,7 +10,7 @@ import { JOURNEY_CARD_LIMITS, journeyEntriesCardSchema, type JourneyEntryLook }
import { describe, expect, it } from 'vitest';
// JRNCARD-001 to JRNCARD-006
// JRNCARD-001 to JRNCARD-007
function look(over: Partial<JourneyEntryLook> = {}): JourneyEntryLook {
return {
@@ -28,7 +28,6 @@ function look(over: Partial<JourneyEntryLook> = {}): JourneyEntryLook {
photoId: 7,
video: false,
photoCount: 4,
visibility: 'public',
draft: false,
fromTripPlace: false,
dayIndex: 0,
@@ -56,6 +55,16 @@ describe('the journal entries card', () => {
expect(journeyEntriesCardSchema.parse(parsed).entries).toHaveLength(2);
});
it('JRNCARD-007: a card stored while entries carried a visibility still reads, without it', () => {
// The field said "private" while the share link showed the entry; it is gone,
// and a conversation saved before keeps its cards.
const before = { ...look(), visibility: 'private' };
const stored = card([before]);
const parsed = journeyEntriesCardSchema.parse(stored);
expect(parsed.entries[0]).not.toHaveProperty('visibility');
expect(storedTrekCardSchema.parse(stored)).not.toBeNull();
});
it('JRNCARD-002: holds one to eight entries, a pending entry without an id among them', () => {
expect(journeyEntriesCardSchema.safeParse(card([])).success).toBe(false);
const eight = Array.from({ length: JOURNEY_CARD_LIMITS.entries }, (_, i) => look({ entryId: i + 1 }));
@@ -1,5 +1,5 @@
import { idSchema } from '../../common/primitives.schema';
import { journeyEntryTypeSchema, journeyEntryVisibilitySchema } from '../../journey/journey.schema';
import { journeyEntryTypeSchema } from '../../journey/journey.schema';
import { cardClockSchema, cardCountSchema, cardDateSchema, cardLatSchema, cardLngSchema, cardText } from './card-parts';
import { z } from 'zod';
@@ -66,7 +66,6 @@ export const journeyEntryLookSchema = z.object({
/** That photo is the poster of a clip. */
video: z.boolean(),
photoCount: cardCountSchema,
visibility: journeyEntryVisibilitySchema,
draft: z.boolean(),
/** Made from a place of a trip: deleting it turns it back into a suggestion. */
fromTripPlace: z.boolean(),
-3
View File
@@ -119,9 +119,6 @@ const journey: TranslationStrings = {
'journey.editor.bodyPlaceholder': 'احكِ قصة هذا اليوم...',
'journey.editor.placePlaceholder': 'الموقع (اختياري)',
'journey.editor.tagsPlaceholder': 'وسوم: جوهرة خفية، أفضل وجبة، يستحق العودة...',
'journey.visibility.private': 'خاص',
'journey.visibility.shared': 'مشترك',
'journey.visibility.public': 'عام',
'journey.emptyState.title': 'قصتك تبدأ هنا',
'journey.emptyState.subtitle': 'سجّل وصولك إلى مكان أو اكتب أول تدوينة',
'journey.frontpage.subtitle': 'حوّل رحلاتك إلى قصص لا تُنسى',
-3
View File
@@ -57,9 +57,6 @@ const journey: TranslationStrings = {
'journey.editor.bodyPlaceholder': 'Bu günün hekayəsini danışın...',
'journey.editor.placePlaceholder': 'Məkan (istəyə bağlı)',
'journey.editor.tagsPlaceholder': 'Teqlər: gizli inci, ən yaxşı yemək, yenidən gəlməli...',
'journey.visibility.private': 'Şəxsi',
'journey.visibility.shared': 'Paylaşılan',
'journey.visibility.public': 'İctimai',
'journey.emptyState.title': 'Hekayəniz burada başlayır',
'journey.emptyState.subtitle': 'Bir məkanda qeydiyyatdan keçin və ya ilk gündəlik qeydinizi yazın',
-3
View File
@@ -51,9 +51,6 @@ const journey: TranslationStrings = {
'journey.editor.bodyPlaceholder': 'Conte a história deste dia...',
'journey.editor.placePlaceholder': 'Localização (opcional)',
'journey.editor.tagsPlaceholder': 'Tags: joia escondida, melhor refeição, preciso voltar...',
'journey.visibility.private': 'Privado',
'journey.visibility.shared': 'Compartilhado',
'journey.visibility.public': 'Público',
'journey.emptyState.title': 'Sua história começa aqui',
'journey.emptyState.subtitle': 'Faça check-in em um lugar ou escreva sua primeira entrada no diário',
'journey.frontpage.subtitle': 'Transforme suas viagens em histórias que você nunca vai esquecer',
-3
View File
@@ -51,9 +51,6 @@ const journey: TranslationStrings = {
'journey.editor.bodyPlaceholder': "Explica la història d'aquest dia...",
'journey.editor.placePlaceholder': 'Ubicació (opcional)',
'journey.editor.tagsPlaceholder': 'Etiquetes: joia amagada, millor menjar, cal tornar...',
'journey.visibility.private': 'Privat',
'journey.visibility.shared': 'Compartit',
'journey.visibility.public': 'Públic',
'journey.emptyState.title': 'La teva història comença aquí',
'journey.emptyState.subtitle': 'Registra una ubicació o escriu la teva primera entrada de diari',
'journey.frontpage.subtitle': 'Converteix els teus viatges en històries que mai no oblidaràs',
-3
View File
@@ -51,9 +51,6 @@ const journey: TranslationStrings = {
'journey.editor.bodyPlaceholder': 'Vyprávějte příběh tohoto dne...',
'journey.editor.placePlaceholder': 'Místo (volitelné)',
'journey.editor.tagsPlaceholder': 'Tagy: skrytý klenot, nejlepší jídlo, musím se vrátit...',
'journey.visibility.private': 'Soukromý',
'journey.visibility.shared': 'Sdílený',
'journey.visibility.public': 'Veřejný',
'journey.emptyState.title': 'Váš příběh začíná zde',
'journey.emptyState.subtitle': 'Odba‍vte se na místě nebo napište svůj první záznam do deníku',
'journey.frontpage.subtitle': 'Proměňte své cesty v příběhy, na které nikdy nezapomenete',
-3
View File
@@ -51,9 +51,6 @@ const journey: TranslationStrings = {
'journey.editor.bodyPlaceholder': 'Erzaehl die Geschichte dieses Tages...',
'journey.editor.placePlaceholder': 'Ort (optional)',
'journey.editor.tagsPlaceholder': 'Tags: Geheimtipp, bestes Essen, nochmal hin...',
'journey.visibility.private': 'Privat',
'journey.visibility.shared': 'Geteilt',
'journey.visibility.public': 'Oeffentlich',
'journey.emptyState.title': 'Deine Geschichte beginnt hier',
'journey.emptyState.subtitle': 'Checke an einem Ort ein oder schreibe deinen ersten Tagebucheintrag',
'journey.frontpage.subtitle': 'Verwandle deine Reisen in Geschichten, die du nie vergisst',
-3
View File
@@ -51,9 +51,6 @@ const journey: TranslationStrings = {
'journey.editor.bodyPlaceholder': 'Tell the story of this day...',
'journey.editor.placePlaceholder': 'Location (optional)',
'journey.editor.tagsPlaceholder': 'Tags: hidden gem, best meal, must revisit...',
'journey.visibility.private': 'Private',
'journey.visibility.shared': 'Shared',
'journey.visibility.public': 'Public',
'journey.emptyState.title': 'Your story starts here',
'journey.emptyState.subtitle': 'Check in at a place or write your first journal entry',
'journey.frontpage.subtitle': "Turn your trips into stories you'll never forget",
-3
View File
@@ -51,9 +51,6 @@ const journey: TranslationStrings = {
'journey.editor.bodyPlaceholder': 'Cuenta la historia de este día...',
'journey.editor.placePlaceholder': 'Ubicación (opcional)',
'journey.editor.tagsPlaceholder': 'Etiquetas: joya oculta, mejor comida, hay que volver...',
'journey.visibility.private': 'Privado',
'journey.visibility.shared': 'Compartido',
'journey.visibility.public': 'Público',
'journey.emptyState.title': 'Tu historia empieza aquí',
'journey.emptyState.subtitle': 'Registra una ubicación o escribe tu primera entrada de diario',
'journey.frontpage.subtitle': 'Convierte tus viajes en historias que nunca olvidarás',
-3
View File
@@ -51,9 +51,6 @@ const journey: TranslationStrings = {
'journey.editor.bodyPlaceholder': 'Jutusta selle päeva lugu...',
'journey.editor.placePlaceholder': 'Asukoht (valikuline)',
'journey.editor.tagsPlaceholder': 'Sildid: peidetud pärl, parim toit, tasub naasta...',
'journey.visibility.private': 'Privaatne',
'journey.visibility.shared': 'Jagatud',
'journey.visibility.public': 'Avalik',
'journey.emptyState.title': 'Sinu lugu algab siit',
'journey.emptyState.subtitle': 'Märgi kohalolek mõnes kohas või kirjuta esimene päevikusissekanne',
'journey.frontpage.subtitle': 'Muuda oma reisid lugudeks, mida sa ei unusta',
-3
View File
@@ -51,9 +51,6 @@ const journey: TranslationStrings = {
'journey.editor.bodyPlaceholder': "Racontez l'histoire de cette journée...",
'journey.editor.placePlaceholder': 'Lieu (facultatif)',
'journey.editor.tagsPlaceholder': 'Tags : pépite cachée, meilleur repas, à revisiter...',
'journey.visibility.private': 'Privé',
'journey.visibility.shared': 'Partagé',
'journey.visibility.public': 'Public', // same-as-en
'journey.emptyState.title': 'Votre histoire commence ici',
'journey.emptyState.subtitle': 'Faites un check-in ou écrivez votre première entrée de journal',
'journey.frontpage.subtitle': 'Transformez vos voyages en histoires inoubliables',
-3
View File
@@ -51,9 +51,6 @@ const journey: TranslationStrings = {
'journey.editor.bodyPlaceholder': 'Πείτε την ιστορία αυτής της ημέρας...',
'journey.editor.placePlaceholder': 'Τοποθεσία (προαιρετικό)',
'journey.editor.tagsPlaceholder': 'Ετικέτες: κρυμμένος θησαυρός, καλύτερο γεύμα, πρέπει να ξαναπάω...',
'journey.visibility.private': 'Ιδιωτικό',
'journey.visibility.shared': 'Κοινόχρηστο',
'journey.visibility.public': 'Δημόσιο',
'journey.emptyState.title': 'Η ιστορία σας ξεκινά εδώ',
'journey.emptyState.subtitle': 'Κάντε άφιξη σε ένα μέρος ή γράψτε την πρώτη σας καταχώρηση ημερολογίου',
'journey.frontpage.subtitle': 'Μετατρέψτε τα ταξίδια σας σε ιστορίες που δεν θα ξεχάσετε ποτέ',
-3
View File
@@ -51,9 +51,6 @@ const journey: TranslationStrings = {
'journey.editor.bodyPlaceholder': 'ספרו את הסיפור של היום הזה...',
'journey.editor.placePlaceholder': 'מיקום (לא חובה)',
'journey.editor.tagsPlaceholder': 'תגיות: פנינה נסתרת, הארוחה הכי טובה, חייבים לחזור...',
'journey.visibility.private': 'פרטי',
'journey.visibility.shared': 'משותף',
'journey.visibility.public': 'ציבורי',
'journey.emptyState.title': 'הסיפור שלכם מתחיל כאן',
'journey.emptyState.subtitle': 'עשו צ׳ק-אין במקום או כתבו את רשומת היומן הראשונה',
'journey.frontpage.subtitle': 'הפכו את הטיולים שלכם לסיפורים שלא תשכחו',
-3
View File
@@ -51,9 +51,6 @@ const journey: TranslationStrings = {
'journey.editor.bodyPlaceholder': 'Meséld el ennek a napnak a történetét...',
'journey.editor.placePlaceholder': 'Helyszín (opcionális)',
'journey.editor.tagsPlaceholder': 'Címkék: rejtett kincs, legjobb étel, újra meglátogatandó...',
'journey.visibility.private': 'Privát',
'journey.visibility.shared': 'Megosztott',
'journey.visibility.public': 'Nyilvános',
'journey.emptyState.title': 'Itt kezdődik a történeted',
'journey.emptyState.subtitle': 'Jelentkezz be egy helyszínen vagy írd meg az első naplóbejegyzésed',
'journey.frontpage.subtitle': 'Alakítsd utazásaidat történetekké, amelyeket soha nem felejtesz el',
-3
View File
@@ -51,9 +51,6 @@ const journey: TranslationStrings = {
'journey.editor.bodyPlaceholder': 'Ceritakan kisah hari ini...',
'journey.editor.placePlaceholder': 'Lokasi (opsional)',
'journey.editor.tagsPlaceholder': 'Tag: permata tersembunyi, makan terbaik, wajib dikunjungi lagi...',
'journey.visibility.private': 'Pribadi',
'journey.visibility.shared': 'Dibagikan',
'journey.visibility.public': 'Publik',
'journey.emptyState.title': 'Kisahmu dimulai di sini',
'journey.emptyState.subtitle': 'Check in di suatu tempat atau tulis entri jurnal pertamamu',
'journey.frontpage.subtitle': 'Ubah perjalananmu menjadi kisah yang tak terlupakan',
-3
View File
@@ -51,9 +51,6 @@ const journey: TranslationStrings = {
'journey.editor.bodyPlaceholder': 'Racconta la storia di questa giornata...',
'journey.editor.placePlaceholder': 'Luogo (facoltativo)',
'journey.editor.tagsPlaceholder': 'Tag: gioiello nascosto, miglior pasto, da rivisitare...',
'journey.visibility.private': 'Privato',
'journey.visibility.shared': 'Condiviso',
'journey.visibility.public': 'Pubblico',
'journey.emptyState.title': 'La tua storia inizia qui',
'journey.emptyState.subtitle': 'Fai un check-in o scrivi la tua prima voce di diario',
'journey.frontpage.subtitle': 'Trasforma i tuoi viaggi in storie indimenticabili',
-3
View File
@@ -51,9 +51,6 @@ const journey: TranslationStrings = {
'journey.editor.bodyPlaceholder': 'この日のストーリーを書いてみよう…',
'journey.editor.placePlaceholder': '場所(任意)',
'journey.editor.tagsPlaceholder': 'タグ:穴場、最高の食事、また行きたい…',
'journey.visibility.private': '非公開',
'journey.visibility.shared': '共有',
'journey.visibility.public': '公開',
'journey.emptyState.title': 'ここから物語が始まります',
'journey.emptyState.subtitle': '場所にチェックインするか、最初の日記を書いてみましょう',
'journey.frontpage.subtitle': '旅を、忘れられない物語に',
-3
View File
@@ -51,9 +51,6 @@ const journey: TranslationStrings = {
'journey.editor.bodyPlaceholder': '오늘의 이야기를 들려주세요...',
'journey.editor.placePlaceholder': '위치 (선택)',
'journey.editor.tagsPlaceholder': '태그: 숨겨진 명소, 최고의 식사, 다시 방문...',
'journey.visibility.private': '비공개',
'journey.visibility.shared': '공유됨',
'journey.visibility.public': '공개',
'journey.emptyState.title': '여기서 이야기가 시작됩니다',
'journey.emptyState.subtitle': '장소에 체크인하거나 첫 번째 일기 항목을 작성하세요',
'journey.frontpage.subtitle': '여행을 영원히 잊지 못할 이야기로 만드세요',
-3
View File
@@ -51,9 +51,6 @@ const journey: TranslationStrings = {
'journey.editor.bodyPlaceholder': 'Vertel het verhaal van deze dag...',
'journey.editor.placePlaceholder': 'Locatie (optioneel)',
'journey.editor.tagsPlaceholder': 'Tags: verborgen parel, beste maaltijd, moet terugkomen...',
'journey.visibility.private': 'Privé',
'journey.visibility.shared': 'Gedeeld',
'journey.visibility.public': 'Openbaar',
'journey.emptyState.title': 'Je verhaal begint hier',
'journey.emptyState.subtitle': 'Check in op een plek of schrijf je eerste dagboekvermelding',
'journey.frontpage.subtitle': 'Maak van je reizen verhalen die je nooit vergeet',
-3
View File
@@ -51,9 +51,6 @@ const journey: TranslationStrings = {
'journey.editor.bodyPlaceholder': 'Opowiedz historię tego dnia...',
'journey.editor.placePlaceholder': 'Lokalizacja (opcjonalnie)',
'journey.editor.tagsPlaceholder': 'Tagi: ukryty skarb, najlepszy posiłek, warto wrócić...',
'journey.visibility.private': 'Prywatny',
'journey.visibility.shared': 'Udostępniony',
'journey.visibility.public': 'Publiczny',
'journey.emptyState.title': 'Twoja historia zaczyna się tutaj',
'journey.emptyState.subtitle': 'Zamelduj się w miejscu lub napisz swój pierwszy wpis w dzienniku',
'journey.frontpage.subtitle': 'Zamień swoje podróże w historie, których nigdy nie zapomnisz',
-3
View File
@@ -51,9 +51,6 @@ const journey: TranslationStrings = {
'journey.editor.bodyPlaceholder': 'Расскажите историю этого дня...',
'journey.editor.placePlaceholder': 'Местоположение (необязательно)',
'journey.editor.tagsPlaceholder': 'Теги: скрытая жемчужина, лучшая еда, стоит вернуться...',
'journey.visibility.private': 'Приватный',
'journey.visibility.shared': 'Общий',
'journey.visibility.public': 'Публичный',
'journey.emptyState.title': 'Ваша история начинается здесь',
'journey.emptyState.subtitle': 'Отметьтесь в месте или напишите первую запись в дневник',
'journey.frontpage.subtitle': 'Превращайте поездки в истории, которые вы никогда не забудете',
-3
View File
@@ -51,9 +51,6 @@ const journey: TranslationStrings = {
'journey.editor.bodyPlaceholder': 'Vyrozprávajte príbeh tohto dňa...',
'journey.editor.placePlaceholder': 'Miesto (voliteľné)',
'journey.editor.tagsPlaceholder': 'Značky: skrytý klenot, najlepšie jedlo, musím sa vrátiť...',
'journey.visibility.private': 'Súkromný',
'journey.visibility.shared': 'Zdieľaný',
'journey.visibility.public': 'Verejný',
'journey.emptyState.title': 'Váš príbeh sa začína tu',
'journey.emptyState.subtitle': 'Odbavte sa na mieste alebo napíšte svoj prvý záznam do denníka',
'journey.frontpage.subtitle': 'Premeňte svoje cesty na príbehy, na ktoré nikdy nezabudnete',
-3
View File
@@ -51,9 +51,6 @@ const journey: TranslationStrings = {
'journey.editor.bodyPlaceholder': 'Berätta om den här dagen...',
'journey.editor.placePlaceholder': 'Plats (valfritt)',
'journey.editor.tagsPlaceholder': 'Taggar: en dold pärla, den bästa måltiden, måste återvända...',
'journey.visibility.private': 'Privat',
'journey.visibility.shared': 'Delad',
'journey.visibility.public': 'Offentlig',
'journey.emptyState.title': 'Din berättelse börjar här',
'journey.emptyState.subtitle': 'Checka in på en plats eller skriv ditt första dagboksinlägg',
'journey.frontpage.subtitle': 'Förvandla dina resor till minnen du aldrig kommer att glömma',
-3
View File
@@ -51,9 +51,6 @@ const journey: TranslationStrings = {
'journey.editor.bodyPlaceholder': 'เล่าเรื่องวันนี้...',
'journey.editor.placePlaceholder': 'สถานที่ตั้ง (ไม่บังคับ)',
'journey.editor.tagsPlaceholder': 'แท็ก: อัญมณีที่ซ่อนอยู่, มื้ออาหารที่ดีที่สุด, ต้องกลับมาอีกครั้ง...',
'journey.visibility.private': 'ส่วนตัว',
'journey.visibility.shared': 'แบ่งปันแล้ว',
'journey.visibility.public': 'สาธารณะ',
'journey.emptyState.title': 'เรื่องราวของคุณเริ่มต้นที่นี่',
'journey.emptyState.subtitle': 'เช็คอินที่สถานที่หรือเขียนบันทึกประจำวันแรกของคุณ',
'journey.frontpage.subtitle': 'เปลี่ยนการเดินทางของคุณให้เป็นเรื่องราวที่คุณจะไม่มีวันลืม',
-3
View File
@@ -51,9 +51,6 @@ const journey: TranslationStrings = {
'journey.editor.bodyPlaceholder': 'Bu günün hikâyesini anlatın...',
'journey.editor.placePlaceholder': 'Konum (isteğe bağlı)',
'journey.editor.tagsPlaceholder': 'Etiketler: gizli cevher, en iyi yemek, tekrar ziyaret...',
'journey.visibility.private': 'Gizli',
'journey.visibility.shared': 'Paylaşılan',
'journey.visibility.public': 'Herkese açık',
'journey.emptyState.title': 'Hikâyeniz burada başlıyor',
'journey.emptyState.subtitle': 'Bir yerde check-in yapın veya ilk günlük kaydınızı yazın',
'journey.frontpage.subtitle': 'Gezilerini asla unutmayacağın hikayelere dönüştür',
-3
View File
@@ -51,9 +51,6 @@ const journey: TranslationStrings = {
'journey.editor.bodyPlaceholder': 'Розкажіть історію цього дня...',
'journey.editor.placePlaceholder': 'Місце розташування (необов’язково)',
'journey.editor.tagsPlaceholder': 'Теги: прихована перлина, найкраща їжа, варто повернутися...',
'journey.visibility.private': 'Приватний',
'journey.visibility.shared': 'Спільний',
'journey.visibility.public': 'Публічний',
'journey.emptyState.title': 'Ваша історія починається тут',
'journey.emptyState.subtitle': 'Позначтесь у місці або напишіть перший запис у щоденник',
'journey.frontpage.subtitle': 'Перетворюйте поїздки на історії, які ви ніколи не забудете',
-3
View File
@@ -51,9 +51,6 @@ const journey: TranslationStrings = {
'journey.editor.bodyPlaceholder': 'Kể lại câu chuyện ngày hôm nay...',
'journey.editor.placePlaceholder': 'Vị trí (tùy chọn)',
'journey.editor.tagsPlaceholder': 'Tags: viên ngọc ẩn, bữa ăn ngon nhất, phải xem lại...',
'journey.visibility.private': 'Riêng tư',
'journey.visibility.shared': 'Đã chia sẻ',
'journey.visibility.public': 'Công cộng',
'journey.emptyState.title': 'Câu chuyện của bạn bắt đầu từ đây',
'journey.emptyState.subtitle': 'Nhận phòng tại một địa điểm hoặc viết mục nhật ký đầu tiên của bạn',
'journey.frontpage.subtitle': 'Biến chuyến đi của bạn thành những câu chuyện bạn sẽ không bao giờ quên',
-3
View File
@@ -51,9 +51,6 @@ const journey: TranslationStrings = {
'journey.editor.bodyPlaceholder': '講述這一天的故事...',
'journey.editor.placePlaceholder': '地點(可選)',
'journey.editor.tagsPlaceholder': '標籤:隱藏寶藏、最佳美食、值得再訪...',
'journey.visibility.private': '私密',
'journey.visibility.shared': '共享',
'journey.visibility.public': '公開',
'journey.emptyState.title': '你的故事從這裡開始',
'journey.emptyState.subtitle': '在某個地方打卡或寫下你的第一篇日誌',
'journey.frontpage.subtitle': '將旅行變成永遠不會忘記的故事',
-3
View File
@@ -51,9 +51,6 @@ const journey: TranslationStrings = {
'journey.editor.bodyPlaceholder': '讲述这一天的故事...',
'journey.editor.placePlaceholder': '地点(可选)',
'journey.editor.tagsPlaceholder': '标签:隐藏宝藏、最佳美食、值得再去...',
'journey.visibility.private': '私密',
'journey.visibility.shared': '共享',
'journey.visibility.public': '公开',
'journey.emptyState.title': '你的故事从这里开始',
'journey.emptyState.subtitle': '在某个地方签到或写下你的第一篇日志',
'journey.frontpage.subtitle': '将旅行变成永远不会忘记的故事',
+1
View File
@@ -132,6 +132,7 @@ export * from './journey/journey-recordings.schema';
export * from './journey/journey-day-import.schema';
export * from './journey/journey-recording-prep.schema';
export * from './journey/journey-map.schema';
export * from './journey/journey-public.schema';
export * from './journey/trip-journal-link.schema';
export * from './book/book.schema';
export * from './book/book-fonts';
@@ -0,0 +1,86 @@
import { journeyPublicResponseSchema } from './journey-public.schema';
import { describe, expect, it } from 'vitest';
const photo = {
id: 3,
photo_id: 30,
caption: 'The tower',
media_type: 'image',
width: 800,
height: 600,
duration_ms: null,
taken_at: '2026-05-14T10:00:00Z',
lat: null,
lng: null,
posterless: false,
};
const answer = {
journey: {
title: 'Venice',
subtitle: null,
cover_image: 'covers/venice.jpg',
status: 'completed',
show_verdict: 1,
show_mood: 1,
show_weather: 0,
},
entries: [
{
id: 7,
type: 'entry',
entry_date: '2026-05-14',
entry_time: '10:00',
sort_order: 0,
title: 'Piazza San Marco',
story: 'Pigeons everywhere.',
location_name: 'Venice',
location_lat: null,
location_lng: null,
country_code: 'IT',
mood: 'good',
weather: 'sunny',
tags: ['square'],
pros_cons: { pros: ['light'], cons: [] },
photos: [photo],
},
// A map-only share: the marker fields alone.
{
id: 8,
type: 'entry',
entry_date: '2026-05-15',
sort_order: 0,
title: null,
location_name: 'Murano',
location_lat: 45.458,
location_lng: 12.353,
},
],
gallery: [photo],
stats: { entries: 2, photos: 1, places: 2 },
cartoApiKey: '',
permissions: { share_timeline: true, share_gallery: true, share_map: false, newest_first: false },
};
describe('journeyPublicResponseSchema', () => {
it('JRNPUB-SCHEMA-001: reads a shared journey with a timeline entry and a map-only one', () => {
expect(journeyPublicResponseSchema.safeParse(answer).success).toBe(true);
// A clip may carry its provider for clients from before `posterless`.
const clip = { ...photo, media_type: 'video', provider: 'local' };
expect(journeyPublicResponseSchema.safeParse({ ...answer, gallery: [clip] }).success).toBe(true);
});
it('JRNPUB-SCHEMA-002: refuses a storage key, an asset id or an author anywhere in the answer', () => {
const leaks = [
{ ...answer, gallery: [{ ...photo, file_path: 'journey/abc.jpg' }] },
{ ...answer, gallery: [{ ...photo, thumbnail_path: 'journey/abc_thumb.jpg' }] },
{ ...answer, gallery: [{ ...photo, asset_id: 'immich-1', provider: 'immich' }] },
{ ...answer, entries: [{ ...answer.entries[0], author_id: 1 }] },
{ ...answer, entries: [{ ...answer.entries[0], visibility: 'private' }] },
{ ...answer, entries: [{ ...answer.entries[0], photos: [{ ...photo, owner_id: 1 }] }] },
{ ...answer, journey: { ...answer.journey, user_id: 1 } },
];
for (const leak of leaks) expect(journeyPublicResponseSchema.safeParse(leak).success).toBe(false);
});
});
@@ -0,0 +1,92 @@
import { idSchema } from '../common/primitives.schema';
import { z } from 'zod';
/**
* What GET /api/public/journey/:token answers: a journey as a reader without an
* account sees it.
*
* Unlike the other response schemas, every object here is strict on purpose. The payload used to spread whole
* rows, so storage keys (`journey/<uuid>.jpg`), provider asset ids, the author
* and columns nothing on the page reads all went out with it. A key that is not
* named below now fails the route's response contract in every test that
* reaches it, rather than quietly reaching the public.
*/
/**
* A photo on the public page, inline in an entry or in the gallery. Bytes are
* fetched by `photo_id` through the share token, so no path or asset id is
* needed. The capture coordinates are null unless the owner shared the map.
*/
export const journeyPublicPhotoSchema = z.strictObject({
/** The gallery row: the page's key for the photo. */
id: idSchema,
/** The TREK photo, what /api/public/journey/:token/photos/:photoId/:kind serves. */
photo_id: idSchema,
caption: z.string().nullable(),
media_type: z.string().nullable(),
width: z.number().nullable(),
height: z.number().nullable(),
duration_ms: z.number().nullable(),
taken_at: z.string().nullable(),
lat: z.number().nullable(),
lng: z.number().nullable(),
/** A clip without a poster frame: its thumbnail route 404s, so the page draws a plain tile (#2341). */
posterless: z.boolean(),
/**
* Clips only, deprecated: 'local' or the provider's name. App builds and
* cached pages from before `posterless` read it to decide on the poster; it
* names no file. Drop it once those have aged out.
*/
provider: z.string().nullable().optional(),
});
export type JourneyPublicPhoto = z.infer<typeof journeyPublicPhotoSchema>;
/**
* An entry on the public page. A map-only share carries just what plots a
* marker, so the narrative fields are optional; the coordinates are null
* unless the map is shared.
*/
export const journeyPublicEntrySchema = z.strictObject({
id: idSchema,
type: z.string(),
entry_date: z.string(),
entry_time: z.string().nullable().optional(),
sort_order: z.number().nullable(),
title: z.string().nullable(),
story: z.string().nullable().optional(),
location_name: z.string().nullable(),
location_lat: z.number().nullable(),
location_lng: z.number().nullable(),
country_code: z.string().nullable().optional(),
mood: z.string().nullable().optional(),
weather: z.string().nullable().optional(),
tags: z.array(z.string()).optional(),
pros_cons: z.record(z.string(), z.unknown()).nullable().optional(),
photos: z.array(journeyPublicPhotoSchema).optional(),
});
export type JourneyPublicEntry = z.infer<typeof journeyPublicEntrySchema>;
export const journeyPublicResponseSchema = z.strictObject({
journey: z.strictObject({
title: z.string(),
subtitle: z.string().nullable(),
/** The cover's upload name, rendered through /uploads. */
cover_image: z.string().nullable(),
status: z.string().nullable(),
show_verdict: z.number(),
show_mood: z.number(),
show_weather: z.number(),
}),
entries: z.array(journeyPublicEntrySchema),
gallery: z.array(journeyPublicPhotoSchema),
stats: z.strictObject({ entries: z.number(), photos: z.number(), places: z.number() }),
cartoApiKey: z.string(),
permissions: z.strictObject({
share_timeline: z.boolean(),
share_gallery: z.boolean(),
share_map: z.boolean(),
newest_first: z.boolean(),
}),
});
export type JourneyPublicResponse = z.infer<typeof journeyPublicResponseSchema>;
+16 -11
View File
@@ -233,18 +233,27 @@ export const journalPluginPhotoInputSchema = z.strictObject({
export type JournalPluginPhotoInput = z.infer<typeof journalPluginPhotoInputSchema>;
/*
* The three entry fields with a fixed set of values. `journey_entries.type` and
* `.visibility` are plain TEXT columns and the REST route forwards whatever the
* client sent, but the row type (JourneyEntry on the server) only ever models
* these, so the MCP tools and the assistant's cards name them rather than take
* a free string: a model that invents "friends-only" would write a value
* nothing reads.
* The entry types. `journey_entries.type` is a plain TEXT column and the REST
* route forwards whatever the client sent, but the row type (JourneyEntry on
* the server) only ever models these, so the MCP tools and the assistant's
* cards name them rather than take a free string: a model that invents "note"
* would write a value nothing reads.
*
* `journey_entries.visibility` is deprecated: nothing reads it, so a "private"
* entry still showed on the share link. The tools keep accepting and storing
* it, as REST does, so a client or a held assistant change that still sends it
* is not refused, but nothing offers it any more. What keeps an entry off the
* link is `is_draft`.
*/
export const journeyEntryTypeSchema = z.enum(['entry', 'checkin', 'skeleton']);
export type JourneyEntryType = z.infer<typeof journeyEntryTypeSchema>;
export const journeyEntryVisibilitySchema = z.enum(['private', 'shared', 'public']);
export type JourneyEntryVisibility = z.infer<typeof journeyEntryVisibilitySchema>;
/** The tool-side description of the deprecated field, one wording for every tool. */
export const JOURNEY_ENTRY_VISIBILITY_DEPRECATED =
'Deprecated, has no effect: stored with the entry but read by nothing, and every entry that is not a draft shows on the share link. Use is_draft instead';
/**
* The verdict on a place. Either side defaults to empty so a caller can send
* only the half it has, which is what the entry editor does when a place was
@@ -293,11 +302,7 @@ export const journeyEntryUpdateToolSchema = z.strictObject({
weather: z.string().max(100).nullable().optional(),
tags: z.array(z.string()).nullable().optional(),
pros_cons: journeyEntryProsConsSchema.nullable().optional().describe('Replaces the whole verdict; null clears it'),
visibility: journeyEntryVisibilitySchema
.optional()
.describe(
'Stored with the entry. It does not decide the share link: every entry that is not a draft shows there. Use is_draft to keep an entry to the contributors',
),
visibility: journeyEntryVisibilitySchema.optional().describe(JOURNEY_ENTRY_VISIBILITY_DEPRECATED),
type: journeyEntryTypeSchema
.optional()
.describe('Promote a trip-derived "skeleton" to a real "entry" once it has been written up'),
+1 -1
View File
@@ -205,7 +205,7 @@ Requires `journey:read` or `journey:write` scope.
| `list_journey_entries` | List the entries of a journey in reading order (date, text, mood, linked trip), with the journey's id and title. `from` and `to` (`YYYY-MM-DD`, both included) keep only the entries of those days. |
| `get_journey_entry` | One journal entry by its id, as `list_journey_entries` answers it (photos included), with the id and title of its journey. |
| `create_journey_entry` | Add an entry with date (required), optional title, story text, time of day, location name, mood, and sort order. `is_draft: true` creates it as a draft that the journey share link leaves out. |
| `update_journey_entry` | Edit a journey entry's title, story, date, time of day, place, coordinates, weather, tags, mood, pros/cons list or visibility. `stats_excluded: true` keeps the entry but takes it off the route and out of `get_journey_stats`; `dismissed: true` waves a trip-derived suggestion away without deleting it, so the trip sync does not offer it again. `is_draft` turns the entry into a draft or publishes it; `visibility` is stored with the entry but keeps nothing off the share link, only a draft stays off it. Answers with what the changed fields held before under `previous`. |
| `update_journey_entry` | Edit a journey entry's title, story, date, time of day, place, coordinates, weather, tags, mood or pros/cons list. `stats_excluded: true` keeps the entry but takes it off the route and out of `get_journey_stats`; `dismissed: true` waves a trip-derived suggestion away without deleting it, so the trip sync does not offer it again. `is_draft` turns the entry into a draft or publishes it; a draft is the only entry the share link leaves out. `visibility` is deprecated: still accepted and stored, but it keeps nothing off the share link. Answers with what the changed fields held before under `previous`. |
| `delete_journey_entry` | Remove an entry from a journey. |
| `reorder_journey_entries` | Reorder entries by providing the new ordered list of entry IDs. Answers with the ids in their order before under `previous_order`. |
| `reorder_journey_entry_photos` | Put the photos of one entry in a new order by passing every photo id of the entry once. The first photo is the entry's cover. |