Compare commits

...

11 Commits

Author SHA1 Message Date
Maurice fa99940945 test(platform): a share-token photo whose copy fails to build is a 404 2026-11-20 19:15:48 +01:00
Maurice 09316025c3 test(share): sweep tests in the thumbnail job, tx and strict baselines follow the resolver split 2026-11-20 18:33:42 +01:00
Maurice 100313cfa9 fix(share): compare the pending rendition build with undefined 2026-11-20 18:23:20 +01:00
Maurice 411ec4af59 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.
2026-11-20 18:18:50 +01:00
Maurice ec7f5e0585 test(atlas): cache the test places' regions in one go rather than an awaited loop 2026-11-19 22:11:29 +01:00
Maurice 8e38749bc3 fix(transit): show every stop name and each ride's arrival in the folded-out itinerary
The same gap as on the phone (#3139) in the desktop day plan's folded-out
transit row and the assistant's transit card: each ride cut its stop names
to one line and showed only its departure, and a walk cut its target. The
names and the walk target now wrap, and each ride shows its arrival under
its departure. The phone's booking sheet lets the route line under its
title wrap too.
2026-11-19 21:57:28 +01:00
Maurice 2c17edd74c docs(docker): the entrypoint drops to node with setpriv, say so beside its copy 2026-11-19 21:57:28 +01:00
Maurice c5e2afc21b fix(atlas): count places and cities the same way on the Atlas page and in the stats API
The Atlas page showed 100 cities and 169 places where GET /api/v1/stats
and the dashboard's passport card showed 66 and 164 for the same account.
The two sides counted with their own code. The Atlas page took the address
part right before the country as the city, which is often the region
(Bavaria for Munich, Nuremberg and Regensburg alike), and counted a bare
place name with no comma as a city. The stats side read its places with a
DISTINCT over address, coordinates and region only, so two places that
looked alike (the same hotel on two trips, places with neither address nor
coordinates) counted once, and its city reader skipped every address part
with a digit, so "10178 Berlin" never counted as Berlin.

Both now take places and cities from one method: every place counts once,
a city is read with cityFromAddress, which skips the region (#1115) and now
reads a city written beside its postcode (German, French, US, Japanese,
Dutch, British and Canadian forms) while a street with its house number
still does not count, and two spellings that differ only in case are one
city. The Atlas page, the passport card, /api/v1/stats and the MCP atlas
tool follow it. The response shapes are unchanged.

Closes #3137
2026-11-19 21:57:28 +01:00
Maurice 502e6916d9 fix(docker): start under rootful Podman on hosts that block gosu's signals
Started as root, the entrypoint dropped to the node user with gosu. gosu is
a Go program, and Go changes a process's ids by sending every runtime thread
a realtime signal and spinning until each one has answered, with no limit.
On a host whose security module drops that signal inside the container
(AppArmor on recent Ubuntu, under rootful Podman) gosu spun at full CPU
forever, before Node printed a line: no logs, no database, port 3000 never
served. Running as uid 1000 worked only because that path skips gosu.

The entrypoint now drops privileges with setpriv from util-linux, which is
already in the image: single-threaded C that makes the same id changes
without any signal. Node still runs as uid and gid 1000 with no
capabilities and HOME=/home/node. gosu stays in the image for anyone who
calls it by hand.

Closes #3135
2026-11-19 21:57:28 +01:00
Maurice 61674cf918 fix(transit): show every stop name and each ride's arrival in the journey details
The expanded transit card on the phone cut a ride's "from -> to" line to
one line, so a long first stop pushed the destination out of sight, and
it showed only the departure of each ride. The phone's booking sheet and
the desktop leg list (booking dialog, booking card, journey modal) cut
the stop names and the sheet title the same way.

The detail views now let stop names, walk targets and the booking title
wrap instead of truncating, and the expanded card shows each ride's
arrival time under its departure. The collapsed card still shortens its
headline, since expanding it shows everything.

Closes #3139
2026-11-19 21:57:28 +01:00
Maurice ac01925be7 fix(mobile): show a place's full name in its details sheet
The details sheet cut the place name to one line, and nothing in the
sheet showed the rest; only the edit form did. The sheet is where a
place is read in full, so the name now wraps onto as many lines as it
needs, as the desktop inspector already does. The address under it
wrapped before and still does.

Closes #3140
2026-11-19 21:57:28 +01:00
111 changed files with 3554 additions and 523 deletions
+4 -4
View File
@@ -94,8 +94,8 @@ RUN echo 'deb [signed-by=/etc/apt/keyrings/pgdg.asc] http://apt.postgresql.org/p
rm -rf /var/lib/apt/lists/* /usr/local/lib/node_modules/npm /usr/local/bin/npm /usr/local/bin/npx && \
chown -R node:node /app
# gosu rebuilt with a current Go toolchain (stage 0) — the entrypoint script uses
# it to drop to node.
# gosu rebuilt with a current Go toolchain (stage 0). The entrypoint drops to node
# with setpriv since #3135; gosu stays in the image for anyone who calls it by hand.
COPY --from=gosu-build /out/gosu /usr/local/bin/gosu
ENV XDG_CACHE_HOME=/tmp/kf6-cache
@@ -173,8 +173,8 @@ HEALTHCHECK --interval=30s --timeout=5s --start-period=15s --retries=3 \
# carrying quotes does not survive that round-trip (the container then dies with
# a shell syntax error before Node starts). A CMD of one bare token does.
COPY server/scripts/entrypoint.sh /usr/local/bin/trek-entrypoint
# Root-owned on purpose — this is what calls gosu, so it runs before the drop to
# node. chmod is explicit because a checkout on Windows carries no exec bit.
# Root-owned on purpose: it runs as root and drops to node itself, with setpriv.
# chmod is explicit because a checkout on Windows carries no exec bit.
RUN chmod 0755 /usr/local/bin/trek-entrypoint
ENTRYPOINT ["dumb-init", "--"]
-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",
-1
View File
@@ -113,7 +113,6 @@
"src/pages/AtlasPage.tsx": 6,
"src/pages/FilesPage.tsx": 1,
"src/pages/JourneyDetailPage.tsx": 1,
"src/pages/JourneyPublicPage.test.tsx": 1,
"src/pages/LoginPage.tsx": 1,
"src/pages/VacayPage.tsx": 1,
"src/pages/admin/useAdmin.ts": 4,
@@ -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;
}
@@ -54,6 +54,14 @@ describe('TransitLegs', () => {
expect(screen.getByText('BVG')).toBeInTheDocument();
});
it('FE-PLANNER-BKTRANSIT-009: stop names and a walk target wrap instead of being cut off (#3139)', () => {
render(<TransitLegs legs={[ride, walk]} compact />);
for (const text of ['Alexanderplatz', 'Eberswalder Str.', 'Walk to Mauerpark']) {
expect(screen.getByText(text)).not.toHaveClass('truncate');
expect(screen.getByText(text)).toHaveClass('break-words');
}
});
it('FE-PLANNER-BKTRANSIT-006: a walk reads as one and leaves out the ride facts', () => {
render(<TransitLegs legs={[walk]} compact />);
expect(screen.getByText('Walk to Mauerpark')).toBeInTheDocument();
@@ -48,9 +48,11 @@ export function TransitLegs({ legs, compact = false }: { legs: TransitLegDisplay
}}>{leg.line || leg.mode}</span>
)}
<div className={`flex min-w-0 flex-1 flex-col ${compact ? 'gap-1' : 'gap-1.5'}`}>
<div className="flex min-w-0 items-center gap-1 font-medium text-content" style={fs(compact ? 12 : 13, 'body')}>
{walk ? <span className="truncate text-content-muted">{t('transit.walkTo', { name: leg.to?.name || '' })}</span> : (
<><span className="truncate">{leg.from?.name}</span><ArrowRight size={compact ? 11 : 12} strokeWidth={2} className="flex-none text-content-faint" /><span className="truncate">{leg.to?.name}</span></>
{/* Detail views show a stop name whole: the names wrap and the
arrow moves to the next line with them when it has to (#3139). */}
<div className="flex min-w-0 flex-wrap items-center gap-1 font-medium text-content" style={fs(compact ? 12 : 13, 'body')}>
{walk ? <span className="min-w-0 break-words text-content-muted [overflow-wrap:anywhere]">{t('transit.walkTo', { name: leg.to?.name || '' })}</span> : (
<><span dir="auto" className="min-w-0 break-words [overflow-wrap:anywhere]">{leg.from?.name}</span><ArrowRight size={compact ? 11 : 12} strokeWidth={2} className="flex-none text-content-faint" /><span dir="auto" className="min-w-0 break-words [overflow-wrap:anywhere]">{leg.to?.name}</span></>
)}
</div>
<TransitMetaBadges size={compact ? 'sm' : 'md'} items={[
@@ -0,0 +1,47 @@
// FE-PLANNER-TRANSITDISPLAY-001 to FE-PLANNER-TRANSITDISPLAY-003
import { describe, expect, it } from 'vitest';
import { render, screen } from '../../../tests/helpers/render';
import type { TransitLegDisplay } from './transitDisplay';
import { TransitItineraryInline, TransitWalkDivider } from './transitDisplay';
const t = (key: string, params?: Record<string, string | number>) =>
params ? `${key}:${Object.values(params).join(',')}` : key;
const ride: TransitLegDisplay = {
mode: 'RAIL',
line: 'XC',
duration: 1260,
from: { name: 'Basingstoke', time: '12:48' },
to: { name: 'Reading', time: '13:09' },
};
const walk: TransitLegDisplay = { mode: 'WALK', duration: 240, to: { name: 'Reading station, Station Approach' } };
/** Whether a rendered element clips its text to one line. */
function clipsToOneLine(el: HTMLElement): boolean {
return el.style.whiteSpace === 'nowrap' || el.style.textOverflow === 'ellipsis';
}
describe('TransitItineraryInline (#3139)', () => {
it('FE-PLANNER-TRANSITDISPLAY-001: a ride shows both stop names in full', () => {
render(<TransitItineraryInline legs={[ride]} t={t} />);
for (const name of ['Basingstoke', 'Reading']) {
const el = screen.getByText(name);
expect(clipsToOneLine(el)).toBe(false);
expect(el.style.overflowWrap).toBe('anywhere');
}
});
it('FE-PLANNER-TRANSITDISPLAY-002: a ride shows its arrival time under its departure', () => {
render(<TransitItineraryInline legs={[ride, { ...ride, to: { name: 'Oxford' } }]} t={t} />);
expect(screen.getByText('13:09')).toBeInTheDocument();
expect(screen.getAllByText('12:48')).toHaveLength(2);
});
});
describe('TransitWalkDivider (#3139)', () => {
it('FE-PLANNER-TRANSITDISPLAY-003: the walk target wraps instead of being cut off', () => {
render(<TransitWalkDivider leg={walk} t={t} size="sm" />);
const text = screen.getByText(/transit\.walkTo:Reading station, Station Approach/);
expect(clipsToOneLine(text)).toBe(false);
});
});
@@ -41,14 +41,14 @@ export function TransitWalkDivider({ leg, t, size = 'md' }: {
background: `linear-gradient(to ${dir}, var(--text-faint), transparent)`,
opacity: 0.55,
})
// On phones the minutes lead so a long stop name only ever clips the name.
// On phones the minutes lead, so they stay on the first line when a long stop name wraps.
const text = isMobile
? `${mins ? `${t('transit.min', { count: mins })} · ` : ''}${t('transit.walkTo', { name: leg.to?.name || '' })}`
: `${t('transit.walkTo', { name: leg.to?.name || '' })}${mins ? ` · ${t('transit.min', { count: mins })}` : ''}`
return (
<div style={{ display: 'flex', alignItems: 'center', gap: 10, padding: size === 'sm' ? '1px 0' : '2px 0' }}>
<span style={rule('left')} />
<span className="text-content-faint" style={{ display: 'inline-flex', alignItems: 'center', gap: 5, fontSize: size === 'sm' ? 'calc(10px * var(--fs-scale-caption, 1))' : 'calc(11.5px * var(--fs-scale-caption, 1))', fontWeight: 500, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis', maxWidth: isMobile ? '85%' : '75%' }}>
<span className="text-content-faint" style={{ display: 'inline-flex', alignItems: 'center', gap: 5, fontSize: size === 'sm' ? 'calc(10px * var(--fs-scale-caption, 1))' : 'calc(11.5px * var(--fs-scale-caption, 1))', fontWeight: 500, textAlign: 'center', overflowWrap: 'anywhere', maxWidth: isMobile ? '85%' : '75%' }}>
<Footprints size={size === 'sm' ? 11 : 12} style={{ flexShrink: 0 }} />
{text}
</span>
@@ -72,8 +72,10 @@ export function TransitItineraryInline({ legs, t }: {
const mins = leg.duration ? Math.round(leg.duration / 60) : null
return (
<div key={i} style={{ display: 'flex', alignItems: 'flex-start', gap: 7 }}>
<span className="text-content-muted" style={{ width: 34, flexShrink: 0, textAlign: 'end', fontSize: 'calc(10px * var(--fs-scale-caption, 1))', fontWeight: 600, paddingTop: 1 }}>
{leg.from?.time || ''}
{/* Departure beside the stops, arrival under it (#3139). */}
<span className="text-content-muted" style={{ width: 34, flexShrink: 0, alignSelf: 'stretch', display: 'flex', flexDirection: 'column', justifyContent: 'space-between', textAlign: 'end', fontSize: 'calc(10px * var(--fs-scale-caption, 1))', fontWeight: 600, paddingTop: 1 }}>
<span>{leg.from?.time || ''}</span>
{leg.to?.time && <span className="text-content-faint">{leg.to.time}</span>}
</span>
<span style={{
display: 'inline-flex', alignItems: 'center', borderRadius: 4, padding: '0 5px',
@@ -84,10 +86,11 @@ export function TransitItineraryInline({ legs, t }: {
{leg.line || leg.mode}
</span>
<div style={{ flex: 1, minWidth: 0 }}>
<div className="text-content" style={{ fontSize: 'calc(11px * var(--fs-scale-caption, 1))', fontWeight: 500, display: 'flex', alignItems: 'center', gap: 4, minWidth: 0 }}>
<span style={{ overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{leg.from?.name}</span>
{/* The folded-out itinerary is where a journey is read in full: stop names wrap (#3139). */}
<div className="text-content" style={{ fontSize: 'calc(11px * var(--fs-scale-caption, 1))', fontWeight: 500, display: 'flex', flexWrap: 'wrap', alignItems: 'center', columnGap: 4, minWidth: 0 }}>
<span dir="auto" style={{ minWidth: 0, overflowWrap: 'anywhere' }}>{leg.from?.name}</span>
<MoveRight size={10} className="text-content-faint" style={{ flexShrink: 0 }} />
<span style={{ overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{leg.to?.name}</span>
<span dir="auto" style={{ minWidth: 0, overflowWrap: 'anywhere' }}>{leg.to?.name}</span>
</div>
<div className="text-content-faint" style={{ fontSize: 'calc(9.5px * var(--fs-scale-caption, 1))', marginTop: 1 }}>
{[
@@ -350,8 +350,11 @@ function TransitLegRows({ legs, t }: { legs: TransitLegDisplay[]; t: Translation
const hasSeg = i < legs.length - 1
return (
<div key={i} className="flex gap-[9px]">
<span className="w-9 flex-none pt-[9px] text-end font-geist text-[0.65625rem] font-semibold tabular-nums text-m-muted">
{isWalk ? '' : leg.from?.time?.slice(0, 5) || ''}
{/* A ride's departure stands beside its stops, its arrival at the
bottom of its row, so the open card holds the whole journey (#3139). */}
<span className="flex w-9 flex-none flex-col justify-between py-[9px] text-end font-geist text-[0.65625rem] font-semibold tabular-nums text-m-muted">
<span>{isWalk ? '' : leg.from?.time?.slice(0, 5) || ''}</span>
{!isWalk && leg.to?.time && <span className="text-m-faint">{leg.to.time.slice(0, 5)}</span>}
</span>
<div className="flex w-3 flex-none flex-col items-center">
{isWalk ? (
@@ -371,16 +374,16 @@ function TransitLegRows({ legs, t }: { legs: TransitLegDisplay[]; t: Translation
</div>
<div className="min-w-0 flex-1 py-[7px]">
{isWalk ? (
<div className="truncate font-geist text-[0.6875rem] font-semibold text-m-muted">
<div className="break-words font-geist text-[0.6875rem] font-semibold text-m-muted [overflow-wrap:anywhere]">
<Footprints size={10} strokeWidth={2.2} className="me-1 inline-block align-[-1px]" />
{[mins ? t('transit.min', { count: mins }) : '', t('transit.walkTo', { name: leg.to?.name || '' })]
.filter(Boolean).join(' · ')}
</div>
) : (
<div>
<div className="flex items-center gap-1.5">
<LineBadge leg={leg} className="flex-none" />
<span className="truncate text-[0.78125rem] font-bold">
<div className="flex items-start gap-1.5">
<LineBadge leg={leg} className="mt-px flex-none" />
<span dir="auto" className="min-w-0 break-words text-[0.78125rem] font-bold [overflow-wrap:anywhere]">
{flowText([leg.from?.name, leg.to?.name].filter((n): n is string => !!n))}
</span>
</div>
@@ -122,3 +122,15 @@ describe('MPlaceSheet ask the assistant', () => {
expect(chatOf(useAssistantStore.getState(), 5).focus).toEqual({ placeIds: [42] })
})
})
describe('MPlaceSheet header (#3140)', () => {
it('lets a long place name wrap instead of cutting it to one line', () => {
const longName = 'Broad Street Christmas Lights & Market'
render(<MPlaceSheet planner={planner({ selectedPlace: buildPlace({ id: 7, name: longName, address: 'Broad Street, RG1 2AF, Reading' }) })} shell={shell} />)
const title = screen.getByText(longName)
expect(title).not.toHaveClass('truncate')
expect(title).toHaveClass('break-words')
expect(screen.getByText('Broad Street, RG1 2AF, Reading').closest('div')).not.toHaveClass('truncate')
})
})
@@ -208,12 +208,14 @@ export default function MPlaceSheet({ planner, shell }: MTripSheetsProps) {
</PlacePhotoGallery>
</div>
<div className="min-w-0 flex-1">
<div className="flex items-center gap-1.5">
<span dir="auto" className="min-w-0 truncate text-[1rem] font-bold leading-snug">{place.name}</span>
<div className="flex items-start gap-1.5">
{/* The sheet is where a place is read in full, so its name wraps
onto as many lines as it needs, as on the desktop (#3140). */}
<span dir="auto" className="min-w-0 break-words text-[1rem] font-bold leading-snug [overflow-wrap:anywhere]">{place.name}</span>
{/* Accepted out of the traveller's own recordings — the same
mark the desktop inspector carries. */}
{place.source === 'dawarich' && (
<span className="flex-none overflow-hidden rounded-[5px]">
<span className="mt-[3px] flex-none overflow-hidden rounded-[5px]">
<DawarichIcon size={15} />
</span>
)}
@@ -236,8 +236,9 @@ export default function MTransportSheet({ planner, shell }: MTripSheetsProps) {
<div className="flex-none px-[18px] pt-4">
<TileHeader
icon={<ResIcon size={19} strokeWidth={1.8} />}
title={<span dir="auto" className="truncate text-[1rem]">{res.title}</span>}
title={<span dir="auto" className="min-w-0 break-words text-[1rem] [overflow-wrap:anywhere]">{res.title}</span>}
sub={subParts.length > 0 ? subParts.join(' · ') : undefined}
subWrap
onClose={shell.closeSheet}
closeLabel={t('common.close')}
/>
@@ -314,9 +315,9 @@ export default function MTransportSheet({ planner, shell }: MTripSheetsProps) {
<span className="text-m-muted">{t('transit.walkTo', { name: leg.to?.name || '' })}</span>
) : (
<>
<span dir="auto" className="truncate">{leg.from?.name}</span>
<span dir="auto" className="min-w-0 break-words [overflow-wrap:anywhere]">{leg.from?.name}</span>
<ArrowRight size={10} strokeWidth={2} className="flex-none text-m-faint" />
<span dir="auto" className="truncate">{leg.to?.name}</span>
<span dir="auto" className="min-w-0 break-words [overflow-wrap:anywhere]">{leg.to?.name}</span>
</>
)}
</div>
+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;
}
@@ -327,6 +327,18 @@ describe('TransitRow', () => {
expect(screen.getByText('transit.min:1 · transit.walkTo:Hotel')).toBeInTheDocument()
})
it('FE-MOB-PLROW-046: the expanded legs show every stop name in full and each ride arrival time (#3139)', () => {
const { container } = render(<TransitRow {...base} open />)
const ride = screen.getByText('Shibuya Sta. → Asakusa Sta.')
expect(ride).not.toHaveClass('truncate')
expect(ride).toHaveClass('break-words')
expect(screen.getByText('transit.min:4 · transit.walkTo:Shibuya Sta.')).not.toHaveClass('truncate')
expect(screen.getByText('10:30')).toBeInTheDocument()
// the departure keeps its place beside the arrival
expect(container.textContent).toContain('10:05')
})
it('FE-MOB-PLROW-024: tapping the header toggles the row', () => {
const onToggle = vi.fn()
render(<TransitRow {...base} open={false} onToggle={onToggle} />)
@@ -144,6 +144,24 @@ describe('MTransportSheet', () => {
expect(screen.getByText('Prater')).toBeInTheDocument()
})
it('FE-MOB-TRSH-025: the title and every stop name wrap instead of being cut off (#3139)', () => {
const res = {
...FLIGHT, type: 'transit', title: 'Basingstoke station → Reading station', endpoints: [], metadata: {
transit: {
legs: [{
mode: 'RAIL', line: 'CrossCountry', duration: 1260,
from: { name: 'Basingstoke', time: '12:48' }, to: { name: 'Reading', time: '13:09' },
}],
},
},
} as unknown as Reservation
render(<MTransportSheet planner={makePlanner({ reservations: [res] })} shell={makeShell()} />)
expect(screen.getByText('Basingstoke station → Reading station')).not.toHaveClass('truncate')
expect(screen.getByText('Basingstoke')).not.toHaveClass('truncate')
expect(screen.getByText('Reading')).not.toHaveClass('truncate')
expect(screen.getByText('Reading')).toHaveClass('break-words')
})
it('FE-MOB-TRSH-010: shows the pending status and the booking code unblurred by default', () => {
render(<MTransportSheet planner={makePlanner()} shell={makeShell()} />)
expect(screen.getByText('Pending')).toBeInTheDocument()
+10 -3
View File
@@ -25,7 +25,7 @@ fi
cd /app/server
# Already started as a non-root user (Kubernetes runAsUser, docker --user): there
# is nothing to chown and no privilege to drop, and gosu would only fail to switch
# is nothing to chown and no privilege to drop, and setpriv would only fail to switch
# users. Run Node as whoever we are; the volumes are that user's to provide.
if [ "$(id -u)" != "0" ]; then
exec node --require tsconfig-paths/register dist/index.js
@@ -42,7 +42,7 @@ fi
# Troubleshooting page of the wiki has the one-off chown for that.
#
# Only the owning user has to be node, because that is what Node runs as and
# what gosu leaves it with. The group is left to whoever set it: a Kubernetes
# what the drop below leaves it with. The group is left to whoever set it: a Kubernetes
# fsGroup other than 1000 gives every file its own gid, and taking that back
# here would make the kubelet's OnRootMismatch walk the volume again on the
# next start, and this script after it, every time. Only a root group (a fresh
@@ -65,4 +65,11 @@ for dir in /app/data /app/uploads; do
fi
done
exec gosu node node --require tsconfig-paths/register dist/index.js
# setpriv, not gosu: gosu is Go, and Go changes the ids of a process by signalling
# every runtime thread with a realtime signal and spinning until each one has
# answered. A host whose security module drops that signal inside the container
# (AppArmor on recent Ubuntu under Podman) left it spinning at full CPU, before
# Node had printed a line (#3135). setpriv is single-threaded C and makes the same
# id changes without any signal. It leaves HOME alone, which gosu set from passwd.
export HOME=/home/node
exec setpriv --reuid=node --regid=node --init-groups -- node --require tsconfig-paths/register dist/index.js
+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,
+2 -2
View File
@@ -1,11 +1,11 @@
{
"scripts/db-call-graph.mjs": 1036,
"scripts/generate-entities.ts": 2259,
"src/db/repositories/Places.repository.ts": 1435,
"src/db/repositories/Places.repository.ts": 1432,
"src/db/repositories/Reservations.repository.ts": 1550,
"src/db/repositories/Trips.repository.ts": 1120,
"src/db/repositories/Users.repository.ts": 1421,
"src/nest/atlas/atlas.service.ts": 1174,
"src/nest/atlas/atlas.service.ts": 1166,
"src/nest/auth/auth.service.ts": 1141,
"src/nest/budget/budget.service.ts": 1607,
"src/nest/collections/collections.service.ts": 1414,
-1
View File
@@ -33,7 +33,6 @@
"src/nest/integrations/dawarich-sync.service.ts#DawarichSyncService.syncUserOnce": 3,
"src/nest/journey/journey.controller.ts#JourneyController.uploadEntryPhotos": 4,
"src/nest/memories/photo-resolver.service.ts#PhotoResolverService.streamCachedThumbnail": 3,
"src/nest/memories/photo-resolver.service.ts#PhotoResolverService.streamPhoto": 2,
"src/nest/memories/synology.service.ts#SynologyService._fetchAllSynologyAlbums": 2,
"src/nest/memories/synology.service.ts#SynologyService._getSynologySession": 2,
"src/nest/memories/synology.service.ts#SynologyService._requestSynologyApi": 3,
+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`
@@ -1108,21 +1108,18 @@ export class PlacesRepository extends TrekRepository<Places> {
}
/**
* AT41 (`AtlasService#getTravelStats`) — `SELECT DISTINCT p.address,
* p.lat, p.lng, pr.region_name FROM places p JOIN trips t ON p.trip_id =
* t.id LEFT JOIN trip_members tm ON t.id = tm.trip_id LEFT JOIN
* place_regions pr ON pr.place_id = p.id WHERE t.user_id = ? OR tm.user_id
* = ?`. The resolved region rides along so `cityFromAddress` can tell the
* city apart from the region sitting right above it in the same address
* (#1115) — unchanged from the legacy projection.
* AT41 (`AtlasService#placeFootprint`): one row per place on a trip the user owns
* or is a member of. `p.id` keeps the DISTINCT to undoing the trip_members fan-out,
* so places sharing an address and coordinates stay apart (#3137). The resolved
* region rides along so `cityFromAddress` can skip it (#1115).
*/
async listAddressesForUser(user_id: number): Promise<{ address: string | null; lat: number | null; lng: number | null; region_name: string | null }[]> {
async listAddressesForUser(user_id: number): Promise<{ id: number; address: string | null; lat: number | null; lng: number | null; region_name: string | null }[]> {
return await this.kysely<PlacesAddressesForUserKyselyDB>()
.selectFrom('places as p')
.innerJoin('trips as t', 't.id', 'p.trip_id')
.leftJoin('trip_members as tm', 'tm.trip_id', 't.id')
.leftJoin('place_regions as pr', 'pr.place_id', 'p.id')
.select(['p.address', 'p.lat', 'p.lng', 'pr.region_name'])
.select(['p.id', 'p.address', 'p.lat', 'p.lng', 'pr.region_name'])
.distinct()
.where((eb) => eb.or([eb('t.user_id', '=', user_id), eb('tm.user_id', '=', user_id)]))
.execute();
@@ -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,
+34 -42
View File
@@ -394,30 +394,10 @@ export class AtlasService {
status: c.status,
}));
const citySet = new Set<string>();
for (const place of places) {
if (place.address) {
const parts = place.address
.split(',')
.map((s: string) => s.trim())
.filter(Boolean);
// The last part is the country; the city is usually right before it, but a
// full formatted address can have a postal code sitting between them
// (e.g. "Bucharest, 010071, Romania"). Walk back from the country and take
// the first part that still has letters once digits/postal noise is stripped.
const candidates = parts.length >= 2 ? parts.slice(0, -1) : parts;
let city = '';
for (let i = candidates.length - 1; i >= 0; i--) {
const cleaned = candidates[i].replace(/[\d\-−〒]+/g, '').trim();
if (cleaned) {
city = cleaned.toLowerCase();
break;
}
}
if (city) citySet.add(city);
}
}
const totalCities = citySet.size;
// Places and cities come from the same count as the dashboard card and
// GET /api/v1/stats, so the three never show different totals (#3137).
const footprint = await this.placeFootprint(userId);
const totalCities = footprint.cities.length;
// Countries the user explicitly removed. Only the zero-count passes below are
// suppressed — a country with real places isn't removable in the UI anyway, and once
@@ -570,7 +550,7 @@ export class AtlasService {
countries,
stats: {
totalTrips: trips.length,
totalPlaces: places.length,
totalPlaces: footprint.totalPlaces,
totalCountries: visited.length,
totalCountriesPlanned: planned.length,
totalCountriesIdea: countries.length - visited.length - planned.length,
@@ -1046,29 +1026,41 @@ export class AtlasService {
.map(([code]) => code);
}
/**
* The places on every trip the user owns or is a member of, archived ones included,
* with the cities and coordinates derived from them. The one count behind the Atlas
* page, the dashboard card, GET /api/v1/stats and the MCP atlas tool (#3137).
*
* Every place counts once, even when two share an address and coordinates (the same
* hotel saved on two trips). A city is read with cityFromAddress, which skips the
* region named in the same address (#1115), and two spellings that differ only in
* case are one city; the first spelling seen is the one listed.
*/
private async placeFootprint(
userId: number,
): Promise<{ totalPlaces: number; cities: string[]; coords: { lat: number; lng: number }[] }> {
const places = await this.places.listAddressesForUser(userId); // AT41
const cities = new Map<string, string>();
const coords: { lat: number; lng: number }[] = [];
for (const p of places) {
// Explicit null checks: lat/lng of exactly 0 (equator / prime meridian)
// are valid coordinates a falsy check would drop.
if (p.lat != null && p.lng != null) coords.push({ lat: p.lat, lng: p.lng });
const city = cityFromAddress(p.address, (part) => KNOWN_COUNTRIES.has(part), p.region_name);
if (city && !cities.has(city.toLowerCase())) cities.set(city.toLowerCase(), city);
}
return { totalPlaces: places.length, cities: [...cities.values()], coords };
}
async getTravelStats(userId: number) {
const today = todayUtc();
// The resolved region rides along so cityFromAddress can tell the city apart from
// the region sitting right above it in the same address (#1115).
const places = await this.places.listAddressesForUser(userId); // AT41
const { totalPlaces, cities, coords } = await this.placeFootprint(userId);
// Archived trips still count here, matching the places, countries and flight
// distance widgets (which never filtered on is_archived) so the dashboard stats
// stay consistent — archiving a trip no longer zeroes out trips/days.
const tripStats = await this.trips.countTripsAndDaysForUser(userId); // AT42
const cities = new Set<string>();
const coords: { lat: number; lng: number }[] = [];
places.forEach(p => {
// Explicit null checks: lat/lng of exactly 0 (equator / prime meridian)
// are valid coordinates the former falsy check silently dropped.
if (p.lat != null && p.lng != null) coords.push({ lat: p.lat, lng: p.lng });
const cityPart = cityFromAddress(p.address, part => KNOWN_COUNTRIES.has(part), p.region_name);
if (cityPart) cities.add(cityPart);
});
// Visited countries: the ones the user marked by hand, plus the countries of
// their places, resolved the way the Atlas map resolves them (#2875). Each
// reached country keeps the last day of its latest trip, for the order.
@@ -1111,11 +1103,11 @@ export class AtlasService {
return {
countries: visits.ordered(manualCountries).filter(code => !hidden.has(code)),
cities: [...cities],
cities,
coords,
totalTrips: tripStats.trips || 0,
totalDays: tripStats.days || 0,
totalPlaces: places.length,
totalPlaces,
totalDistanceKm: await this.flightDistanceKm(userId),
};
}
+33 -2
View File
@@ -13,6 +13,7 @@
* know the region: `place_regions.region_name` is filled by the geocoder, so it can
* simply be skipped. For the address above, with the region resolved as Tokyo, walking
* back past Japan (country), 150-0002 (digits) and Tokyo (the region) lands on Shibuya.
* A city written beside its postcode ("10178 Berlin") counts without the postcode (#3137).
*
* This is still a heuristic over a formatted string. Structured `address.city` from the
* geocoder would be exact, but the fast path for region resolution runs against bundled
@@ -25,6 +26,36 @@ function hasDigits(part: string): boolean {
return /\d/.test(part);
}
/**
* The postcodes geocoders write into the same part as the city: German, French or US
* five digits ("10178 Berlin", "NY 10118"), Japanese "150-0002", Dutch "1012 LG", British
* "SW1A 2AA" and Canadian "M5V 3L9". A house number ("Unter den Linden 77") or a numbered
* district ("Shibuya 2") is none of these and keeps its part out of the running.
*/
const POSTCODES = [
/\b\d{4}\s?[A-Z]{2}\b/g,
/\b[A-Z]{1,2}\d[A-Z\d]?\s?\d[A-Z]{2}\b/g,
/\b[A-Z]\d[A-Z]\s?\d[A-Z]\d\b/g,
/\b\d{3}-\d{4}\b/g,
/\b\d{4,}(?:-\d{4})?\b/g,
];
/**
* The name left in a part once its postcode is taken out, or null when the part holds
* no postcode or nothing but one. The short state or province code that stands beside
* a postcode ("NY 10118", "Roma RM", "ON M5V 3L9") goes with it.
*/
function besidePostcode(part: string): string | null {
let rest = part;
for (const pattern of POSTCODES) rest = rest.replace(pattern, ' ');
if (rest === part) return null;
rest = rest
.split(/\s+/)
.filter((word) => word && !/^[A-Z]{2}$/.test(word))
.join(' ');
return rest && !hasDigits(rest) && /\p{L}/u.test(rest) ? rest : null;
}
function normalize(value: string): string {
return value.trim().toLowerCase();
}
@@ -53,8 +84,8 @@ export function cityFromAddress(
// Index 0 stays out of the running: geocoders lead with the place itself.
for (let i = last; i >= 1; i--) {
const part = parts[i];
if (hasDigits(part)) continue;
const part = hasDigits(parts[i]) ? besidePostcode(parts[i]) : parts[i];
if (!part) continue;
if (isKnownCountry(part)) continue;
if (region && normalize(part) === region) continue;
// Anything with no letter at all (stray punctuation, a lone dash) is not a name.
@@ -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,76 @@ 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.
*
* @txStandalone an idempotent lazy provision: the row only records a
* thumbnail that already exists in storage, whatever the caller does next.
*/
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 +170,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 === undefined) {
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}`);
@@ -1402,7 +1402,7 @@ describe('PlacesRepository.listForTripIds (AT2, AtlasService#getPlacesForTrips)'
});
describe('PlacesRepository.listAddressesForUser (AT41, AtlasService#getTravelStats)', () => {
it('PLACEREPO-061: matches the legacy DISTINCT statement, owner and member trips, region_name joined from place_regions', async () => {
it('PLACEREPO-061: one row per place, owner and member trips, region_name joined from place_regions', async () => {
const { user: owner } = createUser(testDb);
const { user: member } = createUser(testDb);
const { user: stranger } = createUser(testDb);
@@ -1416,7 +1416,7 @@ describe('PlacesRepository.listAddressesForUser (AT41, AtlasService#getTravelSta
// test-sql-allow: the legacy statement is the oracle the repository read is held to.
const legacy = testDb.prepare(`
SELECT DISTINCT p.address, p.lat, p.lng, pr.region_name
SELECT DISTINCT p.id, p.address, p.lat, p.lng, pr.region_name
FROM places p JOIN trips t ON p.trip_id = t.id
LEFT JOIN trip_members tm ON t.id = tm.trip_id
LEFT JOIN place_regions pr ON pr.place_id = p.id
@@ -1425,8 +1425,8 @@ describe('PlacesRepository.listAddressesForUser (AT41, AtlasService#getTravelSta
const typedOwner = await places.listAddressesForUser(owner.id);
expect(typedOwner).toEqual(legacy);
expect(typedOwner).toEqual([
{ address: '5 Avenue Anatole France', lat: 48.85, lng: 2.35, region_name: 'Île-de-France' },
{ address: null, lat: null, lng: null, region_name: null },
{ id: place.id, address: '5 Avenue Anatole France', lat: 48.85, lng: 2.35, region_name: 'Île-de-France' },
{ id: noAddress.id, address: null, lat: null, lng: null, region_name: null },
]);
const typedMember = await places.listAddressesForUser(member.id);
+12 -6
View File
@@ -87,20 +87,26 @@ describe('entrypoint script', () => {
});
// Under runAsUser: 1000 there is no privilege to drop and gosu cannot switch
// users, so the non-root branch has to exec Node itself before any chown or gosu.
it('starts Node directly, without chown or gosu, when not running as root', () => {
// users, so the non-root branch has to exec Node itself before any chown or privilege drop.
it('starts Node directly, without chown or a privilege drop, when not running as root', () => {
const nonRootCheck = code.indexOf('if [ "$(id -u)" != "0" ]; then');
expect(nonRootCheck).toBeGreaterThan(-1);
const branchEnd = code.indexOf('\nfi\n', nonRootCheck);
expect(branchEnd).toBeGreaterThan(nonRootCheck);
const branch = code.slice(nonRootCheck, branchEnd);
expect(branch).toContain('exec node --require tsconfig-paths/register dist/index.js');
expect(branch).not.toContain('gosu');
expect(branch).not.toContain('setpriv');
expect(code.indexOf('chown')).toBeGreaterThan(branchEnd);
expect(code.indexOf('gosu')).toBeGreaterThan(branchEnd);
expect(code.indexOf('setpriv')).toBeGreaterThan(branchEnd);
});
it('still drops to node through gosu when started as root', () => {
expect(source).toContain('exec gosu node node --require tsconfig-paths/register dist/index.js');
// gosu is Go: it changes the ids by signalling every runtime thread and spinning until
// each answers, so a host that drops that signal hung it at full CPU (#3135).
it('drops to node through setpriv, not gosu, when started as root', () => {
expect(source).toContain(
'exec setpriv --reuid=node --regid=node --init-groups -- node --require tsconfig-paths/register dist/index.js',
);
expect(source).toContain('export HOME=/home/node');
expect(source).not.toMatch(/^\s*exec gosu/m);
});
});
@@ -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';
@@ -130,16 +131,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 +161,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');
@@ -163,6 +179,25 @@ describe('JourneyThumbsJob', () => {
await job.sweep();
expect(logMock.logError).toHaveBeenCalledWith('Journey thumbnail cleanup: storage 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.thumbnails.sweepOrphanThumbs).not.toHaveBeenCalled();
@@ -61,3 +61,21 @@ describe('cityFromAddress', () => {
expect(city('Place, -, Lyon, France')).toBe('Lyon');
});
});
describe('cityFromAddress with the postcode in the same part as the city (#3137)', () => {
it('reads the city beside a postcode, the way a Google-style address writes it', () => {
expect(city('Alexanderplatz 1, 10178 Berlin, Germany')).toBe('Berlin');
expect(city('Rue de Rivoli 99, 75001 Paris, France')).toBe('Paris');
expect(city('Via del Corso 12, 00186 Roma RM, Italy')).toBe('Roma');
expect(city('Damrak 1, 1012 LG Amsterdam, Nederland')).toBe('Amsterdam');
expect(city('10 Downing St, London SW1A 2AA, United Kingdom')).toBe('London');
expect(city('Shibuya Crossing, Shibuya City, Tokyo 150-0002, Japan', 'Tokyo')).toBe('Shibuya City');
});
it('never takes a street with its house number, a numbered district or a state code for a city', () => {
expect(city('Hotel Adlon, Unter den Linden 77, Germany')).toBeNull();
expect(city('Shibuya Sky, 12, Shibuya 2, Japan')).toBeNull();
expect(city('350 5th Ave, New York, NY 10118, USA')).toBe('New York');
expect(city('CN Tower, Toronto, ON M5V 3L9, Canada')).toBe('Toronto');
});
});
@@ -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,35 @@ 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');
renditionFor.mockRejectedValue(new Error('storage down'));
const failed = makeRes();
await photoHandler()(ask, failed, next);
expect(failed.statusCode).toBe(404);
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 +534,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 ───────────────────────────────────────────────────
@@ -577,3 +577,88 @@ describe('getTravelStats country order (#2648)', () => {
expect((await atlas.getTravelStats(user.id)).countries).toEqual(['AT', 'FR']);
});
});
/**
* The Atlas page, the dashboard card and GET /api/v1/stats showed different place and
* city totals for the same user (#3137). The Atlas page counted one place per row and
* cut cities with its own address split, while the dashboard collapsed places sharing
* an address and coordinates and read cities with cityFromAddress. Both now share one
* count, so every surface agrees with the others.
*/
describe('Atlas page and passport card count the same places and cities (#3137)', () => {
const MUNICH = { lat: 48.1374, lng: 11.5755 };
const NUREMBERG = { lat: 49.4521, lng: 11.0767 };
async function addPlace(
tripId: number,
name: string,
values: { lat?: number | null; lng?: number | null; address?: string | null },
) {
return insertRow(await sharedTestOrm(testDb), Places, { trip: tripId, name }, { lat: null, lng: null, ...values });
}
async function cacheRegion(placeId: number, regionName: string) {
await upsertRow(await sharedTestOrm(testDb), PlaceRegions, {
place: placeId,
country_code: 'DE',
region_code: 'DE-BY',
region_name: regionName,
});
}
async function seedFootprint() {
const { user } = createUser(testDb);
const { user: friend } = createUser(testDb);
const first = createTrip(testDb, user.id, { title: 'Bavaria', start_date: '2023-05-01', end_date: '2023-05-10' });
const second = createTrip(testDb, friend.id, {
title: 'Bavaria again',
start_date: '2024-05-01',
end_date: '2024-05-03',
});
// Members on both trips, so a join over trip_members fans every place out.
addTripMember(testDb, first.id, friend.id);
addTripMember(testDb, second.id, user.id);
// The same hotel saved on both trips is two places, not one.
const hotelA = await addPlace(first.id, 'Hotel', { ...MUNICH, address: 'Hotel Bayern, Munich, Bavaria, Germany' });
const hotelB = await addPlace(second.id, 'Hotel', { ...MUNICH, address: 'Hotel Bayern, Munich, Bavaria, Germany' });
// Same city in another case: still one city.
const square = await addPlace(first.id, 'Square', { ...MUNICH, address: 'Marienplatz, MUNICH, Bavaria, Germany' });
// The part before the country is the region, the city sits above it.
const castle = await addPlace(first.id, 'Castle', {
...NUREMBERG,
address: 'Kaiserburg, Nuremberg, Bavaria, Germany',
});
const bridge = await addPlace(second.id, 'Bridge', {
lat: 49.0222,
lng: 12.0972,
address: 'Steinerne Bruecke, Regensburg, Bavaria, Germany',
});
await Promise.all([hotelA, hotelB, square, castle, bridge].map((id) => cacheRegion(id, 'Bavaria')));
// A bare name holds no city, and two places without address or coordinates are two places.
await addPlace(first.id, 'Beer garden', { address: 'Augustiner Keller' });
await addPlace(second.id, 'Beer hall', { address: 'Hofbraeuhaus' });
await addPlace(first.id, 'Idea one', {});
await addPlace(second.id, 'Idea two', {});
return user;
}
it('AUTH-DB-130: totalPlaces and the city count agree between stats() and getTravelStats()', async () => {
const user = await seedFootprint();
const atlasTotals = (await atlas.stats(user.id)).stats;
const travel = await atlas.getTravelStats(user.id);
expect(atlasTotals.totalPlaces).toBe(travel.totalPlaces);
expect(atlasTotals.totalCities).toBe(travel.cities.length);
});
it('AUTH-DB-131: every place row counts once and cities come from cityFromAddress, case-insensitively', async () => {
const user = await seedFootprint();
const travel = await atlas.getTravelStats(user.id);
expect(travel.totalPlaces).toBe(9);
expect(travel.cities.map((c) => c.toLowerCase()).sort()).toEqual(['munich', 'nuremberg', 'regensburg']);
expect((await atlas.stats(user.id)).stats.totalCities).toBe(3);
});
});
@@ -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',

Some files were not shown because too many files have changed in this diff Show More