Files
TREK/server/tests/e2e/journey-public-link.e2e.test.ts
T
Maurice ede109dce8 feat(journey): complete sharing, photo drafts and Studio maps
Connect the Journey backend to the web and mobile UI, including public access and subscriptions, day recordings, photo drafts and per-map framing. Preserve legacy recording responses and cover the new behavior in every locale.
2026-11-30 16:56:18 +01:00

258 lines
12 KiB
TypeScript

/**
* A protected public journey link, end to end (#2553, #1702, #2959, #1669): the
* whole app (buildApp, the real guards, share service and rate limit on a
* migrated temp SQLite) between the owner who sets a password and an expiry
* and the reader who opens the link. Every public route refuses a locked link,
* the unlock sets a cookie scoped to the link's own path, a changed password
* locks the old cookie out again, an expired link answers 410, saving a switch
* keeps the protection, readers are counted once a day for the owner only, and
* a new contributor hears about the journey.
*/
import { buildApp } from '../../src/bootstrap';
import { JourneyShareTokens } from '../../src/db/entities/JourneyShareTokens.entity';
import { Notifications } from '../../src/db/entities/Notifications.entity';
import { NotificationsService } from '../../src/nest/notifications/notifications.service';
import { makeJourney } from '../helpers/factories/journeys';
import { countRows, findRow } from '../helpers/factories/rows';
import { setAddonEnabled } from '../helpers/factories/settings';
import { makeUser } from '../helpers/factories/users';
import { resetRateLimits } from '../helpers/test-db';
import { sessionCookie } from './harness';
import { MikroORM } from '@mikro-orm/core';
import type { INestApplication } from '@nestjs/common';
import type { Server } from 'node:http';
import request from 'supertest';
import { afterAll, beforeAll, beforeEach, describe, expect, it } from 'vitest';
let app: INestApplication;
let orm: MikroORM;
let server: Server;
beforeAll(async () => {
app = await buildApp();
orm = app.get(MikroORM);
server = app.getHttpServer() as Server;
await setAddonEnabled(orm, 'journey', true);
}, 60_000);
beforeEach(async () => {
await resetRateLimits(app);
});
afterAll(async () => {
await app?.close();
});
/** A journey with a share link the owner saved with `body`; answers the owner and the token. */
async function sharedJourney(body: Record<string, unknown> = {}) {
const { user: owner } = await makeUser(orm);
const journey = await makeJourney(orm, owner.id);
const res = await request(server)
.post(`/api/journeys/${journey.id}/share-link`)
.set('Cookie', sessionCookie(owner.id))
.send(body);
expect(res.status).toBe(200);
return { owner, journey, token: res.body.token as string };
}
/** The share link as its owner reads it. */
function ownerReads(journeyId: number, ownerId: number) {
return request(server).get(`/api/journeys/${journeyId}/share-link`).set('Cookie', sessionCookie(ownerId));
}
/** The `name=value` of the unlock cookie a response set, and the whole header line. */
function unlockCookie(res: request.Response): { pair: string; line: string } {
const lines = ([] as string[]).concat(res.headers['set-cookie'] ?? []);
const line = lines.find((l) => l.startsWith('trek_journey_unlock=')) ?? '';
return { pair: line.split(';')[0] ?? '', line };
}
describe('a journey link with a password', () => {
it('JPUBLINK-E2E-001: every public route refuses until the right password is typed', async () => {
const { owner, journey, token } = await sharedJourney({ password: 'secret1' });
const read = await ownerReads(journey.id, owner.id);
expect(read.body.link).toMatchObject({ has_password: true, expires_at: null, view_count: 0 });
expect(JSON.stringify(read.body)).not.toContain('$2');
const locked = { error: 'Password required', code: 'JOURNEY_PASSWORD_REQUIRED' };
for (const path of ['', '/map-layers', '/photos/1/thumbnail', '/photo/local/a.jpg/1/original']) {
const res = await request(server).get(`/api/public/journey/${token}${path}`);
expect(res.status, path).toBe(401);
expect(res.body, path).toEqual(locked);
}
const wrong = await request(server).post(`/api/public/journey/${token}/unlock`).send({ password: 'nope' });
expect(wrong.status).toBe(401);
expect(wrong.body).toEqual({ error: 'Wrong password', code: 'JOURNEY_PASSWORD_INVALID' });
expect(unlockCookie(wrong).line).toBe('');
const right = await request(server).post(`/api/public/journey/${token}/unlock`).send({ password: 'secret1' });
expect(right.status).toBe(200);
expect(right.body).toEqual({ success: true });
const { pair, line } = unlockCookie(right);
expect(line).toContain(`Path=/api/public/journey/${token}`);
expect(line).toContain('HttpOnly');
expect(line).toContain('SameSite=Lax');
// Plain HTTP: a Secure cookie would be dropped and the reader locked out for good.
expect(line).not.toContain('Secure');
const open = await request(server).get(`/api/public/journey/${token}`).set('Cookie', pair);
expect(open.status).toBe(200);
expect(open.headers['cache-control']).toBe('private, no-store');
expect(open.body.journey.title).toBe(journey.title);
const map = await request(server).get(`/api/public/journey/${token}/map-layers`).set('Cookie', pair);
expect(map.status).toBe(200);
expect(map.headers['cache-control']).toBe('private, no-store');
});
it('JPUBLINK-E2E-002: a new password locks out the browsers that unlocked the old one', async () => {
const { owner, journey, token } = await sharedJourney({ password: 'secret1' });
const right = await request(server).post(`/api/public/journey/${token}/unlock`).send({ password: 'secret1' });
const { pair } = unlockCookie(right);
await request(server)
.post(`/api/journeys/${journey.id}/share-link`)
.set('Cookie', sessionCookie(owner.id))
.send({ password: 'secret2' });
expect((await request(server).get(`/api/public/journey/${token}`).set('Cookie', pair)).status).toBe(401);
});
it('JPUBLINK-E2E-003: wrong passwords count per address and link, a right one does not', async () => {
const { token } = await sharedJourney({ password: 'secret1' });
for (let i = 0; i < 10; i++) {
const res = await request(server)
.post(`/api/public/journey/${token}/unlock`)
.send({ password: `nope${i}` });
expect(res.status).toBe(401);
}
const limited = await request(server).post(`/api/public/journey/${token}/unlock`).send({ password: 'secret1' });
expect(limited.status).toBe(429);
// Another link is counted on its own.
const other = await sharedJourney({ password: 'secret9' });
const fine = await request(server).post(`/api/public/journey/${other.token}/unlock`).send({ password: 'secret9' });
expect(fine.status).toBe(200);
});
it('JPUBLINK-E2E-004: a bad unlock body is a 400, an unknown link a 404', async () => {
const { token } = await sharedJourney({ password: 'secret1' });
expect((await request(server).post(`/api/public/journey/${token}/unlock`).send({})).status).toBe(400);
expect((await request(server).post('/api/public/journey/nope/unlock').send({ password: 'x' })).status).toBe(404);
});
it('JPUBLINK-E2E-005: the owner refuses a password too short for the contract', async () => {
const { owner, journey } = await sharedJourney();
const res = await request(server)
.post(`/api/journeys/${journey.id}/share-link`)
.set('Cookie', sessionCookie(owner.id))
.send({ password: 'abc' });
expect(res.status).toBe(400);
});
});
describe('a journey link with an expiry', () => {
it('JPUBLINK-E2E-010: works until its date, then every route answers 410', async () => {
const { owner, journey, token } = await sharedJourney({ expires_at: '2099-01-01T00:00:00Z' });
expect((await request(server).get(`/api/public/journey/${token}`)).status).toBe(200);
await request(server)
.post(`/api/journeys/${journey.id}/share-link`)
.set('Cookie', sessionCookie(owner.id))
.send({ expires_at: '2020-01-01T00:00:00Z' });
const gone = { error: 'This link has expired', code: 'JOURNEY_LINK_EXPIRED' };
for (const path of ['', '/map-layers', '/photos/1/thumbnail']) {
const res = await request(server).get(`/api/public/journey/${token}${path}`);
expect(res.status, path).toBe(410);
expect(res.body, path).toEqual(gone);
}
const unlock = await request(server).post(`/api/public/journey/${token}/unlock`).send({ password: 'x' });
expect(unlock.status).toBe(410);
});
it('JPUBLINK-E2E-011: saving a switch keeps the password and the expiry', async () => {
const { owner, journey, token } = await sharedJourney({ password: 'secret1', expires_at: '2099-01-01T00:00:00Z' });
await request(server)
.post(`/api/journeys/${journey.id}/share-link`)
.set('Cookie', sessionCookie(owner.id))
.send({ share_timeline: true, share_gallery: false, share_map: true });
const read = await ownerReads(journey.id, owner.id);
expect(read.body.link).toMatchObject({
share_gallery: false,
has_password: true,
expires_at: '2099-01-01T00:00:00Z',
});
expect((await request(server).get(`/api/public/journey/${token}`)).status).toBe(401);
});
it('JPUBLINK-E2E-012: an existing link, saved before protection existed, stays open', async () => {
const { token } = await sharedJourney();
const row = await findRow(orm, JourneyShareTokens, { token });
expect(row).toMatchObject({ password_hash: null, password_version: 0, expires_at: null });
expect((await request(server).get(`/api/public/journey/${token}`)).status).toBe(200);
});
});
describe('the view count of a journey link', () => {
it('JPUBLINK-E2E-020: records each reader once a day and shows the count only to the owner', async () => {
const { owner, journey, token } = await sharedJourney();
await request(server).get(`/api/public/journey/${token}`).set('User-Agent', 'Reader A');
await request(server).get(`/api/public/journey/${token}/map-layers`).set('User-Agent', 'Reader C');
expect((await ownerReads(journey.id, owner.id)).body.link.view_count).toBe(0);
const view = (reader: string) =>
request(server).post(`/api/public/journey/${token}/view`).set('User-Agent', reader);
expect((await view('Reader A')).status).toBe(200);
expect((await view('Reader A')).status).toBe(200);
expect((await view('Reader B')).status).toBe(200);
const read = await ownerReads(journey.id, owner.id);
expect(read.body.link.view_count).toBe(2);
expect(read.body.link.last_viewed_at).toMatch(/Z$/);
const publicBody = await request(server).get(`/api/public/journey/${token}`);
expect(JSON.stringify(publicBody.body)).not.toContain('view_count');
});
it('JPUBLINK-E2E-021: a locked link counts nobody who has not unlocked it', async () => {
const { token } = await sharedJourney({ password: 'secret1' });
expect((await request(server).post(`/api/public/journey/${token}/view`).set('User-Agent', 'Stranger')).status).toBe(
401,
);
expect((await findRow(orm, JourneyShareTokens, { token }))?.view_count).toBe(0);
});
});
describe('the journey invite notification', () => {
it('JPUBLINK-E2E-030: a new contributor hears about the journey once, a role change says nothing', async () => {
const { user: owner } = await makeUser(orm, { username: 'owner_jp' });
const { user: friend } = await makeUser(orm);
const journey = await makeJourney(orm, owner.id, { title: 'Iceland ring road' });
const notifications = app.get(NotificationsService, { strict: false });
const add = (role: string) =>
request(server)
.post(`/api/journeys/${journey.id}/contributors`)
.set('Cookie', sessionCookie(owner.id))
.send({ user_id: friend.id, role });
const invites = { recipient: friend.id, title_key: 'notif.journey_invite.title' };
expect((await add('viewer')).status).toBe(201);
await notifications.settled();
const sent = await findRow(orm, Notifications, invites);
expect(sent).toMatchObject({ navigate_target: `/journey/${journey.id}` });
expect(JSON.parse(String(sent?.text_params))).toMatchObject({ actor: 'owner_jp', journey: 'Iceland ring road' });
// Posting the same person again only changes the role.
expect((await add('editor')).status).toBe(201);
await notifications.settled();
expect(await countRows(orm, Notifications, invites)).toBe(1);
});
});