test(server): seed the e2e specs through the repositories

The e2e suites for assignments, places, bookings, trips, the public API,
doc sync, addons, transit, to-dos, admin, invite links, school holidays,
categories, feeds and plugin search seeded and inspected their database
with raw better-sqlite3 statements. They now go through the ORM
factories and readers, the way the repositories write and read.

Six of them (public API, transit, to-dos, admin, invite links,
categories) still built a handful of hand-rolled tables. They move to
the migrated snapshot, since an entity reads and writes every mapped
column; where the real schema keeps usernames unique, the seeded users
get distinct names and keep the ones the assertions read back. The dead
canAccessTrip stubs left in two database mocks are dropped: nothing in
src imports it from db/database any more.
This commit is contained in:
Maurice
2026-10-08 15:48:10 +02:00
parent ddf97c5a21
commit 583ba17606
15 changed files with 702 additions and 735 deletions
+24 -14
View File
@@ -40,7 +40,15 @@ vi.mock('../../src/nest/memories/memories.helpers', () => ({ getPhotoProviderCon
import { AddonsModule } from '../../src/nest/addons/addons.module';
import { TrekExceptionFilter } from '../../src/nest/common/trek-exception.filter';
import { TestUnitOfWorkModule } from '../helpers/test-uow';
import { createTestMikroOrmModule } from '../helpers/test-orm';
import { createTestMikroOrmModule, createTestOrm, type TestOrm } from '../helpers/test-orm';
import { makeUser } from '../helpers/factories/users';
import { setAddonEnabled, setAppSetting } from '../helpers/factories/settings';
import { findRow, insertRow } from '../helpers/factories/rows';
import { Addons } from '../../src/db/entities/Addons.entity';
import { PhotoProviderFields } from '../../src/db/entities/PhotoProviderFields.entity';
import { PhotoProviders } from '../../src/db/entities/PhotoProviders.entity';
let orm: TestOrm;
describe('GET /api/addons e2e (real auth guard + temp SQLite)', () => {
let server: Server;
@@ -60,24 +68,26 @@ describe('GET /api/addons e2e (real auth guard + temp SQLite)', () => {
// schema requires NOT NULL (share.e2e.test.ts hit the same thing) — a
// raw insert here instead, matching the SeededUser shape id/role/
// password_version=0 that sessionCookie(1) needs.
db.prepare(
"INSERT INTO users (id, username, email, password_hash, role, password_version) VALUES (1, 'e2e-user', 'e2e@example.test', 'x', 'user', 0)",
).run();
orm = await createTestOrm(db);
await makeUser(orm, { id: 1, username: 'e2e-user', email: 'e2e@example.test' });
// bag tracking is opt-in (=== 'true'); collab flags default ON with no rows
db.prepare("INSERT INTO app_settings (key, value) VALUES ('bag_tracking_enabled', 'true')").run();
db.prepare("INSERT INTO addons (id, name, type, icon, enabled, sort_order) VALUES ('packing','Packing','trip','Backpack',1,1)").run();
db.prepare("INSERT INTO addons (id, name, type, icon, enabled, sort_order) VALUES ('disabled','Disabled','trip','X',0,2)").run();
await setAppSetting(orm, 'bag_tracking_enabled', 'true');
await insertRow(orm, Addons, { id: 'packing', name: 'Packing', type: 'trip', icon: 'Backpack', enabled: true, sort_order: 1 });
await insertRow(orm, Addons, { id: 'disabled', name: 'Disabled', type: 'trip', icon: 'X', enabled: false, sort_order: 2 });
// The providers ride the journey addon — without this row they are dropped from the listing.
db.prepare("INSERT INTO addons (id, name, type, icon, enabled, sort_order) VALUES ('journey','Journey','global','Compass',1,3)").run();
db.prepare("INSERT INTO photo_providers (id, name, icon, enabled, sort_order) VALUES ('immich','Immich','Image',1,1)").run();
db.prepare(`INSERT INTO photo_provider_fields (provider_id, field_key, label, input_type, placeholder, hint, required, secret, settings_key, payload_key, sort_order)
VALUES ('immich','base_url','Base URL','text','https://...',NULL,1,0,'immich_url',NULL,1)`).run();
await insertRow(orm, Addons, { id: 'journey', name: 'Journey', type: 'global', icon: 'Compass', enabled: true, sort_order: 3 });
await insertRow(orm, PhotoProviders, { id: 'immich', name: 'Immich', icon: 'Image', enabled: 1, sort_order: 1 });
await insertRow(orm, PhotoProviderFields, {
provider: 'immich', field_key: 'base_url', label: 'Base URL', input_type: 'text', placeholder: 'https://...', hint: null,
required: 1, secret: 0, settings_key: 'immich_url', payload_key: null, sort_order: 1,
});
app = await build();
server = app.getHttpServer();
});
afterAll(async () => {
await app.close();
await orm.close();
});
it('401 without a cookie', async () => {
@@ -123,7 +133,7 @@ describe('GET /api/addons e2e (real auth guard + temp SQLite)', () => {
});
it('200 drops the photo providers while the journey addon is off', async () => {
db.prepare("UPDATE addons SET enabled = 0 WHERE id = 'journey'").run();
await setAddonEnabled(orm, 'journey', false);
try {
const res = await request(server).get('/api/addons').set('Cookie', sessionCookie(1));
expect(res.status).toBe(200);
@@ -131,9 +141,9 @@ describe('GET /api/addons e2e (real auth guard + temp SQLite)', () => {
expect(res.body.addons).toEqual([
{ id: 'packing', name: 'Packing', type: 'trip', icon: 'Backpack', enabled: true },
]);
expect(db.prepare("SELECT enabled FROM photo_providers WHERE id = 'immich'").get()).toEqual({ enabled: 1 });
expect((await findRow(orm, PhotoProviders, { id: 'immich' }))!.enabled).toBe(1);
} finally {
db.prepare("UPDATE addons SET enabled = 1 WHERE id = 'journey'").run();
await setAddonEnabled(orm, 'journey', true);
}
});
});
+35 -92
View File
@@ -1,10 +1,10 @@
/**
* Admin e2e — exercises the migrated /api/admin endpoints through the real
* JwtAuthGuard + AdminGuard against a temp SQLite db, DI-native: no
* services/adminService path mock, so every route below runs its real SQL
* (trips.e2e.test.ts pattern). Only the shared db module is mocked — the auth
* guard reads users through the singleton and DatabaseModule's factory picks up
* the same mocked db. Covers auth (401), the admin gate (403), create-201,
* JwtAuthGuard + AdminGuard against a migrated temp SQLite db
* (createSnapshotTestDb()), DI-native: no services/adminService path mock, so
* every route below runs its real SQL (trips.e2e.test.ts pattern). Only the
* shared db module is mocked; rows are seeded and read through the factories
* in tests/helpers/factories. Covers auth (401), the admin gate (403), create-201,
* validation 400, the dev-only 404, and real read/write round trips.
*/
import { describe, it, expect, beforeAll, afterAll, beforeEach, vi } from 'vitest';
@@ -13,83 +13,12 @@ import cookieParser from 'cookie-parser';
import type { Server } from 'http';
import { RealtimeModule } from '../../src/nest/realtime/realtime.module';
import { Test } from '@nestjs/testing';
import { seedUser, sessionCookie } from './harness';
import { sessionCookie } from './harness';
const { db } = vi.hoisted(() => {
// eslint-disable-next-line @typescript-eslint/no-require-imports
const Database = require('better-sqlite3');
const tmp = new Database(':memory:');
tmp.exec('PRAGMA journal_mode = WAL');
// `users` carries the columns listUsers/createUser/updateUser select, plus the
// is_guest flag the #1362 COALESCE guards read. Plan 3i Task 1 (admin's
// repository conversion) surfaced the SAME class of drift the
// `invite_tokens`/`used_count` comment below already documents: `UsersRepository
// .insertAdminCreatedUser` writes through entity metadata (MikroORM's native
// insert), which — unlike the legacy raw `INSERT INTO users (username, email,
// password_hash, role) VALUES (...)` — also applies every OTHER column's
// class-level JS default (`mfa_enabled = 0`, `first_seen_version = '0.0.0'`, …),
// even though this repository's own method never names them. Fixed at the
// source (the fixture, adding the columns the real migrated schema has), not
// worked around in the repository. `immich_allow_insecure_tls` (#2475,
// Migration20200101040400) is the same drift again: a defaulted column the
// entity now carries, so the native insert names it.
tmp.exec(`CREATE TABLE users (id INTEGER PRIMARY KEY AUTOINCREMENT, username TEXT NOT NULL,
email TEXT NOT NULL UNIQUE, role TEXT NOT NULL DEFAULT 'user', password_version INTEGER NOT NULL DEFAULT 0,
password_hash TEXT, avatar TEXT, is_guest INTEGER DEFAULT 0,
created_at DATETIME DEFAULT CURRENT_TIMESTAMP, updated_at DATETIME DEFAULT CURRENT_TIMESTAMP,
last_login DATETIME, mfa_enabled INTEGER DEFAULT 0, mfa_secret TEXT, mfa_backup_codes TEXT,
must_change_password INTEGER DEFAULT 0, synology_skip_ssl INTEGER DEFAULT 0,
first_seen_version TEXT DEFAULT '0.0.0', login_count INTEGER DEFAULT 0,
immich_auto_upload INTEGER DEFAULT 0, airtrail_allow_insecure_tls INTEGER DEFAULT 0,
airtrail_write_enabled INTEGER DEFAULT 0, immich_allow_insecure_tls INTEGER NOT NULL DEFAULT 0);`);
tmp.exec(`CREATE TABLE settings (id INTEGER PRIMARY KEY AUTOINCREMENT, user_id INTEGER NOT NULL,
key TEXT NOT NULL, value TEXT, UNIQUE(user_id, key));`);
tmp.exec('CREATE TABLE app_settings (key TEXT PRIMARY KEY, value TEXT);');
// Slim audit_log mirror (no FKs), same shape as plugin-runtime.test.ts.
tmp.exec(`CREATE TABLE audit_log (
id INTEGER PRIMARY KEY AUTOINCREMENT, created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
user_id INTEGER, action TEXT NOT NULL, resource TEXT, details TEXT, ip TEXT);`);
// getStats counts these three alongside users.
tmp.exec('CREATE TABLE trips (id INTEGER PRIMARY KEY AUTOINCREMENT, title TEXT, user_id INTEGER);');
tmp.exec('CREATE TABLE places (id INTEGER PRIMARY KEY AUTOINCREMENT, trip_id INTEGER);');
tmp.exec('CREATE TABLE trip_files (id INTEGER PRIMARY KEY AUTOINCREMENT, trip_id INTEGER, message_id INTEGER);');
// `used_count`, not `uses`: this hand-rolled fixture had drifted from the
// real migrated `invite_tokens` schema (`Migration20200101003500_create_invite_tokens`)
// — the legacy raw-SQL `RegistrationInvitesService` never named the column
// explicitly (its INSERT relied on the table's own DEFAULT, its re-select
// used `i.*`), so the drift stayed invisible. `InviteTokensRepository
// .insertInvite` (Plan 3b) writes through entity metadata, which does
// name every column explicitly — surfacing the drift as `no such column:
// used_count`. Fixed at the source (the fixture), not worked around.
tmp.exec(`CREATE TABLE invite_tokens (id INTEGER PRIMARY KEY AUTOINCREMENT, token TEXT NOT NULL,
max_uses INTEGER, used_count INTEGER DEFAULT 0, expires_at TEXT, created_by INTEGER NOT NULL,
trip_id INTEGER, created_at DATETIME DEFAULT CURRENT_TIMESTAMP);`);
tmp.exec(`CREATE TABLE packing_templates (id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT NOT NULL,
created_by INTEGER NOT NULL, created_at DATETIME DEFAULT CURRENT_TIMESTAMP);`);
tmp.exec(`CREATE TABLE packing_template_categories (id INTEGER PRIMARY KEY AUTOINCREMENT,
template_id INTEGER NOT NULL, name TEXT NOT NULL, sort_order INTEGER DEFAULT 0);`);
tmp.exec(`CREATE TABLE packing_template_items (id INTEGER PRIMARY KEY AUTOINCREMENT,
category_id INTEGER NOT NULL, name TEXT NOT NULL, sort_order INTEGER DEFAULT 0);`);
tmp.exec(`CREATE TABLE addons (id TEXT PRIMARY KEY, name TEXT, description TEXT, icon TEXT,
enabled INTEGER DEFAULT 0, config TEXT, sort_order INTEGER DEFAULT 0);`);
tmp.exec(`CREATE TABLE photo_providers (id TEXT PRIMARY KEY, name TEXT, description TEXT,
icon TEXT, enabled INTEGER DEFAULT 0, sort_order INTEGER DEFAULT 0);`);
tmp.exec(`CREATE TABLE photo_provider_fields (id INTEGER PRIMARY KEY AUTOINCREMENT,
provider_id TEXT NOT NULL, field_key TEXT, label TEXT, input_type TEXT, placeholder TEXT,
required INTEGER DEFAULT 0, secret INTEGER DEFAULT 0, settings_key TEXT, payload_key TEXT,
sort_order INTEGER DEFAULT 0);`);
tmp.exec(`CREATE TABLE mcp_tokens (id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT,
token_prefix TEXT, user_id INTEGER NOT NULL, created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
last_used_at DATETIME);`);
tmp.exec('CREATE TABLE oauth_clients (client_id TEXT PRIMARY KEY, name TEXT);');
tmp.exec(`CREATE TABLE oauth_tokens (id INTEGER PRIMARY KEY AUTOINCREMENT, client_id TEXT NOT NULL,
user_id INTEGER NOT NULL, scopes TEXT, access_token_expires_at DATETIME,
refresh_token_expires_at DATETIME, revoked_at DATETIME,
created_at DATETIME DEFAULT CURRENT_TIMESTAMP);`);
return { db: tmp };
vi.mock('../../src/db/database', async () => {
const { createSnapshotTestDb, buildDbMock } = await import('../helpers/db-mock');
return buildDbMock(createSnapshotTestDb());
});
vi.mock('../../src/db/database', () => ({ db, closeDb: () => {}, reinitialize: () => {} }));
// The audit domain is DI-native: writeAudit runs for real against the temp db's
// audit_log table; only the file logger is silenced.
vi.mock('../../src/nest/audit/audit-log.logger', () => ({ LOG_LEVEL: 'error', logInfo: vi.fn(), logDebug: vi.fn(), logError: vi.fn(), logWarn: vi.fn() }));
@@ -105,6 +34,7 @@ vi.mock('../../src/nest/notifications/notification-preferences.service', async (
return actual;
});
import { db } from '../../src/db/database';
import { AdminModule } from '../../src/nest/admin/admin.module';
import { DatabaseBackupModule } from '../../src/nest/backup/database-backup.module';
// The admin surface is no longer one module: oidc, the account defaults and the admin
@@ -116,7 +46,18 @@ import { NotificationsModule } from '../../src/nest/notifications/notifications.
import { TrekExceptionFilter } from '../../src/nest/common/trek-exception.filter';
import { ZodValidationPipe } from '../../src/nest/common/zod-validation.pipe';
import { TestUnitOfWorkModule } from '../helpers/test-uow';
import { createTestMikroOrmModule } from '../helpers/test-orm';
import { createTestMikroOrmModule, createTestOrm, type TestOrm } from '../helpers/test-orm';
import { makeAdmin, makeUser } from '../helpers/factories/users';
import { makeTrip } from '../helpers/factories/trips';
import { readAppSetting } from '../helpers/factories/settings';
import { countRows, findRow, insertRow } from '../helpers/factories/rows';
import { AuditLog } from '../../src/db/entities/AuditLog.entity';
import { InviteTokens } from '../../src/db/entities/InviteTokens.entity';
import { PackingTemplates } from '../../src/db/entities/PackingTemplates.entity';
import { Places } from '../../src/db/entities/Places.entity';
import { Users } from '../../src/db/entities/Users.entity';
let orm: TestOrm;
describe('Admin e2e (real auth + admin guard + temp SQLite)', () => {
let server: Server;
@@ -138,8 +79,9 @@ describe('Admin e2e (real auth + admin guard + temp SQLite)', () => {
}
beforeAll(async () => {
seedUser(db as never, { id: 1, role: 'admin', email: 'admin@example.test', username: 'admin' });
seedUser(db as never, { id: 2, role: 'user', email: 'member@example.test', username: 'member' });
orm = await createTestOrm(db);
await makeAdmin(orm, { id: 1, email: 'admin@example.test', username: 'admin' });
await makeUser(orm, { id: 2, email: 'member@example.test', username: 'member' });
app = await build();
server = app.getHttpServer();
});
@@ -148,6 +90,7 @@ describe('Admin e2e (real auth + admin guard + temp SQLite)', () => {
afterAll(async () => {
await app.close();
await orm.close();
});
it('401 without a session', async () => {
@@ -174,10 +117,10 @@ describe('Admin e2e (real auth + admin guard + temp SQLite)', () => {
expect(res.status).toBe(201);
expect(res.body.user).toMatchObject({ username: 'created', email: 'new@x.y', role: 'user' });
const row = db.prepare('SELECT username, role FROM users WHERE email = ?').get('new@x.y');
expect(row).toEqual({ username: 'created', role: 'user' });
const audit = db.prepare("SELECT action FROM audit_log WHERE action = 'admin.user_create'").get();
expect(audit).toBeDefined();
const created = await findRow(orm, Users, { email: 'new@x.y' });
expect(created && { username: created.username, role: created.role }).toEqual({ username: 'created', role: 'user' });
const audit = await findRow(orm, AuditLog, { action: 'admin.user_create' });
expect(audit).not.toBeNull();
});
it('400 on user create with a weak password', async () => {
@@ -205,7 +148,7 @@ describe('Admin e2e (real auth + admin guard + temp SQLite)', () => {
it('places-photos toggle round-trips through app_settings', async () => {
const off = await request(server).put('/api/admin/places-photos').set('Cookie', sessionCookie(1)).send({ enabled: false });
expect(off.status).toBe(200);
expect(db.prepare("SELECT value FROM app_settings WHERE key = 'places_photos_enabled'").get()).toEqual({ value: 'false' });
expect(await readAppSetting(orm, 'places_photos_enabled')).toBe('false');
expect((await request(server).get('/api/admin/places-photos').set('Cookie', sessionCookie(1))).body).toEqual({ enabled: false });
await request(server).put('/api/admin/places-photos').set('Cookie', sessionCookie(1)).send({ enabled: true });
@@ -213,8 +156,8 @@ describe('Admin e2e (real auth + admin guard + temp SQLite)', () => {
});
it('GET /stats counts real rows', async () => {
db.prepare("INSERT INTO trips (title, user_id) VALUES ('T', 1)").run();
db.prepare('INSERT INTO places (trip_id) VALUES (1)').run();
const trip = await makeTrip(orm, 1, { title: 'T' });
await insertRow(orm, Places, { trip: trip.id, name: 'P' });
const res = await request(server).get('/api/admin/stats').set('Cookie', sessionCookie(1));
expect(res.status).toBe(200);
expect(res.body).toMatchObject({ totalTrips: 1, totalPlaces: 1, totalFiles: 0 });
@@ -232,7 +175,7 @@ describe('Admin e2e (real auth + admin guard + temp SQLite)', () => {
const del = await request(server).delete(`/api/admin/invites/${created.body.invite.id}`).set('Cookie', sessionCookie(1));
expect(del.status).toBe(200);
expect(db.prepare('SELECT COUNT(*) as c FROM invite_tokens').get()).toEqual({ c: 0 });
expect(await countRows(orm, InviteTokens)).toBe(0);
});
it('404 deleting an unknown invite', async () => {
@@ -251,7 +194,7 @@ describe('Admin e2e (real auth + admin guard + temp SQLite)', () => {
expect(fetched.body.categories).toEqual([]);
expect((await request(server).delete(`/api/admin/packing-templates/${id}`).set('Cookie', sessionCookie(1))).status).toBe(200);
expect(db.prepare('SELECT COUNT(*) as c FROM packing_templates').get()).toEqual({ c: 0 });
expect(await countRows(orm, PackingTemplates)).toBe(0);
});
it('GET /oidc reads app_settings defaults', async () => {
+131 -101
View File
@@ -44,7 +44,33 @@ import { AssignmentsModule } from '../../src/nest/assignments/assignments.module
import { TrekExceptionFilter } from '../../src/nest/common/trek-exception.filter';
import { ZodValidationPipe } from '../../src/nest/common/zod-validation.pipe';
import { TestUnitOfWorkModule } from '../helpers/test-uow';
import { createTestMikroOrmModule } from '../helpers/test-orm';
import { createTestMikroOrmModule, createTestOrm, type TestOrm } from '../helpers/test-orm';
import { makeUser } from '../helpers/factories/users';
import { makeTour } from '../helpers/factories/tours';
import type { DayAssignmentRow } from '../helpers/factories/itinerary';
import { countRows, deleteRows, findRow, findRows, insertRow, insertRowIgnoringConflict, insertRows, updateRows } from '../helpers/factories/rows';
import { AssignmentParticipants } from '../../src/db/entities/AssignmentParticipants.entity';
import { DayAssignments } from '../../src/db/entities/DayAssignments.entity';
import { Days } from '../../src/db/entities/Days.entity';
import { Places } from '../../src/db/entities/Places.entity';
import { Tours } from '../../src/db/entities/Tours.entity';
import { Trips } from '../../src/db/entities/Trips.entity';
let orm: TestOrm;
/** The named columns of the assignment, or undefined once it is gone: what a `SELECT <cols> FROM day_assignments` read back. */
async function assignmentCols<K extends keyof DayAssignmentRow>(id: number, ...cols: K[]): Promise<Pick<DayAssignmentRow, K> | undefined> {
const row = await findRow(orm, DayAssignments, { id });
if (!row) return undefined;
return Object.fromEntries(cols.map(c => [c, row[c]])) as Pick<DayAssignmentRow, K>;
}
/** Drops a place seeded for one test, with its tour and any assignment of it. */
async function dropTourPlace(placeId: number): Promise<void> {
await deleteRows(orm, DayAssignments, { place: placeId });
await deleteRows(orm, Tours, { place: placeId });
await deleteRows(orm, Places, { id: placeId });
}
describe('Assignments e2e (real auth guard + temp SQLite)', () => {
let server: Server;
@@ -70,40 +96,42 @@ describe('Assignments e2e (real auth guard + temp SQLite)', () => {
// password_version=0 that sessionCookie() needs. `username: 'e2e-user'`
// (user 1) matches the harness default so assertion bodies that spell
// out the owner's username stay unchanged.
db.prepare("INSERT INTO users (id, username, email, password_hash, role, password_version) VALUES (1, 'e2e-user', 'e2e@example.test', 'x', 'user', 0)").run();
db.prepare("INSERT INTO users (id, username, email, password_hash, role, password_version) VALUES (2, 'peer', 'peer@example.test', 'x', 'user', 0)").run();
orm = await createTestOrm(db);
await makeUser(orm, { id: 1, username: 'e2e-user', email: 'e2e@example.test' });
await makeUser(orm, { id: 2, username: 'peer', email: 'peer@example.test' });
// Plan 3c Task 0b: TripAccessGuard reads TripsRepository.findAccessible
// directly now, a real query — trip 5's real row (owned by user 1) is
// seeded once here rather than faked per test. `days.day_number` is
// `NOT NULL` on the real schema (the old hand-rolled DDL had no such
// constraint).
db.prepare("INSERT INTO trips (id, user_id, title) VALUES (5, 1, 'Trip')").run();
db.prepare('INSERT INTO days (id, trip_id, day_number) VALUES (3, 5, 1), (4, 5, 2)').run();
db.prepare('INSERT INTO places (id, trip_id, name) VALUES (2, 5, ?)').run('Louvre');
await insertRow(orm, Trips, { id: 5, user: 1, title: 'Trip' });
await insertRows(orm, Days, [{ id: 3, trip: 5, day_number: 1 }, { id: 4, trip: 5, day_number: 2 }]);
await insertRow(orm, Places, { id: 2, trip: 5, name: 'Louvre' });
app = await build();
checkPermission = vi.spyOn(app.get(PermissionsService), 'checkPermission');
server = app.getHttpServer();
});
beforeEach(() => {
beforeEach(async () => {
checkPermission.mockReturnValue(true);
db.prepare('DELETE FROM day_assignments').run();
db.prepare('DELETE FROM assignment_participants').run();
await deleteRows(orm, DayAssignments);
await deleteRows(orm, AssignmentParticipants);
});
afterAll(async () => {
await app.close();
await orm.close();
});
const seedAssignment = (dayId = 3, placeId = 2, orderIndex = 0) =>
Number(db.prepare('INSERT INTO day_assignments (day_id, place_id, order_index) VALUES (?, ?, ?)').run(dayId, placeId, orderIndex).lastInsertRowid);
insertRow(orm, DayAssignments, { day: dayId, place: placeId, order_index: orderIndex });
it('401 without a cookie', async () => {
expect((await request(server).get('/api/trips/5/days/3/assignments')).status).toBe(401);
});
it('200 list day-assignments', async () => {
const id = seedAssignment();
const id = await seedAssignment();
const res = await request(server).get('/api/trips/5/days/3/assignments').set('Cookie', sessionCookie(1));
expect(res.status).toBe(200);
expect(res.body.assignments).toHaveLength(1);
@@ -116,14 +144,16 @@ describe('Assignments e2e (real auth guard + temp SQLite)', () => {
it('200 list projects Tour facets once per assignment and leaves other tracks ordinary', async () => {
const legacyGeometry = JSON.stringify([[48, 11, 600], [48.01, 11.02, 650]]);
const tourGeometry = JSON.stringify([[48.02, 11.03, 700], [48.03, 11.04, 750]]);
db.prepare('INSERT INTO places (id, trip_id, name, route_geometry) VALUES (3, 5, ?, ?), (4, 5, ?, ?)')
.run('Legacy track', legacyGeometry, 'Tour', tourGeometry);
db.prepare("INSERT INTO tours (place_id, tour_type) VALUES (4, 'hike')").run();
await insertRows(orm, Places, [
{ id: 3, trip: 5, name: 'Legacy track', route_geometry: legacyGeometry },
{ id: 4, trip: 5, name: 'Tour', route_geometry: tourGeometry },
]);
await makeTour(orm, 4, { tourTypeRef: 'hike' });
const assignmentIds = [
seedAssignment(3, 2, 0),
seedAssignment(3, 3, 1),
seedAssignment(3, 4, 2),
seedAssignment(3, 4, 3),
await seedAssignment(3, 2, 0),
await seedAssignment(3, 3, 1),
await seedAssignment(3, 4, 2),
await seedAssignment(3, 4, 3),
];
const res = await request(server).get('/api/trips/5/days/3/assignments').set('Cookie', sessionCookie(1));
@@ -140,9 +170,9 @@ describe('Assignments e2e (real auth guard + temp SQLite)', () => {
expect(assignments.map(a => a.id)).toEqual(assignmentIds);
expect(assignments.map(a => a.order_index)).toEqual([0, 1, 2, 3]);
expect(assignments[0]).toMatchObject({ place_id: 2, tour_place_id: null, tour_route_geometry: null });
expect(db.prepare('SELECT route_geometry FROM places WHERE id = 3').get()).toEqual({ route_geometry: legacyGeometry });
expect(db.prepare('SELECT place_id FROM tours WHERE place_id = 3').get()).toBeUndefined();
expect(db.prepare('SELECT place_id FROM tours WHERE place_id = 4').get()).toEqual({ place_id: 4 });
expect((await findRow(orm, Places, { id: 3 }))!.route_geometry).toBe(legacyGeometry);
expect(await findRow(orm, Tours, { place: 3 })).toBeNull();
expect((await findRow(orm, Tours, { place: 4 }))!.place_id).toBe(4);
expect(assignments[1]).toMatchObject({ place_id: 3, tour_place_id: null, tour_route_geometry: null });
expect(assignments.slice(2).map(a => ({
place_id: a.place_id,
@@ -159,7 +189,7 @@ describe('Assignments e2e (real auth guard + temp SQLite)', () => {
const ok = await request(server).post('/api/trips/5/days/3/assignments').set('Cookie', sessionCookie(1)).send({ place_id: 2 });
expect(ok.status).toBe(201);
expect(ok.body.assignment).toMatchObject({ day_id: 3, place_id: 2, order_index: 0, notes: null, place: { id: 2, name: 'Louvre' } });
const row = db.prepare('SELECT * FROM day_assignments WHERE id = ?').get(ok.body.assignment.id);
const row = await findRow(orm, DayAssignments, { id: ok.body.assignment.id });
expect(row).toMatchObject({ day_id: 3, place_id: 2, order_index: 0 });
expect(reconcileTripSkeletons).toHaveBeenCalledWith(5, undefined);
const miss = await request(server).post('/api/trips/5/days/3/assignments').set('Cookie', sessionCookie(1)).send({ place_id: 99 });
@@ -169,8 +199,8 @@ describe('Assignments e2e (real auth guard + temp SQLite)', () => {
it('prevents duplicate Tour/day assignments through concurrent REST requests', async () => {
const tourPlaceId = 20;
db.prepare('INSERT INTO places (id, trip_id, name) VALUES (?, 5, ?)').run(tourPlaceId, 'Ridge walk');
db.prepare("INSERT INTO tours (place_id, tour_type) VALUES (?, 'hike')").run(tourPlaceId);
await insertRow(orm, Places, { id: tourPlaceId, trip: 5, name: 'Ridge walk' });
await makeTour(orm, tourPlaceId, { tourTypeRef: 'hike' });
try {
const createTourAssignment = () => request(server)
.post('/api/trips/5/days/3/assignments')
@@ -179,12 +209,12 @@ describe('Assignments e2e (real auth guard + temp SQLite)', () => {
const results = await Promise.all([createTourAssignment(), createTourAssignment()]);
expect(results.map(result => result.status).sort()).toEqual([201, 409]);
expect(db.prepare('SELECT COUNT(*) AS n FROM day_assignments WHERE day_id = 3 AND place_id = ?').get(tourPlaceId)).toEqual({ n: 1 });
expect(await countRows(orm, DayAssignments, { day: 3, place: tourPlaceId })).toBe(1);
const otherDay = await request(server).post('/api/trips/5/days/4/assignments')
.set('Cookie', sessionCookie(1)).send({ place_id: tourPlaceId });
expect(otherDay.status).toBe(201);
expect(db.prepare('SELECT COUNT(*) AS n FROM day_assignments WHERE place_id = ?').get(tourPlaceId)).toEqual({ n: 2 });
expect(await countRows(orm, DayAssignments, { place: tourPlaceId })).toBe(2);
const firstOrdinary = await request(server).post('/api/trips/5/days/3/assignments')
.set('Cookie', sessionCookie(1)).send({ place_id: 2 });
@@ -193,38 +223,36 @@ describe('Assignments e2e (real auth guard + temp SQLite)', () => {
expect(firstOrdinary.status).toBe(201);
expect(secondOrdinary.status).toBe(201);
} finally {
db.prepare('DELETE FROM day_assignments WHERE place_id = ?').run(tourPlaceId);
db.prepare('DELETE FROM tours WHERE place_id = ?').run(tourPlaceId);
db.prepare('DELETE FROM places WHERE id = ?').run(tourPlaceId);
await dropTourPlace(tourPlaceId);
}
});
it('200 delete assignment reconciles journey skeletons', async () => {
reconcileTripSkeletons.mockClear();
const id = seedAssignment();
const id = await seedAssignment();
const res = await request(server).delete(`/api/trips/5/days/3/assignments/${id}`).set('Cookie', sessionCookie(1));
expect(res.status).toBe(200);
expect(res.body).toEqual({ success: true });
expect(db.prepare('SELECT id FROM day_assignments WHERE id = ?').get(id)).toBeUndefined();
expect(await findRow(orm, DayAssignments, { id })).toBeNull();
expect(reconcileTripSkeletons).toHaveBeenCalledWith(5, undefined);
});
it('200 clear day removes every place of the day and keeps the day (#2470)', async () => {
reconcileTripSkeletons.mockClear();
const first = seedAssignment(3, 2, 0);
const second = seedAssignment(3, 2, 1);
const elsewhere = seedAssignment(4, 2, 0);
const first = await seedAssignment(3, 2, 0);
const second = await seedAssignment(3, 2, 1);
const elsewhere = await seedAssignment(4, 2, 0);
const res = await request(server).delete('/api/trips/5/days/3/assignments').set('Cookie', sessionCookie(1));
expect(res.status).toBe(200);
expect(res.body.success).toBe(true);
expect([...res.body.removedIds].sort()).toEqual([first, second].sort());
expect(db.prepare('SELECT COUNT(*) AS n FROM day_assignments WHERE day_id = 3').get()).toEqual({ n: 0 });
expect(db.prepare('SELECT id FROM day_assignments WHERE id = ?').get(elsewhere)).toEqual({ id: elsewhere });
expect(await countRows(orm, DayAssignments, { day: 3 })).toBe(0);
expect(await assignmentCols(elsewhere, 'id')).toEqual({ id: elsewhere });
expect(reconcileTripSkeletons).toHaveBeenCalledWith(5, undefined);
});
it('403 clear day without day_edit, 404 for a foreign day', async () => {
seedAssignment();
await seedAssignment();
checkPermission.mockReturnValue(false);
expect((await request(server).delete('/api/trips/5/days/3/assignments').set('Cookie', sessionCookie(1))).status).toBe(403);
checkPermission.mockReturnValue(true);
@@ -234,7 +262,7 @@ describe('Assignments e2e (real auth guard + temp SQLite)', () => {
});
it('200 route exclude roundtrip, 400 without a boolean (#2532)', async () => {
const id = seedAssignment();
const id = await seedAssignment();
const res = await request(server).put(`/api/trips/5/assignments/${id}/route`).set('Cookie', sessionCookie(1)).send({ excluded: true });
expect(res.status).toBe(200);
expect(res.body.assignment).toMatchObject({ id, route_excluded: true });
@@ -245,31 +273,31 @@ describe('Assignments e2e (real auth guard + temp SQLite)', () => {
it('200 move assignment reconciles journey skeletons', async () => {
reconcileTripSkeletons.mockClear();
const id = seedAssignment();
const id = await seedAssignment();
const res = await request(server)
.put(`/api/trips/5/assignments/${id}/move`)
.set('Cookie', sessionCookie(1))
.send({ new_day_id: 4, order_index: 0 });
expect(res.status).toBe(200);
expect(res.body.assignment).toMatchObject({ id, day_id: 4, order_index: 0 });
expect(db.prepare('SELECT day_id FROM day_assignments WHERE id = ?').get(id)).toEqual({ day_id: 4 });
expect(await assignmentCols(id, 'day_id')).toEqual({ day_id: 4 });
expect(reconcileTripSkeletons).toHaveBeenCalledWith(5, undefined);
});
it('409 moving a Tour onto a day that already holds it, the row stays put; a reorder within its day still works', async () => {
const tourPlaceId = 21;
db.prepare('INSERT INTO places (id, trip_id, name) VALUES (?, 5, ?)').run(tourPlaceId, 'Lake loop');
db.prepare("INSERT INTO tours (place_id, tour_type) VALUES (?, 'hike')").run(tourPlaceId);
await insertRow(orm, Places, { id: tourPlaceId, trip: 5, name: 'Lake loop' });
await makeTour(orm, tourPlaceId, { tourTypeRef: 'hike' });
try {
seedAssignment(4, tourPlaceId, 0);
const moving = seedAssignment(3, tourPlaceId, 0);
await seedAssignment(4, tourPlaceId, 0);
const moving = await seedAssignment(3, tourPlaceId, 0);
const conflict = await request(server)
.put(`/api/trips/5/assignments/${moving}/move`)
.set('Cookie', sessionCookie(1))
.send({ new_day_id: 4, order_index: 1 });
expect(conflict.status).toBe(409);
expect(conflict.body).toEqual({ error: 'Tour is already assigned to this day' });
expect(db.prepare('SELECT day_id, order_index FROM day_assignments WHERE id = ?').get(moving)).toEqual({ day_id: 3, order_index: 0 });
expect(await assignmentCols(moving, 'day_id', 'order_index')).toEqual({ day_id: 3, order_index: 0 });
const reorder = await request(server)
.put(`/api/trips/5/assignments/${moving}/move`)
@@ -278,9 +306,7 @@ describe('Assignments e2e (real auth guard + temp SQLite)', () => {
expect(reorder.status).toBe(200);
expect(reorder.body.assignment).toMatchObject({ id: moving, day_id: 3, order_index: 2, tour_place_id: tourPlaceId });
} finally {
db.prepare('DELETE FROM day_assignments WHERE place_id = ?').run(tourPlaceId);
db.prepare('DELETE FROM tours WHERE place_id = ?').run(tourPlaceId);
db.prepare('DELETE FROM places WHERE id = ?').run(tourPlaceId);
await dropTourPlace(tourPlaceId);
}
});
@@ -297,7 +323,7 @@ describe('Assignments e2e (real auth guard + temp SQLite)', () => {
.send({ notes: 'Arrive 15 minutes early' });
expect(put.status).toBe(200);
expect(put.body.assignment).toMatchObject({ id, notes: 'Arrive 15 minutes early' });
expect(db.prepare('SELECT notes FROM day_assignments WHERE id = ?').get(id)).toEqual({ notes: 'Arrive 15 minutes early' });
expect(await assignmentCols(id, 'notes')).toEqual({ notes: 'Arrive 15 minutes early' });
const list = await request(server).get('/api/trips/5/days/3/assignments').set('Cookie', sessionCookie(1));
expect(list.status).toBe(200);
@@ -305,50 +331,54 @@ describe('Assignments e2e (real auth guard + temp SQLite)', () => {
});
it('200 notes clear: null and empty string both null the column (#2163)', async () => {
const id = seedAssignment();
db.prepare('UPDATE day_assignments SET notes = ? WHERE id = ?').run('old note', id);
const id = await seedAssignment();
await updateRows(orm, DayAssignments, { id }, { notes: 'old note' });
const cleared = await request(server).put(`/api/trips/5/assignments/${id}/notes`).set('Cookie', sessionCookie(1)).send({ notes: null });
expect(cleared.status).toBe(200);
expect(cleared.body.assignment.notes).toBeNull();
db.prepare('UPDATE day_assignments SET notes = ? WHERE id = ?').run('old note', id);
await updateRows(orm, DayAssignments, { id }, { notes: 'old note' });
const emptied = await request(server).put(`/api/trips/5/assignments/${id}/notes`).set('Cookie', sessionCookie(1)).send({ notes: '' });
expect(emptied.status).toBe(200);
expect(db.prepare('SELECT notes FROM day_assignments WHERE id = ?').get(id)).toEqual({ notes: null });
expect(await assignmentCols(id, 'notes')).toEqual({ notes: null });
});
it('400 notes body without the notes key is rejected by the Zod pipe (#2163)', async () => {
const id = seedAssignment();
const id = await seedAssignment();
const res = await request(server).put(`/api/trips/5/assignments/${id}/notes`).set('Cookie', sessionCookie(1)).send({});
expect(res.status).toBe(400);
});
it('200 update time reconciles journey skeletons', async () => {
reconcileTripSkeletons.mockClear();
const id = seedAssignment();
const id = await seedAssignment();
const res = await request(server)
.put(`/api/trips/5/assignments/${id}/time`)
.set('Cookie', sessionCookie(1))
.send({ place_time: '09:00', end_time: null });
expect(res.status).toBe(200);
expect(res.body.assignment).toMatchObject({ id, assignment_time: '09:00', assignment_end_time: null });
expect(db.prepare('SELECT assignment_time FROM day_assignments WHERE id = ?').get(id)).toEqual({ assignment_time: '09:00' });
expect(await assignmentCols(id, 'assignment_time')).toEqual({ assignment_time: '09:00' });
expect(reconcileTripSkeletons).toHaveBeenCalledWith(5, undefined);
});
describe('PUT /:id/time and the order of the day', () => {
const seedDay = (times: (string | null)[]) => times.map((time, i) => {
const id = seedAssignment(3, 2, i);
if (time) db.prepare('UPDATE day_assignments SET assignment_time = ? WHERE id = ?').run(time, id);
return id;
});
const dayOrder = () =>
(db.prepare('SELECT id FROM day_assignments WHERE day_id = 3 ORDER BY order_index, id').all() as { id: number }[]).map(r => r.id);
const seedDay = async (times: (string | null)[]) => {
const ids: number[] = [];
for (const [i, time] of times.entries()) {
const id = await seedAssignment(3, 2, i);
if (time) await updateRows(orm, DayAssignments, { id }, { assignment_time: time });
ids.push(id);
}
return ids;
};
const dayOrder = async () =>
(await findRows(orm, DayAssignments, { day: 3 }, { order_index: 'asc', id: 'asc' })).map(r => r.id);
const eventsSent = () => broadcast.mock.calls.map(call => call[1]);
beforeEach(() => broadcast.mockClear());
it('keeps the untimed stops in front of the stop that gets a start', async () => {
const [a, b, c] = seedDay([null, null, null]);
const [a, b, c] = await seedDay([null, null, null]);
const res = await request(server)
.put(`/api/trips/5/assignments/${c}/time`)
.set('Cookie', sessionCookie(1))
@@ -356,19 +386,19 @@ describe('Assignments e2e (real auth guard + temp SQLite)', () => {
.send({ place_time: '14:00', end_time: null });
expect(res.status).toBe(200);
expect(res.body.assignment).toMatchObject({ id: c, assignment_time: '14:00', order_index: 2 });
expect(dayOrder()).toEqual([a, b, c]);
expect(await dayOrder()).toEqual([a, b, c]);
expect(eventsSent()).toEqual(['assignment:updated']);
});
it('sorts the timed stops, keeps the untimed head first and sends the whole day', async () => {
const [a, b, c] = seedDay([null, '15:00', null]);
const [a, b, c] = await seedDay([null, '15:00', null]);
const res = await request(server)
.put(`/api/trips/5/assignments/${c}/time`)
.set('Cookie', sessionCookie(1))
.set('X-Socket-Id', 'sock-1')
.send({ place_time: '10:00', end_time: null });
expect(res.status).toBe(200);
expect(dayOrder()).toEqual([a, c, b]);
expect(await dayOrder()).toEqual([a, c, b]);
// No socket left out, so the writer gets the order too.
expect(broadcast).toHaveBeenCalledWith('5', 'assignment:reordered', { dayId: 3, orderedIds: [a, c, b] }, undefined);
// No located stops and no vias on this day, so there is nothing to re-pin.
@@ -377,8 +407,8 @@ describe('Assignments e2e (real auth guard + temp SQLite)', () => {
it('stores the order it sends: a day with a gap in its keys is numbered from 0', async () => {
// The gap a deleted stop leaves. Clients number the ids they are sent by position.
const [a, b, c] = [0, 4, 7].map(key => seedAssignment(3, 2, key));
db.prepare('UPDATE day_assignments SET assignment_time = ? WHERE id = ?').run('15:00', b);
const [a, b, c] = [await seedAssignment(3, 2, 0), await seedAssignment(3, 2, 4), await seedAssignment(3, 2, 7)];
await updateRows(orm, DayAssignments, { id: b }, { assignment_time: '15:00' });
const res = await request(server)
.put(`/api/trips/5/assignments/${c}/time`)
.set('Cookie', sessionCookie(1))
@@ -386,14 +416,14 @@ describe('Assignments e2e (real auth guard + temp SQLite)', () => {
expect(res.status).toBe(200);
const sent = broadcast.mock.calls.find(call => call[1] === 'assignment:reordered')?.[2] as { orderedIds: number[] };
expect(sent.orderedIds).toEqual([a, c, b]);
const keyOf = (id: number) => (db.prepare('SELECT order_index FROM day_assignments WHERE id = ?').get(id) as { order_index: number }).order_index;
expect(sent.orderedIds.map(keyOf)).toEqual([0, 1, 2]);
const keyOf = async (id: number) => (await findRow(orm, DayAssignments, { id }))!.order_index;
expect(await Promise.all(sent.orderedIds.map(keyOf))).toEqual([0, 1, 2]);
expect(res.body.assignment).toMatchObject({ id: c, order_index: 1 });
});
it('leaves a day dragged out of time order alone when only the End changes', async () => {
const [a, b] = seedDay(['14:00', '10:00']);
db.prepare("UPDATE day_assignments SET assignment_end_time = '11:00' WHERE id = ?").run(b);
const [a, b] = await seedDay(['14:00', '10:00']);
await updateRows(orm, DayAssignments, { id: b }, { assignment_end_time: '11:00' });
const res = await request(server)
.put(`/api/trips/5/assignments/${b}/time`)
.set('Cookie', sessionCookie(1))
@@ -401,13 +431,13 @@ describe('Assignments e2e (real auth guard + temp SQLite)', () => {
.send({ place_time: '10:00', end_time: null });
expect(res.status).toBe(200);
expect(res.body.assignment).toMatchObject({ id: b, assignment_time: '10:00', assignment_end_time: null });
expect(dayOrder()).toEqual([a, b]);
expect(await dayOrder()).toEqual([a, b]);
expect(eventsSent()).toEqual(['assignment:updated']);
});
});
it('200 set participants replaces the list (AS28-31, the roster-scoped roundtrip)', async () => {
const id = seedAssignment();
const id = await seedAssignment();
// user 1 is trip 5's owner — TripMembersRepository.rosterUserIds includes
// the owner without a trip_members row (AS28), so this exercises the
// replace-all write (AS29 delete + AS30 insertIgnore) without needing a
@@ -418,7 +448,7 @@ describe('Assignments e2e (real auth guard + temp SQLite)', () => {
.send({ user_ids: [1, 1] }); // duplicate collapses via AS30's INSERT OR IGNORE
expect(res.status).toBe(200);
expect(res.body.participants).toEqual([{ user_id: 1, username: 'e2e-user', avatar: null }]);
expect(db.prepare('SELECT user_id FROM assignment_participants WHERE assignment_id = ?').all(id)).toEqual([{ user_id: 1 }]);
expect((await findRows(orm, AssignmentParticipants, { assignment: id }, { id: 'asc' })).map(r => ({ user_id: r.user_id }))).toEqual([{ user_id: 1 }]);
const cleared = await request(server)
.put(`/api/trips/5/assignments/${id}/participants`)
@@ -429,8 +459,8 @@ describe('Assignments e2e (real auth guard + temp SQLite)', () => {
});
it('200 participants (access-only)', async () => {
const id = seedAssignment();
db.prepare('INSERT INTO assignment_participants (assignment_id, user_id) VALUES (?, 2)').run(id);
const id = await seedAssignment();
await insertRow(orm, AssignmentParticipants, { assignment: id, user: 2 });
const res = await request(server).get(`/api/trips/5/assignments/${id}/participants`).set('Cookie', sessionCookie(1));
expect(res.status).toBe(200);
expect(res.body).toEqual({ participants: [{ user_id: 2, username: 'peer', avatar: null }] });
@@ -449,7 +479,7 @@ describe('Assignments e2e (real auth guard + temp SQLite)', () => {
});
it('move accepts the client api form order_index: null (coerces to 0)', async () => {
const id = seedAssignment();
const id = await seedAssignment();
const res = await request(server)
.put(`/api/trips/5/assignments/${id}/move`)
.set('Cookie', sessionCookie(1))
@@ -466,42 +496,42 @@ describe('Assignments e2e (real auth guard + temp SQLite)', () => {
describe('a trip the caller cannot see', () => {
const FOREIGN_TRIP = 9;
beforeEach(() => {
beforeEach(async () => {
// Plan 3c Task 0b: real access now — trip 9 exists but is owned by
// user 2 (not the caller, user 1, and not a member), so
// TripsRepository.findAccessible genuinely refuses it, the same
// outcome `canAccessTrip.mockImplementation` used to fake.
db.prepare('INSERT OR IGNORE INTO trips (id, user_id, title) VALUES (?, 2, ?)').run(FOREIGN_TRIP, 'Their trip');
await insertRowIgnoringConflict(orm, Trips, { id: FOREIGN_TRIP, user: 2, title: 'Their trip' });
// day_number is NOT NULL on the real schema (the old hand-rolled DDL had no such constraint).
db.prepare('INSERT OR IGNORE INTO days (id, trip_id, day_number) VALUES (30, ?, 1), (31, ?, 2)').run(FOREIGN_TRIP, FOREIGN_TRIP);
db.prepare('INSERT OR IGNORE INTO places (id, trip_id, name) VALUES (20, ?, ?)').run(FOREIGN_TRIP, 'Their hotel');
await insertRowIgnoringConflict(orm, Days, { id: 30, trip: FOREIGN_TRIP, day_number: 1 });
await insertRowIgnoringConflict(orm, Days, { id: 31, trip: FOREIGN_TRIP, day_number: 2 });
await insertRowIgnoringConflict(orm, Places, { id: 20, trip: FOREIGN_TRIP, name: 'Their hotel' });
});
const seedForeignAssignment = () =>
Number(db.prepare('INSERT INTO day_assignments (day_id, place_id, order_index) VALUES (30, 20, 0)').run().lastInsertRowid);
const seedForeignAssignment = () => insertRow(orm, DayAssignments, { day: 30, place: 20, order_index: 0 });
it('404s a move instead of reordering their itinerary', async () => {
const id = seedForeignAssignment();
const id = await seedForeignAssignment();
const res = await request(server)
.put(`/api/trips/${FOREIGN_TRIP}/assignments/${id}/move`)
.set('Cookie', sessionCookie(1))
.send({ new_day_id: 31, order_index: 0 });
expect(res.status).toBe(404);
expect(db.prepare('SELECT day_id FROM day_assignments WHERE id = ?').get(id)).toEqual({ day_id: 30 });
expect(await assignmentCols(id, 'day_id')).toEqual({ day_id: 30 });
});
it('404s a time change instead of rewriting their schedule', async () => {
const id = seedForeignAssignment();
const id = await seedForeignAssignment();
const res = await request(server)
.put(`/api/trips/${FOREIGN_TRIP}/assignments/${id}/time`)
.set('Cookie', sessionCookie(1))
.send({ place_time: '23:00', end_time: null });
expect(res.status).toBe(404);
expect(db.prepare('SELECT assignment_time FROM day_assignments WHERE id = ?').get(id)).toEqual({ assignment_time: null });
expect(await assignmentCols(id, 'assignment_time')).toEqual({ assignment_time: null });
});
it('404s a transport change', async () => {
const id = seedForeignAssignment();
const id = await seedForeignAssignment();
const res = await request(server)
.put(`/api/trips/${FOREIGN_TRIP}/assignments/${id}/transport`)
.set('Cookie', sessionCookie(1))
@@ -510,18 +540,18 @@ describe('Assignments e2e (real auth guard + temp SQLite)', () => {
});
it('404s setting participants instead of writing to their assignment', async () => {
const id = seedForeignAssignment();
const id = await seedForeignAssignment();
const res = await request(server)
.put(`/api/trips/${FOREIGN_TRIP}/assignments/${id}/participants`)
.set('Cookie', sessionCookie(1))
.send({ user_ids: [1] });
expect(res.status).toBe(404);
expect(db.prepare('SELECT COUNT(*) AS n FROM assignment_participants WHERE assignment_id = ?').get(id)).toEqual({ n: 0 });
expect(await countRows(orm, AssignmentParticipants, { assignment: id })).toBe(0);
});
it('404s reading participants instead of disclosing who is on it', async () => {
const id = seedForeignAssignment();
db.prepare('INSERT INTO assignment_participants (assignment_id, user_id) VALUES (?, 2)').run(id);
const id = await seedForeignAssignment();
await insertRow(orm, AssignmentParticipants, { assignment: id, user: 2 });
const res = await request(server)
.get(`/api/trips/${FOREIGN_TRIP}/assignments/${id}/participants`)
.set('Cookie', sessionCookie(1));
@@ -531,27 +561,27 @@ describe('Assignments e2e (real auth guard + temp SQLite)', () => {
// The guard has to reject an assignment borrowed from elsewhere even when the
// caller is legitimately on the trip named in the URL.
it('404s an assignment that belongs to another trip than the URL says', async () => {
const id = seedForeignAssignment();
const id = await seedForeignAssignment();
const res = await request(server)
.put(`/api/trips/5/assignments/${id}/participants`)
.set('Cookie', sessionCookie(1))
.send({ user_ids: [1] });
expect(res.status).toBe(404);
expect(db.prepare('SELECT COUNT(*) AS n FROM assignment_participants WHERE assignment_id = ?').get(id)).toEqual({ n: 0 });
expect(await countRows(orm, AssignmentParticipants, { assignment: id })).toBe(0);
});
it('404s a notes change on a foreign assignment instead of editing it (#2163)', async () => {
const id = seedForeignAssignment();
const id = await seedForeignAssignment();
const res = await request(server)
.put(`/api/trips/${FOREIGN_TRIP}/assignments/${id}/notes`)
.set('Cookie', sessionCookie(1))
.send({ notes: 'hijacked' });
expect(res.status).toBe(404);
expect(db.prepare('SELECT notes FROM day_assignments WHERE id = ?').get(id)).toEqual({ notes: null });
expect(await assignmentCols(id, 'notes')).toEqual({ notes: null });
});
it('403s when the caller is on the trip but lacks day_edit', async () => {
const id = seedAssignment();
const id = await seedAssignment();
checkPermission.mockReturnValue(false);
const res = await request(server)
.put(`/api/trips/5/assignments/${id}/time`)
@@ -561,14 +591,14 @@ describe('Assignments e2e (real auth guard + temp SQLite)', () => {
});
it('403s a notes change without day_edit (#2163)', async () => {
const id = seedAssignment();
const id = await seedAssignment();
checkPermission.mockReturnValue(false);
const res = await request(server)
.put(`/api/trips/5/assignments/${id}/notes`)
.set('Cookie', sessionCookie(1))
.send({ notes: 'nope' });
expect(res.status).toBe(403);
expect(db.prepare('SELECT notes FROM day_assignments WHERE id = ?').get(id)).toEqual({ notes: null });
expect(await assignmentCols(id, 'notes')).toEqual({ notes: null });
});
});
});
+31 -40
View File
@@ -1,49 +1,38 @@
/**
* Categories module e2e — exercises the migrated /api/categories endpoints
* through the real JwtAuthGuard + AdminGuard against a temp SQLite db seeded
* with an admin and a normal user. CategoriesService runs its real SQL via
* DatabaseModule (the DATABASE_CONNECTION factory picks up the mocked db
* singleton): listing is open to any authenticated user; writes are admin-only.
* through the real JwtAuthGuard + AdminGuard against a migrated temp SQLite db
* (createSnapshotTestDb()) seeded with an admin and a normal user through the
* factories in tests/helpers/factories. CategoriesService runs its real
* queries: listing is open to any authenticated user; writes are admin-only.
*/
import { describe, it, expect, beforeAll, beforeEach, afterAll, vi } from 'vitest';
import request from 'supertest';
import cookieParser from 'cookie-parser';
import type { Server } from 'http';
import { Test } from '@nestjs/testing';
import { seedUser, sessionCookie } from './harness';
import { sessionCookie } from './harness';
const { db } = vi.hoisted(() => {
// eslint-disable-next-line @typescript-eslint/no-require-imports
const Database = require('better-sqlite3');
const tmp = new Database(':memory:');
tmp.exec('PRAGMA journal_mode = WAL');
tmp.exec(`CREATE TABLE users (id INTEGER PRIMARY KEY AUTOINCREMENT, username TEXT NOT NULL,
email TEXT NOT NULL UNIQUE, role TEXT NOT NULL DEFAULT 'user', password_version INTEGER NOT NULL DEFAULT 0);`);
tmp.exec(`CREATE TABLE categories (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT NOT NULL,
color TEXT DEFAULT '#6366f1',
icon TEXT DEFAULT '📍',
user_id INTEGER REFERENCES users(id) ON DELETE SET NULL,
created_at DATETIME DEFAULT CURRENT_TIMESTAMP
);`);
return { db: tmp };
vi.mock('../../src/db/database', async () => {
const { createSnapshotTestDb, buildDbMock } = await import('../helpers/db-mock');
return buildDbMock(createSnapshotTestDb());
});
vi.mock('../../src/db/database', () => ({ db, closeDb: () => {}, reinitialize: () => {} }));
import { db } from '../../src/db/database';
import { CategoriesModule } from '../../src/nest/categories/categories.module';
import { RealtimeModule } from '../../src/nest/realtime/realtime.module';
import { TrekExceptionFilter } from '../../src/nest/common/trek-exception.filter';
import { ZodValidationPipe } from '../../src/nest/common/zod-validation.pipe';
import { TestUnitOfWorkModule } from '../helpers/test-uow';
import { createTestMikroOrmModule } from '../helpers/test-orm';
import { createTestMikroOrmModule, createTestOrm, type TestOrm } from '../helpers/test-orm';
import { makeAdmin, makeUser } from '../helpers/factories/users';
import { makeCategory } from '../helpers/factories/places';
import { countRows, deleteRows, findRow } from '../helpers/factories/rows';
import { Categories } from '../../src/db/entities/Categories.entity';
function insertCategory(name: string, color = '#6366f1', icon = '📍', userId = 1): number {
const res = db
.prepare('INSERT INTO categories (name, color, icon, user_id) VALUES (?, ?, ?, ?)')
.run(name, color, icon, userId);
return Number(res.lastInsertRowid);
let orm: TestOrm;
async function insertCategory(name: string, color = '#6366f1', icon = '📍', userId = 1): Promise<number> {
return (await makeCategory(orm, { name, color, icon, user: userId })).id;
}
describe('Categories e2e (real JwtAuthGuard + AdminGuard + temp SQLite)', () => {
@@ -68,18 +57,20 @@ describe('Categories e2e (real JwtAuthGuard + AdminGuard + temp SQLite)', () =>
}
beforeAll(async () => {
seedUser(db as never, { id: 1, role: 'admin', email: 'admin@example.test' });
seedUser(db as never, { id: 2, role: 'user', email: 'user@example.test' });
orm = await createTestOrm(db);
await makeAdmin(orm, { id: 1, username: 'e2e-admin', email: 'admin@example.test' });
await makeUser(orm, { id: 2, username: 'e2e-user', email: 'user@example.test' });
app = await build();
server = app.getHttpServer();
});
beforeEach(() => {
db.exec('DELETE FROM categories');
beforeEach(async () => {
await deleteRows(orm, Categories);
});
afterAll(async () => {
await app.close();
await orm.close();
});
it('401 without a session cookie', async () => {
@@ -88,8 +79,8 @@ describe('Categories e2e (real JwtAuthGuard + AdminGuard + temp SQLite)', () =>
});
it('200 list for any authenticated user (non-admin allowed), ordered by name', async () => {
insertCategory('Zoo');
insertCategory('Aquarium');
await insertCategory('Zoo');
await insertCategory('Aquarium');
const res = await request(server).get('/api/categories').set('Cookie', sessionCookie(2));
expect(res.status).toBe(200);
expect(res.body.categories.map((c: { name: string }) => c.name)).toEqual(['Aquarium', 'Zoo']);
@@ -99,7 +90,7 @@ describe('Categories e2e (real JwtAuthGuard + AdminGuard + temp SQLite)', () =>
const res = await request(server).post('/api/categories').set('Cookie', sessionCookie(2)).send({ name: 'X' });
expect(res.status).toBe(403);
expect(res.body).toEqual({ error: 'Admin access required' });
expect(db.prepare('SELECT COUNT(*) AS n FROM categories').get().n).toBe(0);
expect(await countRows(orm, Categories)).toBe(0);
});
it('201 when an admin creates a category, echoing name/color/icon and user_id', async () => {
@@ -133,7 +124,7 @@ describe('Categories e2e (real JwtAuthGuard + AdminGuard + temp SQLite)', () =>
});
it('400 when an admin updates a category to a non-hex colour', async () => {
const id = insertCategory('Food', '#fff', '🍔');
const id = await insertCategory('Food', '#fff', '🍔');
const res = await request(server)
.put(`/api/categories/${id}`)
.set('Cookie', sessionCookie(1))
@@ -142,7 +133,7 @@ describe('Categories e2e (real JwtAuthGuard + AdminGuard + temp SQLite)', () =>
});
it('200 when an admin updates, COALESCE preserving omitted fields', async () => {
const id = insertCategory('Food', '#fff', '🍔');
const id = await insertCategory('Food', '#fff', '🍔');
const res = await request(server).put(`/api/categories/${id}`).set('Cookie', sessionCookie(1)).send({ name: 'Drinks' });
expect(res.status).toBe(200);
expect(res.body.category).toMatchObject({ id, name: 'Drinks', color: '#fff', icon: '🍔' });
@@ -155,11 +146,11 @@ describe('Categories e2e (real JwtAuthGuard + AdminGuard + temp SQLite)', () =>
});
it('200 when an admin deletes an existing category, removing the row', async () => {
const id = insertCategory('ToDelete');
const id = await insertCategory('ToDelete');
const res = await request(server).delete(`/api/categories/${id}`).set('Cookie', sessionCookie(1));
expect(res.status).toBe(200);
expect(res.body).toEqual({ success: true });
expect(db.prepare('SELECT id FROM categories WHERE id = ?').get(id)).toBeUndefined();
expect(await findRow(orm, Categories, { id })).toBeNull();
});
it('404 when an admin deletes a missing category', async () => {
+24 -17
View File
@@ -32,12 +32,6 @@ vi.mock('../../src/db/database', async () => {
closeDb: () => {},
reinitialize: () => {},
getPlaceWithTags: () => null,
canAccessTrip: (tripId: number | string, userId: number) =>
db
.prepare(
'SELECT t.id, t.user_id FROM trips t LEFT JOIN trip_members m ON m.trip_id = t.id AND m.user_id = ? WHERE t.id = ? AND (t.user_id = ? OR m.user_id IS NOT NULL)',
)
.get(userId, tripId, userId),
isOwner: () => false,
};
});
@@ -79,7 +73,18 @@ import { NextcloudDocumentProvider, OpencloudDocumentProvider } from '../../src/
import { TrekExceptionFilter } from '../../src/nest/common/trek-exception.filter';
import { ZodValidationPipe } from '../../src/nest/common/zod-validation.pipe';
import { TestUnitOfWorkModule } from '../helpers/test-uow';
import { createTestMikroOrmModule } from '../helpers/test-orm';
import { createTestMikroOrmModule, createTestOrm, type TestOrm } from '../helpers/test-orm';
import { addTripMember } from '../helpers/factories/trips';
import { countRows, findRow, updateRows } from '../helpers/factories/rows';
import { DocumentConnections } from '../../src/db/entities/DocumentConnections.entity';
import { DocumentProviders } from '../../src/db/entities/DocumentProviders.entity';
import { TripDocumentLinks } from '../../src/db/entities/TripDocumentLinks.entity';
let orm: TestOrm;
async function connectionRow(tripId: number) {
return (await findRow(orm, DocumentConnections, { trip: tripId }))!;
}
/** A provider that answers plausibly but never opens a socket. */
function fakeProvider(id: string) {
@@ -151,14 +156,15 @@ describe('Document sync e2e (real guards + real services + temp SQLite)', () =>
}
beforeAll(async () => {
orm = await createTestOrm(db);
ownerId = createUser(db as never, { username: 'owner', email: 'owner@test.local' }).user.id;
memberId = createUser(db as never, { username: 'member', email: 'member@test.local' }).user.id;
strangerId = createUser(db as never, { username: 'stranger', email: 'stranger@test.local' }).user.id;
tripId = createTrip(db as never, ownerId, { title: 'Japan', start_date: '2026-10-01', end_date: '2026-10-07' }).id;
db.prepare('INSERT INTO trip_members (trip_id, user_id) VALUES (?, ?)').run(tripId, memberId);
await addTripMember(orm, tripId, memberId);
// Providers are off by default, exactly as a fresh install ships them.
db.prepare("UPDATE document_providers SET enabled = 1 WHERE id IN ('paperless', 'nextcloud')").run();
await updateRows(orm, DocumentProviders, { id: { $in: ['paperless', 'nextcloud'] } }, { enabled: 1 });
app = await build();
server = app.getHttpServer();
@@ -166,6 +172,7 @@ describe('Document sync e2e (real guards + real services + temp SQLite)', () =>
afterAll(async () => {
await app?.close();
await orm?.close();
db.close();
});
@@ -249,7 +256,7 @@ describe('Document sync e2e (real guards + real services + temp SQLite)', () =>
expect(JSON.stringify(res.body)).not.toContain('super-secret-token');
// And it is encrypted at rest, not merely hidden on the way out.
const row = db.prepare('SELECT secrets FROM document_connections WHERE trip_id = ?').get(tripId) as { secrets: string };
const row = await connectionRow(tripId);
expect(row.secrets).toMatch(/^enc:v1:/);
expect(row.secrets).not.toContain('super-secret-token');
});
@@ -260,7 +267,7 @@ describe('Document sync e2e (real guards + real services + temp SQLite)', () =>
.set('Cookie', sessionCookie(ownerId))
.send({ providerId: 'paperless', baseUrl: 'https://paperless.example.com', credentials: { api_token: '' } })
.expect(200);
const row = db.prepare('SELECT secrets FROM document_connections WHERE trip_id = ?').get(tripId) as { secrets: string };
const row = await connectionRow(tripId);
expect(row.secrets).toMatch(/^enc:v1:/);
});
@@ -272,7 +279,7 @@ describe('Document sync e2e (real guards + real services + temp SQLite)', () =>
.set('Cookie', sessionCookie(ownerId))
.send({ providerId: 'paperless', baseUrl: 'https://paperless.example.net', credentials: { api_token: '' } })
.expect(400);
const row = db.prepare('SELECT base_url FROM document_connections WHERE trip_id = ?').get(tripId) as { base_url: string };
const row = await connectionRow(tripId);
expect(row.base_url).toBe('https://paperless.example.com');
});
@@ -380,7 +387,7 @@ describe('Document sync e2e (real guards + real services + temp SQLite)', () =>
it('still names the store of a binding after the admin switches its provider off', async () => {
// The providers list drops a provider that is off, so the binding itself is
// the only thing left that can tell a member where the documents went.
db.prepare("UPDATE document_providers SET enabled = 0 WHERE id = 'paperless'").run();
await updateRows(orm, DocumentProviders, { id: 'paperless' }, { enabled: 0 });
try {
const providers = await request(server)
.get(`/api/trips/${tripId}/docsync/providers`)
@@ -405,7 +412,7 @@ describe('Document sync e2e (real guards + real services + temp SQLite)', () =>
const status = JSON.parse(result.content[0].text) as { links: Array<Record<string, unknown>> };
expect(status.links[0]).toMatchObject({ providerId: 'paperless', providerName: 'Paperless-ngx' });
} finally {
db.prepare("UPDATE document_providers SET enabled = 1 WHERE id = 'paperless'").run();
await updateRows(orm, DocumentProviders, { id: 'paperless' }, { enabled: 1 });
}
});
@@ -443,7 +450,7 @@ describe('Document sync e2e (real guards + real services + temp SQLite)', () =>
.set('Cookie', sessionCookie(ownerId))
.expect(200);
expect(res.body.documentsKept).toBe(true);
expect(db.prepare('SELECT COUNT(*) AS n FROM trip_document_links WHERE id = ?').get(linkId)).toEqual({ n: 0 });
expect(await countRows(orm, TripDocumentLinks, { id: linkId })).toBe(0);
});
it('disconnects the store through the real contract, bindings included', async () => {
@@ -467,8 +474,8 @@ describe('Document sync e2e (real guards + real services + temp SQLite)', () =>
.expect(200);
expect(res.body).toEqual({ success: true });
expect(db.prepare('SELECT COUNT(*) AS n FROM document_connections WHERE trip_id = ?').get(tripId)).toEqual({ n: 0 });
expect(db.prepare('SELECT COUNT(*) AS n FROM trip_document_links WHERE trip_id = ?').get(tripId)).toEqual({ n: 0 });
expect(await countRows(orm, DocumentConnections, { trip: tripId })).toBe(0);
expect(await countRows(orm, TripDocumentLinks, { trip: tripId })).toBe(0);
});
it('accepts an unknown webhook token without revealing that it is unknown', async () => {
+9 -3
View File
@@ -56,7 +56,11 @@ import { RealtimeModule } from '../../src/nest/realtime/realtime.module';
import { TrekExceptionFilter } from '../../src/nest/common/trek-exception.filter';
import { AppConfigModule } from '../../src/nest/app-config/app-config.module';
import { TestUnitOfWorkModule } from '../helpers/test-uow';
import { createTestMikroOrmModule } from '../helpers/test-orm';
import { createTestMikroOrmModule, createTestOrm, type TestOrm } from '../helpers/test-orm';
import { findRow, updateRows } from '../helpers/factories/rows';
import { Trips } from '../../src/db/entities/Trips.entity';
let orm: TestOrm;
const BASE = 'https://trek.example.test';
@@ -85,6 +89,7 @@ describe('Calendar-feed e2e (real auth guard + temp SQLite)', () => {
beforeAll(async () => {
prevAppUrl = process.env.APP_URL;
process.env.APP_URL = BASE;
orm = await createTestOrm(db);
app = await build();
vi.spyOn(app.get(CalendarService), 'buildTripCalendar').mockImplementation(buildTripCalendar as never);
server = app.getHttpServer();
@@ -100,6 +105,7 @@ describe('Calendar-feed e2e (real auth guard + temp SQLite)', () => {
if (prevAppUrl === undefined) delete process.env.APP_URL;
else process.env.APP_URL = prevAppUrl;
await app.close();
await orm.close();
});
// ── Trip token endpoints ───────────────────────────────────────────────────
@@ -202,7 +208,7 @@ describe('Calendar-feed e2e (real auth guard + temp SQLite)', () => {
expect(res.body).toEqual({ error: 'No permission' });
}
// Refused, not silently applied: the column is untouched.
expect((db.prepare('SELECT feed_token FROM trips WHERE id = ?').get(trip.id) as { feed_token: string | null }).feed_token).toBeNull();
expect((await findRow(orm, Trips, { id: trip.id }))!.feed_token).toBeNull();
});
it('a non-member still gets 404 rather than 403, so the 403 is no existence oracle', async () => {
@@ -288,7 +294,7 @@ describe('Calendar-feed e2e (real auth guard + temp SQLite)', () => {
const { user: owner } = createUser(db);
const active = createTrip(db, owner.id, { title: 'Active', start_date: '2026-01-01', end_date: '2099-01-01' });
const archived = createTrip(db, owner.id, { title: 'Archived', start_date: '2026-01-01', end_date: '2099-01-01' });
db.prepare('UPDATE trips SET is_archived = 1 WHERE id = ?').run(archived.id);
await updateRows(orm, Trips, { id: archived.id }, { is_archived: 1 });
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));
+80 -58
View File
@@ -49,7 +49,19 @@ import { PlacesService } from '../../src/nest/places/places.service';
import { TrekExceptionFilter } from '../../src/nest/common/trek-exception.filter';
import { ZodValidationPipe } from '../../src/nest/common/zod-validation.pipe';
import { TestUnitOfWorkModule } from '../helpers/test-uow';
import { createTestMikroOrmModule } from '../helpers/test-orm';
import { createTestMikroOrmModule, createTestOrm, type TestOrm } from '../helpers/test-orm';
import { makeUser } from '../helpers/factories/users';
import { makeTour } from '../helpers/factories/tours';
import { countRows, deleteRows, findRow, findRows, insertRow, insertRows, upsertRow } from '../helpers/factories/rows';
import { BudgetItems } from '../../src/db/entities/BudgetItems.entity';
import { DayAssignments } from '../../src/db/entities/DayAssignments.entity';
import { Days } from '../../src/db/entities/Days.entity';
import { PlaceRatings } from '../../src/db/entities/PlaceRatings.entity';
import { Places } from '../../src/db/entities/Places.entity';
import { Tours } from '../../src/db/entities/Tours.entity';
import { Trips } from '../../src/db/entities/Trips.entity';
let orm: TestOrm;
describe('Places e2e (real auth guard + temp SQLite)', () => {
let server: Server;
@@ -79,29 +91,31 @@ describe('Places e2e (real auth guard + temp SQLite)', () => {
// trip (id 6) several tests below reference — `trips.user_id` and
// `places.trip_id` both carry a real FK now (`ON DELETE CASCADE`), so a
// dangling trip_id the old hand-rolled DDL tolerated would fail here.
db.prepare("INSERT INTO users (id, username, email, password_hash, role, password_version) VALUES (1, 'e2e-user', 'e2e@example.test', 'x', 'user', 0)").run();
db.prepare("INSERT INTO users (id, username, email, password_hash, role, password_version) VALUES (2, 'peer', 'peer@example.test', 'x', 'user', 0)").run();
db.prepare("INSERT INTO trips (id, title, user_id) VALUES (6, 'Theirs', 2)").run();
orm = await createTestOrm(db);
await makeUser(orm, { id: 1, username: 'e2e-user', email: 'e2e@example.test' });
await makeUser(orm, { id: 2, username: 'peer', email: 'peer@example.test' });
await insertRow(orm, Trips, { id: 6, title: 'Theirs', user: 2 });
app = await build();
checkPermission = vi.spyOn(app.get(PermissionsService), 'checkPermission');
server = app.getHttpServer();
});
beforeEach(() => {
beforeEach(async () => {
// Trip 5 (owned by user 1) is the suite's main trip, re-seeded fresh
// every test — deleting it (`ON DELETE CASCADE`) also clears every place/
// day/assignment/rating/tag-link/budget-item this suite seeded under it,
// the real-FK equivalent of the old blanket `DELETE FROM places; …`.
// Trip 6 (the "foreign" trip, owned by user 2) is seeded once in
// beforeAll and left alone.
db.exec('DELETE FROM trips WHERE id = 5;');
db.prepare("INSERT INTO trips (id, title, user_id) VALUES (5, 'Trip', 1)").run();
db.exec('DELETE FROM places WHERE trip_id = 6;');
await deleteRows(orm, Trips, { id: 5 });
await insertRow(orm, Trips, { id: 5, title: 'Trip', user: 1 });
await deleteRows(orm, Places, { trip: 6 });
checkPermission.mockReturnValue(true);
});
afterAll(async () => {
await app.close();
await orm.close();
});
it('401 without a cookie', async () => {
@@ -109,7 +123,7 @@ describe('Places e2e (real auth guard + temp SQLite)', () => {
});
it('200 list', async () => {
db.prepare("INSERT INTO places (id, trip_id, name) VALUES (1, 5, 'Spot')").run();
await insertRow(orm, Places, { id: 1, trip: 5, name: 'Spot' });
const res = await request(server).get('/api/trips/5/places').set('Cookie', sessionCookie(1));
expect(res.status).toBe(200);
expect(res.body.places).toHaveLength(1);
@@ -117,8 +131,8 @@ describe('Places e2e (real auth guard + temp SQLite)', () => {
});
it('marks Tour-backed Places without changing ordinary Place rows', async () => {
db.prepare("INSERT INTO places (id, trip_id, name) VALUES (1, 5, 'Plain'), (2, 5, 'Tour')").run();
db.prepare("INSERT INTO tours (place_id, tour_type) VALUES (2, 'hike')").run();
await insertRows(orm, Places, [{ id: 1, trip: 5, name: 'Plain' }, { id: 2, trip: 5, name: 'Tour' }]);
await makeTour(orm, 2, { tourTypeRef: 'hike' });
const all = await request(server).get('/api/trips/5/places').set('Cookie', sessionCookie(1));
expect(all.status).toBe(200);
@@ -129,8 +143,8 @@ describe('Places e2e (real auth guard + temp SQLite)', () => {
});
it('200 list scoped to the trip', async () => {
db.prepare("INSERT INTO places (trip_id, name) VALUES (5, 'Mine')").run();
db.prepare("INSERT INTO places (trip_id, name) VALUES (6, 'Theirs')").run();
await insertRow(orm, Places, { trip: 5, name: 'Mine' });
await insertRow(orm, Places, { trip: 6, name: 'Theirs' });
const res = await request(server).get('/api/trips/5/places').set('Cookie', sessionCookie(1));
expect(res.body.places.map((p: { name: string }) => p.name)).toEqual(['Mine']);
});
@@ -140,7 +154,7 @@ describe('Places e2e (real auth guard + temp SQLite)', () => {
expect(ok.status).toBe(201);
expect(ok.body.place).toMatchObject({ name: 'Spot', trip_id: 5, transport_mode: 'walking', duration_minutes: 60 });
// The row really landed.
expect(db.prepare('SELECT COUNT(*) AS n FROM places WHERE trip_id = 5').get()).toEqual({ n: 1 });
expect(await countRows(orm, Places, { trip: 5 })).toBe(1);
const long = await request(server).post('/api/trips/5/places').set('Cookie', sessionCookie(1)).send({ name: 'x'.repeat(201) });
expect(long.status).toBe(400);
@@ -152,13 +166,13 @@ describe('Places e2e (real auth guard + temp SQLite)', () => {
});
it('200 (not 201) bulk-delete, 400 on bad ids', async () => {
db.prepare("INSERT INTO places (id, trip_id, name) VALUES (1, 5, 'A'), (2, 5, 'B')").run();
db.prepare("INSERT INTO places (id, trip_id, name) VALUES (3, 6, 'Foreign')").run();
await insertRows(orm, Places, [{ id: 1, trip: 5, name: 'A' }, { id: 2, trip: 5, name: 'B' }]);
await insertRow(orm, Places, { id: 3, trip: 6, name: 'Foreign' });
const ok = await request(server).post('/api/trips/5/places/bulk-delete').set('Cookie', sessionCookie(1)).send({ ids: [1, 2, 3] });
expect(ok.status).toBe(200);
expect(ok.body).toEqual({ deleted: [1, 2], count: 2, tourPlaceIds: [] });
// The foreign trip's place is untouched.
expect(db.prepare('SELECT id FROM places ORDER BY id').all()).toEqual([{ id: 3 }]);
expect((await findRows(orm, Places, {}, { id: 'asc' })).map(p => ({ id: p.id }))).toEqual([{ id: 3 }]);
// The ZodValidationPipe owns this 400 since the DTO ratchet — the legacy
// 'ids must be an array of numbers' string is gone.
@@ -178,7 +192,7 @@ describe('Places e2e (real auth guard + temp SQLite)', () => {
// And it fires ahead of the trip-access 404 it used to follow (documented
// parity shift of the ratchet — the todo/trips precedent).
db.prepare('DELETE FROM trips WHERE id = 5').run();
await deleteRows(orm, Trips, { id: 5 });
const noTrip = await request(server).post('/api/trips/5/places').set('Cookie', sessionCookie(1)).send({});
expect(noTrip.status).toBe(400);
});
@@ -207,7 +221,7 @@ describe('Places e2e (real auth guard + temp SQLite)', () => {
});
it('PUT route_color: hex through, null through, garbage rejected (#776)', async () => {
db.prepare("INSERT INTO places (id, trip_id, name) VALUES (9, 5, 'Walk')").run();
await insertRow(orm, Places, { id: 9, trip: 5, name: 'Walk' });
const ok = await request(server).put('/api/trips/5/places/9').set('Cookie', sessionCookie(1)).send({ route_color: '#e11d48' });
expect(ok.status).toBe(200);
@@ -234,7 +248,7 @@ describe('Places e2e (real auth guard + temp SQLite)', () => {
const updated = await request(server).put(`/api/trips/5/places/${id}`).set('Cookie', sessionCookie(1))
.send({ website: '//www.example.fr/patrimoine' });
expect(updated.status).toBe(200);
expect(db.prepare('SELECT website FROM places WHERE id = ?').get(id)).toEqual({ website: 'https://www.example.fr/patrimoine' });
expect((await findRow(orm, Places, { id }))!.website).toBe('https://www.example.fr/patrimoine');
// An explicit scheme is stored exactly as sent, and '' still clears the field.
const kept = await request(server).put(`/api/trips/5/places/${id}`).set('Cookie', sessionCookie(1))
@@ -250,11 +264,11 @@ describe('Places e2e (real auth guard + temp SQLite)', () => {
expect(res.status).toBe(400);
expect(res.body).toEqual({ error: 'website must be an http or https URL' });
}
expect(db.prepare('SELECT COUNT(*) AS n FROM places WHERE trip_id = 5').get()).toEqual({ n: 0 });
expect(await countRows(orm, Places, { trip: 5 })).toBe(0);
});
it('409 on a stale If-Match token (#1135)', async () => {
db.prepare("INSERT INTO places (id, trip_id, name, updated_at) VALUES (9, 5, 'Walk', '2026-01-01 00:00:00')").run();
await insertRow(orm, Places, { id: 9, trip: 5, name: 'Walk', updated_at: '2026-01-01 00:00:00' });
const res = await request(server)
.put('/api/trips/5/places/9')
.set('Cookie', sessionCookie(1))
@@ -262,29 +276,29 @@ describe('Places e2e (real auth guard + temp SQLite)', () => {
.send({ name: 'Mine' });
expect(res.status).toBe(409);
expect(res.body.error).toBe('conflict');
expect(db.prepare('SELECT name FROM places WHERE id = 9').get()).toEqual({ name: 'Walk' });
expect((await findRow(orm, Places, { id: 9 }))!.name).toBe('Walk');
});
it('PUT/DELETE :id/rating stores and clears the caller\'s vote', async () => {
db.prepare("INSERT INTO places (id, trip_id, name) VALUES (9, 5, 'Rated')").run();
await insertRow(orm, Places, { id: 9, trip: 5, name: 'Rated' });
const rated = await request(server).put('/api/trips/5/places/9/rating').set('Cookie', sessionCookie(1)).send({ rating: 4 });
expect(rated.status).toBe(200);
expect(db.prepare('SELECT user_id, rating FROM place_ratings WHERE place_id = 9').all()).toEqual([{ user_id: 1, rating: 4 }]);
expect((await findRows(orm, PlaceRatings, { place: 9 }, { id: 'asc' })).map(r => ({ user_id: r.user_id, rating: r.rating }))).toEqual([{ user_id: 1, rating: 4 }]);
const cleared = await request(server).delete('/api/trips/5/places/9/rating').set('Cookie', sessionCookie(1));
expect(cleared.status).toBe(200);
expect(db.prepare('SELECT COUNT(*) AS n FROM place_ratings WHERE place_id = 9').get()).toEqual({ n: 0 });
expect(await countRows(orm, PlaceRatings, { place: 9 })).toBe(0);
});
it('DELETE :id removes the row, 404 for a foreign place', async () => {
db.prepare("INSERT INTO places (id, trip_id, name) VALUES (9, 5, 'Gone')").run();
db.prepare("INSERT INTO places (id, trip_id, name) VALUES (10, 6, 'Foreign')").run();
await insertRow(orm, Places, { id: 9, trip: 5, name: 'Gone' });
await insertRow(orm, Places, { id: 10, trip: 6, name: 'Foreign' });
const ok = await request(server).delete('/api/trips/5/places/9').set('Cookie', sessionCookie(1));
expect(ok.status).toBe(200);
expect(ok.body).toEqual({ success: true, tourPlaceIds: [] });
expect(db.prepare('SELECT id FROM places WHERE id = 9').get()).toBeUndefined();
expect(await findRow(orm, Places, { id: 9 })).toBeNull();
const foreign = await request(server).delete('/api/trips/5/places/10').set('Cookie', sessionCookie(1));
expect(foreign.status).toBe(404);
@@ -292,13 +306,18 @@ describe('Places e2e (real auth guard + temp SQLite)', () => {
});
it('DELETE :id and bulk-delete report the Tour place ids they removed', async () => {
db.prepare("INSERT INTO places (id, trip_id, name) VALUES (20, 5, 'Tour A'), (21, 5, 'Tour B'), (22, 5, 'Plain')").run();
db.prepare("INSERT INTO tours (place_id, tour_type) VALUES (20, 'hike'), (21, 'hike')").run();
await insertRows(orm, Places, [
{ id: 20, trip: 5, name: 'Tour A' },
{ id: 21, trip: 5, name: 'Tour B' },
{ id: 22, trip: 5, name: 'Plain' },
]);
await makeTour(orm, 20, { tourTypeRef: 'hike' });
await makeTour(orm, 21, { tourTypeRef: 'hike' });
const single = await request(server).delete('/api/trips/5/places/20').set('Cookie', sessionCookie(1));
expect(single.status).toBe(200);
expect(single.body).toEqual({ success: true, tourPlaceIds: [20] });
expect(db.prepare('SELECT place_id FROM tours WHERE place_id = 20').get()).toBeUndefined();
expect(await findRow(orm, Tours, { place: 20 })).toBeNull();
const bulk = await request(server).post('/api/trips/5/places/bulk-delete').set('Cookie', sessionCookie(1)).send({ ids: [21, 22] });
expect(bulk.status).toBe(200);
@@ -306,22 +325,22 @@ describe('Places e2e (real auth guard + temp SQLite)', () => {
});
it('DELETE :id takes the expense linked to the place with it (#1298)', async () => {
db.prepare("INSERT INTO places (id, trip_id, name) VALUES (12, 5, 'Louvre')").run();
db.prepare("INSERT INTO budget_items (id, trip_id, name, total_price, place_id) VALUES (44, 5, 'Tickets', 34, 12)").run();
db.prepare("INSERT INTO budget_items (id, trip_id, name, total_price) VALUES (45, 5, 'Coffee', 3)").run();
await insertRow(orm, Places, { id: 12, trip: 5, name: 'Louvre' });
await insertRow(orm, BudgetItems, { id: 44, trip: 5, name: 'Tickets', total_price: 34, place: 12 });
await insertRow(orm, BudgetItems, { id: 45, trip: 5, name: 'Coffee', total_price: 3 });
const res = await request(server).delete('/api/trips/5/places/12').set('Cookie', sessionCookie(1));
expect(res.status).toBe(200);
expect(db.prepare('SELECT id FROM budget_items ORDER BY id').all()).toEqual([{ id: 45 }]);
expect((await findRows(orm, BudgetItems, {}, { id: 'asc' })).map(b => ({ id: b.id }))).toEqual([{ id: 45 }]);
});
it('DELETE :id tells the deleting tab about the expense that went with the place', async () => {
// X-Socket-Id keeps a tab from hearing back what it did itself. The tab
// removed the place; the expense went on the server alone, so that event
// goes out without the filter or the tab keeps the expense until a reload.
db.prepare("INSERT INTO places (id, trip_id, name) VALUES (13, 5, 'Louvre')").run();
db.prepare("INSERT INTO budget_items (id, trip_id, name, total_price, place_id) VALUES (46, 5, 'Tickets', 34, 13)").run();
await insertRow(orm, Places, { id: 13, trip: 5, name: 'Louvre' });
await insertRow(orm, BudgetItems, { id: 46, trip: 5, name: 'Tickets', total_price: 34, place: 13 });
vi.mocked(broadcast).mockClear();
const res = await request(server).delete('/api/trips/5/places/13')
@@ -333,7 +352,7 @@ describe('Places e2e (real auth guard + temp SQLite)', () => {
});
it('404 trip when not accessible', async () => {
db.prepare('DELETE FROM trips WHERE id = 5').run();
await deleteRows(orm, Trips, { id: 5 });
const res = await request(server).get('/api/trips/5/places').set('Cookie', sessionCookie(1));
expect(res.status).toBe(404);
expect(res.body).toEqual({ error: 'Trip not found' });
@@ -344,18 +363,18 @@ describe('Places e2e (real auth guard + temp SQLite)', () => {
// the status, so a check that happens to return the right code for the wrong
// reason still fails.
it('DELETE :id demands place_edit, by name', async () => {
db.prepare("INSERT INTO places (id, trip_id, name) VALUES (11, 5, 'Guarded')").run();
await insertRow(orm, Places, { id: 11, trip: 5, name: 'Guarded' });
checkPermission.mockReturnValue(false);
const res = await request(server).delete('/api/trips/5/places/11').set('Cookie', sessionCookie(1));
expect(res.status).toBe(403);
expect(res.body).toEqual({ error: 'No permission' });
expect(checkPermission).toHaveBeenCalledWith('place_edit', 'user', 1, 1, false);
expect(db.prepare('SELECT id FROM places WHERE id = 11').get()).toBeDefined();
expect(await findRow(orm, Places, { id: 11 })).not.toBeNull();
});
it('the guarded read routes 404 an inaccessible trip without touching the place', async () => {
db.prepare('DELETE FROM trips WHERE id = 5').run();
await deleteRows(orm, Trips, { id: 5 });
for (const path of ['/api/trips/5/places/9', '/api/trips/5/places/9/image']) {
const res = await request(server).get(path).set('Cookie', sessionCookie(1));
expect(res.status).toBe(404);
@@ -368,16 +387,19 @@ describe('Places e2e (real auth guard + temp SQLite)', () => {
// ── GPX export ────────────────────────────────────────────────────────────
describe('GET export.gpx (#1442)', () => {
const seedTrip = () => {
db.prepare("INSERT OR REPLACE INTO trips (id, title, user_id) VALUES (5, 'Alpine week', 1)").run();
db.prepare("INSERT INTO places (id, trip_id, name, lat, lng) VALUES (1, 5, 'Trailhead', 47.1, 11.2)").run();
db.prepare("INSERT INTO places (id, trip_id, name, lat, lng, route_geometry) VALUES (2, 5, 'Ridge', 47.2, 11.3, '[[47.2,11.3],[47.25,11.35]]')").run();
db.prepare("INSERT INTO days (id, trip_id, day_number, date, title) VALUES (1, 5, 1, '2026-05-01', 'Warm up')").run();
db.prepare('INSERT INTO day_assignments (day_id, place_id, order_index) VALUES (1, 1, 0), (1, 2, 1)').run();
const seedTrip = 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 });
await insertRow(orm, Places, { id: 2, trip: 5, name: 'Ridge', lat: 47.2, lng: 11.3, route_geometry: '[[47.2,11.3],[47.25,11.35]]' });
await insertRow(orm, Days, { id: 1, trip: 5, day_number: 1, date: '2026-05-01', title: 'Warm up' });
await insertRows(orm, DayAssignments, [
{ day: 1, place: 1, order_index: 0 },
{ day: 1, place: 2, order_index: 1 },
]);
};
it('serves the trip as an attachment named after it', async () => {
seedTrip();
await seedTrip();
const res = await request(server).get('/api/trips/5/places/export.gpx').set('Cookie', sessionCookie(1));
expect(res.status).toBe(200);
@@ -393,8 +415,8 @@ describe('Places e2e (real auth guard + temp SQLite)', () => {
// ERR_INVALID_CHAR before the first body byte. Now the header folds to
// ASCII and carries the real name RFC 5987-encoded.
it('a non-ASCII trip title exports 200 with a filename* header instead of a 500 (#2165)', async () => {
db.prepare('INSERT OR REPLACE INTO trips (id, title, user_id) VALUES (5, ?, 1)').run('沖縄 4泊5日');
db.prepare('INSERT INTO places (id, trip_id, name, lat, lng) VALUES (1, 5, ?, 26.217, 127.719)').run('首里城');
await upsertRow(orm, Trips, { id: 5, title: '沖縄 4泊5日', user: 1 });
await insertRow(orm, Places, { id: 1, trip: 5, name: '首里城', lat: 26.217, lng: 127.719 });
const res = await request(server).get('/api/trips/5/places/export.gpx').set('Cookie', sessionCookie(1));
expect(res.status).toBe(200);
@@ -405,7 +427,7 @@ describe('Places e2e (real auth guard + temp SQLite)', () => {
});
it('narrows the document to the requested parts', async () => {
seedTrip();
await seedTrip();
const res = await request(server)
.get('/api/trips/5/places/export.gpx?waypoints=false&dayRoutes=false')
.set('Cookie', sessionCookie(1));
@@ -417,7 +439,7 @@ describe('Places e2e (real auth guard + temp SQLite)', () => {
});
it('400s when every part was switched off', async () => {
seedTrip();
await seedTrip();
const res = await request(server)
.get('/api/trips/5/places/export.gpx?waypoints=false&tracks=false&dayRoutes=false')
.set('Cookie', sessionCookie(1));
@@ -427,15 +449,15 @@ describe('Places e2e (real auth guard + temp SQLite)', () => {
});
it('404s an empty trip rather than handing over a file that imports as nothing', async () => {
db.prepare("INSERT OR REPLACE INTO trips (id, title, user_id) VALUES (5, 'Nothing here', 1)").run();
await upsertRow(orm, Trips, { id: 5, title: 'Nothing here', user: 1 });
const res = await request(server).get('/api/trips/5/places/export.gpx').set('Cookie', sessionCookie(1));
expect(res.status).toBe(404);
expect(res.body).toEqual({ error: 'Nothing to export' });
});
it('404s a trip the caller cannot reach, and 401s without a cookie', async () => {
seedTrip();
db.prepare('DELETE FROM trips WHERE id = 5').run();
await seedTrip();
await deleteRows(orm, Trips, { id: 5 });
const res = await request(server).get('/api/trips/5/places/export.gpx').set('Cookie', sessionCookie(1));
expect(res.status).toBe(404);
expect(res.body).toEqual({ error: 'Trip not found' });
@@ -444,7 +466,7 @@ describe('Places e2e (real auth guard + temp SQLite)', () => {
});
it('is a read: no place_edit permission required', async () => {
seedTrip();
await seedTrip();
checkPermission.mockReturnValue(false);
const res = await request(server).get('/api/trips/5/places/export.gpx').set('Cookie', sessionCookie(1));
expect(res.status).toBe(200);
@@ -455,7 +477,7 @@ describe('Places e2e (real auth guard + temp SQLite)', () => {
// 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.
it('a bad create body still 400s ahead of the trip 404', async () => {
db.prepare('DELETE FROM trips WHERE id = 5').run();
await deleteRows(orm, Trips, { id: 5 });
const res = await request(server).post('/api/trips/5/places').set('Cookie', sessionCookie(1)).send({});
expect(res.status).toBe(400);
});
+7 -4
View File
@@ -43,7 +43,10 @@ vi.mock('../../src/nest/plugins/kill-switch', () => ({ pluginsEnabled: () => plu
import { db } from '../../src/db/database';
import { TestUnitOfWorkModule } from '../helpers/test-uow';
import { createTestMikroOrmModule } from '../helpers/test-orm';
import { createTestMikroOrmModule, createTestOrm, type TestOrm } from '../helpers/test-orm';
import { makeUser } from '../helpers/factories/users';
let orm: TestOrm;
const place = (id: string, name: string) => ({ id, name, lat: 35.66, lng: 139.7, address: 'Shibuya', rating: 4.4 });
@@ -70,9 +73,8 @@ describe('Plugin search e2e (real guard chain + temp SQLite)', () => {
// harness.ts's seedUser() omits password_hash, which the migrated schema
// requires NOT NULL (addons.e2e.test.ts does the same) — the same SeededUser
// shape sessionCookie(1) needs, with the hash filled in.
db.prepare(
"INSERT INTO users (id, username, email, password_hash, role, password_version) VALUES (1, 'e2e-user', 'e2e@example.test', 'x', 'user', 0)",
).run();
orm = await createTestOrm(db);
await makeUser(orm, { id: 1, username: 'e2e-user', email: 'e2e@example.test' });
app = await build();
const hooks = app.get(PluginHooks, { strict: false });
providersOf = vi.spyOn(hooks, 'providersOf');
@@ -95,6 +97,7 @@ describe('Plugin search e2e (real guard chain + temp SQLite)', () => {
afterAll(async () => {
await app?.close();
await orm?.close();
});
const cookie = () => sessionCookie(1);
+83 -133
View File
@@ -1,5 +1,7 @@
/**
* Public API v1 e2e — the real ApiTokenGuard and real SQL against a temp SQLite db.
* Public API v1 e2e — the real ApiTokenGuard and real SQL against a migrated temp
* SQLite db (createSnapshotTestDb()), seeded and read through the factories in
* tests/helpers/factories.
*
* The unit tests pin the shaping; this one exists for the question a mock cannot
* answer: does a token actually only reach its owner's trips? Two users, two trips,
@@ -11,73 +13,13 @@ import { describe, it, expect, beforeAll, afterAll, vi } from 'vitest';
import request from 'supertest';
import type { Server } from 'http';
import { Test } from '@nestjs/testing';
import { createHash } from 'crypto';
const { db } = vi.hoisted(() => {
// eslint-disable-next-line @typescript-eslint/no-require-imports
const Database = require('better-sqlite3');
const tmp = new Database(':memory:');
tmp.exec('PRAGMA journal_mode = WAL');
tmp.exec(`
CREATE TABLE users (id INTEGER PRIMARY KEY AUTOINCREMENT, username TEXT NOT NULL,
email TEXT NOT NULL UNIQUE, role TEXT NOT NULL DEFAULT 'user', password_version INTEGER NOT NULL DEFAULT 0);
-- scope_mode/api_scopes are spelled exactly as the scopes migration adds
-- them (NOT NULL DEFAULT 'all', and a nullable JSON list): a row here has to
-- be able to be the row the guard reads in production, or the scope cases
-- below would be passing against a table that does not exist anywhere else.
CREATE TABLE mcp_tokens (id INTEGER PRIMARY KEY AUTOINCREMENT, user_id INTEGER NOT NULL,
name TEXT NOT NULL, token_hash TEXT NOT NULL, token_prefix TEXT NOT NULL,
created_at DATETIME DEFAULT CURRENT_TIMESTAMP, last_used_at DATETIME,
kind TEXT NOT NULL DEFAULT 'mcp',
scope_mode TEXT NOT NULL DEFAULT 'all', api_scopes TEXT);
CREATE TABLE trips (id INTEGER PRIMARY KEY AUTOINCREMENT, user_id INTEGER NOT NULL,
title TEXT NOT NULL, description TEXT, start_date TEXT, end_date TEXT, currency TEXT,
is_archived INTEGER DEFAULT 0, created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
updated_at DATETIME DEFAULT CURRENT_TIMESTAMP);
CREATE TABLE trip_members (trip_id INTEGER NOT NULL, user_id INTEGER NOT NULL);
CREATE TABLE days (id INTEGER PRIMARY KEY AUTOINCREMENT, trip_id INTEGER NOT NULL,
day_number INTEGER NOT NULL, date TEXT NOT NULL, notes TEXT, title TEXT);
CREATE TABLE places (id INTEGER PRIMARY KEY AUTOINCREMENT, trip_id INTEGER NOT NULL,
name TEXT NOT NULL, address TEXT, lat REAL, lng REAL, category_id INTEGER,
place_time TEXT, end_time TEXT, duration_minutes INTEGER, notes TEXT, transport_mode TEXT,
created_at DATETIME DEFAULT CURRENT_TIMESTAMP);
CREATE TABLE categories (id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT NOT NULL);
CREATE TABLE day_assignments (id INTEGER PRIMARY KEY AUTOINCREMENT, day_id INTEGER NOT NULL,
place_id INTEGER NOT NULL, order_index INTEGER NOT NULL DEFAULT 0, accommodation_id INTEGER);
CREATE TABLE day_notes (id INTEGER PRIMARY KEY AUTOINCREMENT, day_id INTEGER NOT NULL,
trip_id INTEGER NOT NULL, text TEXT NOT NULL, time TEXT, icon TEXT, sort_order REAL DEFAULT 0);
CREATE TABLE day_accommodations (id INTEGER PRIMARY KEY AUTOINCREMENT, trip_id INTEGER NOT NULL,
place_id INTEGER, start_day_id INTEGER, end_day_id INTEGER, check_in TEXT, check_in_end TEXT,
check_out TEXT, confirmation TEXT, notes TEXT);
CREATE TABLE reservations (id INTEGER PRIMARY KEY AUTOINCREMENT, trip_id INTEGER NOT NULL,
day_id INTEGER, end_day_id INTEGER, place_id INTEGER, assignment_id INTEGER, title TEXT,
accommodation_id TEXT, reservation_time TEXT, reservation_end_time TEXT, location TEXT,
confirmation_number TEXT, notes TEXT, status TEXT, type TEXT);
CREATE TABLE bucket_list (id INTEGER PRIMARY KEY AUTOINCREMENT, user_id INTEGER NOT NULL,
name TEXT NOT NULL, lat REAL, lng REAL, country_code TEXT, notes TEXT,
target_date TEXT, created_at DATETIME DEFAULT CURRENT_TIMESTAMP);
`);
return { db: tmp };
});
vi.mock('../../src/db/database', async (importActual) => {
const actual = await importActual<typeof import('../../src/db/database')>();
return {
...actual,
db,
closeDb: () => {},
reinitialize: () => {},
canAccessTrip: (tripId: number | string, userId: number) =>
db
.prepare(
`SELECT t.id, t.user_id, t.currency FROM trips t
LEFT JOIN trip_members m ON m.trip_id = t.id AND m.user_id = ?
WHERE t.id = ? AND (t.user_id = ? OR m.user_id IS NOT NULL)`,
)
.get(userId, tripId, userId),
};
vi.mock('../../src/db/database', async () => {
const { createSnapshotTestDb, buildDbMock } = await import('../helpers/db-mock');
return buildDbMock(createSnapshotTestDb());
});
import { db } from '../../src/db/database';
import { RateLimitModule } from '../../src/nest/common/rate-limit.module';
import { PublicApiModule } from '../../src/nest/public-api/public-api.module';
import { ApiTokenGuard } from '../../src/nest/public-api/api-token.guard';
@@ -86,17 +28,27 @@ import { PublicStatsController } from '../../src/nest/atlas/public-stats.control
import { AtlasService } from '../../src/nest/atlas/atlas.service';
import { TrekExceptionFilter } from '../../src/nest/common/trek-exception.filter';
import { TestUnitOfWorkModule } from '../helpers/test-uow';
import { createTestMikroOrmModule } from '../helpers/test-orm';
import { createTestMikroOrmModule, createTestOrm, type TestOrm } from '../helpers/test-orm';
import { makeUser } from '../helpers/factories/users';
import { addTripMember } from '../helpers/factories/trips';
import { makeCategory } from '../helpers/factories/places';
import { makeMcpToken } from '../helpers/factories/tokens';
import { makeBucketListItem } from '../helpers/factories/atlas';
import { findRow, insertRow } from '../helpers/factories/rows';
import { DayAccommodations } from '../../src/db/entities/DayAccommodations.entity';
import { DayAssignments } from '../../src/db/entities/DayAssignments.entity';
import { DayNotes } from '../../src/db/entities/DayNotes.entity';
import { Days } from '../../src/db/entities/Days.entity';
import { McpTokens } from '../../src/db/entities/McpTokens.entity';
import { Places } from '../../src/db/entities/Places.entity';
import { Reservations } from '../../src/db/entities/Reservations.entity';
import { Trips } from '../../src/db/entities/Trips.entity';
let orm: TestOrm;
/** Mints a token the way TokenService does, so the guard's hash lookup is real. */
function seedToken(userId: number, raw: string, kind: 'api' | 'mcp' = 'api'): string {
db.prepare('INSERT INTO mcp_tokens (user_id, name, token_hash, token_prefix, kind) VALUES (?, ?, ?, ?, ?)').run(
userId,
'test',
createHash('sha256').update(raw).digest('hex'),
raw.slice(0, 13),
kind,
);
async function seedToken(userId: number, raw: string, kind: 'api' | 'mcp' = 'api'): Promise<string> {
await makeMcpToken(orm, userId, { rawToken: raw, name: 'test', token_prefix: raw.slice(0, 13), kind });
return raw;
}
@@ -105,18 +57,15 @@ function seedToken(userId: number, raw: string, kind: 'api' | 'mcp' = 'api'): st
* the deliberately unparseable value one case needs, which is why this takes a
* string rather than an array.
*/
function seedLimitedToken(userId: number, raw: string, rawScopes: string): string {
db.prepare(
'INSERT INTO mcp_tokens (user_id, name, token_hash, token_prefix, kind, scope_mode, api_scopes) VALUES (?, ?, ?, ?, ?, ?, ?)',
).run(
userId,
'test-limited',
createHash('sha256').update(raw).digest('hex'),
raw.slice(0, 13),
'api',
'limited',
rawScopes,
);
async function seedLimitedToken(userId: number, raw: string, rawScopes: string): Promise<string> {
await makeMcpToken(orm, userId, {
rawToken: raw,
name: 'test-limited',
token_prefix: raw.slice(0, 13),
kind: 'api',
scope_mode: 'limited',
api_scopes: rawScopes,
});
return raw;
}
@@ -171,55 +120,60 @@ describe('Public API v1 e2e (real guard + real SQL)', () => {
}
beforeAll(async () => {
db.prepare("INSERT INTO users (id, username, email) VALUES (1, 'ada', 'ada@example.com')").run();
db.prepare("INSERT INTO users (id, username, email) VALUES (2, 'bob', 'bob@example.com')").run();
seedToken(1, ADA_TOKEN);
seedToken(2, BOB_TOKEN);
seedToken(1, MCP_TOKEN, 'mcp');
orm = await createTestOrm(db);
await makeUser(orm, { id: 1, username: 'ada', email: 'ada@example.com' });
await makeUser(orm, { id: 2, username: 'bob', email: 'bob@example.com' });
await seedToken(1, ADA_TOKEN);
await seedToken(2, BOB_TOKEN);
await seedToken(1, MCP_TOKEN, 'mcp');
// ADA_TOKEN above is seeded without ever naming the two scope columns — the
// row a key minted before the feature existed leaves behind. It is the
// backwards-compatibility case and every existing test in this file rides on
// it, so if narrowing ever leaks into the default those tests fail first.
seedLimitedToken(1, TRIPS_ONLY_TOKEN, JSON.stringify(['trips']));
seedLimitedToken(1, TRIPS_DAYS_TOKEN, JSON.stringify(['trips', 'days', 'notes']));
seedLimitedToken(1, TRIPS_PLACES_TOKEN, JSON.stringify(['trips', 'places']));
seedLimitedToken(1, BROKEN_SCOPES_TOKEN, '{"not":"a list"');
await seedLimitedToken(1, TRIPS_ONLY_TOKEN, JSON.stringify(['trips']));
await seedLimitedToken(1, TRIPS_DAYS_TOKEN, JSON.stringify(['trips', 'days', 'notes']));
await seedLimitedToken(1, TRIPS_PLACES_TOKEN, JSON.stringify(['trips', 'places']));
await seedLimitedToken(1, BROKEN_SCOPES_TOKEN, '{"not":"a list"');
// Ada owns trip 1; Bob owns trip 2; trip 3 is Bob's but Ada is a member.
db.prepare(
"INSERT INTO trips (id, user_id, title, description, start_date, end_date, currency) VALUES (1, 1, 'Toskana', 'Wein', '2026-06-14', '2026-06-16', 'EUR')",
).run();
db.prepare("INSERT INTO trips (id, user_id, title, start_date) VALUES (2, 2, 'Bobs Secret', '2026-07-01')").run();
db.prepare("INSERT INTO trips (id, user_id, title, start_date) VALUES (3, 2, 'Shared', '2026-08-01')").run();
db.prepare('INSERT INTO trip_members (trip_id, user_id) VALUES (3, 1)').run();
await insertRow(orm, Trips, {
id: 1, user: 1, title: 'Toskana', description: 'Wein', start_date: '2026-06-14', end_date: '2026-06-16', currency: 'EUR',
});
await insertRow(orm, Trips, { id: 2, user: 2, title: 'Bobs Secret', start_date: '2026-07-01' });
await insertRow(orm, Trips, { id: 3, user: 2, title: 'Shared', start_date: '2026-08-01' });
await addTripMember(orm, 3, 1);
db.prepare("INSERT INTO days (id, trip_id, day_number, date, title, notes) VALUES (1, 1, 1, '2026-06-14', 'Ankunft', 'Schlüssel beim Nachbarn abholen')").run();
db.prepare("INSERT INTO days (id, trip_id, day_number, date) VALUES (2, 1, 2, '2026-06-15')").run();
db.prepare("INSERT INTO categories (id, name) VALUES (1, 'Museum')").run();
db.prepare(
"INSERT INTO places (id, trip_id, name, address, lat, lng, category_id, place_time, duration_minutes, transport_mode) VALUES (1, 1, 'Uffizien', 'Firenze', 43.76, 11.25, 1, '14:00', 180, 'walking')",
).run();
db.prepare("INSERT INTO places (id, trip_id, name, lat, lng) VALUES (2, 1, 'Ponte Vecchio', 43.76, 11.24)").run();
db.prepare("INSERT INTO places (id, trip_id, name) VALUES (3, 1, 'Hotel Alba')").run();
await insertRow(orm, Days, { id: 1, trip: 1, day_number: 1, date: '2026-06-14', title: 'Ankunft', notes: 'Schlüssel beim Nachbarn abholen' });
await insertRow(orm, Days, { id: 2, trip: 1, day_number: 2, date: '2026-06-15' });
// The migrated database ships with its seeded categories, so this one takes the next free id.
const museum = await makeCategory(orm, { name: 'Museum' });
await insertRow(orm, Places, {
id: 1, trip: 1, name: 'Uffizien', address: 'Firenze', lat: 43.76, lng: 11.25, category: museum.id,
place_time: '14:00', duration_minutes: 180, transport_mode: 'walking',
});
await insertRow(orm, Places, { id: 2, trip: 1, name: 'Ponte Vecchio', lat: 43.76, lng: 11.24 });
await insertRow(orm, Places, { id: 3, trip: 1, name: 'Hotel Alba' });
// Deliberately inserted out of order to prove order_index decides the sequence.
db.prepare('INSERT INTO day_assignments (day_id, place_id, order_index) VALUES (1, 2, 1)').run();
await insertRow(orm, DayAssignments, { day: 1, place: 2, order_index: 1 });
// Ein Ort auf der Shortlist: Koordinaten, aber noch kein Tag.
db.prepare("INSERT INTO places (id, trip_id, name, lat, lng, notes) VALUES (4, 1, 'Boboli-Garten', 43.762, 11.248, 'vielleicht')").run();
await insertRow(orm, Places, { id: 4, trip: 1, name: 'Boboli-Garten', lat: 43.762, lng: 11.248, notes: 'vielleicht' });
// Eine Buchung, die keinen Tag (mehr) hat.
db.prepare("INSERT INTO reservations (trip_id, day_id, type, title, location, reservation_time, status) VALUES (1, NULL, 'flight', 'LH 1234', 'FRA', '2026-06-14T08:00', 'confirmed')").run();
db.prepare("INSERT INTO bucket_list (user_id, name, lat, lng, country_code, notes, target_date) VALUES (1, 'Hokkaido', 43.06, 141.35, 'JP', 'im Winter', '2027-02-01')").run();
db.prepare("INSERT INTO bucket_list (user_id, name, lat, lng) VALUES (2, 'Bobs Traumziel', 1.0, 2.0)").run();
db.prepare('INSERT INTO day_assignments (day_id, place_id, order_index) VALUES (1, 1, 0)').run();
db.prepare("INSERT INTO day_notes (day_id, trip_id, text, time, sort_order) VALUES (1, 1, 'Tickets mitnehmen', '09:00', 0)").run();
db.prepare(
"INSERT INTO reservations (trip_id, day_id, type, title, location, reservation_time, status) VALUES (1, 1, 'flight', 'LH 1234', 'FRA', '2026-06-14T08:00', 'confirmed')",
).run();
db.prepare(
"INSERT INTO day_accommodations (id, trip_id, place_id, start_day_id, end_day_id, check_in, check_out) VALUES (1, 1, 3, 1, 2, '15:00', '11:00')",
).run();
await insertRow(orm, Reservations, {
trip: 1, day: null, type: 'flight', title: 'LH 1234', location: 'FRA', reservation_time: '2026-06-14T08:00', status: 'confirmed',
});
await makeBucketListItem(orm, 1, { name: 'Hokkaido', lat: 43.06, lng: 141.35, country_code: 'JP', notes: 'im Winter', target_date: '2027-02-01' });
await makeBucketListItem(orm, 2, { name: 'Bobs Traumziel', lat: 1.0, lng: 2.0 });
await insertRow(orm, DayAssignments, { day: 1, place: 1, order_index: 0 });
await insertRow(orm, DayNotes, { day: 1, trip: 1, text: 'Tickets mitnehmen', time: '09:00', sort_order: 0 });
await insertRow(orm, Reservations, {
trip: 1, day: 1, type: 'flight', title: 'LH 1234', location: 'FRA', reservation_time: '2026-06-14T08:00', status: 'confirmed',
});
await insertRow(orm, DayAccommodations, {
id: 1, trip: 1, place: 3, startDay: 1, endDay: 2, check_in: '15:00', check_out: '11:00',
});
// The stop a booked night puts on its check-in day, so the route can reach the
// hotel. It belongs to the stay, not to the day's plan.
db.prepare('INSERT INTO day_assignments (day_id, place_id, order_index, accommodation_id) VALUES (1, 3, 2, 1)').run();
await insertRow(orm, DayAssignments, { day: 1, place: 3, order_index: 2, accommodation_id: 1 });
app = await build();
server = app.getHttpServer() as Server;
@@ -227,6 +181,7 @@ describe('Public API v1 e2e (real guard + real SQL)', () => {
afterAll(async () => {
await app?.close();
await orm?.close();
});
const get = (path: string, token?: string) => {
@@ -272,9 +227,7 @@ describe('Public API v1 e2e (real guard + real SQL)', () => {
it('records last_used_at so a stale token is visible in settings', async () => {
await get('/api/v1/trips', ADA_TOKEN);
const row = db.prepare('SELECT last_used_at FROM mcp_tokens WHERE user_id = 1').get() as {
last_used_at: string | null;
};
const row = (await findRow(orm, McpTokens, { user: 1, token_prefix: ADA_TOKEN.slice(0, 13) }))!;
expect(row.last_used_at).not.toBeNull();
});
});
@@ -471,10 +424,9 @@ describe('Public API v1 e2e (real guard + real SQL)', () => {
* keys that already exist is a promise.
*/
describe('read scopes', () => {
it('PUBAPI-SCOPE-001: a key minted before scopes existed is stored as a full grant', () => {
const row = db
.prepare('SELECT scope_mode, api_scopes FROM mcp_tokens WHERE token_prefix = ?')
.get(ADA_TOKEN.slice(0, 13)) as { scope_mode: string; api_scopes: string | null };
it('PUBAPI-SCOPE-001: a key minted before scopes existed is stored as a full grant', async () => {
const token = (await findRow(orm, McpTokens, { token_prefix: ADA_TOKEN.slice(0, 13) }))!;
const row = { scope_mode: token.scope_mode, api_scopes: token.api_scopes };
// The two columns were never named at insert time — exactly the row the
// ALTER leaves behind for a key that already existed.
expect(row).toEqual({ scope_mode: 'all', api_scopes: null });
@@ -642,9 +594,7 @@ describe('Public API v1 e2e (real guard + real SQL)', () => {
it('PUBAPI-SCOPE-013: a narrowed key is stamped as used like any other', async () => {
await get('/api/v1/trips', TRIPS_ONLY_TOKEN);
const row = db
.prepare('SELECT last_used_at FROM mcp_tokens WHERE token_prefix = ?')
.get(TRIPS_ONLY_TOKEN.slice(0, 13)) as { last_used_at: string | null };
const row = (await findRow(orm, McpTokens, { token_prefix: TRIPS_ONLY_TOKEN.slice(0, 13) }))!;
expect(row.last_used_at).not.toBeNull();
});
});
+81 -49
View File
@@ -50,7 +50,38 @@ let checkPermission: MockInstance;
import { db } from '../../src/db/database';
import { NotificationsService } from '../../src/nest/notifications/notifications.service';
import { TestUnitOfWorkModule } from '../helpers/test-uow';
import { createTestMikroOrmModule } from '../helpers/test-orm';
import { createTestMikroOrmModule, createTestOrm, type TestOrm } from '../helpers/test-orm';
import { makeUser } from '../helpers/factories/users';
import { makeTrip, makeDay } from '../helpers/factories/trips';
import { countRows, deleteRows, findRow, findRows, insertRow, insertRowIgnoringConflict } from '../helpers/factories/rows';
import { BudgetItems } from '../../src/db/entities/BudgetItems.entity';
import { DayAccommodations } from '../../src/db/entities/DayAccommodations.entity';
import { DayAssignments } from '../../src/db/entities/DayAssignments.entity';
import { Places } from '../../src/db/entities/Places.entity';
import { ReservationDayPositions } from '../../src/db/entities/ReservationDayPositions.entity';
import { Reservations } from '../../src/db/entities/Reservations.entity';
import { Trips } from '../../src/db/entities/Trips.entity';
import { Users } from '../../src/db/entities/Users.entity';
let orm: TestOrm;
/** The expense booked with the reservation, as total, currency and frozen rate. */
async function bookedExpense(reservationId: number) {
const item = await findRow(orm, BudgetItems, { reservation: reservationId });
return item ? { total_price: item.total_price, currency: item.currency, exchange_rate: item.exchange_rate } : undefined;
}
function seedReservation(tripId: number, title: string, type: string, extra: { reservation_time?: string; accommodation_id?: string } = {}) {
return insertRow(orm, Reservations, { trip: tripId, title, type, ...extra });
}
function seedPlace(tripId: number, name: string) {
return insertRow(orm, Places, { trip: tripId, name });
}
async function seedDay(tripId: number, dayNumber: number, date: string) {
return (await makeDay(orm, tripId, { day_number: dayNumber, date })).id;
}
import { ExchangeRatesService } from '../../src/nest/budget/exchange-rates.service';
describe('Reservations + accommodations e2e (real auth guard + temp SQLite, real reservation SQL)', () => {
@@ -78,10 +109,9 @@ describe('Reservations + accommodations e2e (real auth guard + temp SQLite, real
beforeAll(async () => {
// The temp db carries the real schema (password_hash NOT NULL), so seed the
// auth user directly instead of via the trimmed-DDL seedUser helper.
db.prepare(
"INSERT INTO users (id, username, email, password_hash, role, password_version) VALUES (1, 'e2e-user', 'e2e@example.test', 'x', 'user', 0)",
).run();
tripId = Number(db.prepare("INSERT INTO trips (user_id, title) VALUES (1, 'E2E Trip')").run().lastInsertRowid);
orm = await createTestOrm(db);
await makeUser(orm, { id: 1, username: 'e2e-user', email: 'e2e@example.test' });
tripId = (await makeTrip(orm, 1, { title: 'E2E Trip' })).id;
app = await build();
checkPermission = vi.spyOn(app.get(PermissionsService), 'checkPermission');
server = app.getHttpServer();
@@ -94,6 +124,7 @@ describe('Reservations + accommodations e2e (real auth guard + temp SQLite, real
afterAll(async () => {
await app.close();
await orm.close();
});
it('401 without a cookie (reservations)', async () => {
@@ -101,7 +132,7 @@ describe('Reservations + accommodations e2e (real auth guard + temp SQLite, real
});
it('200 list reservations (real SQL, joins attached)', async () => {
const rid = db.prepare("INSERT INTO reservations (trip_id, title, type) VALUES (?, 'Hotel', 'hotel')").run(tripId).lastInsertRowid;
const rid = await seedReservation(tripId, 'Hotel', 'hotel');
const res = await request(server).get(`/api/trips/${tripId}/reservations`).set('Cookie', sessionCookie(1));
expect(res.status).toBe(200);
const row = res.body.reservations.find((r: { id: number }) => r.id === Number(rid));
@@ -113,8 +144,8 @@ describe('Reservations + accommodations e2e (real auth guard + temp SQLite, real
});
it('200 cross-trip upcoming reservations feed, without the hotels (#1934)', async () => {
db.prepare("INSERT INTO reservations (trip_id, title, type, reservation_time) VALUES (?, 'Flight', 'flight', '2999-01-01T10:00:00')").run(tripId);
db.prepare("INSERT INTO reservations (trip_id, title, type, reservation_time) VALUES (?, 'Stay', 'hotel', '2999-01-01T09:00:00')").run(tripId);
await seedReservation(tripId, 'Flight', 'flight', { reservation_time: '2999-01-01T10:00:00' });
await seedReservation(tripId, 'Stay', 'hotel', { reservation_time: '2999-01-01T09:00:00' });
const res = await request(server).get('/api/reservations/upcoming').set('Cookie', sessionCookie(1));
expect(res.status).toBe(200);
const titles = res.body.reservations.map((r: { title: string }) => r.title);
@@ -128,13 +159,13 @@ describe('Reservations + accommodations e2e (real auth guard + temp SQLite, real
// longer intercepts it. The trip row is seeded once in `beforeAll` (not
// re-seeded per test), so it is removed and restored around this one
// assertion instead.
db.prepare('DELETE FROM trips WHERE id = ?').run(tripId);
await deleteRows(orm, Trips, { id: tripId });
try {
const res = await request(server).get(`/api/trips/${tripId}/reservations`).set('Cookie', sessionCookie(1));
expect(res.status).toBe(404);
expect(res.body).toEqual({ error: 'Trip not found' });
} finally {
db.prepare("INSERT INTO trips (id, user_id, title) VALUES (?, 1, 'E2E Trip')").run(tripId);
await insertRow(orm, Trips, { id: tripId, user: 1, title: 'E2E Trip' });
}
});
@@ -149,7 +180,7 @@ describe('Reservations + accommodations e2e (real auth guard + temp SQLite, real
});
expect(res.status).toBe(201);
// It used to land as 801.76 with no currency, which is 801.76 of the trip's euros.
const item = db.prepare('SELECT total_price, currency, exchange_rate FROM budget_items WHERE reservation_id = ?').get(res.body.reservation.id);
const item = await bookedExpense(res.body.reservation.id);
expect(item).toEqual({ total_price: 801.76, currency: 'USD', exchange_rate: 1.17 });
});
@@ -159,7 +190,7 @@ describe('Reservations + accommodations e2e (real auth guard + temp SQLite, real
.set('Cookie', sessionCookie(1))
.send({ title: 'Museum', type: 'event', create_budget_entry: { total_price: 20, currency: 'not a code' } });
expect(res.status).toBe(201);
const item = db.prepare('SELECT total_price, currency, exchange_rate FROM budget_items WHERE reservation_id = ?').get(res.body.reservation.id);
const item = await bookedExpense(res.body.reservation.id);
expect(item).toEqual({ total_price: 20, currency: null, exchange_rate: 1 });
});
@@ -170,7 +201,7 @@ describe('Reservations + accommodations e2e (real auth guard + temp SQLite, real
.send({ title: 'Hotel' });
expect(ok.status).toBe(201);
expect(ok.body.reservation).toMatchObject({ title: 'Hotel', type: 'other', status: 'pending' });
expect(db.prepare('SELECT title FROM reservations WHERE id = ?').get(ok.body.reservation.id)).toEqual({ title: 'Hotel' });
expect((await findRow(orm, Reservations, { id: ok.body.reservation.id }))!.title).toBe('Hotel');
// The fire-and-forget booking notification reaches the (mocked) notification service.
await vi.waitFor(() => expect(notificationSend).toHaveBeenCalled());
expect(notificationSend).toHaveBeenCalledWith(expect.objectContaining({ event: 'booking_change', actorId: 1 }));
@@ -183,7 +214,7 @@ describe('Reservations + accommodations e2e (real auth guard + temp SQLite, real
// The reported repro (#2355): an id that resolves to nothing used to reach
// the statement and come back as an unhandled SqliteError, i.e. a bare 500.
it('400 on an update whose place_id exists nowhere, and the row is left alone', async () => {
const rid = Number(db.prepare("INSERT INTO reservations (trip_id, title, type) VALUES (?, 'Dinner', 'other')").run(tripId).lastInsertRowid);
const rid = await seedReservation(tripId, 'Dinner', 'other');
const res = await request(server)
.put(`/api/trips/${tripId}/reservations/${rid}`)
@@ -192,13 +223,14 @@ describe('Reservations + accommodations e2e (real auth guard + temp SQLite, real
expect(res.status).toBe(400);
expect(res.body).toEqual({ error: 'Unknown reference: place_id' });
expect(db.prepare('SELECT title, place_id FROM reservations WHERE id = ?').get(rid)).toEqual({ title: 'Dinner', place_id: null });
const dinner = (await findRow(orm, Reservations, { id: rid }))!;
expect({ title: dinner.title, place_id: dinner.place_id }).toEqual({ title: 'Dinner', place_id: null });
});
it('400 on a create whose create_accommodation day exists nowhere, and no stay is written', async () => {
const placeId = Number(db.prepare('INSERT INTO places (trip_id, name) VALUES (?, ?)').run(tripId, 'Hotel Unknown').lastInsertRowid);
const dayId = Number(db.prepare('INSERT INTO days (trip_id, day_number, date) VALUES (?, 7, ?)').run(tripId, '2026-03-07').lastInsertRowid);
const before = db.prepare('SELECT COUNT(*) as c FROM day_accommodations WHERE trip_id = ?').get(tripId);
const placeId = await seedPlace(tripId, 'Hotel Unknown');
const dayId = await seedDay(tripId, 7, '2026-03-07');
const before = await countRows(orm, DayAccommodations, { trip: tripId });
const res = await request(server)
.post(`/api/trips/${tripId}/reservations`)
@@ -207,16 +239,14 @@ describe('Reservations + accommodations e2e (real auth guard + temp SQLite, real
expect(res.status).toBe(400);
expect(res.body).toEqual({ error: 'Unknown reference: create_accommodation.end_day_id' });
expect(db.prepare('SELECT COUNT(*) as c FROM day_accommodations WHERE trip_id = ?').get(tripId)).toEqual(before);
expect(await countRows(orm, DayAccommodations, { trip: tripId })).toBe(before);
});
// #522, which must survive all of the above: shortening a trip cascades the
// stay away and leaves the booking pointing at a gap, and the booking still
// has to be savable.
it('200 on an update whose stored accommodation_id no longer resolves', async () => {
const rid = Number(
db.prepare("INSERT INTO reservations (trip_id, title, type, accommodation_id) VALUES (?, 'Stay', 'hotel', 999999)").run(tripId).lastInsertRowid,
);
const rid = await seedReservation(tripId, 'Stay', 'hotel', { accommodation_id: '999999' });
const res = await request(server)
.put(`/api/trips/${tripId}/reservations/${rid}`)
@@ -224,13 +254,14 @@ describe('Reservations + accommodations e2e (real auth guard + temp SQLite, real
.send({ title: 'Stay, renamed', accommodation_id: 999999 });
expect(res.status).toBe(200);
expect(db.prepare('SELECT title, accommodation_id FROM reservations WHERE id = ?').get(rid))
const stay = (await findRow(orm, Reservations, { id: rid }))!;
expect({ title: stay.title, accommodation_id: stay.accommodation_id })
.toEqual({ title: 'Stay, renamed', accommodation_id: null });
});
it('200 list accommodations + 201 create (real insert + auto hotel reservation), 404 on bad refs', async () => {
const placeId = Number(db.prepare('INSERT INTO places (trip_id, name) VALUES (?, ?)').run(tripId, 'Grand Hotel').lastInsertRowid);
const dayId = Number(db.prepare('INSERT INTO days (trip_id, day_number, date) VALUES (?, 1, ?)').run(tripId, '2026-03-01').lastInsertRowid);
const placeId = await seedPlace(tripId, 'Grand Hotel');
const dayId = await seedDay(tripId, 1, '2026-03-01');
const create = await request(server)
.post(`/api/trips/${tripId}/accommodations`)
.set('Cookie', sessionCookie(1))
@@ -238,7 +269,7 @@ describe('Reservations + accommodations e2e (real auth guard + temp SQLite, real
expect(create.status).toBe(201);
expect(create.body.accommodation).toMatchObject({ place_id: placeId, start_day_id: dayId, end_day_id: dayId, place_name: 'Grand Hotel' });
// The partner hotel reservation is auto-created by the real DaysService SQL.
const linked = db.prepare('SELECT * FROM reservations WHERE accommodation_id = ?').get(create.body.accommodation.id) as { type: string; status: string };
const linked = await findRow(orm, Reservations, { accommodation_id: String(create.body.accommodation.id) });
expect(linked).toMatchObject({ type: 'hotel', status: 'confirmed' });
const list = await request(server).get(`/api/trips/${tripId}/accommodations`).set('Cookie', sessionCookie(1));
expect(list.status).toBe(200);
@@ -256,8 +287,8 @@ describe('Reservations + accommodations e2e (real auth guard + temp SQLite, real
// The road-trip view builds its stops from day_assignments and only looks the stay
// up afterwards, so a booking without one never reaches the route: the complaint
// was having to enter the same hotel a second time as an ordinary place.
const placeId = Number(db.prepare('INSERT INTO places (trip_id, name) VALUES (?, ?)').run(tripId, 'Hotel Adlon').lastInsertRowid);
const dayId = Number(db.prepare('INSERT INTO days (trip_id, day_number, date) VALUES (?, 4, ?)').run(tripId, '2026-03-04').lastInsertRowid);
const placeId = await seedPlace(tripId, 'Hotel Adlon');
const dayId = await seedDay(tripId, 4, '2026-03-04');
const create = await request(server)
.post(`/api/trips/${tripId}/accommodations`)
@@ -266,26 +297,26 @@ describe('Reservations + accommodations e2e (real auth guard + temp SQLite, real
expect(create.status).toBe(201);
// In the answer, not only on the socket: the broadcast skips the sender.
expect(create.body.assignment).toMatchObject({ day_id: dayId, place_id: placeId });
expect(db.prepare('SELECT stop_type FROM places WHERE id = ?').get(placeId)).toMatchObject({ stop_type: 'hotel' });
expect(await findRow(orm, Places, { id: placeId })).toMatchObject({ stop_type: 'hotel' });
const del = await request(server)
.delete(`/api/trips/${tripId}/accommodations/${create.body.accommodation.id}`)
.set('Cookie', sessionCookie(1));
expect(del.status).toBe(200);
expect(del.body.removedAssignments).toEqual([{ id: create.body.assignment.id, dayId }]);
expect(db.prepare('SELECT id FROM day_assignments WHERE day_id = ?').all(dayId)).toEqual([]);
expect(await findRows(orm, DayAssignments, { day: dayId })).toEqual([]);
});
it('404 when trip not accessible (accommodations)', async () => {
// See the reservations 404 case above for why this deletes/restores the
// real row instead of mocking canAccessTrip.
db.prepare('DELETE FROM trips WHERE id = ?').run(tripId);
await deleteRows(orm, Trips, { id: tripId });
try {
const res = await request(server).get(`/api/trips/${tripId}/accommodations`).set('Cookie', sessionCookie(1));
expect(res.status).toBe(404);
expect(res.body).toEqual({ error: 'Trip not found' });
} finally {
db.prepare("INSERT INTO trips (id, user_id, title) VALUES (?, 1, 'E2E Trip')").run(tripId);
await insertRow(orm, Trips, { id: tripId, user: 1, title: 'E2E Trip' });
}
});
@@ -312,19 +343,20 @@ describe('Reservations + accommodations e2e (real auth guard + temp SQLite, real
// for every case, so the numbers have to keep climbing.
let dayNumber = 100;
beforeEach(() => {
db.prepare(
"INSERT OR IGNORE INTO users (id, username, email, password_hash, role, password_version) VALUES (2, 'victim', 'victim@example.test', 'x', 'user', 0)",
).run();
foreignTripId = Number(db.prepare("INSERT INTO trips (user_id, title) VALUES (2, 'Someone else')").run().lastInsertRowid);
foreignReservationId = Number(db.prepare("INSERT INTO reservations (trip_id, title, type) VALUES (?, 'Secret', 'other')").run(foreignTripId).lastInsertRowid);
beforeEach(async () => {
await insertRowIgnoringConflict(orm, Users, {
id: 2, username: 'victim', email: 'victim@example.test', password_hash: 'x', role: 'user', password_version: 0,
});
foreignTripId = (await makeTrip(orm, 2, { title: 'Someone else' })).id;
foreignReservationId = await seedReservation(foreignTripId, 'Secret', 'other');
dayNumber += 1;
foreignDayId = Number(db.prepare("INSERT INTO days (trip_id, day_number, date) VALUES (?, ?, '2026-05-01')").run(foreignTripId, dayNumber).lastInsertRowid);
ownDayId = Number(db.prepare("INSERT INTO days (trip_id, day_number, date) VALUES (?, ?, '2026-05-01')").run(tripId, dayNumber).lastInsertRowid);
foreignDayId = await seedDay(foreignTripId, dayNumber, '2026-05-01');
ownDayId = await seedDay(tripId, dayNumber, '2026-05-01');
});
function positionRow(reservationId: number, dayId: number) {
return db.prepare('SELECT position FROM reservation_day_positions WHERE reservation_id = ? AND day_id = ?').get(reservationId, dayId);
async function positionRow(reservationId: number, dayId: number) {
const row = await findRow(orm, ReservationDayPositions, { reservation: reservationId, day: dayId });
return row ? { position: row.position } : undefined;
}
it('writes nothing when both ids belong to another trip', async () => {
@@ -333,7 +365,7 @@ describe('Reservations + accommodations e2e (real auth guard + temp SQLite, real
.set('Cookie', sessionCookie(1))
.send({ positions: [{ id: foreignReservationId, day_plan_position: 999 }], day_id: foreignDayId });
expect(res.status).toBe(200);
expect(positionRow(foreignReservationId, foreignDayId)).toBeUndefined();
expect(await positionRow(foreignReservationId, foreignDayId)).toBeUndefined();
});
it('writes nothing when only the reservation is foreign', async () => {
@@ -342,27 +374,27 @@ describe('Reservations + accommodations e2e (real auth guard + temp SQLite, real
.set('Cookie', sessionCookie(1))
.send({ positions: [{ id: foreignReservationId, day_plan_position: 5 }], day_id: ownDayId });
expect(res.status).toBe(200);
expect(positionRow(foreignReservationId, ownDayId)).toBeUndefined();
expect(await positionRow(foreignReservationId, ownDayId)).toBeUndefined();
});
it('writes nothing when only the day is foreign', async () => {
const ownReservationId = Number(db.prepare("INSERT INTO reservations (trip_id, title, type) VALUES (?, 'Mine', 'other')").run(tripId).lastInsertRowid);
const ownReservationId = await seedReservation(tripId, 'Mine', 'other');
const res = await request(server)
.put(`/api/trips/${tripId}/reservations/positions`)
.set('Cookie', sessionCookie(1))
.send({ positions: [{ id: ownReservationId, day_plan_position: 5 }], day_id: foreignDayId });
expect(res.status).toBe(200);
expect(positionRow(ownReservationId, foreignDayId)).toBeUndefined();
expect(await positionRow(ownReservationId, foreignDayId)).toBeUndefined();
});
it('still stores a position when both ids are on the trip', async () => {
const ownReservationId = Number(db.prepare("INSERT INTO reservations (trip_id, title, type) VALUES (?, 'Mine', 'other')").run(tripId).lastInsertRowid);
const ownReservationId = await seedReservation(tripId, 'Mine', 'other');
const res = await request(server)
.put(`/api/trips/${tripId}/reservations/positions`)
.set('Cookie', sessionCookie(1))
.send({ positions: [{ id: ownReservationId, day_plan_position: 3 }], day_id: ownDayId });
expect(res.status).toBe(200);
expect(positionRow(ownReservationId, ownDayId)).toEqual({ position: 3 });
expect(await positionRow(ownReservationId, ownDayId)).toEqual({ position: 3 });
});
// An id that exists nowhere used to raise a foreign-key error, which the
@@ -377,7 +409,7 @@ describe('Reservations + accommodations e2e (real auth guard + temp SQLite, real
});
it('does not fall over when day_plan_position is omitted', async () => {
const ownReservationId = Number(db.prepare("INSERT INTO reservations (trip_id, title, type) VALUES (?, 'Mine', 'other')").run(tripId).lastInsertRowid);
const ownReservationId = await seedReservation(tripId, 'Mine', 'other');
const res = await request(server)
.put(`/api/trips/${tripId}/reservations/positions`)
.set('Cookie', sessionCookie(1))
+18 -7
View File
@@ -24,6 +24,13 @@ import { createTestRegistry } from '../../src/nest-mcp';
import { trekMcpAccessPolicy, trekMcpValidateAccess } from '../../src/mcp/nest-mcp-policy';
import { TestUnitOfWorkModule } from '../helpers/test-uow';
import { createTestMikroOrmModule } from '../helpers/test-orm';
import { makeAdmin, makeUser } from '../helpers/factories/users';
import { deleteRows, findRows, insertRow, insertRowIgnoringConflict } from '../helpers/factories/rows';
import { SchoolHolidayCountries } from '../../src/db/entities/SchoolHolidayCountries.entity';
import { SchoolHolidayPeriods } from '../../src/db/entities/SchoolHolidayPeriods.entity';
import { SchoolHolidayRegions } from '../../src/db/entities/SchoolHolidayRegions.entity';
import { VacayHolidayCalendars } from '../../src/db/entities/VacayHolidayCalendars.entity';
import { VacayPlans } from '../../src/db/entities/VacayPlans.entity';
const base = '/api/school-holiday-catalog';
const winter = { name: 'Winter break', startDate: '2026-12-20', endDate: '2027-01-06' };
@@ -31,7 +38,6 @@ let app: INestApplication;
let service: SchoolHolidaysService;
let orm: MikroORM;
beforeAll(async () => {
db.prepare("INSERT INTO users (id, username, email, password_hash, role) VALUES (1, 'admin', 'admin@test.local', '', 'admin'), (2, 'member', 'member@test.local', '', 'user')").run();
const module = await Test.createTestingModule({ imports: [await TestUnitOfWorkModule.forRoot(db), await createTestMikroOrmModule(db), RealtimeModule, SchoolHolidaysModule] }).compile();
app = module.createNestApplication();
app.use(cookieParser());
@@ -40,10 +46,15 @@ beforeAll(async () => {
await app.init();
service = app.get(SchoolHolidaysService);
orm = app.get(MikroORM);
await makeAdmin(orm, { id: 1, username: 'admin', email: 'admin@test.local' });
await makeUser(orm, { id: 2, username: 'member', email: 'member@test.local' });
});
afterAll(async () => { await app.close(); db.close(); });
beforeEach(() => {
db.exec('DELETE FROM vacay_holiday_calendars; DELETE FROM school_holiday_periods; DELETE FROM school_holiday_regions; DELETE FROM school_holiday_countries;');
beforeEach(async () => {
await deleteRows(orm, VacayHolidayCalendars);
await deleteRows(orm, SchoolHolidayPeriods);
await deleteRows(orm, SchoolHolidayRegions);
await deleteRows(orm, SchoolHolidayCountries);
});
async function seed() {
@@ -126,13 +137,13 @@ describe('global manual school holidays', () => {
it('protects used regions and deletes unused regions with their periods', () => withRequestContext(orm, async () => {
const region = await seed();
db.prepare('INSERT OR IGNORE INTO vacay_plans (id, owner_id) VALUES (1, 1)').run();
db.prepare("INSERT INTO vacay_holiday_calendars (plan_id, type, region) VALUES (1, 'school_holiday', ?)").run(region.code);
await insertRowIgnoringConflict(orm, VacayPlans, { id: 1, owner: 1 });
await insertRow(orm, VacayHolidayCalendars, { plan: 1, type: 'school_holiday', region: region.code });
await request(app.getHttpServer()).delete(`${base}/regions/${region.id}?revision=1`).set('Cookie', sessionCookie(1)).expect(409);
await request(app.getHttpServer()).delete(`${base}/countries/US`).set('Cookie', sessionCookie(1)).expect(409);
db.exec('DELETE FROM vacay_holiday_calendars');
await deleteRows(orm, VacayHolidayCalendars);
await request(app.getHttpServer()).delete(`${base}/regions/${region.id}?revision=1`).set('Cookie', sessionCookie(1)).expect(200);
expect(db.prepare('SELECT * FROM school_holiday_periods').all()).toEqual([]);
expect(await findRows(orm, SchoolHolidayPeriods)).toEqual([]);
await request(app.getHttpServer()).delete(`${base}/countries/US`).set('Cookie', sessionCookie(1)).expect(200);
expect(await service.catalog()).toEqual({ countries: [], regions: [] });
}));
+47 -83
View File
@@ -1,71 +1,25 @@
/**
* To-do module e2e — exercises the migrated /api/trips/:tripId/todo endpoints
* through the real JwtAuthGuard against a temp SQLite db. TodoService runs its
* real SQL via DatabaseModule (the DATABASE_CONNECTION factory picks up the
* mocked db singleton); trip access resolves through a real-SQL canAccessTrip
* over the temp db. Only the permission check and the WebSocket broadcast stay
* mocked.
* through the real JwtAuthGuard against a migrated temp SQLite db
* (createSnapshotTestDb()). TodoService and the trip access check run their
* real queries through the repositories; rows are seeded and read through the
* factories in tests/helpers/factories. Only the permission check and the
* WebSocket broadcast stay mocked.
*/
import { describe, it, expect, beforeAll, afterAll, beforeEach, vi, type MockInstance } from 'vitest';
import request from 'supertest';
import cookieParser from 'cookie-parser';
import type { Server } from 'http';
import { Test } from '@nestjs/testing';
import { seedUser, sessionCookie } from './harness';
import { sessionCookie } from './harness';
const { db } = vi.hoisted(() => {
// eslint-disable-next-line @typescript-eslint/no-require-imports
const Database = require('better-sqlite3');
const tmp = new Database(':memory:');
tmp.exec('PRAGMA journal_mode = WAL');
tmp.exec(`CREATE TABLE users (id INTEGER PRIMARY KEY AUTOINCREMENT, username TEXT NOT NULL,
email TEXT NOT NULL UNIQUE, role TEXT NOT NULL DEFAULT 'user', password_version INTEGER NOT NULL DEFAULT 0,
avatar TEXT);`);
tmp.exec('CREATE TABLE trips (id INTEGER PRIMARY KEY AUTOINCREMENT, user_id INTEGER, title TEXT, currency TEXT);');
tmp.exec('CREATE TABLE trip_members (trip_id INTEGER NOT NULL, user_id INTEGER NOT NULL);');
tmp.exec(`CREATE TABLE todo_items (
id INTEGER PRIMARY KEY AUTOINCREMENT,
trip_id INTEGER NOT NULL,
name TEXT NOT NULL,
checked INTEGER NOT NULL DEFAULT 0,
category TEXT,
sort_order INTEGER NOT NULL DEFAULT 0,
due_date TEXT,
description TEXT,
assigned_user_id INTEGER,
priority INTEGER NOT NULL DEFAULT 0,
created_at DATETIME DEFAULT CURRENT_TIMESTAMP
);`);
tmp.exec(`CREATE TABLE todo_category_assignees (
id INTEGER PRIMARY KEY AUTOINCREMENT,
trip_id INTEGER NOT NULL,
category_name TEXT NOT NULL,
user_id INTEGER NOT NULL,
UNIQUE(trip_id, category_name, user_id)
);`);
// StorageRegistryService (behind StorageModule, now in this module chain) reads
// this at onModuleInit.
tmp.exec('CREATE TABLE app_settings (key TEXT PRIMARY KEY, value TEXT);');
return { db: tmp };
vi.mock('../../src/db/database', async () => {
const { createSnapshotTestDb, buildDbMock } = await import('../helpers/db-mock');
return buildDbMock(createSnapshotTestDb());
});
vi.mock('../../src/db/database', () => ({
db,
// Real-SQL trip access over the temp db — TodoService.verifyTripAccess and
// DatabaseModule both read the mocked singleton.
canAccessTrip: (tripId: number | string, userId: number) =>
db.prepare(`
SELECT t.id, t.user_id FROM trips t
LEFT JOIN trip_members m ON m.trip_id = t.id AND m.user_id = ?
WHERE t.id = ? AND (t.user_id = ? OR m.user_id IS NOT NULL)
`).get(userId, tripId, userId),
isOwner: () => false,
getPlaceWithTags: () => null,
closeDb: () => {},
reinitialize: () => {},
}));
vi.mock('../../src/websocket', () => ({ broadcast: vi.fn() }));
import { db } from '../../src/db/database';
import { PermissionsService } from '../../src/nest/permissions/permissions.service';
// Since the permissions DI migration, the check is a spy on the container's
@@ -77,13 +31,19 @@ import { RealtimeModule } from '../../src/nest/realtime/realtime.module';
import { TrekExceptionFilter } from '../../src/nest/common/trek-exception.filter';
import { ZodValidationPipe } from '../../src/nest/common/zod-validation.pipe';
import { TestUnitOfWorkModule } from '../helpers/test-uow';
import { createTestMikroOrmModule } from '../helpers/test-orm';
import { createTestMikroOrmModule, createTestOrm, type TestOrm } from '../helpers/test-orm';
import { makeUser } from '../helpers/factories/users';
import { addTripMember, makeTrip } from '../helpers/factories/trips';
import { countRows, deleteRows, findRow, findRows, insertRow } from '../helpers/factories/rows';
import { TodoCategoryAssignees } from '../../src/db/entities/TodoCategoryAssignees.entity';
import { TodoItems } from '../../src/db/entities/TodoItems.entity';
import { TripMembers } from '../../src/db/entities/TripMembers.entity';
import { Trips } from '../../src/db/entities/Trips.entity';
function insertItem(tripId: number, name: string, extra: Partial<{ sort_order: number; due_date: string }> = {}): number {
const res = db
.prepare('INSERT INTO todo_items (trip_id, name, sort_order, due_date) VALUES (?, ?, ?, ?)')
.run(tripId, name, extra.sort_order ?? 0, extra.due_date ?? null);
return Number(res.lastInsertRowid);
let orm: TestOrm;
function insertItem(tripId: number, name: string, extra: Partial<{ sort_order: number; due_date: string }> = {}): Promise<number> {
return insertRow(orm, TodoItems, { trip: tripId, name, sort_order: extra.sort_order ?? 0, due_date: extra.due_date ?? null });
}
describe('To-do e2e (real auth guard + real SQL over temp SQLite)', () => {
@@ -104,24 +64,28 @@ describe('To-do e2e (real auth guard + real SQL over temp SQLite)', () => {
}
beforeAll(async () => {
seedUser(db as never, { id: 1 });
seedUser(db as never, { id: 2, email: 'stranger@example.test' });
orm = await createTestOrm(db);
// Usernames are unique on the migrated schema. User 2 carries 'e2e-user',
// the name the category assignee case below reads back for it.
await makeUser(orm, { id: 1, username: 'e2e-owner', email: 'e2e@example.test' });
await makeUser(orm, { id: 2, username: 'e2e-user', email: 'stranger@example.test' });
app = await build();
checkPermission = vi.spyOn(app.get(PermissionsService), 'checkPermission');
server = app.getHttpServer();
});
beforeEach(() => {
db.exec('DELETE FROM todo_category_assignees');
db.exec('DELETE FROM todo_items');
db.exec('DELETE FROM trip_members');
db.exec('DELETE FROM trips');
tripId = Number(db.prepare('INSERT INTO trips (user_id, title) VALUES (1, ?)').run('Trip').lastInsertRowid);
beforeEach(async () => {
await deleteRows(orm, TodoCategoryAssignees);
await deleteRows(orm, TodoItems);
await deleteRows(orm, TripMembers);
await deleteRows(orm, Trips);
tripId = (await makeTrip(orm, 1, { title: 'Trip' })).id;
checkPermission.mockReturnValue(true);
});
afterAll(async () => {
await app.close();
await orm.close();
});
it('401 without a session cookie', async () => {
@@ -130,8 +94,8 @@ describe('To-do e2e (real auth guard + real SQL over temp SQLite)', () => {
});
it('200 list ordered by sort_order', async () => {
insertItem(tripId, 'Second', { sort_order: 1 });
insertItem(tripId, 'First', { sort_order: 0 });
await insertItem(tripId, 'Second', { sort_order: 1 });
await insertItem(tripId, 'First', { sort_order: 0 });
const res = await request(server).get(`/api/trips/${tripId}/todo`).set('Cookie', sessionCookie(1));
expect(res.status).toBe(200);
expect(res.body.items.map((i: { name: string }) => i.name)).toEqual(['First', 'Second']);
@@ -144,11 +108,11 @@ describe('To-do e2e (real auth guard + real SQL over temp SQLite)', () => {
});
it('201 on create, inserting the row with the legacy defaults and incrementing sort_order', async () => {
insertItem(tripId, 'Existing', { sort_order: 4 });
await insertItem(tripId, 'Existing', { sort_order: 4 });
const res = await request(server).post(`/api/trips/${tripId}/todo`).set('Cookie', sessionCookie(1)).send({ name: 'Book hotel' });
expect(res.status).toBe(201);
expect(res.body.item).toMatchObject({ name: 'Book hotel', checked: 0, priority: 0, sort_order: 5 });
expect(db.prepare('SELECT name FROM todo_items WHERE id = ?').get(res.body.item.id)).toEqual({ name: 'Book hotel' });
expect((await findRow(orm, TodoItems, { id: res.body.item.id }))!.name).toBe('Book hotel');
});
it('400 from the Zod pipe on create without a name', async () => {
@@ -164,7 +128,7 @@ describe('To-do e2e (real auth guard + real SQL over temp SQLite)', () => {
});
it('accepts the legacy numeric checked form through the pipe', async () => {
const id = insertItem(tripId, 'Toggle me');
const id = await insertItem(tripId, 'Toggle me');
const res = await request(server).put(`/api/trips/${tripId}/todo/${id}`).set('Cookie', sessionCookie(1)).send({ checked: 1 });
expect(res.status).toBe(200);
expect(res.body.item.checked).toBe(1);
@@ -175,11 +139,11 @@ describe('To-do e2e (real auth guard + real SQL over temp SQLite)', () => {
const res = await request(server).post(`/api/trips/${tripId}/todo`).set('Cookie', sessionCookie(1)).send({ name: 'X' });
expect(res.status).toBe(403);
expect(res.body).toEqual({ error: 'No permission' });
expect((db.prepare('SELECT COUNT(*) AS n FROM todo_items').get() as { n: number }).n).toBe(0);
expect(await countRows(orm, TodoItems)).toBe(0);
});
it('200 on update; a body key with null clears the field, omitted keys stay', async () => {
const id = insertItem(tripId, 'Task', { due_date: '2026-06-01' });
const id = await insertItem(tripId, 'Task', { due_date: '2026-06-01' });
const renamed = await request(server).put(`/api/trips/${tripId}/todo/${id}`).set('Cookie', sessionCookie(1)).send({ name: 'Renamed' });
expect(renamed.status).toBe(200);
expect(renamed.body.item).toMatchObject({ id, name: 'Renamed', due_date: '2026-06-01' });
@@ -212,28 +176,28 @@ describe('To-do e2e (real auth guard + real SQL over temp SQLite)', () => {
});
it('200 on reorder, persisting the new sort_order', async () => {
const a = insertItem(tripId, 'A', { sort_order: 0 });
const b = insertItem(tripId, 'B', { sort_order: 1 });
const a = await insertItem(tripId, 'A', { sort_order: 0 });
const b = await insertItem(tripId, 'B', { sort_order: 1 });
const res = await request(server).put(`/api/trips/${tripId}/todo/reorder`).set('Cookie', sessionCookie(1)).send({ orderedIds: [b, a] });
expect(res.status).toBe(200);
expect(res.body).toEqual({ success: true });
const rows = db.prepare('SELECT id FROM todo_items WHERE trip_id = ? ORDER BY sort_order').all(tripId) as { id: number }[];
const rows = await findRows(orm, TodoItems, { trip: tripId }, { sort_order: 'asc' });
expect(rows.map((r) => r.id)).toEqual([b, a]);
});
it('200 on delete, removing the row; 404 when already gone', async () => {
const id = insertItem(tripId, 'Gone');
const id = await insertItem(tripId, 'Gone');
const ok = await request(server).delete(`/api/trips/${tripId}/todo/${id}`).set('Cookie', sessionCookie(1));
expect(ok.status).toBe(200);
expect(ok.body).toEqual({ success: true });
expect(db.prepare('SELECT id FROM todo_items WHERE id = ?').get(id)).toBeUndefined();
expect(await findRow(orm, TodoItems, { id })).toBeNull();
const missing = await request(server).delete(`/api/trips/${tripId}/todo/${id}`).set('Cookie', sessionCookie(1));
expect(missing.status).toBe(404);
expect(missing.body).toEqual({ error: 'Item not found' });
});
it('category assignees round-trip: PUT replaces, GET groups by category', async () => {
db.prepare('INSERT INTO trip_members (trip_id, user_id) VALUES (?, ?)').run(tripId, 2);
await addTripMember(orm, tripId, 2);
const put = await request(server)
.put(`/api/trips/${tripId}/todo/category-assignees/Booking`)
.set('Cookie', sessionCookie(1))
+29 -26
View File
@@ -12,28 +12,27 @@ import request from 'supertest';
import cookieParser from 'cookie-parser';
import type { Server } from 'http';
import { Test } from '@nestjs/testing';
import { seedUser, sessionCookie } from './harness';
import { sessionCookie } from './harness';
const { db } = vi.hoisted(() => {
// eslint-disable-next-line @typescript-eslint/no-require-imports
const Database = require('better-sqlite3');
const tmp = new Database(':memory:');
tmp.exec('PRAGMA journal_mode = WAL');
tmp.exec(`CREATE TABLE users (id INTEGER PRIMARY KEY AUTOINCREMENT, username TEXT NOT NULL,
email TEXT NOT NULL UNIQUE, role TEXT NOT NULL DEFAULT 'user', password_version INTEGER NOT NULL DEFAULT 0,
maps_api_key TEXT, unsplash_api_key TEXT);`);
tmp.exec('CREATE TABLE app_settings (key TEXT PRIMARY KEY, value TEXT);');
tmp.exec('CREATE TABLE google_api_usage (day TEXT PRIMARY KEY, calls INTEGER NOT NULL DEFAULT 0);');
return { db: tmp };
vi.mock('../../src/db/database', async () => {
const { createSnapshotTestDb, buildDbMock } = await import('../helpers/db-mock');
return buildDbMock(createSnapshotTestDb());
});
vi.mock('../../src/db/database', () => ({ db, closeDb: () => {}, reinitialize: () => {} }));
import { db } from '../../src/db/database';
import { TransitModule } from '../../src/nest/transit/transit.module';
import { RealtimeModule } from '../../src/nest/realtime/realtime.module';
import { TrekExceptionFilter } from '../../src/nest/common/trek-exception.filter';
import { clearGoogleTransitCache } from '../../src/nest/transit/google-transit.provider';
import { TestUnitOfWorkModule } from '../helpers/test-uow';
import { createTestMikroOrmModule } from '../helpers/test-orm';
import { createTestMikroOrmModule, createTestOrm, type TestOrm } from '../helpers/test-orm';
import { makeAdmin } from '../helpers/factories/users';
import { setAppSetting } from '../helpers/factories/settings';
import { deleteRows, updateRows } from '../helpers/factories/rows';
import { AppSettings } from '../../src/db/entities/AppSettings.entity';
import { Users } from '../../src/db/entities/Users.entity';
let orm: TestOrm;
const ADMIN = 1;
@@ -60,13 +59,17 @@ describe('Transit backend switch e2e (#1699)', () => {
}
beforeAll(async () => {
seedUser(db as never, { id: ADMIN, role: 'admin' });
orm = await createTestOrm(db);
await makeAdmin(orm, { id: ADMIN });
app = await build();
server = app.getHttpServer();
});
afterAll(async () => { await app?.close(); });
afterAll(async () => {
await app?.close();
await orm?.close();
});
beforeEach(() => {
beforeEach(async () => {
vi.stubGlobal('fetch', fetchMock);
fetchMock.mockReset();
// MOTIS and Routes shapes both parse as "no itineraries", which is all this
@@ -74,8 +77,8 @@ describe('Transit backend switch e2e (#1699)', () => {
fetchMock.mockResolvedValue({
ok: true, status: 200, headers: { get: () => null }, json: async () => ({}),
});
db.prepare('DELETE FROM app_settings').run();
db.prepare('UPDATE users SET maps_api_key = NULL WHERE id = ?').run(ADMIN);
await deleteRows(orm, AppSettings);
await updateRows(orm, Users, { id: ADMIN }, { maps_api_key: null });
clearGoogleTransitCache();
});
@@ -94,7 +97,7 @@ describe('Transit backend switch e2e (#1699)', () => {
});
it('TRANSIT-PROV-E2E-002: selecting Google without a key still plans through Transitous', async () => {
db.prepare("INSERT INTO app_settings (key, value) VALUES ('transit_provider', 'google')").run();
await setAppSetting(orm, 'transit_provider', 'google');
expect(await planUpstream()).toContain('transitous.org');
// The response says who really answered, so the empty state cannot blame
// Google for a Transitous result.
@@ -102,15 +105,15 @@ describe('Transit backend switch e2e (#1699)', () => {
});
it('TRANSIT-PROV-E2E-003: with the switch on and a key set, the plan leaves for the Routes API', async () => {
db.prepare("INSERT INTO app_settings (key, value) VALUES ('transit_provider', 'google')").run();
db.prepare("INSERT INTO app_settings (key, value) VALUES ('maps_api_key', 'instance-key')").run();
await setAppSetting(orm, 'transit_provider', 'google');
await setAppSetting(orm, 'maps_api_key', 'instance-key');
expect(await planUpstream()).toBe('https://routes.googleapis.com/directions/v2:computeRoutes');
expect(lastBody.provider).toBe('google');
});
it('TRANSIT-PROV-E2E-004: the picker follows the switch to Google Places', async () => {
db.prepare("INSERT INTO app_settings (key, value) VALUES ('transit_provider', 'google')").run();
db.prepare("INSERT INTO app_settings (key, value) VALUES ('maps_api_key', 'instance-key')").run();
await setAppSetting(orm, 'transit_provider', 'google');
await setAppSetting(orm, 'maps_api_key', 'instance-key');
const res = await request(server)
.get('/api/transit/geocode?q=Nakanoshima&lang=ja')
@@ -120,8 +123,8 @@ describe('Transit backend switch e2e (#1699)', () => {
});
it("TRANSIT-PROV-E2E-005: a member's own key is used when the instance has none", async () => {
db.prepare("INSERT INTO app_settings (key, value) VALUES ('transit_provider', 'google')").run();
db.prepare('UPDATE users SET maps_api_key = ? WHERE id = ?').run('personal-key', ADMIN);
await setAppSetting(orm, 'transit_provider', 'google');
await updateRows(orm, Users, { id: ADMIN }, { maps_api_key: 'personal-key' });
expect(await planUpstream()).toBe('https://routes.googleapis.com/directions/v2:computeRoutes');
expect(fetchMock.mock.calls[0][1].headers['X-Goog-Api-Key']).toBe('personal-key');
+47 -63
View File
@@ -1,8 +1,9 @@
/**
* Trip invite-link e2e — exercises /api/trips/:tripId/invite-link (manage) and
* /api/trip-invites/:token (preview + accept) through the real JwtAuthGuard
* against a temp SQLite db. TripInviteService is DI-native and runs its real
* SQL against the temp db; only the permission check, membership join and
* against a migrated temp SQLite db (createSnapshotTestDb()), seeded and read
* through the factories in tests/helpers/factories. TripInviteService is
* DI-native and runs its real SQL against the temp db; only the permission check, membership join and
* audit log are mocked. Focuses on auth (401), trip-access 404, the
* share_manage 403, the login-required join, and invalid-token 404s (#1143).
*/
@@ -11,41 +12,15 @@ import request from 'supertest';
import cookieParser from 'cookie-parser';
import type { Server } from 'http';
import { Test } from '@nestjs/testing';
import { seedUser, sessionCookie } from './harness';
const { db } = vi.hoisted(() => {
// eslint-disable-next-line @typescript-eslint/no-require-imports
const Database = require('better-sqlite3');
const tmp = new Database(':memory:');
tmp.exec('PRAGMA journal_mode = WAL');
tmp.exec(`CREATE TABLE users (id INTEGER PRIMARY KEY AUTOINCREMENT, username TEXT NOT NULL,
email TEXT NOT NULL UNIQUE, role TEXT NOT NULL DEFAULT 'user', password_version INTEGER NOT NULL DEFAULT 0);`);
tmp.exec('CREATE TABLE trips (id INTEGER PRIMARY KEY AUTOINCREMENT, title TEXT, user_id INTEGER, currency TEXT);');
// TripAccessGuard/TripOwnerGuard now read 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);');
// TripInviteService now runs its real SQL (DI-injected, no mock) — mirror of
// the trip_invite_tokens DDL from migration 153.
tmp.exec(`CREATE TABLE trip_invite_tokens (
id INTEGER PRIMARY KEY AUTOINCREMENT,
trip_id INTEGER NOT NULL UNIQUE REFERENCES trips(id) ON DELETE CASCADE,
token TEXT UNIQUE NOT NULL,
created_by INTEGER REFERENCES users(id) ON DELETE SET NULL,
expires_at TEXT,
created_at DATETIME DEFAULT CURRENT_TIMESTAMP);`);
// AuditService now runs its real INSERT (DI-injected, no mock) — slim
// audit_log mirror (no FKs), same shape as plugin-runtime.test.ts.
tmp.exec(`CREATE TABLE audit_log (
id INTEGER PRIMARY KEY AUTOINCREMENT, created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
user_id INTEGER, action TEXT NOT NULL, resource TEXT, details TEXT, ip TEXT);`);
return { db: tmp };
});
import { sessionCookie } from './harness';
const { canAccessTrip } = vi.hoisted(() => ({ canAccessTrip: vi.fn() }));
vi.mock('../../src/db/database', () => ({
db, canAccessTrip, getPlaceWithTags: vi.fn(), closeDb: () => {}, reinitialize: () => {},
}));
vi.mock('../../src/db/database', async () => {
const { createSnapshotTestDb, buildDbMock } = await import('../helpers/db-mock');
return { ...buildDbMock(createSnapshotTestDb()), canAccessTrip, getPlaceWithTags: vi.fn() };
});
import { db } from '../../src/db/database';
import { PermissionsService } from '../../src/nest/permissions/permissions.service';
// Since the permissions DI migration, the check is a spy on the container's
@@ -65,7 +40,13 @@ import { TripMembershipService } from '../../src/nest/trip-membership/trip-membe
import { TrekExceptionFilter } from '../../src/nest/common/trek-exception.filter';
import { ZodValidationPipe } from '../../src/nest/common/zod-validation.pipe';
import { TestUnitOfWorkModule } from '../helpers/test-uow';
import { createTestMikroOrmModule } from '../helpers/test-orm';
import { createTestMikroOrmModule, createTestOrm, type TestOrm } from '../helpers/test-orm';
import { makeUser } from '../helpers/factories/users';
import { countRows, deleteRows, findRows, insertRow } from '../helpers/factories/rows';
import { TripInviteTokens } from '../../src/db/entities/TripInviteTokens.entity';
import { Trips } from '../../src/db/entities/Trips.entity';
let orm: TestOrm;
describe('Trip invite-link e2e (real auth guard + temp SQLite)', () => {
let server: Server;
@@ -83,32 +64,35 @@ describe('Trip invite-link e2e (real auth guard + temp SQLite)', () => {
return nest;
}
function seedTrip(id: number, title: string, ownerId = 1) {
db.prepare('INSERT INTO trips (id, title, user_id) VALUES (?, ?, ?)').run(id, title, ownerId);
async function seedTrip(id: number, title: string, ownerId = 1) {
await insertRow(orm, Trips, { id, title, user: ownerId });
}
function seedToken(tripId: number, token: string, expiresAt: string | null = null) {
db.prepare('INSERT INTO trip_invite_tokens (trip_id, token, created_by, expires_at) VALUES (?, ?, 1, ?)')
.run(tripId, token, expiresAt);
async function seedToken(tripId: number, token: string, expiresAt: string | null = null) {
await insertRow(orm, TripInviteTokens, { trip: tripId, token, createdByRef: 1, expires_at: expiresAt });
}
beforeAll(async () => {
seedUser(db as never, { id: 1 });
seedUser(db as never, { id: 2, username: 'e2e-user-2', email: 'e2e-2@example.test' });
orm = await createTestOrm(db);
await makeUser(orm, { id: 1, username: 'e2e-user', email: 'e2e@example.test' });
await makeUser(orm, { id: 2, username: 'e2e-user-2', email: 'e2e-2@example.test' });
app = await build();
checkPermission = vi.spyOn(app.get(PermissionsService), 'checkPermission');
server = app.getHttpServer();
});
beforeEach(() => {
db.prepare('DELETE FROM trip_invite_tokens').run();
db.prepare('DELETE FROM trips').run();
beforeEach(async () => {
await deleteRows(orm, TripInviteTokens);
await deleteRows(orm, Trips);
// 0b review L2 / security review F-B7: dead mock scaffolding — see
// budget.e2e.test.ts's identical comment.
checkPermission.mockReturnValue(true);
joinTripAsMember.mockReset();
});
afterAll(async () => { await app.close(); });
afterAll(async () => {
await app.close();
await orm.close();
});
// ── manage ──
it('401 without a session cookie', async () => {
@@ -116,8 +100,8 @@ describe('Trip invite-link e2e (real auth guard + temp SQLite)', () => {
});
it('GET returns the current link for a trip member', async () => {
seedTrip(5, 'Lisbon');
seedToken(5, 'abc');
await seedTrip(5, 'Lisbon');
await seedToken(5, 'abc');
const res = await request(server).get('/api/trips/5/invite-link').set('Cookie', sessionCookie(1));
expect(res.status).toBe(200);
expect(res.body.token).toBe('abc');
@@ -125,26 +109,26 @@ describe('Trip invite-link e2e (real auth guard + temp SQLite)', () => {
});
it('GET returns { token: null } when no link exists', async () => {
seedTrip(5, 'Lisbon');
await seedTrip(5, 'Lisbon');
const res = await request(server).get('/api/trips/5/invite-link').set('Cookie', sessionCookie(1));
expect(res.status).toBe(200);
expect(res.body).toEqual({ token: null });
});
it('POST creates/rotates the link', async () => {
seedTrip(5, 'Lisbon');
seedToken(5, 'old-token');
await seedTrip(5, 'Lisbon');
await seedToken(5, 'old-token');
const res = await request(server).post('/api/trips/5/invite-link').set('Cookie', sessionCookie(1)).send({});
expect([200, 201]).toContain(res.status);
expect(res.body.token).toMatch(/^[A-Za-z0-9_-]{20,}$/);
expect(res.body.token).not.toBe('old-token');
const rows = db.prepare('SELECT token FROM trip_invite_tokens WHERE trip_id = 5').all() as { token: string }[];
const rows = await findRows(orm, TripInviteTokens, { trip: 5 });
expect(rows).toHaveLength(1);
expect(rows[0].token).toBe(res.body.token);
});
it('POST with expires_in_days bounds the link life', async () => {
seedTrip(5, 'Lisbon');
await seedTrip(5, 'Lisbon');
const res = await request(server).post('/api/trips/5/invite-link').set('Cookie', sessionCookie(1))
.send({ expires_in_days: 7 });
expect([200, 201]).toContain(res.status);
@@ -154,22 +138,22 @@ describe('Trip invite-link e2e (real auth guard + temp SQLite)', () => {
});
it('POST 400 for a non-numeric expires_in_days string', async () => {
seedTrip(5, 'Lisbon');
await seedTrip(5, 'Lisbon');
const res = await request(server).post('/api/trips/5/invite-link').set('Cookie', sessionCookie(1))
.send({ expires_in_days: '7abc' });
expect(res.status).toBe(400);
expect(db.prepare('SELECT COUNT(*) AS n FROM trip_invite_tokens').get()).toEqual({ n: 0 });
expect(await countRows(orm, TripInviteTokens)).toBe(0);
});
it('403 to create without share_manage', async () => {
seedTrip(5, 'Lisbon');
await seedTrip(5, 'Lisbon');
checkPermission.mockReturnValue(false);
const res = await request(server).post('/api/trips/5/invite-link').set('Cookie', sessionCookie(1)).send({});
expect(res.status).toBe(403);
});
it('403 to READ the link without share_manage (token grants membership)', async () => {
seedTrip(5, 'Lisbon');
await seedTrip(5, 'Lisbon');
checkPermission.mockReturnValue(false);
const res = await request(server).get('/api/trips/5/invite-link').set('Cookie', sessionCookie(1));
expect(res.status).toBe(403);
@@ -190,23 +174,23 @@ describe('Trip invite-link e2e (real auth guard + temp SQLite)', () => {
});
it('preview resolves the trip title for an authed user', async () => {
seedTrip(9, 'Rome 2026');
seedToken(9, 'tok');
await seedTrip(9, 'Rome 2026');
await seedToken(9, 'tok');
const res = await request(server).get('/api/trip-invites/tok').set('Cookie', sessionCookie(2));
expect(res.status).toBe(200);
expect(res.body).toEqual({ trip_id: 9, title: 'Rome 2026' });
});
it('preview 404 for an invalid/expired token', async () => {
seedTrip(9, 'Rome 2026');
seedToken(9, 'tok', new Date(Date.now() - 3600_000).toISOString());
await seedTrip(9, 'Rome 2026');
await seedToken(9, 'tok', new Date(Date.now() - 3600_000).toISOString());
expect((await request(server).get('/api/trip-invites/bad').set('Cookie', sessionCookie(2))).status).toBe(404);
expect((await request(server).get('/api/trip-invites/tok').set('Cookie', sessionCookie(2))).status).toBe(404);
});
it('accept joins the current user and returns the trip id', async () => {
seedTrip(9, 'Rome 2026');
seedToken(9, 'tok');
await seedTrip(9, 'Rome 2026');
await seedToken(9, 'tok');
joinTripAsMember.mockReturnValueOnce({ joined: true, tripId: 9 });
const res = await request(server).post('/api/trip-invites/tok/accept').set('Cookie', sessionCookie(2));
expect(res.status).toBe(200);
+56 -45
View File
@@ -58,7 +58,24 @@ import { BudgetService } from '../../src/nest/budget/budget.service';
import { TripsModule } from '../../src/nest/trips/trips.module';
import { TrekExceptionFilter } from '../../src/nest/common/trek-exception.filter';
import { TestUnitOfWorkModule } from '../helpers/test-uow';
import { createTestMikroOrmModule } from '../helpers/test-orm';
import { createTestMikroOrmModule, createTestOrm, type TestOrm } from '../helpers/test-orm';
import { makeUser } from '../helpers/factories/users';
import { setUserSetting } from '../helpers/factories/settings';
import { countRows, deleteRows, findRow, findRows, insertRow } from '../helpers/factories/rows';
import { AuditLog } from '../../src/db/entities/AuditLog.entity';
import { Days } from '../../src/db/entities/Days.entity';
import { JourneyEntries } from '../../src/db/entities/JourneyEntries.entity';
import { Journeys } from '../../src/db/entities/Journeys.entity';
import { Settings } from '../../src/db/entities/Settings.entity';
import { TripMembers } from '../../src/db/entities/TripMembers.entity';
import { Trips } from '../../src/db/entities/Trips.entity';
let orm: TestOrm;
/** The trip's day ids in day order. */
async function dayIds(tripId: number): Promise<number[]> {
return (await findRows(orm, Days, { trip: tripId }, { day_number: 'asc' })).map(d => d.id);
}
describe('Trips e2e (real auth guard + temp SQLite)', () => {
let server: Server;
@@ -77,9 +94,8 @@ describe('Trips e2e (real auth guard + temp SQLite)', () => {
// harness.ts's seedUser() omits password_hash, which the real migrated
// schema requires NOT NULL (days.e2e.test.ts/addons.e2e.test.ts hit the
// same thing) — a raw insert here instead.
db.prepare(
"INSERT INTO users (id, username, email, password_hash, role, password_version) VALUES (1, 'e2e-user', 'e2e@example.test', 'x', 'user', 0)",
).run();
orm = await createTestOrm(db);
await makeUser(orm, { id: 1, username: 'e2e-user', email: 'e2e@example.test' });
app = await build();
checkPermission = vi.spyOn(app.get(PermissionsService), 'checkPermission');
vi.spyOn(app.get(BudgetService), 'listBudgetItems').mockResolvedValue([]);
@@ -87,12 +103,12 @@ describe('Trips e2e (real auth guard + temp SQLite)', () => {
server = app.getHttpServer();
});
beforeEach(() => {
db.prepare('DELETE FROM trips').run();
db.prepare('DELETE FROM trip_members').run();
db.prepare('DELETE FROM days').run();
db.prepare('DELETE FROM audit_log').run();
db.prepare('DELETE FROM settings').run();
beforeEach(async () => {
await deleteRows(orm, Trips);
await deleteRows(orm, TripMembers);
await deleteRows(orm, Days);
await deleteRows(orm, AuditLog);
await deleteRows(orm, Settings);
// 0b review L2 / security review F-B7: dead mock scaffolding — see
// budget.e2e.test.ts's identical comment.
checkPermission.mockReturnValue(true);
@@ -100,17 +116,17 @@ describe('Trips e2e (real auth guard + temp SQLite)', () => {
afterAll(async () => {
await app.close();
await orm.close();
});
const seedTrip = (title = 'T', userId = 1) =>
Number(db.prepare('INSERT INTO trips (user_id, title) VALUES (?, ?)').run(userId, title).lastInsertRowid);
const seedTrip = (title = 'T', userId = 1) => insertRow(orm, Trips, { user: userId, title });
it('401 without a cookie', async () => {
expect((await request(server).get('/api/trips')).status).toBe(401);
});
it('200 list (real TRIP_SELECT: is_owner + counts)', async () => {
const tripId = seedTrip('T');
const tripId = await seedTrip('T');
const res = await request(server).get('/api/trips').set('Cookie', sessionCookie(1));
expect(res.status).toBe(200);
expect(res.body.trips).toHaveLength(1);
@@ -122,18 +138,18 @@ describe('Trips e2e (real auth guard + temp SQLite)', () => {
expect(ok.status).toBe(201);
// The dateless create seeds the default 7 placeholder days.
expect(ok.body.trip).toMatchObject({ title: 'T', currency: 'EUR', day_count: 7, is_owner: 1 });
const dayRows = db.prepare('SELECT COUNT(*) AS n FROM days WHERE trip_id = ?').get(ok.body.trip.id) as { n: number };
expect(dayRows.n).toBe(7);
const dayRows = await countRows(orm, Days, { trip: ok.body.trip.id });
expect(dayRows).toBe(7);
// The DI-native AuditService wrote the real row (audit_log DDL above).
const audit = db.prepare("SELECT user_id FROM audit_log WHERE action = 'trip.create'").get() as { user_id: number };
expect(audit).toEqual({ user_id: 1 });
const audit = await findRow(orm, AuditLog, { action: 'trip.create' });
expect({ user_id: audit?.user_id }).toEqual({ user_id: 1 });
checkPermission.mockReturnValue(false);
const forbidden = await request(server).post('/api/trips').set('Cookie', sessionCookie(1)).send({ title: 'T' });
expect(forbidden.status).toBe(403);
});
it('201 create without a currency takes the display currency from the settings', async () => {
db.prepare("INSERT INTO settings (user_id, key, value) VALUES (1, 'default_currency', ?)").run(JSON.stringify('USD'));
await setUserSetting(orm, 1, 'default_currency', JSON.stringify('USD'));
const preferred = await request(server).post('/api/trips').set('Cookie', sessionCookie(1)).send({ title: 'Road trip' });
expect(preferred.status).toBe(201);
expect(preferred.body.trip).toMatchObject({ title: 'Road trip', currency: 'USD' });
@@ -148,9 +164,8 @@ describe('Trips e2e (real auth guard + temp SQLite)', () => {
.send({ title: 'Gap year', start_date: '2025-01-26', end_date: '2026-01-28' });
expect(res.status).toBe(201);
expect(res.body.trip).toMatchObject({ start_date: '2025-01-26', end_date: '2026-01-28', day_count: 368 });
const last = db.prepare('SELECT day_number, date FROM days WHERE trip_id = ? ORDER BY day_number DESC LIMIT 1')
.get(res.body.trip.id) as { day_number: number; date: string };
expect(last).toEqual({ day_number: 368, date: '2026-01-28' });
const [last] = await findRows(orm, Days, { trip: res.body.trip.id }, { day_number: 'desc' });
expect({ day_number: last.day_number, date: last.date }).toEqual({ day_number: 368, date: '2026-01-28' });
});
it('400 on a date range past MAX_TRIP_DAYS, for create and update alike', async () => {
@@ -158,7 +173,7 @@ describe('Trips e2e (real auth guard + temp SQLite)', () => {
.send({ title: 'Decade', start_date: '2026-01-01', end_date: '2036-01-01' });
expect(tooLong.status).toBe(400);
expect(tooLong.body).toEqual({ error: `A trip can span at most ${MAX_TRIP_DAYS} days` });
expect(db.prepare('SELECT COUNT(*) AS n FROM trips').get()).toEqual({ n: 0 });
expect(await countRows(orm, Trips)).toBe(0);
const week = await request(server).post('/api/trips').set('Cookie', sessionCookie(1))
.send({ title: 'Week', start_date: '2026-07-01', end_date: '2026-07-07' });
@@ -166,19 +181,19 @@ describe('Trips e2e (real auth guard + temp SQLite)', () => {
.send({ end_date: '2036-07-01' });
expect(stretched.status).toBe(400);
expect(stretched.body).toEqual({ error: `A trip can span at most ${MAX_TRIP_DAYS} days` });
expect(db.prepare('SELECT end_date FROM trips WHERE id = ?').get(week.body.trip.id)).toEqual({ end_date: '2026-07-07' });
expect((await findRow(orm, Trips, { id: week.body.trip.id }))!.end_date).toBe('2026-07-07');
});
it('200 update with an earlier end drops the last days, and the answer stays { trip }', async () => {
const week = await request(server).post('/api/trips').set('Cookie', sessionCookie(1))
.send({ title: 'Week', start_date: '2026-07-01', end_date: '2026-07-07' });
const kept = db.prepare('SELECT id FROM days WHERE trip_id = ? ORDER BY day_number LIMIT 5').all(week.body.trip.id);
const kept = (await dayIds(week.body.trip.id)).slice(0, 5);
const res = await request(server).put(`/api/trips/${week.body.trip.id}`).set('Cookie', sessionCookie(1))
.send({ end_date: '2026-07-05' });
expect(res.status).toBe(200);
expect(Object.keys(res.body)).toEqual(['trip']);
expect(res.body.trip).toMatchObject({ start_date: '2026-07-01', end_date: '2026-07-05', day_count: 5 });
expect(db.prepare('SELECT id FROM days WHERE trip_id = ? ORDER BY day_number').all(week.body.trip.id)).toEqual(kept);
expect(await dayIds(week.body.trip.id)).toEqual(kept);
});
it('404 on a missing trip', async () => {
@@ -189,8 +204,7 @@ describe('Trips e2e (real auth guard + temp SQLite)', () => {
describe('GET /active (startup destination)', () => {
const seedDated = (title: string, start: string, end: string) =>
Number(db.prepare('INSERT INTO trips (user_id, title, start_date, end_date) VALUES (1, ?, ?, ?)')
.run(title, start, end).lastInsertRowid);
insertRow(orm, Trips, { user: 1, title, start_date: start, end_date: end });
it('401 without a cookie', async () => {
expect((await request(server).get('/api/trips/active')).status).toBe(401);
@@ -199,7 +213,7 @@ describe('Trips e2e (real auth guard + temp SQLite)', () => {
// The literal route sits above @Get(':id'); if it ever slips below, this
// asks for a trip with the id "active" and comes back 404 instead.
it('resolves as its own route rather than as /api/trips/:id', async () => {
const running = seedDated('Running', '2000-01-01', '2999-12-31');
const running = await seedDated('Running', '2000-01-01', '2999-12-31');
const res = await request(server).get('/api/trips/active').set('Cookie', sessionCookie(1));
expect(res.status).toBe(200);
expect(res.body).toEqual({ trip: { id: running, title: 'Running', start_date: '2000-01-01', end_date: '2999-12-31' } });
@@ -212,7 +226,7 @@ describe('Trips e2e (real auth guard + temp SQLite)', () => {
});
it('carries no wide trip columns — it is read on first paint', async () => {
seedDated('Running', '2000-01-01', '2999-12-31');
await seedDated('Running', '2000-01-01', '2999-12-31');
const res = await request(server).get('/api/trips/active').set('Cookie', sessionCookie(1));
expect(Object.keys(res.body.trip).sort()).toEqual(['end_date', 'id', 'start_date', 'title']);
});
@@ -221,8 +235,7 @@ describe('Trips e2e (real auth guard + temp SQLite)', () => {
// Real CalendarService against the temp db: a title carrying U+3000 slipped
// through the old \s keep-class into setHeader and 500'd the export (#2165).
it('200 export.ics with a header-safe filename for a title full of ideographic whitespace', async () => {
const tripId = Number(db.prepare('INSERT INTO trips (user_id, title, start_date, end_date) VALUES (1, ?, ?, ?)')
.run('沖縄 4泊5日', '2026-05-01', '2026-05-05').lastInsertRowid);
const tripId = await insertRow(orm, Trips, { user: 1, title: '沖縄 4泊5日', start_date: '2026-05-01', end_date: '2026-05-05' });
const res = await request(server).get(`/api/trips/${tripId}/export.ics`).set('Cookie', sessionCookie(1));
expect(res.status).toBe(200);
expect(res.headers['content-type']).toContain('text/calendar');
@@ -231,14 +244,14 @@ describe('Trips e2e (real auth guard + temp SQLite)', () => {
});
it('200 bundle for an accessible trip (real member list)', async () => {
const tripId = seedTrip('B');
const tripId = await seedTrip('B');
const res = await request(server).get(`/api/trips/${tripId}/bundle`).set('Cookie', sessionCookie(1));
expect(res.status).toBe(200);
expect(res.body).toMatchObject({ trip: { id: tripId }, days: [], members: [{ id: 1, role: 'owner' }] });
});
it('200 delete cleans up synced journey entries (real SQL)', async () => {
const tripId = seedTrip('D');
const tripId = await seedTrip('D');
// Task 9 fix wave (M6) finding: the hand-rolled DDL this test used to run
// against had no NOT NULL/FK constraints on `journey_entries` at all
// (no `author_id`, no `entry_date`, no FK to a real `journeys` row) — a
@@ -249,20 +262,18 @@ describe('Trips e2e (real auth guard + temp SQLite)', () => {
// NULL — a real journey row (and those columns) are seeded here so the
// insert that used to pass for the wrong reason now passes for the real
// one. The assertions below are untouched, character-for-character.
const journeyId = Number(db.prepare(
"INSERT INTO journeys (user_id, title, created_at, updated_at) VALUES (1, 'J', 0, 0)",
).run().lastInsertRowid);
db.prepare(
"INSERT INTO journey_entries (journey_id, source_trip_id, author_id, type, entry_date, created_at, updated_at) VALUES (?, ?, 1, 'skeleton', '2026-01-01', 0, 0)",
).run(journeyId, tripId);
const filledId = Number(db.prepare(
"INSERT INTO journey_entries (journey_id, source_trip_id, author_id, type, entry_date, created_at, updated_at) VALUES (?, ?, 1, 'story', '2026-01-01', 0, 0)",
).run(journeyId, tripId).lastInsertRowid);
const journeyId = await insertRow(orm, Journeys, { user: 1, title: 'J', created_at: 0, updated_at: 0 });
await insertRow(orm, JourneyEntries, {
journey: journeyId, sourceTrip: tripId, author: 1, type: 'skeleton', entry_date: '2026-01-01', created_at: 0, updated_at: 0,
});
const filledId = await insertRow(orm, JourneyEntries, {
journey: journeyId, sourceTrip: tripId, author: 1, type: 'story', entry_date: '2026-01-01', created_at: 0, updated_at: 0,
});
const res = await request(server).delete(`/api/trips/${tripId}`).set('Cookie', sessionCookie(1));
expect(res.status).toBe(200);
expect(res.body).toEqual({ success: true });
expect(db.prepare('SELECT id FROM trips WHERE id = ?').get(tripId)).toBeUndefined();
expect(db.prepare("SELECT id FROM journey_entries WHERE type = 'skeleton'").get()).toBeUndefined();
expect((db.prepare('SELECT source_trip_id FROM journey_entries WHERE id = ?').get(filledId) as { source_trip_id: number | null }).source_trip_id).toBeNull();
expect(await findRow(orm, Trips, { id: tripId })).toBeNull();
expect(await findRow(orm, JourneyEntries, { type: 'skeleton' })).toBeNull();
expect((await findRow(orm, JourneyEntries, { id: filledId }))!.source_trip_id).toBeNull();
});
});