mirror of
https://github.com/mauriceboe/TREK.git
synced 2026-06-20 22:01:45 +00:00
Migrate TREK 3 to NestJS + React 19 with a shared Zod contract layer
Brownfield strangler migration of the backend onto NestJS modules (auth, trips, days, places, assignments, packing, todo, budget, reservations, collab, files, photos, journey, share, settings, backup, oidc, oauth, admin, atlas, vacay, weather, airports, maps, categories, tags, notifications, system-notices) served through a per-prefix dispatcher, keeping the existing SQLite/better-sqlite3 DB and JWT httpOnly cookie auth, with behavioural parity for every route. Client: React 19 upgrade, "page = wiring container + data hook" pattern across all pages, per-domain Zustand stores bound to @trek/shared contracts, and decomposition of the large components (DayPlanSidebar, PackingListPanel, CollabNotes, FileManager, MemoriesPanel, PlacesSidebar, CollabChat, SystemNoticeModal, BudgetPanel, PlaceFormModal, ...) into focused render units backed by in-file hooks. Apply the shared global request pipeline (helmet/CSP, CORS, HSTS, forced HTTPS, the global MFA policy and request logging) to the NestJS instance as well, so a migrated route is protected identically to the legacy fallback rather than bypassing it.
This commit is contained in:
@@ -0,0 +1,99 @@
|
||||
/**
|
||||
* Admin e2e — exercises the migrated /api/admin endpoints through the real
|
||||
* JwtAuthGuard + AdminGuard against a temp SQLite db. The admin service +
|
||||
* helpers are mocked; this focuses on auth (401), the admin gate (403 for a
|
||||
* non-admin), create-201, validation 400 and the dev-only 404.
|
||||
*/
|
||||
import { describe, it, expect, beforeAll, afterAll, beforeEach, 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';
|
||||
|
||||
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);`);
|
||||
return { db: tmp };
|
||||
});
|
||||
|
||||
vi.mock('../../src/db/database', () => ({ db, closeDb: () => {}, reinitialize: () => {} }));
|
||||
vi.mock('../../src/services/auditLog', () => ({ writeAudit: vi.fn(), getClientIp: () => '1.2.3.4', logInfo: vi.fn() }));
|
||||
vi.mock('../../src/mcp', () => ({ invalidateMcpSessions: vi.fn() }));
|
||||
vi.mock('../../src/services/notificationPreferencesService', () => ({ getPreferencesMatrix: vi.fn(() => ({})), setAdminPreferences: vi.fn() }));
|
||||
vi.mock('../../src/services/settingsService', () => ({ getAdminUserDefaults: vi.fn(() => ({})), setAdminUserDefaults: vi.fn() }));
|
||||
vi.mock('../../src/services/notificationService', () => ({ send: vi.fn().mockResolvedValue(undefined) }));
|
||||
|
||||
const { adminSvc } = vi.hoisted(() => ({
|
||||
adminSvc: { listUsers: vi.fn(), createUser: vi.fn(), updatePlacesPhotos: vi.fn() },
|
||||
}));
|
||||
vi.mock('../../src/services/adminService', () => adminSvc);
|
||||
|
||||
import { AdminModule } from '../../src/nest/admin/admin.module';
|
||||
import { TrekExceptionFilter } from '../../src/nest/common/trek-exception.filter';
|
||||
|
||||
describe('Admin e2e (real auth + admin guard + temp SQLite)', () => {
|
||||
let server: Server;
|
||||
let app: Awaited<ReturnType<typeof build>>;
|
||||
|
||||
async function build() {
|
||||
const moduleRef = await Test.createTestingModule({ imports: [AdminModule] }).compile();
|
||||
const nest = moduleRef.createNestApplication();
|
||||
nest.use(cookieParser());
|
||||
nest.useGlobalFilters(new TrekExceptionFilter());
|
||||
await nest.init();
|
||||
return nest;
|
||||
}
|
||||
|
||||
beforeAll(async () => {
|
||||
seedUser(db as never, { id: 1, role: 'admin', email: 'admin@example.test' });
|
||||
seedUser(db as never, { id: 2, role: 'user', email: 'member@example.test' });
|
||||
app = await build();
|
||||
server = app.getHttpServer();
|
||||
adminSvc.listUsers.mockReturnValue([{ id: 1 }]);
|
||||
});
|
||||
|
||||
beforeEach(() => { delete process.env.NODE_ENV; });
|
||||
|
||||
afterAll(async () => {
|
||||
await app.close();
|
||||
});
|
||||
|
||||
it('401 without a session', async () => {
|
||||
expect((await request(server).get('/api/admin/users')).status).toBe(401);
|
||||
});
|
||||
|
||||
it('403 for a non-admin', async () => {
|
||||
const res = await request(server).get('/api/admin/users').set('Cookie', sessionCookie(2));
|
||||
expect(res.status).toBe(403);
|
||||
expect(res.body).toEqual({ error: 'Admin access required' });
|
||||
});
|
||||
|
||||
it('200 list for an admin', async () => {
|
||||
const res = await request(server).get('/api/admin/users').set('Cookie', sessionCookie(1));
|
||||
expect(res.status).toBe(200);
|
||||
expect(res.body).toEqual({ users: [{ id: 1 }] });
|
||||
});
|
||||
|
||||
it('201 on user create', async () => {
|
||||
adminSvc.createUser.mockReturnValue({ user: { id: 3 }, insertedId: 3, auditDetails: {} });
|
||||
const res = await request(server).post('/api/admin/users').set('Cookie', sessionCookie(1)).send({ email: 'new@x.y' });
|
||||
expect(res.status).toBe(201);
|
||||
expect(res.body).toEqual({ user: { id: 3 } });
|
||||
});
|
||||
|
||||
it('400 on a non-boolean feature toggle', async () => {
|
||||
const res = await request(server).put('/api/admin/places-photos').set('Cookie', sessionCookie(1)).send({ enabled: 'yes' });
|
||||
expect(res.status).toBe(400);
|
||||
expect(res.body).toEqual({ error: 'enabled must be a boolean' });
|
||||
});
|
||||
|
||||
it('404 on the dev-only test-notification outside development', async () => {
|
||||
const res = await request(server).post('/api/admin/dev/test-notification').set('Cookie', sessionCookie(1)).send({});
|
||||
expect(res.status).toBe(404);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,95 @@
|
||||
/**
|
||||
* Airports module e2e — exercises the migrated /api/airports endpoints through
|
||||
* the real JwtAuthGuard against a temp SQLite db (seeded via the shared harness).
|
||||
* The airport service is mocked so the test doesn't depend on the bundled dataset.
|
||||
*/
|
||||
import { describe, it, expect, beforeAll, 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';
|
||||
|
||||
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);`);
|
||||
return { db: tmp };
|
||||
});
|
||||
|
||||
vi.mock('../../src/db/database', () => ({ db, closeDb: () => {}, reinitialize: () => {} }));
|
||||
|
||||
const { mockSearch, mockFindByIata } = vi.hoisted(() => ({ mockSearch: vi.fn(), mockFindByIata: vi.fn() }));
|
||||
vi.mock('../../src/services/airportService', async (importActual) => {
|
||||
const actual = await importActual<typeof import('../../src/services/airportService')>();
|
||||
return { ...actual, searchAirports: mockSearch, findByIata: mockFindByIata };
|
||||
});
|
||||
|
||||
import { AirportsModule } from '../../src/nest/airports/airports.module';
|
||||
import { TrekExceptionFilter } from '../../src/nest/common/trek-exception.filter';
|
||||
|
||||
const BER = {
|
||||
iata: 'BER', icao: 'EDDB', name: 'Berlin Brandenburg', city: 'Berlin',
|
||||
country: 'DE', lat: 52.36, lng: 13.5, tz: 'Europe/Berlin',
|
||||
};
|
||||
|
||||
describe('Airports e2e (real auth guard + temp SQLite)', () => {
|
||||
let server: Server;
|
||||
let app: Awaited<ReturnType<typeof build>>;
|
||||
|
||||
async function build() {
|
||||
const moduleRef = await Test.createTestingModule({ imports: [AirportsModule] }).compile();
|
||||
const nest = moduleRef.createNestApplication();
|
||||
nest.use(cookieParser());
|
||||
nest.useGlobalFilters(new TrekExceptionFilter());
|
||||
await nest.init();
|
||||
return nest;
|
||||
}
|
||||
|
||||
beforeAll(async () => {
|
||||
seedUser(db as never, { id: 1 });
|
||||
app = await build();
|
||||
server = app.getHttpServer();
|
||||
mockSearch.mockReturnValue([BER]);
|
||||
mockFindByIata.mockImplementation((code: string) => (code === 'BER' ? BER : null));
|
||||
});
|
||||
|
||||
afterAll(async () => {
|
||||
await app.close();
|
||||
});
|
||||
|
||||
it('401 { error, code } without a session cookie', async () => {
|
||||
const res = await request(server).get('/api/airports/search').query({ q: 'ber' });
|
||||
expect(res.status).toBe(401);
|
||||
expect(res.body).toEqual({ error: 'Access token required', code: 'AUTH_REQUIRED' });
|
||||
});
|
||||
|
||||
it('200 with results for a query', async () => {
|
||||
const res = await request(server).get('/api/airports/search').set('Cookie', sessionCookie(1)).query({ q: 'ber' });
|
||||
expect(res.status).toBe(200);
|
||||
expect(res.body).toEqual([BER]);
|
||||
});
|
||||
|
||||
it('200 [] for a missing query without hitting the service', async () => {
|
||||
mockSearch.mockClear();
|
||||
const res = await request(server).get('/api/airports/search').set('Cookie', sessionCookie(1));
|
||||
expect(res.status).toBe(200);
|
||||
expect(res.body).toEqual([]);
|
||||
expect(mockSearch).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('200 for a known IATA code', async () => {
|
||||
const res = await request(server).get('/api/airports/BER').set('Cookie', sessionCookie(1));
|
||||
expect(res.status).toBe(200);
|
||||
expect(res.body).toEqual(BER);
|
||||
});
|
||||
|
||||
it('404 { error } for an unknown IATA code', async () => {
|
||||
const res = await request(server).get('/api/airports/ZZZ').set('Cookie', sessionCookie(1));
|
||||
expect(res.status).toBe(404);
|
||||
expect(res.body).toEqual({ error: 'Airport not found' });
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,109 @@
|
||||
/**
|
||||
* Assignments module e2e — exercises both migrated controllers through the real
|
||||
* JwtAuthGuard against a temp SQLite db. assignmentService, journeyService,
|
||||
* the permission check, canAccessTrip and the WebSocket broadcast are mocked.
|
||||
*/
|
||||
import { describe, it, expect, beforeAll, afterAll, beforeEach, 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';
|
||||
|
||||
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);`);
|
||||
return { db: tmp };
|
||||
});
|
||||
|
||||
const { canAccessTrip } = vi.hoisted(() => ({ canAccessTrip: vi.fn() }));
|
||||
vi.mock('../../src/db/database', () => ({
|
||||
db, canAccessTrip, isOwner: vi.fn(() => true), getPlaceWithTags: vi.fn(), closeDb: () => {}, reinitialize: () => {},
|
||||
}));
|
||||
vi.mock('../../src/websocket', () => ({ broadcast: vi.fn() }));
|
||||
vi.mock('../../src/services/journeyService', () => ({ onPlaceCreated: vi.fn() }));
|
||||
|
||||
const { checkPermission } = vi.hoisted(() => ({ checkPermission: vi.fn() }));
|
||||
vi.mock('../../src/services/permissions', () => ({ checkPermission }));
|
||||
|
||||
const { asg } = vi.hoisted(() => ({
|
||||
asg: {
|
||||
getAssignmentWithPlace: vi.fn(), listDayAssignments: vi.fn(), dayExists: vi.fn(), placeExists: vi.fn(),
|
||||
createAssignment: vi.fn(), assignmentExistsInDay: vi.fn(), deleteAssignment: vi.fn(), reorderAssignments: vi.fn(),
|
||||
getAssignmentForTrip: vi.fn(), moveAssignment: vi.fn(), getParticipants: vi.fn(), updateTime: vi.fn(), setParticipants: vi.fn(),
|
||||
},
|
||||
}));
|
||||
vi.mock('../../src/services/assignmentService', () => asg);
|
||||
|
||||
import { AssignmentsModule } from '../../src/nest/assignments/assignments.module';
|
||||
import { TrekExceptionFilter } from '../../src/nest/common/trek-exception.filter';
|
||||
|
||||
describe('Assignments e2e (real auth guard + temp SQLite)', () => {
|
||||
let server: Server;
|
||||
let app: Awaited<ReturnType<typeof build>>;
|
||||
|
||||
async function build() {
|
||||
const moduleRef = await Test.createTestingModule({ imports: [AssignmentsModule] }).compile();
|
||||
const nest = moduleRef.createNestApplication();
|
||||
nest.use(cookieParser());
|
||||
nest.useGlobalFilters(new TrekExceptionFilter());
|
||||
await nest.init();
|
||||
return nest;
|
||||
}
|
||||
|
||||
beforeAll(async () => {
|
||||
seedUser(db as never, { id: 1 });
|
||||
app = await build();
|
||||
server = app.getHttpServer();
|
||||
asg.listDayAssignments.mockReturnValue([{ id: 1 }]);
|
||||
asg.createAssignment.mockReturnValue({ id: 9 });
|
||||
asg.getParticipants.mockReturnValue([{ user_id: 2 }]);
|
||||
});
|
||||
|
||||
beforeEach(() => {
|
||||
canAccessTrip.mockReturnValue({ id: 5, user_id: 1 });
|
||||
checkPermission.mockReturnValue(true);
|
||||
asg.dayExists.mockReturnValue(true);
|
||||
asg.placeExists.mockReturnValue(true);
|
||||
});
|
||||
|
||||
afterAll(async () => {
|
||||
await app.close();
|
||||
});
|
||||
|
||||
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 res = await request(server).get('/api/trips/5/days/3/assignments').set('Cookie', sessionCookie(1));
|
||||
expect(res.status).toBe(200);
|
||||
expect(res.body).toEqual({ assignments: [{ id: 1 }] });
|
||||
});
|
||||
|
||||
it('201 create, 404 place', async () => {
|
||||
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).toEqual({ assignment: { id: 9 } });
|
||||
asg.placeExists.mockReturnValue(false);
|
||||
const miss = await request(server).post('/api/trips/5/days/3/assignments').set('Cookie', sessionCookie(1)).send({ place_id: 99 });
|
||||
expect(miss.status).toBe(404);
|
||||
expect(miss.body).toEqual({ error: 'Place not found' });
|
||||
});
|
||||
|
||||
it('200 participants (access-only)', async () => {
|
||||
const res = await request(server).get('/api/trips/5/assignments/9/participants').set('Cookie', sessionCookie(1));
|
||||
expect(res.status).toBe(200);
|
||||
expect(res.body).toEqual({ participants: [{ user_id: 2 }] });
|
||||
});
|
||||
|
||||
it('400 set participants with non-array', async () => {
|
||||
const res = await request(server).put('/api/trips/5/assignments/9/participants').set('Cookie', sessionCookie(1)).send({ user_ids: 'no' });
|
||||
expect(res.status).toBe(400);
|
||||
expect(res.body).toEqual({ error: 'user_ids must be an array' });
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,124 @@
|
||||
/**
|
||||
* Atlas module e2e — exercises the migrated /api/addons/atlas endpoints through
|
||||
* the real JwtAuthGuard against a temp SQLite db. atlasService is mocked; this
|
||||
* focuses on auth, status codes (mark POSTs stay 200), the cache headers and the
|
||||
* bespoke 400/404 bodies.
|
||||
*/
|
||||
import { describe, it, expect, beforeAll, 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';
|
||||
|
||||
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);`);
|
||||
return { db: tmp };
|
||||
});
|
||||
|
||||
vi.mock('../../src/db/database', () => ({ db, closeDb: () => {}, reinitialize: () => {} }));
|
||||
|
||||
const { mocks } = vi.hoisted(() => ({
|
||||
mocks: {
|
||||
getStats: vi.fn(),
|
||||
getCountryPlaces: vi.fn(),
|
||||
markCountryVisited: vi.fn(),
|
||||
unmarkCountryVisited: vi.fn(),
|
||||
markRegionVisited: vi.fn(),
|
||||
unmarkRegionVisited: vi.fn(),
|
||||
getVisitedRegions: vi.fn(),
|
||||
getRegionGeo: vi.fn(),
|
||||
listBucketList: vi.fn(),
|
||||
createBucketItem: vi.fn(),
|
||||
updateBucketItem: vi.fn(),
|
||||
deleteBucketItem: vi.fn(),
|
||||
},
|
||||
}));
|
||||
vi.mock('../../src/services/atlasService', () => mocks);
|
||||
|
||||
import { AtlasModule } from '../../src/nest/atlas/atlas.module';
|
||||
import { TrekExceptionFilter } from '../../src/nest/common/trek-exception.filter';
|
||||
|
||||
describe('Atlas e2e (real auth guard + temp SQLite)', () => {
|
||||
let server: Server;
|
||||
let app: Awaited<ReturnType<typeof build>>;
|
||||
|
||||
async function build() {
|
||||
const moduleRef = await Test.createTestingModule({ imports: [AtlasModule] }).compile();
|
||||
const nest = moduleRef.createNestApplication();
|
||||
nest.use(cookieParser());
|
||||
nest.useGlobalFilters(new TrekExceptionFilter());
|
||||
await nest.init();
|
||||
return nest;
|
||||
}
|
||||
|
||||
beforeAll(async () => {
|
||||
seedUser(db as never, { id: 1 });
|
||||
app = await build();
|
||||
server = app.getHttpServer();
|
||||
mocks.getStats.mockResolvedValue({ countries: 3 });
|
||||
mocks.markCountryVisited.mockReturnValue(undefined);
|
||||
mocks.listBucketList.mockReturnValue([{ id: 1, name: 'Tokyo' }]);
|
||||
});
|
||||
|
||||
afterAll(async () => {
|
||||
await app.close();
|
||||
});
|
||||
|
||||
it('401 without a session cookie', async () => {
|
||||
const res = await request(server).get('/api/addons/atlas/stats');
|
||||
expect(res.status).toBe(401);
|
||||
});
|
||||
|
||||
it('200 stats for an authenticated user', async () => {
|
||||
const res = await request(server).get('/api/addons/atlas/stats').set('Cookie', sessionCookie(1));
|
||||
expect(res.status).toBe(200);
|
||||
expect(res.body).toEqual({ countries: 3 });
|
||||
});
|
||||
|
||||
it('200 (not 201) on POST country mark, with upper-cased code', async () => {
|
||||
const res = await request(server).post('/api/addons/atlas/country/de/mark').set('Cookie', sessionCookie(1));
|
||||
expect(res.status).toBe(200);
|
||||
expect(res.body).toEqual({ success: true });
|
||||
expect(mocks.markCountryVisited).toHaveBeenCalledWith(1, 'DE');
|
||||
});
|
||||
|
||||
it('400 on region mark without name/country_code', async () => {
|
||||
const res = await request(server).post('/api/addons/atlas/region/by/mark').set('Cookie', sessionCookie(1)).send({ name: 'Bavaria' });
|
||||
expect(res.status).toBe(400);
|
||||
expect(res.body).toEqual({ error: 'name and country_code are required' });
|
||||
});
|
||||
|
||||
it('no-store cache header on /regions', async () => {
|
||||
mocks.getVisitedRegions.mockResolvedValue({ regions: {} });
|
||||
const res = await request(server).get('/api/addons/atlas/regions').set('Cookie', sessionCookie(1));
|
||||
expect(res.status).toBe(200);
|
||||
expect(res.headers['cache-control']).toBe('no-cache, no-store');
|
||||
});
|
||||
|
||||
it('empty FeatureCollection (no cache header) when /regions/geo has no countries', async () => {
|
||||
const res = await request(server).get('/api/addons/atlas/regions/geo').set('Cookie', sessionCookie(1));
|
||||
expect(res.status).toBe(200);
|
||||
expect(res.body).toEqual({ type: 'FeatureCollection', features: [] });
|
||||
expect(res.headers['cache-control']).toBeUndefined();
|
||||
});
|
||||
|
||||
it('201 on bucket-list create', async () => {
|
||||
mocks.createBucketItem.mockReturnValue({ id: 2, name: 'Kyoto' });
|
||||
const res = await request(server).post('/api/addons/atlas/bucket-list').set('Cookie', sessionCookie(1)).send({ name: 'Kyoto' });
|
||||
expect(res.status).toBe(201);
|
||||
expect(res.body).toEqual({ item: { id: 2, name: 'Kyoto' } });
|
||||
});
|
||||
|
||||
it('404 on delete of a missing bucket item', async () => {
|
||||
mocks.deleteBucketItem.mockReturnValue(false);
|
||||
const res = await request(server).delete('/api/addons/atlas/bucket-list/9').set('Cookie', sessionCookie(1));
|
||||
expect(res.status).toBe(404);
|
||||
expect(res.body).toEqual({ error: 'Item not found' });
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,108 @@
|
||||
/**
|
||||
* Auth e2e — exercises the migrated /api/auth endpoints through the real
|
||||
* JwtAuthGuard/OptionalJwtGuard AND the real cookie service against a temp
|
||||
* SQLite db. Only the authService (credential/MFA logic) + audit/notifications
|
||||
* are mocked; this proves the httpOnly trek_session cookie is set on login and
|
||||
* cleared on logout, that /me requires a session, and that /app-config is
|
||||
* optional-auth.
|
||||
*/
|
||||
import { describe, it, expect, beforeAll, afterAll, beforeEach, 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';
|
||||
|
||||
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);`);
|
||||
return { db: tmp };
|
||||
});
|
||||
|
||||
vi.mock('../../src/db/database', () => ({ db, closeDb: () => {}, reinitialize: () => {} }));
|
||||
vi.mock('../../src/services/auditLog', () => ({ writeAudit: vi.fn(), getClientIp: vi.fn(() => '1.2.3.4') }));
|
||||
vi.mock('../../src/services/notifications', () => ({ getAppUrl: () => 'https://x', sendPasswordResetEmail: vi.fn().mockResolvedValue({ delivered: true }) }));
|
||||
|
||||
const { authSvc } = vi.hoisted(() => ({
|
||||
authSvc: {
|
||||
getAppConfig: vi.fn(), demoLogin: vi.fn(), validateInviteToken: vi.fn(), registerUser: vi.fn(), loginUser: vi.fn(),
|
||||
requestPasswordReset: vi.fn(), resetPassword: vi.fn(), verifyMfaLogin: vi.fn(), getCurrentUser: vi.fn(),
|
||||
changePassword: vi.fn(), deleteAccount: vi.fn(), updateMapsKey: vi.fn(), updateApiKeys: vi.fn(), updateSettings: vi.fn(),
|
||||
getSettings: vi.fn(), saveAvatar: vi.fn(), deleteAvatar: vi.fn(), listUsers: vi.fn(), validateKeys: vi.fn(),
|
||||
getAppSettings: vi.fn(), updateAppSettings: vi.fn(), getTravelStats: vi.fn(), setupMfa: vi.fn(), enableMfa: vi.fn(),
|
||||
disableMfa: vi.fn(), listMcpTokens: vi.fn(), createMcpToken: vi.fn(), deleteMcpToken: vi.fn(), createWsToken: vi.fn(),
|
||||
createResourceToken: vi.fn(),
|
||||
},
|
||||
}));
|
||||
vi.mock('../../src/services/authService', () => authSvc);
|
||||
|
||||
import { AuthModule } from '../../src/nest/auth/auth.module';
|
||||
import { TrekExceptionFilter } from '../../src/nest/common/trek-exception.filter';
|
||||
|
||||
describe('Auth e2e (real auth guard + real cookie service + temp SQLite)', () => {
|
||||
let server: Server;
|
||||
let app: Awaited<ReturnType<typeof build>>;
|
||||
|
||||
async function build() {
|
||||
const moduleRef = await Test.createTestingModule({ imports: [AuthModule] }).compile();
|
||||
const nest = moduleRef.createNestApplication();
|
||||
nest.use(cookieParser());
|
||||
nest.useGlobalFilters(new TrekExceptionFilter());
|
||||
await nest.init();
|
||||
return nest;
|
||||
}
|
||||
|
||||
beforeAll(async () => {
|
||||
seedUser(db as never, { id: 1, email: 'u@example.test' });
|
||||
app = await build();
|
||||
server = app.getHttpServer();
|
||||
authSvc.getAppConfig.mockReturnValue({ version: '3' });
|
||||
authSvc.loginUser.mockReturnValue({ token: 'jwt.token.value', user: { id: 1 } });
|
||||
authSvc.getCurrentUser.mockReturnValue({ id: 1, email: 'u@example.test' });
|
||||
});
|
||||
|
||||
beforeEach(() => vi.clearAllMocks());
|
||||
|
||||
afterAll(async () => {
|
||||
await app.close();
|
||||
});
|
||||
|
||||
it('GET /app-config is optional-auth (200 without a cookie)', async () => {
|
||||
authSvc.getAppConfig.mockReturnValue({ version: '3' });
|
||||
const res = await request(server).get('/api/auth/app-config');
|
||||
expect(res.status).toBe(200);
|
||||
expect(res.body).toEqual({ version: '3' });
|
||||
});
|
||||
|
||||
it('GET /me requires a session (401 without a cookie)', async () => {
|
||||
expect((await request(server).get('/api/auth/me')).status).toBe(401);
|
||||
});
|
||||
|
||||
it('GET /me returns the user with a valid session', async () => {
|
||||
authSvc.getCurrentUser.mockReturnValue({ id: 1, email: 'u@example.test' });
|
||||
const res = await request(server).get('/api/auth/me').set('Cookie', sessionCookie(1));
|
||||
expect(res.status).toBe(200);
|
||||
expect(res.body).toEqual({ user: { id: 1, email: 'u@example.test' } });
|
||||
});
|
||||
|
||||
it('POST /login sets the httpOnly trek_session cookie', async () => {
|
||||
authSvc.loginUser.mockReturnValue({ token: 'jwt.token.value', user: { id: 1 } });
|
||||
const res = await request(server).post('/api/auth/login').send({ email: 'u@example.test', password: 'pw' });
|
||||
expect(res.status).toBe(200);
|
||||
expect(res.body).toEqual({ token: 'jwt.token.value', user: { id: 1 } });
|
||||
const setCookie = res.headers['set-cookie'] as unknown as string[];
|
||||
expect(setCookie.some((c) => c.startsWith('trek_session=') && /HttpOnly/i.test(c))).toBe(true);
|
||||
}, 10000);
|
||||
|
||||
it('POST /logout clears the session cookie', async () => {
|
||||
const res = await request(server).post('/api/auth/logout');
|
||||
expect(res.status).toBe(200);
|
||||
expect(res.body).toEqual({ success: true });
|
||||
const setCookie = res.headers['set-cookie'] as unknown as string[];
|
||||
expect(setCookie.some((c) => c.startsWith('trek_session='))).toBe(true);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,108 @@
|
||||
/**
|
||||
* Backup e2e — exercises the migrated /api/backup endpoints through the real
|
||||
* JwtAuthGuard + AdminGuard against a temp SQLite db. The backup service +
|
||||
* audit log are mocked; this focuses on auth (401), the admin gate (403 for a
|
||||
* non-admin), the rate-limit 429, filename guards and status codes.
|
||||
*/
|
||||
import { describe, it, expect, beforeAll, afterAll, beforeEach, 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';
|
||||
|
||||
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);`);
|
||||
return { db: tmp };
|
||||
});
|
||||
|
||||
vi.mock('../../src/db/database', () => ({ db, closeDb: () => {}, reinitialize: () => {} }));
|
||||
vi.mock('../../src/services/auditLog', () => ({ writeAudit: vi.fn(), getClientIp: vi.fn(() => '1.2.3.4') }));
|
||||
|
||||
const { backupSvc } = vi.hoisted(() => ({
|
||||
backupSvc: {
|
||||
listBackups: vi.fn(), createBackup: vi.fn(), restoreFromZip: vi.fn(), getAutoSettings: vi.fn(),
|
||||
updateAutoSettings: vi.fn(), deleteBackup: vi.fn(), isValidBackupFilename: vi.fn(), backupFilePath: vi.fn(),
|
||||
backupFileExists: vi.fn(), checkRateLimit: vi.fn(), getUploadTmpDir: () => '/tmp', BACKUP_RATE_WINDOW: 3600000,
|
||||
MAX_BACKUP_UPLOAD_SIZE: 1024,
|
||||
},
|
||||
}));
|
||||
vi.mock('../../src/services/backupService', () => backupSvc);
|
||||
|
||||
import { BackupModule } from '../../src/nest/backup/backup.module';
|
||||
import { TrekExceptionFilter } from '../../src/nest/common/trek-exception.filter';
|
||||
|
||||
describe('Backup e2e (real auth + admin guard + temp SQLite)', () => {
|
||||
let server: Server;
|
||||
let app: Awaited<ReturnType<typeof build>>;
|
||||
|
||||
async function build() {
|
||||
const moduleRef = await Test.createTestingModule({ imports: [BackupModule] }).compile();
|
||||
const nest = moduleRef.createNestApplication();
|
||||
nest.use(cookieParser());
|
||||
nest.useGlobalFilters(new TrekExceptionFilter());
|
||||
await nest.init();
|
||||
return nest;
|
||||
}
|
||||
|
||||
beforeAll(async () => {
|
||||
seedUser(db as never, { id: 1, role: 'admin', email: 'admin@example.test' });
|
||||
seedUser(db as never, { id: 2, role: 'user', email: 'member@example.test' });
|
||||
app = await build();
|
||||
server = app.getHttpServer();
|
||||
backupSvc.listBackups.mockReturnValue([{ filename: 'a.zip', size: 1 }]);
|
||||
backupSvc.createBackup.mockResolvedValue({ filename: 'b.zip', size: 10 });
|
||||
});
|
||||
|
||||
beforeEach(() => {
|
||||
backupSvc.isValidBackupFilename.mockReturnValue(true);
|
||||
backupSvc.backupFileExists.mockReturnValue(true);
|
||||
backupSvc.checkRateLimit.mockReturnValue(true);
|
||||
});
|
||||
|
||||
afterAll(async () => {
|
||||
await app.close();
|
||||
});
|
||||
|
||||
it('401 without a session cookie', async () => {
|
||||
expect((await request(server).get('/api/backup/list')).status).toBe(401);
|
||||
});
|
||||
|
||||
it('403 for a non-admin', async () => {
|
||||
const res = await request(server).get('/api/backup/list').set('Cookie', sessionCookie(2));
|
||||
expect(res.status).toBe(403);
|
||||
expect(res.body).toEqual({ error: 'Admin access required' });
|
||||
});
|
||||
|
||||
it('200 list for an admin', async () => {
|
||||
const res = await request(server).get('/api/backup/list').set('Cookie', sessionCookie(1));
|
||||
expect(res.status).toBe(200);
|
||||
expect(res.body).toEqual({ backups: [{ filename: 'a.zip', size: 1 }] });
|
||||
});
|
||||
|
||||
it('429 when create is rate-limited', async () => {
|
||||
backupSvc.checkRateLimit.mockReturnValue(false);
|
||||
const res = await request(server).post('/api/backup/create').set('Cookie', sessionCookie(1));
|
||||
expect(res.status).toBe(429);
|
||||
expect(res.body).toEqual({ error: 'Too many backup requests. Please try again later.' });
|
||||
});
|
||||
|
||||
it('400 on an invalid download filename', async () => {
|
||||
backupSvc.isValidBackupFilename.mockReturnValue(false);
|
||||
const res = await request(server).get('/api/backup/download/bad').set('Cookie', sessionCookie(1));
|
||||
expect(res.status).toBe(400);
|
||||
expect(res.body).toEqual({ error: 'Invalid filename' });
|
||||
});
|
||||
|
||||
it('404 deleting a missing backup', async () => {
|
||||
backupSvc.backupFileExists.mockReturnValue(false);
|
||||
const res = await request(server).delete('/api/backup/x.zip').set('Cookie', sessionCookie(1));
|
||||
expect(res.status).toBe(404);
|
||||
expect(res.body).toEqual({ error: 'Backup not found' });
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,107 @@
|
||||
/**
|
||||
* Budget module e2e — exercises the migrated /api/trips/:tripId/budget endpoints
|
||||
* through the real JwtAuthGuard against a temp SQLite db. budgetService, the
|
||||
* permission check and the WebSocket broadcast are mocked.
|
||||
*/
|
||||
import { describe, it, expect, beforeAll, afterAll, beforeEach, 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';
|
||||
|
||||
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);`);
|
||||
return { db: tmp };
|
||||
});
|
||||
|
||||
vi.mock('../../src/db/database', () => ({ db, closeDb: () => {}, reinitialize: () => {} }));
|
||||
vi.mock('../../src/websocket', () => ({ broadcast: vi.fn() }));
|
||||
|
||||
const { checkPermission } = vi.hoisted(() => ({ checkPermission: vi.fn() }));
|
||||
vi.mock('../../src/services/permissions', () => ({ checkPermission }));
|
||||
|
||||
const { svc } = vi.hoisted(() => ({
|
||||
svc: {
|
||||
verifyTripAccess: vi.fn(), listBudgetItems: vi.fn(), createBudgetItem: vi.fn(), updateBudgetItem: vi.fn(),
|
||||
deleteBudgetItem: vi.fn(), updateMembers: vi.fn(), toggleMemberPaid: vi.fn(), getPerPersonSummary: vi.fn(),
|
||||
calculateSettlement: vi.fn(), reorderBudgetItems: vi.fn(), reorderBudgetCategories: vi.fn(),
|
||||
},
|
||||
}));
|
||||
vi.mock('../../src/services/budgetService', () => svc);
|
||||
|
||||
import { BudgetModule } from '../../src/nest/budget/budget.module';
|
||||
import { TrekExceptionFilter } from '../../src/nest/common/trek-exception.filter';
|
||||
|
||||
describe('Budget e2e (real auth guard + temp SQLite)', () => {
|
||||
let server: Server;
|
||||
let app: Awaited<ReturnType<typeof build>>;
|
||||
|
||||
async function build() {
|
||||
const moduleRef = await Test.createTestingModule({ imports: [BudgetModule] }).compile();
|
||||
const nest = moduleRef.createNestApplication();
|
||||
nest.use(cookieParser());
|
||||
nest.useGlobalFilters(new TrekExceptionFilter());
|
||||
await nest.init();
|
||||
return nest;
|
||||
}
|
||||
|
||||
beforeAll(async () => {
|
||||
seedUser(db as never, { id: 1 });
|
||||
app = await build();
|
||||
server = app.getHttpServer();
|
||||
svc.listBudgetItems.mockReturnValue([{ id: 1, name: 'Hotel' }]);
|
||||
svc.createBudgetItem.mockReturnValue({ id: 9, name: 'Hotel' });
|
||||
});
|
||||
|
||||
beforeEach(() => {
|
||||
svc.verifyTripAccess.mockReturnValue({ id: 5, user_id: 1 });
|
||||
checkPermission.mockReturnValue(true);
|
||||
});
|
||||
|
||||
afterAll(async () => {
|
||||
await app.close();
|
||||
});
|
||||
|
||||
it('401 without a session cookie', async () => {
|
||||
const res = await request(server).get('/api/trips/5/budget');
|
||||
expect(res.status).toBe(401);
|
||||
});
|
||||
|
||||
it('200 list for an accessible trip', async () => {
|
||||
const res = await request(server).get('/api/trips/5/budget').set('Cookie', sessionCookie(1));
|
||||
expect(res.status).toBe(200);
|
||||
expect(res.body).toEqual({ items: [{ id: 1, name: 'Hotel' }] });
|
||||
});
|
||||
|
||||
it('404 when the trip is not accessible', async () => {
|
||||
svc.verifyTripAccess.mockReturnValue(undefined);
|
||||
const res = await request(server).get('/api/trips/5/budget').set('Cookie', sessionCookie(1));
|
||||
expect(res.status).toBe(404);
|
||||
expect(res.body).toEqual({ error: 'Trip not found' });
|
||||
});
|
||||
|
||||
it('201 on create with permission', async () => {
|
||||
const res = await request(server).post('/api/trips/5/budget').set('Cookie', sessionCookie(1)).send({ name: 'Hotel' });
|
||||
expect(res.status).toBe(201);
|
||||
expect(res.body).toEqual({ item: { id: 9, name: 'Hotel' } });
|
||||
});
|
||||
|
||||
it('403 on create without permission', async () => {
|
||||
checkPermission.mockReturnValue(false);
|
||||
const res = await request(server).post('/api/trips/5/budget').set('Cookie', sessionCookie(1)).send({ name: 'Hotel' });
|
||||
expect(res.status).toBe(403);
|
||||
expect(res.body).toEqual({ error: 'No permission' });
|
||||
});
|
||||
|
||||
it('400 on member update with a non-array user_ids', async () => {
|
||||
const res = await request(server).put('/api/trips/5/budget/9/members').set('Cookie', sessionCookie(1)).send({ user_ids: 'no' });
|
||||
expect(res.status).toBe(400);
|
||||
expect(res.body).toEqual({ error: 'user_ids must be an array' });
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,119 @@
|
||||
/**
|
||||
* 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. categoryService is mocked.
|
||||
*/
|
||||
import { describe, it, expect, beforeAll, 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';
|
||||
|
||||
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);`);
|
||||
return { db: tmp };
|
||||
});
|
||||
|
||||
vi.mock('../../src/db/database', () => ({ db, closeDb: () => {}, reinitialize: () => {} }));
|
||||
|
||||
const { mocks } = vi.hoisted(() => ({
|
||||
mocks: {
|
||||
listCategories: vi.fn(),
|
||||
createCategory: vi.fn(),
|
||||
getCategoryById: vi.fn(),
|
||||
updateCategory: vi.fn(),
|
||||
deleteCategory: vi.fn(),
|
||||
},
|
||||
}));
|
||||
vi.mock('../../src/services/categoryService', () => mocks);
|
||||
|
||||
import { CategoriesModule } from '../../src/nest/categories/categories.module';
|
||||
import { DatabaseModule } from '../../src/nest/database/database.module';
|
||||
import { TrekExceptionFilter } from '../../src/nest/common/trek-exception.filter';
|
||||
|
||||
const cat = { id: 1, name: 'Food', color: '#fff', icon: '🍔' };
|
||||
|
||||
describe('Categories e2e (real JwtAuthGuard + AdminGuard + temp SQLite)', () => {
|
||||
let server: Server;
|
||||
let app: Awaited<ReturnType<typeof build>>;
|
||||
|
||||
async function build() {
|
||||
const moduleRef = await Test.createTestingModule({ imports: [DatabaseModule, CategoriesModule] }).compile();
|
||||
const nest = moduleRef.createNestApplication();
|
||||
nest.use(cookieParser());
|
||||
nest.useGlobalFilters(new TrekExceptionFilter());
|
||||
await nest.init();
|
||||
return nest;
|
||||
}
|
||||
|
||||
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' });
|
||||
app = await build();
|
||||
server = app.getHttpServer();
|
||||
mocks.listCategories.mockReturnValue([cat]);
|
||||
mocks.createCategory.mockReturnValue(cat);
|
||||
mocks.getCategoryById.mockImplementation((id: string | number) => (String(id) === '1' ? cat : undefined));
|
||||
mocks.updateCategory.mockReturnValue({ ...cat, name: 'Drinks' });
|
||||
});
|
||||
|
||||
afterAll(async () => {
|
||||
await app.close();
|
||||
});
|
||||
|
||||
it('401 without a session cookie', async () => {
|
||||
const res = await request(server).get('/api/categories');
|
||||
expect(res.status).toBe(401);
|
||||
});
|
||||
|
||||
it('200 list for any authenticated user (non-admin allowed)', async () => {
|
||||
const res = await request(server).get('/api/categories').set('Cookie', sessionCookie(2));
|
||||
expect(res.status).toBe(200);
|
||||
expect(res.body).toEqual({ categories: [cat] });
|
||||
});
|
||||
|
||||
it('403 when a non-admin tries to create', async () => {
|
||||
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(mocks.createCategory).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('201 when an admin creates a category', async () => {
|
||||
const res = await request(server).post('/api/categories').set('Cookie', sessionCookie(1)).send({ name: 'Food', color: '#fff', icon: '🍔' });
|
||||
expect(res.status).toBe(201);
|
||||
expect(res.body).toEqual({ category: cat });
|
||||
expect(mocks.createCategory).toHaveBeenCalledWith(1, 'Food', '#fff', '🍔');
|
||||
});
|
||||
|
||||
it('400 when an admin creates without a name', async () => {
|
||||
const res = await request(server).post('/api/categories').set('Cookie', sessionCookie(1)).send({});
|
||||
expect(res.status).toBe(400);
|
||||
expect(res.body).toEqual({ error: 'Category name is required' });
|
||||
});
|
||||
|
||||
it('200 when an admin updates an existing category', async () => {
|
||||
const res = await request(server).put('/api/categories/1').set('Cookie', sessionCookie(1)).send({ name: 'Drinks' });
|
||||
expect(res.status).toBe(200);
|
||||
expect(res.body).toEqual({ category: { ...cat, name: 'Drinks' } });
|
||||
});
|
||||
|
||||
it('404 when an admin updates a missing category', async () => {
|
||||
const res = await request(server).put('/api/categories/9').set('Cookie', sessionCookie(1)).send({ name: 'X' });
|
||||
expect(res.status).toBe(404);
|
||||
expect(res.body).toEqual({ error: 'Category not found' });
|
||||
});
|
||||
|
||||
it('200 when an admin deletes an existing category', async () => {
|
||||
const res = await request(server).delete('/api/categories/1').set('Cookie', sessionCookie(1));
|
||||
expect(res.status).toBe(200);
|
||||
expect(res.body).toEqual({ success: true });
|
||||
expect(mocks.deleteCategory).toHaveBeenCalledWith('1');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,137 @@
|
||||
/**
|
||||
* Collab module e2e — exercises the migrated /api/trips/:tripId/collab endpoints
|
||||
* through the real JwtAuthGuard against a temp SQLite db. The collab service,
|
||||
* permission check, WebSocket broadcast and the chat/note notification are
|
||||
* mocked; this focuses on auth, trip-access 404, permission 403, the create-201
|
||||
* status codes and the vote/react 200 overrides.
|
||||
*/
|
||||
import { describe, it, expect, beforeAll, afterAll, beforeEach, 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';
|
||||
|
||||
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);`);
|
||||
// The note/message notifications read the trip title fire-and-forget; the table
|
||||
// must exist so that query doesn't throw after the test has torn down.
|
||||
tmp.exec('CREATE TABLE trips (id INTEGER PRIMARY KEY AUTOINCREMENT, title TEXT);');
|
||||
tmp.prepare("INSERT INTO trips (id, title) VALUES (5, 'Trip')").run();
|
||||
return { db: tmp };
|
||||
});
|
||||
|
||||
vi.mock('../../src/db/database', () => ({ db, closeDb: () => {}, reinitialize: () => {} }));
|
||||
vi.mock('../../src/websocket', () => ({ broadcast: vi.fn() }));
|
||||
vi.mock('../../src/services/notificationService', () => ({ send: vi.fn().mockResolvedValue(undefined) }));
|
||||
|
||||
const { checkPermission } = vi.hoisted(() => ({ checkPermission: vi.fn() }));
|
||||
vi.mock('../../src/services/permissions', () => ({ checkPermission }));
|
||||
|
||||
const { svc } = vi.hoisted(() => ({
|
||||
svc: {
|
||||
verifyTripAccess: vi.fn(), listNotes: vi.fn(), createNote: vi.fn(), updateNote: vi.fn(), deleteNote: vi.fn(),
|
||||
addNoteFile: vi.fn(), getFormattedNoteById: vi.fn(), deleteNoteFile: vi.fn(),
|
||||
listPolls: vi.fn(), createPoll: vi.fn(), votePoll: vi.fn(), closePoll: vi.fn(), deletePoll: vi.fn(),
|
||||
listMessages: vi.fn(), createMessage: vi.fn(), deleteMessage: vi.fn(), addOrRemoveReaction: vi.fn(), fetchLinkPreview: vi.fn(),
|
||||
},
|
||||
}));
|
||||
vi.mock('../../src/services/collabService', () => svc);
|
||||
|
||||
import { CollabModule } from '../../src/nest/collab/collab.module';
|
||||
import { TrekExceptionFilter } from '../../src/nest/common/trek-exception.filter';
|
||||
|
||||
describe('Collab e2e (real auth guard + temp SQLite)', () => {
|
||||
let server: Server;
|
||||
let app: Awaited<ReturnType<typeof build>>;
|
||||
|
||||
async function build() {
|
||||
const moduleRef = await Test.createTestingModule({ imports: [CollabModule] }).compile();
|
||||
const nest = moduleRef.createNestApplication();
|
||||
nest.use(cookieParser());
|
||||
nest.useGlobalFilters(new TrekExceptionFilter());
|
||||
await nest.init();
|
||||
return nest;
|
||||
}
|
||||
|
||||
beforeAll(async () => {
|
||||
seedUser(db as never, { id: 1 });
|
||||
app = await build();
|
||||
server = app.getHttpServer();
|
||||
svc.listNotes.mockReturnValue([{ id: 1, title: 'N' }]);
|
||||
svc.createNote.mockReturnValue({ id: 9, title: 'N' });
|
||||
svc.createPoll.mockReturnValue({ id: 7 });
|
||||
svc.votePoll.mockReturnValue({ poll: { id: 7 } });
|
||||
svc.createMessage.mockReturnValue({ message: { id: 3, text: 'hi' } });
|
||||
svc.addOrRemoveReaction.mockReturnValue({ found: true, reactions: [{ emoji: '👍', count: 1 }] });
|
||||
svc.fetchLinkPreview.mockResolvedValue({ title: 'T', description: null, image: null, url: 'http://x' });
|
||||
});
|
||||
|
||||
beforeEach(() => {
|
||||
svc.verifyTripAccess.mockReturnValue({ id: 5, user_id: 1 });
|
||||
checkPermission.mockReturnValue(true);
|
||||
});
|
||||
|
||||
afterAll(async () => {
|
||||
await app.close();
|
||||
});
|
||||
|
||||
it('401 without a session cookie', async () => {
|
||||
expect((await request(server).get('/api/trips/5/collab/notes')).status).toBe(401);
|
||||
});
|
||||
|
||||
it('200 list notes for an accessible trip', async () => {
|
||||
const res = await request(server).get('/api/trips/5/collab/notes').set('Cookie', sessionCookie(1));
|
||||
expect(res.status).toBe(200);
|
||||
expect(res.body).toEqual({ notes: [{ id: 1, title: 'N' }] });
|
||||
});
|
||||
|
||||
it('404 when the trip is not accessible', async () => {
|
||||
svc.verifyTripAccess.mockReturnValue(undefined);
|
||||
const res = await request(server).get('/api/trips/5/collab/notes').set('Cookie', sessionCookie(1));
|
||||
expect(res.status).toBe(404);
|
||||
expect(res.body).toEqual({ error: 'Trip not found' });
|
||||
});
|
||||
|
||||
it('201 on note create with permission', async () => {
|
||||
const res = await request(server).post('/api/trips/5/collab/notes').set('Cookie', sessionCookie(1)).send({ title: 'N' });
|
||||
expect(res.status).toBe(201);
|
||||
expect(res.body).toEqual({ note: { id: 9, title: 'N' } });
|
||||
});
|
||||
|
||||
it('403 on note create without permission', async () => {
|
||||
checkPermission.mockReturnValue(false);
|
||||
const res = await request(server).post('/api/trips/5/collab/notes').set('Cookie', sessionCookie(1)).send({ title: 'N' });
|
||||
expect(res.status).toBe(403);
|
||||
expect(res.body).toEqual({ error: 'No permission' });
|
||||
});
|
||||
|
||||
it('200 on poll vote (not 201)', async () => {
|
||||
const res = await request(server).post('/api/trips/5/collab/polls/7/vote').set('Cookie', sessionCookie(1)).send({ option_index: 0 });
|
||||
expect(res.status).toBe(200);
|
||||
expect(res.body).toEqual({ poll: { id: 7 } });
|
||||
});
|
||||
|
||||
it('201 on message create', async () => {
|
||||
const res = await request(server).post('/api/trips/5/collab/messages').set('Cookie', sessionCookie(1)).send({ text: 'hi' });
|
||||
expect(res.status).toBe(201);
|
||||
expect(res.body).toEqual({ message: { id: 3, text: 'hi' } });
|
||||
});
|
||||
|
||||
it('200 on react (not 201)', async () => {
|
||||
const res = await request(server).post('/api/trips/5/collab/messages/3/react').set('Cookie', sessionCookie(1)).send({ emoji: '👍' });
|
||||
expect(res.status).toBe(200);
|
||||
expect(res.body).toEqual({ reactions: [{ emoji: '👍', count: 1 }] });
|
||||
});
|
||||
|
||||
it('400 on link-preview without a url', async () => {
|
||||
const res = await request(server).get('/api/trips/5/collab/link-preview').set('Cookie', sessionCookie(1));
|
||||
expect(res.status).toBe(400);
|
||||
expect(res.body).toEqual({ error: 'URL is required' });
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,39 @@
|
||||
/**
|
||||
* Public config e2e — verifies /api/config is reachable WITHOUT authentication
|
||||
* (it has no guard) and returns the server default language. No db needed.
|
||||
*/
|
||||
import { describe, it, expect, beforeAll, afterAll } from 'vitest';
|
||||
import request from 'supertest';
|
||||
import type { Server } from 'http';
|
||||
import { Test } from '@nestjs/testing';
|
||||
import { ConfigModule } from '../../src/nest/config/config.module';
|
||||
import { TrekExceptionFilter } from '../../src/nest/common/trek-exception.filter';
|
||||
import { DEFAULT_LANGUAGE } from '../../src/config';
|
||||
|
||||
describe('Public config e2e (no auth guard)', () => {
|
||||
let server: Server;
|
||||
let app: Awaited<ReturnType<typeof build>>;
|
||||
|
||||
async function build() {
|
||||
const moduleRef = await Test.createTestingModule({ imports: [ConfigModule] }).compile();
|
||||
const nest = moduleRef.createNestApplication();
|
||||
nest.useGlobalFilters(new TrekExceptionFilter());
|
||||
await nest.init();
|
||||
return nest;
|
||||
}
|
||||
|
||||
beforeAll(async () => {
|
||||
app = await build();
|
||||
server = app.getHttpServer();
|
||||
});
|
||||
|
||||
afterAll(async () => {
|
||||
await app.close();
|
||||
});
|
||||
|
||||
it('200 with the default language and no cookie required', async () => {
|
||||
const res = await request(server).get('/api/config');
|
||||
expect(res.status).toBe(200);
|
||||
expect(res.body).toEqual({ defaultLanguage: DEFAULT_LANGUAGE });
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,113 @@
|
||||
/**
|
||||
* Days + day-notes module e2e — exercises both migrated mounts through the real
|
||||
* JwtAuthGuard against a temp SQLite db. The day/day-note services, the
|
||||
* permission check, canAccessTrip and the WebSocket broadcast are mocked.
|
||||
*/
|
||||
import { describe, it, expect, beforeAll, afterAll, beforeEach, 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';
|
||||
|
||||
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);`);
|
||||
return { db: tmp };
|
||||
});
|
||||
|
||||
const { canAccessTrip } = vi.hoisted(() => ({ canAccessTrip: vi.fn() }));
|
||||
vi.mock('../../src/db/database', () => ({
|
||||
db, canAccessTrip, isOwner: vi.fn(() => true), getPlaceWithTags: vi.fn(), closeDb: () => {}, reinitialize: () => {},
|
||||
}));
|
||||
vi.mock('../../src/websocket', () => ({ broadcast: vi.fn() }));
|
||||
|
||||
const { checkPermission } = vi.hoisted(() => ({ checkPermission: vi.fn() }));
|
||||
vi.mock('../../src/services/permissions', () => ({ checkPermission }));
|
||||
|
||||
const { day, note } = vi.hoisted(() => ({
|
||||
day: { listDays: vi.fn(), createDay: vi.fn(), getDay: vi.fn(), updateDay: vi.fn(), deleteDay: vi.fn() },
|
||||
note: {
|
||||
verifyTripAccess: vi.fn(), listNotes: vi.fn(), dayExists: vi.fn(), createNote: vi.fn(),
|
||||
getNote: vi.fn(), updateNote: vi.fn(), deleteNote: vi.fn(),
|
||||
},
|
||||
}));
|
||||
vi.mock('../../src/services/dayService', () => day);
|
||||
vi.mock('../../src/services/dayNoteService', () => note);
|
||||
|
||||
import { DaysModule } from '../../src/nest/days/days.module';
|
||||
import { TrekExceptionFilter } from '../../src/nest/common/trek-exception.filter';
|
||||
|
||||
describe('Days + day-notes e2e (real auth guard + temp SQLite)', () => {
|
||||
let server: Server;
|
||||
let app: Awaited<ReturnType<typeof build>>;
|
||||
|
||||
async function build() {
|
||||
const moduleRef = await Test.createTestingModule({ imports: [DaysModule] }).compile();
|
||||
const nest = moduleRef.createNestApplication();
|
||||
nest.use(cookieParser());
|
||||
nest.useGlobalFilters(new TrekExceptionFilter());
|
||||
await nest.init();
|
||||
return nest;
|
||||
}
|
||||
|
||||
beforeAll(async () => {
|
||||
seedUser(db as never, { id: 1 });
|
||||
app = await build();
|
||||
server = app.getHttpServer();
|
||||
day.listDays.mockReturnValue({ days: [{ id: 1 }] });
|
||||
day.createDay.mockReturnValue({ id: 9 });
|
||||
note.listNotes.mockReturnValue([{ id: 1 }]);
|
||||
note.dayExists.mockReturnValue(true);
|
||||
note.createNote.mockReturnValue({ id: 7 });
|
||||
});
|
||||
|
||||
beforeEach(() => {
|
||||
canAccessTrip.mockReturnValue({ id: 5, user_id: 1 });
|
||||
note.verifyTripAccess.mockReturnValue({ id: 5, user_id: 1 });
|
||||
checkPermission.mockReturnValue(true);
|
||||
});
|
||||
|
||||
afterAll(async () => {
|
||||
await app.close();
|
||||
});
|
||||
|
||||
it('401 without a cookie', async () => {
|
||||
expect((await request(server).get('/api/trips/5/days')).status).toBe(401);
|
||||
});
|
||||
|
||||
it('200 list days (the { days } envelope)', async () => {
|
||||
const res = await request(server).get('/api/trips/5/days').set('Cookie', sessionCookie(1));
|
||||
expect(res.status).toBe(200);
|
||||
expect(res.body).toEqual({ days: [{ id: 1 }] });
|
||||
});
|
||||
|
||||
it('201 create day, 404 trip when not accessible', async () => {
|
||||
const ok = await request(server).post('/api/trips/5/days').set('Cookie', sessionCookie(1)).send({ date: '2026-07-01' });
|
||||
expect(ok.status).toBe(201);
|
||||
expect(ok.body).toEqual({ day: { id: 9 } });
|
||||
canAccessTrip.mockReturnValue(undefined);
|
||||
const miss = await request(server).get('/api/trips/5/days').set('Cookie', sessionCookie(1));
|
||||
expect(miss.status).toBe(404);
|
||||
expect(miss.body).toEqual({ error: 'Trip not found' });
|
||||
});
|
||||
|
||||
it('201 create note, 400 on over-long text (before access)', async () => {
|
||||
const ok = await request(server).post('/api/trips/5/days/3/notes').set('Cookie', sessionCookie(1)).send({ text: 'Lunch' });
|
||||
expect(ok.status).toBe(201);
|
||||
expect(ok.body).toEqual({ note: { id: 7 } });
|
||||
const long = await request(server).post('/api/trips/5/days/3/notes').set('Cookie', sessionCookie(1)).send({ text: 'x'.repeat(501) });
|
||||
expect(long.status).toBe(400);
|
||||
expect(long.body).toEqual({ error: 'text must be 500 characters or less' });
|
||||
});
|
||||
|
||||
it('400 note without text', async () => {
|
||||
const res = await request(server).post('/api/trips/5/days/3/notes').set('Cookie', sessionCookie(1)).send({ text: ' ' });
|
||||
expect(res.status).toBe(400);
|
||||
expect(res.body).toEqual({ error: 'Text required' });
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,135 @@
|
||||
/**
|
||||
* Files + photos e2e — exercises the migrated /api/trips/:tripId/files and
|
||||
* /api/photos endpoints through the real JwtAuthGuard against a temp SQLite db.
|
||||
* The file/photo services, permission check and broadcast are mocked; this
|
||||
* focuses on auth (incl. the unguarded download's own token auth), trip-access
|
||||
* 404, permission 403, the photo id/access guards and status codes.
|
||||
*/
|
||||
import { describe, it, expect, beforeAll, afterAll, beforeEach, 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';
|
||||
|
||||
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);`);
|
||||
return { db: tmp };
|
||||
});
|
||||
|
||||
vi.mock('../../src/db/database', () => ({ db, closeDb: () => {}, reinitialize: () => {} }));
|
||||
vi.mock('../../src/websocket', () => ({ broadcast: vi.fn() }));
|
||||
vi.mock('../../src/services/demo', () => ({ isDemoEmail: vi.fn(() => false) }));
|
||||
|
||||
const { checkPermission } = vi.hoisted(() => ({ checkPermission: vi.fn() }));
|
||||
vi.mock('../../src/services/permissions', () => ({ checkPermission }));
|
||||
|
||||
const { fileSvc } = vi.hoisted(() => ({
|
||||
fileSvc: {
|
||||
MAX_FILE_SIZE: 50 * 1024 * 1024, BLOCKED_EXTENSIONS: ['.exe', '.svg'], filesDir: '/tmp/files', getAllowedExtensions: () => '*',
|
||||
verifyTripAccess: vi.fn(), resolveFilePath: vi.fn(), authenticateDownload: vi.fn(),
|
||||
listFiles: vi.fn(), getFileById: vi.fn(), getDeletedFile: vi.fn(), createFile: vi.fn(), updateFile: vi.fn(),
|
||||
toggleStarred: vi.fn(), softDeleteFile: vi.fn(), restoreFile: vi.fn(), permanentDeleteFile: vi.fn(),
|
||||
emptyTrash: vi.fn(), createFileLink: vi.fn(), deleteFileLink: vi.fn(), getFileLinks: vi.fn(), formatFile: vi.fn(),
|
||||
},
|
||||
}));
|
||||
vi.mock('../../src/services/fileService', () => fileSvc);
|
||||
|
||||
const { photoSvc, helperSvc } = vi.hoisted(() => ({
|
||||
photoSvc: { streamPhoto: vi.fn(), getPhotoInfo: vi.fn(), resolveTrekPhoto: vi.fn() },
|
||||
helperSvc: { canAccessTrekPhoto: vi.fn() },
|
||||
}));
|
||||
vi.mock('../../src/services/memories/photoResolverService', () => photoSvc);
|
||||
vi.mock('../../src/services/memories/helpersService', () => helperSvc);
|
||||
|
||||
import { FilesModule } from '../../src/nest/files/files.module';
|
||||
import { PhotosModule } from '../../src/nest/photos/photos.module';
|
||||
import { TrekExceptionFilter } from '../../src/nest/common/trek-exception.filter';
|
||||
|
||||
describe('Files + photos e2e (real auth guard + temp SQLite)', () => {
|
||||
let server: Server;
|
||||
let app: Awaited<ReturnType<typeof build>>;
|
||||
|
||||
async function build() {
|
||||
const moduleRef = await Test.createTestingModule({ imports: [FilesModule, PhotosModule] }).compile();
|
||||
const nest = moduleRef.createNestApplication();
|
||||
nest.use(cookieParser());
|
||||
nest.useGlobalFilters(new TrekExceptionFilter());
|
||||
await nest.init();
|
||||
return nest;
|
||||
}
|
||||
|
||||
beforeAll(async () => {
|
||||
seedUser(db as never, { id: 1 });
|
||||
app = await build();
|
||||
server = app.getHttpServer();
|
||||
fileSvc.listFiles.mockReturnValue([{ id: 1, original_name: 'a.pdf' }]);
|
||||
fileSvc.getFileById.mockReturnValue({ id: 9, starred: 0 });
|
||||
fileSvc.toggleStarred.mockReturnValue({ id: 9, starred: 1 });
|
||||
});
|
||||
|
||||
beforeEach(() => {
|
||||
fileSvc.verifyTripAccess.mockReturnValue({ id: 5, user_id: 1 });
|
||||
checkPermission.mockReturnValue(true);
|
||||
helperSvc.canAccessTrekPhoto.mockReturnValue(true);
|
||||
});
|
||||
|
||||
afterAll(async () => {
|
||||
await app.close();
|
||||
});
|
||||
|
||||
it('401 listing files without a session cookie', async () => {
|
||||
expect((await request(server).get('/api/trips/5/files')).status).toBe(401);
|
||||
});
|
||||
|
||||
it('200 list for an accessible trip', async () => {
|
||||
const res = await request(server).get('/api/trips/5/files').set('Cookie', sessionCookie(1));
|
||||
expect(res.status).toBe(200);
|
||||
expect(res.body).toEqual({ files: [{ id: 1, original_name: 'a.pdf' }] });
|
||||
});
|
||||
|
||||
it('404 when the trip is not accessible', async () => {
|
||||
fileSvc.verifyTripAccess.mockReturnValue(undefined);
|
||||
const res = await request(server).get('/api/trips/5/files').set('Cookie', sessionCookie(1));
|
||||
expect(res.status).toBe(404);
|
||||
expect(res.body).toEqual({ error: 'Trip not found' });
|
||||
});
|
||||
|
||||
it('200 toggling a star with permission', async () => {
|
||||
const res = await request(server).patch('/api/trips/5/files/9/star').set('Cookie', sessionCookie(1));
|
||||
expect(res.status).toBe(200);
|
||||
expect(res.body).toEqual({ file: { id: 9, starred: 1 } });
|
||||
});
|
||||
|
||||
it('403 deleting without file_delete permission', async () => {
|
||||
checkPermission.mockReturnValue(false);
|
||||
const res = await request(server).delete('/api/trips/5/files/9').set('Cookie', sessionCookie(1));
|
||||
expect(res.status).toBe(403);
|
||||
expect(res.body).toEqual({ error: 'No permission to delete files' });
|
||||
});
|
||||
|
||||
it('download is unguarded but enforces its own token auth (401 without one)', async () => {
|
||||
fileSvc.authenticateDownload.mockReturnValue({ error: 'Authentication required', status: 401 });
|
||||
const res = await request(server).get('/api/trips/5/files/9/download');
|
||||
expect(res.status).toBe(401);
|
||||
expect(res.body).toEqual({ error: 'Authentication required' });
|
||||
});
|
||||
|
||||
it('400 on a photo with a non-finite id', async () => {
|
||||
const res = await request(server).get('/api/photos/abc/thumbnail').set('Cookie', sessionCookie(1));
|
||||
expect(res.status).toBe(400);
|
||||
expect(res.body).toEqual({ error: 'Invalid photo ID' });
|
||||
});
|
||||
|
||||
it('403 on a photo the user cannot access', async () => {
|
||||
helperSvc.canAccessTrekPhoto.mockReturnValue(false);
|
||||
const res = await request(server).get('/api/photos/5/original').set('Cookie', sessionCookie(1));
|
||||
expect(res.status).toBe(403);
|
||||
expect(res.body).toEqual({ error: 'Forbidden' });
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,119 @@
|
||||
/**
|
||||
* Journey e2e — exercises the migrated /api/journeys and /api/public/journey
|
||||
* endpoints through the real JwtAuthGuard against a temp SQLite db. The journey
|
||||
* services + addon gate are mocked; this focuses on the addon-gate-before-auth
|
||||
* ordering (404 wins over 401), auth, the service-owned 403/404 mapping, status
|
||||
* codes and the unguarded public route.
|
||||
*/
|
||||
import { describe, it, expect, beforeAll, afterAll, beforeEach, 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';
|
||||
|
||||
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);`);
|
||||
return { db: tmp };
|
||||
});
|
||||
|
||||
vi.mock('../../src/db/database', () => ({ db, closeDb: () => {}, reinitialize: () => {} }));
|
||||
|
||||
const { isAddonEnabled } = vi.hoisted(() => ({ isAddonEnabled: vi.fn(() => true) }));
|
||||
vi.mock('../../src/services/adminService', () => ({ isAddonEnabled }));
|
||||
vi.mock('../../src/services/fileService', () => ({ getAllowedExtensions: () => '*' }));
|
||||
vi.mock('../../src/services/memories/immichService', () => ({ uploadToImmich: vi.fn(), streamImmichAsset: vi.fn() }));
|
||||
vi.mock('../../src/services/memories/photoResolverService', () => ({ streamPhoto: vi.fn() }));
|
||||
|
||||
const { jsvc } = vi.hoisted(() => ({
|
||||
jsvc: { listJourneys: vi.fn(), createJourney: vi.fn(), getJourneyFull: vi.fn() },
|
||||
}));
|
||||
vi.mock('../../src/services/journeyService', () => jsvc);
|
||||
|
||||
const { sharesvc } = vi.hoisted(() => ({ sharesvc: { getPublicJourney: vi.fn() } }));
|
||||
vi.mock('../../src/services/journeyShareService', () => sharesvc);
|
||||
|
||||
import { JourneyModule } from '../../src/nest/journey/journey.module';
|
||||
import { TrekExceptionFilter } from '../../src/nest/common/trek-exception.filter';
|
||||
|
||||
describe('Journey e2e (real auth guard + temp SQLite)', () => {
|
||||
let server: Server;
|
||||
let app: Awaited<ReturnType<typeof build>>;
|
||||
|
||||
async function build() {
|
||||
const moduleRef = await Test.createTestingModule({ imports: [JourneyModule] }).compile();
|
||||
const nest = moduleRef.createNestApplication();
|
||||
nest.use(cookieParser());
|
||||
nest.useGlobalFilters(new TrekExceptionFilter());
|
||||
await nest.init();
|
||||
return nest;
|
||||
}
|
||||
|
||||
beforeAll(async () => {
|
||||
seedUser(db as never, { id: 1 });
|
||||
app = await build();
|
||||
server = app.getHttpServer();
|
||||
jsvc.listJourneys.mockReturnValue([{ id: 1, title: 'J' }]);
|
||||
jsvc.createJourney.mockReturnValue({ id: 9, title: 'J' });
|
||||
sharesvc.getPublicJourney.mockReturnValue({ id: 9 });
|
||||
});
|
||||
|
||||
beforeEach(() => {
|
||||
isAddonEnabled.mockReturnValue(true);
|
||||
});
|
||||
|
||||
afterAll(async () => {
|
||||
await app.close();
|
||||
});
|
||||
|
||||
it('404 (addon gate wins over auth) when the Journey addon is disabled', async () => {
|
||||
isAddonEnabled.mockReturnValue(false);
|
||||
const res = await request(server).get('/api/journeys');
|
||||
expect(res.status).toBe(404);
|
||||
expect(res.body).toEqual({ error: 'Journey addon is not enabled' });
|
||||
});
|
||||
|
||||
it('401 with the addon enabled but no session cookie', async () => {
|
||||
expect((await request(server).get('/api/journeys')).status).toBe(401);
|
||||
});
|
||||
|
||||
it('200 list with a session', async () => {
|
||||
const res = await request(server).get('/api/journeys').set('Cookie', sessionCookie(1));
|
||||
expect(res.status).toBe(200);
|
||||
expect(res.body).toEqual({ journeys: [{ id: 1, title: 'J' }] });
|
||||
});
|
||||
|
||||
it('201 create, 400 without a title', async () => {
|
||||
const ok = await request(server).post('/api/journeys').set('Cookie', sessionCookie(1)).send({ title: 'J' });
|
||||
expect(ok.status).toBe(201);
|
||||
expect(ok.body).toEqual({ id: 9, title: 'J' });
|
||||
const bad = await request(server).post('/api/journeys').set('Cookie', sessionCookie(1)).send({});
|
||||
expect(bad.status).toBe(400);
|
||||
expect(bad.body).toEqual({ error: 'Title is required' });
|
||||
});
|
||||
|
||||
it('404 for an inaccessible journey', async () => {
|
||||
jsvc.getJourneyFull.mockReturnValue(null);
|
||||
const res = await request(server).get('/api/journeys/9').set('Cookie', sessionCookie(1));
|
||||
expect(res.status).toBe(404);
|
||||
expect(res.body).toEqual({ error: 'Journey not found' });
|
||||
});
|
||||
|
||||
it('public journey read is unguarded (200 with a valid token, no cookie)', async () => {
|
||||
const res = await request(server).get('/api/public/journey/tok');
|
||||
expect(res.status).toBe(200);
|
||||
expect(res.body).toEqual({ id: 9 });
|
||||
});
|
||||
|
||||
it('public journey 404 for an unknown token', async () => {
|
||||
sharesvc.getPublicJourney.mockReturnValueOnce(null);
|
||||
const res = await request(server).get('/api/public/journey/bad');
|
||||
expect(res.status).toBe(404);
|
||||
expect(res.body).toEqual({ error: 'Not found' });
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,101 @@
|
||||
/**
|
||||
* Maps module e2e — exercises the migrated /api/maps endpoints through the real
|
||||
* JwtAuthGuard against a temp SQLite db. mapsService is mocked (no outbound HTTP),
|
||||
* and the temp db carries an empty app_settings table so the kill-switch reads
|
||||
* resolve to "enabled".
|
||||
*/
|
||||
import { describe, it, expect, beforeAll, 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';
|
||||
|
||||
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 app_settings (key TEXT PRIMARY KEY, value TEXT);');
|
||||
return { db: tmp };
|
||||
});
|
||||
|
||||
vi.mock('../../src/db/database', () => ({ db, closeDb: () => {}, reinitialize: () => {} }));
|
||||
|
||||
const { mocks } = vi.hoisted(() => ({
|
||||
mocks: {
|
||||
searchPlaces: vi.fn(),
|
||||
autocompletePlaces: vi.fn(),
|
||||
getPlaceDetails: vi.fn(),
|
||||
getPlaceDetailsExpanded: vi.fn(),
|
||||
getPlacePhoto: vi.fn(),
|
||||
reverseGeocode: vi.fn(),
|
||||
resolveGoogleMapsUrl: vi.fn(),
|
||||
},
|
||||
}));
|
||||
vi.mock('../../src/services/mapsService', async (importActual) => {
|
||||
const actual = await importActual<typeof import('../../src/services/mapsService')>();
|
||||
return { ...actual, ...mocks };
|
||||
});
|
||||
|
||||
import { MapsModule } from '../../src/nest/maps/maps.module';
|
||||
import { DatabaseModule } from '../../src/nest/database/database.module';
|
||||
import { TrekExceptionFilter } from '../../src/nest/common/trek-exception.filter';
|
||||
|
||||
describe('Maps e2e (real auth guard + temp SQLite)', () => {
|
||||
let server: Server;
|
||||
let app: Awaited<ReturnType<typeof build>>;
|
||||
|
||||
async function build() {
|
||||
const moduleRef = await Test.createTestingModule({ imports: [DatabaseModule, MapsModule] }).compile();
|
||||
const nest = moduleRef.createNestApplication();
|
||||
nest.use(cookieParser());
|
||||
nest.useGlobalFilters(new TrekExceptionFilter());
|
||||
await nest.init();
|
||||
return nest;
|
||||
}
|
||||
|
||||
beforeAll(async () => {
|
||||
seedUser(db as never, { id: 1 });
|
||||
app = await build();
|
||||
server = app.getHttpServer();
|
||||
mocks.searchPlaces.mockResolvedValue({ places: [{ name: 'Berlin' }], source: 'osm' });
|
||||
mocks.reverseGeocode.mockResolvedValue({ name: 'Spot', address: 'Street 1' });
|
||||
});
|
||||
|
||||
afterAll(async () => {
|
||||
await app.close();
|
||||
});
|
||||
|
||||
it('401 without a session cookie', async () => {
|
||||
const res = await request(server).post('/api/maps/search').send({ query: 'berlin' });
|
||||
expect(res.status).toBe(401);
|
||||
expect(res.body).toEqual({ error: 'Access token required', code: 'AUTH_REQUIRED' });
|
||||
});
|
||||
|
||||
it('400 when authenticated but query is missing', async () => {
|
||||
const res = await request(server).post('/api/maps/search').set('Cookie', sessionCookie(1)).send({});
|
||||
expect(res.status).toBe(400);
|
||||
expect(res.body).toEqual({ error: 'Search query is required' });
|
||||
});
|
||||
|
||||
it('200 with results for a search (POST stays 200, not 201)', async () => {
|
||||
const res = await request(server).post('/api/maps/search').set('Cookie', sessionCookie(1)).send({ query: 'berlin' });
|
||||
expect(res.status).toBe(200);
|
||||
expect(res.body).toEqual({ places: [{ name: 'Berlin' }], source: 'osm' });
|
||||
});
|
||||
|
||||
it('200 on reverse geocode', async () => {
|
||||
const res = await request(server).get('/api/maps/reverse').set('Cookie', sessionCookie(1)).query({ lat: '52.5', lng: '13.4' });
|
||||
expect(res.status).toBe(200);
|
||||
expect(res.body).toEqual({ name: 'Spot', address: 'Street 1' });
|
||||
});
|
||||
|
||||
it('400 on reverse geocode without coordinates', async () => {
|
||||
const res = await request(server).get('/api/maps/reverse').set('Cookie', sessionCookie(1)).query({ lat: '52.5' });
|
||||
expect(res.status).toBe(400);
|
||||
expect(res.body).toEqual({ error: 'lat and lng required' });
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,116 @@
|
||||
/**
|
||||
* Notifications module e2e — exercises the migrated /api/notifications endpoints
|
||||
* through the real JwtAuthGuard against a temp SQLite db. The notification
|
||||
* services are mocked; this focuses on auth, the inline admin gate on
|
||||
* /test-smtp, routing (the /in-app/all ordering trap) and status/body shapes.
|
||||
*/
|
||||
import { describe, it, expect, beforeAll, 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';
|
||||
|
||||
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);`);
|
||||
return { db: tmp };
|
||||
});
|
||||
|
||||
vi.mock('../../src/db/database', () => ({ db, closeDb: () => {}, reinitialize: () => {} }));
|
||||
|
||||
const { prefs, inapp, channels } = vi.hoisted(() => ({
|
||||
prefs: { getPreferencesMatrix: vi.fn(), setPreferences: vi.fn() },
|
||||
inapp: {
|
||||
getNotifications: vi.fn(), getUnreadCount: vi.fn(), markRead: vi.fn(), markUnread: vi.fn(),
|
||||
markAllRead: vi.fn(), deleteNotification: vi.fn(), deleteAll: vi.fn(), respondToBoolean: vi.fn(),
|
||||
},
|
||||
channels: {
|
||||
testSmtp: vi.fn(), testWebhook: vi.fn(), testNtfy: vi.fn(),
|
||||
getUserWebhookUrl: vi.fn(), getAdminWebhookUrl: vi.fn(),
|
||||
getUserNtfyConfig: vi.fn(), getAdminNtfyConfig: vi.fn(),
|
||||
},
|
||||
}));
|
||||
vi.mock('../../src/services/notificationPreferencesService', () => prefs);
|
||||
vi.mock('../../src/services/inAppNotifications', () => inapp);
|
||||
vi.mock('../../src/services/notifications', () => channels);
|
||||
|
||||
import { NotificationsModule } from '../../src/nest/notifications/notifications.module';
|
||||
import { TrekExceptionFilter } from '../../src/nest/common/trek-exception.filter';
|
||||
|
||||
describe('Notifications e2e (real auth guard + temp SQLite)', () => {
|
||||
let server: Server;
|
||||
let app: Awaited<ReturnType<typeof build>>;
|
||||
|
||||
async function build() {
|
||||
const moduleRef = await Test.createTestingModule({ imports: [NotificationsModule] }).compile();
|
||||
const nest = moduleRef.createNestApplication();
|
||||
nest.use(cookieParser());
|
||||
nest.useGlobalFilters(new TrekExceptionFilter());
|
||||
await nest.init();
|
||||
return nest;
|
||||
}
|
||||
|
||||
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' });
|
||||
app = await build();
|
||||
server = app.getHttpServer();
|
||||
prefs.getPreferencesMatrix.mockReturnValue({ preferences: {}, available_channels: {}, event_types: [], implemented_combos: {} });
|
||||
inapp.getUnreadCount.mockReturnValue(2);
|
||||
inapp.deleteAll.mockReturnValue(4);
|
||||
channels.testSmtp.mockResolvedValue({ success: true });
|
||||
});
|
||||
|
||||
afterAll(async () => {
|
||||
await app.close();
|
||||
});
|
||||
|
||||
it('401 without a session cookie', async () => {
|
||||
const res = await request(server).get('/api/notifications/preferences');
|
||||
expect(res.status).toBe(401);
|
||||
});
|
||||
|
||||
it('200 preferences for an authenticated user', async () => {
|
||||
const res = await request(server).get('/api/notifications/preferences').set('Cookie', sessionCookie(2));
|
||||
expect(res.status).toBe(200);
|
||||
expect(res.body).toMatchObject({ preferences: {} });
|
||||
});
|
||||
|
||||
it('403 { error: Admin only } when a non-admin hits test-smtp', async () => {
|
||||
const res = await request(server).post('/api/notifications/test-smtp').set('Cookie', sessionCookie(2)).send({});
|
||||
expect(res.status).toBe(403);
|
||||
expect(res.body).toEqual({ error: 'Admin only' });
|
||||
expect(channels.testSmtp).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('200 test-smtp for an admin (stays 200, not 201)', async () => {
|
||||
const res = await request(server).post('/api/notifications/test-smtp').set('Cookie', sessionCookie(1)).send({ email: 'x@y.z' });
|
||||
expect(res.status).toBe(200);
|
||||
expect(res.body).toEqual({ success: true });
|
||||
});
|
||||
|
||||
it('200 unread-count', async () => {
|
||||
const res = await request(server).get('/api/notifications/in-app/unread-count').set('Cookie', sessionCookie(2));
|
||||
expect(res.status).toBe(200);
|
||||
expect(res.body).toEqual({ count: 2 });
|
||||
});
|
||||
|
||||
it('DELETE /in-app/all hits deleteAll, not deleteNotification', async () => {
|
||||
const res = await request(server).delete('/api/notifications/in-app/all').set('Cookie', sessionCookie(2));
|
||||
expect(res.status).toBe(200);
|
||||
expect(res.body).toEqual({ success: true, count: 4 });
|
||||
expect(inapp.deleteAll).toHaveBeenCalledWith(2);
|
||||
expect(inapp.deleteNotification).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('400 on a non-numeric in-app id', async () => {
|
||||
const res = await request(server).put('/api/notifications/in-app/abc/read').set('Cookie', sessionCookie(2));
|
||||
expect(res.status).toBe(400);
|
||||
expect(res.body).toEqual({ error: 'Invalid id' });
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,113 @@
|
||||
/**
|
||||
* OAuth e2e — exercises the migrated /oauth/* and /api/oauth/* endpoints through
|
||||
* the real JwtAuthGuard / CookieAuthGuard / OptionalJwtGuard against a temp
|
||||
* SQLite db. The OAuth service + addon gate are mocked; this focuses on the
|
||||
* public token/userinfo guards, the MCP 404/403 gates, and the cookie-only auth
|
||||
* on the management endpoints (a Bearer must NOT satisfy them).
|
||||
*/
|
||||
import { describe, it, expect, beforeAll, afterAll, beforeEach, 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, signSession } 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);`);
|
||||
return { db: tmp };
|
||||
});
|
||||
|
||||
vi.mock('../../src/db/database', () => ({ db, closeDb: () => {}, reinitialize: () => {} }));
|
||||
vi.mock('../../src/services/auditLog', () => ({ writeAudit: vi.fn(), getClientIp: () => '1.2.3.4', logWarn: vi.fn() }));
|
||||
vi.mock('../../src/services/notifications', () => ({ getMcpSafeUrl: () => 'https://app' }));
|
||||
|
||||
const { isAddonEnabled } = vi.hoisted(() => ({ isAddonEnabled: vi.fn(() => true) }));
|
||||
vi.mock('../../src/services/adminService', () => ({ isAddonEnabled }));
|
||||
|
||||
const { oauthSvc } = vi.hoisted(() => ({
|
||||
oauthSvc: {
|
||||
validateAuthorizeRequest: vi.fn(), createAuthCode: vi.fn(), consumeAuthCode: vi.fn(), saveConsent: vi.fn(),
|
||||
issueTokens: vi.fn(), issueClientCredentialsToken: vi.fn(), refreshTokens: vi.fn(), revokeToken: vi.fn(),
|
||||
verifyPKCE: vi.fn(), authenticateClient: vi.fn(), listOAuthClients: vi.fn(), createOAuthClient: vi.fn(),
|
||||
deleteOAuthClient: vi.fn(), rotateOAuthClientSecret: vi.fn(), listOAuthSessions: vi.fn(), revokeSession: vi.fn(),
|
||||
getUserByAccessToken: vi.fn(),
|
||||
},
|
||||
}));
|
||||
vi.mock('../../src/services/oauthService', () => oauthSvc);
|
||||
|
||||
import { OauthModule } from '../../src/nest/oauth/oauth.module';
|
||||
import { TrekExceptionFilter } from '../../src/nest/common/trek-exception.filter';
|
||||
|
||||
describe('OAuth e2e (real guards + temp SQLite)', () => {
|
||||
let server: Server;
|
||||
let app: Awaited<ReturnType<typeof build>>;
|
||||
|
||||
async function build() {
|
||||
const moduleRef = await Test.createTestingModule({ imports: [OauthModule] }).compile();
|
||||
const nest = moduleRef.createNestApplication();
|
||||
nest.use(cookieParser());
|
||||
nest.useGlobalFilters(new TrekExceptionFilter());
|
||||
await nest.init();
|
||||
return nest;
|
||||
}
|
||||
|
||||
beforeAll(async () => {
|
||||
vi.spyOn(console, 'error').mockImplementation(() => {});
|
||||
seedUser(db as never, { id: 1 });
|
||||
app = await build();
|
||||
server = app.getHttpServer();
|
||||
oauthSvc.listOAuthClients.mockReturnValue([{ id: 'c1' }]);
|
||||
});
|
||||
|
||||
beforeEach(() => { isAddonEnabled.mockReturnValue(true); });
|
||||
|
||||
afterAll(async () => {
|
||||
await app.close();
|
||||
});
|
||||
|
||||
it('POST /oauth/token is public — 401 invalid_client without client_id', async () => {
|
||||
const res = await request(server).post('/oauth/token').send({});
|
||||
expect(res.status).toBe(401);
|
||||
expect(res.body).toEqual({ error: 'invalid_client', error_description: 'client_id is required' });
|
||||
expect(res.headers['cache-control']).toBe('no-store');
|
||||
});
|
||||
|
||||
it('POST /oauth/token 404 (empty) when MCP is disabled', async () => {
|
||||
isAddonEnabled.mockReturnValue(false);
|
||||
const res = await request(server).post('/oauth/token').send({ client_id: 'c' });
|
||||
expect(res.status).toBe(404);
|
||||
expect(res.text).toBe('');
|
||||
});
|
||||
|
||||
it('GET /oauth/userinfo 401 with a WWW-Authenticate challenge', async () => {
|
||||
const res = await request(server).get('/oauth/userinfo');
|
||||
expect(res.status).toBe(401);
|
||||
expect(res.headers['www-authenticate']).toContain('Bearer');
|
||||
});
|
||||
|
||||
it('GET /api/oauth/clients 401 without a session', async () => {
|
||||
expect((await request(server).get('/api/oauth/clients')).status).toBe(401);
|
||||
});
|
||||
|
||||
it('GET /api/oauth/clients works with a Bearer (authenticate) session', async () => {
|
||||
const res = await request(server).get('/api/oauth/clients').set('Authorization', `Bearer ${signSession(1)}`);
|
||||
expect(res.status).toBe(200);
|
||||
expect(res.body).toEqual({ clients: [{ id: 'c1' }] });
|
||||
});
|
||||
|
||||
it('POST /api/oauth/clients requires a COOKIE session (a Bearer is rejected)', async () => {
|
||||
const bearer = await request(server).post('/api/oauth/clients').set('Authorization', `Bearer ${signSession(1)}`).send({ name: 'CLI', allowed_scopes: ['a'] });
|
||||
expect(bearer.status).toBe(401);
|
||||
expect(bearer.body).toEqual({ error: 'Cookie session required for this endpoint', code: 'COOKIE_AUTH_REQUIRED' });
|
||||
|
||||
oauthSvc.createOAuthClient.mockReturnValue({ client_id: 'c1', client_secret: 's' });
|
||||
const cookie = await request(server).post('/api/oauth/clients').set('Cookie', sessionCookie(1)).send({ name: 'CLI', allowed_scopes: ['a'] });
|
||||
expect(cookie.status).toBe(201);
|
||||
expect(cookie.body).toEqual({ client_id: 'c1', client_secret: 's' });
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,86 @@
|
||||
/**
|
||||
* OIDC e2e — exercises the migrated /api/auth/oidc flow with the real cookie
|
||||
* service. The OIDC service + auth toggles are mocked; this proves the flow is
|
||||
* unauthenticated, the sso-disabled 403, the login redirect, and that /exchange
|
||||
* sets the httpOnly trek_session cookie from a valid auth code.
|
||||
*/
|
||||
import { describe, it, expect, beforeAll, afterAll, beforeEach, vi } from 'vitest';
|
||||
import request from 'supertest';
|
||||
import cookieParser from 'cookie-parser';
|
||||
import type { Server } from 'http';
|
||||
import { Test } from '@nestjs/testing';
|
||||
|
||||
vi.mock('../../src/services/notifications', () => ({ getAppUrl: () => 'https://app' }));
|
||||
|
||||
const { toggles } = vi.hoisted(() => ({ toggles: { oidc_login: true } }));
|
||||
vi.mock('../../src/services/authService', () => ({ resolveAuthToggles: () => toggles }));
|
||||
|
||||
const { oidcSvc } = vi.hoisted(() => ({
|
||||
oidcSvc: {
|
||||
getOidcConfig: vi.fn(), discover: vi.fn(), createState: vi.fn(), consumeState: vi.fn(), createAuthCode: vi.fn(),
|
||||
consumeAuthCode: vi.fn(), exchangeCodeForToken: vi.fn(), getUserInfo: vi.fn(), verifyIdToken: vi.fn(),
|
||||
findOrCreateUser: vi.fn(), touchLastLogin: vi.fn(), generateToken: vi.fn(), frontendUrl: (p: string) => 'https://app' + p,
|
||||
},
|
||||
}));
|
||||
vi.mock('../../src/services/oidcService', () => oidcSvc);
|
||||
|
||||
import { OidcModule } from '../../src/nest/oidc/oidc.module';
|
||||
import { TrekExceptionFilter } from '../../src/nest/common/trek-exception.filter';
|
||||
|
||||
describe('OIDC e2e (real cookie service)', () => {
|
||||
let server: Server;
|
||||
let app: Awaited<ReturnType<typeof build>>;
|
||||
|
||||
async function build() {
|
||||
const moduleRef = await Test.createTestingModule({ imports: [OidcModule] }).compile();
|
||||
const nest = moduleRef.createNestApplication();
|
||||
nest.use(cookieParser());
|
||||
nest.useGlobalFilters(new TrekExceptionFilter());
|
||||
await nest.init();
|
||||
return nest;
|
||||
}
|
||||
|
||||
beforeAll(async () => {
|
||||
vi.spyOn(console, 'error').mockImplementation(() => {});
|
||||
app = await build();
|
||||
server = app.getHttpServer();
|
||||
oidcSvc.getOidcConfig.mockReturnValue({ issuer: 'https://idp', clientId: 'c', clientSecret: 's', discoveryUrl: null });
|
||||
oidcSvc.discover.mockResolvedValue({ authorization_endpoint: 'https://idp/auth', userinfo_endpoint: 'https://idp/ui', issuer: 'https://idp' });
|
||||
oidcSvc.createState.mockReturnValue({ state: 'st', codeChallenge: 'cc' });
|
||||
oidcSvc.consumeAuthCode.mockReturnValue({ token: 'jwt.value' });
|
||||
});
|
||||
|
||||
beforeEach(() => { toggles.oidc_login = true; });
|
||||
|
||||
afterAll(async () => {
|
||||
await app.close();
|
||||
});
|
||||
|
||||
it('GET /login is unauthenticated and redirects (302) to the provider', async () => {
|
||||
const res = await request(server).get('/api/auth/oidc/login').redirects(0);
|
||||
expect(res.status).toBe(302);
|
||||
expect(res.headers.location).toContain('https://idp/auth?');
|
||||
});
|
||||
|
||||
it('GET /login returns 403 when SSO is disabled', async () => {
|
||||
toggles.oidc_login = false;
|
||||
const res = await request(server).get('/api/auth/oidc/login');
|
||||
expect(res.status).toBe(403);
|
||||
expect(res.body).toEqual({ error: 'SSO login is disabled.' });
|
||||
});
|
||||
|
||||
it('GET /exchange 400 without a code', async () => {
|
||||
const res = await request(server).get('/api/auth/oidc/exchange');
|
||||
expect(res.status).toBe(400);
|
||||
expect(res.body).toEqual({ error: 'Code required' });
|
||||
});
|
||||
|
||||
it('GET /exchange sets the httpOnly trek_session cookie + returns the token', async () => {
|
||||
oidcSvc.consumeAuthCode.mockReturnValue({ token: 'jwt.value' });
|
||||
const res = await request(server).get('/api/auth/oidc/exchange').query({ code: 'good' });
|
||||
expect(res.status).toBe(200);
|
||||
expect(res.body).toEqual({ token: 'jwt.value' });
|
||||
const setCookie = res.headers['set-cookie'] as unknown as string[];
|
||||
expect(setCookie.some((c) => c.startsWith('trek_session=') && /HttpOnly/i.test(c))).toBe(true);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,106 @@
|
||||
/**
|
||||
* Packing module e2e — exercises the migrated /api/trips/:tripId/packing
|
||||
* endpoints through the real JwtAuthGuard against a temp SQLite db. The packing
|
||||
* service, permission check and WebSocket broadcast are mocked; this focuses on
|
||||
* auth, trip-access 404, permission 403, status codes and bodies.
|
||||
*/
|
||||
import { describe, it, expect, beforeAll, afterAll, beforeEach, 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';
|
||||
|
||||
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);');
|
||||
return { db: tmp };
|
||||
});
|
||||
|
||||
vi.mock('../../src/db/database', () => ({ db, closeDb: () => {}, reinitialize: () => {} }));
|
||||
vi.mock('../../src/websocket', () => ({ broadcast: vi.fn() }));
|
||||
vi.mock('../../src/services/notificationService', () => ({ send: vi.fn().mockResolvedValue(undefined) }));
|
||||
|
||||
const { checkPermission } = vi.hoisted(() => ({ checkPermission: vi.fn() }));
|
||||
vi.mock('../../src/services/permissions', () => ({ checkPermission }));
|
||||
|
||||
const { svc } = vi.hoisted(() => ({
|
||||
svc: {
|
||||
verifyTripAccess: vi.fn(), listItems: vi.fn(), createItem: vi.fn(), updateItem: vi.fn(),
|
||||
deleteItem: vi.fn(), bulkImport: vi.fn(), reorderItems: vi.fn(), listBags: vi.fn(),
|
||||
createBag: vi.fn(), updateBag: vi.fn(), deleteBag: vi.fn(), applyTemplate: vi.fn(),
|
||||
saveAsTemplate: vi.fn(), setBagMembers: vi.fn(), getCategoryAssignees: vi.fn(),
|
||||
updateCategoryAssignees: vi.fn(),
|
||||
},
|
||||
}));
|
||||
vi.mock('../../src/services/packingService', () => svc);
|
||||
|
||||
import { PackingModule } from '../../src/nest/packing/packing.module';
|
||||
import { TrekExceptionFilter } from '../../src/nest/common/trek-exception.filter';
|
||||
|
||||
describe('Packing e2e (real auth guard + temp SQLite)', () => {
|
||||
let server: Server;
|
||||
let app: Awaited<ReturnType<typeof build>>;
|
||||
|
||||
async function build() {
|
||||
const moduleRef = await Test.createTestingModule({ imports: [PackingModule] }).compile();
|
||||
const nest = moduleRef.createNestApplication();
|
||||
nest.use(cookieParser());
|
||||
nest.useGlobalFilters(new TrekExceptionFilter());
|
||||
await nest.init();
|
||||
return nest;
|
||||
}
|
||||
|
||||
beforeAll(async () => {
|
||||
seedUser(db as never, { id: 1 });
|
||||
app = await build();
|
||||
server = app.getHttpServer();
|
||||
svc.listItems.mockReturnValue([{ id: 1, name: 'Socks' }]);
|
||||
svc.createItem.mockReturnValue({ id: 9, name: 'Socks' });
|
||||
});
|
||||
|
||||
beforeEach(() => {
|
||||
svc.verifyTripAccess.mockReturnValue({ id: 5, user_id: 1 });
|
||||
checkPermission.mockReturnValue(true);
|
||||
});
|
||||
|
||||
afterAll(async () => {
|
||||
await app.close();
|
||||
});
|
||||
|
||||
it('401 without a session cookie', async () => {
|
||||
const res = await request(server).get('/api/trips/5/packing');
|
||||
expect(res.status).toBe(401);
|
||||
});
|
||||
|
||||
it('200 list for an accessible trip', async () => {
|
||||
const res = await request(server).get('/api/trips/5/packing').set('Cookie', sessionCookie(1));
|
||||
expect(res.status).toBe(200);
|
||||
expect(res.body).toEqual({ items: [{ id: 1, name: 'Socks' }] });
|
||||
});
|
||||
|
||||
it('404 when the trip is not accessible', async () => {
|
||||
svc.verifyTripAccess.mockReturnValue(undefined);
|
||||
const res = await request(server).get('/api/trips/5/packing').set('Cookie', sessionCookie(1));
|
||||
expect(res.status).toBe(404);
|
||||
expect(res.body).toEqual({ error: 'Trip not found' });
|
||||
});
|
||||
|
||||
it('201 on create with permission', async () => {
|
||||
const res = await request(server).post('/api/trips/5/packing').set('Cookie', sessionCookie(1)).send({ name: 'Socks' });
|
||||
expect(res.status).toBe(201);
|
||||
expect(res.body).toEqual({ item: { id: 9, name: 'Socks' } });
|
||||
});
|
||||
|
||||
it('403 on create without permission', async () => {
|
||||
checkPermission.mockReturnValue(false);
|
||||
const res = await request(server).post('/api/trips/5/packing').set('Cookie', sessionCookie(1)).send({ name: 'Socks' });
|
||||
expect(res.status).toBe(403);
|
||||
expect(res.body).toEqual({ error: 'No permission' });
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,114 @@
|
||||
/**
|
||||
* Places module e2e — exercises the migrated /api/trips/:tripId/places endpoints
|
||||
* through the real JwtAuthGuard against a temp SQLite db. placeService,
|
||||
* journeyService, the permission check, canAccessTrip and the WebSocket
|
||||
* broadcast are mocked.
|
||||
*/
|
||||
import { describe, it, expect, beforeAll, afterAll, beforeEach, 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';
|
||||
|
||||
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);`);
|
||||
return { db: tmp };
|
||||
});
|
||||
|
||||
const { canAccessTrip } = vi.hoisted(() => ({ canAccessTrip: vi.fn() }));
|
||||
vi.mock('../../src/db/database', () => ({
|
||||
db, canAccessTrip, isOwner: vi.fn(() => true), getPlaceWithTags: vi.fn(), closeDb: () => {}, reinitialize: () => {},
|
||||
}));
|
||||
vi.mock('../../src/websocket', () => ({ broadcast: vi.fn() }));
|
||||
vi.mock('../../src/services/journeyService', () => ({ onPlaceCreated: vi.fn(), onPlaceUpdated: vi.fn(), onPlaceDeleted: vi.fn() }));
|
||||
|
||||
const { checkPermission } = vi.hoisted(() => ({ checkPermission: vi.fn() }));
|
||||
vi.mock('../../src/services/permissions', () => ({ checkPermission }));
|
||||
|
||||
const { pl } = vi.hoisted(() => ({
|
||||
pl: {
|
||||
listPlaces: vi.fn(), createPlace: vi.fn(), getPlace: vi.fn(), updatePlace: vi.fn(), deletePlace: vi.fn(),
|
||||
deletePlacesMany: vi.fn(), importGpx: vi.fn(), importMapFile: vi.fn(), importGoogleList: vi.fn(),
|
||||
importNaverList: vi.fn(), searchPlaceImage: vi.fn(),
|
||||
},
|
||||
}));
|
||||
vi.mock('../../src/services/placeService', () => pl);
|
||||
|
||||
import { PlacesModule } from '../../src/nest/places/places.module';
|
||||
import { TrekExceptionFilter } from '../../src/nest/common/trek-exception.filter';
|
||||
|
||||
describe('Places e2e (real auth guard + temp SQLite)', () => {
|
||||
let server: Server;
|
||||
let app: Awaited<ReturnType<typeof build>>;
|
||||
|
||||
async function build() {
|
||||
const moduleRef = await Test.createTestingModule({ imports: [PlacesModule] }).compile();
|
||||
const nest = moduleRef.createNestApplication();
|
||||
nest.use(cookieParser());
|
||||
nest.useGlobalFilters(new TrekExceptionFilter());
|
||||
await nest.init();
|
||||
return nest;
|
||||
}
|
||||
|
||||
beforeAll(async () => {
|
||||
seedUser(db as never, { id: 1 });
|
||||
app = await build();
|
||||
server = app.getHttpServer();
|
||||
pl.listPlaces.mockReturnValue([{ id: 1, name: 'Spot' }]);
|
||||
pl.createPlace.mockReturnValue({ id: 9, name: 'Spot' });
|
||||
pl.deletePlacesMany.mockReturnValue([1, 2]);
|
||||
});
|
||||
|
||||
beforeEach(() => {
|
||||
canAccessTrip.mockReturnValue({ id: 5, user_id: 1 });
|
||||
checkPermission.mockReturnValue(true);
|
||||
});
|
||||
|
||||
afterAll(async () => {
|
||||
await app.close();
|
||||
});
|
||||
|
||||
it('401 without a cookie', async () => {
|
||||
expect((await request(server).get('/api/trips/5/places')).status).toBe(401);
|
||||
});
|
||||
|
||||
it('200 list', async () => {
|
||||
const res = await request(server).get('/api/trips/5/places').set('Cookie', sessionCookie(1));
|
||||
expect(res.status).toBe(200);
|
||||
expect(res.body).toEqual({ places: [{ id: 1, name: 'Spot' }] });
|
||||
});
|
||||
|
||||
it('201 create, 403 without permission, 400 over-long name', async () => {
|
||||
const ok = await request(server).post('/api/trips/5/places').set('Cookie', sessionCookie(1)).send({ name: 'Spot' });
|
||||
expect(ok.status).toBe(201);
|
||||
expect(ok.body).toEqual({ place: { id: 9, name: 'Spot' } });
|
||||
const long = await request(server).post('/api/trips/5/places').set('Cookie', sessionCookie(1)).send({ name: 'x'.repeat(201) });
|
||||
expect(long.status).toBe(400);
|
||||
expect(long.body).toEqual({ error: 'name must be 200 characters or less' });
|
||||
checkPermission.mockReturnValue(false);
|
||||
const forbidden = await request(server).post('/api/trips/5/places').set('Cookie', sessionCookie(1)).send({ name: 'Spot' });
|
||||
expect(forbidden.status).toBe(403);
|
||||
});
|
||||
|
||||
it('200 (not 201) bulk-delete, 400 on bad ids', async () => {
|
||||
const ok = await request(server).post('/api/trips/5/places/bulk-delete').set('Cookie', sessionCookie(1)).send({ ids: [1, 2] });
|
||||
expect(ok.status).toBe(200);
|
||||
expect(ok.body).toEqual({ deleted: [1, 2], count: 2 });
|
||||
const bad = await request(server).post('/api/trips/5/places/bulk-delete').set('Cookie', sessionCookie(1)).send({ ids: ['a'] });
|
||||
expect(bad.status).toBe(400);
|
||||
expect(bad.body).toEqual({ error: 'ids must be an array of numbers' });
|
||||
});
|
||||
|
||||
it('404 trip when not accessible', async () => {
|
||||
canAccessTrip.mockReturnValue(undefined);
|
||||
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' });
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,134 @@
|
||||
/**
|
||||
* Reservations + accommodations module e2e — exercises both migrated mounts
|
||||
* through the real JwtAuthGuard against a temp SQLite db. The reservation/day/
|
||||
* budget services, the permission check, canAccessTrip and the WebSocket
|
||||
* broadcast are mocked.
|
||||
*/
|
||||
import { describe, it, expect, beforeAll, afterAll, beforeEach, 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';
|
||||
|
||||
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);');
|
||||
return { db: tmp };
|
||||
});
|
||||
|
||||
const { canAccessTrip } = vi.hoisted(() => ({ canAccessTrip: vi.fn() }));
|
||||
vi.mock('../../src/db/database', () => ({
|
||||
db, canAccessTrip, isOwner: vi.fn(() => true), getPlaceWithTags: vi.fn(), closeDb: () => {}, reinitialize: () => {},
|
||||
}));
|
||||
vi.mock('../../src/websocket', () => ({ broadcast: vi.fn() }));
|
||||
vi.mock('../../src/services/notificationService', () => ({ send: vi.fn().mockResolvedValue(undefined) }));
|
||||
|
||||
const { checkPermission } = vi.hoisted(() => ({ checkPermission: vi.fn() }));
|
||||
vi.mock('../../src/services/permissions', () => ({ checkPermission }));
|
||||
|
||||
const { resv, budget, day } = vi.hoisted(() => ({
|
||||
resv: {
|
||||
verifyTripAccess: vi.fn(), listReservations: vi.fn(), createReservation: vi.fn(), updatePositions: vi.fn(),
|
||||
getReservation: vi.fn(), updateReservation: vi.fn(), deleteReservation: vi.fn(),
|
||||
},
|
||||
budget: { createBudgetItem: vi.fn(), updateBudgetItem: vi.fn(), deleteBudgetItem: vi.fn(), linkBudgetItemToReservation: vi.fn() },
|
||||
day: {
|
||||
listAccommodations: vi.fn(), validateAccommodationRefs: vi.fn(), createAccommodation: vi.fn(),
|
||||
getAccommodation: vi.fn(), updateAccommodation: vi.fn(), deleteAccommodation: vi.fn(),
|
||||
},
|
||||
}));
|
||||
vi.mock('../../src/services/reservationService', () => resv);
|
||||
vi.mock('../../src/services/budgetService', () => budget);
|
||||
vi.mock('../../src/services/dayService', () => day);
|
||||
|
||||
import { ReservationsModule } from '../../src/nest/reservations/reservations.module';
|
||||
import { TrekExceptionFilter } from '../../src/nest/common/trek-exception.filter';
|
||||
|
||||
describe('Reservations + accommodations e2e (real auth guard + temp SQLite)', () => {
|
||||
let server: Server;
|
||||
let app: Awaited<ReturnType<typeof build>>;
|
||||
|
||||
async function build() {
|
||||
const moduleRef = await Test.createTestingModule({ imports: [ReservationsModule] }).compile();
|
||||
const nest = moduleRef.createNestApplication();
|
||||
nest.use(cookieParser());
|
||||
nest.useGlobalFilters(new TrekExceptionFilter());
|
||||
await nest.init();
|
||||
return nest;
|
||||
}
|
||||
|
||||
beforeAll(async () => {
|
||||
seedUser(db as never, { id: 1 });
|
||||
app = await build();
|
||||
server = app.getHttpServer();
|
||||
resv.listReservations.mockReturnValue([{ id: 1, title: 'Hotel' }]);
|
||||
resv.createReservation.mockReturnValue({ reservation: { id: 9, title: 'Hotel' }, accommodationCreated: false });
|
||||
day.listAccommodations.mockReturnValue([{ id: 1 }]);
|
||||
day.validateAccommodationRefs.mockReturnValue([]);
|
||||
day.createAccommodation.mockReturnValue({ id: 9 });
|
||||
});
|
||||
|
||||
beforeEach(() => {
|
||||
resv.verifyTripAccess.mockReturnValue({ id: 5, user_id: 1 });
|
||||
canAccessTrip.mockReturnValue({ id: 5, user_id: 1 });
|
||||
checkPermission.mockReturnValue(true);
|
||||
});
|
||||
|
||||
afterAll(async () => {
|
||||
await app.close();
|
||||
});
|
||||
|
||||
it('401 without a cookie (reservations)', async () => {
|
||||
expect((await request(server).get('/api/trips/5/reservations')).status).toBe(401);
|
||||
});
|
||||
|
||||
it('200 list reservations', async () => {
|
||||
const res = await request(server).get('/api/trips/5/reservations').set('Cookie', sessionCookie(1));
|
||||
expect(res.status).toBe(200);
|
||||
expect(res.body).toEqual({ reservations: [{ id: 1, title: 'Hotel' }] });
|
||||
});
|
||||
|
||||
it('404 when trip not accessible (reservations)', async () => {
|
||||
resv.verifyTripAccess.mockReturnValue(undefined);
|
||||
const res = await request(server).get('/api/trips/5/reservations').set('Cookie', sessionCookie(1));
|
||||
expect(res.status).toBe(404);
|
||||
expect(res.body).toEqual({ error: 'Trip not found' });
|
||||
});
|
||||
|
||||
it('201 create reservation, 400 without title', async () => {
|
||||
const ok = await request(server).post('/api/trips/5/reservations').set('Cookie', sessionCookie(1)).send({ title: 'Hotel' });
|
||||
expect(ok.status).toBe(201);
|
||||
expect(ok.body).toEqual({ reservation: { id: 9, title: 'Hotel' } });
|
||||
const bad = await request(server).post('/api/trips/5/reservations').set('Cookie', sessionCookie(1)).send({});
|
||||
expect(bad.status).toBe(400);
|
||||
expect(bad.body).toEqual({ error: 'Title is required' });
|
||||
});
|
||||
|
||||
it('200 list accommodations + 201 create', async () => {
|
||||
const list = await request(server).get('/api/trips/5/accommodations').set('Cookie', sessionCookie(1));
|
||||
expect(list.status).toBe(200);
|
||||
expect(list.body).toEqual({ accommodations: [{ id: 1 }] });
|
||||
const create = await request(server).post('/api/trips/5/accommodations').set('Cookie', sessionCookie(1)).send({ place_id: 2, start_day_id: 10, end_day_id: 11 });
|
||||
expect(create.status).toBe(201);
|
||||
expect(create.body).toEqual({ accommodation: { id: 9 } });
|
||||
});
|
||||
|
||||
it('404 when trip not accessible (accommodations)', async () => {
|
||||
canAccessTrip.mockReturnValue(undefined);
|
||||
const res = await request(server).get('/api/trips/5/accommodations').set('Cookie', sessionCookie(1));
|
||||
expect(res.status).toBe(404);
|
||||
expect(res.body).toEqual({ error: 'Trip not found' });
|
||||
});
|
||||
|
||||
it('400 accommodation create without refs', async () => {
|
||||
const res = await request(server).post('/api/trips/5/accommodations').set('Cookie', sessionCookie(1)).send({ place_id: 2 });
|
||||
expect(res.status).toBe(400);
|
||||
expect(res.body).toEqual({ error: 'place_id, start_day_id, and end_day_id are required' });
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,90 @@
|
||||
/**
|
||||
* Settings e2e — exercises the migrated /api/settings endpoints through the real
|
||||
* JwtAuthGuard against a temp SQLite db. The settings service is mocked; this
|
||||
* focuses on auth, the 400 guards, the masked-sentinel no-op and status codes.
|
||||
*/
|
||||
import { describe, it, expect, beforeAll, afterAll, beforeEach, 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';
|
||||
|
||||
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);`);
|
||||
return { db: tmp };
|
||||
});
|
||||
|
||||
vi.mock('../../src/db/database', () => ({ db, closeDb: () => {}, reinitialize: () => {} }));
|
||||
|
||||
const { settingsSvc } = vi.hoisted(() => ({
|
||||
settingsSvc: { getUserSettings: vi.fn(), upsertSetting: vi.fn(), bulkUpsertSettings: vi.fn() },
|
||||
}));
|
||||
vi.mock('../../src/services/settingsService', () => settingsSvc);
|
||||
|
||||
import { SettingsModule } from '../../src/nest/settings/settings.module';
|
||||
import { TrekExceptionFilter } from '../../src/nest/common/trek-exception.filter';
|
||||
|
||||
describe('Settings e2e (real auth guard + temp SQLite)', () => {
|
||||
let server: Server;
|
||||
let app: Awaited<ReturnType<typeof build>>;
|
||||
|
||||
async function build() {
|
||||
const moduleRef = await Test.createTestingModule({ imports: [SettingsModule] }).compile();
|
||||
const nest = moduleRef.createNestApplication();
|
||||
nest.use(cookieParser());
|
||||
nest.useGlobalFilters(new TrekExceptionFilter());
|
||||
await nest.init();
|
||||
return nest;
|
||||
}
|
||||
|
||||
beforeAll(async () => {
|
||||
seedUser(db as never, { id: 1 });
|
||||
app = await build();
|
||||
server = app.getHttpServer();
|
||||
settingsSvc.getUserSettings.mockReturnValue({ theme: 'dark' });
|
||||
settingsSvc.bulkUpsertSettings.mockReturnValue(2);
|
||||
});
|
||||
|
||||
beforeEach(() => vi.clearAllMocks());
|
||||
|
||||
afterAll(async () => {
|
||||
await app.close();
|
||||
});
|
||||
|
||||
it('401 without a session cookie', async () => {
|
||||
expect((await request(server).get('/api/settings')).status).toBe(401);
|
||||
});
|
||||
|
||||
it('200 list with a session', async () => {
|
||||
settingsSvc.getUserSettings.mockReturnValue({ theme: 'dark' });
|
||||
const res = await request(server).get('/api/settings').set('Cookie', sessionCookie(1));
|
||||
expect(res.status).toBe(200);
|
||||
expect(res.body).toEqual({ settings: { theme: 'dark' } });
|
||||
});
|
||||
|
||||
it('PUT 400 without a key', async () => {
|
||||
const res = await request(server).put('/api/settings').set('Cookie', sessionCookie(1)).send({ value: 'x' });
|
||||
expect(res.status).toBe(400);
|
||||
expect(res.body).toEqual({ error: 'Key is required' });
|
||||
});
|
||||
|
||||
it('PUT no-ops on the masked sentinel', async () => {
|
||||
const res = await request(server).put('/api/settings').set('Cookie', sessionCookie(1)).send({ key: 'secret', value: '••••••••' });
|
||||
expect(res.status).toBe(200);
|
||||
expect(res.body).toEqual({ success: true, key: 'secret', unchanged: true });
|
||||
expect(settingsSvc.upsertSetting).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('POST /bulk 200', async () => {
|
||||
settingsSvc.bulkUpsertSettings.mockReturnValue(2);
|
||||
const res = await request(server).post('/api/settings/bulk').set('Cookie', sessionCookie(1)).send({ settings: { a: 1, b: 2 } });
|
||||
expect(res.status).toBe(200);
|
||||
expect(res.body).toEqual({ success: true, updated: 2 });
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,109 @@
|
||||
/**
|
||||
* Share-link e2e — exercises the migrated /api/trips/:tripId/share-link and the
|
||||
* public /api/shared/:token endpoints through the real JwtAuthGuard against a
|
||||
* temp SQLite db. The share service + permission check are mocked; this focuses
|
||||
* on auth, trip-access 404, permission 403, the create-201-vs-update-200 split
|
||||
* and the unguarded public read.
|
||||
*/
|
||||
import { describe, it, expect, beforeAll, afterAll, beforeEach, 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';
|
||||
|
||||
const { db, canAccessTrip } = 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);`);
|
||||
return { db: tmp, canAccessTrip: vi.fn() };
|
||||
});
|
||||
|
||||
vi.mock('../../src/db/database', () => ({ db, canAccessTrip, closeDb: () => {}, reinitialize: () => {} }));
|
||||
|
||||
const { checkPermission } = vi.hoisted(() => ({ checkPermission: vi.fn() }));
|
||||
vi.mock('../../src/services/permissions', () => ({ checkPermission }));
|
||||
|
||||
const { shareSvc } = vi.hoisted(() => ({
|
||||
shareSvc: { createOrUpdateShareLink: vi.fn(), getShareLink: vi.fn(), deleteShareLink: vi.fn(), getSharedTripData: vi.fn() },
|
||||
}));
|
||||
vi.mock('../../src/services/shareService', () => shareSvc);
|
||||
|
||||
import { ShareModule } from '../../src/nest/share/share.module';
|
||||
import { TrekExceptionFilter } from '../../src/nest/common/trek-exception.filter';
|
||||
|
||||
describe('Share-link e2e (real auth guard + temp SQLite)', () => {
|
||||
let server: Server;
|
||||
let app: Awaited<ReturnType<typeof build>>;
|
||||
|
||||
async function build() {
|
||||
const moduleRef = await Test.createTestingModule({ imports: [ShareModule] }).compile();
|
||||
const nest = moduleRef.createNestApplication();
|
||||
nest.use(cookieParser());
|
||||
nest.useGlobalFilters(new TrekExceptionFilter());
|
||||
await nest.init();
|
||||
return nest;
|
||||
}
|
||||
|
||||
beforeAll(async () => {
|
||||
seedUser(db as never, { id: 1 });
|
||||
app = await build();
|
||||
server = app.getHttpServer();
|
||||
shareSvc.getSharedTripData.mockReturnValue({ trip: { id: 9 } });
|
||||
});
|
||||
|
||||
beforeEach(() => {
|
||||
canAccessTrip.mockReturnValue({ user_id: 1 });
|
||||
checkPermission.mockReturnValue(true);
|
||||
});
|
||||
|
||||
afterAll(async () => {
|
||||
await app.close();
|
||||
});
|
||||
|
||||
it('401 without a session cookie', async () => {
|
||||
expect((await request(server).get('/api/trips/5/share-link')).status).toBe(401);
|
||||
});
|
||||
|
||||
it('201 on first create, 200 on a subsequent update', async () => {
|
||||
shareSvc.createOrUpdateShareLink.mockReturnValueOnce({ token: 't', created: true });
|
||||
const created = await request(server).post('/api/trips/5/share-link').set('Cookie', sessionCookie(1)).send({ share_map: true });
|
||||
expect(created.status).toBe(201);
|
||||
expect(created.body).toEqual({ token: 't' });
|
||||
|
||||
shareSvc.createOrUpdateShareLink.mockReturnValueOnce({ token: 't', created: false });
|
||||
const updated = await request(server).post('/api/trips/5/share-link').set('Cookie', sessionCookie(1)).send({});
|
||||
expect(updated.status).toBe(200);
|
||||
expect(updated.body).toEqual({ token: 't' });
|
||||
});
|
||||
|
||||
it('403 without share_manage', async () => {
|
||||
checkPermission.mockReturnValue(false);
|
||||
const res = await request(server).post('/api/trips/5/share-link').set('Cookie', sessionCookie(1)).send({});
|
||||
expect(res.status).toBe(403);
|
||||
expect(res.body).toEqual({ error: 'No permission' });
|
||||
});
|
||||
|
||||
it('404 when the trip is not accessible', async () => {
|
||||
canAccessTrip.mockReturnValue(undefined);
|
||||
const res = await request(server).get('/api/trips/5/share-link').set('Cookie', sessionCookie(1));
|
||||
expect(res.status).toBe(404);
|
||||
expect(res.body).toEqual({ error: 'Trip not found' });
|
||||
});
|
||||
|
||||
it('public shared read is unguarded (200, no cookie)', async () => {
|
||||
const res = await request(server).get('/api/shared/tok');
|
||||
expect(res.status).toBe(200);
|
||||
expect(res.body).toEqual({ trip: { id: 9 } });
|
||||
});
|
||||
|
||||
it('public shared read 404 for an invalid token', async () => {
|
||||
shareSvc.getSharedTripData.mockReturnValueOnce(null);
|
||||
const res = await request(server).get('/api/shared/bad');
|
||||
expect(res.status).toBe(404);
|
||||
expect(res.body).toEqual({ error: 'Invalid or expired link' });
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,92 @@
|
||||
/**
|
||||
* System-notices module e2e — exercises the migrated /api/system-notices
|
||||
* endpoints through the real JwtAuthGuard against a temp SQLite db. The notices
|
||||
* service is mocked so the test doesn't depend on the static registry or the
|
||||
* dismissal tables; it focuses on routing, auth, status codes and bodies.
|
||||
*/
|
||||
import { describe, it, expect, beforeAll, 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';
|
||||
|
||||
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);`);
|
||||
return { db: tmp };
|
||||
});
|
||||
|
||||
vi.mock('../../src/db/database', () => ({ db, closeDb: () => {}, reinitialize: () => {} }));
|
||||
|
||||
const { mockGetActive, mockDismiss } = vi.hoisted(() => ({ mockGetActive: vi.fn(), mockDismiss: vi.fn() }));
|
||||
vi.mock('../../src/systemNotices/service', () => ({
|
||||
getActiveNoticesFor: mockGetActive,
|
||||
dismissNotice: mockDismiss,
|
||||
}));
|
||||
|
||||
import { SystemNoticesModule } from '../../src/nest/system-notices/system-notices.module';
|
||||
import { TrekExceptionFilter } from '../../src/nest/common/trek-exception.filter';
|
||||
|
||||
const notice = {
|
||||
id: 'welcome', display: 'modal', severity: 'info',
|
||||
titleKey: 'notice.welcome.title', bodyKey: 'notice.welcome.body', dismissible: true,
|
||||
};
|
||||
|
||||
describe('System-notices e2e (real auth guard + temp SQLite)', () => {
|
||||
let server: Server;
|
||||
let app: Awaited<ReturnType<typeof build>>;
|
||||
|
||||
async function build() {
|
||||
const moduleRef = await Test.createTestingModule({ imports: [SystemNoticesModule] }).compile();
|
||||
const nest = moduleRef.createNestApplication();
|
||||
nest.use(cookieParser());
|
||||
nest.useGlobalFilters(new TrekExceptionFilter());
|
||||
await nest.init();
|
||||
return nest;
|
||||
}
|
||||
|
||||
beforeAll(async () => {
|
||||
seedUser(db as never, { id: 1 });
|
||||
app = await build();
|
||||
server = app.getHttpServer();
|
||||
});
|
||||
|
||||
afterAll(async () => {
|
||||
await app.close();
|
||||
});
|
||||
|
||||
it('401 without a session cookie', async () => {
|
||||
const res = await request(server).get('/api/system-notices/active');
|
||||
expect(res.status).toBe(401);
|
||||
expect(res.body).toEqual({ error: 'Access token required', code: 'AUTH_REQUIRED' });
|
||||
});
|
||||
|
||||
it('200 with the active notices for the user', async () => {
|
||||
mockGetActive.mockReturnValue([notice]);
|
||||
const res = await request(server).get('/api/system-notices/active').set('Cookie', sessionCookie(1));
|
||||
expect(res.status).toBe(200);
|
||||
expect(res.body).toEqual([notice]);
|
||||
expect(mockGetActive).toHaveBeenCalledWith(1);
|
||||
});
|
||||
|
||||
it('204 with no body on a successful dismiss', async () => {
|
||||
mockDismiss.mockReturnValue(true);
|
||||
const res = await request(server).post('/api/system-notices/welcome/dismiss').set('Cookie', sessionCookie(1));
|
||||
expect(res.status).toBe(204);
|
||||
expect(res.body).toEqual({});
|
||||
expect(res.text).toBe('');
|
||||
expect(mockDismiss).toHaveBeenCalledWith(1, 'welcome');
|
||||
});
|
||||
|
||||
it('404 { error: NOTICE_NOT_FOUND } when the id is unknown', async () => {
|
||||
mockDismiss.mockReturnValue(false);
|
||||
const res = await request(server).post('/api/system-notices/nope/dismiss').set('Cookie', sessionCookie(1));
|
||||
expect(res.status).toBe(404);
|
||||
expect(res.body).toEqual({ error: 'NOTICE_NOT_FOUND' });
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,111 @@
|
||||
/**
|
||||
* Tags module e2e — exercises the migrated /api/tags endpoints through the real
|
||||
* JwtAuthGuard against a temp SQLite db. tagService is mocked; tags are
|
||||
* user-scoped (no admin gate), so a normal authenticated user can do everything.
|
||||
*/
|
||||
import { describe, it, expect, beforeAll, 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';
|
||||
|
||||
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);`);
|
||||
return { db: tmp };
|
||||
});
|
||||
|
||||
vi.mock('../../src/db/database', () => ({ db, closeDb: () => {}, reinitialize: () => {} }));
|
||||
|
||||
const { mocks } = vi.hoisted(() => ({
|
||||
mocks: {
|
||||
listTags: vi.fn(),
|
||||
createTag: vi.fn(),
|
||||
getTagByIdAndUser: vi.fn(),
|
||||
updateTag: vi.fn(),
|
||||
deleteTag: vi.fn(),
|
||||
},
|
||||
}));
|
||||
vi.mock('../../src/services/tagService', () => mocks);
|
||||
|
||||
import { TagsModule } from '../../src/nest/tags/tags.module';
|
||||
import { TrekExceptionFilter } from '../../src/nest/common/trek-exception.filter';
|
||||
|
||||
const tag = { id: 1, user_id: 1, name: 'Beach', color: '#10b981' };
|
||||
|
||||
describe('Tags e2e (real auth guard + temp SQLite)', () => {
|
||||
let server: Server;
|
||||
let app: Awaited<ReturnType<typeof build>>;
|
||||
|
||||
async function build() {
|
||||
const moduleRef = await Test.createTestingModule({ imports: [TagsModule] }).compile();
|
||||
const nest = moduleRef.createNestApplication();
|
||||
nest.use(cookieParser());
|
||||
nest.useGlobalFilters(new TrekExceptionFilter());
|
||||
await nest.init();
|
||||
return nest;
|
||||
}
|
||||
|
||||
beforeAll(async () => {
|
||||
seedUser(db as never, { id: 1 });
|
||||
app = await build();
|
||||
server = app.getHttpServer();
|
||||
mocks.listTags.mockReturnValue([tag]);
|
||||
mocks.createTag.mockReturnValue(tag);
|
||||
mocks.getTagByIdAndUser.mockImplementation((id: string | number) => (String(id) === '1' ? tag : undefined));
|
||||
mocks.updateTag.mockReturnValue({ ...tag, name: 'Hike' });
|
||||
});
|
||||
|
||||
afterAll(async () => {
|
||||
await app.close();
|
||||
});
|
||||
|
||||
it('401 without a session cookie', async () => {
|
||||
const res = await request(server).get('/api/tags');
|
||||
expect(res.status).toBe(401);
|
||||
});
|
||||
|
||||
it('200 list scoped to the user', async () => {
|
||||
const res = await request(server).get('/api/tags').set('Cookie', sessionCookie(1));
|
||||
expect(res.status).toBe(200);
|
||||
expect(res.body).toEqual({ tags: [tag] });
|
||||
expect(mocks.listTags).toHaveBeenCalledWith(1);
|
||||
});
|
||||
|
||||
it('201 on create', async () => {
|
||||
const res = await request(server).post('/api/tags').set('Cookie', sessionCookie(1)).send({ name: 'Beach', color: '#10b981' });
|
||||
expect(res.status).toBe(201);
|
||||
expect(res.body).toEqual({ tag });
|
||||
expect(mocks.createTag).toHaveBeenCalledWith(1, 'Beach', '#10b981');
|
||||
});
|
||||
|
||||
it('400 on create without a name', async () => {
|
||||
const res = await request(server).post('/api/tags').set('Cookie', sessionCookie(1)).send({});
|
||||
expect(res.status).toBe(400);
|
||||
expect(res.body).toEqual({ error: 'Tag name is required' });
|
||||
});
|
||||
|
||||
it('200 on update of an owned tag', async () => {
|
||||
const res = await request(server).put('/api/tags/1').set('Cookie', sessionCookie(1)).send({ name: 'Hike' });
|
||||
expect(res.status).toBe(200);
|
||||
expect(res.body).toEqual({ tag: { ...tag, name: 'Hike' } });
|
||||
});
|
||||
|
||||
it('404 on update of a tag the user does not own', async () => {
|
||||
const res = await request(server).put('/api/tags/9').set('Cookie', sessionCookie(1)).send({ name: 'X' });
|
||||
expect(res.status).toBe(404);
|
||||
expect(res.body).toEqual({ error: 'Tag not found' });
|
||||
});
|
||||
|
||||
it('200 on delete of an owned tag', async () => {
|
||||
const res = await request(server).delete('/api/tags/1').set('Cookie', sessionCookie(1));
|
||||
expect(res.status).toBe(200);
|
||||
expect(res.body).toEqual({ success: true });
|
||||
expect(mocks.deleteTag).toHaveBeenCalledWith('1');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,100 @@
|
||||
/**
|
||||
* To-do module e2e — exercises the migrated /api/trips/:tripId/todo endpoints
|
||||
* through the real JwtAuthGuard against a temp SQLite db. todoService, the
|
||||
* permission check and the WebSocket broadcast are mocked.
|
||||
*/
|
||||
import { describe, it, expect, beforeAll, afterAll, beforeEach, 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';
|
||||
|
||||
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);`);
|
||||
return { db: tmp };
|
||||
});
|
||||
|
||||
vi.mock('../../src/db/database', () => ({ db, closeDb: () => {}, reinitialize: () => {} }));
|
||||
vi.mock('../../src/websocket', () => ({ broadcast: vi.fn() }));
|
||||
|
||||
const { checkPermission } = vi.hoisted(() => ({ checkPermission: vi.fn() }));
|
||||
vi.mock('../../src/services/permissions', () => ({ checkPermission }));
|
||||
|
||||
const { svc } = vi.hoisted(() => ({
|
||||
svc: {
|
||||
verifyTripAccess: vi.fn(), listItems: vi.fn(), createItem: vi.fn(), updateItem: vi.fn(),
|
||||
deleteItem: vi.fn(), reorderItems: vi.fn(), getCategoryAssignees: vi.fn(), updateCategoryAssignees: vi.fn(),
|
||||
},
|
||||
}));
|
||||
vi.mock('../../src/services/todoService', () => svc);
|
||||
|
||||
import { TodoModule } from '../../src/nest/todo/todo.module';
|
||||
import { TrekExceptionFilter } from '../../src/nest/common/trek-exception.filter';
|
||||
|
||||
describe('To-do e2e (real auth guard + temp SQLite)', () => {
|
||||
let server: Server;
|
||||
let app: Awaited<ReturnType<typeof build>>;
|
||||
|
||||
async function build() {
|
||||
const moduleRef = await Test.createTestingModule({ imports: [TodoModule] }).compile();
|
||||
const nest = moduleRef.createNestApplication();
|
||||
nest.use(cookieParser());
|
||||
nest.useGlobalFilters(new TrekExceptionFilter());
|
||||
await nest.init();
|
||||
return nest;
|
||||
}
|
||||
|
||||
beforeAll(async () => {
|
||||
seedUser(db as never, { id: 1 });
|
||||
app = await build();
|
||||
server = app.getHttpServer();
|
||||
svc.listItems.mockReturnValue([{ id: 1, name: 'Book hotel' }]);
|
||||
svc.createItem.mockReturnValue({ id: 9, name: 'Book hotel' });
|
||||
});
|
||||
|
||||
beforeEach(() => {
|
||||
svc.verifyTripAccess.mockReturnValue({ id: 5, user_id: 1 });
|
||||
checkPermission.mockReturnValue(true);
|
||||
});
|
||||
|
||||
afterAll(async () => {
|
||||
await app.close();
|
||||
});
|
||||
|
||||
it('401 without a session cookie', async () => {
|
||||
const res = await request(server).get('/api/trips/5/todo');
|
||||
expect(res.status).toBe(401);
|
||||
});
|
||||
|
||||
it('200 list for an accessible trip', async () => {
|
||||
const res = await request(server).get('/api/trips/5/todo').set('Cookie', sessionCookie(1));
|
||||
expect(res.status).toBe(200);
|
||||
expect(res.body).toEqual({ items: [{ id: 1, name: 'Book hotel' }] });
|
||||
});
|
||||
|
||||
it('404 when the trip is not accessible', async () => {
|
||||
svc.verifyTripAccess.mockReturnValue(undefined);
|
||||
const res = await request(server).get('/api/trips/5/todo').set('Cookie', sessionCookie(1));
|
||||
expect(res.status).toBe(404);
|
||||
expect(res.body).toEqual({ error: 'Trip not found' });
|
||||
});
|
||||
|
||||
it('201 on create with permission', async () => {
|
||||
const res = await request(server).post('/api/trips/5/todo').set('Cookie', sessionCookie(1)).send({ name: 'Book hotel' });
|
||||
expect(res.status).toBe(201);
|
||||
expect(res.body).toEqual({ item: { id: 9, name: 'Book hotel' } });
|
||||
});
|
||||
|
||||
it('403 on create without permission', async () => {
|
||||
checkPermission.mockReturnValue(false);
|
||||
const res = await request(server).post('/api/trips/5/todo').set('Cookie', sessionCookie(1)).send({ name: 'Book hotel' });
|
||||
expect(res.status).toBe(403);
|
||||
expect(res.body).toEqual({ error: 'No permission' });
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,119 @@
|
||||
/**
|
||||
* Trips module e2e — exercises the migrated /api/trips aggregate-root endpoints
|
||||
* through the real JwtAuthGuard against a temp SQLite db. tripService, the bundle
|
||||
* list-services, auditLog, demo, the permission check, canAccessTrip and the
|
||||
* WebSocket broadcast are mocked.
|
||||
*/
|
||||
import { describe, it, expect, beforeAll, afterAll, beforeEach, 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';
|
||||
|
||||
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);');
|
||||
return { db: tmp };
|
||||
});
|
||||
|
||||
const { canAccessTrip } = vi.hoisted(() => ({ canAccessTrip: vi.fn() }));
|
||||
vi.mock('../../src/db/database', () => ({
|
||||
db, canAccessTrip, isOwner: vi.fn(() => true), getPlaceWithTags: vi.fn(), closeDb: () => {}, reinitialize: () => {},
|
||||
}));
|
||||
vi.mock('../../src/websocket', () => ({ broadcast: vi.fn() }));
|
||||
vi.mock('../../src/services/notificationService', () => ({ send: vi.fn().mockResolvedValue(undefined) }));
|
||||
vi.mock('../../src/services/auditLog', () => ({ writeAudit: vi.fn(), getClientIp: vi.fn(() => '1.2.3.4'), logInfo: vi.fn() }));
|
||||
vi.mock('../../src/services/demo', () => ({ isDemoEmail: vi.fn(() => false) }));
|
||||
|
||||
const { checkPermission } = vi.hoisted(() => ({ checkPermission: vi.fn() }));
|
||||
vi.mock('../../src/services/permissions', () => ({ checkPermission }));
|
||||
|
||||
const { tripSvc } = vi.hoisted(() => ({
|
||||
tripSvc: {
|
||||
listTrips: vi.fn(), createTrip: vi.fn(), getTrip: vi.fn(), updateTrip: vi.fn(), deleteTrip: vi.fn(),
|
||||
getTripRaw: vi.fn(), getTripOwner: vi.fn(), deleteOldCover: vi.fn(), updateCoverImage: vi.fn(),
|
||||
listMembers: vi.fn(), addMember: vi.fn(), removeMember: vi.fn(), exportICS: vi.fn(), copyTripById: vi.fn(),
|
||||
verifyTripAccess: vi.fn(), NotFoundError: class NotFoundError extends Error {}, ValidationError: class ValidationError extends Error {}, TRIP_SELECT: 'SELECT',
|
||||
},
|
||||
}));
|
||||
vi.mock('../../src/services/tripService', () => tripSvc);
|
||||
vi.mock('../../src/services/dayService', () => ({ listDays: () => ({ days: [] }), listAccommodations: () => [] }));
|
||||
vi.mock('../../src/services/placeService', () => ({ listPlaces: () => [] }));
|
||||
vi.mock('../../src/services/packingService', () => ({ listItems: () => [] }));
|
||||
vi.mock('../../src/services/todoService', () => ({ listItems: () => [] }));
|
||||
vi.mock('../../src/services/budgetService', () => ({ listBudgetItems: () => [] }));
|
||||
vi.mock('../../src/services/reservationService', () => ({ listReservations: () => [] }));
|
||||
vi.mock('../../src/services/fileService', () => ({ listFiles: () => [] }));
|
||||
|
||||
import { TripsModule } from '../../src/nest/trips/trips.module';
|
||||
import { TrekExceptionFilter } from '../../src/nest/common/trek-exception.filter';
|
||||
|
||||
describe('Trips e2e (real auth guard + temp SQLite)', () => {
|
||||
let server: Server;
|
||||
let app: Awaited<ReturnType<typeof build>>;
|
||||
|
||||
async function build() {
|
||||
const moduleRef = await Test.createTestingModule({ imports: [TripsModule] }).compile();
|
||||
const nest = moduleRef.createNestApplication();
|
||||
nest.use(cookieParser());
|
||||
nest.useGlobalFilters(new TrekExceptionFilter());
|
||||
await nest.init();
|
||||
return nest;
|
||||
}
|
||||
|
||||
beforeAll(async () => {
|
||||
seedUser(db as never, { id: 1 });
|
||||
app = await build();
|
||||
server = app.getHttpServer();
|
||||
tripSvc.listTrips.mockReturnValue([{ id: 1, title: 'T' }]);
|
||||
tripSvc.createTrip.mockReturnValue({ trip: { id: 9 }, tripId: 9, reminderDays: 0 });
|
||||
tripSvc.getTrip.mockImplementation((id: string) => (id === '9' ? { id: 9, user_id: 1 } : undefined));
|
||||
tripSvc.listMembers.mockReturnValue({ owner: { id: 1 }, members: [] });
|
||||
});
|
||||
|
||||
beforeEach(() => {
|
||||
canAccessTrip.mockReturnValue({ user_id: 1 });
|
||||
checkPermission.mockReturnValue(true);
|
||||
});
|
||||
|
||||
afterAll(async () => {
|
||||
await app.close();
|
||||
});
|
||||
|
||||
it('401 without a cookie', async () => {
|
||||
expect((await request(server).get('/api/trips')).status).toBe(401);
|
||||
});
|
||||
|
||||
it('200 list', async () => {
|
||||
const res = await request(server).get('/api/trips').set('Cookie', sessionCookie(1));
|
||||
expect(res.status).toBe(200);
|
||||
expect(res.body).toEqual({ trips: [{ id: 1, title: 'T' }] });
|
||||
});
|
||||
|
||||
it('201 create, 403 without permission', async () => {
|
||||
const ok = await request(server).post('/api/trips').set('Cookie', sessionCookie(1)).send({ title: 'T' });
|
||||
expect(ok.status).toBe(201);
|
||||
expect(ok.body).toEqual({ trip: { id: 9 } });
|
||||
checkPermission.mockReturnValue(false);
|
||||
const forbidden = await request(server).post('/api/trips').set('Cookie', sessionCookie(1)).send({ title: 'T' });
|
||||
expect(forbidden.status).toBe(403);
|
||||
});
|
||||
|
||||
it('404 on a missing trip', async () => {
|
||||
const res = await request(server).get('/api/trips/77').set('Cookie', sessionCookie(1));
|
||||
expect(res.status).toBe(404);
|
||||
expect(res.body).toEqual({ error: 'Trip not found' });
|
||||
});
|
||||
|
||||
it('200 bundle for an accessible trip', async () => {
|
||||
const res = await request(server).get('/api/trips/9/bundle').set('Cookie', sessionCookie(1));
|
||||
expect(res.status).toBe(200);
|
||||
expect(res.body).toMatchObject({ trip: { id: 9 }, days: [], members: [{ id: 1 }] });
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,100 @@
|
||||
/**
|
||||
* Vacay module e2e — exercises the migrated /api/addons/vacay endpoints through
|
||||
* the real JwtAuthGuard against a temp SQLite db. vacayService is mocked; this
|
||||
* focuses on auth, status codes (POSTs stay 200) and a couple of validation/403
|
||||
* bodies.
|
||||
*/
|
||||
import { describe, it, expect, beforeAll, 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';
|
||||
|
||||
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);`);
|
||||
return { db: tmp };
|
||||
});
|
||||
|
||||
vi.mock('../../src/db/database', () => ({ db, closeDb: () => {}, reinitialize: () => {} }));
|
||||
|
||||
const { svc } = vi.hoisted(() => ({
|
||||
svc: {
|
||||
getPlanData: vi.fn(), getActivePlanId: vi.fn(), getActivePlan: vi.fn(), updatePlan: vi.fn(),
|
||||
addHolidayCalendar: vi.fn(), updateHolidayCalendar: vi.fn(), deleteHolidayCalendar: vi.fn(),
|
||||
getPlanUsers: vi.fn(), setUserColor: vi.fn(), sendInvite: vi.fn(), acceptInvite: vi.fn(),
|
||||
declineInvite: vi.fn(), cancelInvite: vi.fn(), dissolvePlan: vi.fn(), getAvailableUsers: vi.fn(),
|
||||
listYears: vi.fn(), addYear: vi.fn(), deleteYear: vi.fn(), getEntries: vi.fn(),
|
||||
toggleEntry: vi.fn(), toggleCompanyHoliday: vi.fn(), getStats: vi.fn(), updateStats: vi.fn(),
|
||||
getCountries: vi.fn(), getHolidays: vi.fn(),
|
||||
},
|
||||
}));
|
||||
vi.mock('../../src/services/vacayService', () => svc);
|
||||
|
||||
import { VacayModule } from '../../src/nest/vacay/vacay.module';
|
||||
import { TrekExceptionFilter } from '../../src/nest/common/trek-exception.filter';
|
||||
|
||||
describe('Vacay e2e (real auth guard + temp SQLite)', () => {
|
||||
let server: Server;
|
||||
let app: Awaited<ReturnType<typeof build>>;
|
||||
|
||||
async function build() {
|
||||
const moduleRef = await Test.createTestingModule({ imports: [VacayModule] }).compile();
|
||||
const nest = moduleRef.createNestApplication();
|
||||
nest.use(cookieParser());
|
||||
nest.useGlobalFilters(new TrekExceptionFilter());
|
||||
await nest.init();
|
||||
return nest;
|
||||
}
|
||||
|
||||
beforeAll(async () => {
|
||||
seedUser(db as never, { id: 1 });
|
||||
app = await build();
|
||||
server = app.getHttpServer();
|
||||
svc.getActivePlanId.mockReturnValue(10);
|
||||
svc.getActivePlan.mockReturnValue({ id: 10 });
|
||||
svc.getPlanUsers.mockReturnValue([{ id: 1 }]);
|
||||
svc.getPlanData.mockReturnValue({ plan: { id: 10 } });
|
||||
svc.toggleEntry.mockReturnValue({ action: 'added' });
|
||||
});
|
||||
|
||||
afterAll(async () => {
|
||||
await app.close();
|
||||
});
|
||||
|
||||
it('401 without a session cookie', async () => {
|
||||
const res = await request(server).get('/api/addons/vacay/plan');
|
||||
expect(res.status).toBe(401);
|
||||
});
|
||||
|
||||
it('200 plan for an authenticated user', async () => {
|
||||
const res = await request(server).get('/api/addons/vacay/plan').set('Cookie', sessionCookie(1));
|
||||
expect(res.status).toBe(200);
|
||||
expect(res.body).toEqual({ plan: { id: 10 } });
|
||||
});
|
||||
|
||||
it('200 (not 201) on POST entries/toggle, forwarding the socket id', async () => {
|
||||
const res = await request(server).post('/api/addons/vacay/entries/toggle')
|
||||
.set('Cookie', sessionCookie(1)).set('X-Socket-Id', 'sock-7').send({ date: '2026-07-01' });
|
||||
expect(res.status).toBe(200);
|
||||
expect(res.body).toEqual({ action: 'added' });
|
||||
expect(svc.toggleEntry).toHaveBeenCalledWith(1, 10, '2026-07-01', 'sock-7');
|
||||
});
|
||||
|
||||
it('400 on entries/toggle without a date', async () => {
|
||||
const res = await request(server).post('/api/addons/vacay/entries/toggle').set('Cookie', sessionCookie(1)).send({});
|
||||
expect(res.status).toBe(400);
|
||||
expect(res.body).toEqual({ error: 'date required' });
|
||||
});
|
||||
|
||||
it('403 on color for a user not in the plan', async () => {
|
||||
const res = await request(server).put('/api/addons/vacay/color').set('Cookie', sessionCookie(1)).send({ color: '#fff', target_user_id: 99 });
|
||||
expect(res.status).toBe(403);
|
||||
expect(res.body).toEqual({ error: 'User not in plan' });
|
||||
});
|
||||
});
|
||||
Reference in New Issue
Block a user