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:
Maurice
2026-11-30 14:36:42 +01:00
parent ddfb7ad7ad
commit 55fc5f6679
29 changed files with 1540 additions and 197 deletions
@@ -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);
}
});
});
@@ -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.
+1
View File
@@ -255,6 +255,7 @@ const NOT_HASHED: Record<string, string> = {
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). */
@@ -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 });
});
});
@@ -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);
@@ -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<unknown>): 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;
}
+171 -170
View File
@@ -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<JourneyService> = {}) =>
svc({ assertPublicAccess: vi.fn().mockResolvedValue({ id: 1 }), ...o } as Partial<JourneyService>);
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<JourneyService>),
storageStub,
publicMediaStub,
).get('tok'),
),
).toEqual({ status: 404, body: { error: 'Not found' } });
expect(
await new JourneyPublicController(
svc({ getPublicJourney: vi.fn().mockReturnValue({ id: 1 }) } as Partial<JourneyService>),
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<JourneyService>),
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<JourneyService>),
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<JourneyService>),
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<JourneyService>);
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<JourneyService>),
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<JourneyService>);
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<JourneyService>);
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<JourneyService>);
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<JourneyService>);
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<JourneyService>);
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<JourneyService>);
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<JourneyService>);
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<JourneyService>);
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<JourneyService>);
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<JourneyService>);
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<JourneyService>);
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<JourneyService>);
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();
});
});
@@ -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<string, unknown> = {}) => ({ ...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);
});
});