fix(journey): keep a protected link's photos out of shared caches

The photo proxies answer public, max-age, so a proxy or CDN in front of
TREK could hand a password-protected link's photo to somebody who never
unlocked it. For a link with a password every Cache-Control the proxy
sets is turned private.
This commit is contained in:
Maurice
2026-11-30 15:20:05 +01:00
parent 6ac15213d9
commit cbdc6850ca
3 changed files with 70 additions and 6 deletions
@@ -12,7 +12,13 @@ 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 {
JOURNEY_UNLOCK_COOKIE,
keepCachesPrivate,
unlockCookieOptions,
unlockProofOf,
viewerOf,
} from './journey-share-access';
import { JourneyPublicUnlockDto } from './journey.dto';
import { JourneyService } from './journey.service';
import { Body, Controller, Get, HttpCode, HttpException, Param, Post, Req, Res, UseGuards } from '@nestjs/common';
@@ -53,7 +59,8 @@ function sharedPhotoKind(kind: string): 'thumbnail' | 'preview' | 'original' {
* Every route but the unlock first asks `assertPublicAccess` (#2553): the link
* exists (404), has not run out (410) and, when it has a password, the browser
* holds the unlock cookie for it (401). The photo proxies ask too, so a locked
* link hands out no picture even to somebody who knows a photo's address.
* link hands out no picture even to somebody who knows a photo's address, and
* they answer a protected link's photos as `private`, so no shared cache keeps one.
*/
@Public('share-token validated: the whole point is a link that works without an account')
@UseGuards(AddonGuard)
@@ -139,7 +146,8 @@ export class JourneyPublicController {
@Res() res: Response,
@Req() req: Request,
): Promise<void> {
await this.journey.assertPublicAccess(token, unlockProofOf(req));
const link = await this.journey.assertPublicAccess(token, unlockProofOf(req));
if (link.password_hash) keepCachesPrivate(res);
const valid = await this.journey.validateShareTokenForPhoto(token, photoId);
if (!valid) {
throw new HttpException({ error: 'Not found' }, 404);
@@ -156,7 +164,8 @@ export class JourneyPublicController {
@Res() res: Response,
@Req() req: Request,
): Promise<void> {
await this.journey.assertPublicAccess(token, unlockProofOf(req));
const link = await this.journey.assertPublicAccess(token, unlockProofOf(req));
if (link.password_hash) keepCachesPrivate(res);
const valid = await this.journey.validateShareTokenForAsset(token, assetId);
if (!valid) {
throw new HttpException({ error: 'Not found' }, 404);
@@ -2,7 +2,7 @@ import { JWT_SECRET } from '../../config';
import { parseDbTimestamp } from '../../db/types';
import bcrypt from 'bcryptjs';
import type { CookieOptions, Request } from 'express';
import type { CookieOptions, Request, Response } from 'express';
import { createHash, createHmac, timingSafeEqual } from 'node:crypto';
/**
@@ -96,6 +96,30 @@ export function unlockCookieOptions(
};
}
/** A `Cache-Control` value with `public` turned into `private`; anything else stays as it is. */
export function privateCacheControl(value: number | string | readonly string[]): number | string | string[] {
const toPrivate = (v: string) => v.replace(/\bpublic\b/gi, 'private');
if (typeof value === 'number') return value;
if (typeof value === 'string') return toPrivate(value);
return value.map(toPrivate);
}
/**
* Keeps a protected link's photo out of shared caches. The photo proxies of
* the memories domain answer `public, max-age=…`, which is right for an open
* link, but a proxy or CDN between TREK and the reader would then hand a
* protected link's photo to somebody who never typed the password. Every
* `Cache-Control` the response is given from here on is made `private`, so
* only the reader's own browser keeps it.
*/
export function keepCachesPrivate(res: Response): void {
const setHeader = res.setHeader.bind(res);
res.setHeader = ((name: string, value: number | string | readonly string[]) => {
const isCacheControl = name.toLowerCase() === 'cache-control';
return setHeader(name, isCacheControl ? privateCacheControl(value) : value);
}) as Response['setHeader'];
}
/** 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'] : '';
@@ -7,6 +7,8 @@ import {
checkSharePassword,
hashSharePassword,
JOURNEY_UNLOCK_COOKIE,
keepCachesPrivate,
privateCacheControl,
proofUnlocks,
shareLinkExpired,
unlockCookieOptions,
@@ -17,7 +19,7 @@ import {
} from '../../../../src/nest/journey/journey-share-access';
import { InMemoryJourneyShareViewStore } from '../../../../src/nest/journey/journey-share-views.store';
import type { Request } from 'express';
import type { Request, Response } from 'express';
import { describe, expect, it } from 'vitest';
const BASE = { cookies: {}, headers: { 'user-agent': 'Firefox' }, ip: '203.0.113.9', secure: false };
@@ -125,3 +127,32 @@ describe('InMemoryJourneyShareViewStore', () => {
expect(await store.firstToday('a', day)).toBe(true);
});
});
describe('the photo caches of a protected link', () => {
it('JSHAREACC-011: turns public into private and leaves every other value alone', () => {
expect(privateCacheControl('public, max-age=86400')).toBe('private, max-age=86400');
expect(privateCacheControl('Public, max-age=3600')).toBe('private, max-age=3600');
expect(privateCacheControl('no-store, max-age=0')).toBe('no-store, max-age=0');
expect(privateCacheControl(['public', 'max-age=60'])).toEqual(['private', 'max-age=60']);
expect(privateCacheControl(60)).toBe(60);
});
it('JSHAREACC-012: rewrites every Cache-Control the response is given afterwards, and only that header', () => {
const headers: Record<string, unknown> = {};
const res = {
setHeader(name: string, value: unknown) {
headers[name] = value;
return res;
},
} as unknown as Response;
keepCachesPrivate(res);
res.setHeader('Cache-Control', 'public, max-age=86400');
res.setHeader('cache-control', 'public, max-age=3600');
res.setHeader('Content-Type', 'image/public');
expect(headers).toEqual({
'Cache-Control': 'private, max-age=86400',
'cache-control': 'private, max-age=3600',
'Content-Type': 'image/public',
});
});
});