merge dev into feat/postgres-support

This commit is contained in:
Maurice
2026-11-17 11:10:01 +01:00
3032 changed files with 153102 additions and 20800 deletions
+22 -1
View File
@@ -24,7 +24,7 @@ import { NotificationsModule } from '../../src/nest/notifications/notifications.
import { OidcModule } from '../../src/nest/oidc/oidc.module';
import { RealtimeModule } from '../../src/nest/realtime/realtime.module';
import { SettingsModule } from '../../src/nest/settings/settings.module';
import { countRows, findRow, insertRow } from '../helpers/factories/rows';
import { countRows, findRow, insertRow, updateRows } from '../helpers/factories/rows';
import { readAppSetting } from '../helpers/factories/settings';
import { makeTrip } from '../helpers/factories/trips';
import { makeAdmin, makeUser } from '../helpers/factories/users';
@@ -262,6 +262,27 @@ describe('Admin e2e (real auth + admin guard + temp SQLite)', () => {
});
});
it('DELETE /users/:id/sso clears the stored SSO identity, audits it, and is admin-only (#3065)', async () => {
const { user } = await makeUser(orm, { email: 'sso-moved@example.test', username: 'sso-moved' });
await updateRows(orm, Users, { id: user.id }, { oidc_sub: 'sub-old', oidc_issuer: 'https://idp.example.test' });
const denied = await request(server).delete(`/api/admin/users/${user.id}/sso`).set('Cookie', sessionCookie(2));
expect(denied.status).toBe(403);
const res = await request(server).delete(`/api/admin/users/${user.id}/sso`).set('Cookie', sessionCookie(1));
expect(res.status).toBe(200);
expect(res.body).toEqual({ success: true, unlinked: true });
const row = await findRow(orm, Users, { id: user.id });
expect(row && { oidc_sub: row.oidc_sub ?? null, oidc_issuer: row.oidc_issuer ?? null }).toEqual({
oidc_sub: null,
oidc_issuer: null,
});
expect(await findRow(orm, AuditLog, { action: 'admin.user_sso_unlink', resource: String(user.id) })).not.toBeNull();
const self = await request(server).delete('/api/admin/users/1/sso').set('Cookie', sessionCookie(1));
expect(self.status).toBe(400);
});
it('404 on the dev-only test-notification outside development', async () => {
const res = await request(server).post('/api/admin/dev/test-notification').set('Cookie', sessionCookie(1)).send({});
expect(res.status).toBe(404);
+22
View File
@@ -120,6 +120,28 @@ describe('Auth e2e (real auth guard + real service + real cookie service + temp
expect(res.body.permissions).toBeUndefined();
});
it('PUT /app-settings oidc_auto_redirect reaches the public app-config the login page reads (#2925)', async () => {
const admin = createUser(db as never, {
username: 'redirect-admin',
email: 'redirect-admin@example.test',
role: 'admin',
});
const autoRedirect = async () => (await request(server).get('/api/auth/app-config')).body.oidc_auto_redirect;
try {
expect(await autoRedirect()).toBe(true);
const res = await request(server)
.put('/api/auth/app-settings')
.set('Cookie', sessionCookie(admin.user.id))
.send({ oidc_auto_redirect: false });
expect(res.status).toBe(200);
expect(await readAppSetting(orm, 'oidc_auto_redirect')).toBe('false');
expect(await autoRedirect()).toBe(false);
} finally {
await deleteRows(orm, AppSettings, { key: 'oidc_auto_redirect' });
}
});
it('GET /me requires a session (401 without a cookie)', async () => {
expect((await request(server).get('/api/auth/me')).status).toBe(401);
});
+33 -1
View File
@@ -217,7 +217,9 @@ describe('Booking import e2e (#2477): a schema-bound provider on the upload rout
expect(res.body.warnings[0]).toMatch(
/^Incomplete LodgingReservation in Bestätigung_1234567890\.PDF\[0\] \(no reservationFor\)/,
);
expect(res.body.files).toEqual([{ fileName: 'Bestätigung_1234567890.PDF', aiAvailable: true, aiUsed: true }]);
expect(res.body.files).toEqual([
{ fileName: 'Bestätigung_1234567890.PDF', aiAvailable: true, aiUsed: true, outcome: 'ok' },
]);
});
it('once Gemini fills the venue: one hotel in EUR, attached to the uploaded file', async () => {
@@ -250,4 +252,34 @@ describe('Booking import e2e (#2477): a schema-bound provider on the upload rout
expect(res.body.items[0].metadata.priceCurrency).toBe('EUR');
expect(res.body.items[0].source.fileName).toBe('Bestätigung_2.pdf');
});
it('confirm writes a referenced booking once: a second copy, in the same request or a later one, is a duplicate', async () => {
const train = {
type: 'train',
title: 'ICE 123',
confirmation_number: 'ab 12c',
reservation_time: '2026-09-06T10:00',
source: { fileName: 'ticket.pdf', index: 0 },
};
const confirm = (items: unknown[]) =>
request(server)
.post(`/api/trips/${tripId}/reservations/import/booking/confirm`)
.set('Cookie', sessionCookie(1))
.send({ items });
const first = await confirm([train, { ...train, confirmation_number: 'AB12C' }]);
expect(first.status).toBe(201);
expect(first.body.created).toHaveLength(1);
expect(first.body.created[0]).toMatchObject({
title: 'ICE 123',
external_source: 'import',
external_id: 'AB12C|train|2026-09-06|',
sync_enabled: 0,
});
expect(first.body.failed).toEqual([{ index: 1, reason: 'duplicate' }]);
const again = await confirm([train]);
expect(again.status).toBe(201);
expect(again.body).toEqual({ created: [], failed: [{ index: 0, reason: 'duplicate' }] });
});
});
+40 -1
View File
@@ -3,11 +3,13 @@
* called through a real MCP session on the whole app (buildApp, the real
* registry with its addon and sub-feature gates, scopes and error mapper,
* the real CollabService and a migrated temp SQLite), the way the
* assistant's note cards read them.
* assistant's note cards read them. The shared links (#3076) ride the same
* path: saved over MCP, read back over MCP and over the REST route.
*/
import { buildApp } from '../../src/bootstrap';
import { createLocalMcpServer, McpRegistryService } from '../../src/nest-mcp';
import { withRequestContext } from '../../src/nest/database/request-context';
import { authCookie } from '../helpers/auth';
import { makeCollabNote } from '../helpers/factories/collab';
import { setAddonEnabled, setCollabFeature } from '../helpers/factories/settings';
import { makeTrip } from '../helpers/factories/trips';
@@ -17,6 +19,7 @@ import { Client } from '@modelcontextprotocol/sdk/client/index';
import { InMemoryTransport } from '@modelcontextprotocol/sdk/inMemory';
import type { INestApplication } from '@nestjs/common';
import request from 'supertest';
import { afterAll, beforeAll, describe, expect, it } from 'vitest';
let app: INestApplication;
@@ -107,3 +110,39 @@ describe('the shared notes over MCP', () => {
expect((await session(user.id, 'list_collab_notes', { tripId: trip.id })).answer).toEqual({ notes: [] });
});
});
describe('the shared links over MCP', () => {
it('COLLAB-MCP-E2E-004: saves a link the Links panel then lists, and reads it back', async () => {
const { user } = await makeUser(orm);
const trip = await makeTrip(orm, user.id, { title: 'Lisbon' });
const created = await session(user.id, 'create_collab_link', {
tripId: trip.id,
title: 'Tram 28 timetable',
url: 'https://example.com/tram-28',
});
const link = (created.answer as { link: Record<string, unknown> }).link;
expect(link).toMatchObject({ title: 'Tram 28 timetable', url: 'https://example.com/tram-28', pinned: 0 });
const { answer } = await session(user.id, 'list_collab_links', { tripId: trip.id });
expect(answer).toEqual({ links: [expect.objectContaining({ id: link.id, username: user.username })] });
const rest = await request(app.getHttpServer())
.get(`/api/trips/${trip.id}/collab/links`)
.set('Cookie', authCookie(user.id));
expect(rest.status).toBe(200);
expect(rest.body.links.map((row: { id: number }) => row.id)).toEqual([link.id]);
});
it('COLLAB-MCP-E2E-005: is gone while the links are switched off', async () => {
const { user } = await makeUser(orm);
const trip = await makeTrip(orm, user.id);
await setCollabFeature(orm, 'links', false);
try {
const { offered } = await session(user.id, 'list_collab_links', { tripId: trip.id });
expect(offered).not.toContain('list_collab_links');
expect(offered).not.toContain('create_collab_link');
expect(offered).toContain('list_collab_notes');
} finally {
await setCollabFeature(orm, 'links', true);
}
});
});
+91
View File
@@ -208,6 +208,66 @@ describe('Collections e2e (real auth guard + real service + temp SQLite)', () =>
expect(await countRows(orm, CollectionPlaces, { collection: col.id })).toBe(0);
});
// #2646: saving took the provider ids, website, phone and price while editing
// did not, so fixing one meant deleting and re-saving the place, which lost its
// labels, ratings, position and id.
it('COLLECTIONS-E2E-091: PATCH sets and clears the provider ids, website, phone and price', async () => {
const col = (
await request(server)
.post('/api/addons/collections')
.set('Cookie', sessionCookie(ownerId))
.send({ name: 'Listings' })
).body;
const saved = await request(server)
.post('/api/addons/collections/places')
.set('Cookie', sessionCookie(ownerId))
.send({ collection_id: col.id, name: 'Septime', phone: '+33 1 43 67 38 29', price: 40, currency: 'EUR' });
expect(saved.status).toBe(200);
const placeId = saved.body.place.id;
const patch = (body: Record<string, unknown>) =>
request(server)
.patch(`/api/addons/collections/places/${placeId}`)
.set('Cookie', sessionCookie(ownerId))
.send(body);
const patched = await patch({
google_place_id: 'ChIJseptime',
google_ftid: '0x47e6:0x1b2',
osm_id: 'node/42',
website: 'septime-charonne.fr',
price: 55,
});
expect(patched.status).toBe(200);
// A bare domain gets https:// as on save; what the update leaves out stays.
expect(patched.body).toMatchObject({
id: placeId,
google_place_id: 'ChIJseptime',
google_ftid: '0x47e6:0x1b2',
osm_id: 'node/42',
website: 'https://septime-charonne.fr',
phone: '+33 1 43 67 38 29',
price: 55,
currency: 'EUR',
});
const refused = await patch({ website: 'javascript:alert(1)' });
expect(refused.status).toBe(400);
expect(refused.body.error).toMatch(/^website: /);
expect((await findRow(orm, CollectionPlaces, { id: placeId }))?.website).toBe('https://septime-charonne.fr');
const cleared = await patch({ website: null, phone: null, price: null, currency: null, google_place_id: null });
expect(cleared.status).toBe(200);
expect(await findRow(orm, CollectionPlaces, { id: placeId })).toMatchObject({
website: null,
phone: null,
price: null,
currency: null,
google_place_id: null,
google_ftid: '0x47e6:0x1b2',
osm_id: 'node/42',
});
});
// Regression for #1437: editing a place (PATCH without a status field) must NOT
// reset a 'want'/'visited' place back to 'idea'.
it('COLLECTIONS-E2E-012: PATCH without status leaves the saved status unchanged', async () => {
@@ -648,6 +708,37 @@ describe('Collections e2e (real auth guard + real service + temp SQLite)', () =>
expect((await request(server).post('/api/addons/collections/gpx/read').send({ gpx: '<gpx/>' })).status).toBe(401);
});
// ── KML for Google My Maps (#1866) ───────────────────────────────────────
it('COLLECTIONS-E2E-092: a list goes out as KML pins, the places without coordinates counted', async () => {
const as = (userId: number) => ({ Cookie: sessionCookie(userId) });
const col = (await request(server).post('/api/addons/collections').set(as(ownerId)).send({ name: 'Rome' })).body;
await request(server).post('/api/addons/collections/places').set(as(ownerId)).send({
collection_id: col.id,
name: 'Pinned',
lat: 41.9,
lng: 12.48,
address: 'Via Nuova 1',
status: 'revisit',
});
await request(server)
.post('/api/addons/collections/places')
.set(as(ownerId))
.send({ collection_id: col.id, name: 'Vague' });
const exported = await request(server).get(`/api/addons/collections/${col.id}/export/kml`).set(as(ownerId));
expect(exported.status).toBe(200);
expect(exported.body).toMatchObject({ name: 'Rome', pins: 1, omitted: 1 });
expect(exported.body.kml).toContain('<name>Pinned</name>');
expect(exported.body.kml).toContain('<address>Via Nuova 1</address>');
expect(exported.body.kml).toContain('<coordinates>12.48,41.9</coordinates>');
expect(exported.body.kml).not.toContain('Vague');
// The same read as the list file: a list the caller cannot see has none.
expect((await request(server).get(`/api/addons/collections/${col.id}/export/kml`).set(as(otherId))).status).toBe(
404,
);
});
it('COLLECTIONS-E2E-082: a list the caller cannot see has no GPX either', async () => {
const col = (
await request(server).post('/api/addons/collections').set('Cookie', sessionCookie(ownerId)).send({ name: 'Mine' })
+1
View File
@@ -78,6 +78,7 @@ function makeClientStub() {
listVisits: boom('listVisits'),
listTracks: boom('listTracks'),
listPoints: boom('listPoints'),
listGeocodedPoints: boom('listGeocodedPoints'),
listVisitedCities: boom('listVisitedCities'),
findVisitsNear: boom('findVisitsNear'),
};
+40 -8
View File
@@ -62,6 +62,13 @@ let orm: TestOrm;
const BASE = 'https://trek.example.test';
/** The token at the end of a feed url, failing the case when the url has none. */
function feedToken(url: string, kind: 'trip' | 'user'): string {
const token = new RegExp(`${kind}/([0-9a-f-]+)[.]ics$`).exec(url)?.[1];
if (!token) throw new Error(`no ${kind} feed token in ${url}`);
return token;
}
describe('Calendar-feed e2e (real auth guard + temp SQLite)', () => {
let server: Server;
let app: Awaited<ReturnType<typeof build>>;
@@ -153,7 +160,7 @@ describe('Calendar-feed e2e (real auth guard + temp SQLite)', () => {
const { user: owner } = createUser(db);
const trip = createTrip(db, owner.id, { start_date: '2026-01-01', end_date: '2099-01-01' });
const gen = await request(server).post(`/api/trips/${trip.id}/feed/token`).set('Cookie', sessionCookie(owner.id));
const token = gen.body.feed_url.match(/trip\/([0-9a-f-]+)\.ics$/)![1];
const token = feedToken(gen.body.feed_url, 'trip');
expect((await request(server).get(`/api/feed/trip/${token}.ics`)).status).toBe(200);
const del = await request(server).delete(`/api/trips/${trip.id}/feed/token`).set('Cookie', sessionCookie(owner.id));
@@ -232,7 +239,7 @@ describe('Calendar-feed e2e (real auth guard + temp SQLite)', () => {
const { user: member } = createUser(db);
const trip = createTrip(db, owner.id, { start_date: '2026-01-01', end_date: '2099-01-01' });
const gen = await request(server).post(`/api/trips/${trip.id}/feed/token`).set('Cookie', sessionCookie(owner.id));
const token = gen.body.feed_url.match(/trip\/([0-9a-f-]+)\.ics$/)![1];
const token = feedToken(gen.body.feed_url, 'trip');
addTripMember(db, trip.id, member.id);
// The member may no longer manage it, but existing subscriptions must not break.
@@ -248,7 +255,7 @@ describe('Calendar-feed e2e (real auth guard + temp SQLite)', () => {
const { user: owner } = createUser(db);
const trip = createTrip(db, owner.id, { start_date: '2026-01-01', end_date: '2099-01-01' });
const gen = await request(server).post(`/api/trips/${trip.id}/feed/token`).set('Cookie', sessionCookie(owner.id));
const token = gen.body.feed_url.match(/trip\/([0-9a-f-]+)\.ics$/)![1];
const token = feedToken(gen.body.feed_url, 'trip');
const res = await request(server).get(`/api/feed/trip/${token}.ics`);
expect(res.status).toBe(200);
@@ -256,7 +263,7 @@ describe('Calendar-feed e2e (real auth guard + temp SQLite)', () => {
expect(res.text).toContain('REFRESH-INTERVAL;VALUE=DURATION:PT1H');
expect(res.text).toContain('X-PUBLISHED-TTL:PT1H');
expect(res.text).toContain('BEGIN:VEVENT');
expect(buildTripCalendar).toHaveBeenCalledWith(trip.id);
expect(buildTripCalendar).toHaveBeenCalledWith(trip.id, { dayEvents: true });
});
// The @Public feed quoted cal.filename straight into Content-Disposition, so
@@ -265,7 +272,7 @@ describe('Calendar-feed e2e (real auth guard + temp SQLite)', () => {
const { user: owner } = createUser(db);
const trip = createTrip(db, owner.id, { start_date: '2026-01-01', end_date: '2099-01-01' });
const gen = await request(server).post(`/api/trips/${trip.id}/feed/token`).set('Cookie', sessionCookie(owner.id));
const token = gen.body.feed_url.match(/trip\/([0-9a-f-]+)\.ics$/)![1];
const token = feedToken(gen.body.feed_url, 'trip');
// ASCII parity first: the default sample calendar keeps the exact legacy header.
const plain = await request(server).get(`/api/feed/trip/${token}.ics`);
@@ -279,6 +286,17 @@ describe('Calendar-feed e2e (real auth guard + temp SQLite)', () => {
);
});
it('public trip feed: days=0 asks the calendar for no per-day summaries (#2602)', async () => {
const { user: owner } = createUser(db);
const trip = createTrip(db, owner.id, { start_date: '2026-01-01', end_date: '2099-01-01' });
const gen = await request(server).post(`/api/trips/${trip.id}/feed/token`).set('Cookie', sessionCookie(owner.id));
const token = feedToken(gen.body.feed_url, 'trip');
const res = await request(server).get(`/api/feed/trip/${token}.ics?days=0`);
expect(res.status).toBe(200);
expect(buildTripCalendar).toHaveBeenCalledWith(trip.id, { dayEvents: false });
});
it('public trip feed: 404 for an unknown token', async () => {
const res = await request(server).get('/api/feed/trip/00000000-0000-0000-0000-000000000000.ics');
expect(res.status).toBe(404);
@@ -302,7 +320,7 @@ describe('Calendar-feed e2e (real auth guard + temp SQLite)', () => {
createTrip(db, owner.id, { title: 'Old', start_date: '2000-01-01', end_date: '2000-01-10' });
const gen = await request(server).post('/api/feed/user/token').set('Cookie', sessionCookie(owner.id));
const token = gen.body.feed_url.match(/user\/([0-9a-f-]+)\.ics$/)![1];
const token = feedToken(gen.body.feed_url, 'user');
const res = await request(server).get(`/api/feed/user/${token}.ics`);
expect(res.status).toBe(200);
@@ -322,7 +340,7 @@ describe('Calendar-feed e2e (real auth guard + temp SQLite)', () => {
addTripMember(db, shared.id, owner.id);
const gen = await request(server).post('/api/feed/user/token').set('Cookie', sessionCookie(owner.id));
const token = gen.body.feed_url.match(/user\/([0-9a-f-]+)\.ics$/)![1];
const token = feedToken(gen.body.feed_url, 'user');
const res = await request(server).get(`/api/feed/user/${token}.ics`);
expect(res.status).toBe(200);
@@ -331,6 +349,20 @@ describe('Calendar-feed e2e (real auth guard + temp SQLite)', () => {
expect(calledIds).toEqual([owned.id, shared.id].sort((a, b) => a - b));
});
it('all-trips feed: days=0 reaches the calendar of every trip (#2602)', async () => {
const { user: owner } = createUser(db);
const first = createTrip(db, owner.id, { start_date: '2026-01-01', end_date: '2099-01-01' });
const second = createTrip(db, owner.id, { start_date: '2026-02-01', end_date: '2099-01-01' });
const gen = await request(server).post('/api/feed/user/token').set('Cookie', sessionCookie(owner.id));
const token = feedToken(gen.body.feed_url, 'user');
const res = await request(server).get(`/api/feed/user/${token}.ics?days=0`);
expect(res.status).toBe(200);
expect(buildTripCalendar).toHaveBeenCalledWith(first.id, { dayEvents: false });
expect(buildTripCalendar).toHaveBeenCalledWith(second.id, { dayEvents: false });
});
it('public user feed: 404 for an unknown token', async () => {
const res = await request(server).get('/api/feed/user/00000000-0000-0000-0000-000000000000.ics');
expect(res.status).toBe(404);
@@ -355,7 +387,7 @@ describe('Calendar-feed e2e (real auth guard + temp SQLite)', () => {
}));
const gen = await request(server).post('/api/feed/user/token').set('Cookie', sessionCookie(owner.id));
const token = gen.body.feed_url.match(/user\/([0-9a-f-]+)\.ics$/)![1];
const token = feedToken(gen.body.feed_url, 'user');
const res = await request(server).get(`/api/feed/user/${token}.ics`);
expect(res.status).toBe(200);
+2 -1
View File
@@ -40,7 +40,8 @@ const { db } = vi.hoisted(() => {
// (is_archived, reminder_days and the two timestamps); the real schema has all four.
tmp.exec(`CREATE TABLE trips (id INTEGER PRIMARY KEY AUTOINCREMENT, user_id INTEGER, title TEXT, currency TEXT,
is_archived INTEGER DEFAULT 0, reminder_days INTEGER DEFAULT 3,
created_at DATETIME DEFAULT CURRENT_TIMESTAMP, updated_at DATETIME DEFAULT CURRENT_TIMESTAMP);`);
created_at DATETIME DEFAULT CURRENT_TIMESTAMP, updated_at DATETIME DEFAULT CURRENT_TIMESTAMP,
costs_mode TEXT NOT NULL DEFAULT 'split');`);
// TripAccessGuard now reads TripsRepository.findAccessible directly
// (Plan 3c Task 0b), a real join against trip_members.
tmp.exec('CREATE TABLE trip_members (trip_id INTEGER NOT NULL, user_id INTEGER NOT NULL);');
+154
View File
@@ -0,0 +1,154 @@
/**
* Live flight status e2e: GET /api/trips/:tripId/flights/live through the
* real JwtAuthGuard and TripAccessGuard over a migrated snapshot db. The
* read never asks a feed, so fetch is a spy that must stay unused; the
* response contract is checked on every 200 (NODE_ENV=test).
*/
import { AppSettings } from '../../src/db/entities/AppSettings.entity';
import { AppConfigModule } from '../../src/nest/app-config/app-config.module';
import { TrekExceptionFilter } from '../../src/nest/common/trek-exception.filter';
import { FlightLiveModule } from '../../src/nest/flight-live/flight-live.module';
import { RealtimeModule } from '../../src/nest/realtime/realtime.module';
import { createSnapshotTestDb } from '../helpers/db-mock';
import { makeReservation, makeReservationEndpoint } from '../helpers/factories/reservations';
import { deleteRows, insertRow } from '../helpers/factories/rows';
import { makeTrip } from '../helpers/factories/trips';
import { makeUser } from '../helpers/factories/users';
import { createTestMikroOrmModule } from '../helpers/test-orm';
import { TestUnitOfWorkModule } from '../helpers/test-uow';
import { sessionCookie } from './harness';
import { MikroORM } from '@mikro-orm/core';
import { Test } from '@nestjs/testing';
import { tripFlightLiveResponseSchema } from '@trek/shared';
import cookieParser from 'cookie-parser';
import type { Server } from 'http';
import request from 'supertest';
import { afterAll, afterEach, beforeAll, describe, expect, it, vi } from 'vitest';
const db = createSnapshotTestDb();
describe('Flight live e2e (real guards + snapshot SQLite)', () => {
let server: Server;
let app: Awaited<ReturnType<typeof build>>;
let ownerId: number;
let strangerId: number;
let tripId: number;
let flightId: number;
async function build() {
const moduleRef = await Test.createTestingModule({
imports: [
await TestUnitOfWorkModule.forRoot(db),
await createTestMikroOrmModule(db),
AppConfigModule,
RealtimeModule,
FlightLiveModule,
],
}).compile();
const nest = moduleRef.createNestApplication();
nest.use(cookieParser());
nest.useGlobalFilters(new TrekExceptionFilter());
await nest.init();
return nest;
}
beforeAll(async () => {
app = await build();
server = app.getHttpServer();
const orm = app.get(MikroORM);
const { user: owner } = await makeUser(orm);
const { user: stranger } = await makeUser(orm);
ownerId = owner.id;
strangerId = stranger.id;
tripId = (await makeTrip(orm, owner.id, { title: 'Japan' })).id;
const flight = await makeReservation(orm, tripId, {
title: 'FRA to HND',
type: 'flight',
metadata: JSON.stringify({ flight_number: 'LH 716', airline: 'Lufthansa' }),
});
flightId = flight.id;
await makeReservationEndpoint(orm, flight.id, {
role: 'from',
sequence: 0,
name: 'Frankfurt (FRA)',
code: 'FRA',
lat: 50.0333,
lng: 8.5706,
timezone: 'Europe/Berlin',
local_date: '2030-07-01',
local_time: '13:40',
});
await makeReservationEndpoint(orm, flight.id, {
role: 'to',
sequence: 1,
name: 'Tokyo Haneda (HND)',
code: 'HND',
lat: 35.5523,
lng: 139.7798,
timezone: 'Asia/Tokyo',
local_date: '2030-07-02',
local_time: '08:15',
});
});
afterEach(() => {
vi.unstubAllGlobals();
});
afterAll(async () => {
await app.close();
db.close();
});
const url = (id: number = tripId) => `/api/trips/${id}/flights/live`;
it('FLE2E-001: 401 without a session cookie', async () => {
const res = await request(server).get(url());
expect(res.status).toBe(401);
});
it('FLE2E-002: 404 "Trip not found" for a trip the caller cannot reach', async () => {
const res = await request(server).get(url()).set('Cookie', sessionCookie(strangerId));
expect(res.status).toBe(404);
expect(res.body).toEqual({ error: 'Trip not found' });
});
it('FLE2E-003: 200 with every flight leg and its schedule in UTC, without asking a feed', async () => {
const fetcher = vi.fn();
vi.stubGlobal('fetch', fetcher);
const res = await request(server).get(url()).set('Cookie', sessionCookie(ownerId));
expect(res.status).toBe(200);
expect(tripFlightLiveResponseSchema.parse(res.body)).toEqual(res.body);
expect(res.body).toMatchObject({ enabled: true, attribution: 'Live positions: adsb.lol (ODbL)' });
expect(res.body.flights).toEqual([
expect.objectContaining({
reservation_id: flightId,
leg_index: 0,
callsign: 'DLH716',
flight_number: 'LH 716',
service_date: '2030-07-01',
origin: { code: 'FRA', name: 'Frankfurt', lat: 50.0333, lng: 8.5706, timezone: 'Europe/Berlin' },
destination: { code: 'HND', name: 'Tokyo Haneda', lat: 35.5523, lng: 139.7798, timezone: 'Asia/Tokyo' },
phase: 'scheduled',
scheduled_departure: '2030-07-01T11:40:00.000Z',
scheduled_arrival: '2030-07-01T23:15:00.000Z',
position: null,
source: null,
}),
]);
expect(fetcher).not.toHaveBeenCalled();
});
it('FLE2E-004: switched off by the admin it answers enabled false and no flights', async () => {
const orm = app.get(MikroORM);
await insertRow(orm, AppSettings, { key: 'flight_live_enabled', value: 'false' });
try {
const res = await request(server).get(url()).set('Cookie', sessionCookie(ownerId));
expect(res.status).toBe(200);
expect(res.body).toEqual({ enabled: false, attribution: null, flights: [] });
} finally {
await deleteRows(orm, AppSettings, { key: 'flight_live_enabled' });
}
});
});
+286
View File
@@ -0,0 +1,286 @@
/**
* /api/mail-ingest e2e: the real JwtAuthGuard, TripAccessGuard, AdminGuard,
* Zod pipe, multer and response contracts over a snapshot SQLite, with
* MailIngestModule's real repositories and services. Replaced: what reaches
* outside (the AI reading, kitinerary, file storage, geocoding, the
* notifications). A mail goes in by upload and by the signed webhook, is
* read by the real pipeline, and is added, undone and refused through the
* routes the client and the admin dialog use.
*/
import { Reservations } from '../../src/db/entities/Reservations.entity';
import { BookingImportService } from '../../src/nest/booking-import/booking-import.service';
import { importExternalId } from '../../src/nest/booking-import/booking-origin';
import { encrypt_api_key } from '../../src/nest/common/crypto/apiKeyCrypto';
import { TrekExceptionFilter } from '../../src/nest/common/trek-exception.filter';
import { ZodValidationPipe } from '../../src/nest/common/zod-validation.pipe';
import { withRequestContext } from '../../src/nest/database/request-context';
import { FilesService } from '../../src/nest/files/files.service';
import { MailReadService } from '../../src/nest/llm-parse/mail-read.service';
import { walkMail } from '../../src/nest/llm-parse/mime-walker';
import { MailIngestProcessJob } from '../../src/nest/mail-ingest/mail-ingest-process.job';
import { signWebhookMail } from '../../src/nest/mail-ingest/mail-ingest-webhook.service';
import { MailIngestModule } from '../../src/nest/mail-ingest/mail-ingest.module';
import { MapsService } from '../../src/nest/maps/maps.service';
import { NotificationsService } from '../../src/nest/notifications/notifications.service';
import { createSnapshotTestDb } from '../helpers/db-mock';
import { countRows } from '../helpers/factories/rows';
import { setAppSetting } from '../helpers/factories/settings';
import { makeTrip } from '../helpers/factories/trips';
import { makeAdmin, makeUser } from '../helpers/factories/users';
import { createTestMikroOrmModule, createTestOrm, type TestOrm } from '../helpers/test-orm';
import { TestUnitOfWorkModule } from '../helpers/test-uow';
import { sessionCookie } from './harness';
import { MikroORM } from '@mikro-orm/core';
import { Test } from '@nestjs/testing';
import type { BookingImportPreviewItem } from '@trek/shared';
import cookieParser from 'cookie-parser';
import type { Server } from 'http';
import request from 'supertest';
import { afterAll, beforeAll, describe, expect, it, vi } from 'vitest';
// A snapshot database of its own, handed to the ORM, the unit of work and the factories.
const db = createSnapshotTestDb();
const USER = 1;
const OTHER = 2;
const ADMIN = 3;
const SECRET = 'w'.repeat(40);
const TEMPLATE = 'trek+{token}@mail.example.com';
/** A day `days` from today: the checks take a booking only within a few years of now. */
const dayFromToday = (days: number) => new Date(Date.now() + days * 86_400_000).toISOString().slice(0, 10);
const FLIGHT_DAY = dayFromToday(30);
const endpoint = (role: 'from' | 'to', name: string, code: string, lat: number, lng: number) => ({
role,
sequence: role === 'from' ? 0 : 1,
name,
code,
lat,
lng,
timezone: null,
local_time: null,
local_date: null,
});
const FLIGHT: BookingImportPreviewItem = {
type: 'flight',
title: 'LH 716 Tokyo to Osaka',
reservation_time: `${FLIGHT_DAY}T10:00`,
reservation_end_time: `${FLIGHT_DAY}T11:15`,
confirmation_number: 'ABC123',
metadata: { flight_number: 'LH716' },
endpoints: [
endpoint('from', 'Tokyo Haneda', 'HND', 35.55, 139.78),
endpoint('to', 'Osaka Itami', 'ITM', 34.78, 135.44),
],
source: { fileName: 'mail.eml', index: 0 },
};
const bookingImport = {
readMailBookings: vi.fn(async (): Promise<BookingImportPreviewItem[]> => [FLIGHT]),
mapAiReservations: vi.fn(async (): Promise<BookingImportPreviewItem[]> => []),
externalKey: (item: BookingImportPreviewItem) => importExternalId(item),
};
const reader = { walk: (raw: Buffer) => walkMail(raw), isAvailable: vi.fn(async () => false), read: vi.fn() };
function eml(id: string, to = 'trips@example.com'): Buffer {
return Buffer.from(
[
'From: Mia <mia@example.com>',
`To: ${to}`,
'Subject: Fwd: Your flight LH 716',
`Message-ID: <${id}@example.com>`,
'Date: Mon, 1 Jan 2030 10:00:00 +0000',
'Content-Type: text/plain; charset=utf-8',
'',
`Booking reference ABC123. Flight LH 716 from Tokyo to Osaka on ${FLIGHT_DAY}.`,
].join('\r\n'),
);
}
describe('/api/mail-ingest e2e (real guards + snapshot SQLite)', () => {
let orm: TestOrm;
let server: Server;
let app: Awaited<ReturnType<typeof build>>;
let tripId: number;
async function build() {
const moduleRef = await Test.createTestingModule({
imports: [await TestUnitOfWorkModule.forRoot(db), await createTestMikroOrmModule(db), MailIngestModule],
})
.overrideProvider(BookingImportService)
.useValue(bookingImport)
.overrideProvider(MailReadService)
.useValue(reader)
.overrideProvider(FilesService)
.useValue({ createFileFromBytes: vi.fn(async () => ({ id: 77 })), softDeleteFile: vi.fn() })
.overrideProvider(MapsService)
.useValue({ geocodeQuery: vi.fn(async () => null) })
.overrideProvider(NotificationsService)
.useValue({ send: vi.fn(async () => ({ attempted: 0, delivered: 0 })), registerResponseAction: vi.fn() })
.compile();
const nest = moduleRef.createNestApplication();
nest.use(cookieParser());
nest.useGlobalFilters(new TrekExceptionFilter());
nest.useGlobalPipes(new ZodValidationPipe());
await nest.init();
return nest;
}
const as = (userId: number) => ({ Cookie: sessionCookie(userId) });
/**
* Runs the pipeline over what came in, the way its two-minute job does: the
* cron registrar runs every tick in a request context of its own.
*/
const readQueued = () => withRequestContext(app.get(MikroORM), () => app.get(MailIngestProcessJob).tick());
beforeAll(async () => {
orm = await createTestOrm(db);
await makeUser(orm, { id: USER, username: 'mia', email: 'mia@example.com' });
await makeUser(orm, { id: OTHER, username: 'noa', email: 'noa@example.com' });
await makeAdmin(orm, { id: ADMIN, username: 'admin', email: 'admin@example.com' });
const dates = { start_date: dayFromToday(20), end_date: dayFromToday(40) };
tripId = (await makeTrip(orm, USER, { title: 'Japan', ...dates })).id;
await setAppSetting(orm, 'mail_ingest_enabled', 'true');
await setAppSetting(orm, 'mail_ingest_address_template', TEMPLATE);
app = await build();
server = app.getHttpServer();
});
afterAll(async () => {
await app.close();
await orm.close();
});
it('MAIL-E2E-001: 401 without a session on every route a person or an admin uses', async () => {
const paths = ['/api/mail-ingest/settings', '/api/mail-ingest/inbox', '/api/admin/mail-ingest/status'];
const answers = await Promise.all(paths.map((path) => request(server).get(path)));
answers.forEach((answer, i) => expect(answer.status, paths[i]).toBe(401));
expect((await request(server).post(`/api/trips/${tripId}/mail-ingest/address`)).status).toBe(401);
});
it('MAIL-E2E-002: the settings card, its switches and a renewed own address', async () => {
const card = await request(server).get('/api/mail-ingest/settings').set(as(USER));
expect(card.status).toBe(200);
expect(card.body).toMatchObject({ available: true, ai_available: false, pending: 0 });
// The first look makes the person's own address, so nobody has to ask for one before forwarding.
const first = card.body.address.address as string;
expect(first).toMatch(/^trek\+[a-z2-7]{24}@mail\.example\.com$/);
const again = await request(server).get('/api/mail-ingest/settings').set(as(USER));
expect(again.body.address.address).toBe(first);
expect((await request(server).patch('/api/mail-ingest/settings').set(as(USER)).send({})).status).toBe(400);
const off = await request(server).patch('/api/mail-ingest/settings').set(as(USER)).send({ auto_add: false });
expect(off.status).toBe(200);
expect(off.body.prefs).toEqual({ enabled: true, ai_enabled: true, auto_add: false });
const renewed = await request(server).post('/api/mail-ingest/address/renew').set(as(USER));
expect(renewed.status).toBe(200);
expect(renewed.body.address.address).toMatch(/^trek\+[a-z2-7]{24}@mail\.example\.com$/);
expect(renewed.body.address.address).not.toBe(first);
});
it('MAIL-E2E-003: an uploaded mail waits in the inbox, is added by hand and undone, for its person', async () => {
const soon = vi.spyOn(app.get(MailIngestProcessJob), 'runSoon');
const upload = await request(server)
.post('/api/mail-ingest/upload')
.set(as(USER))
.attach('file', eml('upload-1'), { filename: 'booking.eml', contentType: 'message/rfc822' });
expect(upload.status).toBe(201);
expect(upload.body).toMatchObject({ duplicate: false, message: { transport: 'upload', status: 'queued' } });
expect(soon).toHaveBeenCalledTimes(1);
soon.mockRestore();
expect(await readQueued()).toBe(1);
const inbox = await request(server).get('/api/mail-ingest/inbox').set(as(USER));
expect(inbox.status).toBe(200);
expect(inbox.body.pending).toBe(1);
const [entry] = inbox.body.entries;
expect(entry).toMatchObject({ reason: 'ask_first', suggested_trip: { id: tripId, title: 'Japan' } });
expect((await request(server).get('/api/mail-ingest/inbox/count').set(as(USER))).body).toEqual({ pending: 1 });
const apply = (userId: number) =>
request(server).post(`/api/mail-ingest/candidates/${entry.id}/apply`).set(as(userId)).send({});
expect((await apply(OTHER)).status).toBe(404);
const applied = await apply(USER);
expect(applied.status).toBe(200);
expect(applied.body.candidate).toMatchObject({ resolution: 'applied', resolved_trip_id: tripId });
expect(await countRows(orm, Reservations, { trip: tripId })).toBe(1);
const undone = await request(server).post(`/api/mail-ingest/candidates/${entry.id}/undo`).set(as(USER)).send({});
expect(undone.status).toBe(200);
expect(undone.body.candidate.resolution).toBe('undone');
expect(await countRows(orm, Reservations, { trip: tripId })).toBe(0);
const preview = (userId: number) =>
request(server).get(`/api/mail-ingest/messages/${entry.message_id}/preview`).set(as(userId));
const shown = await preview(USER);
expect(shown.status).toBe(200);
expect(shown.body.text).toContain('Booking reference ABC123');
expect((await preview(OTHER)).status).toBe(404);
});
it('MAIL-E2E-004: an upload that is no mail, and a closed body, are refused', async () => {
const pdf = await request(server)
.post('/api/mail-ingest/upload')
.set(as(USER))
.attach('file', Buffer.from('%PDF-1.4'), { filename: 'ticket.pdf', contentType: 'application/pdf' });
expect(pdf.status).toBe(400);
const extra = await request(server).post('/api/mail-ingest/candidates/1/undo').set(as(USER)).send({ token: 'x' });
expect(extra.status).toBe(400);
});
it('MAIL-E2E-005: a trip address is made by a member who may add bookings, and hidden from others', async () => {
const path = `/api/trips/${tripId}/mail-ingest/address`;
const made = await request(server).post(path).set(as(USER));
expect(made.status).toBe(200);
expect(made.body.address).toMatchObject({ trip_id: tripId });
expect((await request(server).get(path).set(as(USER))).body).toEqual(made.body);
expect((await request(server).get(path).set(as(OTHER))).status).toBe(404);
expect((await request(server).delete(path).set(as(USER))).body).toEqual({ success: true });
expect((await request(server).get(path).set(as(USER))).body).toEqual({ address: null });
});
it('MAIL-E2E-006: the status card and the connection test are the admin’s, and hold counts only', async () => {
expect((await request(server).get('/api/admin/mail-ingest/status').set(as(USER))).status).toBe(403);
const status = await request(server).get('/api/admin/mail-ingest/status').set(as(ADMIN));
expect(status.status).toBe(200);
expect(status.body).toMatchObject({ transport: 'off', last_day: { by_status: { processed: 1 } } });
expect(JSON.stringify(status.body)).not.toContain('LH 716');
const test = await request(server).post('/api/admin/mail-ingest/test').set(as(ADMIN));
expect(test.status).toBe(200);
expect(test.body).toMatchObject({ transport: 'off', ok: false });
});
it('MAIL-E2E-007: the webhook is a 404 until it is the transport, then takes signed mail only', async () => {
const own = await request(server).get('/api/mail-ingest/settings').set(as(USER));
const address: string = own.body.address.address;
const raw = eml('hook-1', address);
const post = (headers: Record<string, string>, body: Buffer = raw) =>
request(server)
.post('/api/mail-ingest/inbound')
.set({ 'Content-Type': 'message/rfc822', ...headers })
.send(body);
const signed = (timestamp = String(Math.floor(Date.now() / 1000))) => ({
'X-Trek-Timestamp': timestamp,
'X-Trek-Recipient': address,
'X-Trek-Signature': `sha256=${signWebhookMail(SECRET, timestamp, address, raw)}`,
});
expect((await post(signed())).status).toBe(404);
await setAppSetting(orm, 'mail_ingest_transport', 'webhook');
await setAppSetting(orm, 'mail_ingest_webhook_secret', encrypt_api_key(SECRET));
expect((await post({})).status).toBe(401);
expect((await post(signed(String(Math.floor(Date.now() / 1000) - 3600)))).status).toBe(401);
const json = await request(server).post('/api/mail-ingest/inbound').set(signed()).send({ raw: 'x' });
expect(json.status).toBe(415);
const taken = await post(signed());
expect(taken.status).toBe(200);
expect(taken.body).toEqual({ accepted: true, duplicate: false });
expect((await post(signed())).body).toEqual({ accepted: true, duplicate: true });
});
});
+145
View File
@@ -0,0 +1,145 @@
/**
* Native sign-in hand-off e2e: the real CookieAuthGuard, the real cookie
* helpers, the real AuthService and session table over a migrated temp SQLite
* db. Walks the whole round trip the apps make: the browser side mints a code
* for a challenge, the WebView side redeems it with the verifier and walks
* away with a session cookie that /api/auth/me accepts.
*/
import { AuditLog } from '../../src/db/entities/AuditLog.entity';
import { AuthModule } from '../../src/nest/auth/auth.module';
import { TrekExceptionFilter } from '../../src/nest/common/trek-exception.filter';
import { ZodValidationPipe } from '../../src/nest/common/zod-validation.pipe';
import { NativeAuthModule } from '../../src/nest/native-auth/native-auth.module';
import { MailerService } from '../../src/nest/notifications/mailer/mailer.service';
import { createSnapshotTestDb } from '../helpers/db-mock';
import { findRows } from '../helpers/factories/rows';
import { makeUser } from '../helpers/factories/users';
import { resetRateLimits } from '../helpers/test-db';
import { createTestMikroOrmModule, createTestOrm, type TestOrm } from '../helpers/test-orm';
import { TestUnitOfWorkModule } from '../helpers/test-uow';
import { sessionCookie, signSession } from './harness';
import { Test } from '@nestjs/testing';
import cookieParser from 'cookie-parser';
import { createHash, randomBytes } from 'crypto';
import type { Server } from 'http';
import request from 'supertest';
import { afterAll, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest';
vi.mock('../../src/nest/audit/audit-log.logger', () => ({
LOG_LEVEL: 'error',
logInfo: vi.fn(),
logDebug: vi.fn(),
logError: vi.fn(),
logWarn: vi.fn(),
}));
const verifier = randomBytes(32).toString('base64url');
const challenge = createHash('sha256').update(verifier).digest('hex');
const db = createSnapshotTestDb();
let orm: TestOrm;
let server: Server;
let app: Awaited<ReturnType<typeof build>>;
let userId: number;
async function build() {
const moduleRef = await Test.createTestingModule({
imports: [await TestUnitOfWorkModule.forRoot(db), await createTestMikroOrmModule(db), AuthModule, NativeAuthModule],
})
.overrideProvider(MailerService)
.useValue({ sendPasswordResetEmail: vi.fn() })
.compile();
const nest = moduleRef.createNestApplication();
nest.use(cookieParser());
nest.useGlobalFilters(new TrekExceptionFilter());
nest.useGlobalPipes(new ZodValidationPipe());
await nest.init();
return nest;
}
const handoff = (cookie: string, body: object = { challenge }) =>
request(server).post('/api/auth/native/handoff').set('Cookie', cookie).send(body);
const exchange = (body: object) => request(server).post('/api/auth/native/exchange').send(body);
beforeAll(async () => {
orm = await createTestOrm(db);
userId = (await makeUser(orm, { username: 'native-e2e', email: 'native-e2e@example.test' })).user.id;
app = await build();
server = app.getHttpServer();
});
beforeEach(async () => {
await resetRateLimits(app);
});
afterAll(async () => {
await app.close();
await orm.close();
});
describe('Native sign-in hand-off e2e', () => {
it('NATIVE-E2E-001: carries a browser session into a fresh session cookie for the app', async () => {
const minted = await handoff(sessionCookie(userId));
expect(minted.status).toBe(200);
expect(typeof minted.body.code).toBe('string');
const redeemed = await exchange({ code: minted.body.code, verifier });
expect(redeemed.status).toBe(200);
expect(redeemed.body).toEqual({ success: true });
const cookie = (redeemed.headers['set-cookie'] as unknown as string[]).find((c) => c.startsWith('trek_session='));
expect(cookie).toMatch(/HttpOnly/);
expect(cookie).toMatch(/Max-Age=\d+/);
const me = await request(server).get('/api/auth/me').set('Cookie', String(cookie).split(';')[0]);
expect(me.status).toBe(200);
expect(me.body.user.id).toBe(userId);
const logins = await findRows(orm, AuditLog, { user: userId, action: 'user.login' });
expect(logins.map((row) => JSON.parse(row.details ?? '{}'))).toContainEqual({ method: 'native_app' });
});
it('NATIVE-E2E-002: refuses to mint a code without a cookie session, even for a valid bearer token', async () => {
const res = await request(server)
.post('/api/auth/native/handoff')
.set('Authorization', `Bearer ${signSession(userId)}`)
.send({ challenge });
expect(res.status).toBe(401);
expect(res.body.code).toBe('COOKIE_AUTH_REQUIRED');
});
it('NATIVE-E2E-003: validates the challenge shape', async () => {
expect((await handoff(sessionCookie(userId), { challenge: 'not-a-hash' })).status).toBe(400);
});
it('NATIVE-E2E-004: refuses a code presented with the wrong verifier, and the code is gone after', async () => {
const { code } = (await handoff(sessionCookie(userId))).body as { code: string };
const wrong = await exchange({ code, verifier: 'x'.repeat(43) });
expect(wrong.status).toBe(400);
expect(wrong.body).toEqual({ error: 'Invalid or expired code' });
expect(wrong.headers['set-cookie']).toBeUndefined();
const retry = await exchange({ code, verifier });
expect(retry.status).toBe(400);
});
it('NATIVE-E2E-005: rate-limits the exchange per ip', async () => {
// One after another: twenty requests at once reset the ephemeral test server's connections.
await Array.from({ length: 20 }).reduce<Promise<unknown>>(
(previous, _, i) => previous.then(() => exchange({ code: `nope-${i}`, verifier })),
Promise.resolve(),
);
const blocked = await exchange({ code: 'nope', verifier });
expect(blocked.status).toBe(429);
});
it('NATIVE-E2E-006: the browser starts at a page under /api that forwards to the handoff page', async () => {
const res = await request(server).get(`/api/auth/native/start?challenge=${challenge}&start=oidc`);
expect(res.status).toBe(200);
expect(res.headers['content-type']).toMatch(/text\/html/);
expect(res.headers['cache-control']).toBe('no-store');
expect(res.text).toContain(`data-target="/native-handoff?challenge=${challenge}&amp;start=oidc"`);
expect((await request(server).get('/api/auth/native/start?challenge=nope')).status).toBe(400);
});
});
+39
View File
@@ -555,6 +555,45 @@ describe('Places e2e (real auth guard + temp SQLite)', () => {
});
});
// ── KML export (#1866): the places as pins for Google My Maps ─────────────
describe('GET export.kml (#1866)', () => {
it('serves every place with coordinates as a pin, named after the trip', async () => {
await upsertRow(orm, Trips, { id: 5, title: 'Alpine week', user: 1 });
await insertRow(orm, Places, { id: 1, trip: 5, name: 'Trailhead', lat: 47.1, lng: 11.2, address: 'Hut road 1' });
await insertRow(orm, Places, { id: 2, trip: 5, name: 'Somewhere', lat: null, lng: null });
const res = await request(server).get('/api/trips/5/places/export.kml').set('Cookie', sessionCookie(1));
expect(res.status).toBe(200);
expect(res.headers['content-type']).toContain('application/vnd.google-earth.kml+xml');
expect(res.headers['content-disposition']).toBe('attachment; filename="Alpine-week.kml"');
expect(res.text).toContain('<name>Trailhead</name>');
expect(res.text).toContain('<address>Hut road 1</address>');
expect(res.text).toContain('<coordinates>11.2,47.1</coordinates>');
expect(res.text).not.toContain('Somewhere');
});
it('404s a trip without a place to pin, and one the caller cannot reach', async () => {
await upsertRow(orm, Trips, { id: 5, title: 'Nothing here', user: 1 });
const empty = await request(server).get('/api/trips/5/places/export.kml').set('Cookie', sessionCookie(1));
expect(empty.status).toBe(404);
expect(empty.body).toEqual({ error: 'Nothing to export' });
await deleteRows(orm, Trips, { id: 5 });
const gone = await request(server).get('/api/trips/5/places/export.kml').set('Cookie', sessionCookie(1));
expect(gone.status).toBe(404);
expect(gone.body).toEqual({ error: 'Trip not found' });
expect((await request(server).get('/api/trips/5/places/export.kml')).status).toBe(401);
});
it('is a read: no place_edit permission required', async () => {
await upsertRow(orm, Trips, { id: 5, title: 'Alpine week', user: 1 });
await insertRow(orm, Places, { id: 1, trip: 5, name: 'Trailhead', lat: 47.1, lng: 11.2 });
checkPermission.mockReturnValue(false);
const res = await request(server).get('/api/trips/5/places/export.kml').set('Cookie', sessionCookie(1));
expect(res.status).toBe(200);
});
});
// The reason places keeps its inline checks on the write routes: a guard runs
// before the pipe, so guarding create would answer 404 where the suite above
// pins a 400. This is the non-regression pin for that decision.
+1 -1
View File
@@ -184,7 +184,7 @@ describe('Photos through AI Parsing e2e', () => {
expect(res.status).toBe(201);
expect(res.body.items).toHaveLength(1);
expect(res.body.files).toEqual([{ fileName: 'ticket.png', aiAvailable: true, aiUsed: true }]);
expect(res.body.files).toEqual([{ fileName: 'ticket.png', aiAvailable: true, aiUsed: true, outcome: 'ok' }]);
const image = sentUserContent().find((p: { type: string }) => p.type === 'image_url');
expect(image.image_url.url).toMatch(/^data:image\/png;base64,/);
});
+58 -1
View File
@@ -28,6 +28,7 @@ import { NotificationsService } from '../../src/nest/notifications/notifications
import { PermissionsService } from '../../src/nest/permissions/permissions.service';
import { RealtimeModule } from '../../src/nest/realtime/realtime.module';
import { ReservationsModule } from '../../src/nest/reservations/reservations.module';
import { makeReservation } from '../helpers/factories/reservations';
import {
countRows,
deleteRows,
@@ -36,7 +37,7 @@ import {
insertRow,
insertRowIgnoringConflict,
} from '../helpers/factories/rows';
import { makeTrip, makeDay } from '../helpers/factories/trips';
import { makeTrip, makeDay, readTripDays } from '../helpers/factories/trips';
import { makeUser } from '../helpers/factories/users';
import { createTestMikroOrmModule, createTestOrm, type TestOrm } from '../helpers/test-orm';
import { TestUnitOfWorkModule } from '../helpers/test-uow';
@@ -502,4 +503,60 @@ describe('Reservations + accommodations e2e (real auth guard + temp SQLite, real
expect(res.status).toBe(200);
});
});
// Adding notes to two time-only Shinkansen bookings from the browser took them
// off their days: the stored "12:00" resolved to no day, and the day_id the PUT
// left out was written as null.
describe('a partial update keeps the day it does not name', () => {
let days: number[];
let datedTripId: number;
beforeAll(async () => {
datedTripId = (await makeTrip(orm, 1, { title: 'Japan', start_date: '2026-11-10', end_date: '2026-11-12' })).id;
days = (await readTripDays(orm, datedTripId)).map((d) => d.id);
});
async function seedTrain(reservationTime: string, dayId: number | null) {
const train = await makeReservation(orm, datedTripId, {
title: 'Shinkansen',
type: 'train',
reservation_time: reservationTime,
day: dayId,
});
return train.id;
}
function put(reservationId: number, body: Record<string, unknown>) {
return request(server)
.put(`/api/trips/${datedTripId}/reservations/${reservationId}`)
.set('Cookie', sessionCookie(1))
.send(body);
}
it('200 a notes-only update leaves a time-only booking on its day', async () => {
const rid = await seedTrain('12:00', days[1]);
const res = await put(rid, { notes: 'Car 7, seats 12A-B' });
expect(res.status).toBe(200);
expect(res.body.reservation).toMatchObject({
notes: 'Car 7, seats 12A-B',
reservation_time: '12:00',
day_id: days[1],
});
expect(await findRow(orm, Reservations, { id: rid })).toMatchObject({ day_id: days[1] });
});
it('200 a dated time still moves the booking to the day it names', async () => {
const rid = await seedTrain('12:00', days[0]);
const res = await put(rid, { reservation_time: '2026-11-12T09:00' });
expect(res.status).toBe(200);
expect(await findRow(orm, Reservations, { id: rid })).toMatchObject({ day_id: days[2] });
});
it('200 an explicit day_id null still takes the booking off its day', async () => {
const rid = await seedTrain('12:00', days[1]);
const res = await put(rid, { day_id: null, notes: 'Not planned yet' });
expect(res.status).toBe(200);
expect(await findRow(orm, Reservations, { id: rid })).toMatchObject({ day_id: null });
});
});
});
+2 -1
View File
@@ -39,7 +39,8 @@ const { db } = vi.hoisted(() => {
// is_archived, reminder_days, the timestamps and added_at), so those are here too.
tmp.exec(`CREATE TABLE trips (id INTEGER PRIMARY KEY AUTOINCREMENT, user_id INTEGER NOT NULL,
title TEXT NOT NULL DEFAULT 'Trip', currency TEXT, is_archived INTEGER DEFAULT 0, reminder_days INTEGER DEFAULT 3,
created_at DATETIME DEFAULT CURRENT_TIMESTAMP, updated_at DATETIME DEFAULT CURRENT_TIMESTAMP);`);
created_at DATETIME DEFAULT CURRENT_TIMESTAMP, updated_at DATETIME DEFAULT CURRENT_TIMESTAMP,
costs_mode TEXT NOT NULL DEFAULT 'split');`);
tmp.exec(`CREATE TABLE trip_members (id INTEGER PRIMARY KEY AUTOINCREMENT, trip_id INTEGER NOT NULL,
user_id INTEGER NOT NULL, added_at DATETIME DEFAULT CURRENT_TIMESTAMP);`);
return { db: tmp };
+225
View File
@@ -0,0 +1,225 @@
/**
* Trip tags e2e for an MCP client: the four trip tag tools and the `tags` the
* place tools take, called through a real MCP session on the whole app
* (buildApp, the real registry with its scopes and error mapper, the real
* services and a migrated temp SQLite), the way an assistant tags a trip.
*/
import { buildApp } from '../../src/bootstrap';
import { createLocalMcpServer, McpRegistryService } from '../../src/nest-mcp';
import { withRequestContext } from '../../src/nest/database/request-context';
import { PermissionsService } from '../../src/nest/permissions/permissions.service';
import { makePlace, makeTag, tagPlace } from '../helpers/factories/places';
import { addTripMember, makeDay, makeTrip } from '../helpers/factories/trips';
import { makeUser } from '../helpers/factories/users';
import { MikroORM } from '@mikro-orm/core';
import { Client } from '@modelcontextprotocol/sdk/client/index';
import { InMemoryTransport } from '@modelcontextprotocol/sdk/inMemory';
import type { INestApplication } from '@nestjs/common';
import { afterAll, beforeAll, describe, expect, it, vi } from 'vitest';
let app: INestApplication;
let orm: MikroORM;
interface TagAnswer {
id: number;
name: string;
color: string;
trip_id?: number | null;
user_id?: number;
}
interface Answer {
tags?: TagAnswer[];
tag?: TagAnswer;
place?: { id: number; tags: TagAnswer[] };
success?: boolean;
}
const NO_ACCESS = 'Trip not found or access denied.';
/** The tools `userId` is offered with `scopes`, and one call of `tool`: its JSON, or the text of its error. */
async function call(userId: number, tool: string, args: Record<string, unknown>, scopes: string[] | null = null) {
const server = createLocalMcpServer('TREK trip tags e2e');
const around = (_info: unknown, run: () => unknown): unknown => withRequestContext(orm, run);
await withRequestContext(orm, () =>
app
.get(McpRegistryService)
.attach(server, { userId, scopes, isStaticToken: false }, { include: (kind) => kind === 'tool', around }),
);
const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair();
const client = new Client({ name: 'trip-tags-e2e', version: '1.0.0' });
await server.connect(serverTransport);
await client.connect(clientTransport);
try {
const offered = (await client.listTools()).tools.map((entry) => entry.name);
if (!offered.includes(tool)) return { offered, answer: null, error: null };
const result = await client.callTool({ name: tool, arguments: args });
const content = Array.isArray(result.content) ? (result.content as Array<{ text?: string }>) : [];
const text = content[0]?.text ?? '';
if (result.isError === true) return { offered, answer: null, error: text };
return { offered, answer: JSON.parse(text) as Answer, error: null };
} finally {
await client.close();
await server.close();
}
}
const names = (answer: Answer | null) => (answer?.tags ?? []).map((tag) => tag.name);
const tagIds = (answer: Answer | null) => (answer?.place?.tags ?? []).map((tag) => tag.id).sort((a, b) => a - b);
/** A trip of `owner` with `member` on it; `stranger` is on neither and has a trip of their own. */
async function scene() {
const { user: owner } = await makeUser(orm);
const { user: member } = await makeUser(orm);
const { user: stranger } = await makeUser(orm);
const trip = await makeTrip(orm, owner.id, { title: 'Lisbon' });
await addTripMember(orm, trip.id, member.id, owner.id);
const elsewhere = await makeTrip(orm, stranger.id, { title: 'Porto' });
return { owner, member, stranger, trip, elsewhere };
}
beforeAll(async () => {
app = await buildApp();
orm = app.get(MikroORM);
}, 60_000);
afterAll(async () => {
await app?.close();
});
describe('the tags of a trip over MCP', () => {
it('TRIPTAG-MCP-001: a member adds a tag every member then lists, renames and deletes', async () => {
const s = await scene();
const tripId = s.trip.id;
const created = await call(s.member.id, 'create_trip_tag', { tripId, name: ' Monument ', color: '#ff0000' });
expect(created.error).toBeNull();
expect(created.answer?.tag).toMatchObject({ name: 'Monument', color: '#ff0000', trip_id: tripId });
const tagId = created.answer?.tag?.id ?? 0;
// The same name again, in another case and by somebody else, is that tag.
const again = await call(s.owner.id, 'create_trip_tag', { tripId, name: 'MONUMENT' });
expect(again.answer?.tag).toMatchObject({ id: tagId, name: 'Monument', color: '#ff0000' });
expect(names((await call(s.owner.id, 'list_trip_tags', { tripId })).answer)).toEqual(['Monument']);
const renamed = await call(s.owner.id, 'update_trip_tag', { tripId, tagId, name: 'Landmark' });
expect(renamed.answer?.tag).toMatchObject({ id: tagId, name: 'Landmark', color: '#ff0000' });
expect(names((await call(s.member.id, 'list_trip_tags', { tripId })).answer)).toEqual(['Landmark']);
const deleted = await call(s.member.id, 'delete_trip_tag', { tripId, tagId });
expect(deleted.answer).toEqual({ success: true });
expect(names((await call(s.owner.id, 'list_trip_tags', { tripId })).answer)).toEqual([]);
});
it('TRIPTAG-MCP-002: lists the trip’s tags only, never a personal one or another trip’s', async () => {
const s = await scene();
await makeTag(orm, s.owner.id, { trip: s.trip.id, name: 'Zone' });
await makeTag(orm, s.owner.id, { name: 'personal' });
await makeTag(orm, s.stranger.id, { trip: s.elsewhere.id, name: 'Elsewhere' });
expect(names((await call(s.member.id, 'list_trip_tags', { tripId: s.trip.id })).answer)).toEqual(['Zone']);
// And the personal list keeps to itself.
expect(names((await call(s.owner.id, 'list_tags', {})).answer)).toEqual(['personal']);
});
it('TRIPTAG-MCP-003: refuses a trip the caller is not on, a tag that is not the trip’s and a taken name', async () => {
const s = await scene();
const tripId = s.trip.id;
const zone = await makeTag(orm, s.owner.id, { trip: tripId, name: 'Zone' });
const monument = await makeTag(orm, s.owner.id, { trip: tripId, name: 'Monument' });
const personal = await makeTag(orm, s.owner.id, { name: 'personal' });
expect((await call(s.stranger.id, 'list_trip_tags', { tripId })).error).toBe(NO_ACCESS);
expect((await call(s.stranger.id, 'create_trip_tag', { tripId, name: 'Mine' })).error).toBe(NO_ACCESS);
expect((await call(s.stranger.id, 'update_trip_tag', { tripId, tagId: zone.id, name: 'Mine' })).error).toBe(
NO_ACCESS,
);
expect((await call(s.stranger.id, 'delete_trip_tag', { tripId, tagId: zone.id })).error).toBe(NO_ACCESS);
expect((await call(s.owner.id, 'update_trip_tag', { tripId, tagId: personal.id, name: 'x' })).error).toBe(
'Tag not found.',
);
expect((await call(s.owner.id, 'delete_trip_tag', { tripId, tagId: personal.id })).error).toBe('Tag not found.');
expect((await call(s.owner.id, 'update_trip_tag', { tripId, tagId: monument.id, name: 'zone' })).error).toBe(
'A tag with this name already exists',
);
expect(names((await call(s.owner.id, 'list_trip_tags', { tripId })).answer)).toEqual(['Monument', 'Zone']);
});
it('TRIPTAG-MCP-004: a write needs the right to edit the trip’s places', async () => {
const s = await scene();
const check = vi.spyOn(app.get(PermissionsService), 'checkPermission').mockResolvedValue(false);
try {
const refused = await call(s.member.id, 'create_trip_tag', { tripId: s.trip.id, name: 'Zone' });
expect(refused.error).toBe('You do not have permission to perform this action on this trip.');
expect(names((await call(s.member.id, 'list_trip_tags', { tripId: s.trip.id })).answer)).toEqual([]);
} finally {
check.mockRestore();
}
});
it('TRIPTAG-MCP-005: reading takes the places read scope and writing the write scope', async () => {
const { user } = await makeUser(orm);
const offeredTo = async (scopes: string[]) => (await call(user.id, 'no_such_tool', {}, scopes)).offered;
const writes = ['create_trip_tag', 'delete_trip_tag', 'update_trip_tag'];
const writesOf = (offered: string[]) => offered.filter((tool) => writes.includes(tool)).sort();
const reader = await offeredTo(['places:read']);
expect(reader).toContain('list_trip_tags');
expect(writesOf(reader)).toEqual([]);
expect(writesOf(await offeredTo(['places:write']))).toEqual(writes);
expect(await offeredTo(['trips:read'])).not.toContain('list_trip_tags');
});
});
describe('tags on the MCP place tools', () => {
it('TRIPTAG-MCP-010: a new place takes the trip’s tags and the personal tags of people on it, nothing else', async () => {
const s = await scene();
const tripId = s.trip.id;
const monument = await makeTag(orm, s.owner.id, { trip: tripId, name: 'Monument' });
const ownPersonal = await makeTag(orm, s.member.id, { name: 'mine' });
const foreignTrip = await makeTag(orm, s.stranger.id, { trip: s.elsewhere.id, name: 'Elsewhere' });
const foreignPersonal = await makeTag(orm, s.stranger.id, { name: 'theirs' });
const created = await call(s.member.id, 'create_place', {
tripId,
name: 'Belem Tower',
tags: [monument.id, ownPersonal.id, foreignTrip.id, foreignPersonal.id],
});
expect(created.error).toBeNull();
expect(tagIds(created.answer)).toEqual([monument.id, ownPersonal.id].sort((a, b) => a - b));
});
it('TRIPTAG-MCP-011: create_and_assign_place tags the place it plans', async () => {
const s = await scene();
const day = await makeDay(orm, s.trip.id, { day_number: 1 });
const zone = await makeTag(orm, s.owner.id, { trip: s.trip.id, name: 'Zone' });
const created = await call(s.owner.id, 'create_and_assign_place', {
tripId: s.trip.id,
dayId: day.id,
name: 'Alfama',
tags: [zone.id],
});
expect(created.error).toBeNull();
expect(tagIds(created.answer)).toEqual([zone.id]);
});
it('TRIPTAG-MCP-012: an update replaces the tags it names, keeps them when it names none and clears them on []', async () => {
const s = await scene();
const tripId = s.trip.id;
const place = await makePlace(orm, tripId, { name: 'Belem Tower' });
const monument = await makeTag(orm, s.owner.id, { trip: tripId, name: 'Monument' });
const zone = await makeTag(orm, s.owner.id, { trip: tripId, name: 'Zone' });
await tagPlace(orm, place.id, [monument.id]);
const update = (args: Record<string, unknown>) =>
call(s.member.id, 'update_place', { tripId, placeId: place.id, ...args });
expect(tagIds((await update({ notes: 'By the river' })).answer)).toEqual([monument.id]);
expect(tagIds((await update({ tags: [zone.id] })).answer)).toEqual([zone.id]);
expect(tagIds((await update({ tags: [] })).answer)).toEqual([]);
expect((await update({ tags: ['zone'] })).error).toBeTruthy();
});
});
+269
View File
@@ -0,0 +1,269 @@
/**
* Trip tags e2e: the /api/trips/:tripId/tags routes through the real
* JwtAuthGuard and TripAccessGuard against a migrated temp SQLite db
* (createSnapshotTestDb()). TripTagsService and the trip access check run
* their real queries; rows are seeded and read through the factories in
* tests/helpers/factories. The permission check is a spy, so a case can take
* the `place_edit` right away, and the broadcasts go to a FakeRealtimeService.
*/
import { Tags } from '../../src/db/entities/Tags.entity';
import { TripMembers } from '../../src/db/entities/TripMembers.entity';
import { Trips } from '../../src/db/entities/Trips.entity';
import { TrekExceptionFilter } from '../../src/nest/common/trek-exception.filter';
import { ZodValidationPipe } from '../../src/nest/common/zod-validation.pipe';
import { PermissionsService } from '../../src/nest/permissions/permissions.service';
import { RealtimeModule } from '../../src/nest/realtime/realtime.module';
import { RealtimeService } from '../../src/nest/realtime/realtime.service';
import { TagsModule } from '../../src/nest/tags/tags.module';
import { createSnapshotTestDb } from '../helpers/db-mock';
import { makeTag } from '../helpers/factories/places';
import { countRows, deleteRows, findRow } from '../helpers/factories/rows';
import { addTripMember, makeTrip } from '../helpers/factories/trips';
import { makeUser } from '../helpers/factories/users';
import { FakeRealtimeService } from '../helpers/fake-realtime';
import { createTestMikroOrmModule, createTestOrm, type TestOrm } from '../helpers/test-orm';
import { TestUnitOfWorkModule } from '../helpers/test-uow';
import { sessionCookie } from './harness';
import { Test } from '@nestjs/testing';
import cookieParser from 'cookie-parser';
import type { Server } from 'http';
import request from 'supertest';
import { describe, it, expect, beforeAll, afterAll, beforeEach, vi, type MockInstance } from 'vitest';
const db = createSnapshotTestDb();
const realtime = new FakeRealtimeService();
const broadcast = realtime.broadcastMock;
// A spy on the container's PermissionsService, created in beforeAll once the app is built.
let checkPermission: MockInstance;
let orm: TestOrm;
const OWNER = 1;
const MEMBER = 2;
const STRANGER = 3;
describe('Trip tags e2e (real auth and trip guards + real SQL over temp SQLite)', () => {
let server: Server;
let app: Awaited<ReturnType<typeof build>>;
let tripId: number;
let otherTripId: number;
async function build() {
const moduleRef = await Test.createTestingModule({
imports: [await TestUnitOfWorkModule.forRoot(db), await createTestMikroOrmModule(db), RealtimeModule, TagsModule],
})
.overrideProvider(RealtimeService)
.useValue(realtime)
.compile();
const nest = moduleRef.createNestApplication();
nest.use(cookieParser());
nest.useGlobalFilters(new TrekExceptionFilter());
// Mirror the production APP_PIPE (app.module.ts): the DTO-typed bodies
// validate by metatype, exactly as they do under buildApp().
nest.useGlobalPipes(new ZodValidationPipe());
await nest.init();
return nest;
}
const tagsPath = (trip = tripId) => `/api/trips/${trip}/tags`;
beforeAll(async () => {
orm = await createTestOrm(db);
// Pinned ids: sessionCookie(n) signs for exactly these users.
await makeUser(orm, { id: OWNER, username: 'e2e-owner', email: 'owner@example.test' });
await makeUser(orm, { id: MEMBER, username: 'e2e-member', email: 'member@example.test' });
await makeUser(orm, { id: STRANGER, username: 'e2e-stranger', email: 'stranger@example.test' });
app = await build();
checkPermission = vi.spyOn(app.get(PermissionsService), 'checkPermission');
server = app.getHttpServer();
});
beforeEach(async () => {
await deleteRows(orm, Tags);
await deleteRows(orm, TripMembers);
await deleteRows(orm, Trips);
tripId = (await makeTrip(orm, OWNER, { title: 'Lisbon' })).id;
await addTripMember(orm, tripId, MEMBER, OWNER);
otherTripId = (await makeTrip(orm, STRANGER, { title: 'Porto' })).id;
checkPermission.mockResolvedValue(true);
broadcast.mockClear();
});
afterAll(async () => {
await app.close();
await orm.close();
});
it('401 without a session cookie', async () => {
const res = await request(server).get(tagsPath());
expect(res.status).toBe(401);
});
it('200 list: the same tags for every member, by name, without personal ones', async () => {
await makeTag(orm, OWNER, { trip: tripId, name: 'Zone' });
await makeTag(orm, MEMBER, { trip: tripId, name: 'Activity' });
await makeTag(orm, OWNER, { name: 'personal' });
await makeTag(orm, STRANGER, { trip: otherTripId, name: 'Elsewhere' });
const asOwner = await request(server).get(tagsPath()).set('Cookie', sessionCookie(OWNER));
const asMember = await request(server).get(tagsPath()).set('Cookie', sessionCookie(MEMBER));
expect(asOwner.status).toBe(200);
expect(asOwner.body.tags.map((tag: { name: string }) => tag.name)).toEqual(['Activity', 'Zone']);
expect(asMember.body).toEqual(asOwner.body);
});
it('404 on every route for a trip the user is not on', async () => {
const tag = await makeTag(orm, OWNER, { trip: tripId, name: 'Zone' });
const cookie = sessionCookie(STRANGER);
const list = await request(server).get(tagsPath()).set('Cookie', cookie);
const create = await request(server).post(tagsPath()).set('Cookie', cookie).send({ name: 'Mine' });
const update = await request(server).put(`${tagsPath()}/${tag.id}`).set('Cookie', cookie).send({ name: 'Mine' });
const remove = await request(server).delete(`${tagsPath()}/${tag.id}`).set('Cookie', cookie);
for (const res of [list, create, update, remove]) {
expect(res.status).toBe(404);
expect(res.body).toEqual({ error: 'Trip not found' });
}
expect(await findRow(orm, Tags, { id: tag.id })).toMatchObject({ name: 'Zone' });
});
it('201 on create by a member: the tag is the trip’s, with the default colour, and the trip is told', async () => {
const res = await request(server)
.post(tagsPath())
.set('Cookie', sessionCookie(MEMBER))
.set('X-Socket-Id', 'sock-9')
.send({ name: ' Monument ' });
expect(res.status).toBe(201);
expect(res.body.tag).toMatchObject({ name: 'Monument', color: '#10b981', trip_id: tripId, user_id: MEMBER });
expect(await findRow(orm, Tags, { id: res.body.tag.id })).toMatchObject({ name: 'Monument', trip_id: tripId });
expect(broadcast.mock.calls).toEqual([[String(tripId), 'tripTags:changed', {}, 'sock-9']]);
});
it('201 on create with a name the trip has: answers that tag and makes no second one', async () => {
const existing = await makeTag(orm, OWNER, { trip: tripId, name: 'Monument', color: '#ff0000' });
const res = await request(server)
.post(tagsPath())
.set('Cookie', sessionCookie(MEMBER))
.send({ name: 'MONUMENT', color: '#00ff00' });
expect(res.status).toBe(201);
expect(res.body.tag).toMatchObject({ id: existing.id, name: 'Monument', color: '#ff0000' });
expect(await countRows(orm, Tags, { trip: tripId })).toBe(1);
expect(broadcast).not.toHaveBeenCalled();
});
it('400 from the Zod pipe on create without a name, and with a colour that is not hex', async () => {
const cookie = sessionCookie(OWNER);
const unnamed = await request(server).post(tagsPath()).set('Cookie', cookie).send({ name: ' ' });
const coloured = await request(server).post(tagsPath()).set('Cookie', cookie).send({ name: 'Zone', color: 'red' });
expect(unnamed.status).toBe(400);
expect(unnamed.body.error).toContain('name');
expect(coloured.status).toBe(400);
expect(coloured.body.error).toContain('color');
expect(await countRows(orm, Tags, { trip: tripId })).toBe(0);
});
it('403 on every write without the right to edit the trip’s places; reading stays open', async () => {
const tag = await makeTag(orm, OWNER, { trip: tripId, name: 'Zone' });
checkPermission.mockResolvedValue(false);
const cookie = sessionCookie(MEMBER);
const create = await request(server).post(tagsPath()).set('Cookie', cookie).send({ name: 'Mine' });
const update = await request(server).put(`${tagsPath()}/${tag.id}`).set('Cookie', cookie).send({ name: 'Mine' });
const remove = await request(server).delete(`${tagsPath()}/${tag.id}`).set('Cookie', cookie);
const list = await request(server).get(tagsPath()).set('Cookie', cookie);
for (const res of [create, update, remove]) {
expect(res.status).toBe(403);
expect(res.body).toEqual({ error: 'No permission' });
}
expect(list.status).toBe(200);
expect(list.body.tags.map((row: { name: string }) => row.name)).toEqual(['Zone']);
expect(broadcast).not.toHaveBeenCalled();
});
it('200 on update: a member renames and recolours a tag the owner created', async () => {
const tag = await makeTag(orm, OWNER, { trip: tripId, name: 'Monument', color: '#ff0000' });
const res = await request(server)
.put(`${tagsPath()}/${tag.id}`)
.set('Cookie', sessionCookie(MEMBER))
.send({ name: 'Landmark', color: '#0ea5e9' });
expect(res.status).toBe(200);
expect(res.body.tag).toMatchObject({ id: tag.id, name: 'Landmark', color: '#0ea5e9', user_id: OWNER });
expect(broadcast.mock.calls).toEqual([[String(tripId), 'tripTags:changed', {}, undefined]]);
});
it('409 on update onto the name of another tag of the trip', async () => {
const tag = await makeTag(orm, OWNER, { trip: tripId, name: 'Monument' });
await makeTag(orm, OWNER, { trip: tripId, name: 'Zone' });
const res = await request(server)
.put(`${tagsPath()}/${tag.id}`)
.set('Cookie', sessionCookie(OWNER))
.send({ name: 'zone' });
expect(res.status).toBe(409);
expect(res.body).toEqual({ error: 'A tag with this name already exists' });
expect(await findRow(orm, Tags, { id: tag.id })).toMatchObject({ name: 'Monument' });
});
it('404 on update and delete of a personal tag and of another trip’s tag', async () => {
const personal = await makeTag(orm, OWNER, { name: 'personal' });
const foreign = await makeTag(orm, STRANGER, { trip: otherTripId, name: 'Elsewhere' });
const cookie = sessionCookie(OWNER);
const renamePersonal = await request(server)
.put(`${tagsPath()}/${personal.id}`)
.set('Cookie', cookie)
.send({ name: 'Mine' });
const deletePersonal = await request(server).delete(`${tagsPath()}/${personal.id}`).set('Cookie', cookie);
const renameForeign = await request(server)
.put(`${tagsPath()}/${foreign.id}`)
.set('Cookie', cookie)
.send({ name: 'Mine' });
const deleteForeign = await request(server).delete(`${tagsPath()}/${foreign.id}`).set('Cookie', cookie);
for (const res of [renamePersonal, deletePersonal, renameForeign, deleteForeign]) {
expect(res.status).toBe(404);
expect(res.body).toEqual({ error: 'Tag not found' });
}
expect(await countRows(orm, Tags, {})).toBe(2);
});
it('200 on delete: the row goes and the trip is told', async () => {
const tag = await makeTag(orm, OWNER, { trip: tripId, name: 'Monument' });
const res = await request(server)
.delete(`${tagsPath()}/${tag.id}`)
.set('Cookie', sessionCookie(MEMBER))
.set('X-Socket-Id', 'sock-9');
expect(res.status).toBe(200);
expect(res.body).toEqual({ success: true });
expect(await findRow(orm, Tags, { id: tag.id })).toBeNull();
expect(broadcast.mock.calls).toEqual([[String(tripId), 'tripTags:changed', {}, 'sock-9']]);
});
it('a tag of a trip stays off its creator’s personal /api/tags, which cannot change it either', async () => {
const tag = await makeTag(orm, OWNER, { trip: tripId, name: 'Monument' });
const cookie = sessionCookie(OWNER);
const list = await request(server).get('/api/tags').set('Cookie', cookie);
const update = await request(server).put(`/api/tags/${tag.id}`).set('Cookie', cookie).send({ name: 'Mine' });
const remove = await request(server).delete(`/api/tags/${tag.id}`).set('Cookie', cookie);
expect(list.body).toEqual({ tags: [] });
expect(update.status).toBe(404);
expect(remove.status).toBe(404);
expect(await findRow(orm, Tags, { id: tag.id })).toMatchObject({ name: 'Monument' });
});
});
+23
View File
@@ -43,6 +43,7 @@ import { VacayPlans } from '../../src/db/entities/VacayPlans.entity';
import { GUEST_HAS_PAYMENTS } from '../../src/nest/budget/budget-departure.helpers';
import { BudgetService } from '../../src/nest/budget/budget.service';
import { TrekExceptionFilter } from '../../src/nest/common/trek-exception.filter';
import { ZodValidationPipe } from '../../src/nest/common/zod-validation.pipe';
import { withRequestContext } from '../../src/nest/database/request-context';
import { PermissionsService } from '../../src/nest/permissions/permissions.service';
import { RealtimeModule } from '../../src/nest/realtime/realtime.module';
@@ -108,6 +109,8 @@ describe('Trips e2e (real auth guard + temp SQLite)', () => {
const nest = moduleRef.createNestApplication();
nest.use(cookieParser());
nest.useGlobalFilters(new TrekExceptionFilter());
// The contracts are checked at the pipe, as in the app (APP_PIPE).
nest.useGlobalPipes(new ZodValidationPipe());
await nest.init();
return nest;
}
@@ -243,6 +246,26 @@ describe('Trips e2e (real auth guard + temp SQLite)', () => {
expect(await dayIds(week.body.trip.id)).toEqual(kept);
});
it('200 update keeps the costs as totals only, the trip as it was otherwise; 400 on another mode (#1714)', async () => {
const trip = await request(server).post('/api/trips').set('Cookie', sessionCookie(1)).send({ title: 'Lisbon' });
expect(trip.body.trip.costs_mode).toBe('split');
const res = await request(server)
.put(`/api/trips/${trip.body.trip.id}`)
.set('Cookie', sessionCookie(1))
.send({ costs_mode: 'totals' });
expect(res.status).toBe(200);
expect(res.body.trip).toMatchObject({ title: 'Lisbon', costs_mode: 'totals' });
const audit = await findRow(orm, AuditLog, { action: 'trip.update' });
expect(JSON.parse(audit?.details ?? '{}')).toMatchObject({ costs_mode: 'totals' });
const bogus = await request(server)
.put(`/api/trips/${trip.body.trip.id}`)
.set('Cookie', sessionCookie(1))
.send({ costs_mode: 'shares' });
expect(bogus.status).toBe(400);
expect((await findRow(orm, Trips, { id: trip.body.trip.id }))?.costs_mode).toBe('totals');
});
it('200 update with a later start moves the leave days of the owner along, off the blocked weekend, and tells the plan (#2604)', async () => {
// 2030-11-25 is a Monday; the plan blocks Saturday and Sunday by default.
const trip = await request(server)
+214
View File
@@ -0,0 +1,214 @@
/**
* GET /api/trips/:tripId/reservations/:id/wallet-pass end to end: the session,
* the trip guard, the booking read through the reservations module and the
* request the TREK services' pass signer receives. The signer itself is
* stubbed at the fetch seam.
*/
import { servicesConfig } from '../../src/nest/app-config/tokens';
import { TrekExceptionFilter } from '../../src/nest/common/trek-exception.filter';
import { ZodValidationPipe } from '../../src/nest/common/zod-validation.pipe';
import { WalletPassModule } from '../../src/nest/wallet-pass/wallet-pass.module';
import { createSnapshotTestDb } from '../helpers/db-mock';
import { makeReservation, makeReservationEndpoint } from '../helpers/factories/reservations';
import { makeTrip } from '../helpers/factories/trips';
import { makeUser } from '../helpers/factories/users';
import { createTestMikroOrmModule, createTestOrm, type TestOrm } from '../helpers/test-orm';
import { TestUnitOfWorkModule } from '../helpers/test-uow';
import { sessionCookie } from './harness';
import { Test } from '@nestjs/testing';
import cookieParser from 'cookie-parser';
import request from 'supertest';
import { afterAll, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest';
const { safeFetchAdminConfigured } = vi.hoisted(() => ({ safeFetchAdminConfigured: vi.fn() }));
vi.mock('../../src/utils/ssrfGuard', async (importOriginal) => ({
...(await importOriginal<typeof import('../../src/utils/ssrfGuard')>()),
safeFetchAdminConfigured,
}));
const db = createSnapshotTestDb();
const OWNER = 1;
const STRANGER = 2;
const PASS = Buffer.concat([Buffer.from([0x50, 0x4b, 0x03, 0x04]), Buffer.from('signed pass')]);
let orm: TestOrm;
let app: Awaited<ReturnType<typeof build>>;
let tripId: number;
let flightId: number;
async function build() {
const moduleRef = await Test.createTestingModule({
imports: [await TestUnitOfWorkModule.forRoot(db), await createTestMikroOrmModule(db), WalletPassModule],
})
.overrideProvider(servicesConfig.KEY)
.useValue({ mode: 'auto', key: null, hosts: [], walletPassUrl: 'https://push.liketrek.com/v1/wallet/pass' })
.compile();
const nest = moduleRef.createNestApplication();
nest.use(cookieParser());
nest.useGlobalFilters(new TrekExceptionFilter());
nest.useGlobalPipes(new ZodValidationPipe());
await nest.init();
return nest;
}
const as = (userId: number) => ({ Cookie: sessionCookie(userId) });
const path = (trip: number, id: number, lang = 'de') =>
`/api/trips/${trip}/reservations/${id}/wallet-pass?lang=${lang}`;
beforeAll(async () => {
orm = await createTestOrm(db);
await makeUser(orm, { id: OWNER, username: 'owner', email: 'owner@example.test' });
await makeUser(orm, { id: STRANGER, username: 'stranger', email: 'stranger@example.test' });
const trip = await makeTrip(orm, OWNER, { title: 'Japan 2027' });
tripId = trip.id;
const flight = await makeReservation(orm, tripId, {
title: 'LH 716',
type: 'flight',
reservation_time: '2027-04-01T13:25',
confirmation_number: 'X7K2QP',
metadata: JSON.stringify({ airline: 'Lufthansa', flight_number: 'LH716', seat: '34K' }),
});
flightId = flight.id;
await makeReservationEndpoint(orm, flightId, {
role: 'from',
name: 'Frankfurt',
code: 'FRA',
lat: 50.03,
lng: 8.57,
timezone: 'Europe/Berlin',
local_date: '2027-04-01',
local_time: '13:25',
});
await makeReservationEndpoint(orm, flightId, {
role: 'to',
sequence: 1,
name: 'Tokyo Haneda',
code: 'HND',
lat: 35.55,
lng: 139.78,
timezone: 'Asia/Tokyo',
local_date: '2027-04-02',
local_time: '08:50',
});
app = await build();
});
beforeEach(() => {
safeFetchAdminConfigured.mockReset();
safeFetchAdminConfigured.mockResolvedValue(
new Response(PASS, { status: 200, headers: { 'content-type': 'application/vnd.apple.pkpass' } }),
);
});
afterAll(async () => {
await app.close();
await orm.close();
});
describe('GET /api/trips/:tripId/reservations/:id/wallet-pass', () => {
it('WALLET-E2E-001: answers 401 without a session and asks nobody', async () => {
const res = await request(app.getHttpServer()).get(path(tripId, flightId));
expect(res.status).toBe(401);
expect(safeFetchAdminConfigured).not.toHaveBeenCalled();
});
it('WALLET-E2E-002: someone outside the trip gets a 404, not a pass', async () => {
const res = await request(app.getHttpServer()).get(path(tripId, flightId)).set(as(STRANGER));
expect(res.status).toBe(404);
expect(safeFetchAdminConfigured).not.toHaveBeenCalled();
});
it('WALLET-E2E-003: the owner gets the signed pass, built from the booking in their language', async () => {
const res = await request(app.getHttpServer())
.get(path(tripId, flightId))
.set(as(OWNER))
.buffer(true)
.parse((r, done) => {
const chunks: Buffer[] = [];
r.on('data', (c: Buffer) => chunks.push(c));
r.on('end', () => done(null, Buffer.concat(chunks)));
});
expect(res.status).toBe(200);
expect(res.headers['content-type']).toContain('application/vnd.apple.pkpass');
expect(res.headers['content-disposition']).toBe('attachment; filename="LH-716.pkpass"');
expect(Buffer.compare(res.body as Buffer, PASS)).toBe(0);
const [url, init] = safeFetchAdminConfigured.mock.calls[0] as [string, RequestInit];
expect(url).toBe('https://push.liketrek.com/v1/wallet/pass');
const body = JSON.parse(String(init.body));
expect(body).toMatchObject({
kind: 'flight',
title: 'LH 716',
trip: 'Japan 2027',
start: '2027-04-01T13:25:00+02:00',
end: '2027-04-02T08:50:00+09:00',
from: { code: 'FRA', name: 'Frankfurt' },
to: { code: 'HND', name: 'Tokyo Haneda' },
confirmation: { value: 'X7K2QP' },
locale: 'de-DE',
});
expect(body.details.map((d: { label: string }) => d.label)).toContain('Sitzplatz');
});
it('WALLET-E2E-004: a booking of another trip, or none, is a 404', async () => {
const other = await makeTrip(orm, OWNER, { title: 'Elsewhere' });
expect((await request(app.getHttpServer()).get(path(other.id, flightId)).set(as(OWNER))).status).toBe(404);
expect((await request(app.getHttpServer()).get(path(tripId, 999_999)).set(as(OWNER))).status).toBe(404);
expect(safeFetchAdminConfigured).not.toHaveBeenCalled();
});
it('WALLET-E2E-005: a booking without a date gets a 422, and the signer failing a 502', async () => {
const undated = await makeReservation(orm, tripId, { title: 'Someday', type: 'event', reservation_time: null });
expect((await request(app.getHttpServer()).get(path(tripId, undated.id)).set(as(OWNER))).status).toBe(422);
safeFetchAdminConfigured.mockRejectedValueOnce(new Error('ECONNREFUSED'));
expect((await request(app.getHttpServer()).get(path(tripId, flightId)).set(as(OWNER))).status).toBe(502);
});
});
describe('Google Wallet', () => {
const google = (trip: number, id: number) => `/api/trips/${trip}/reservations/${id}/wallet-pass/google?lang=de`;
const SAVE_URL = 'https://pay.google.com/gp/v/save/eyJhbGciOiJSUzI1NiJ9.payload.signature';
const answer = (status: number, body: string, type = 'application/json') =>
safeFetchAdminConfigured.mockResolvedValueOnce(new Response(body, { status, headers: { 'content-type': type } }));
it('WALLET-E2E-006: the owner gets the save link, signed at the Google route beside the Apple one', async () => {
answer(200, JSON.stringify({ saveUrl: SAVE_URL }));
const res = await request(app.getHttpServer()).get(google(tripId, flightId)).set(as(OWNER));
expect(res.status).toBe(200);
expect(res.body).toEqual({ saveUrl: SAVE_URL });
const [url, init] = safeFetchAdminConfigured.mock.calls[0] as [string, RequestInit];
expect(url).toBe('https://push.liketrek.com/v1/wallet/google');
expect(JSON.parse(String(init.body))).toMatchObject({ kind: 'flight', title: 'LH 716', locale: 'de-DE' });
});
it('WALLET-E2E-007: a stranger, another trip and a missing booking get a 404 and ask nobody', async () => {
expect((await request(app.getHttpServer()).get(google(tripId, flightId))).status).toBe(401);
expect((await request(app.getHttpServer()).get(google(tripId, flightId)).set(as(STRANGER))).status).toBe(404);
const other = await makeTrip(orm, OWNER, { title: 'Elsewhere too' });
expect((await request(app.getHttpServer()).get(google(other.id, flightId)).set(as(OWNER))).status).toBe(404);
expect((await request(app.getHttpServer()).get(google(tripId, 999_999)).set(as(OWNER))).status).toBe(404);
expect(safeFetchAdminConfigured).not.toHaveBeenCalled();
});
it('WALLET-E2E-008: no issuer yet is a 404, a link that is not Google Wallet a 502', async () => {
answer(404, 'not found', 'text/plain');
expect((await request(app.getHttpServer()).get(google(tripId, flightId)).set(as(OWNER))).status).toBe(404);
answer(200, JSON.stringify({ saveUrl: 'https://evil.example/save' }));
expect((await request(app.getHttpServer()).get(google(tripId, flightId)).set(as(OWNER))).status).toBe(502);
});
it('WALLET-E2E-009: the trip members can ask whether Google Wallet works here', async () => {
safeFetchAdminConfigured.mockResolvedValueOnce(new Response('', { status: 405 }));
const res = await request(app.getHttpServer())
.get(`/api/trips/${tripId}/reservations/google-wallet`)
.set(as(OWNER));
expect(res.status).toBe(200);
expect(res.body).toEqual({ available: true });
expect(
(await request(app.getHttpServer()).get(`/api/trips/${tripId}/reservations/google-wallet`).set(as(STRANGER)))
.status,
).toBe(404);
});
});