From 55fc5f66798c934b644f7a2850e47a86b3a4e6ed Mon Sep 17 00:00:00 2001 From: Maurice Date: Mon, 30 Nov 2026 14:36:42 +0100 Subject: [PATCH] feat(journey): protect a public journey link with a password and an expiry A journey's share link can now ask readers for a password, stop working on a date its owner picks, and count how often it was opened (#2553, #1702, no password, no expiry and no views. - journey_share_tokens gains password_hash, password_version, expires_at, view_count and last_viewed_at (append-only migration, SQLite and Postgres, added only where missing). - The password is hashed with bcrypt at the account cost. POST /api/public/journey/:token/unlock checks it, rate limited per address and link (only refusals count), and sets an httpOnly cookie scoped to the link's API path holding an HMAC over the token and the password version. Secure follows the request, so plain-HTTP installs keep working. Changing or removing the password raises the version and locks every old cookie out. - Every public route, the photo proxies included, first checks the link: 404 unknown, 410 expired (JOURNEY_LINK_EXPIRED), 401 locked (JOURNEY_PASSWORD_REQUIRED). - Saving the share switches keeps the password and the expiry; the owner's read returns has_password, expires_at, view_count and last_viewed_at, never the hash, and none of it reaches the public payload. - A reader is counted once a day per address and browser, in an in-memory store behind an injectable port; a restart may count them again. - create_journey_share_link takes password and expires_at like the REST route; get_journey_share_link reports has_password. --- .../db/entities/JourneyShareTokens.entity.ts | 10 + .../src/db/kysely/JourneyShareTokens.table.ts | 5 + ...link_can_ask_for_a_password_and_run_out.ts | 45 +++ .../JourneyShareTokens.repository.ts | 56 ++- .../src/nest/common/validate-route-guards.ts | 1 + .../src/nest/journey/journey-domain.module.ts | 3 + .../nest/journey/journey-public.controller.ts | 64 +++- .../src/nest/journey/journey-share-access.ts | 108 ++++++ .../nest/journey/journey-share-views.store.ts | 52 +++ .../src/nest/journey/journey-share.service.ts | 174 ++++++++- server/src/nest/journey/journey.controller.ts | 3 + server/src/nest/journey/journey.dto.ts | 3 + server/src/nest/journey/journey.mcp.ts | 9 +- server/src/nest/journey/journey.module.ts | 3 + server/src/nest/journey/journey.service.ts | 12 +- .../tests/e2e/journey-public-link.e2e.test.ts | 215 +++++++++++ server/tests/e2e/journey.e2e.test.ts | 3 +- ...journey-share-protection-migration.test.ts | 91 +++++ server/tests/unit/db/legacy-baseline.test.ts | 1 + server/tests/unit/db/nul-free.test.ts | 1 + .../JourneyShareTokens.repository.test.ts | 99 +++++ server/tests/unit/mcp/tools-journey.test.ts | 41 +++ .../unit/nest/journey-share.service.test.ts | 189 ++++++++++ .../unit/nest/journey.controller.test.ts | 341 +++++++++--------- .../nest/journey/journey-share-access.test.ts | 127 +++++++ shared/src/journey/journey-public.schema.ts | 24 ++ shared/src/journey/journey.schema.spec.ts | 27 ++ shared/src/journey/journey.schema.ts | 26 +- wiki/MCP-Addon-Tools.md | 4 +- 29 files changed, 1540 insertions(+), 197 deletions(-) create mode 100644 server/src/db/migrations/Migration20200101046620_a_journey_link_can_ask_for_a_password_and_run_out.ts create mode 100644 server/src/nest/journey/journey-share-access.ts create mode 100644 server/src/nest/journey/journey-share-views.store.ts create mode 100644 server/tests/e2e/journey-public-link.e2e.test.ts create mode 100644 server/tests/unit/db/journey-share-protection-migration.test.ts create mode 100644 server/tests/unit/db/repositories/JourneyShareTokens.repository.test.ts create mode 100644 server/tests/unit/nest/journey/journey-share-access.test.ts diff --git a/server/src/db/entities/JourneyShareTokens.entity.ts b/server/src/db/entities/JourneyShareTokens.entity.ts index 794d139af..431523fed 100644 --- a/server/src/db/entities/JourneyShareTokens.entity.ts +++ b/server/src/db/entities/JourneyShareTokens.entity.ts @@ -18,6 +18,11 @@ export class JourneyShareTokens { newest_first: number & Opt = 0; share_plan: number & Opt = 0; share_recordings: number & Opt = 0; + password_hash?: string | null; + password_version: number & Opt = 0; + expires_at?: string | null; + view_count: number & Opt = 0; + last_viewed_at?: string | null; createdByRef!: Ref; } @@ -38,6 +43,11 @@ export const JourneyShareTokensSchema = defineEntity({ newest_first: p.integer().default(0), share_plan: p.integer().default(0), share_recordings: p.integer().default(0), + password_hash: p.text().nullable(), + password_version: p.integer().default(0), + expires_at: p.type(DbTimestampType).nullable(), + view_count: p.integer().default(0), + last_viewed_at: p.type(DbTimestampType).nullable(), createdByRef: () => p.manyToOne(Users).ref().joinColumn('created_by').hidden().index('idx_journey_share_tokens_created_by'), }, }); diff --git a/server/src/db/kysely/JourneyShareTokens.table.ts b/server/src/db/kysely/JourneyShareTokens.table.ts index 16841e46b..8421112d0 100644 --- a/server/src/db/kysely/JourneyShareTokens.table.ts +++ b/server/src/db/kysely/JourneyShareTokens.table.ts @@ -14,4 +14,9 @@ export interface JourneyShareTokensTable { newest_first: InsertOptional; share_plan: InsertOptional; share_recordings: InsertOptional; + password_hash: InsertOptional; + password_version: InsertOptional; + expires_at: InsertOptional; + view_count: InsertOptional; + last_viewed_at: InsertOptional; } diff --git a/server/src/db/migrations/Migration20200101046620_a_journey_link_can_ask_for_a_password_and_run_out.ts b/server/src/db/migrations/Migration20200101046620_a_journey_link_can_ask_for_a_password_and_run_out.ts new file mode 100644 index 000000000..124e09dd7 --- /dev/null +++ b/server/src/db/migrations/Migration20200101046620_a_journey_link_can_ask_for_a_password_and_run_out.ts @@ -0,0 +1,45 @@ +import { addColumnIfMissing } from '../migration-utils'; +import { Migration } from '@mikro-orm/migrations'; + +/** + * A journey's public link can ask a reader for a password, stop working on a + * date its owner picks, and count how often it was opened (#2553, #1702, #2959). + * + * - `password_hash`: the bcrypt hash of the link's password, null for a link + * anyone with the address may read. + * - `password_version`: raised whenever the password is set, changed or taken + * off. A reader's unlock cookie is signed over it, so a changed password + * locks out everybody who unlocked the old one. + * - `expires_at`: when the link stops working, null for never. + * - `view_count` / `last_viewed_at`: how many readers opened it, each counted + * once a day, and when the last one did. The owner sees them, a reader never. + * + * Every existing link keeps working exactly as before: no password, no expiry, + * nothing counted yet. + */ +export class Migration20200101046620_a_journey_link_can_ask_for_a_password_and_run_out extends Migration { + override name = 'Migration20200101046620_a_journey_link_can_ask_for_a_password_and_run_out'; + + override async up(): Promise { + await addColumnIfMissing(this, 'journey_share_tokens', 'password_hash', { + sqlite: 'password_hash TEXT', + postgres: '"password_hash" text null', + }); + await addColumnIfMissing(this, 'journey_share_tokens', 'password_version', { + sqlite: 'password_version INTEGER NOT NULL DEFAULT 0', + postgres: '"password_version" bigint not null default 0', + }); + await addColumnIfMissing(this, 'journey_share_tokens', 'expires_at', { + sqlite: 'expires_at DATETIME', + postgres: '"expires_at" text null', + }); + await addColumnIfMissing(this, 'journey_share_tokens', 'view_count', { + sqlite: 'view_count INTEGER NOT NULL DEFAULT 0', + postgres: '"view_count" bigint not null default 0', + }); + await addColumnIfMissing(this, 'journey_share_tokens', 'last_viewed_at', { + sqlite: 'last_viewed_at DATETIME', + postgres: '"last_viewed_at" text null', + }); + } +} diff --git a/server/src/db/repositories/JourneyShareTokens.repository.ts b/server/src/db/repositories/JourneyShareTokens.repository.ts index 8dad2cb24..77872adbe 100644 --- a/server/src/db/repositories/JourneyShareTokens.repository.ts +++ b/server/src/db/repositories/JourneyShareTokens.repository.ts @@ -1,6 +1,10 @@ +import { currentTimestampKysely } from '../dialect/kysely-functions'; import type { JourneyShareTokens } from '../entities/JourneyShareTokens.entity'; +import type { DB } from '../kysely/db'; import { TrekRepository } from './_shared/trek-repository'; +type ShareTokensDB = Pick; + /** JS1's narrow projection — `createOrUpdateJourneyShareLink`'s existing-link read. */ export interface JourneyShareLinkFlagsRow { token: string; @@ -10,6 +14,9 @@ export interface JourneyShareLinkFlagsRow { newest_first: number; share_plan: number; share_recordings: number; + password_hash: string | null; + password_version: number; + expires_at: string | null; } /** JS4/JS11's full-row shape (`getJourneyShareLink`, `getPublicJourney`'s entrypoint read). */ @@ -25,6 +32,21 @@ export interface JourneyShareTokenRow { newest_first: number; share_plan: number; share_recordings: number; + /** The bcrypt hash of the link's password, null when anyone with the address may read. */ + password_hash: string | null; + /** Raised on every password change; the unlock cookie is signed over it. */ + password_version: number; + /** When the link stops working (canonical DATETIME text), null for never. */ + expires_at: string | null; + view_count: number; + last_viewed_at: string | null; +} + +/** A link's password and expiry, as stored. */ +export interface JourneyShareProtection { + password_hash: string | null; + password_version: number; + expires_at: string | null; } /** Every flag of a link, as stored (0/1). */ @@ -104,6 +126,9 @@ export class JourneyShareTokensRepository extends TrekRepository('get', false); @@ -121,9 +146,36 @@ export class JourneyShareTokensRepository extends TrekRepository { + await this.nativeUpdate({ journey: journeyId }, protection); + } + /** JS3 — the create branch: `INSERT INTO journey_share_tokens (journey_id, token, created_by, share_timeline, share_gallery, share_map, newest_first) VALUES (?,?,?,?,?,?,?)`. */ - async insertLink(journeyId: number, token: string, createdBy: number, flags: JourneyShareFlags): Promise { - await this.insert({ journey: journeyId, token, createdByRef: createdBy, ...flags }); + async insertLink( + journeyId: number, + token: string, + createdBy: number, + flags: JourneyShareFlags, + protection: JourneyShareProtection = { password_hash: null, password_version: 0, expires_at: null }, + ): Promise { + await this.insert({ journey: journeyId, token, createdByRef: createdBy, ...flags, ...protection }); + } + + /** + * One more reader opened the link: count it and remember when. A single + * statement, so two readers at once both count. + */ + async recordView(id: number): Promise { + const now = currentTimestampKysely(this.getEntityManager().getPlatform()); + await this.kysely() + .updateTable('journey_share_tokens') + .set((eb) => ({ view_count: eb('view_count', '+', 1), last_viewed_at: now })) + .where('id', '=', id) + .execute(); } /** JS4 — `getJourneyShareLink`: `SELECT * FROM journey_share_tokens WHERE journey_id = ?`. */ diff --git a/server/src/nest/common/validate-route-guards.ts b/server/src/nest/common/validate-route-guards.ts index 7e42ba23e..cd8f52db6 100644 --- a/server/src/nest/common/validate-route-guards.ts +++ b/server/src/nest/common/validate-route-guards.ts @@ -132,6 +132,7 @@ export const PUBLIC_ROUTE_ALLOW_LIST: string[] = [ 'JourneyPublicController.legacyPhoto', 'JourneyPublicController.mapLayers', 'JourneyPublicController.photo', + 'JourneyPublicController.unlock', // The booking mail webhook. A mail service holds no session; the HMAC over // the raw mail is the credential, and the route is a 404 unless the admin // made the webhook the import's transport and set its secret. diff --git a/server/src/nest/journey/journey-domain.module.ts b/server/src/nest/journey/journey-domain.module.ts index 1fa6e7bfe..58945b82b 100644 --- a/server/src/nest/journey/journey-domain.module.ts +++ b/server/src/nest/journey/journey-domain.module.ts @@ -23,6 +23,7 @@ import { JourneyPhotoLinksService } from './journey-photo-links.service'; import { JourneyRecordedDaysService } from './journey-recorded-days.service'; import { JourneyRecordingPrepService } from './journey-recording-prep.service'; import { JourneySettingsService } from './journey-settings.service'; +import { InMemoryJourneyShareViewStore, JourneyShareViewStore } from './journey-share-views.store'; import { JourneyShareService } from './journey-share.service'; import { MikroOrmModule } from '@mikro-orm/nestjs'; import { Module } from '@nestjs/common'; @@ -120,6 +121,8 @@ import { Module } from '@nestjs/common'; JourneySettingsService, JourneyPhotoLinksService, JourneyGalleryService, + // Who opened a share link today, for its view count: in memory, like the rate limits. + { provide: JourneyShareViewStore, useFactory: () => new InMemoryJourneyShareViewStore() }, ], exports: [ JourneyDomainService, diff --git a/server/src/nest/journey/journey-public.controller.ts b/server/src/nest/journey/journey-public.controller.ts index 7e6113638..58dc73f42 100644 --- a/server/src/nest/journey/journey-public.controller.ts +++ b/server/src/nest/journey/journey-public.controller.ts @@ -2,6 +2,7 @@ import { ADDON_IDS } from '../../addons'; import { AddonGuard } from '../addons/addon.guard'; import { RequireAddon } from '../addons/require-addon.decorator'; import { Public } from '../auth-core/public.decorator'; +import { RateLimitService } from '../common/rate-limit.service'; import { ResponseContract } from '../common/response-contract'; import { rowId } from '../common/row-id.pipe'; import { @@ -11,13 +12,19 @@ import { RENDITION_PENDING, } from '../memories/public-media.service'; import { StorageService } from '../storage/storage.service'; +import { JOURNEY_UNLOCK_COOKIE, unlockCookieOptions, unlockProofOf, viewerOf } from './journey-share-access'; +import { JourneyPublicUnlockDto } from './journey.dto'; import { JourneyService } from './journey.service'; -import { Controller, Get, HttpException, Param, Res, UseGuards } from '@nestjs/common'; -import { journeyPublicMapLayersResponseSchema, journeyPublicResponseSchema } from '@trek/shared'; +import { Body, Controller, Get, HttpCode, HttpException, Param, Post, Req, Res, UseGuards } from '@nestjs/common'; +import { journeyPublicMapLayersResponseSchema, journeyPublicResponseSchema, successResponseSchema } from '@trek/shared'; -import type { Response } from 'express'; +import type { Request, Response } from 'express'; import path from 'node:path'; +/** Wrong passwords one address may try on one link per window before a 429. */ +const UNLOCK_MAX_FAILURES = 10; +const UNLOCK_WINDOW_MS = 15 * 60 * 1000; + /** * The size a share link's photo route was asked for. Anything but the two * smaller renditions is the original, as it has always been; `preview` (#2874) @@ -42,6 +49,11 @@ function sharedPhotoKind(kind: string): 'thumbnail' | 'preview' | 'original' { * addon off is meant to take the feature away, and without it already-published * journeys stayed publicly readable while the authenticated surface went dark. * AddonGuard only reads addon state, so it is safe in front of a @Public route. + * + * 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. */ @Public('share-token validated: the whole point is a link that works without an account') @UseGuards(AddonGuard) @@ -52,6 +64,7 @@ export class JourneyPublicController { private readonly journey: JourneyService, private readonly storage: StorageService, private readonly publicMedia: PublicMediaService, + private readonly rl: RateLimitService, ) {} /** @@ -61,8 +74,9 @@ export class JourneyPublicController { */ @Get(':token') @ResponseContract(journeyPublicResponseSchema) - async get(@Param('token') token: string) { - const data = await this.journey.getPublicJourney(token); + 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)); if (!data) { throw new HttpException({ error: 'Not found' }, 404); } @@ -75,7 +89,8 @@ export class JourneyPublicController { */ @Get(':token/map-layers') @ResponseContract(journeyPublicMapLayersResponseSchema) - async mapLayers(@Param('token') token: string) { + async mapLayers(@Param('token') token: string, @Req() req: Request) { + await this.journey.assertPublicAccess(token, unlockProofOf(req)); const layers = await this.journey.getPublicMapLayers(token); if (!layers) { throw new HttpException({ error: 'Not found' }, 404); @@ -83,13 +98,48 @@ export class JourneyPublicController { return layers; } + /** + * A reader typed the link's password (#2553). The right one sets the unlock + * cookie, scoped to this link's routes, and answers `{ success: true }`; a + * link without a password answers the same and sets nothing. A wrong one is + * a 401 with its own `code`. + * + * Only refusals count against the limit (the attempt is given back once the + * password matched), per address and link, so a reader who typed it right + * once is never locked out by reloading, and nobody can guess at a link for + * long. + */ + @Post(':token/unlock') + @HttpCode(200) + @ResponseContract(successResponseSchema) + async unlock( + @Param('token') token: string, + @Body() body: JourneyPublicUnlockDto, + @Req() req: Request, + @Res({ passthrough: true }) res: Response, + ) { + const key = `${req.ip || 'unknown'}|${token}`; + const now = Date.now(); + if (!(await this.rl.check('journey_unlock', key, UNLOCK_MAX_FAILURES, UNLOCK_WINDOW_MS, now))) { + throw new HttpException({ error: 'Too many attempts. Please try again later.' }, 429); + } + const unlocked = await this.journey.unlockPublicLink(token, body.password); + await this.rl.release('journey_unlock', key, UNLOCK_WINDOW_MS, now); + if (unlocked) { + res.cookie(JOURNEY_UNLOCK_COOKIE, unlocked.proof, unlockCookieOptions(token, req, unlocked.expiresAt)); + } + return { success: true as const }; + } + @Get(':token/photos/:photoId/:kind') async photo( @Param('token') token: string, @Param('photoId', rowId('Not found')) photoId: number, @Param('kind') kind: string, @Res() res: Response, + @Req() req: Request, ): Promise { + await this.journey.assertPublicAccess(token, unlockProofOf(req)); const valid = await this.journey.validateShareTokenForPhoto(token, photoId); if (!valid) { throw new HttpException({ error: 'Not found' }, 404); @@ -104,7 +154,9 @@ export class JourneyPublicController { @Param('assetId') assetId: string, @Param('kind') kind: string, @Res() res: Response, + @Req() req: Request, ): Promise { + await this.journey.assertPublicAccess(token, unlockProofOf(req)); const valid = await this.journey.validateShareTokenForAsset(token, assetId); if (!valid) { throw new HttpException({ error: 'Not found' }, 404); diff --git a/server/src/nest/journey/journey-share-access.ts b/server/src/nest/journey/journey-share-access.ts new file mode 100644 index 000000000..1d6cde800 --- /dev/null +++ b/server/src/nest/journey/journey-share-access.ts @@ -0,0 +1,108 @@ +import { JWT_SECRET } from '../../config'; +import { parseDbTimestamp } from '../../db/types'; + +import bcrypt from 'bcryptjs'; +import type { CookieOptions, Request } from 'express'; +import { createHash, createHmac, timingSafeEqual } from 'node:crypto'; + +/** + * The pure half of a protected journey link (#2553): hashing and checking its + * password, the proof a reader's browser keeps once it typed the right one, + * the cookie that proof travels in, and whether the link ran out. + * + * Why a cookie: the shared page loads its photos through plain `` tags, + * which send no header of their own, so the proof has to ride along by itself. + * It is scoped to the link's own API path, so it reaches the journey's routes + * and its photo proxy and nothing else, and one browser can hold the proofs of + * several links side by side. + */ + +/** The unlock cookie. One name for every link; its path tells them apart. */ +export const JOURNEY_UNLOCK_COOKIE = 'trek_journey_unlock'; + +/** The same bcrypt cost the account passwords take (auth.helpers.ts BCRYPT_COST). */ +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; + +/** The password's hash for the link row. Async, so a hash never blocks the event loop. */ +export function hashSharePassword(password: string): Promise { + return bcrypt.hash(password, SHARE_PASSWORD_BCRYPT_COST); +} + +/** Whether `password` is the one the link was given. */ +export function checkSharePassword(password: string, hash: string): Promise { + return bcrypt.compare(password, hash); +} + +/** + * What a browser that typed the right password holds: an HMAC over the token + * and the link's password version, keyed with the server's session secret. It + * carries nothing a reader could turn back into the password, it is useless for + * any other link, and changing or removing the password (which raises the + * version) invalidates it. Rotating the session secret does too, which only + * means typing the password once more. + */ +export function unlockProof(token: string, passwordVersion: number): string { + return createHmac('sha256', JWT_SECRET).update(`journey-unlock:${token}:${passwordVersion}`).digest('base64url'); +} + +/** Whether `proof` unlocks the link, compared in constant time. */ +export function proofUnlocks(token: string, passwordVersion: number, proof: string | undefined): boolean { + if (!proof) return false; + const expected = Buffer.from(unlockProof(token, passwordVersion)); + const given = Buffer.from(proof); + return given.length === expected.length && timingSafeEqual(given, expected); +} + +/** Whether the link's expiry (stored DATETIME text) has passed at `now`. A link without one never runs out. */ +export function shareLinkExpired(expiresAt: string | null | undefined, now: Date = new Date()): boolean { + const at = parseDbTimestamp(expiresAt); + return at !== null && at.getTime() <= now.getTime(); +} + +/** The proof the request's browser sends for this link, if any. */ +export function unlockProofOf(req: Request): string | undefined { + const cookies = req.cookies as Record | undefined; + const value = cookies?.[JOURNEY_UNLOCK_COOKIE]; + return typeof value === 'string' ? value : undefined; +} + +/** + * The cookie options for a link's proof: only this link's API path, never + * readable from script, and kept no longer than the link lives. + * + * `Secure` follows the request alone. `req.secure` is true for HTTPS, and + * behind a reverse proxy for an `X-Forwarded-Proto: https` the trust-proxy + * setting lets through. A self-hoster reaching TREK over plain HTTP on the LAN + * gets a cookie the browser keeps, instead of one it drops and a password + * prompt that never goes away. + */ +export function unlockCookieOptions( + token: string, + req: Request, + expiresAt: string | null, + now: Date = new Date(), +): CookieOptions { + const until = parseDbTimestamp(expiresAt); + const maxAge = until ? Math.max(0, Math.min(UNLOCK_MAX_AGE_MS, until.getTime() - now.getTime())) : UNLOCK_MAX_AGE_MS; + return { + httpOnly: true, + secure: req.secure === true, + sameSite: 'lax', + path: `/api/public/journey/${encodeURIComponent(token)}`, + maxAge, + }; +} + +/** Who is asking, as far as the view count needs to tell readers apart: their address and browser. */ +export function viewerOf(req: Request): string { + const agent = typeof req.headers['user-agent'] === 'string' ? req.headers['user-agent'] : ''; + return `${req.ip ?? ''}|${agent}`; +} + +/** A reader of one link as the view store keeps them: hashed, so nothing held in memory names them. */ +export function viewKey(linkId: number, viewer: string): string { + return createHash('sha256').update(`${linkId}|${viewer}`).digest('base64url'); +} diff --git a/server/src/nest/journey/journey-share-views.store.ts b/server/src/nest/journey/journey-share-views.store.ts new file mode 100644 index 000000000..9167924bd --- /dev/null +++ b/server/src/nest/journey/journey-share-views.store.ts @@ -0,0 +1,52 @@ +/** + * Which readers already opened a public journey link today, so the owner's view + * count goes up once per reader and day rather than on every reload. + * + * A port, like RateLimitStore: in this process's memory today, which is right + * while TREK runs as one process. A restart forgets who was seen, so a reader + * who comes back the same day is counted again; the count is a quiet hint for + * the owner, not an audit, and that is the price of keeping nobody's address + * on disk. The method returns a promise because a shared store would live in + * the database or on the network. + */ +export abstract class JourneyShareViewStore { + /** + * True the first time `key` (a link and a reader, already hashed) is seen on + * the UTC day of `now`, false every time after that on the same day. + */ + abstract firstToday(key: string, now: Date): Promise; +} + +export class InMemoryJourneyShareViewStore extends JourneyShareViewStore { + private day = ''; + private readonly seen = new Set(); + + /** + * `cap` is the most readers one day keeps. Past it the day starts over, which + * counts a few readers twice instead of letting a crawler grow the set without end. + */ + constructor(private readonly cap = 50_000) { + super(); + } + + firstToday(key: string, now: Date): Promise { + return Promise.resolve(this.mark(key, now.toISOString().slice(0, 10))); + } + + /** How many readers today holds; only the tests look. */ + size(): number { + return this.seen.size; + } + + /** The day check and the mark, in one synchronous step so two readers cannot interleave. */ + private mark(key: string, day: string): boolean { + if (day !== this.day) { + this.day = day; + this.seen.clear(); + } + if (this.seen.has(key)) return false; + if (this.seen.size >= this.cap) this.seen.clear(); + this.seen.add(key); + return true; + } +} diff --git a/server/src/nest/journey/journey-share.service.ts b/server/src/nest/journey/journey-share.service.ts index 32ba23a93..1d3bd6719 100644 --- a/server/src/nest/journey/journey-share.service.ts +++ b/server/src/nest/journey/journey-share.service.ts @@ -9,16 +9,33 @@ import type { JourneyPublicEntryPhotoRow, } from '../../db/repositories/JourneyEntryPhotos.repository'; import type { JourneyPhotosRepository } from '../../db/repositories/JourneyPhotos.repository'; -import type { JourneyShareTokensRepository } from '../../db/repositories/JourneyShareTokens.repository'; +import type { + JourneyShareLinkFlagsRow, + JourneyShareProtection, + JourneyShareTokenRow, + JourneyShareTokensRepository, +} from '../../db/repositories/JourneyShareTokens.repository'; import type { JourneysRepository } from '../../db/repositories/Journeys.repository'; +import { dbNow, utcSuffix } from '../../db/types'; +import { logWarn } from '../audit/audit-log.logger'; +import { DomainError } from '../common/domain-error'; 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 { + checkSharePassword, + hashSharePassword, + proofUnlocks, + shareLinkExpired, + unlockProof, + viewKey, +} from './journey-share-access'; +import { JourneyShareViewStore } from './journey-share-views.store'; import { InjectRepository } from '@mikro-orm/nestjs'; import { Injectable } from '@nestjs/common'; -import type { JourneyPublicEntry, JourneyPublicResponse } from '@trek/shared'; +import { JOURNEY_PUBLIC_ERROR_CODES, type JourneyPublicEntry, type JourneyPublicResponse } from '@trek/shared'; import crypto from 'crypto'; @@ -32,6 +49,10 @@ interface JourneySharePermissions { share_plan?: boolean; /** The recorded days on the shared map (JRN-04); off unless asked for. */ share_recordings?: boolean; + /** A new password, or null to take it off; left out keeps the current one (#2553). */ + password?: string | null; + /** When the link stops working (ISO), or null for never; left out keeps the current one. */ + expires_at?: string | null; } interface JourneyShareTokenInfo { @@ -43,6 +64,40 @@ interface JourneyShareTokenInfo { newest_first: boolean; share_plan: boolean; share_recordings: boolean; + has_password: boolean; + expires_at: string | null; + view_count: number; + last_viewed_at: string | null; +} + +const NO_PROTECTION: JourneyShareProtection = { password_hash: null, password_version: 0, expires_at: null }; + +/** + * The password and expiry a save leaves on a link: what it was given, and what + * the link had for whatever it was not given, like the flags. Setting or + * taking off the password raises its version, which signs every reader who + * unlocked the old one out again. + */ +function resolveProtection( + existing: Pick, + permissions: JourneySharePermissions, + newHash: string | null | undefined, +): JourneyShareProtection { + const passwordGiven = newHash !== undefined; + let expiresAt = existing.expires_at; + if (permissions.expires_at === null) expiresAt = null; + else if (permissions.expires_at !== undefined) expiresAt = dbNow(new Date(permissions.expires_at)); + return { + password_hash: passwordGiven ? newHash : existing.password_hash, + password_version: passwordGiven ? existing.password_version + 1 : existing.password_version, + expires_at: expiresAt, + }; +} + +/** The hash a save asks for: undefined keeps the current password, null takes it off. */ +function hashFor(password: string | null | undefined): Promise { + if (password === undefined || password === null) return Promise.resolve(password); + return hashSharePassword(password); } /** @@ -82,6 +137,8 @@ export class JourneyShareService { // module change needed. @InjectRepository(JourneyEntries) private readonly entriesRepo: JourneyEntriesRepository, @InjectRepository(JourneyEntryPhotos) private readonly entryPhotosRepo: JourneyEntryPhotosRepository, + // Which readers already opened a link today, so each is counted once a day. + private readonly views: JourneyShareViewStore, ) {} async createOrUpdateJourneyShareLink( @@ -93,6 +150,10 @@ export class JourneyShareService { // able to publish the journey or change which screens are shared. if (!(await this.journey.isOwner(journeyId, createdBy))) return null; + // Hashed before the transaction: bcrypt takes a noticeable moment on + // purpose, and the transaction holds the database's write lock. + const newHash = await hashFor(permissions.password); + // L1 (rule 11/24) — the existing-link read and the insert below are // separate awaits, so two concurrent first-creates for the same journey // could both read "no link yet" and both try to insert: the loser hits @@ -126,6 +187,11 @@ export class JourneyShareService { share_plan: share_plan ? 1 : 0, share_recordings: share_recordings ? 1 : 0, }); + // The same "keep what was not given" rule for the password and the + // expiry: saving a switch never takes either off. + if (newHash !== undefined || permissions.expires_at !== undefined) { + await this.shareTokensRepo.updateProtection(journeyId, resolveProtection(existing, permissions, newHash)); + } return { token: existing.token, created: false }; } @@ -140,14 +206,20 @@ export class JourneyShareService { const token = crypto.randomBytes(24).toString('base64url'); // JS3. - await this.shareTokensRepo.insertLink(journeyId, token, createdBy, { - share_timeline: share_timeline ? 1 : 0, - share_gallery: share_gallery ? 1 : 0, - share_map: share_map ? 1 : 0, - newest_first: newest_first ? 1 : 0, - share_plan: share_plan ? 1 : 0, - share_recordings: share_recordings ? 1 : 0, - }); + await this.shareTokensRepo.insertLink( + journeyId, + token, + createdBy, + { + share_timeline: share_timeline ? 1 : 0, + share_gallery: share_gallery ? 1 : 0, + share_map: share_map ? 1 : 0, + newest_first: newest_first ? 1 : 0, + share_plan: share_plan ? 1 : 0, + share_recordings: share_recordings ? 1 : 0, + }, + resolveProtection(NO_PROTECTION, permissions, newHash), + ); return { token, created: true }; }); } @@ -183,6 +255,12 @@ export class JourneyShareService { newest_first: !!row.newest_first, share_plan: !!row.share_plan, share_recordings: !!row.share_recordings, + // Whether there is a password, never the hash: the owner sets a new one + // rather than reading the old one back. + has_password: !!row.password_hash, + expires_at: utcSuffix(row.expires_at), + view_count: row.view_count, + last_viewed_at: utcSuffix(row.last_viewed_at), }; } @@ -193,6 +271,55 @@ export class JourneyShareService { return true; } + /** + * The gate in front of every public route of a link (#2553): it exists, it + * has not run out, and when it has a password, the browser holds the proof + * of having typed it. Refuses with 404 for an unknown token (as every public + * route always has), 410 for an expired link and 401 for a locked one, each + * with its own `code` so the page knows what to show. + * + * The expiry is checked first: a link that is gone stays gone whatever + * password a reader knows. + */ + async assertPublicAccess(token: string, proof: string | undefined): Promise { + const row = await this.openLink(token); + if (row.password_hash && !proofUnlocks(token, row.password_version, proof)) { + throw new DomainError(401, 'Password required', { + details: { code: JOURNEY_PUBLIC_ERROR_CODES.locked }, + }); + } + return row; + } + + /** + * A reader typed the link's password. Answers the proof their browser keeps + * (the caller puts it in the link's cookie), or null for a link that has no + * password, where there is nothing to unlock. A wrong password is a 401 with + * its own `code`; an unknown or expired link refuses as the reads do. + */ + async unlockPublicLink(token: string, password: string): Promise<{ proof: string; expiresAt: string | null } | null> { + const row = await this.openLink(token); + if (!row.password_hash) return null; + if (!(await checkSharePassword(password, row.password_hash))) { + throw new DomainError(401, 'Wrong password', { + details: { code: JOURNEY_PUBLIC_ERROR_CODES.denied }, + }); + } + return { proof: unlockProof(token, row.password_version), expiresAt: row.expires_at }; + } + + /** The link a public request names, refused when there is none (404) or it ran out (410). */ + private async openLink(token: string): Promise { + const row = await this.shareTokensRepo.findByToken(token); + if (!row) throw new DomainError(404, 'Not found'); + if (shareLinkExpired(row.expires_at)) { + throw new DomainError(410, 'This link has expired', { + details: { code: JOURNEY_PUBLIC_ERROR_CODES.expired }, + }); + } + return row; + } + async validateShareTokenForPhoto( token: string, photoId: number, @@ -233,7 +360,11 @@ export class JourneyShareService { return { ownerId: photo.owner_id || photo.journey_owner_id }; } - async getPublicJourney(token: string): Promise { + /** + * The shared journey. `viewer` (address and browser, see `viewerOf`) is who + * opened it, for the owner's view count; left out, nothing is counted. + */ + async getPublicJourney(token: string, viewer?: string): Promise { // JS11 — exact-match token lookup, no LIKE/COLLATE (R4). const row = await this.shareTokensRepo.findByToken(token); if (!row) return null; @@ -242,6 +373,8 @@ 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); @@ -325,4 +458,23 @@ export class JourneyShareService { }, }; } + + /** + * One reader opened the link: count them once a day (#2959, #2553). Only the + * payload read counts, never a photo or the map layers it pulls in after. + * + * This is the one write a public GET makes, and it is deliberately one that + * cannot change what anybody reads. A count that fails is logged and the + * reader still gets the journey. + * + * @txStandalone a counter bumped in one statement, independent of the read around it. + */ + private async countView(linkId: number, viewer: string): Promise { + try { + if (!(await this.views.firstToday(viewKey(linkId, viewer), new Date()))) return; + await this.shareTokensRepo.recordView(linkId); + } catch (err) { + logWarn(`[journey-share] the view of link ${linkId} could not be counted: ${(err as Error).message}`); + } + } } diff --git a/server/src/nest/journey/journey.controller.ts b/server/src/nest/journey/journey.controller.ts index d372b9a2b..c115c987e 100644 --- a/server/src/nest/journey/journey.controller.ts +++ b/server/src/nest/journey/journey.controller.ts @@ -860,6 +860,9 @@ export class JourneyController { newest_first: body.newest_first as boolean | undefined, share_plan: body.share_plan, share_recordings: body.share_recordings, + // Left out keeps what the link has, null takes it off (#2553). + password: body.password, + expires_at: body.expires_at, }); if (!result) { throw new HttpException({ error: 'Not allowed' }, 403); diff --git a/server/src/nest/journey/journey.dto.ts b/server/src/nest/journey/journey.dto.ts index be45466f0..98797d5d0 100644 --- a/server/src/nest/journey/journey.dto.ts +++ b/server/src/nest/journey/journey.dto.ts @@ -13,6 +13,7 @@ import { journeyPhotosMoveRequestSchema, journeyPreferencesRequestSchema, journeyProviderPhotosRequestSchema, + journeyPublicUnlockRequestSchema, journeyReorderEntriesRequestSchema, journeyReorderEntryPhotosRequestSchema, journeyShareLinkRequestSchema, @@ -50,6 +51,8 @@ export class JourneyContributorAddDto extends createZodDto(journeyContributorReq export class JourneyContributorUpdateDto extends createZodDto(journeyContributorUpdateRequestSchema) {} export class JourneyPreferencesDto extends createZodDto(journeyPreferencesRequestSchema) {} export class JourneyShareLinkDto extends createZodDto(journeyShareLinkRequestSchema) {} +/** The password a reader typed for a protected public link (#2553): strict, a new route. */ +export class JourneyPublicUnlockDto extends createZodDto(journeyPublicUnlockRequestSchema) {} export class JourneyProviderPhotosDto extends createZodDto(journeyProviderPhotosRequestSchema) {} export class JourneyLinkPhotoDto extends createZodDto(journeyLinkPhotoRequestSchema) {} export class JourneyPhotoUpdateDto extends createZodDto(journeyPhotoUpdateRequestSchema) {} diff --git a/server/src/nest/journey/journey.mcp.ts b/server/src/nest/journey/journey.mcp.ts index 0d4a6a7be..b835bb1c8 100644 --- a/server/src/nest/journey/journey.mcp.ts +++ b/server/src/nest/journey/journey.mcp.ts @@ -677,7 +677,8 @@ export class JourneyMcp { @Tool({ name: 'get_journey_share_link', - description: 'Get the current public share link for a journey. Owner only. Returns null if none exists.', + description: + 'Get the current public share link for a journey. Owner only. Returns null if none exists. has_password says whether readers must enter a password (the password itself is never returned); expires_at is when the link stops working (null: never); view_count counts readers once a day.', inputSchema: { journeyId: idSchema }, annotations: TOOL_ANNOTATIONS_READONLY, when: journeyAddonOn, @@ -694,7 +695,7 @@ export class JourneyMcp { @Tool({ name: 'create_journey_share_link', description: - 'Create or update the public share link for a journey. Owner only. Flags left out keep their current value on an existing link; a new link defaults to timeline/gallery/map on and plan/recordings off. share_plan puts the planned places and GPX tracks on the shared map, share_recordings the recorded days that have a published entry and the stays of published entries; neither shows anything while share_map is off.', + 'Create or update the public share link for a journey. Owner only. Flags left out keep their current value on an existing link; a new link defaults to timeline/gallery/map on and plan/recordings off. share_plan puts the planned places and GPX tracks on the shared map, share_recordings the recorded days that have a published entry and the stays of published entries; neither shows anything while share_map is off. password (4 to 72 characters) makes readers enter it before the link shows anything, null removes it; expires_at (ISO timestamp) is when the link stops working, null means never. Both keep their current value when left out; changing or removing the password signs out every reader who unlocked the old one.', inputSchema: { journeyId: idSchema, share_timeline: z.boolean().optional(), @@ -703,6 +704,8 @@ export class JourneyMcp { newest_first: z.boolean().optional(), share_plan: journeyShareLinkRequestSchema.shape.share_plan, share_recordings: journeyShareLinkRequestSchema.shape.share_recordings, + password: journeyShareLinkRequestSchema.shape.password, + expires_at: journeyShareLinkRequestSchema.shape.expires_at, }, annotations: TOOL_ANNOTATIONS_WRITE, when: journeyAddonOn, @@ -720,6 +723,8 @@ export class JourneyMcp { newest_first?: boolean; share_plan?: boolean; share_recordings?: boolean; + password?: string | null; + expires_at?: string | null; }, ctx: McpContext, ) { diff --git a/server/src/nest/journey/journey.module.ts b/server/src/nest/journey/journey.module.ts index 8e8de9a4a..902e2af10 100644 --- a/server/src/nest/journey/journey.module.ts +++ b/server/src/nest/journey/journey.module.ts @@ -1,6 +1,7 @@ import { Users } from '../../db/entities/Users.entity'; import { AddonsModule } from '../addons/addons.module'; import { AppConfigModule } from '../app-config/app-config.module'; +import { RateLimitModule } from '../common/rate-limit.module'; import { UserConnectionRepositoriesModule } from '../database/user-connection-repositories.module'; import { AllowedFileTypesModule } from '../files/allowed-file-types.module'; import { AllowedFileTypesService } from '../files/allowed-file-types.service'; @@ -44,6 +45,8 @@ import { MulterModule } from '@nestjs/platform-express'; }), StorageModule, AddonsModule, + // The public unlock route counts wrong passwords per address and link (#2553). + RateLimitModule, // RuntimeEnvService: the controller refuses the demo account's uploads in demo mode. AppConfigModule, MemoriesModule, diff --git a/server/src/nest/journey/journey.service.ts b/server/src/nest/journey/journey.service.ts index db4772186..51fb589d4 100644 --- a/server/src/nest/journey/journey.service.ts +++ b/server/src/nest/journey/journey.service.ts @@ -171,8 +171,16 @@ export class JourneyService { } // Public (share-token) access — no auth, validated by token. - async getPublicJourney(token: string) { - return this.share.getPublicJourney(token); + /** The gate in front of every public route of a link: 404, 410 or 401 (#2553). */ + assertPublicAccess(token: string, proof: string | undefined) { + return this.share.assertPublicAccess(token, proof); + } + /** A reader's password for a protected link: the proof for their cookie, or null when there is no password. */ + unlockPublicLink(token: string, password: string) { + return this.share.unlockPublicLink(token, password); + } + async getPublicJourney(token: string, viewer?: string) { + return this.share.getPublicJourney(token, viewer); } getPublicMapLayers(token: string) { return this.map.publicMapLayers(token); diff --git a/server/tests/e2e/journey-public-link.e2e.test.ts b/server/tests/e2e/journey-public-link.e2e.test.ts new file mode 100644 index 000000000..8f650b72f --- /dev/null +++ b/server/tests/e2e/journey-public-link.e2e.test.ts @@ -0,0 +1,215 @@ +/** + * A protected public journey link, end to end (#2553, #1702, #2959): the + * whole app (buildApp, the real guards, share service and rate limit on a + * migrated temp SQLite) between the owner who sets a password and an expiry + * and the reader who opens the link. Every public route refuses a locked link, + * the unlock sets a cookie scoped to the link's own path, a changed password + * locks the old cookie out again, an expired link answers 410, saving a switch + * keeps the protection, and readers are counted once a day for the owner only. + */ +import { buildApp } from '../../src/bootstrap'; +import { JourneyShareTokens } from '../../src/db/entities/JourneyShareTokens.entity'; +import { makeJourney } from '../helpers/factories/journeys'; +import { findRow } from '../helpers/factories/rows'; +import { setAddonEnabled } from '../helpers/factories/settings'; +import { makeUser } from '../helpers/factories/users'; +import { resetRateLimits } from '../helpers/test-db'; +import { sessionCookie } from './harness'; +import { MikroORM } from '@mikro-orm/core'; +import type { INestApplication } from '@nestjs/common'; + +import type { Server } from 'node:http'; +import request from 'supertest'; +import { afterAll, beforeAll, beforeEach, describe, expect, it } from 'vitest'; + +let app: INestApplication; +let orm: MikroORM; +let server: Server; + +beforeAll(async () => { + app = await buildApp(); + orm = app.get(MikroORM); + server = app.getHttpServer() as Server; + await setAddonEnabled(orm, 'journey', true); +}, 60_000); + +beforeEach(async () => { + await resetRateLimits(app); +}); + +afterAll(async () => { + await app?.close(); +}); + +/** A journey with a share link the owner saved with `body`; answers the owner and the token. */ +async function sharedJourney(body: Record = {}) { + const { user: owner } = await makeUser(orm); + const journey = await makeJourney(orm, owner.id); + const res = await request(server) + .post(`/api/journeys/${journey.id}/share-link`) + .set('Cookie', sessionCookie(owner.id)) + .send(body); + expect(res.status).toBe(200); + return { owner, journey, token: res.body.token as string }; +} + +/** The share link as its owner reads it. */ +function ownerReads(journeyId: number, ownerId: number) { + return request(server).get(`/api/journeys/${journeyId}/share-link`).set('Cookie', sessionCookie(ownerId)); +} + +/** The `name=value` of the unlock cookie a response set, and the whole header line. */ +function unlockCookie(res: request.Response): { pair: string; line: string } { + const lines = ([] as string[]).concat(res.headers['set-cookie'] ?? []); + const line = lines.find((l) => l.startsWith('trek_journey_unlock=')) ?? ''; + return { pair: line.split(';')[0] ?? '', line }; +} + +describe('a journey link with a password', () => { + it('JPUBLINK-E2E-001: every public route refuses until the right password is typed', async () => { + const { owner, journey, token } = await sharedJourney({ password: 'secret1' }); + + const read = await ownerReads(journey.id, owner.id); + expect(read.body.link).toMatchObject({ has_password: true, expires_at: null, view_count: 0 }); + expect(JSON.stringify(read.body)).not.toContain('$2'); + + const locked = { error: 'Password required', code: 'JOURNEY_PASSWORD_REQUIRED' }; + for (const path of ['', '/map-layers', '/photos/1/thumbnail', '/photo/local/a.jpg/1/original']) { + const res = await request(server).get(`/api/public/journey/${token}${path}`); + expect(res.status, path).toBe(401); + expect(res.body, path).toEqual(locked); + } + + const wrong = await request(server).post(`/api/public/journey/${token}/unlock`).send({ password: 'nope' }); + expect(wrong.status).toBe(401); + expect(wrong.body).toEqual({ error: 'Wrong password', code: 'JOURNEY_PASSWORD_INVALID' }); + expect(unlockCookie(wrong).line).toBe(''); + + const right = await request(server).post(`/api/public/journey/${token}/unlock`).send({ password: 'secret1' }); + expect(right.status).toBe(200); + expect(right.body).toEqual({ success: true }); + const { pair, line } = unlockCookie(right); + expect(line).toContain(`Path=/api/public/journey/${token}`); + expect(line).toContain('HttpOnly'); + expect(line).toContain('SameSite=Lax'); + // Plain HTTP: a Secure cookie would be dropped and the reader locked out for good. + expect(line).not.toContain('Secure'); + + const open = await request(server).get(`/api/public/journey/${token}`).set('Cookie', pair); + expect(open.status).toBe(200); + 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); + }); + + it('JPUBLINK-E2E-002: a new password locks out the browsers that unlocked the old one', async () => { + const { owner, journey, token } = await sharedJourney({ password: 'secret1' }); + const right = await request(server).post(`/api/public/journey/${token}/unlock`).send({ password: 'secret1' }); + const { pair } = unlockCookie(right); + + await request(server) + .post(`/api/journeys/${journey.id}/share-link`) + .set('Cookie', sessionCookie(owner.id)) + .send({ password: 'secret2' }); + + expect((await request(server).get(`/api/public/journey/${token}`).set('Cookie', pair)).status).toBe(401); + }); + + 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}` }); + expect(res.status).toBe(401); + } + const limited = await request(server).post(`/api/public/journey/${token}/unlock`).send({ password: 'secret1' }); + expect(limited.status).toBe(429); + + // Another link is counted on its own. + const other = await sharedJourney({ password: 'secret9' }); + const fine = await request(server).post(`/api/public/journey/${other.token}/unlock`).send({ password: 'secret9' }); + expect(fine.status).toBe(200); + }); + + it('JPUBLINK-E2E-004: a bad unlock body is a 400, an unknown link a 404', async () => { + const { token } = await sharedJourney({ password: 'secret1' }); + expect((await request(server).post(`/api/public/journey/${token}/unlock`).send({})).status).toBe(400); + expect((await request(server).post('/api/public/journey/nope/unlock').send({ password: 'x' })).status).toBe(404); + }); + + it('JPUBLINK-E2E-005: the owner refuses a password too short for the contract', async () => { + const { owner, journey } = await sharedJourney(); + const res = await request(server) + .post(`/api/journeys/${journey.id}/share-link`) + .set('Cookie', sessionCookie(owner.id)) + .send({ password: 'abc' }); + expect(res.status).toBe(400); + }); +}); + +describe('a journey link with an expiry', () => { + it('JPUBLINK-E2E-010: works until its date, then every route answers 410', async () => { + const { owner, journey, token } = await sharedJourney({ expires_at: '2099-01-01T00:00:00Z' }); + expect((await request(server).get(`/api/public/journey/${token}`)).status).toBe(200); + + await request(server) + .post(`/api/journeys/${journey.id}/share-link`) + .set('Cookie', sessionCookie(owner.id)) + .send({ expires_at: '2020-01-01T00:00:00Z' }); + + const gone = { error: 'This link has expired', code: 'JOURNEY_LINK_EXPIRED' }; + for (const path of ['', '/map-layers', '/photos/1/thumbnail']) { + const res = await request(server).get(`/api/public/journey/${token}${path}`); + expect(res.status, path).toBe(410); + expect(res.body, path).toEqual(gone); + } + const unlock = await request(server).post(`/api/public/journey/${token}/unlock`).send({ password: 'x' }); + expect(unlock.status).toBe(410); + }); + + it('JPUBLINK-E2E-011: saving a switch keeps the password and the expiry', async () => { + const { owner, journey, token } = await sharedJourney({ password: 'secret1', expires_at: '2099-01-01T00:00:00Z' }); + + await request(server) + .post(`/api/journeys/${journey.id}/share-link`) + .set('Cookie', sessionCookie(owner.id)) + .send({ share_timeline: true, share_gallery: false, share_map: true }); + + const read = await ownerReads(journey.id, owner.id); + expect(read.body.link).toMatchObject({ + share_gallery: false, + has_password: true, + expires_at: '2099-01-01T00:00:00Z', + }); + expect((await request(server).get(`/api/public/journey/${token}`)).status).toBe(401); + }); + + it('JPUBLINK-E2E-012: an existing link, saved before protection existed, stays open', async () => { + const { token } = await sharedJourney(); + const row = await findRow(orm, JourneyShareTokens, { token }); + expect(row).toMatchObject({ password_hash: null, password_version: 0, expires_at: null }); + expect((await request(server).get(`/api/public/journey/${token}`)).status).toBe(200); + }); +}); + +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 () => { + 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'); + + const read = await ownerReads(journey.id, owner.id); + expect(read.body.link.view_count).toBe(2); + expect(read.body.link.last_viewed_at).toMatch(/Z$/); + + const publicBody = await request(server).get(`/api/public/journey/${token}`); + expect(JSON.stringify(publicBody.body)).not.toContain('view_count'); + }); + + 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 findRow(orm, JourneyShareTokens, { token }))?.view_count).toBe(0); + }); +}); diff --git a/server/tests/e2e/journey.e2e.test.ts b/server/tests/e2e/journey.e2e.test.ts index f7097f4bc..491d47e4f 100644 --- a/server/tests/e2e/journey.e2e.test.ts +++ b/server/tests/e2e/journey.e2e.test.ts @@ -128,7 +128,8 @@ const { gallerysvc } = vi.hoisted(() => ({ const { backfillRun, backfillSchedule } = vi.hoisted(() => ({ backfillRun: vi.fn(), backfillSchedule: vi.fn() })); const { sharesvc } = vi.hoisted(() => ({ - sharesvc: { getPublicJourney: vi.fn(), validateShareTokenForAsset: vi.fn() }, + // assertPublicAccess resolves: these cases are about the routes, the gate (#2553) has its own suite. + sharesvc: { getPublicJourney: vi.fn(), validateShareTokenForAsset: vi.fn(), assertPublicAccess: vi.fn() }, })); // What the share service answers for a link with every section on: the route diff --git a/server/tests/unit/db/journey-share-protection-migration.test.ts b/server/tests/unit/db/journey-share-protection-migration.test.ts new file mode 100644 index 000000000..c9a4ae40c --- /dev/null +++ b/server/tests/unit/db/journey-share-protection-migration.test.ts @@ -0,0 +1,91 @@ +/** + * `Migration20200101046620_a_journey_link_can_ask_for_a_password_and_run_out`: + * the password, expiry and view-count columns on `journey_share_tokens`. + * Migrate to the step before it with a published journey already there, apply + * just this one, and check that the existing link comes through unprotected, + * never expiring and uncounted, with every flag it had. On Postgres the same + * step runs in the Postgres lane, where PARITY-PG holds the migrated columns to + * the entity. + */ +import { createMigrationOrm, migrateTo, pendingNames, rawExec, rawQuery } from '../../helpers/migration-step'; + +import { describe, expect, it } from 'vitest'; + +const TARGET = 'Migration20200101046620_a_journey_link_can_ask_for_a_password_and_run_out'; + +describe('journey_share_tokens protection migration', () => { + it('JSHAREPROT-MIG-001: adds the columns and leaves an existing link open, unexpiring and uncounted', async () => { + const orm = await createMigrationOrm(); + try { + const names = await pendingNames(orm); + const idx = names.indexOf(TARGET); + expect(idx).toBeGreaterThan(0); + const previous = names[idx - 1]; + 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 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)", + ); + + await migrateTo(orm, TARGET); + + const columns = await rawQuery<{ name: string; type: string; notnull: number; dflt_value: string | null }>( + orm, + "SELECT name, type, \"notnull\", dflt_value FROM pragma_table_info('journey_share_tokens') WHERE name IN ('password_hash', 'password_version', 'expires_at', 'view_count', 'last_viewed_at') ORDER BY cid", + ); + expect(columns).toEqual([ + { name: 'password_hash', type: 'TEXT', notnull: 0, dflt_value: null }, + { name: 'password_version', type: 'INTEGER', notnull: 1, dflt_value: '0' }, + { name: 'expires_at', type: 'DATETIME', notnull: 0, dflt_value: null }, + { name: 'view_count', type: 'INTEGER', notnull: 1, dflt_value: '0' }, + { name: 'last_viewed_at', type: 'DATETIME', notnull: 0, dflt_value: null }, + ]); + expect( + await rawQuery( + orm, + 'SELECT token, share_timeline, share_gallery, share_map, share_plan, password_hash, password_version, expires_at, view_count, last_viewed_at FROM journey_share_tokens WHERE id = 9', + ), + ).toEqual([ + { + token: 'tok', + share_timeline: 1, + share_gallery: 0, + share_map: 1, + share_plan: 1, + password_hash: null, + password_version: 0, + expires_at: null, + view_count: 0, + last_viewed_at: null, + }, + ]); + } finally { + await orm.close(true); + } + }); + + it('JSHAREPROT-MIG-002: running it on a database that already has the columns changes nothing', async () => { + const orm = await createMigrationOrm(); + try { + const names = await pendingNames(orm); + const previous = names[names.indexOf(TARGET) - 1]; + if (!previous) throw new Error('no step before the target'); + await migrateTo(orm, previous); + // A development build that added one of them by hand already. + await rawExec(orm, 'ALTER TABLE journey_share_tokens ADD COLUMN view_count INTEGER NOT NULL DEFAULT 0'); + + await migrateTo(orm, TARGET); + + const columns = await rawQuery<{ name: string }>( + orm, + "SELECT name FROM pragma_table_info('journey_share_tokens') WHERE name = 'view_count'", + ); + expect(columns).toHaveLength(1); + } finally { + await orm.close(true); + } + }); +}); diff --git a/server/tests/unit/db/legacy-baseline.test.ts b/server/tests/unit/db/legacy-baseline.test.ts index 2956fc9bb..01f6ced3a 100644 --- a/server/tests/unit/db/legacy-baseline.test.ts +++ b/server/tests/unit/db/legacy-baseline.test.ts @@ -127,6 +127,7 @@ const UNNUMBERED = [ 'Migration20200101046590_a_place_carries_the_tags_of_its_lists_and_trips', 'Migration20200101046600_a_list_tour_link_keeps_its_full_unique_name', 'Migration20200101046610_a_vote_remembers_when_it_last_changed', + 'Migration20200101046620_a_journey_link_can_ask_for_a_password_and_run_out', ]; // The last step the positional runner ever had; planLegacyBaseline refuses a // schema_version past it. diff --git a/server/tests/unit/db/nul-free.test.ts b/server/tests/unit/db/nul-free.test.ts index 74c57a779..ef654d200 100644 --- a/server/tests/unit/db/nul-free.test.ts +++ b/server/tests/unit/db/nul-free.test.ts @@ -255,6 +255,7 @@ const NOT_HASHED: Record = { oidc_client_secret: 'stored encrypted and sent to the OIDC provider', mail_ingest_webhook_secret: 'compared with the secret a mail webhook presents', secret: "a plugin setting's flag that marks a field as secret", + has_password: 'a flag in the journey share link answer saying whether the link asks for a password', }; /** The object keys named like a secret in `files` and in the TypeScript under `dir` (specs and locales left out). */ diff --git a/server/tests/unit/db/repositories/JourneyShareTokens.repository.test.ts b/server/tests/unit/db/repositories/JourneyShareTokens.repository.test.ts new file mode 100644 index 000000000..cd6698e08 --- /dev/null +++ b/server/tests/unit/db/repositories/JourneyShareTokens.repository.test.ts @@ -0,0 +1,99 @@ +/** + * `JourneyShareTokensRepository`, the protection of a public journey link + * (#2553): a new link is open and never expires unless told otherwise, the + * password and the expiry are written as the service resolved them and read + * back with the flags, and a view is counted in one statement. + */ +import { JourneyShareTokens } from '../../../../src/db/entities/JourneyShareTokens.entity'; +import type { JourneyShareTokensRepository } from '../../../../src/db/repositories/JourneyShareTokens.repository'; +import { createSnapshotTestDb } from '../../../helpers/db-mock'; +import { makeJourney } from '../../../helpers/factories/journeys'; +import { findRow } from '../../../helpers/factories/rows'; +import { makeUser } from '../../../helpers/factories/users'; +import { resetTestDb } from '../../../helpers/test-db'; +import { createTestOrm, type TestOrm } from '../../../helpers/test-orm'; + +import { afterAll, beforeAll, beforeEach, describe, expect, it } from 'vitest'; + +const testDb = createSnapshotTestDb(); +let t: TestOrm; +let links: JourneyShareTokensRepository; + +const FLAGS = { share_timeline: 1, share_gallery: 1, share_map: 0, newest_first: 0, share_plan: 0, share_recordings: 0 }; + +beforeAll(async () => { + t = await createTestOrm(testDb); + links = t.repo(JourneyShareTokens); +}); +beforeEach(() => { + resetTestDb(testDb); + t.clear(); +}); +afterAll(async () => { + await t.close(); + testDb.close(); +}); + +async function journeyOf() { + const { user } = await makeUser(t); + const journey = await makeJourney(t, user.id); + return { user, journey }; +} + +describe('JourneyShareTokensRepository protection', () => { + it('JSHARE-REPO-001: a link inserted without protection is open, never expires and has no views', async () => { + const { user, journey } = await journeyOf(); + await links.insertLink(journey.id, 'tok-open', user.id, FLAGS); + + expect(await links.findByToken('tok-open')).toMatchObject({ + password_hash: null, + password_version: 0, + expires_at: null, + view_count: 0, + last_viewed_at: null, + }); + expect(await links.findFlagsByJourneyId(journey.id)).toMatchObject({ + token: 'tok-open', + password_hash: null, + password_version: 0, + expires_at: null, + }); + }); + + it('JSHARE-REPO-002: inserts and updates the password and the expiry as given, leaving the flags alone', async () => { + const { user, journey } = await journeyOf(); + await links.insertLink(journey.id, 'tok-locked', user.id, FLAGS, { + password_hash: '$2b$12$hash', + password_version: 1, + expires_at: '2099-01-01 00:00:00', + }); + expect(await links.findFlagsByJourneyId(journey.id)).toMatchObject({ + share_map: 0, + password_hash: '$2b$12$hash', + password_version: 1, + expires_at: '2099-01-01 00:00:00', + }); + + await links.updateProtection(journey.id, { password_hash: null, password_version: 2, expires_at: null }); + const row = await findRow(t, JourneyShareTokens, { token: 'tok-locked' }); + expect(row).toMatchObject({ password_hash: null, password_version: 2, expires_at: null, share_timeline: 1 }); + }); + + it('JSHARE-REPO-003: a view adds one and stamps the time; another link is left alone', async () => { + const { user, journey } = await journeyOf(); + const other = await journeyOf(); + await links.insertLink(journey.id, 'tok-a', user.id, FLAGS); + await links.insertLink(other.journey.id, 'tok-b', other.user.id, FLAGS); + const a = await links.findByToken('tok-a'); + if (!a) throw new Error('no link'); + + await links.recordView(a.id); + await links.recordView(a.id); + + t.clear(); + const after = await links.findByToken('tok-a'); + expect(after?.view_count).toBe(2); + expect(after?.last_viewed_at).toMatch(/^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}$/); + expect(await links.findByToken('tok-b')).toMatchObject({ view_count: 0, last_viewed_at: null }); + }); +}); diff --git a/server/tests/unit/mcp/tools-journey.test.ts b/server/tests/unit/mcp/tools-journey.test.ts index 2367196d0..fd87fc752 100644 --- a/server/tests/unit/mcp/tools-journey.test.ts +++ b/server/tests/unit/mcp/tools-journey.test.ts @@ -1428,6 +1428,47 @@ describe('journey share-link tools', () => { }); }); + it('sets a password and an expiry like the REST route, and reads back has_password, never the hash (#2553)', async () => { + const { user } = await makeUser(orm); + await withHarness(user.id, async (h) => { + const journey = await seedJourney(h); + await h.client.callTool({ + name: 'create_journey_share_link', + arguments: { journeyId: journey.id, password: 'secret1', expires_at: '2099-01-01T00:00:00Z' }, + }); + // A later call without them, flipping one switch, keeps both. + await h.client.callTool({ + name: 'create_journey_share_link', + arguments: { journeyId: journey.id, share_map: false }, + }); + const read = parseToolResult( + await h.client.callTool({ name: 'get_journey_share_link', arguments: { journeyId: journey.id } }), + ) as any; + expect(read.shareLink.has_password).toBe(true); + expect(read.shareLink.expires_at).toBe('2099-01-01T00:00:00Z'); + expect(read.shareLink.share_map).toBe(false); + expect(JSON.stringify(read)).not.toContain('password_hash'); + expect(JSON.stringify(read)).not.toContain('secret1'); + + await h.client.callTool({ + name: 'create_journey_share_link', + arguments: { journeyId: journey.id, password: null, expires_at: null }, + }); + const cleared = parseToolResult( + await h.client.callTool({ name: 'get_journey_share_link', arguments: { journeyId: journey.id } }), + ) as any; + expect(cleared.shareLink.has_password).toBe(false); + expect(cleared.shareLink.expires_at).toBeNull(); + + // The same bounds as REST: a three-letter password is refused. + const short = await h.client.callTool({ + name: 'create_journey_share_link', + arguments: { journeyId: journey.id, password: 'abc' }, + }); + expect(short.isError).toBe(true); + }); + }); + it('get_journey_share_link is owner-only, like create and delete', async () => { const { user: owner } = await makeUser(orm); const { user: guest } = await makeUser(orm); diff --git a/server/tests/unit/nest/journey-share.service.test.ts b/server/tests/unit/nest/journey-share.service.test.ts index 6a630e83f..2a75a69dc 100644 --- a/server/tests/unit/nest/journey-share.service.test.ts +++ b/server/tests/unit/nest/journey-share.service.test.ts @@ -15,6 +15,8 @@ import type { JourneyEntriesRepository } from '../../../src/db/repositories/Jour import type { JourneyEntryPhotosRepository } from '../../../src/db/repositories/JourneyEntryPhotos.repository'; import type { JourneyShareTokensRepository } from '../../../src/db/repositories/JourneyShareTokens.repository'; import { JourneyDomainService } from '../../../src/nest/journey/journey-domain.service'; +import { unlockProof } from '../../../src/nest/journey/journey-share-access'; +import { InMemoryJourneyShareViewStore } from '../../../src/nest/journey/journey-share-views.store'; import { JourneyShareService } from '../../../src/nest/journey/journey-share.service'; import { TrekPhotoRegistrationService } from '../../../src/nest/photos/trek-photo-registration.service'; import { RealtimeService } from '../../../src/nest/realtime/realtime.service'; @@ -66,6 +68,7 @@ vi.mock('../../../src/db/database', async () => { }); let svc: JourneyShareService; +let views: InMemoryJourneyShareViewStore; let t: TestOrm; let membership: TestModule; @@ -121,6 +124,8 @@ beforeAll(async () => { // `JourneyShareTokensRepository`'s own fallback stub. await createTestJourneyEntriesRepo(testDb), await createTestJourneyEntryPhotosRepo(testDb), + // #2553: who opened a link today, for its view count. + (views = new InMemoryJourneyShareViewStore()), ); }); @@ -1344,3 +1349,187 @@ function flipCase(token: string): string { const upper = token.toUpperCase(); return upper !== token ? upper : token.toLowerCase(); } + +// -- Password, expiry and views (#2553, #1702, #2959) --------------------------- + +/** The DomainError a call refuses with, as status, body and nothing else. */ +async function refusal(call: () => Promise): Promise<{ status: number; body: unknown }> { + try { + await call(); + } catch (err) { + const e = err as { getStatus: () => number; getResponse: () => unknown }; + return { status: e.getStatus(), body: e.getResponse() }; + } + throw new Error('expected a refusal'); +} + +describe('a protected share link', () => { + it('JOURNEY-SHARE-PW-001: a new link is open, never expires and has no views; the owner sees all of it', async () => { + const { user } = createUser(testDb); + const journey = createJourney(testDb, user.id); + const { token } = await svc.createOrUpdateJourneyShareLink(journey.id, user.id, {}); + + const link = await svc.getJourneyShareLink(journey.id); + expect(link).toMatchObject({ has_password: false, expires_at: null, view_count: 0, last_viewed_at: null }); + expect((await svc.assertPublicAccess(token, undefined)).journey_id).toBe(journey.id); + }); + + it('JOURNEY-SHARE-PW-002: a password is stored only as a bcrypt hash and locks every public read', async () => { + const { user } = createUser(testDb); + const journey = createJourney(testDb, user.id); + const { token } = await svc.createOrUpdateJourneyShareLink(journey.id, user.id, { password: 'open sesame' }); + + const row = await findRow(t, JourneyShareTokens, { token }); + expect(row?.password_hash).toMatch(/^\$2[aby]\$12\$/); + expect(row?.password_hash).not.toContain('open sesame'); + expect(row?.password_version).toBe(1); + expect((await svc.getJourneyShareLink(journey.id))?.has_password).toBe(true); + expect(JSON.stringify(await svc.getJourneyShareLink(journey.id))).not.toContain('$2'); + + expect(await refusal(() => svc.assertPublicAccess(token, undefined))).toEqual({ + status: 401, + body: { error: 'Password required', code: 'JOURNEY_PASSWORD_REQUIRED' }, + }); + expect(await refusal(() => svc.assertPublicAccess(token, 'forged'))).toMatchObject({ status: 401 }); + }); + + it('JOURNEY-SHARE-PW-003: the right password unlocks, the proof opens the link, a wrong one is refused', async () => { + const { user } = createUser(testDb); + const journey = createJourney(testDb, user.id); + const { token } = await svc.createOrUpdateJourneyShareLink(journey.id, user.id, { password: 'open sesame' }); + + expect(await refusal(() => svc.unlockPublicLink(token, 'wrong'))).toEqual({ + status: 401, + body: { error: 'Wrong password', code: 'JOURNEY_PASSWORD_INVALID' }, + }); + const unlocked = await svc.unlockPublicLink(token, 'open sesame'); + expect(unlocked).toEqual({ proof: unlockProof(token, 1), expiresAt: null }); + expect((await svc.assertPublicAccess(token, unlocked!.proof)).journey_id).toBe(journey.id); + // A proof is only good for its own link. + const other = await svc.createOrUpdateJourneyShareLink(createJourney(testDb, user.id).id, user.id, { + password: 'open sesame', + }); + expect(await refusal(() => svc.assertPublicAccess(other.token, unlocked!.proof))).toMatchObject({ status: 401 }); + }); + + it('JOURNEY-SHARE-PW-004: changing or removing the password signs every unlocked reader out again', async () => { + const { user } = createUser(testDb); + const journey = createJourney(testDb, user.id); + const { token } = await svc.createOrUpdateJourneyShareLink(journey.id, user.id, { password: 'first one' }); + const before = unlockProof(token, 1); + + await svc.createOrUpdateJourneyShareLink(journey.id, user.id, { password: 'second one' }); + expect(await refusal(() => svc.assertPublicAccess(token, before))).toMatchObject({ status: 401 }); + expect((await findRow(t, JourneyShareTokens, { token }))?.password_version).toBe(2); + + await svc.createOrUpdateJourneyShareLink(journey.id, user.id, { password: null }); + const row = await findRow(t, JourneyShareTokens, { token }); + expect(row?.password_hash).toBeNull(); + expect(row?.password_version).toBe(3); + // Open again for everybody, and an unlock of an open link has nothing to do. + expect((await svc.assertPublicAccess(token, undefined)).journey_id).toBe(journey.id); + expect(await svc.unlockPublicLink(token, 'anything')).toBeNull(); + }); + + it('JOURNEY-SHARE-PW-005: saving the switches keeps the password and the expiry', async () => { + const { user } = createUser(testDb); + const journey = createJourney(testDb, user.id); + const { token } = await svc.createOrUpdateJourneyShareLink(journey.id, user.id, { + password: 'keep me', + expires_at: '2099-06-01T12:00:00Z', + }); + + await svc.createOrUpdateJourneyShareLink(journey.id, user.id, { share_gallery: false }); + await svc.createOrUpdateJourneyShareLink(journey.id, user.id, { share_map: false, newest_first: true }); + + const row = await findRow(t, JourneyShareTokens, { token }); + expect(row?.password_hash).toBeTruthy(); + expect(row?.password_version).toBe(1); + expect(row?.expires_at).toBe('2099-06-01 12:00:00'); + const link = await svc.getJourneyShareLink(journey.id); + expect(link).toMatchObject({ + has_password: true, + expires_at: '2099-06-01T12:00:00Z', + share_gallery: false, + share_map: false, + newest_first: true, + }); + }); + + it('JOURNEY-SHARE-PW-006: an expiry is stored as UTC text, cleared with null, and a past one answers 410', async () => { + const { user } = createUser(testDb); + const journey = createJourney(testDb, user.id); + const { token } = await svc.createOrUpdateJourneyShareLink(journey.id, user.id, { + expires_at: '2099-06-01T14:00:00+02:00', + }); + expect((await findRow(t, JourneyShareTokens, { token }))?.expires_at).toBe('2099-06-01 12:00:00'); + + await svc.createOrUpdateJourneyShareLink(journey.id, user.id, { expires_at: '2020-01-01T00:00:00Z' }); + const gone = { status: 410, body: { error: 'This link has expired', code: 'JOURNEY_LINK_EXPIRED' } }; + expect(await refusal(() => svc.assertPublicAccess(token, undefined))).toEqual(gone); + // Gone is gone, whatever password a reader knows. + expect(await refusal(() => svc.unlockPublicLink(token, 'x'))).toEqual(gone); + + await svc.createOrUpdateJourneyShareLink(journey.id, user.id, { expires_at: null }); + expect((await findRow(t, JourneyShareTokens, { token }))?.expires_at).toBeNull(); + expect((await svc.assertPublicAccess(token, undefined)).journey_id).toBe(journey.id); + }); + + it('JOURNEY-SHARE-PW-007: an unknown token is the 404 every public route always gave', async () => { + expect(await refusal(() => svc.assertPublicAccess('nope', undefined))).toEqual({ + status: 404, + body: { error: 'Not found' }, + }); + expect(await refusal(() => svc.unlockPublicLink('nope', 'x'))).toMatchObject({ status: 404 }); + }); + + it("JOURNEY-SHARE-PW-008: a contributor cannot set a password on the owner's link", async () => { + const { user: owner } = createUser(testDb); + const { user: editor } = createUser(testDb); + const journey = createJourney(testDb, owner.id); + addJourneyContributor(testDb, journey.id, editor.id, 'editor'); + const { token } = await svc.createOrUpdateJourneyShareLink(journey.id, owner.id, {}); + + expect(await svc.createOrUpdateJourneyShareLink(journey.id, editor.id, { password: 'mine now' })).toBeNull(); + expect((await findRow(t, JourneyShareTokens, { token }))?.password_hash).toBeNull(); + }); +}); + +describe('the view count of a share link', () => { + it('JOURNEY-SHARE-VIEW-001: counts a reader once a day, and every other reader too', async () => { + const { user } = createUser(testDb); + const journey = createJourney(testDb, user.id); + const { token } = await svc.createOrUpdateJourneyShareLink(journey.id, user.id, {}); + + await publicJourneyAs(token, '203.0.113.1|Firefox'); + await publicJourneyAs(token, '203.0.113.1|Firefox'); + await publicJourneyAs(token, '203.0.113.2|Safari'); + // A read that names no reader (an internal caller) counts nothing. + await svc.getPublicJourney(token); + + const link = await svc.getJourneyShareLink(journey.id); + expect(link?.view_count).toBe(2); + expect(link?.last_viewed_at).toMatch(/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}Z$/); + // Never in what a reader gets. + expect(JSON.stringify(await publicJourneyAs(token, 'x'))).not.toContain('view_count'); + }); + + it('JOURNEY-SHARE-VIEW-002: a count that cannot be stored still hands the reader the journey', async () => { + const { user } = createUser(testDb); + const journey = createJourney(testDb, user.id); + const { token } = await svc.createOrUpdateJourneyShareLink(journey.id, user.id, {}); + const firstToday = vi.spyOn(views, 'firstToday').mockRejectedValueOnce(new Error('store down')); + try { + expect(await publicJourneyAs(token, 'reader')).not.toBeNull(); + } finally { + firstToday.mockRestore(); + } + expect((await svc.getJourneyShareLink(journey.id))?.view_count).toBe(0); + }); +}); + +async function publicJourneyAs(token: string, viewer: string) { + const result = await svc.getPublicJourney(token, viewer); + if (!result) throw new Error('no public payload for the share link'); + return result; +} diff --git a/server/tests/unit/nest/journey.controller.test.ts b/server/tests/unit/nest/journey.controller.test.ts index 525d3e2aa..b1b11726e 100644 --- a/server/tests/unit/nest/journey.controller.test.ts +++ b/server/tests/unit/nest/journey.controller.test.ts @@ -2,6 +2,8 @@ import { ADDON_IDS } from '../../../src/addons'; import { AddonGuard } from '../../../src/nest/addons/addon.guard'; import { REQUIRE_ADDON } from '../../../src/nest/addons/require-addon.decorator'; import { RuntimeEnvService } from '../../../src/nest/app-config/runtime-env.service'; +import { DomainError } from '../../../src/nest/common/domain-error'; +import type { RateLimitService } from '../../../src/nest/common/rate-limit.service'; import type { JourneyBookService } from '../../../src/nest/journey/journey-book.service'; import type { JourneyGalleryService } from '../../../src/nest/journey/journey-gallery.service'; import type { JourneyPhotoCaptureService } from '../../../src/nest/journey/journey-photo-capture.service'; @@ -14,7 +16,7 @@ import type { StorageService } from '../../../src/nest/storage/storage.service'; import type { User } from '../../../src/types'; import { HttpException } from '@nestjs/common'; -import type { Response } from 'express'; +import type { Request, Response } from 'express'; import fs from 'node:fs'; import os from 'node:os'; import path from 'node:path'; @@ -1089,6 +1091,26 @@ describe('JourneyController in demo mode', () => { }); describe('JourneyPublicController', () => { + // #2553: every route asks the share service whether this browser may read the + // link; these stubs let it in unless a case says otherwise. + const rlCheck = vi.fn(); + const rlRelease = vi.fn(); + const rateLimitStub = { check: rlCheck, release: rlRelease } as unknown as RateLimitService; + const anon = { + cookies: {}, + headers: { 'user-agent': 'Firefox' }, + ip: '203.0.113.9', + secure: false, + } as unknown as Request; + const open = (o: Partial = {}) => + svc({ assertPublicAccess: vi.fn().mockResolvedValue({ id: 1 }), ...o } as Partial); + const pub = (s: JourneyService) => new JourneyPublicController(s, storageStub, publicMediaStub, rateLimitStub); + + beforeEach(() => { + rlCheck.mockResolvedValue(true); + rlRelease.mockResolvedValue(undefined); + }); + it('is addon-gated like the authenticated surface', () => { // Turning the Journey addon off is meant to take the feature away; without // this, already-published journeys stayed publicly readable. @@ -1100,89 +1122,143 @@ describe('JourneyPublicController', () => { }); it('GET /:token 404 / json', async () => { - expect( - await thrownAsync(() => - new JourneyPublicController( - svc({ getPublicJourney: vi.fn().mockReturnValue(null) } as Partial), - storageStub, - publicMediaStub, - ).get('tok'), - ), - ).toEqual({ status: 404, body: { error: 'Not found' } }); - expect( - await new JourneyPublicController( - svc({ getPublicJourney: vi.fn().mockReturnValue({ id: 1 }) } as Partial), - storageStub, - publicMediaStub, - ).get('tok'), - ).toEqual({ id: 1 }); + const missing = open({ getPublicJourney: vi.fn().mockReturnValue(null) }); + expect(await thrownAsync(() => pub(missing).get('tok', anon))).toEqual({ + status: 404, + body: { error: 'Not found' }, + }); + 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'); }); it('GET /:token/map-layers 404 on an unknown link, else the layers as the service cut them (JRN-04)', async () => { - expect( - await thrownAsync(() => - new JourneyPublicController( - svc({ getPublicMapLayers: vi.fn().mockResolvedValue(null) } as Partial), - storageStub, - publicMediaStub, - ).mapLayers('tok'), - ), - ).toEqual({ status: 404, body: { error: 'Not found' } }); + const missing = open({ getPublicMapLayers: vi.fn().mockResolvedValue(null) }); + expect(await thrownAsync(() => pub(missing).mapLayers('tok', anon))).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), - storageStub, - publicMediaStub, - ).mapLayers('tok'), - ).toBe(layers); + expect(await pub(open({ getPublicMapLayers })).mapLayers('tok', anon)).toBe(layers); expect(getPublicMapLayers).toHaveBeenCalledWith('tok'); }); - it('photo proxy 404 on invalid token, else streams', async () => { - expect( - await thrownAsync(() => - new JourneyPublicController( - svc({ validateShareTokenForPhoto: vi.fn().mockReturnValue(null) } as Partial), - storageStub, - publicMediaStub, - ).photo('tok', 7, 'thumbnail', {} as Response), - ), - ).toEqual({ status: 404, body: { error: 'Not found' } }); - const streamPhoto = vi.fn().mockResolvedValue(undefined); + it('every public route refuses before reading anything when the link is locked or gone (#2553)', async () => { + const locked = new DomainError(401, 'Password required', { details: { code: 'JOURNEY_PASSWORD_REQUIRED' } }); + const getPublicJourney = vi.fn(); + const getPublicMapLayers = vi.fn(); + const validateShareTokenForPhoto = vi.fn(); + const validateShareTokenForAsset = vi.fn(); + const assertPublicAccess = vi.fn().mockRejectedValue(locked); const s = svc({ - validateShareTokenForPhoto: vi.fn().mockReturnValue({ ownerId: 2 }), - streamPhoto, + assertPublicAccess, + getPublicJourney, + getPublicMapLayers, + validateShareTokenForPhoto, + validateShareTokenForAsset, } as Partial); - await new JourneyPublicController(s, storageStub, publicMediaStub).photo('tok', 7, 'original', {} as Response); + const refused = { status: 401, body: { error: 'Password required', code: 'JOURNEY_PASSWORD_REQUIRED' } }; + + expect(await thrownAsync(() => pub(s).get('tok', anon))).toEqual(refused); + expect(await thrownAsync(() => pub(s).mapLayers('tok', anon))).toEqual(refused); + expect(await thrownAsync(() => pub(s).photo('tok', 7, 'thumbnail', {} as Response, anon))).toEqual(refused); + expect( + await thrownAsync(() => pub(s).legacyPhoto('tok', 'local', 'a.jpg', 'thumbnail', {} as Response, anon)), + ).toEqual(refused); + expect(getPublicJourney).not.toHaveBeenCalled(); + expect(getPublicMapLayers).not.toHaveBeenCalled(); + expect(validateShareTokenForPhoto).not.toHaveBeenCalled(); + expect(validateShareTokenForAsset).not.toHaveBeenCalled(); + }); + + it('hands the share service the unlock cookie the browser sent', async () => { + const assertPublicAccess = vi.fn().mockResolvedValue({ id: 1 }); + const s = open({ assertPublicAccess, getPublicJourney: vi.fn().mockReturnValue({ id: 1 }) }); + const unlocked = { ...anon, cookies: { trek_journey_unlock: 'proof' } } as unknown as Request; + await pub(s).get('tok', unlocked); + expect(assertPublicAccess).toHaveBeenCalledWith('tok', 'proof'); + await pub(s).get('tok', anon); + expect(assertPublicAccess).toHaveBeenLastCalledWith('tok', undefined); + }); + + it('POST /:token/unlock sets the link-scoped cookie and gives the attempt back', async () => { + const cookie = vi.fn(); + const res = { cookie } as unknown as Response; + const unlockPublicLink = vi.fn().mockResolvedValue({ proof: 'p', expiresAt: null }); + const answer = await pub(open({ unlockPublicLink })).unlock('tok', { password: 'pw' }, anon, res); + + expect(answer).toEqual({ success: true }); + expect(unlockPublicLink).toHaveBeenCalledWith('tok', 'pw'); + expect(cookie).toHaveBeenCalledWith( + 'trek_journey_unlock', + 'p', + expect.objectContaining({ httpOnly: true, secure: false, sameSite: 'lax', path: '/api/public/journey/tok' }), + ); + expect(rlCheck).toHaveBeenCalledWith('journey_unlock', '203.0.113.9|tok', 10, 15 * 60 * 1000, expect.any(Number)); + expect(rlRelease).toHaveBeenCalledWith('journey_unlock', '203.0.113.9|tok', 15 * 60 * 1000, expect.any(Number)); + }); + + it('POST /:token/unlock marks the cookie Secure only on an HTTPS request', async () => { + const cookie = vi.fn(); + const unlockPublicLink = vi.fn().mockResolvedValue({ proof: 'p', expiresAt: null }); + const https = { ...anon, secure: true } as unknown as Request; + await pub(open({ unlockPublicLink })).unlock('tok', { password: 'pw' }, https, { cookie } as unknown as Response); + expect(cookie.mock.calls[0]?.[2]).toMatchObject({ secure: true }); + }); + + it('POST /:token/unlock on a link without a password sets nothing', async () => { + const cookie = vi.fn(); + const s = open({ unlockPublicLink: vi.fn().mockResolvedValue(null) }); + const answer = await pub(s).unlock('tok', { password: 'pw' }, anon, { cookie } as unknown as Response); + expect(answer).toEqual({ success: true }); + expect(cookie).not.toHaveBeenCalled(); + }); + + it('POST /:token/unlock keeps a wrong password counted and refuses with 429 once the limit is reached', async () => { + const wrong = new DomainError(401, 'Wrong password', { details: { code: 'JOURNEY_PASSWORD_INVALID' } }); + const unlockPublicLink = vi.fn().mockRejectedValue(wrong); + const cookie = vi.fn(); + const res = { cookie } as unknown as Response; + const ctl = pub(open({ unlockPublicLink })); + expect(await thrownAsync(() => ctl.unlock('tok', { password: 'x' }, anon, res))).toEqual({ + status: 401, + body: { error: 'Wrong password', code: 'JOURNEY_PASSWORD_INVALID' }, + }); + expect(rlRelease).not.toHaveBeenCalled(); + + rlCheck.mockResolvedValue(false); + expect(await thrownAsync(() => ctl.unlock('tok', { password: 'x' }, anon, res))).toEqual({ + status: 429, + body: { error: 'Too many attempts. Please try again later.' }, + }); + expect(unlockPublicLink).toHaveBeenCalledTimes(1); + expect(cookie).not.toHaveBeenCalled(); + }); + + 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({ + 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'); }); it('legacy photo proxy: 404 invalid token, immich path streams', async () => { + const invalid = open({ validateShareTokenForAsset: vi.fn().mockReturnValue(null) }); expect( - await thrownAsync(() => - new JourneyPublicController( - svc({ validateShareTokenForAsset: vi.fn().mockReturnValue(null) } as Partial), - storageStub, - publicMediaStub, - ).legacyPhoto('tok', 'immich', 'a1', 'thumbnail', {} as Response), - ), + await thrownAsync(() => pub(invalid).legacyPhoto('tok', 'immich', 'a1', 'thumbnail', {} 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 = svc({ - validateShareTokenForAsset: vi.fn().mockReturnValue({ ownerId: 5 }), - streamProviderAsset, - } as Partial); - await new JourneyPublicController(s, storageStub, publicMediaStub).legacyPhoto( - 'tok', - 'immich', - 'a1', - 'original', - {} as Response, - ); + const s = open({ validateShareTokenForAsset: vi.fn().mockReturnValue({ ownerId: 5 }), streamProviderAsset }); + await pub(s).legacyPhoto('tok', 'immich', 'a1', 'original', {} as Response, anon); expect(streamProviderAsset).toHaveBeenCalledWith( {}, 'immich', @@ -1193,11 +1269,8 @@ describe('JourneyPublicController', () => { it('photo proxy streams thumbnails too', async () => { const streamPhoto = vi.fn().mockResolvedValue(undefined); - const s = svc({ - validateShareTokenForPhoto: vi.fn().mockReturnValue({ ownerId: 3 }), - streamPhoto, - } as Partial); - await new JourneyPublicController(s, storageStub, publicMediaStub).photo('tok', 7, 'thumbnail', {} as Response); + 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'); }); @@ -1220,17 +1293,8 @@ describe('JourneyPublicController', () => { it('legacy photo proxy: synology streams, and a failure becomes a 404 json', async () => { const streamProviderAsset = vi.fn().mockResolvedValue(undefined); - const s = svc({ - validateShareTokenForAsset: vi.fn().mockReturnValue({ ownerId: 5 }), - streamProviderAsset, - } as Partial); - await new JourneyPublicController(s, storageStub, publicMediaStub).legacyPhoto( - 'tok', - 'synologyphotos', - 'a1', - 'thumbnail', - {} as Response, - ); + const s = open({ validateShareTokenForAsset: vi.fn().mockReturnValue({ ownerId: 5 }), streamProviderAsset }); + await pub(s).legacyPhoto('tok', 'synologyphotos', 'a1', 'thumbnail', {} as Response, anon); expect(streamProviderAsset).toHaveBeenCalledWith( {}, 'synologyphotos', @@ -1241,17 +1305,11 @@ describe('JourneyPublicController', () => { const status = vi.fn().mockReturnThis(); const json = vi.fn(); const res = { status, json } as unknown as Response; - const failing = svc({ + const failing = open({ validateShareTokenForAsset: vi.fn().mockReturnValue({ ownerId: 0 }), streamProviderAsset: vi.fn().mockRejectedValue(new Error('no synology')), - } as Partial); - await new JourneyPublicController(failing, storageStub, publicMediaStub).legacyPhoto( - 'tok', - 'synologyphotos', - 'a1', - 'original', - res, - ); + }); + await pub(failing).legacyPhoto('tok', 'synologyphotos', 'a1', 'original', res, anon); expect(status).toHaveBeenCalledWith(404); expect(json).toHaveBeenCalledWith({ error: 'Provider not supported' }); }); @@ -1264,17 +1322,8 @@ describe('JourneyPublicController', () => { const status = vi.fn().mockReturnThis(); const json = vi.fn(); const res = { status, json } as unknown as Response; - const s = svc({ - validateShareTokenForAsset: vi.fn().mockReturnValue({ ownerId: 5 }), - streamProviderAsset, - } as Partial); - await new JourneyPublicController(s, storageStub, publicMediaStub).legacyPhoto( - 'tok', - 'photoprism', - 'a1', - 'original', - res, - ); + const s = open({ validateShareTokenForAsset: vi.fn().mockReturnValue({ ownerId: 5 }), streamProviderAsset }); + await pub(s).legacyPhoto('tok', 'photoprism', 'a1', 'original', res, anon); expect(status).toHaveBeenCalledWith(404); expect(json).toHaveBeenCalledWith({ error: 'Provider not supported' }); }); @@ -1284,17 +1333,8 @@ describe('JourneyPublicController', () => { // may choose from the URL. The share service resolves it, falling back to // the journey owner when the photo row carries no owner_id. const streamProviderAsset = vi.fn().mockResolvedValue(undefined); - const s = svc({ - validateShareTokenForAsset: vi.fn().mockReturnValue({ ownerId: 3 }), - streamProviderAsset, - } as Partial); - await new JourneyPublicController(s, storageStub, publicMediaStub).legacyPhoto( - 'tok', - 'immich', - 'a1', - 'original', - {} as Response, - ); + const s = open({ validateShareTokenForAsset: vi.fn().mockReturnValue({ ownerId: 3 }), streamProviderAsset }); + await pub(s).legacyPhoto('tok', 'immich', 'a1', 'original', {} as Response, anon); expect(streamProviderAsset).toHaveBeenCalledWith( {}, 'immich', @@ -1305,17 +1345,9 @@ describe('JourneyPublicController', () => { it('legacy photo proxy: local provider 404s when the object does not exist', async () => { storageExists.mockResolvedValue(false); - const s = svc({ validateShareTokenForAsset: vi.fn().mockReturnValue({ ownerId: 5 }) } as Partial); + const s = open({ validateShareTokenForAsset: vi.fn().mockReturnValue({ ownerId: 5 }) }); expect( - await thrownAsync(() => - new JourneyPublicController(s, storageStub, publicMediaStub).legacyPhoto( - 'tok', - 'local', - 'gone.jpg', - 'thumbnail', - {} as Response, - ), - ), + await thrownAsync(() => pub(s).legacyPhoto('tok', 'local', 'gone.jpg', 'thumbnail', {} as Response, anon)), ).toEqual({ status: 404, body: { error: 'Not found' } }); expect(storageSendToResponse).not.toHaveBeenCalled(); }); @@ -1325,14 +1357,8 @@ describe('JourneyPublicController', () => { storageSendToResponse.mockResolvedValue(undefined); const set = vi.fn(); const res = { set } as unknown as Response; - const s = svc({ validateShareTokenForAsset: vi.fn().mockReturnValue({ ownerId: 5 }) } as Partial); - await new JourneyPublicController(s, storageStub, publicMediaStub).legacyPhoto( - 'tok', - 'local', - 'photo.jpg', - 'original', - res, - ); + 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'); // The location-free copy goes out, never the stored original. @@ -1345,14 +1371,8 @@ describe('JourneyPublicController', () => { renditionFor.mockRejectedValueOnce(new RenditionPendingError()); const json = vi.fn(); const res = { set: vi.fn(), status: vi.fn(() => ({ json })) } as unknown as Response; - const s = svc({ validateShareTokenForAsset: vi.fn().mockReturnValue({ ownerId: 5 }) } as Partial); - await new JourneyPublicController(s, storageStub, publicMediaStub).legacyPhoto( - 'tok', - 'local', - 'clip.mp4', - 'original', - res, - ); + 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); expect(res.set).toHaveBeenCalledWith('Retry-After', '10'); expect(storageSendToResponse).not.toHaveBeenCalled(); @@ -1362,18 +1382,11 @@ describe('JourneyPublicController', () => { 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); - expect( - await thrownAsync(() => - new JourneyPublicController(s, storageStub, publicMediaStub).legacyPhoto( - 'tok', - 'local', - 'a.bmp', - 'original', - res, - ), - ), - ).toEqual({ status: 404, body: { error: 'Not found' } }); + 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, + body: { error: 'Not found' }, + }); expect(storageSendToResponse).not.toHaveBeenCalled(); }); @@ -1381,16 +1394,10 @@ describe('JourneyPublicController', () => { storageExists.mockResolvedValue(true); storageSendToResponse.mockResolvedValue(undefined); const res = { set: vi.fn() } as unknown as Response; - const s = svc({ validateShareTokenForAsset: vi.fn().mockReturnValue({ ownerId: 5 }) } as Partial); + const s = open({ validateShareTokenForAsset: vi.fn().mockReturnValue({ ownerId: 5 }) }); // Express decodes %2F in a single path param to '/', so the handler sees this. - await new JourneyPublicController(s, storageStub, publicMediaStub).legacyPhoto( - 'tok', - 'local', - '../../files/secret.pdf', - 'original', - res, - ); + await pub(s).legacyPhoto('tok', 'local', '../../files/secret.pdf', 'original', res, anon); // basename() collapses the traversal before the storage lookup, and central // key validation (storage-keys.ts) rejects anything that still carries a @@ -1403,18 +1410,12 @@ describe('JourneyPublicController', () => { // '..' survives basename(); storage.exists rejects it as an invalid key, // which the handler reads as a miss. storageExists.mockRejectedValue(new Error('invalid storage key: journey/..')); - const s = svc({ validateShareTokenForAsset: vi.fn().mockReturnValue({ ownerId: 5 }) } as Partial); - expect( - await thrownAsync(() => - new JourneyPublicController(s, storageStub, publicMediaStub).legacyPhoto( - 'tok', - 'local', - '..', - 'original', - {} as Response, - ), - ), - ).toEqual({ status: 404, body: { error: 'Not found' } }); + const s = open({ validateShareTokenForAsset: vi.fn().mockReturnValue({ ownerId: 5 }) }); + const read = () => pub(s).legacyPhoto('tok', 'local', '..', 'original', {} as Response, anon); + expect(await thrownAsync(read)).toEqual({ + status: 404, + body: { error: 'Not found' }, + }); expect(storageSendToResponse).not.toHaveBeenCalled(); }); }); diff --git a/server/tests/unit/nest/journey/journey-share-access.test.ts b/server/tests/unit/nest/journey/journey-share-access.test.ts new file mode 100644 index 000000000..b6079c8e8 --- /dev/null +++ b/server/tests/unit/nest/journey/journey-share-access.test.ts @@ -0,0 +1,127 @@ +/** + * The pure half of a protected journey link (#2553) and the store behind its + * view count: the password hash, the unlock proof and its cookie, the expiry, + * and who was seen today. + */ +import { + checkSharePassword, + hashSharePassword, + JOURNEY_UNLOCK_COOKIE, + proofUnlocks, + shareLinkExpired, + unlockCookieOptions, + unlockProof, + unlockProofOf, + viewerOf, + viewKey, +} from '../../../../src/nest/journey/journey-share-access'; +import { InMemoryJourneyShareViewStore } from '../../../../src/nest/journey/journey-share-views.store'; + +import type { Request } from 'express'; +import { describe, expect, it } from 'vitest'; + +const BASE = { cookies: {}, headers: { 'user-agent': 'Firefox' }, ip: '203.0.113.9', secure: false }; +const req = (over: Record = {}) => ({ ...BASE, ...over }) as unknown as Request; + +describe('the share password', () => { + it('JSHAREACC-001: hashes with bcrypt at the account cost and checks against the hash', async () => { + const hash = await hashSharePassword('open sesame'); + expect(hash).toMatch(/^\$2[aby]\$12\$/); + expect(await checkSharePassword('open sesame', hash)).toBe(true); + expect(await checkSharePassword('open sesame!', hash)).toBe(false); + }); +}); + +describe('the unlock proof', () => { + it('JSHAREACC-002: is tied to the token and the password version', () => { + const proof = unlockProof('tok', 1); + expect(proof).toMatch(/^[A-Za-z0-9_-]+$/); + expect(unlockProof('tok', 1)).toBe(proof); + expect(unlockProof('tok', 2)).not.toBe(proof); + expect(unlockProof('other', 1)).not.toBe(proof); + }); + + it('JSHAREACC-003: unlocks only with the exact proof', () => { + const proof = unlockProof('tok', 3); + expect(proofUnlocks('tok', 3, proof)).toBe(true); + expect(proofUnlocks('tok', 4, proof)).toBe(false); + expect(proofUnlocks('tok', 3, `${proof}x`)).toBe(false); + expect(proofUnlocks('tok', 3, '')).toBe(false); + expect(proofUnlocks('tok', 3, undefined)).toBe(false); + }); + + it('JSHAREACC-004: is read from the link cookie only when it is a string', () => { + expect(unlockProofOf(req({ cookies: { [JOURNEY_UNLOCK_COOKIE]: 'p' } }))).toBe('p'); + expect(unlockProofOf(req({ cookies: { [JOURNEY_UNLOCK_COOKIE]: ['p'] } }))).toBeUndefined(); + expect(unlockProofOf(req({ cookies: undefined }))).toBeUndefined(); + }); +}); + +describe('the unlock cookie', () => { + const now = new Date('2026-11-30T12:00:00Z'); + + it('JSHAREACC-005: is scoped to the link, http-only, and Secure only over HTTPS', () => { + expect(unlockCookieOptions('tok', req(), null, now)).toEqual({ + httpOnly: true, + secure: false, + sameSite: 'lax', + path: '/api/public/journey/tok', + maxAge: 30 * 24 * 60 * 60 * 1000, + }); + expect(unlockCookieOptions('tok', req({ secure: true }), null, now).secure).toBe(true); + }); + + it('JSHAREACC-006: lives no longer than the link', () => { + expect(unlockCookieOptions('tok', req(), '2026-11-30 13:00:00', now).maxAge).toBe(60 * 60 * 1000); + expect(unlockCookieOptions('tok', req(), '2099-01-01 00:00:00', now).maxAge).toBe(30 * 24 * 60 * 60 * 1000); + expect(unlockCookieOptions('tok', req(), '2020-01-01 00:00:00', now).maxAge).toBe(0); + }); +}); + +describe('the expiry', () => { + const now = new Date('2026-11-30T12:00:00Z'); + + it('JSHAREACC-007: a link without one never runs out, one with one runs out at it', () => { + expect(shareLinkExpired(null, now)).toBe(false); + expect(shareLinkExpired(undefined, now)).toBe(false); + expect(shareLinkExpired('2026-11-30 12:00:01', now)).toBe(false); + expect(shareLinkExpired('2026-11-30 12:00:00', now)).toBe(true); + expect(shareLinkExpired('2026-11-29 00:00:00', now)).toBe(true); + // Text that reads as no date never locks a link away. + expect(shareLinkExpired('garbage', now)).toBe(false); + }); +}); + +describe('the reader behind a view', () => { + it('JSHAREACC-008: is their address and browser, hashed per link', () => { + expect(viewerOf(req())).toBe('203.0.113.9|Firefox'); + expect(viewerOf(req({ headers: {}, ip: undefined }))).toBe('|'); + const key = viewKey(1, viewerOf(req())); + expect(key).not.toContain('203.0.113.9'); + expect(viewKey(1, viewerOf(req()))).toBe(key); + expect(viewKey(2, viewerOf(req()))).not.toBe(key); + }); +}); + +describe('InMemoryJourneyShareViewStore', () => { + it('JSHAREACC-009: sees a reader once a UTC day', async () => { + const store = new InMemoryJourneyShareViewStore(); + const morning = new Date('2026-11-30T08:00:00Z'); + expect(await store.firstToday('a', morning)).toBe(true); + expect(await store.firstToday('a', new Date('2026-11-30T23:59:59Z'))).toBe(false); + expect(await store.firstToday('b', morning)).toBe(true); + expect(await store.firstToday('a', new Date('2026-12-01T00:00:00Z'))).toBe(true); + // The new day dropped yesterday's readers. + expect(store.size()).toBe(1); + }); + + it('JSHAREACC-010: starts the day over past its cap instead of growing without end', async () => { + const store = new InMemoryJourneyShareViewStore(2); + const day = new Date('2026-11-30T08:00:00Z'); + await store.firstToday('a', day); + await store.firstToday('b', day); + expect(await store.firstToday('c', day)).toBe(true); + expect(store.size()).toBe(1); + expect(await store.firstToday('a', day)).toBe(true); + }); +}); diff --git a/shared/src/journey/journey-public.schema.ts b/shared/src/journey/journey-public.schema.ts index 38b2257d2..f5b125c27 100644 --- a/shared/src/journey/journey-public.schema.ts +++ b/shared/src/journey/journey-public.schema.ts @@ -90,3 +90,27 @@ export const journeyPublicResponseSchema = z.strictObject({ }), }); export type JourneyPublicResponse = z.infer; + +/** + * POST /api/public/journey/:token/unlock: the password a reader typed for a + * protected link. Bounded but not held to the owner's rules, so a reader only + * ever learns "wrong password", never a hint about what the password looks like. + */ +export const journeyPublicUnlockRequestSchema = z.object({ + password: z.string().min(1).max(200), +}); +export type JourneyPublicUnlockRequest = z.infer; + +/** + * The `code` beside `error` when a public journey route refuses, so the reader's + * page can tell "ask for the password" from "this link is gone" without reading + * the message. + */ +export const JOURNEY_PUBLIC_ERROR_CODES = { + /** 401: the link has a password and this browser has not unlocked it yet. */ + locked: 'JOURNEY_PASSWORD_REQUIRED', + /** 401 from the unlock route: the password did not match. */ + denied: 'JOURNEY_PASSWORD_INVALID', + /** 410: the link ran past the date its owner set. */ + expired: 'JOURNEY_LINK_EXPIRED', +} as const; diff --git a/shared/src/journey/journey.schema.spec.ts b/shared/src/journey/journey.schema.spec.ts index 608e64d38..d5e2043dd 100644 --- a/shared/src/journey/journey.schema.spec.ts +++ b/shared/src/journey/journey.schema.spec.ts @@ -20,6 +20,7 @@ import { journeyUpdateToolSchema, journeyTrackSchema, } from './journey.schema'; +import { journeyPublicUnlockRequestSchema } from './journey-public.schema'; import { describe, it, expect } from 'vitest'; @@ -145,6 +146,32 @@ describe('journeyShareLinkRequestSchema', () => { expect(journeyShareLinkRequestSchema.safeParse({ share_plan: 'true' }).success).toBe(false); expect(journeyShareLinkRequestSchema.safeParse({ share_recordings: 1 }).success).toBe(false); }); + + it('sets, clears or keeps a password, within what bcrypt reads whole (#2553)', () => { + expect(journeyShareLinkRequestSchema.safeParse({ password: 'secret' }).success).toBe(true); + expect(journeyShareLinkRequestSchema.safeParse({ password: null }).success).toBe(true); + expect(journeyShareLinkRequestSchema.safeParse({ share_map: true }).data).not.toHaveProperty('password'); + expect(journeyShareLinkRequestSchema.safeParse({ password: 'abc' }).success).toBe(false); + expect(journeyShareLinkRequestSchema.safeParse({ password: 'x'.repeat(73) }).success).toBe(false); + expect(journeyShareLinkRequestSchema.safeParse({ password: 1234 }).success).toBe(false); + }); + + it('takes an expiry as an ISO timestamp or null, and nothing else', () => { + expect(journeyShareLinkRequestSchema.safeParse({ expires_at: '2027-01-01T00:00:00Z' }).success).toBe(true); + expect(journeyShareLinkRequestSchema.safeParse({ expires_at: '2027-01-01T00:00:00+02:00' }).success).toBe(true); + expect(journeyShareLinkRequestSchema.safeParse({ expires_at: null }).success).toBe(true); + expect(journeyShareLinkRequestSchema.safeParse({ expires_at: '2027-01-01' }).success).toBe(false); + expect(journeyShareLinkRequestSchema.safeParse({ expires_at: 'tomorrow' }).success).toBe(false); + }); +}); + +describe('journeyPublicUnlockRequestSchema', () => { + it('needs a password and caps its length', () => { + expect(journeyPublicUnlockRequestSchema.safeParse({ password: 'a' }).success).toBe(true); + expect(journeyPublicUnlockRequestSchema.safeParse({ password: '' }).success).toBe(false); + expect(journeyPublicUnlockRequestSchema.safeParse({}).success).toBe(false); + expect(journeyPublicUnlockRequestSchema.safeParse({ password: 'x'.repeat(201) }).success).toBe(false); + }); }); describe('the free-form bodies keep their unknown keys', () => { diff --git a/shared/src/journey/journey.schema.ts b/shared/src/journey/journey.schema.ts index 7e77d466f..185633b95 100644 --- a/shared/src/journey/journey.schema.ts +++ b/shared/src/journey/journey.schema.ts @@ -1,4 +1,4 @@ -import { idSchema } from '../common/primitives.schema'; +import { idSchema, isoDateTime } from '../common/primitives.schema'; import { journeyRecordingDateSchema } from './journey-recordings.schema'; import { z } from 'zod'; @@ -414,6 +414,12 @@ export type JourneyGalleryVideoRequest = z.infer; +/** + * A share link's password. bcrypt reads at most 72 bytes, so a longer one would + * be cut short without anyone noticing. + */ +export const journeySharePasswordSchema = z.string().min(4).max(72); + export const journeyShareLinkRequestSchema = z.looseObject({ share_timeline: z.unknown().optional(), share_gallery: z.unknown().optional(), @@ -424,6 +430,16 @@ export const journeyShareLinkRequestSchema = z.looseObject({ share_plan: z.boolean().optional(), /** Put the recorded days on the shared map, on days with a published entry (JRN-04). */ share_recordings: z.boolean().optional(), + /** + * Ask a reader for this password before the link shows anything (#2553). + * A string sets or replaces it, null takes it off, leaving it out keeps it. + */ + password: journeySharePasswordSchema.nullable().optional(), + /** + * When the link stops working, as an ISO timestamp. Null means never (the + * default), leaving it out keeps what the link had. + */ + expires_at: isoDateTime.nullable().optional(), }); export type JourneyShareLinkRequest = z.infer; @@ -510,6 +526,14 @@ export const journeyShareLinkSchema = z.object({ newest_first: z.boolean(), share_plan: z.boolean(), share_recordings: z.boolean(), + /** Whether a reader has to enter a password first. The password itself never leaves the server. */ + has_password: z.boolean(), + /** When the link stops working (ISO, UTC), or null when it never does. */ + expires_at: z.string().nullable(), + /** How many readers opened the link, each counted once a day. Only the owner sees it. */ + view_count: z.number(), + /** When a reader last opened the link (ISO, UTC), or null before the first one. */ + last_viewed_at: z.string().nullable(), }); export type JourneyShareLink = z.infer; diff --git a/wiki/MCP-Addon-Tools.md b/wiki/MCP-Addon-Tools.md index 73559be74..202964d82 100644 --- a/wiki/MCP-Addon-Tools.md +++ b/wiki/MCP-Addon-Tools.md @@ -243,8 +243,8 @@ Requires `journey:read` or `journey:write` scope. | `add_journey_provider_photos` | Attach photos from a connected library (Immich or Synology Photos) to a journey, or to one entry when `entryId` is given. Find the asset ids first with `search_provider_photos` or `list_provider_album_photos`. No image data passes through: the journey stores a reference and the app fetches the picture. An asset already attached is skipped rather than duplicated. | | `get_journey_suggestions` | Get suggested trips to add to journeys based on recent trip history. | | `list_journey_available_trips` | List all trips available to the current user for linking to a journey. | -| `get_journey_share_link` | Get the current public share link for a journey. Requires `journey:share`. | -| `create_journey_share_link` | Create or update the public share link for a journey. `share_plan` adds the linked trips' planned places and GPX routes to the shared map, `share_recordings` the recorded days that have a published entry; both start off and show nothing while the map is not shared. Requires `journey:share`. | +| `get_journey_share_link` | Get the current public share link for a journey: its switches, whether it has a password (never the password itself), when it expires and how many readers opened it. Requires `journey:share`. | +| `create_journey_share_link` | Create or update the public share link for a journey. `share_plan` adds the linked trips' planned places and GPX routes to the shared map, `share_recordings` the recorded days that have a published entry; both start off and show nothing while the map is not shared. `password` (4 to 72 characters) asks readers for it before the link shows anything, `null` removes it; `expires_at` (an ISO timestamp) ends the link on that date, `null` means never. Left out, both keep their value. Requires `journey:share`. | | `delete_journey_share_link` | Revoke the public share link for a journey. Requires `journey:share`. | | `list_journey_recorded_days` | The days of recorded route a journey keeps, from Dawarich or from a GPX file: zone, distance, pieces, gaps, modes, whether the day was still running, and whose recording it is, without the geometry. Readable without a Dawarich connection. | | `import_journey_gpx_days` | Read the recorded route of a GPX file into a journey as recorded days, one per local day the file covers, cut in the zone of where it was recorded (or one fixed zone) and drawn on the journey map also on days without an entry. Reading the same file again replaces only its GPX days; days taken over from Dawarich stay. Needs edit access, no Dawarich. |