feat(journey): complete sharing, photo drafts and Studio maps

Connect the Journey backend to the web and mobile UI, including public access and subscriptions, day recordings, photo drafts and per-map framing. Preserve legacy recording responses and cover the new behavior in every locale.
This commit is contained in:
Maurice
2026-11-30 16:55:22 +01:00
parent 458227f489
commit ede109dce8
90 changed files with 5306 additions and 292 deletions
@@ -76,7 +76,7 @@ export const ASSISTANT_DENIED_TOOLS: Readonly<Record<string, string>> = {
create_journey_share_link: 'mints a public link token',
delete_journey_share_link: 'belongs with the share links above',
add_journey_comment: "speaks in the user's name to the journey's people and the readers of its share link",
list_journey_subscribers:'reads the email addresses of people without an account, which would reach the AI provider',
list_journey_subscribers: 'reads the email addresses of people without an account, which would reach the AI provider',
remove_journey_subscriber: 'belongs with the followers above',
get_trip_calendar_feed: 'reads a calendar feed token',
enable_trip_calendar_feed: 'mints a calendar feed token',
@@ -65,8 +65,14 @@ export class JourneyRecordingsController {
@Get()
@ResponseContract(journeyRecordedDaysResponseSchema)
async list(@CurrentUser() user: User, @Param('id', rowId('Journey not found')) id: number) {
return { days: await this.recordings.list(user.id, id) };
async list(
@CurrentUser() user: User,
@Param('id', rowId('Journey not found')) id: number,
@Query('includeGpx') includeGpx?: string,
) {
const days = await this.recordings.list(user.id, id);
// Older clients validate the entire response against a Dawarich-only source enum.
return { days: includeGpx === 'true' ? days : days.filter((day) => day.source === 'dawarich') };
}
/** JRN-03: whether the journey prepares its recorded days, and how the caller's last runs went. */
@@ -112,7 +112,7 @@ export class JourneyRecordingsMcp {
@Tool({
name: 'import_journey_gpx_days',
description:
"Read the recorded route of a GPX file (its track segments with times; waypoints and routes are left out) into a journey as recorded days with source gpx, one per local day the file covers, so the journey map draws them, also on days without an entry. Each point names its day in the zone of where it was recorded unless utcOffsetMinutes fixes one zone; date keeps only that one local day. A day the journey kept from a GPX file before is replaced, one kept exactly so is left as it is, and a day kept from Dawarich is never touched. Points without a time with a zone are counted as untimedPoints and left out. Never changes an entry or a text of the journey. Everyone who can open the journey sees the route on its map. Needs edit access to the journey.",
'Read the recorded route of a GPX file (its track segments with times; waypoints and routes are left out) into a journey as recorded days with source gpx, one per local day the file covers, so the journey map draws them, also on days without an entry. Each point names its day in the zone of where it was recorded unless utcOffsetMinutes fixes one zone; date keeps only that one local day. A day the journey kept from a GPX file before is replaced, one kept exactly so is left as it is, and a day kept from Dawarich is never touched. Points without a time with a zone are counted as untimedPoints and left out. Never changes an entry or a text of the journey. Everyone who can open the journey sees the route on its map. Needs edit access to the journey.',
inputSchema: { journeyId: idSchema, gpx: journeyGpxTextSchema, ...journeyGpxImportOptionsSchema.shape },
annotations: TOOL_ANNOTATIONS_WRITE,
when: journeyAddonOn,
@@ -6,14 +6,14 @@ import { RateLimitService } from '../common/rate-limit.service';
import { ResponseContract } from '../common/response-contract';
import { rowId } from '../common/row-id.pipe';
import { JourneyCommentsService } from './journey-comments.service';
import { unlockProofOf } from './journey-share-access';
import { JOURNEY_SHARE_CACHE_CONTROL, unlockProofOf } from './journey-share-access';
import {
JourneyPublicCommentCreateDto,
JourneyPublicSubscribeDto,
JourneySubscriptionTokenDto,
} from './journey-social.dto';
import { JourneySubscriptionsService } from './journey-subscriptions.service';
import { Body, Controller, Get, HttpCode, HttpException, Param, Post, Req, UseGuards } from '@nestjs/common';
import { Body, Controller, Get, Header, HttpCode, HttpException, Param, Post, Req, UseGuards } from '@nestjs/common';
import {
journeyPublicCommentsResponseSchema,
journeySubscriptionConfirmResponseSchema,
@@ -57,6 +57,7 @@ export class JourneyPublicSocialController {
) {}
@Get(':token/comments')
@Header('Cache-Control', JOURNEY_SHARE_CACHE_CONTROL)
@ResponseContract(journeyPublicCommentsResponseSchema)
listComments(@Param('token') token: string, @Req() req: Request) {
return this.comments.listPublic(token, unlockProofOf(req));
@@ -14,14 +14,27 @@ import {
import { StorageService } from '../storage/storage.service';
import {
JOURNEY_UNLOCK_COOKIE,
keepCachesPrivate,
JOURNEY_SHARE_CACHE_CONTROL,
preventSharePhotoCaching,
unlockCookieOptions,
unlockProofOf,
viewerOf,
} from './journey-share-access';
import { JourneyPublicUnlockDto } from './journey.dto';
import { JourneyService } from './journey.service';
import { Body, Controller, Get, HttpCode, HttpException, Param, Post, Req, Res, UseGuards } from '@nestjs/common';
import {
Body,
Controller,
Get,
Header,
HttpCode,
HttpException,
Param,
Post,
Req,
Res,
UseGuards,
} from '@nestjs/common';
import { journeyPublicMapLayersResponseSchema, journeyPublicResponseSchema, successResponseSchema } from '@trek/shared';
import type { Request, Response } from 'express';
@@ -59,8 +72,8 @@ function sharedPhotoKind(kind: string): 'thumbnail' | 'preview' | 'original' {
* Every route but the unlock first asks `assertPublicAccess` (#2553): the link
* exists (404), has not run out (410) and, when it has a password, the browser
* holds the unlock cookie for it (401). The photo proxies ask too, so a locked
* link hands out no picture even to somebody who knows a photo's address, and
* they answer a protected link's photos as `private`, so no shared cache keeps one.
* link hands out no picture even to somebody who knows a photo's address.
* Shared content cannot be reused from a cache after the owner changes access.
*/
@Public('share-token validated: the whole point is a link that works without an account')
@UseGuards(AddonGuard)
@@ -80,21 +93,32 @@ export class JourneyPublicController {
* this route instead of going out to the public.
*/
@Get(':token')
@Header('Cache-Control', JOURNEY_SHARE_CACHE_CONTROL)
@ResponseContract(journeyPublicResponseSchema)
async get(@Param('token') token: string, @Req() req: Request) {
await this.journey.assertPublicAccess(token, unlockProofOf(req));
const data = await this.journey.getPublicJourney(token, viewerOf(req));
const data = await this.journey.getPublicJourney(token);
if (!data) {
throw new HttpException({ error: 'Not found' }, 404);
}
return data;
}
@Post(':token/view')
@HttpCode(200)
@ResponseContract(successResponseSchema)
async view(@Param('token') token: string, @Req() req: Request) {
const link = await this.journey.assertPublicAccess(token, unlockProofOf(req));
await this.journey.recordPublicView(link.id, viewerOf(req));
return { success: true as const };
}
/**
* What the shared map shows beside the entries and photos (JRN-04), cut to
* the link's flags on the server: nothing while the map is not shared.
*/
@Get(':token/map-layers')
@Header('Cache-Control', JOURNEY_SHARE_CACHE_CONTROL)
@ResponseContract(journeyPublicMapLayersResponseSchema)
async mapLayers(@Param('token') token: string, @Req() req: Request) {
await this.journey.assertPublicAccess(token, unlockProofOf(req));
@@ -146,8 +170,8 @@ export class JourneyPublicController {
@Res() res: Response,
@Req() req: Request,
): Promise<void> {
const link = await this.journey.assertPublicAccess(token, unlockProofOf(req));
if (link.password_hash) keepCachesPrivate(res);
await this.journey.assertPublicAccess(token, unlockProofOf(req));
preventSharePhotoCaching(res);
const valid = await this.journey.validateShareTokenForPhoto(token, photoId);
if (!valid) {
throw new HttpException({ error: 'Not found' }, 404);
@@ -164,8 +188,8 @@ export class JourneyPublicController {
@Res() res: Response,
@Req() req: Request,
): Promise<void> {
const link = await this.journey.assertPublicAccess(token, unlockProofOf(req));
if (link.password_hash) keepCachesPrivate(res);
await this.journey.assertPublicAccess(token, unlockProofOf(req));
preventSharePhotoCaching(res);
const valid = await this.journey.validateShareTokenForAsset(token, assetId);
if (!valid) {
throw new HttpException({ error: 'Not found' }, 404);
@@ -191,7 +215,6 @@ export class JourneyPublicController {
if (!rendition) {
throw new HttpException({ error: 'Not found' }, 404);
}
res.set('Cache-Control', 'public, max-age=86400');
await this.storage.sendToResponse('journey', rendition, res);
return;
}
+16 -22
View File
@@ -26,14 +26,19 @@ const SHARE_PASSWORD_BCRYPT_COST = 12;
/** How long a browser stays unlocked unless the link runs out first: 30 days. */
const UNLOCK_MAX_AGE_MS = 30 * 24 * 60 * 60 * 1000;
/** Keep every UTF-8 byte of the password in the fixed-length value bcrypt sees. */
function passwordMaterial(password: string): string {
return createHash('sha256').update(password).digest('base64url');
}
/** The password's hash for the link row. Async, so a hash never blocks the event loop. */
export function hashSharePassword(password: string): Promise<string> {
return bcrypt.hash(password, SHARE_PASSWORD_BCRYPT_COST);
return bcrypt.hash(passwordMaterial(password), SHARE_PASSWORD_BCRYPT_COST);
}
/** Whether `password` is the one the link was given. */
export function checkSharePassword(password: string, hash: string): Promise<boolean> {
return bcrypt.compare(password, hash);
return bcrypt.compare(passwordMaterial(password), hash);
}
/**
@@ -96,28 +101,17 @@ export function unlockCookieOptions(
};
}
/** A `Cache-Control` value with `public` turned into `private`; anything else stays as it is. */
export function privateCacheControl(value: number | string | readonly string[]): number | string | string[] {
const toPrivate = (v: string) => v.replace(/\bpublic\b/gi, 'private');
if (typeof value === 'number') return value;
if (typeof value === 'string') return toPrivate(value);
return value.map(toPrivate);
}
export const JOURNEY_SHARE_CACHE_CONTROL = 'private, no-store';
/**
* Keeps a protected link's photo out of shared caches. The photo proxies of
* the memories domain answer `public, max-age=…`, which is right for an open
* link, but a proxy or CDN between TREK and the reader would then hand a
* protected link's photo to somebody who never typed the password. Every
* `Cache-Control` the response is given from here on is made `private`, so
* only the reader's own browser keeps it.
*/
export function keepCachesPrivate(res: Response): void {
/** Reuse the provider streams while keeping every photo request subject to current link access. */
export function preventSharePhotoCaching(res: Response): void {
res.setHeader('Cache-Control', JOURNEY_SHARE_CACHE_CONTROL);
const setHeader = res.setHeader.bind(res);
res.setHeader = ((name: string, value: number | string | readonly string[]) => {
const isCacheControl = name.toLowerCase() === 'cache-control';
return setHeader(name, isCacheControl ? privateCacheControl(value) : value);
}) as Response['setHeader'];
res.setHeader = ((name: string, value: number | string | readonly string[]) =>
setHeader(
name,
name.toLowerCase() === 'cache-control' ? JOURNEY_SHARE_CACHE_CONTROL : value,
)) as Response['setHeader'];
}
/** Who is asking, as far as the view count needs to tell readers apart: their address and browser. */
@@ -377,16 +377,11 @@ export class JourneyShareService {
}
/**
* The shared journey. `viewer` (address and browser, see `viewerOf`) is who
* opened it, for the owner's view count; left out, nothing is counted.
* The shared journey.
* `canMail` says whether the instance can send mail at all: a reader is only
* offered to follow the link by email when it can (#1669).
*/
async getPublicJourney(
token: string,
viewer?: string,
options: { canMail?: boolean } = {},
): Promise<JourneyPublicResponse | null> {
async getPublicJourney(token: string, options: { canMail?: boolean } = {}): Promise<JourneyPublicResponse | null> {
// JS11 — exact-match token lookup, no LIKE/COLLATE (R4).
const row = await this.shareTokensRepo.findByToken(token);
if (!row) return null;
@@ -395,8 +390,6 @@ export class JourneyShareService {
const journey = await this.journeysRepo.findById(row.journey_id);
if (!journey) return null;
if (viewer !== undefined) await this.countView(row.id, viewer);
// Entries with photos — JS13 (Plan 4 Task 8b: relocated to `JourneyEntriesRepository`).
const entries = await this.entriesRepo.listPublicEntries(row.journey_id);
@@ -497,7 +490,7 @@ export class JourneyShareService {
*
* @txStandalone a counter bumped in one statement, independent of the read around it.
*/
private async countView(linkId: number, viewer: string): Promise<void> {
async recordPublicView(linkId: number, viewer: string): Promise<void> {
try {
if (!(await this.views.firstToday(viewKey(linkId, viewer), new Date()))) return;
await this.shareTokensRepo.recordView(linkId);
+5 -2
View File
@@ -220,8 +220,11 @@ export class JourneyService {
unlockPublicLink(token: string, password: string) {
return this.share.unlockPublicLink(token, password);
}
async getPublicJourney(token: string, viewer?: string) {
return this.share.getPublicJourney(token, viewer, { canMail: await this.mailer.isSmtpConfigured() });
async getPublicJourney(token: string) {
return this.share.getPublicJourney(token, { canMail: await this.mailer.isSmtpConfigured() });
}
recordPublicView(linkId: number, viewer: string) {
return this.share.recordPublicView(linkId, viewer);
}
getPublicMapLayers(token: string) {
return this.map.publicMapLayers(token);
@@ -109,12 +109,7 @@ export class PhotoResolverService {
* told the asset goes to the public, so it can send a rendition without the
* stored location in place of the original file.
*/
async streamPublicPhoto(
res: Response,
ownerId: number,
photoId: number,
kind: PhotoAssetKind,
): Promise<void> {
async streamPublicPhoto(res: Response, ownerId: number, photoId: number, kind: PhotoAssetKind): Promise<void> {
await this.stream(res, ownerId, photoId, kind, undefined, 'public');
}
@@ -100,8 +100,11 @@ describe('a journey link with a password', () => {
const open = await request(server).get(`/api/public/journey/${token}`).set('Cookie', pair);
expect(open.status).toBe(200);
expect(open.headers['cache-control']).toBe('private, no-store');
expect(open.body.journey.title).toBe(journey.title);
expect((await request(server).get(`/api/public/journey/${token}/map-layers`).set('Cookie', pair)).status).toBe(200);
const map = await request(server).get(`/api/public/journey/${token}/map-layers`).set('Cookie', pair);
expect(map.status).toBe(200);
expect(map.headers['cache-control']).toBe('private, no-store');
});
it('JPUBLINK-E2E-002: a new password locks out the browsers that unlocked the old one', async () => {
@@ -120,7 +123,9 @@ describe('a journey link with a password', () => {
it('JPUBLINK-E2E-003: wrong passwords count per address and link, a right one does not', async () => {
const { token } = await sharedJourney({ password: 'secret1' });
for (let i = 0; i < 10; i++) {
const res = await request(server).post(`/api/public/journey/${token}/unlock`).send({ password: `nope${i}` });
const res = await request(server)
.post(`/api/public/journey/${token}/unlock`)
.send({ password: `nope${i}` });
expect(res.status).toBe(401);
}
const limited = await request(server).post(`/api/public/journey/${token}/unlock`).send({ password: 'secret1' });
@@ -194,13 +199,17 @@ describe('a journey link with an expiry', () => {
});
describe('the view count of a journey link', () => {
it('JPUBLINK-E2E-020: counts each reader once a day, on the journey read only, for the owner only', async () => {
it('JPUBLINK-E2E-020: records each reader once a day and shows the count only to the owner', async () => {
const { owner, journey, token } = await sharedJourney();
await request(server).get(`/api/public/journey/${token}`).set('User-Agent', 'Reader A');
await request(server).get(`/api/public/journey/${token}`).set('User-Agent', 'Reader A');
await request(server).get(`/api/public/journey/${token}`).set('User-Agent', 'Reader B');
await request(server).get(`/api/public/journey/${token}/map-layers`).set('User-Agent', 'Reader C');
expect((await ownerReads(journey.id, owner.id)).body.link.view_count).toBe(0);
const view = (reader: string) =>
request(server).post(`/api/public/journey/${token}/view`).set('User-Agent', reader);
expect((await view('Reader A')).status).toBe(200);
expect((await view('Reader A')).status).toBe(200);
expect((await view('Reader B')).status).toBe(200);
const read = await ownerReads(journey.id, owner.id);
expect(read.body.link.view_count).toBe(2);
@@ -212,7 +221,9 @@ describe('the view count of a journey link', () => {
it('JPUBLINK-E2E-021: a locked link counts nobody who has not unlocked it', async () => {
const { token } = await sharedJourney({ password: 'secret1' });
await request(server).get(`/api/public/journey/${token}`).set('User-Agent', 'Stranger');
expect((await request(server).post(`/api/public/journey/${token}/view`).set('User-Agent', 'Stranger')).status).toBe(
401,
);
expect((await findRow(orm, JourneyShareTokens, { token }))?.view_count).toBe(0);
});
});
@@ -366,7 +366,9 @@ describe('Journey recordings e2e (real guards + temp SQLite)', () => {
'12',
);
const listed = await request(server).get(base()).set(as(VIEWER));
const legacy = await request(server).get(base()).set(as(VIEWER));
expect(legacy.body.days.map((day: { source: string }) => day.source)).toEqual(['dawarich']);
const listed = await request(server).get(base()).query({ includeGpx: true }).set(as(VIEWER));
expect(listed.body.days.map((d: { date: string; source: string }) => [d.date, d.source])).toEqual([
[DAY, 'dawarich'],
[DAY, 'gpx'],
@@ -379,7 +381,7 @@ describe('Journey recordings e2e (real guards + temp SQLite)', () => {
const dropped = await request(server).delete(`${base()}/${DAY}?source=gpx`).set(as(EDITOR));
expect(dropped.status).toBe(200);
const left = await request(server).get(base()).set(as(OWNER));
const left = await request(server).get(base()).query({ includeGpx: true }).set(as(OWNER));
expect(left.body.days.map((d: { date: string; source: string }) => [d.date, d.source])).toEqual([
[DAY, 'dawarich'],
['2026-05-15', 'gpx'],
@@ -24,7 +24,10 @@ describe('journey_share_tokens protection migration', () => {
if (!previous) throw new Error('no step before the target');
await migrateTo(orm, previous);
await rawExec(orm, "INSERT INTO users (id, username, email, password_hash) VALUES (1, 'owner', 'o@test', 'x')");
await rawExec(orm, "INSERT INTO journeys (id, user_id, title, created_at, updated_at) VALUES (5, 1, 'Iceland', 0, 0)");
await rawExec(
orm,
"INSERT INTO journeys (id, user_id, title, created_at, updated_at) VALUES (5, 1, 'Iceland', 0, 0)",
);
await rawExec(
orm,
"INSERT INTO journey_share_tokens (id, journey_id, token, created_by, share_timeline, share_gallery, share_map, share_plan) VALUES (9, 5, 'tok', 1, 1, 0, 1, 1)",
@@ -116,13 +116,11 @@ describe('MCP tool input schemas', () => {
it('MCP-SCHEMA-004: the page edit and the design revision, which take every page operation, stay under their ceiling', () => {
// Every element kind's add and style operation widen the op union; the design's
// revision takes the same ops. A layout's undo takes its layout as JSON text, so it stays small.
// Measured at about 45 400 since a map's scope (country, day, stop), its own view and its coast
// (book schema revision 12), up from 44 600, with the scope and the view each checked whole to stay small.
const sizeOf = (tool: string) =>
JSON.stringify([...schemas].find(([key]) => key.endsWith(`#${tool}`))?.[1] ?? null).length;
for (const tool of ['edit_book_page', 'revise_book_design']) {
expect(sizeOf(tool)).toBeGreaterThan(10_000);
expect(sizeOf(tool)).toBeLessThan(46_000);
expect(sizeOf(tool)).toBeLessThan(45_000);
}
expect(sizeOf('restore_book_layout')).toBeLessThan(2_000);
});
@@ -1529,7 +1529,9 @@ describe('the view count of a share link', () => {
});
async function publicJourneyAs(token: string, viewer: string) {
const result = await svc.getPublicJourney(token, viewer);
const link = await svc.assertPublicAccess(token, undefined);
await svc.recordPublicView(link.id, viewer);
const result = await svc.getPublicJourney(token);
if (!result) throw new Error('no public payload for the share link');
return result;
}
@@ -50,7 +50,6 @@ const captureBackfillStub = {
scheduleUpload,
} as unknown as JourneyPhotoCaptureService;
/**
* Build the controller.
*
@@ -1129,8 +1128,13 @@ describe('JourneyPublicController', () => {
});
const getPublicJourney = vi.fn().mockReturnValue({ id: 1 });
expect(await pub(open({ getPublicJourney })).get('tok', anon)).toEqual({ id: 1 });
// The reader is named for the view count by address and browser, nothing more.
expect(getPublicJourney).toHaveBeenCalledWith('tok', '203.0.113.9|Firefox');
expect(getPublicJourney).toHaveBeenCalledWith('tok');
});
it('records a view against the link that passed the shared access check', async () => {
const recordPublicView = vi.fn().mockResolvedValue(undefined);
expect(await pub(open({ recordPublicView })).view('tok', anon)).toEqual({ success: true });
expect(recordPublicView).toHaveBeenCalledWith(1, '203.0.113.9|Firefox');
});
it('GET /:token/map-layers 404 on an unknown link, else the layers as the service cut them (JRN-04)', async () => {
@@ -1239,28 +1243,46 @@ describe('JourneyPublicController', () => {
it('photo proxy 404 on invalid token, else streams', async () => {
const invalid = open({ validateShareTokenForPhoto: vi.fn().mockReturnValue(null) });
expect(await thrownAsync(() => pub(invalid).photo('tok', 7, 'thumbnail', {} as Response, anon))).toEqual({
expect(
await thrownAsync(() =>
pub(invalid).photo('tok', 7, 'thumbnail', { setHeader: vi.fn() } as unknown as Response, anon),
),
).toEqual({
status: 404,
body: { error: 'Not found' },
});
const streamPhoto = vi.fn().mockResolvedValue(undefined);
const s = open({ validateShareTokenForPhoto: vi.fn().mockReturnValue({ ownerId: 2 }), streamPhoto });
await pub(s).photo('tok', 7, 'original', {} as Response, anon);
expect(streamPhoto).toHaveBeenCalledWith({}, 2, 7, 'original');
await pub(s).photo('tok', 7, 'original', { setHeader: vi.fn() } as unknown as Response, anon);
expect(streamPhoto).toHaveBeenCalledWith(
expect.objectContaining({ setHeader: expect.any(Function) }),
2,
7,
'original',
);
});
it('legacy photo proxy: 404 invalid token, immich path streams', async () => {
const invalid = open({ validateShareTokenForAsset: vi.fn().mockReturnValue(null) });
expect(
await thrownAsync(() => pub(invalid).legacyPhoto('tok', 'immich', 'a1', 'thumbnail', {} as Response, anon)),
await thrownAsync(() =>
pub(invalid).legacyPhoto(
'tok',
'immich',
'a1',
'thumbnail',
{ setHeader: vi.fn() } as unknown as Response,
anon,
),
),
).toEqual({ status: 404, body: { error: 'Not found' } });
// One call for every provider now, with the ids in a ref instead of in a
// per-provider argument order.
const streamProviderAsset = vi.fn().mockResolvedValue(undefined);
const s = open({ validateShareTokenForAsset: vi.fn().mockReturnValue({ ownerId: 5 }), streamProviderAsset });
await pub(s).legacyPhoto('tok', 'immich', 'a1', 'original', {} as Response, anon);
await pub(s).legacyPhoto('tok', 'immich', 'a1', 'original', { setHeader: vi.fn() } as unknown as Response, anon);
expect(streamProviderAsset).toHaveBeenCalledWith(
{},
expect.objectContaining({ setHeader: expect.any(Function) }),
'immich',
{ userId: 5, ownerId: 5, assetId: 'a1' },
'original',
@@ -1270,33 +1292,50 @@ describe('JourneyPublicController', () => {
it('photo proxy streams thumbnails too', async () => {
const streamPhoto = vi.fn().mockResolvedValue(undefined);
const s = open({ validateShareTokenForPhoto: vi.fn().mockReturnValue({ ownerId: 3 }), streamPhoto });
await pub(s).photo('tok', 7, 'thumbnail', {} as Response, anon);
expect(streamPhoto).toHaveBeenCalledWith({}, 3, 7, 'thumbnail');
await pub(s).photo('tok', 7, 'thumbnail', { setHeader: vi.fn() } as unknown as Response, anon);
expect(streamPhoto).toHaveBeenCalledWith(
expect.objectContaining({ setHeader: expect.any(Function) }),
3,
7,
'thumbnail',
);
});
it('both photo proxies hand a preview on as one (#2874), and any other size as the original', async () => {
const streamPhoto = vi.fn().mockResolvedValue(undefined);
const streamProviderAsset = vi.fn().mockResolvedValue(undefined);
const s = svc({
const s = open({
validateShareTokenForPhoto: vi.fn().mockReturnValue({ ownerId: 3 }),
validateShareTokenForAsset: vi.fn().mockReturnValue({ ownerId: 3 }),
streamPhoto,
streamProviderAsset,
} as Partial<JourneyService>);
const proxy = new JourneyPublicController(s, storageStub, publicMediaStub);
await proxy.photo('tok', 7, 'preview', {} as Response);
await proxy.photo('tok', 7, 'huge', {} as Response);
await proxy.legacyPhoto('tok', 'immich', 'a1', 'preview', {} as Response);
});
const proxy = pub(s);
await proxy.photo('tok', 7, 'preview', { setHeader: vi.fn() } as unknown as Response, anon);
await proxy.photo('tok', 7, 'huge', { setHeader: vi.fn() } as unknown as Response, anon);
await proxy.legacyPhoto('tok', 'immich', 'a1', 'preview', { setHeader: vi.fn() } as unknown as Response, anon);
expect(streamPhoto.mock.calls.map((call) => call[3])).toEqual(['preview', 'original']);
expect(streamProviderAsset).toHaveBeenCalledWith({}, 'immich', { userId: 3, ownerId: 3, assetId: 'a1' }, 'preview');
expect(streamProviderAsset).toHaveBeenCalledWith(
expect.objectContaining({ setHeader: expect.any(Function) }),
'immich',
{ userId: 3, ownerId: 3, assetId: 'a1' },
'preview',
);
});
it('legacy photo proxy: synology streams, and a failure becomes a 404 json', async () => {
const streamProviderAsset = vi.fn().mockResolvedValue(undefined);
const s = open({ validateShareTokenForAsset: vi.fn().mockReturnValue({ ownerId: 5 }), streamProviderAsset });
await pub(s).legacyPhoto('tok', 'synologyphotos', 'a1', 'thumbnail', {} as Response, anon);
await pub(s).legacyPhoto(
'tok',
'synologyphotos',
'a1',
'thumbnail',
{ setHeader: vi.fn() } as unknown as Response,
anon,
);
expect(streamProviderAsset).toHaveBeenCalledWith(
{},
expect.objectContaining({ setHeader: expect.any(Function) }),
'synologyphotos',
{ userId: 5, ownerId: 5, assetId: 'a1' },
'thumbnail',
@@ -1304,7 +1343,7 @@ describe('JourneyPublicController', () => {
const status = vi.fn().mockReturnThis();
const json = vi.fn();
const res = { status, json } as unknown as Response;
const res = { status, json, setHeader: vi.fn() } as unknown as Response;
const failing = open({
validateShareTokenForAsset: vi.fn().mockReturnValue({ ownerId: 0 }),
streamProviderAsset: vi.fn().mockRejectedValue(new Error('no synology')),
@@ -1321,7 +1360,7 @@ describe('JourneyPublicController', () => {
const streamProviderAsset = vi.fn().mockReturnValue(null);
const status = vi.fn().mockReturnThis();
const json = vi.fn();
const res = { status, json } as unknown as Response;
const res = { status, json, setHeader: vi.fn() } as unknown as Response;
const s = open({ validateShareTokenForAsset: vi.fn().mockReturnValue({ ownerId: 5 }), streamProviderAsset });
await pub(s).legacyPhoto('tok', 'photoprism', 'a1', 'original', res, anon);
expect(status).toHaveBeenCalledWith(404);
@@ -1334,9 +1373,9 @@ describe('JourneyPublicController', () => {
// the journey owner when the photo row carries no owner_id.
const streamProviderAsset = vi.fn().mockResolvedValue(undefined);
const s = open({ validateShareTokenForAsset: vi.fn().mockReturnValue({ ownerId: 3 }), streamProviderAsset });
await pub(s).legacyPhoto('tok', 'immich', 'a1', 'original', {} as Response, anon);
await pub(s).legacyPhoto('tok', 'immich', 'a1', 'original', { setHeader: vi.fn() } as unknown as Response, anon);
expect(streamProviderAsset).toHaveBeenCalledWith(
{},
expect.objectContaining({ setHeader: expect.any(Function) }),
'immich',
{ userId: 3, ownerId: 3, assetId: 'a1' },
'original',
@@ -1347,20 +1386,29 @@ describe('JourneyPublicController', () => {
storageExists.mockResolvedValue(false);
const s = open({ validateShareTokenForAsset: vi.fn().mockReturnValue({ ownerId: 5 }) });
expect(
await thrownAsync(() => pub(s).legacyPhoto('tok', 'local', 'gone.jpg', 'thumbnail', {} as Response, anon)),
await thrownAsync(() =>
pub(s).legacyPhoto(
'tok',
'local',
'gone.jpg',
'thumbnail',
{ setHeader: vi.fn() } as unknown as Response,
anon,
),
),
).toEqual({ status: 404, body: { error: 'Not found' } });
expect(storageSendToResponse).not.toHaveBeenCalled();
});
it('legacy photo proxy: local provider serves through storage with the day cache header', async () => {
it('legacy photo proxy: local provider serves through storage without allowing cached access', async () => {
storageExists.mockResolvedValue(true);
storageSendToResponse.mockResolvedValue(undefined);
const set = vi.fn();
const res = { set } as unknown as Response;
const setHeader = vi.fn();
const res = { setHeader } as unknown as Response;
const s = open({ validateShareTokenForAsset: vi.fn().mockReturnValue({ ownerId: 5 }) });
await pub(s).legacyPhoto('tok', 'local', 'photo.jpg', 'original', res, anon);
expect(storageExists).toHaveBeenCalledWith('journey', 'photo.jpg');
expect(set).toHaveBeenCalledWith('Cache-Control', 'public, max-age=86400');
expect(setHeader).toHaveBeenCalledWith('Cache-Control', 'private, no-store');
// The location-free copy goes out, never the stored original.
expect(renditionFor).toHaveBeenCalledWith('journey', 'photo.jpg');
expect(storageSendToResponse).toHaveBeenCalledWith('journey', 'public/photo.jpg', res);
@@ -1370,7 +1418,7 @@ describe('JourneyPublicController', () => {
storageExists.mockResolvedValue(true);
renditionFor.mockRejectedValueOnce(new RenditionPendingError());
const json = vi.fn();
const res = { set: vi.fn(), status: vi.fn(() => ({ json })) } as unknown as Response;
const res = { set: vi.fn(), setHeader: vi.fn(), status: vi.fn(() => ({ json })) } as unknown as Response;
const s = open({ validateShareTokenForAsset: vi.fn().mockReturnValue({ ownerId: 5 }) });
await pub(s).legacyPhoto('tok', 'local', 'clip.mp4', 'original', res, anon);
expect(res.status).toHaveBeenCalledWith(503);
@@ -1381,7 +1429,7 @@ describe('JourneyPublicController', () => {
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 res = { set: vi.fn(), setHeader: vi.fn() } as unknown as Response;
const s = open({ validateShareTokenForAsset: vi.fn().mockReturnValue({ ownerId: 5 }) });
expect(await thrownAsync(() => pub(s).legacyPhoto('tok', 'local', 'a.bmp', 'original', res, anon))).toEqual({
status: 404,
@@ -1393,7 +1441,7 @@ describe('JourneyPublicController', () => {
it('legacy photo proxy: local provider cannot escape uploads/journey via a traversal asset id', async () => {
storageExists.mockResolvedValue(true);
storageSendToResponse.mockResolvedValue(undefined);
const res = { set: vi.fn() } as unknown as Response;
const res = { set: vi.fn(), setHeader: vi.fn() } as unknown as Response;
const s = open({ validateShareTokenForAsset: vi.fn().mockReturnValue({ ownerId: 5 }) });
// Express decodes %2F in a single path param to '/', so the handler sees this.
@@ -1411,7 +1459,8 @@ describe('JourneyPublicController', () => {
// which the handler reads as a miss.
storageExists.mockRejectedValue(new Error('invalid storage key: journey/..'));
const s = open({ validateShareTokenForAsset: vi.fn().mockReturnValue({ ownerId: 5 }) });
const read = () => pub(s).legacyPhoto('tok', 'local', '..', 'original', {} as Response, anon);
const read = () =>
pub(s).legacyPhoto('tok', 'local', '..', 'original', { setHeader: vi.fn() } as unknown as Response, anon);
expect(await thrownAsync(read)).toEqual({
status: 404,
body: { error: 'Not found' },
@@ -7,8 +7,7 @@ import {
checkSharePassword,
hashSharePassword,
JOURNEY_UNLOCK_COOKIE,
keepCachesPrivate,
privateCacheControl,
preventSharePhotoCaching,
proofUnlocks,
shareLinkExpired,
unlockCookieOptions,
@@ -20,7 +19,7 @@ import {
import { InMemoryJourneyShareViewStore } from '../../../../src/nest/journey/journey-share-views.store';
import type { Request, Response } from 'express';
import { describe, expect, it } from 'vitest';
import { describe, expect, it, vi } from 'vitest';
const BASE = { cookies: {}, headers: { 'user-agent': 'Firefox' }, ip: '203.0.113.9', secure: false };
const req = (over: Record<string, unknown> = {}) => ({ ...BASE, ...over }) as unknown as Request;
@@ -32,6 +31,13 @@ describe('the share password', () => {
expect(await checkSharePassword('open sesame', hash)).toBe(true);
expect(await checkSharePassword('open sesame!', hash)).toBe(false);
});
it('checks the entire password when it has more than 72 UTF-8 bytes', async () => {
const prefix = '旅'.repeat(24);
const hash = await hashSharePassword(`${prefix}a`);
expect(await checkSharePassword(`${prefix}a`, hash)).toBe(true);
expect(await checkSharePassword(`${prefix}b`, hash)).toBe(false);
});
});
describe('the unlock proof', () => {
@@ -128,13 +134,11 @@ describe('InMemoryJourneyShareViewStore', () => {
});
});
describe('the photo caches of a protected link', () => {
it('JSHAREACC-011: turns public into private and leaves every other value alone', () => {
expect(privateCacheControl('public, max-age=86400')).toBe('private, max-age=86400');
expect(privateCacheControl('Public, max-age=3600')).toBe('private, max-age=3600');
expect(privateCacheControl('no-store, max-age=0')).toBe('no-store, max-age=0');
expect(privateCacheControl(['public', 'max-age=60'])).toEqual(['private', 'max-age=60']);
expect(privateCacheControl(60)).toBe(60);
describe('public Journey photo caching', () => {
it('JSHAREACC-011: sets the cache policy even when the stream sends none', () => {
const setHeader = vi.fn();
preventSharePhotoCaching({ setHeader } as unknown as Response);
expect(setHeader).toHaveBeenCalledWith('Cache-Control', 'private, no-store');
});
it('JSHAREACC-012: rewrites every Cache-Control the response is given afterwards, and only that header', () => {
@@ -145,13 +149,13 @@ describe('the photo caches of a protected link', () => {
return res;
},
} as unknown as Response;
keepCachesPrivate(res);
preventSharePhotoCaching(res);
res.setHeader('Cache-Control', 'public, max-age=86400');
res.setHeader('cache-control', 'public, max-age=3600');
res.setHeader('Content-Type', 'image/public');
expect(headers).toEqual({
'Cache-Control': 'private, max-age=86400',
'cache-control': 'private, max-age=3600',
'Cache-Control': 'private, no-store',
'cache-control': 'private, no-store',
'Content-Type': 'image/public',
});
});