mirror of
https://github.com/mauriceboe/TREK.git
synced 2026-12-03 09:38:54 +00:00
chore: move trip-invite backend to proper DI
Fold the legacy tripInviteService SQL into the Nest TripInviteService over the injected DatabaseService (byte-identical statements; the JS-side expiry check and non-positive-means-no-expiry coercion preserved) and delete the legacy module. No bridge, no MCP port and no plugin-host change needed — nothing outside the container consumed this domain. Also wraps the rotation's probe + write + re-select in db.transaction() per the repo rule that multi-statement writes are never bare. Unit suite moved to tests/unit/nest preserving TRIP-INVITE-001..006 and adding 007 (expiry pinning); the e2e converted to the DI-native pattern (real SQL against temp trips/trip_invite_tokens tables).
This commit is contained in:
@@ -1,9 +1,10 @@
|
||||
/**
|
||||
* Trip invite-link e2e — exercises /api/trips/:tripId/invite-link (manage) and
|
||||
* /api/trip-invites/:token (preview + accept) through the real JwtAuthGuard
|
||||
* against a temp SQLite db. The invite service, permission check and membership
|
||||
* join are mocked; this focuses on auth (401), trip-access 404, the share_manage
|
||||
* 403, the login-required join, and invalid-token 404s (#1143).
|
||||
* against a temp SQLite db. TripInviteService is DI-native and runs its real
|
||||
* SQL against the temp db; only the permission check, membership join and
|
||||
* audit log are mocked. Focuses on auth (401), trip-access 404, the
|
||||
* share_manage 403, the login-required join, and invalid-token 404s (#1143).
|
||||
*/
|
||||
import { describe, it, expect, beforeAll, afterAll, beforeEach, vi } from 'vitest';
|
||||
import request from 'supertest';
|
||||
@@ -13,31 +14,34 @@ import { DatabaseModule } from '../../src/nest/database/database.module';
|
||||
import { Test } from '@nestjs/testing';
|
||||
import { seedUser, sessionCookie } from './harness';
|
||||
|
||||
const { db, canAccessTrip } = vi.hoisted(() => {
|
||||
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, canAccessTrip: vi.fn() };
|
||||
tmp.exec('CREATE TABLE trips (id INTEGER PRIMARY KEY AUTOINCREMENT, title TEXT);');
|
||||
// TripInviteService now runs its real SQL (DI-injected, no mock) — mirror of
|
||||
// the trip_invite_tokens DDL from migration 153.
|
||||
tmp.exec(`CREATE TABLE trip_invite_tokens (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
trip_id INTEGER NOT NULL UNIQUE REFERENCES trips(id) ON DELETE CASCADE,
|
||||
token TEXT UNIQUE NOT NULL,
|
||||
created_by INTEGER REFERENCES users(id) ON DELETE SET NULL,
|
||||
expires_at TEXT,
|
||||
created_at DATETIME DEFAULT CURRENT_TIMESTAMP);`);
|
||||
return { db: tmp };
|
||||
});
|
||||
|
||||
vi.mock('../../src/db/database', () => ({ db, canAccessTrip, closeDb: () => {}, reinitialize: () => {} }));
|
||||
const { canAccessTrip } = vi.hoisted(() => ({ canAccessTrip: vi.fn() }));
|
||||
vi.mock('../../src/db/database', () => ({
|
||||
db, canAccessTrip, isOwner: vi.fn(() => true), getPlaceWithTags: vi.fn(), closeDb: () => {}, reinitialize: () => {},
|
||||
}));
|
||||
|
||||
const { checkPermission } = vi.hoisted(() => ({ checkPermission: vi.fn() }));
|
||||
vi.mock('../../src/services/permissions', () => ({ checkPermission }));
|
||||
|
||||
const { inviteSvc } = vi.hoisted(() => ({
|
||||
inviteSvc: {
|
||||
getTripInviteLink: vi.fn(),
|
||||
createOrRotateTripInviteLink: vi.fn(),
|
||||
deleteTripInviteLink: vi.fn(),
|
||||
resolveTripInvite: vi.fn(),
|
||||
},
|
||||
}));
|
||||
vi.mock('../../src/services/tripInviteService', () => inviteSvc);
|
||||
|
||||
const { joinTripAsMember } = vi.hoisted(() => ({ joinTripAsMember: vi.fn() }));
|
||||
vi.mock('../../src/services/tripMembership', () => ({ joinTripAsMember }));
|
||||
|
||||
@@ -45,6 +49,7 @@ vi.mock('../../src/services/auditLog', () => ({ writeAudit: vi.fn(), getClientIp
|
||||
|
||||
import { TripInviteModule } from '../../src/nest/trip-invite/trip-invite.module';
|
||||
import { TrekExceptionFilter } from '../../src/nest/common/trek-exception.filter';
|
||||
import { ZodValidationPipe } from '../../src/nest/common/zod-validation.pipe';
|
||||
|
||||
describe('Trip invite-link e2e (real auth guard + temp SQLite)', () => {
|
||||
let server: Server;
|
||||
@@ -54,11 +59,20 @@ describe('Trip invite-link e2e (real auth guard + temp SQLite)', () => {
|
||||
const moduleRef = await Test.createTestingModule({ imports: [DatabaseModule, TripInviteModule] }).compile();
|
||||
const nest = moduleRef.createNestApplication();
|
||||
nest.use(cookieParser());
|
||||
nest.useGlobalPipes(new ZodValidationPipe());
|
||||
nest.useGlobalFilters(new TrekExceptionFilter());
|
||||
await nest.init();
|
||||
return nest;
|
||||
}
|
||||
|
||||
function seedTrip(id: number, title: string) {
|
||||
db.prepare('INSERT INTO trips (id, title) VALUES (?, ?)').run(id, title);
|
||||
}
|
||||
function seedToken(tripId: number, token: string, expiresAt: string | null = null) {
|
||||
db.prepare('INSERT INTO trip_invite_tokens (trip_id, token, created_by, expires_at) VALUES (?, ?, 1, ?)')
|
||||
.run(tripId, token, expiresAt);
|
||||
}
|
||||
|
||||
beforeAll(async () => {
|
||||
seedUser(db as never, { id: 1 });
|
||||
seedUser(db as never, { id: 2, username: 'e2e-user-2', email: 'e2e-2@example.test' });
|
||||
@@ -67,11 +81,10 @@ describe('Trip invite-link e2e (real auth guard + temp SQLite)', () => {
|
||||
});
|
||||
|
||||
beforeEach(() => {
|
||||
db.prepare('DELETE FROM trip_invite_tokens').run();
|
||||
db.prepare('DELETE FROM trips').run();
|
||||
canAccessTrip.mockReturnValue({ user_id: 1 });
|
||||
checkPermission.mockReturnValue(true);
|
||||
inviteSvc.getTripInviteLink.mockReset();
|
||||
inviteSvc.createOrRotateTripInviteLink.mockReset();
|
||||
inviteSvc.resolveTripInvite.mockReset();
|
||||
joinTripAsMember.mockReset();
|
||||
});
|
||||
|
||||
@@ -83,24 +96,49 @@ describe('Trip invite-link e2e (real auth guard + temp SQLite)', () => {
|
||||
});
|
||||
|
||||
it('GET returns the current link for a trip member', async () => {
|
||||
inviteSvc.getTripInviteLink.mockReturnValueOnce({ token: 'abc', expires_at: null, created_at: 'now' });
|
||||
seedTrip(5, 'Lisbon');
|
||||
seedToken(5, 'abc');
|
||||
const res = await request(server).get('/api/trips/5/invite-link').set('Cookie', sessionCookie(1));
|
||||
expect(res.status).toBe(200);
|
||||
expect(res.body.token).toBe('abc');
|
||||
expect(res.body.expires_at).toBeNull();
|
||||
});
|
||||
|
||||
it('GET returns { token: null } when no link exists', async () => {
|
||||
inviteSvc.getTripInviteLink.mockReturnValueOnce(null);
|
||||
seedTrip(5, 'Lisbon');
|
||||
const res = await request(server).get('/api/trips/5/invite-link').set('Cookie', sessionCookie(1));
|
||||
expect(res.status).toBe(200);
|
||||
expect(res.body).toEqual({ token: null });
|
||||
});
|
||||
|
||||
it('POST creates/rotates the link', async () => {
|
||||
inviteSvc.createOrRotateTripInviteLink.mockReturnValueOnce({ token: 'new', expires_at: null, created_at: 'now' });
|
||||
seedTrip(5, 'Lisbon');
|
||||
seedToken(5, 'old-token');
|
||||
const res = await request(server).post('/api/trips/5/invite-link').set('Cookie', sessionCookie(1)).send({});
|
||||
expect([200, 201]).toContain(res.status);
|
||||
expect(res.body.token).toBe('new');
|
||||
expect(res.body.token).toMatch(/^[A-Za-z0-9_-]{20,}$/);
|
||||
expect(res.body.token).not.toBe('old-token');
|
||||
const rows = db.prepare('SELECT token FROM trip_invite_tokens WHERE trip_id = 5').all() as { token: string }[];
|
||||
expect(rows).toHaveLength(1);
|
||||
expect(rows[0].token).toBe(res.body.token);
|
||||
});
|
||||
|
||||
it('POST with expires_in_days bounds the link life', async () => {
|
||||
seedTrip(5, 'Lisbon');
|
||||
const res = await request(server).post('/api/trips/5/invite-link').set('Cookie', sessionCookie(1))
|
||||
.send({ expires_in_days: 7 });
|
||||
expect([200, 201]).toContain(res.status);
|
||||
const expires = new Date(res.body.expires_at).getTime();
|
||||
expect(expires).toBeGreaterThan(Date.now() + 6 * 86400000);
|
||||
expect(expires).toBeLessThan(Date.now() + 8 * 86400000);
|
||||
});
|
||||
|
||||
it('POST 400 for a non-numeric expires_in_days string', async () => {
|
||||
seedTrip(5, 'Lisbon');
|
||||
const res = await request(server).post('/api/trips/5/invite-link').set('Cookie', sessionCookie(1))
|
||||
.send({ expires_in_days: '7abc' });
|
||||
expect(res.status).toBe(400);
|
||||
expect(db.prepare('SELECT COUNT(*) AS n FROM trip_invite_tokens').get()).toEqual({ n: 0 });
|
||||
});
|
||||
|
||||
it('403 to create without share_manage', async () => {
|
||||
@@ -127,20 +165,23 @@ describe('Trip invite-link e2e (real auth guard + temp SQLite)', () => {
|
||||
});
|
||||
|
||||
it('preview resolves the trip title for an authed user', async () => {
|
||||
inviteSvc.resolveTripInvite.mockReturnValueOnce({ trip_id: 9, title: 'Rome 2026' });
|
||||
seedTrip(9, 'Rome 2026');
|
||||
seedToken(9, 'tok');
|
||||
const res = await request(server).get('/api/trip-invites/tok').set('Cookie', sessionCookie(2));
|
||||
expect(res.status).toBe(200);
|
||||
expect(res.body).toEqual({ trip_id: 9, title: 'Rome 2026' });
|
||||
});
|
||||
|
||||
it('preview 404 for an invalid/expired token', async () => {
|
||||
inviteSvc.resolveTripInvite.mockReturnValueOnce(null);
|
||||
const res = await request(server).get('/api/trip-invites/bad').set('Cookie', sessionCookie(2));
|
||||
expect(res.status).toBe(404);
|
||||
seedTrip(9, 'Rome 2026');
|
||||
seedToken(9, 'tok', new Date(Date.now() - 3600_000).toISOString());
|
||||
expect((await request(server).get('/api/trip-invites/bad').set('Cookie', sessionCookie(2))).status).toBe(404);
|
||||
expect((await request(server).get('/api/trip-invites/tok').set('Cookie', sessionCookie(2))).status).toBe(404);
|
||||
});
|
||||
|
||||
it('accept joins the current user and returns the trip id', async () => {
|
||||
inviteSvc.resolveTripInvite.mockReturnValueOnce({ trip_id: 9, title: 'Rome 2026' });
|
||||
seedTrip(9, 'Rome 2026');
|
||||
seedToken(9, 'tok');
|
||||
joinTripAsMember.mockReturnValueOnce({ joined: true, tripId: 9 });
|
||||
const res = await request(server).post('/api/trip-invites/tok/accept').set('Cookie', sessionCookie(2));
|
||||
expect(res.status).toBe(200);
|
||||
@@ -149,7 +190,6 @@ describe('Trip invite-link e2e (real auth guard + temp SQLite)', () => {
|
||||
});
|
||||
|
||||
it('accept 404 for an invalid/expired token (no join attempted)', async () => {
|
||||
inviteSvc.resolveTripInvite.mockReturnValueOnce(null);
|
||||
const res = await request(server).post('/api/trip-invites/bad/accept').set('Cookie', sessionCookie(2));
|
||||
expect(res.status).toBe(404);
|
||||
expect(joinTripAsMember).not.toHaveBeenCalled();
|
||||
|
||||
Reference in New Issue
Block a user