mirror of
https://github.com/mauriceboe/TREK.git
synced 2026-11-30 16:33:16 +00:00
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.
This commit is contained in:
@@ -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<Users>;
|
||||
}
|
||||
|
||||
@@ -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'),
|
||||
},
|
||||
});
|
||||
|
||||
@@ -14,4 +14,9 @@ export interface JourneyShareTokensTable {
|
||||
newest_first: InsertOptional<number>;
|
||||
share_plan: InsertOptional<number>;
|
||||
share_recordings: InsertOptional<number>;
|
||||
password_hash: InsertOptional<string | null>;
|
||||
password_version: InsertOptional<number>;
|
||||
expires_at: InsertOptional<string | null>;
|
||||
view_count: InsertOptional<number>;
|
||||
last_viewed_at: InsertOptional<string | null>;
|
||||
}
|
||||
|
||||
+45
@@ -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<void> {
|
||||
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',
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -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<DB, 'journey_share_tokens'>;
|
||||
|
||||
/** 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<JourneyShareTok
|
||||
'jst.newest_first',
|
||||
'jst.share_plan',
|
||||
'jst.share_recordings',
|
||||
'jst.password_hash',
|
||||
'jst.password_version',
|
||||
'jst.expires_at',
|
||||
])
|
||||
.where({ journey: journeyId })
|
||||
.execute<JourneyShareLinkFlagsRow | undefined>('get', false);
|
||||
@@ -121,9 +146,36 @@ export class JourneyShareTokensRepository extends TrekRepository<JourneyShareTok
|
||||
await this.nativeUpdate({ journey: journeyId }, flags);
|
||||
}
|
||||
|
||||
/**
|
||||
* The password and expiry of a link, written as the service resolved them
|
||||
* (the same "keep what was not given" merge as the flags above).
|
||||
*/
|
||||
async updateProtection(journeyId: number, protection: JourneyShareProtection): Promise<void> {
|
||||
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<void> {
|
||||
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<void> {
|
||||
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<void> {
|
||||
const now = currentTimestampKysely(this.getEntityManager().getPlatform());
|
||||
await this.kysely<ShareTokensDB>()
|
||||
.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 = ?`. */
|
||||
|
||||
@@ -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.
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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<void> {
|
||||
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<void> {
|
||||
await this.journey.assertPublicAccess(token, unlockProofOf(req));
|
||||
const valid = await this.journey.validateShareTokenForAsset(token, assetId);
|
||||
if (!valid) {
|
||||
throw new HttpException({ error: 'Not found' }, 404);
|
||||
|
||||
@@ -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 `<img>` 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<string> {
|
||||
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<boolean> {
|
||||
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<string, unknown> | 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');
|
||||
}
|
||||
@@ -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<boolean>;
|
||||
}
|
||||
|
||||
export class InMemoryJourneyShareViewStore extends JourneyShareViewStore {
|
||||
private day = '';
|
||||
private readonly seen = new Set<string>();
|
||||
|
||||
/**
|
||||
* `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<boolean> {
|
||||
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;
|
||||
}
|
||||
}
|
||||
@@ -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<JourneyShareLinkFlagsRow, 'password_hash' | 'password_version' | 'expires_at'>,
|
||||
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<string | null | undefined> {
|
||||
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<JourneyShareTokenRow> {
|
||||
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<JourneyShareTokenRow> {
|
||||
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<JourneyPublicResponse | null> {
|
||||
/**
|
||||
* 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<JourneyPublicResponse | null> {
|
||||
// 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<void> {
|
||||
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}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -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) {}
|
||||
|
||||
@@ -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,
|
||||
) {
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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);
|
||||
|
||||
Reference in New Issue
Block a user