/** * The social side of a journey, end to end (#1702, #1669): the whole app * (buildApp, the real guards, services, rate limits and repositories on a * migrated temp database) between the people on a journey, the readers of its * share link and the addresses that follow it by email. Mail never leaves the * process: the mailer's SMTP check and its send are spied on. */ import { buildApp } from '../../src/bootstrap'; import { JourneyEntries } from '../../src/db/entities/JourneyEntries.entity'; import { JourneyEntryComments } from '../../src/db/entities/JourneyEntryComments.entity'; import { JourneyShareSubscribers } from '../../src/db/entities/JourneyShareSubscribers.entity'; import { Journeys } from '../../src/db/entities/Journeys.entity'; import { Notifications } from '../../src/db/entities/Notifications.entity'; import { withRequestContext } from '../../src/nest/database/request-context'; import { JourneyDigestService } from '../../src/nest/journey/journey-digest.service'; import { MailerService } from '../../src/nest/notifications/mailer/mailer.service'; import { NotificationsService } from '../../src/nest/notifications/notifications.service'; import { forEachInOrder } from '../../src/utils/for-each-in-order'; import { addJourneyContributor, makeJourney, makeJourneyEntry } from '../helpers/factories/journeys'; import { countRows, deleteRows, findRow, findRows } 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, afterEach, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest'; let app: INestApplication; let orm: MikroORM; let server: Server; let mailer: MailerService; let notifications: NotificationsService; beforeAll(async () => { app = await buildApp(); orm = app.get(MikroORM); server = app.getHttpServer() as Server; mailer = app.get(MailerService, { strict: false }); notifications = app.get(NotificationsService, { strict: false }); await setAddonEnabled(orm, 'journey', true); }, 60_000); beforeEach(async () => { await resetRateLimits(app); }); afterEach(() => { vi.restoreAllMocks(); }); afterAll(async () => { await app?.close(); }); /** Mail as if SMTP were set up; answers the spy on the send. */ function mailWorks() { vi.spyOn(mailer, 'isSmtpConfigured').mockResolvedValue(true); return vi.spyOn(mailer, 'sendStandaloneEmail').mockResolvedValue(true); } /** An owner, a journey with one published entry, and the owner's editor and viewer. */ async function journeyWithPeople() { const { user: owner } = await makeUser(orm); const { user: editor } = await makeUser(orm); const { user: viewer } = await makeUser(orm); const { user: stranger } = await makeUser(orm); const journey = await makeJourney(orm, owner.id, { title: 'Azores' }); await addJourneyContributor(orm, journey.id, editor.id, 'editor'); await addJourneyContributor(orm, journey.id, viewer.id, 'viewer'); const entry = await makeJourneyEntry(orm, journey.id, owner.id, { title: 'Sete Cidades', announced: 1 }); return { owner, editor, viewer, stranger, journey, entry }; } /** The owner saves the journey's share link with `body`; answers its token. */ async function share(journeyId: number, ownerId: number, body: Record) { const res = await request(server) .post(`/api/journeys/${journeyId}/share-link`) .set('Cookie', sessionCookie(ownerId)) .send(body); expect(res.status).toBe(200); return res.body.token as string; } const as = (userId: number) => ({ Cookie: sessionCookie(userId) }); /** The value, or a failed test when there is none. */ function must(value: T | null | undefined): T { if (value === null || value === undefined) throw new Error('expected a value'); return value; } describe('comments in the app', () => { it('JSOCIAL-E2E-001: everyone on the journey comments and reads; the owner hears about it', async () => { const { owner, viewer, stranger, journey, entry } = await journeyWithPeople(); const added = await request(server) .post(`/api/journeys/${journey.id}/entries/${entry.id}/comments`) .set(as(viewer.id)) .send({ body: ' What a view! ' }); expect(added.status).toBe(201); expect(added.body.comment).toMatchObject({ entry_id: entry.id, user_id: viewer.id, author_name: viewer.username, is_guest: false, body: 'What a view!', hidden: false, own: true, }); const read = await request(server).get(`/api/journeys/${journey.id}/comments`).set(as(owner.id)); expect(read.status).toBe(200); expect(read.body.can_moderate).toBe(true); expect(read.body.comments).toHaveLength(1); expect(read.body.comments[0].own).toBe(false); await notifications.settled(); const note = await findRow(orm, Notifications, { recipient: owner.id, title_key: 'notif.journey_comment.title' }); expect(note).toMatchObject({ navigate_target: `/journey/${journey.id}` }); expect(JSON.parse(String(note?.text_params))).toMatchObject({ entry: 'Sete Cidades', journey: 'Azores' }); expect((await request(server).get(`/api/journeys/${journey.id}/comments`).set(as(stranger.id))).status).toBe(404); const strangerPost = await request(server) .post(`/api/journeys/${journey.id}/entries/${entry.id}/comments`) .set(as(stranger.id)) .send({ body: 'Hi' }); expect(strangerPost.status).toBe(404); }); it('JSOCIAL-E2E-002: the owner commenting gets no notification of their own', async () => { const { owner, journey, entry } = await journeyWithPeople(); await request(server) .post(`/api/journeys/${journey.id}/entries/${entry.id}/comments`) .set(as(owner.id)) .send({ body: 'Note to self' }); await notifications.settled(); expect(await countRows(orm, Notifications, { recipient: owner.id, title_key: 'notif.journey_comment.title' })).toBe( 0, ); }); it('JSOCIAL-E2E-003: an editor hides and shows; a viewer does not see a hidden one and may not hide', async () => { const { editor, viewer, journey, entry } = await journeyWithPeople(); const added = await request(server) .post(`/api/journeys/${journey.id}/entries/${entry.id}/comments`) .set(as(viewer.id)) .send({ body: 'Spam?' }); const id = added.body.comment.id as number; const hide = (userId: number, hidden: boolean) => request(server).patch(`/api/journeys/${journey.id}/comments/${id}`).set(as(userId)).send({ hidden }); expect((await hide(viewer.id, true)).status).toBe(403); expect((await hide(editor.id, true)).status).toBe(200); expect( (await request(server).get(`/api/journeys/${journey.id}/comments`).set(as(viewer.id))).body.comments, ).toEqual([]); const editorView = await request(server).get(`/api/journeys/${journey.id}/comments`).set(as(editor.id)); expect(editorView.body.comments[0].hidden).toBe(true); expect((await hide(editor.id, false)).status).toBe(200); expect( (await request(server).get(`/api/journeys/${journey.id}/comments`).set(as(viewer.id))).body.comments, ).toHaveLength(1); }); it('JSOCIAL-E2E-004: the author deletes their own, an editor anybody’s, a viewer nobody else’s', async () => { const { owner, editor, viewer, journey, entry } = await journeyWithPeople(); const post = async (userId: number) => ( await request(server) .post(`/api/journeys/${journey.id}/entries/${entry.id}/comments`) .set(as(userId)) .send({ body: 'x' }) ).body.comment.id as number; const ownersComment = await post(owner.id); const viewersComment = await post(viewer.id); const del = (userId: number, id: number) => request(server).delete(`/api/journeys/${journey.id}/comments/${id}`).set(as(userId)); expect((await del(viewer.id, ownersComment)).status).toBe(403); expect((await del(viewer.id, viewersComment)).status).toBe(200); expect((await del(editor.id, ownersComment)).status).toBe(200); expect(await countRows(orm, JourneyEntryComments, { journey: journey.id })).toBe(0); expect((await del(editor.id, ownersComment)).status).toBe(404); }); it('JSOCIAL-E2E-005: a comment that is too long, empty or under another journey is refused', async () => { const { owner, journey, entry } = await journeyWithPeople(); const other = await makeJourney(orm, owner.id); const otherEntry = await makeJourneyEntry(orm, other.id, owner.id); const post = (entryId: number, body: string) => request(server).post(`/api/journeys/${journey.id}/entries/${entryId}/comments`).set(as(owner.id)).send({ body }); expect((await post(entry.id, 'x'.repeat(2001))).status).toBe(400); expect((await post(entry.id, ' ')).status).toBe(400); expect((await post(otherEntry.id, 'Hi')).status).toBe(404); }); it('JSOCIAL-E2E-006: a deleted journey takes its comments along', async () => { const { owner, journey, entry } = await journeyWithPeople(); await request(server) .post(`/api/journeys/${journey.id}/entries/${entry.id}/comments`) .set(as(owner.id)) .send({ body: 'Bye' }); await deleteRows(orm, Journeys, { id: journey.id }); expect(await countRows(orm, JourneyEntryComments, { journey: journey.id })).toBe(0); }); }); describe('comments through the share link', () => { it('JSOCIAL-E2E-010: closed by default; the owner opens them and a guest comment shows at once', async () => { const { owner, journey, entry } = await journeyWithPeople(); const token = await share(journey.id, owner.id, {}); const post = (body: Record) => request(server).post(`/api/public/journey/${token}/entries/${entry.id}/comments`).send(body); expect((await request(server).get(`/api/public/journey/${token}`)).body.interaction).toEqual({ comments: false, subscribe: false, }); expect((await post({ name: 'Ana', body: 'Hello' })).status).toBe(403); expect((await request(server).get(`/api/public/journey/${token}/comments`)).body).toEqual({ comments: [] }); await share(journey.id, owner.id, { allow_comments: true }); expect((await request(server).get(`/api/public/journey/${token}`)).body.interaction.comments).toBe(true); const ok = await post({ name: ' Ana ', body: 'Hello from Lisbon' }); expect(ok.status).toBe(200); expect(ok.body).toEqual({ success: true }); const read = await request(server).get(`/api/public/journey/${token}/comments`); expect(read.status).toBe(200); expect(read.body.comments).toHaveLength(1); expect(read.body.comments[0]).toMatchObject({ entry_id: entry.id, author_name: 'Ana', is_guest: true, body: 'Hello from Lisbon', }); expect(JSON.stringify(read.body)).not.toContain('user_id'); // In the app the people on the journey see it too, as a guest's. const inApp = await request(server).get(`/api/journeys/${journey.id}/comments`).set(as(owner.id)); expect(inApp.body.comments[0]).toMatchObject({ is_guest: true, author_name: 'Ana', user_id: null }); }); it('JSOCIAL-E2E-011: saving another switch keeps comments open; a hidden comment leaves the page', async () => { const { owner, journey, entry } = await journeyWithPeople(); const token = await share(journey.id, owner.id, { allow_comments: true }); await share(journey.id, owner.id, { share_gallery: false }); const link = await request(server).get(`/api/journeys/${journey.id}/share-link`).set(as(owner.id)); expect(link.body.link).toMatchObject({ allow_comments: true, allow_subscriptions: false }); await request(server) .post(`/api/public/journey/${token}/entries/${entry.id}/comments`) .send({ name: 'Bot?', body: 'Buy now' }); const id = must(await findRow(orm, JourneyEntryComments, { journey: journey.id })).id; await request(server).patch(`/api/journeys/${journey.id}/comments/${id}`).set(as(owner.id)).send({ hidden: true }); expect((await request(server).get(`/api/public/journey/${token}/comments`)).body.comments).toEqual([]); }); it('JSOCIAL-E2E-012: a draft entry takes no comment, the honeypot saves nothing, the limit answers 429', async () => { const { owner, journey, entry } = await journeyWithPeople(); const draft = await makeJourneyEntry(orm, journey.id, owner.id, { is_draft: 1 }); const token = await share(journey.id, owner.id, { allow_comments: true }); const post = (entryId: number, body: Record) => request(server).post(`/api/public/journey/${token}/entries/${entryId}/comments`).send(body); expect((await post(draft.id, { name: 'Ana', body: 'Hi' })).status).toBe(404); expect((await post(entry.id, { name: 'Bot', body: 'Hi', website: 'http://spam.example' })).status).toBe(200); expect(await countRows(orm, JourneyEntryComments, { journey: journey.id })).toBe(0); await forEachInOrder( Array.from({ length: 8 }, (_, i) => i), async (i) => { expect((await post(entry.id, { name: 'Ana', body: `Hi ${i}` })).status).toBe(200); }, ); expect((await post(entry.id, { name: 'Ana', body: 'One more' })).status).toBe(429); }); it('JSOCIAL-E2E-013: a locked link refuses comments until it is unlocked', async () => { const { owner, journey, entry } = await journeyWithPeople(); const token = await share(journey.id, owner.id, { allow_comments: true, password: 'secret1' }); expect((await request(server).get(`/api/public/journey/${token}/comments`)).status).toBe(401); const post = await request(server) .post(`/api/public/journey/${token}/entries/${entry.id}/comments`) .send({ name: 'Ana', body: 'Hi' }); expect(post.status).toBe(401); }); }); describe('following a link by email', () => { it('JSOCIAL-E2E-020: closed by default, and closed while the instance cannot send mail', async () => { const { owner, journey } = await journeyWithPeople(); const token = await share(journey.id, owner.id, {}); const follow = () => request(server).post(`/api/public/journey/${token}/subscribe`).send({ email: 'a@example.com' }); expect((await follow()).status).toBe(403); await share(journey.id, owner.id, { allow_subscriptions: true }); vi.spyOn(mailer, 'isSmtpConfigured').mockResolvedValue(false); expect((await request(server).get(`/api/public/journey/${token}`)).body.interaction.subscribe).toBe(false); expect((await follow()).status).toBe(403); }); it('JSOCIAL-E2E-021: double opt-in, the owner list, unsubscribe', async () => { const send = mailWorks(); const { owner, viewer, journey } = await journeyWithPeople(); const token = await share(journey.id, owner.id, { allow_subscriptions: true }); expect((await request(server).get(`/api/public/journey/${token}`)).body.interaction.subscribe).toBe(true); const follow = await request(server) .post(`/api/public/journey/${token}/subscribe`) .send({ email: ' Ana@Example.com ', locale: 'de' }); expect(follow.status).toBe(200); const row = must(await findRow(orm, JourneyShareSubscribers, { email: 'ana@example.com' })); expect(row).toMatchObject({ locale: 'de', confirmed_at: null }); expect(send).toHaveBeenCalledTimes(1); const [to, mail] = must(send.mock.calls[0]); expect(to).toBe('ana@example.com'); expect(mail.cta.href).toContain(`/public/journey-follow/confirm?token=${row.confirm_token}`); expect(mail.footer.href).toContain(`/public/journey-follow/unsubscribe?token=${row.unsubscribe_token}`); expect(mail.subject).toContain('Azores'); // Asking again while it waits sends the same confirmation again, and adds nobody. await request(server).post(`/api/public/journey/${token}/subscribe`).send({ email: 'ana@example.com' }); expect(send).toHaveBeenCalledTimes(2); expect(await countRows(orm, JourneyShareSubscribers, {})).toBeGreaterThanOrEqual(1); const confirmed = await request(server) .post('/api/public/journey-subscriptions/confirm') .send({ token: row.confirm_token }); expect(confirmed.status).toBe(200); expect(confirmed.body).toEqual({ title: 'Azores', link: token }); // Once it follows, asking again sends nothing and says nothing different. const again = await request(server) .post(`/api/public/journey/${token}/subscribe`) .send({ email: 'ana@example.com' }); expect(again.status).toBe(200); expect(send).toHaveBeenCalledTimes(2); const list = await request(server).get(`/api/journeys/${journey.id}/share-link/subscribers`).set(as(owner.id)); expect(list.status).toBe(200); expect(list.body).toMatchObject({ count: 1, pending: 0 }); expect(list.body.subscribers[0]).toMatchObject({ email: 'ana@example.com', confirmed: true }); expect( (await request(server).get(`/api/journeys/${journey.id}/share-link/subscribers`).set(as(viewer.id))).status, ).toBe(403); const gone = await request(server) .post('/api/public/journey-subscriptions/unsubscribe') .send({ token: row.unsubscribe_token }); expect(gone.status).toBe(200); expect(await countRows(orm, JourneyShareSubscribers, { id: row.id })).toBe(0); // An unsubscribe link clicked twice answers the same. const twice = await request(server) .post('/api/public/journey-subscriptions/unsubscribe') .send({ token: row.unsubscribe_token }); expect(twice.status).toBe(200); expect( (await request(server).post('/api/public/journey-subscriptions/confirm').send({ token: row.confirm_token })) .status, ).toBe(404); }); it('JSOCIAL-E2E-022: the owner removes an address; a deleted link takes its addresses along', async () => { mailWorks(); const { owner, journey } = await journeyWithPeople(); const token = await share(journey.id, owner.id, { allow_subscriptions: true }); await request(server).post(`/api/public/journey/${token}/subscribe`).send({ email: 'one@example.com' }); await request(server).post(`/api/public/journey/${token}/subscribe`).send({ email: 'two@example.com' }); const one = must(await findRow(orm, JourneyShareSubscribers, { email: 'one@example.com' })); const removed = await request(server) .delete(`/api/journeys/${journey.id}/share-link/subscribers/${one.id}`) .set(as(owner.id)); expect(removed.status).toBe(200); expect( (await request(server).delete(`/api/journeys/${journey.id}/share-link/subscribers/${one.id}`).set(as(owner.id))) .status, ).toBe(404); await request(server).delete(`/api/journeys/${journey.id}/share-link`).set(as(owner.id)); expect(await countRows(orm, JourneyShareSubscribers, { email: 'two@example.com' })).toBe(0); }); it('JSOCIAL-E2E-023: following asks at most five times an hour per address and link', async () => { mailWorks(); const { owner, journey } = await journeyWithPeople(); const token = await share(journey.id, owner.id, { allow_subscriptions: true }); await forEachInOrder( Array.from({ length: 5 }, (_, i) => i), async (i) => { const res = await request(server) .post(`/api/public/journey/${token}/subscribe`) .send({ email: `r${i}@example.com` }); expect(res.status).toBe(200); }, ); const sixth = await request(server) .post(`/api/public/journey/${token}/subscribe`) .send({ email: 'r6@example.com' }); expect(sixth.status).toBe(429); }); }); describe('the daily digest', () => { const runDigest = () => withRequestContext(orm, () => app.get(JourneyDigestService, { strict: false }).run()); it('JSOCIAL-E2E-030: the people hear of new entries, followers get one mail, nothing is told twice', async () => { const send = mailWorks(); const { owner, editor, viewer, journey } = await journeyWithPeople(); const token = await share(journey.id, owner.id, { allow_subscriptions: true }); await request(server).post(`/api/public/journey/${token}/subscribe`).send({ email: 'reader@example.com' }); const follower = must(await findRow(orm, JourneyShareSubscribers, { email: 'reader@example.com' })); await request(server).post('/api/public/journey-subscriptions/confirm').send({ token: follower.confirm_token }); send.mockClear(); const fresh = await makeJourneyEntry(orm, journey.id, editor.id, { title: 'Furnas', entry_date: '2026-11-29' }); await makeJourneyEntry(orm, journey.id, editor.id, { title: 'Still a draft', is_draft: 1 }); const result = await runDigest(); await notifications.settled(); expect(result.journeys).toBeGreaterThanOrEqual(1); expect(result.mailed).toBe(1); const people = new Set([owner.id, editor.id, viewer.id]); const told = await findRows(orm, Notifications, { title_key: 'notif.journey_entry_published.title' }); const recipients = told .map((n) => n.recipient_id) .filter((id) => people.has(id)) .sort(); // The author of the only new entry is not told about it. expect(recipients).toEqual([owner.id, viewer.id].sort()); expect(send).toHaveBeenCalledTimes(1); const [to, mail] = must(send.mock.calls[0]); expect(to).toBe('reader@example.com'); expect(mail.body).toContain('Furnas'); expect(mail.body).not.toContain('Still a draft'); expect(mail.cta.href).toContain(`/public/journey/${token}`); expect((await findRow(orm, JourneyEntries, { id: fresh.id }))?.announced).toBe(1); send.mockClear(); expect(await runDigest()).toMatchObject({ journeys: 0, mailed: 0 }); expect(send).not.toHaveBeenCalled(); }); it('JSOCIAL-E2E-031: a follower of a link that got a password hears of something new, never what', async () => { const send = mailWorks(); const { owner, journey } = await journeyWithPeople(); const token = await share(journey.id, owner.id, { allow_subscriptions: true }); await request(server).post(`/api/public/journey/${token}/subscribe`).send({ email: 'locked-out@example.com' }); const follower = must(await findRow(orm, JourneyShareSubscribers, { email: 'locked-out@example.com' })); await request(server).post('/api/public/journey-subscriptions/confirm').send({ token: follower.confirm_token }); await share(journey.id, owner.id, { password: 'a new secret' }); send.mockClear(); await makeJourneyEntry(orm, journey.id, owner.id, { title: 'Behind the password', location_name: 'Furnas' }); await runDigest(); await notifications.settled(); const mails = send.mock.calls.filter(([to]) => to === 'locked-out@example.com'); expect(mails).toHaveLength(1); const [, mail] = must(mails[0]); expect(mail.body).not.toContain('Behind the password'); expect(mail.body).not.toContain('Furnas'); expect(mail.cta.href).toContain(`/public/journey/${token}`); }); });