mirror of
https://github.com/mauriceboe/TREK.git
synced 2026-12-04 18:04:18 +00:00
chore: move files backend to proper DI
Folds the legacy services/fileService.ts into the DI-native FilesService (injected DatabaseService, byte-identical SQL). Load-time constants move to files.constants.ts; files.bridge.ts survives with a single export for the request-time getAllowedExtensions read the module-scope multer configs need outside DI. TripsService and PluginHostDepsFactory inject FilesService. Also rides the nestjs-zod ratchet (FileUploadDto/FileUpdateDto/FileLinkDto over the @trek/shared contracts, FilesController entries dropped from the body-contract allow-list) and fixes the verified legacy quirks: file-link insert failures now surface instead of being swallowed, updateFile coerces an empty-string description to NULL like createFile, and formatFile's misleading optional trip_id annotation is gone.
This commit is contained in:
@@ -1,9 +1,11 @@
|
||||
/**
|
||||
* 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.
|
||||
* FilesService is DI-native (no service mock): the file rows live in the temp
|
||||
* db and the SQL runs for real; only canAccessTrip, the permission check, the
|
||||
* photo services and the broadcast are mocked. 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';
|
||||
@@ -18,29 +20,36 @@ const { db } = vi.hoisted(() => {
|
||||
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);`);
|
||||
email TEXT NOT NULL UNIQUE, role TEXT NOT NULL DEFAULT 'user', password_version INTEGER NOT NULL DEFAULT 0,
|
||||
avatar TEXT);`);
|
||||
// FilesService runs its real SQL against these (FILE_SELECT joins reservations
|
||||
// and users; the link batch reads file_links; findForeignLinkTarget probes
|
||||
// reservations/places/day_assignments).
|
||||
tmp.exec('CREATE TABLE trips (id INTEGER PRIMARY KEY AUTOINCREMENT, user_id INTEGER, title TEXT);');
|
||||
tmp.exec(`CREATE TABLE trip_files (id INTEGER PRIMARY KEY AUTOINCREMENT, trip_id INTEGER NOT NULL,
|
||||
place_id INTEGER, reservation_id INTEGER, filename TEXT NOT NULL, original_name TEXT NOT NULL,
|
||||
file_size INTEGER, mime_type TEXT, description TEXT, uploaded_by INTEGER, starred INTEGER DEFAULT 0,
|
||||
deleted_at DATETIME, created_at DATETIME DEFAULT CURRENT_TIMESTAMP);`);
|
||||
tmp.exec(`CREATE TABLE file_links (id INTEGER PRIMARY KEY AUTOINCREMENT, file_id INTEGER NOT NULL,
|
||||
reservation_id INTEGER, assignment_id INTEGER, place_id INTEGER,
|
||||
created_at DATETIME DEFAULT CURRENT_TIMESTAMP);`);
|
||||
tmp.exec('CREATE TABLE reservations (id INTEGER PRIMARY KEY AUTOINCREMENT, trip_id INTEGER, title TEXT);');
|
||||
tmp.exec('CREATE TABLE places (id INTEGER PRIMARY KEY AUTOINCREMENT, trip_id INTEGER);');
|
||||
tmp.exec('CREATE TABLE days (id INTEGER PRIMARY KEY AUTOINCREMENT, trip_id INTEGER);');
|
||||
tmp.exec('CREATE TABLE day_assignments (id INTEGER PRIMARY KEY AUTOINCREMENT, day_id INTEGER);');
|
||||
return { db: tmp };
|
||||
});
|
||||
|
||||
vi.mock('../../src/db/database', () => ({ db, 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: () => {},
|
||||
}));
|
||||
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, MAX_VIDEO_SIZE: 500 * 1024 * 1024, BLOCKED_EXTENSIONS: ['.exe', '.svg'], filesDir: '/tmp/files', getAllowedExtensions: () => '*',
|
||||
isVideoExtension: (ext: string) => ['mp4', 'm4v', 'webm', 'mov'].includes(String(ext).toLowerCase().replace(/^\./, '')), isVideoMime: (m?: string) => !!m && m.startsWith('video/'),
|
||||
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() },
|
||||
@@ -48,6 +57,7 @@ const { photoSvc, helperSvc } = vi.hoisted(() => ({
|
||||
vi.mock('../../src/services/memories/photoResolverService', () => photoSvc);
|
||||
vi.mock('../../src/services/memories/helpersService', () => helperSvc);
|
||||
|
||||
import { DatabaseModule } from '../../src/nest/database/database.module';
|
||||
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';
|
||||
@@ -57,7 +67,7 @@ describe('Files + photos e2e (real auth guard + temp SQLite)', () => {
|
||||
let app: Awaited<ReturnType<typeof build>>;
|
||||
|
||||
async function build() {
|
||||
const moduleRef = await Test.createTestingModule({ imports: [FilesModule, PhotosModule] }).compile();
|
||||
const moduleRef = await Test.createTestingModule({ imports: [DatabaseModule, FilesModule, PhotosModule] }).compile();
|
||||
const nest = moduleRef.createNestApplication();
|
||||
nest.use(cookieParser());
|
||||
nest.useGlobalFilters(new TrekExceptionFilter());
|
||||
@@ -67,15 +77,15 @@ describe('Files + photos e2e (real auth guard + temp SQLite)', () => {
|
||||
|
||||
beforeAll(async () => {
|
||||
seedUser(db as never, { id: 1 });
|
||||
db.prepare('INSERT INTO trips (id, user_id, title) VALUES (5, 1, ?)').run('Trip');
|
||||
db.prepare("INSERT INTO trip_files (id, trip_id, filename, original_name, uploaded_by) VALUES (1, 5, 'stored-a.pdf', 'a.pdf', 1)").run();
|
||||
db.prepare("INSERT INTO trip_files (id, trip_id, filename, original_name, uploaded_by, starred) VALUES (9, 5, 'stored-b.pdf', 'b.pdf', 1, 0)").run();
|
||||
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 });
|
||||
canAccessTrip.mockReturnValue({ id: 5, user_id: 1 });
|
||||
checkPermission.mockReturnValue(true);
|
||||
helperSvc.canAccessTrekPhoto.mockReturnValue(true);
|
||||
});
|
||||
@@ -88,23 +98,30 @@ describe('Files + photos e2e (real auth guard + temp SQLite)', () => {
|
||||
expect((await request(server).get('/api/trips/5/files')).status).toBe(401);
|
||||
});
|
||||
|
||||
it('200 list for an accessible trip', async () => {
|
||||
it('200 list for an accessible trip (real SQL, formatted rows)', 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' }] });
|
||||
expect(res.body.files).toHaveLength(2);
|
||||
const first = res.body.files.find((f: { id: number }) => f.id === 1);
|
||||
expect(first.original_name).toBe('a.pdf');
|
||||
expect(first.url).toBe('/api/trips/5/files/1/download');
|
||||
expect(first.linked_reservation_ids).toEqual([]);
|
||||
});
|
||||
|
||||
it('404 when the trip is not accessible', async () => {
|
||||
fileSvc.verifyTripAccess.mockReturnValue(undefined);
|
||||
canAccessTrip.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 () => {
|
||||
it('200 toggling a star with permission (real UPDATE + re-select)', 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 } });
|
||||
expect(res.body.file.id).toBe(9);
|
||||
expect(res.body.file.starred).toBe(1);
|
||||
// put it back so the case is order-independent
|
||||
db.prepare('UPDATE trip_files SET starred = 0 WHERE id = 9').run();
|
||||
});
|
||||
|
||||
it('403 deleting without file_delete permission', async () => {
|
||||
@@ -115,7 +132,6 @@ describe('Files + photos e2e (real auth guard + temp SQLite)', () => {
|
||||
});
|
||||
|
||||
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' });
|
||||
|
||||
@@ -27,12 +27,10 @@ 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: () => '*',
|
||||
MAX_VIDEO_SIZE: 500 * 1024 * 1024,
|
||||
isVideoExtension: (ext: string) => ['mp4', 'm4v', 'webm', 'mov'].includes(String(ext).toLowerCase().replace(/^\./, '')),
|
||||
isVideoMime: (m?: string) => !!m && m.startsWith('video/'),
|
||||
}));
|
||||
// The controller's pure helpers (isVideoExtension/isVideoMime/MAX_VIDEO_SIZE)
|
||||
// now come from the real files.constants; only the request-time app_settings
|
||||
// read is mocked, preserving the old '*'-allowlist semantics for the fixtures.
|
||||
vi.mock('../../src/nest/files/files.bridge', () => ({ getAllowedExtensions: () => '*' }));
|
||||
vi.mock('../../src/services/memories/immichService', () => ({ uploadToImmich: vi.fn(), streamImmichAsset: vi.fn() }));
|
||||
vi.mock('../../src/services/memories/photoResolverService', () => ({ streamPhoto: vi.fn() }));
|
||||
|
||||
|
||||
@@ -18,7 +18,8 @@ const { db } = vi.hoisted(() => {
|
||||
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);`);
|
||||
email TEXT NOT NULL UNIQUE, role TEXT NOT NULL DEFAULT 'user', password_version INTEGER NOT NULL DEFAULT 0,
|
||||
avatar TEXT);`);
|
||||
tmp.exec('CREATE TABLE trips (id INTEGER PRIMARY KEY AUTOINCREMENT, title TEXT);');
|
||||
// bundle()'s todoItems now runs TodoService's real SQL (DI-injected, no mock).
|
||||
tmp.exec(`CREATE TABLE todo_items (id INTEGER PRIMARY KEY AUTOINCREMENT, trip_id INTEGER NOT NULL,
|
||||
@@ -34,6 +35,16 @@ const { db } = vi.hoisted(() => {
|
||||
created_at DATETIME DEFAULT CURRENT_TIMESTAMP);`);
|
||||
tmp.exec(`CREATE TABLE packing_item_recipients (item_id INTEGER NOT NULL, user_id INTEGER NOT NULL,
|
||||
PRIMARY KEY (item_id, user_id));`);
|
||||
// bundle()'s files now runs FilesService's real SQL (DI-injected, no mock) —
|
||||
// empty tables satisfy the FILE_SELECT joins and the file_links batch.
|
||||
tmp.exec(`CREATE TABLE trip_files (id INTEGER PRIMARY KEY AUTOINCREMENT, trip_id INTEGER NOT NULL,
|
||||
place_id INTEGER, reservation_id INTEGER, filename TEXT NOT NULL, original_name TEXT NOT NULL,
|
||||
file_size INTEGER, mime_type TEXT, description TEXT, uploaded_by INTEGER, starred INTEGER DEFAULT 0,
|
||||
deleted_at DATETIME, created_at DATETIME DEFAULT CURRENT_TIMESTAMP);`);
|
||||
tmp.exec(`CREATE TABLE file_links (id INTEGER PRIMARY KEY AUTOINCREMENT, file_id INTEGER NOT NULL,
|
||||
reservation_id INTEGER, assignment_id INTEGER, place_id INTEGER,
|
||||
created_at DATETIME DEFAULT CURRENT_TIMESTAMP);`);
|
||||
tmp.exec('CREATE TABLE IF NOT EXISTS reservations (id INTEGER PRIMARY KEY AUTOINCREMENT, trip_id INTEGER, title TEXT);');
|
||||
return { db: tmp };
|
||||
});
|
||||
|
||||
@@ -62,7 +73,6 @@ vi.mock('../../src/services/dayService', () => ({ listDays: () => ({ days: [] })
|
||||
vi.mock('../../src/services/placeService', () => ({ listPlaces: () => [] }));
|
||||
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';
|
||||
|
||||
@@ -13,6 +13,7 @@ import { DayNotesService } from '../../src/nest/days/day-notes.service';
|
||||
import { AssignmentsService } from '../../src/nest/assignments/assignments.service';
|
||||
import { LlmConfigResolver } from '../../src/nest/llm-parse/llm-config.resolver';
|
||||
import { SettingsService } from '../../src/nest/settings/settings.service';
|
||||
import { FilesService } from '../../src/nest/files/files.service';
|
||||
|
||||
/**
|
||||
* Hand-wired counterpart of the PluginsModule DI graph for no-Nest tests
|
||||
@@ -33,6 +34,7 @@ export function createHostDepsFactory(dbs: DatabaseService): PluginHostDepsFacto
|
||||
new AssignmentsService(dbs),
|
||||
new LlmConfigResolver(new SettingsService(dbs), dbs),
|
||||
dbs,
|
||||
new FilesService(dbs),
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@@ -1,134 +1,548 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest';
|
||||
import type { Request } from 'express';
|
||||
/**
|
||||
* Unit tests for the DI-native FilesService — FILE-SVC-001 through FILE-SVC-036.
|
||||
* The legacy services/fileService.ts never had a unit suite (behavior was pinned
|
||||
* only by tests/integration/files.test.ts), so these cases are new: they pin the
|
||||
* relocated SQL, the falsy-coercion defaults, the unlink-first delete semantics
|
||||
* and the download-token auth over a real in-memory SQLite DB, plus the
|
||||
* files.bridge delegation (inside the src/nest coverage gate).
|
||||
*/
|
||||
import { describe, it, expect, vi, beforeAll, beforeEach, afterAll, afterEach } from 'vitest';
|
||||
import path from 'path';
|
||||
import fs from 'fs';
|
||||
|
||||
// Mock the side-effect dependencies the wrapper reaches into directly.
|
||||
const { broadcast } = vi.hoisted(() => ({ broadcast: vi.fn() }));
|
||||
vi.mock('../../../src/websocket', () => ({ broadcast }));
|
||||
// ── DB setup ──────────────────────────────────────────────────────────────────
|
||||
|
||||
const { testDb, bareDb, dbMock } = vi.hoisted(() => {
|
||||
const Database = require('better-sqlite3');
|
||||
const db = new Database(':memory:');
|
||||
db.exec('PRAGMA journal_mode = WAL');
|
||||
db.exec('PRAGMA foreign_keys = ON');
|
||||
db.exec('PRAGMA busy_timeout = 5000');
|
||||
// A second, schema-less DB for the getAllowedExtensions catch branch.
|
||||
const bare = new Database(':memory:');
|
||||
const mock = {
|
||||
db,
|
||||
closeDb: () => {},
|
||||
reinitialize: () => {},
|
||||
getPlaceWithTags: () => null,
|
||||
canAccessTrip: (tripId: unknown, userId: number) =>
|
||||
db.prepare(`
|
||||
SELECT t.id, t.user_id FROM trips t
|
||||
LEFT JOIN trip_members m ON m.trip_id = t.id AND m.user_id = ?
|
||||
WHERE t.id = ? AND (t.user_id = ? OR m.user_id IS NOT NULL)
|
||||
`).get(userId, tripId, userId),
|
||||
isOwner: (tripId: unknown, userId: number) =>
|
||||
!!db.prepare('SELECT id FROM trips WHERE id = ? AND user_id = ?').get(tripId, userId),
|
||||
};
|
||||
return { testDb: db, bareDb: bare, dbMock: mock };
|
||||
});
|
||||
|
||||
vi.mock('../../../src/db/database', () => dbMock);
|
||||
vi.mock('../../../src/config', () => ({
|
||||
JWT_SECRET: 'test-secret',
|
||||
ENCRYPTION_KEY: 'a1b2c3d4e5f6a7b8c9d0e1f2a3b4c5d6a7b8c9d0e1f2a3b4c5d6a7b8c9d0e1f2',
|
||||
updateJwtSecret: () => {},
|
||||
}));
|
||||
vi.mock('../../../src/websocket', () => ({ broadcast: vi.fn() }));
|
||||
|
||||
const { checkPermission } = vi.hoisted(() => ({ checkPermission: vi.fn(() => true) }));
|
||||
vi.mock('../../../src/services/permissions', () => ({ checkPermission }));
|
||||
|
||||
const { svc } = vi.hoisted(() => ({
|
||||
svc: {
|
||||
verifyTripAccess: vi.fn(),
|
||||
authenticateDownload: vi.fn(),
|
||||
resolveFilePath: 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(),
|
||||
},
|
||||
}));
|
||||
vi.mock('../../../src/services/fileService', () => svc);
|
||||
const { verifyJwtAndLoadUser } = vi.hoisted(() => ({ verifyJwtAndLoadUser: vi.fn() }));
|
||||
vi.mock('../../../src/middleware/auth', () => ({ verifyJwtAndLoadUser }));
|
||||
|
||||
const { consumeEphemeralToken } = vi.hoisted(() => ({ consumeEphemeralToken: vi.fn() }));
|
||||
vi.mock('../../../src/services/ephemeralTokens', () => ({ consumeEphemeralToken }));
|
||||
|
||||
import type { Request } from 'express';
|
||||
import { createTables } from '../../../src/db/schema';
|
||||
import { runMigrations } from '../../../src/db/migrations';
|
||||
import { resetTestDb } from '../../helpers/test-db';
|
||||
import { createUser, createTrip, addTripMember, createPlace, createReservation, createDay, createDayAssignment, setAppSetting } from '../../helpers/factories';
|
||||
import { DatabaseService } from '../../../src/nest/database/database.service';
|
||||
import { FilesService } from '../../../src/nest/files/files.service';
|
||||
import type { User } from '../../../src/types';
|
||||
import { getAllowedExtensions as bridgeGetAllowedExtensions } from '../../../src/nest/files/files.bridge';
|
||||
import {
|
||||
DEFAULT_ALLOWED_EXTENSIONS,
|
||||
MAX_FILE_SIZE,
|
||||
MAX_VIDEO_SIZE,
|
||||
BLOCKED_EXTENSIONS,
|
||||
filesDir,
|
||||
isVideoMime,
|
||||
isVideoExtension,
|
||||
} from '../../../src/nest/files/files.constants';
|
||||
import type { TripFile, User } from '../../../src/types';
|
||||
|
||||
function service() {
|
||||
return new FilesService();
|
||||
const svc = new FilesService(new DatabaseService(testDb));
|
||||
|
||||
beforeAll(() => {
|
||||
createTables(testDb);
|
||||
runMigrations(testDb);
|
||||
});
|
||||
|
||||
beforeEach(() => {
|
||||
resetTestDb(testDb);
|
||||
vi.clearAllMocks();
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
afterAll(() => {
|
||||
testDb.close();
|
||||
bareDb.close();
|
||||
});
|
||||
|
||||
function seedTrip() {
|
||||
const { user } = createUser(testDb);
|
||||
const trip = createTrip(testDb, user.id);
|
||||
return { user, trip };
|
||||
}
|
||||
|
||||
beforeEach(() => vi.clearAllMocks());
|
||||
function makeFile(tripId: number, userId: number, overrides: Partial<{ filename: string; originalname: string; size: number; mimetype: string }> = {}, opts: Parameters<FilesService['createFile']>[3] = {}) {
|
||||
return svc.createFile(
|
||||
tripId,
|
||||
{ filename: 'stored-name.pdf', originalname: 'visa.pdf', size: 1234, mimetype: 'application/pdf', ...overrides },
|
||||
userId,
|
||||
opts
|
||||
);
|
||||
}
|
||||
|
||||
describe('FilesService (thin wrapper around the legacy fileService)', () => {
|
||||
it('verifyTripAccess delegates to the legacy service', () => {
|
||||
svc.verifyTripAccess.mockReturnValue({ id: 5, user_id: 2 });
|
||||
expect(service().verifyTripAccess('5', 2)).toEqual({ id: 5, user_id: 2 });
|
||||
expect(svc.verifyTripAccess).toHaveBeenCalledWith('5', 2);
|
||||
function req(parts: { cookie?: string; bearer?: string; token?: string }): Request {
|
||||
return {
|
||||
cookies: parts.cookie ? { trek_session: parts.cookie } : {},
|
||||
headers: parts.bearer ? { authorization: `Bearer ${parts.bearer}` } : {},
|
||||
query: parts.token ? { token: parts.token } : {},
|
||||
} as unknown as Request;
|
||||
}
|
||||
|
||||
// ── constants & pure helpers (files.constants.ts) ─────────────────────────────
|
||||
|
||||
describe('files.constants', () => {
|
||||
it('FILE-SVC-001: isVideoMime accepts video/* only', () => {
|
||||
expect(isVideoMime('video/mp4')).toBe(true);
|
||||
expect(isVideoMime('image/png')).toBe(false);
|
||||
expect(isVideoMime(undefined)).toBe(false);
|
||||
expect(isVideoMime(null)).toBe(false);
|
||||
expect(isVideoMime('')).toBe(false);
|
||||
});
|
||||
|
||||
it('can forwards the ownership flag when the user owns the trip', () => {
|
||||
checkPermission.mockReturnValue(true);
|
||||
const user = { id: 1, role: 'user' } as User;
|
||||
expect(service().can('file_edit', { user_id: 1 } as never, user)).toBe(true);
|
||||
expect(checkPermission).toHaveBeenCalledWith('file_edit', 'user', 1, 1, false);
|
||||
it('FILE-SVC-002: isVideoExtension strips a leading dot and lowercases', () => {
|
||||
expect(isVideoExtension('mp4')).toBe(true);
|
||||
expect(isVideoExtension('.MP4')).toBe(true);
|
||||
expect(isVideoExtension('.mov')).toBe(true);
|
||||
expect(isVideoExtension('pdf')).toBe(false);
|
||||
expect(isVideoExtension('svg')).toBe(false);
|
||||
});
|
||||
|
||||
it('can marks the user as a guest when they do not own the trip', () => {
|
||||
checkPermission.mockReturnValue(false);
|
||||
const user = { id: 1, role: 'user' } as User;
|
||||
expect(service().can('file_upload', { user_id: 2 } as never, user)).toBe(false);
|
||||
expect(checkPermission).toHaveBeenCalledWith('file_upload', 'user', 2, 1, true);
|
||||
it('FILE-SVC-003: blocklist, size caps and the default allowlist are pinned', () => {
|
||||
expect(BLOCKED_EXTENSIONS).toHaveLength(25);
|
||||
expect(BLOCKED_EXTENSIONS).toContain('.svg');
|
||||
expect(BLOCKED_EXTENSIONS).toContain('.exe');
|
||||
expect(BLOCKED_EXTENSIONS).toContain('.ps1');
|
||||
expect(MAX_FILE_SIZE).toBe(50 * 1024 * 1024);
|
||||
expect(MAX_VIDEO_SIZE).toBe(500 * 1024 * 1024);
|
||||
expect(DEFAULT_ALLOWED_EXTENSIONS).toBe('jpg,jpeg,png,gif,webp,heic,pdf,doc,docx,xls,xlsx,txt,csv,pkpass,pkpasses,md,markdown');
|
||||
});
|
||||
|
||||
it('broadcast forwards to the websocket helper', () => {
|
||||
service().broadcast('5', 'file:created', { file: { id: 1 } }, 'sock');
|
||||
expect(broadcast).toHaveBeenCalledWith('5', 'file:created', { file: { id: 1 } }, 'sock');
|
||||
it('FILE-SVC-004: filesDir resolves to <server>/uploads/files despite the deeper module location', () => {
|
||||
const serverRoot = path.resolve(__dirname, '../../..');
|
||||
expect(path.resolve(filesDir)).toBe(path.join(serverRoot, 'uploads', 'files'));
|
||||
});
|
||||
|
||||
it('authenticateDownload / resolveFilePath delegate', () => {
|
||||
const req = { headers: {} } as Request;
|
||||
svc.authenticateDownload.mockReturnValue({ userId: 7 });
|
||||
expect(service().authenticateDownload(req)).toEqual({ userId: 7 });
|
||||
expect(svc.authenticateDownload).toHaveBeenCalledWith(req);
|
||||
it('FILE-SVC-005: resolveFilePath neutralizes traversal via basename and stays inside filesDir', () => {
|
||||
const plain = svc.resolveFilePath('photo.jpg');
|
||||
expect(plain.resolved).toBe(path.resolve(path.join(filesDir, 'photo.jpg')));
|
||||
expect(plain.safe).toBe(true);
|
||||
|
||||
svc.resolveFilePath.mockReturnValue({ resolved: '/a/b.pdf', safe: true });
|
||||
expect(service().resolveFilePath('b.pdf')).toEqual({ resolved: '/a/b.pdf', safe: true });
|
||||
expect(svc.resolveFilePath).toHaveBeenCalledWith('b.pdf');
|
||||
});
|
||||
|
||||
it('the read helpers delegate', () => {
|
||||
svc.listFiles.mockReturnValue([{ id: 1 }]);
|
||||
expect(service().listFiles('5', true)).toEqual([{ id: 1 }]);
|
||||
expect(svc.listFiles).toHaveBeenCalledWith('5', true);
|
||||
|
||||
svc.getFileById.mockReturnValue({ id: 9 });
|
||||
expect(service().getFileById('9', '5')).toEqual({ id: 9 });
|
||||
expect(svc.getFileById).toHaveBeenCalledWith('9', '5');
|
||||
|
||||
svc.getDeletedFile.mockReturnValue({ id: 9 });
|
||||
expect(service().getDeletedFile('9', '5')).toEqual({ id: 9 });
|
||||
expect(svc.getDeletedFile).toHaveBeenCalledWith('9', '5');
|
||||
|
||||
svc.getFileLinks.mockReturnValue([{ id: 1 }]);
|
||||
expect(service().getFileLinks('9')).toEqual([{ id: 1 }]);
|
||||
expect(svc.getFileLinks).toHaveBeenCalledWith('9');
|
||||
});
|
||||
|
||||
it('the mutating helpers delegate', () => {
|
||||
const file = { filename: 'a.pdf' } as Express.Multer.File;
|
||||
svc.createFile.mockReturnValue({ id: 9 });
|
||||
expect(service().createFile('5', file, 1, { description: 'd' })).toEqual({ id: 9 });
|
||||
expect(svc.createFile).toHaveBeenCalledWith('5', file, 1, { description: 'd' });
|
||||
|
||||
svc.updateFile.mockReturnValue({ id: 9 });
|
||||
const current = { id: 9 } as never;
|
||||
expect(service().updateFile('9', current, { description: 'x' })).toEqual({ id: 9 });
|
||||
expect(svc.updateFile).toHaveBeenCalledWith('9', current, { description: 'x' });
|
||||
|
||||
svc.toggleStarred.mockReturnValue({ id: 9, starred: 1 });
|
||||
expect(service().toggleStarred('9', 0)).toEqual({ id: 9, starred: 1 });
|
||||
expect(svc.toggleStarred).toHaveBeenCalledWith('9', 0);
|
||||
|
||||
service().softDeleteFile('9');
|
||||
expect(svc.softDeleteFile).toHaveBeenCalledWith('9');
|
||||
|
||||
svc.restoreFile.mockReturnValue({ id: 9 });
|
||||
expect(service().restoreFile('9')).toEqual({ id: 9 });
|
||||
expect(svc.restoreFile).toHaveBeenCalledWith('9');
|
||||
|
||||
const trashed = { id: 9 } as never;
|
||||
service().permanentDeleteFile(trashed);
|
||||
expect(svc.permanentDeleteFile).toHaveBeenCalledWith(trashed);
|
||||
|
||||
svc.emptyTrash.mockReturnValue(3);
|
||||
expect(service().emptyTrash('5')).toBe(3);
|
||||
expect(svc.emptyTrash).toHaveBeenCalledWith('5');
|
||||
|
||||
svc.createFileLink.mockReturnValue([{ id: 1 }]);
|
||||
expect(service().createFileLink('9', { reservation_id: 2 })).toEqual([{ id: 1 }]);
|
||||
expect(svc.createFileLink).toHaveBeenCalledWith('9', { reservation_id: 2 });
|
||||
|
||||
service().deleteFileLink('3', '9');
|
||||
expect(svc.deleteFileLink).toHaveBeenCalledWith('3', '9');
|
||||
const sneaky = svc.resolveFilePath('../../../etc/passwd');
|
||||
expect(sneaky.resolved).toBe(path.resolve(path.join(filesDir, 'passwd')));
|
||||
expect(sneaky.safe).toBe(true);
|
||||
expect(sneaky.resolved.startsWith(path.resolve(filesDir))).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
// ── getAllowedExtensions ──────────────────────────────────────────────────────
|
||||
|
||||
describe('getAllowedExtensions', () => {
|
||||
it('FILE-SVC-006: returns the app_settings value when set', () => {
|
||||
setAppSetting(testDb, 'allowed_file_types', 'pdf,txt');
|
||||
expect(svc.getAllowedExtensions()).toBe('pdf,txt');
|
||||
});
|
||||
|
||||
it('FILE-SVC-007: returns the default when the row is absent', () => {
|
||||
expect(svc.getAllowedExtensions()).toBe(DEFAULT_ALLOWED_EXTENSIONS);
|
||||
});
|
||||
|
||||
it('FILE-SVC-008: returns the default for an empty value (|| coercion, not ??)', () => {
|
||||
setAppSetting(testDb, 'allowed_file_types', '');
|
||||
expect(svc.getAllowedExtensions()).toBe(DEFAULT_ALLOWED_EXTENSIONS);
|
||||
});
|
||||
|
||||
it('FILE-SVC-009: returns the default when the query throws (no app_settings table)', () => {
|
||||
const bareSvc = new FilesService(new DatabaseService(bareDb));
|
||||
expect(bareSvc.getAllowedExtensions()).toBe(DEFAULT_ALLOWED_EXTENSIONS);
|
||||
});
|
||||
});
|
||||
|
||||
// ── trip-scoped reads ─────────────────────────────────────────────────────────
|
||||
|
||||
describe('getFileById / getDeletedFile', () => {
|
||||
it('FILE-SVC-010: getFileById is trip-scoped', () => {
|
||||
const { user, trip } = seedTrip();
|
||||
const other = createTrip(testDb, user.id);
|
||||
const file = makeFile(trip.id, user.id);
|
||||
expect(svc.getFileById(file.id, trip.id)?.id).toBe(file.id);
|
||||
expect(svc.getFileById(file.id, other.id)).toBeUndefined();
|
||||
});
|
||||
|
||||
it('FILE-SVC-011: getDeletedFile returns only soft-deleted rows', () => {
|
||||
const { user, trip } = seedTrip();
|
||||
const file = makeFile(trip.id, user.id);
|
||||
expect(svc.getDeletedFile(file.id, trip.id)).toBeUndefined();
|
||||
svc.softDeleteFile(file.id);
|
||||
expect(svc.getDeletedFile(file.id, trip.id)?.id).toBe(file.id);
|
||||
});
|
||||
});
|
||||
|
||||
describe('listFiles', () => {
|
||||
it('FILE-SVC-012: active list excludes trash, is starred-first and carries the formatted shape', () => {
|
||||
const { user, trip } = seedTrip();
|
||||
makeFile(trip.id, user.id, { originalname: 'plain.pdf' });
|
||||
const starred = makeFile(trip.id, user.id, { originalname: 'starred.pdf' });
|
||||
const trashed = makeFile(trip.id, user.id, { originalname: 'gone.pdf' });
|
||||
svc.toggleStarred(starred.id, 0);
|
||||
svc.softDeleteFile(trashed.id);
|
||||
|
||||
const files = svc.listFiles(trip.id, false) as Record<string, unknown>[];
|
||||
expect(files.map((f) => f.id)).toHaveLength(2);
|
||||
expect(files[0].id).toBe(starred.id); // ORDER BY f.starred DESC first
|
||||
expect(files.map((f) => f.id)).not.toContain(trashed.id);
|
||||
expect(files[0].url).toBe(`/api/trips/${trip.id}/files/${starred.id}/download`);
|
||||
expect(files[0].uploaded_by_name).toBe(user.username);
|
||||
expect(files[0]).toHaveProperty('uploaded_by_avatar');
|
||||
});
|
||||
|
||||
it('FILE-SVC-013: trash list returns only soft-deleted files', () => {
|
||||
const { user, trip } = seedTrip();
|
||||
const kept = makeFile(trip.id, user.id);
|
||||
const trashed = makeFile(trip.id, user.id);
|
||||
svc.softDeleteFile(trashed.id);
|
||||
|
||||
const trash = svc.listFiles(trip.id, true) as Record<string, unknown>[];
|
||||
expect(trash.map((f) => f.id)).toEqual([trashed.id]);
|
||||
expect(trash.map((f) => f.id)).not.toContain(kept.id);
|
||||
});
|
||||
|
||||
it('FILE-SVC-014: batches file_links and filters null targets by truthiness', () => {
|
||||
const { user, trip } = seedTrip();
|
||||
const reservation = createReservation(testDb, trip.id);
|
||||
const place = createPlace(testDb, trip.id);
|
||||
const linked = makeFile(trip.id, user.id);
|
||||
const bare = makeFile(trip.id, user.id);
|
||||
svc.createFileLink(linked.id, { reservation_id: reservation.id });
|
||||
svc.createFileLink(linked.id, { place_id: place.id });
|
||||
|
||||
const files = svc.listFiles(trip.id, false) as Record<string, unknown>[];
|
||||
const linkedRow = files.find((f) => f.id === linked.id);
|
||||
const bareRow = files.find((f) => f.id === bare.id);
|
||||
expect(linkedRow.linked_reservation_ids).toEqual([reservation.id]);
|
||||
expect(linkedRow.linked_place_ids).toEqual([place.id]);
|
||||
expect(bareRow.linked_reservation_ids).toEqual([]);
|
||||
expect(bareRow.linked_place_ids).toEqual([]);
|
||||
|
||||
// The empty-trip guard skips the IN () batch entirely.
|
||||
const empty = createTrip(testDb, user.id);
|
||||
expect(svc.listFiles(empty.id, false)).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
// ── createFile / updateFile / toggleStarred ───────────────────────────────────
|
||||
|
||||
describe('createFile', () => {
|
||||
it('FILE-SVC-015: coerces falsy opts to NULL (|| null) and re-selects the formatted row', () => {
|
||||
const { user, trip } = seedTrip();
|
||||
const file = makeFile(trip.id, user.id, {}, { place_id: '', reservation_id: undefined, description: '' });
|
||||
const row = testDb.prepare('SELECT * FROM trip_files WHERE id = ?').get(file.id) as Record<string, unknown>;
|
||||
expect(row.place_id).toBeNull();
|
||||
expect(row.reservation_id).toBeNull();
|
||||
expect(row.description).toBeNull();
|
||||
expect(file.url).toBe(`/api/trips/${trip.id}/files/${file.id}/download`);
|
||||
expect((file as unknown as Record<string, unknown>).uploaded_by_name).toBe(user.username);
|
||||
});
|
||||
|
||||
it('FILE-SVC-016: stores the provided metadata and links the reservation title through FILE_SELECT', () => {
|
||||
const { user, trip } = seedTrip();
|
||||
const reservation = createReservation(testDb, trip.id, { title: 'Night train' });
|
||||
const file = makeFile(trip.id, user.id, { originalname: 'ticket.pdf', size: 99, mimetype: 'application/pdf' }, {
|
||||
reservation_id: String(reservation.id),
|
||||
description: 'the booking',
|
||||
});
|
||||
expect((file as unknown as Record<string, unknown>).reservation_title).toBe('Night train');
|
||||
expect(file.description).toBe('the booking');
|
||||
expect(file.original_name).toBe('ticket.pdf');
|
||||
expect(file.file_size).toBe(99);
|
||||
expect(file.uploaded_by).toBe(user.id);
|
||||
});
|
||||
});
|
||||
|
||||
describe('updateFile', () => {
|
||||
it('FILE-SVC-017: undefined fields keep the current values', () => {
|
||||
const { user, trip } = seedTrip();
|
||||
const place = createPlace(testDb, trip.id);
|
||||
const file = makeFile(trip.id, user.id, {}, { description: 'keep me', place_id: String(place.id) });
|
||||
const current = svc.getFileById(file.id, trip.id)!;
|
||||
const updated = svc.updateFile(file.id, current, {}) as Record<string, unknown>;
|
||||
expect(updated.description).toBe('keep me');
|
||||
expect(updated.place_id).toBe(place.id);
|
||||
});
|
||||
|
||||
it("FILE-SVC-018: '' clears every field (|| null) — description matches createFile's coercion", () => {
|
||||
const { user, trip } = seedTrip();
|
||||
const place = createPlace(testDb, trip.id);
|
||||
const reservation = createReservation(testDb, trip.id);
|
||||
const file = makeFile(trip.id, user.id, {}, { description: 'old', place_id: String(place.id), reservation_id: String(reservation.id) });
|
||||
const current = svc.getFileById(file.id, trip.id)!;
|
||||
const updated = svc.updateFile(file.id, current, { description: '', place_id: '', reservation_id: null }) as Record<string, unknown>;
|
||||
expect(updated.description).toBeNull(); // '' → NULL on update too (post-migration fix: symmetric with createFile)
|
||||
expect(updated.place_id).toBeNull();
|
||||
expect(updated.reservation_id).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe('toggleStarred / softDeleteFile / restoreFile', () => {
|
||||
it('FILE-SVC-019: toggleStarred flips 0→1 and 1→0', () => {
|
||||
const { user, trip } = seedTrip();
|
||||
const file = makeFile(trip.id, user.id);
|
||||
const on = svc.toggleStarred(file.id, 0) as Record<string, unknown>;
|
||||
expect(on.starred).toBe(1);
|
||||
const off = svc.toggleStarred(file.id, on.starred) as Record<string, unknown>;
|
||||
expect(off.starred).toBe(0);
|
||||
});
|
||||
|
||||
it('FILE-SVC-020: softDeleteFile stamps deleted_at', () => {
|
||||
const { user, trip } = seedTrip();
|
||||
const file = makeFile(trip.id, user.id);
|
||||
svc.softDeleteFile(file.id);
|
||||
const row = testDb.prepare('SELECT deleted_at FROM trip_files WHERE id = ?').get(file.id) as Record<string, unknown>;
|
||||
expect(row.deleted_at).not.toBeNull();
|
||||
});
|
||||
|
||||
it('FILE-SVC-021: restoreFile clears deleted_at and returns the formatted row', () => {
|
||||
const { user, trip } = seedTrip();
|
||||
const file = makeFile(trip.id, user.id);
|
||||
svc.softDeleteFile(file.id);
|
||||
const restored = svc.restoreFile(file.id) as Record<string, unknown>;
|
||||
expect(restored.deleted_at).toBeNull();
|
||||
expect(restored.url).toBe(`/api/trips/${trip.id}/files/${file.id}/download`);
|
||||
});
|
||||
});
|
||||
|
||||
// ── permanentDeleteFile / emptyTrash (unlink-first semantics) ─────────────────
|
||||
|
||||
describe('permanentDeleteFile', () => {
|
||||
it('FILE-SVC-022: removes the resolved path with force:true, then the DB row', async () => {
|
||||
const { user, trip } = seedTrip();
|
||||
const file = makeFile(trip.id, user.id, { filename: 'on-disk.pdf' });
|
||||
const rm = vi.spyOn(fs.promises, 'rm').mockResolvedValue(undefined);
|
||||
await svc.permanentDeleteFile(svc.getFileById(file.id, trip.id) as TripFile);
|
||||
expect(rm).toHaveBeenCalledWith(svc.resolveFilePath('on-disk.pdf').resolved, { force: true });
|
||||
expect(svc.getFileById(file.id, trip.id)).toBeUndefined();
|
||||
});
|
||||
|
||||
it('FILE-SVC-023: an unlink failure logs [files], rethrows and keeps the DB row', async () => {
|
||||
const { user, trip } = seedTrip();
|
||||
const file = makeFile(trip.id, user.id, { filename: 'stuck.pdf' });
|
||||
const boom = new Error('EACCES');
|
||||
vi.spyOn(fs.promises, 'rm').mockRejectedValue(boom);
|
||||
const err = vi.spyOn(console, 'error').mockImplementation(() => {});
|
||||
await expect(svc.permanentDeleteFile(svc.getFileById(file.id, trip.id) as TripFile)).rejects.toThrow('EACCES');
|
||||
expect(err).toHaveBeenCalledWith('[files] unlink failed for stuck.pdf, keeping DB row:', boom);
|
||||
expect(svc.getFileById(file.id, trip.id)).toBeDefined();
|
||||
});
|
||||
});
|
||||
|
||||
describe('emptyTrash', () => {
|
||||
it('FILE-SVC-024: unlinks every trashed file and deletes their rows, returning the count', async () => {
|
||||
const { user, trip } = seedTrip();
|
||||
const a = makeFile(trip.id, user.id, { filename: 'a.pdf' });
|
||||
const b = makeFile(trip.id, user.id, { filename: 'b.pdf' });
|
||||
const kept = makeFile(trip.id, user.id, { filename: 'kept.pdf' });
|
||||
svc.softDeleteFile(a.id);
|
||||
svc.softDeleteFile(b.id);
|
||||
vi.spyOn(fs.promises, 'rm').mockResolvedValue(undefined);
|
||||
|
||||
await expect(svc.emptyTrash(trip.id)).resolves.toBe(2);
|
||||
expect(svc.listFiles(trip.id, true)).toEqual([]);
|
||||
expect(svc.getFileById(kept.id, trip.id)).toBeDefined();
|
||||
});
|
||||
|
||||
it('FILE-SVC-025: a partial unlink failure keeps the failed row, swallows the error and counts only successes', async () => {
|
||||
const { user, trip } = seedTrip();
|
||||
const good = makeFile(trip.id, user.id, { filename: 'good.pdf' });
|
||||
const bad = makeFile(trip.id, user.id, { filename: 'bad.pdf' });
|
||||
svc.softDeleteFile(good.id);
|
||||
svc.softDeleteFile(bad.id);
|
||||
const boom = new Error('EBUSY');
|
||||
vi.spyOn(fs.promises, 'rm').mockImplementation((p) =>
|
||||
String(p).includes('bad.pdf') ? Promise.reject(boom) : Promise.resolve()
|
||||
);
|
||||
const err = vi.spyOn(console, 'error').mockImplementation(() => {});
|
||||
|
||||
await expect(svc.emptyTrash(trip.id)).resolves.toBe(1);
|
||||
expect(err).toHaveBeenCalledWith('[files] unlink failed for bad.pdf, keeping DB row:', boom);
|
||||
expect(svc.getFileById(good.id, trip.id)).toBeUndefined();
|
||||
expect(svc.getDeletedFile(bad.id, trip.id)).toBeDefined();
|
||||
});
|
||||
|
||||
it('FILE-SVC-026: an empty trash resolves to 0 without touching the disk', async () => {
|
||||
const { trip } = seedTrip();
|
||||
const rm = vi.spyOn(fs.promises, 'rm');
|
||||
await expect(svc.emptyTrash(trip.id)).resolves.toBe(0);
|
||||
expect(rm).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
// ── findForeignLinkTarget ─────────────────────────────────────────────────────
|
||||
|
||||
describe('findForeignLinkTarget', () => {
|
||||
function twoTrips() {
|
||||
const { user } = createUser(testDb);
|
||||
const mine = createTrip(testDb, user.id);
|
||||
const foreign = createTrip(testDb, user.id);
|
||||
return { user, mine, foreign };
|
||||
}
|
||||
|
||||
it('FILE-SVC-027: flags each foreign target kind and passes same-trip ids', () => {
|
||||
const { mine, foreign } = twoTrips();
|
||||
const foreignRes = createReservation(testDb, foreign.id);
|
||||
const foreignPlace = createPlace(testDb, foreign.id);
|
||||
const foreignDay = createDay(testDb, foreign.id);
|
||||
const foreignAssignment = createDayAssignment(testDb, foreignDay.id, createPlace(testDb, foreign.id).id);
|
||||
const myRes = createReservation(testDb, mine.id);
|
||||
|
||||
expect(svc.findForeignLinkTarget(mine.id, { reservation_id: foreignRes.id })).toBe('reservation_id');
|
||||
expect(svc.findForeignLinkTarget(mine.id, { place_id: foreignPlace.id })).toBe('place_id');
|
||||
expect(svc.findForeignLinkTarget(mine.id, { assignment_id: foreignAssignment.id })).toBe('assignment_id');
|
||||
expect(svc.findForeignLinkTarget(mine.id, { reservation_id: myRes.id })).toBeNull();
|
||||
});
|
||||
|
||||
it('FILE-SVC-028: falsy ids are skipped (they clear the link) and reservation is checked first', () => {
|
||||
const { mine, foreign } = twoTrips();
|
||||
const foreignRes = createReservation(testDb, foreign.id);
|
||||
const foreignPlace = createPlace(testDb, foreign.id);
|
||||
|
||||
expect(svc.findForeignLinkTarget(mine.id, { reservation_id: 0, place_id: null, assignment_id: undefined })).toBeNull();
|
||||
expect(svc.findForeignLinkTarget(mine.id, { reservation_id: '' })).toBeNull();
|
||||
// Both foreign — the reservation check runs before the place check.
|
||||
expect(svc.findForeignLinkTarget(mine.id, { reservation_id: foreignRes.id, place_id: foreignPlace.id })).toBe('reservation_id');
|
||||
});
|
||||
});
|
||||
|
||||
// ── file links ────────────────────────────────────────────────────────────────
|
||||
|
||||
describe('createFileLink / deleteFileLink / getFileLinks', () => {
|
||||
it('FILE-SVC-029: inserts with || null coercion, dedupes via INSERT OR IGNORE and returns the re-select', () => {
|
||||
const { user, trip } = seedTrip();
|
||||
const reservation = createReservation(testDb, trip.id, { title: 'Ferry' });
|
||||
const file = makeFile(trip.id, user.id);
|
||||
|
||||
const links = svc.createFileLink(file.id, { reservation_id: reservation.id, place_id: '' }) as Record<string, unknown>[];
|
||||
expect(links).toHaveLength(1);
|
||||
expect(links[0].reservation_id).toBe(reservation.id);
|
||||
expect(links[0].place_id).toBeNull();
|
||||
|
||||
const again = svc.createFileLink(file.id, { reservation_id: reservation.id }) as Record<string, unknown>[];
|
||||
expect(again).toHaveLength(1); // UNIQUE(file_id, reservation_id) + OR IGNORE
|
||||
|
||||
const hydrated = svc.getFileLinks(file.id) as Record<string, unknown>[];
|
||||
expect(hydrated[0].reservation_title).toBe('Ferry');
|
||||
});
|
||||
|
||||
it('FILE-SVC-030: an insert error propagates (post-migration fix: no silent swallow)', () => {
|
||||
const { user, trip } = seedTrip();
|
||||
const file = makeFile(trip.id, user.id);
|
||||
expect(() => svc.createFileLink(file.id, { reservation_id: { bad: true } as never })).toThrow();
|
||||
});
|
||||
|
||||
it('FILE-SVC-031: deleteFileLink is scoped to (id AND file_id)', () => {
|
||||
const { user, trip } = seedTrip();
|
||||
const reservation = createReservation(testDb, trip.id);
|
||||
const file = makeFile(trip.id, user.id);
|
||||
const other = makeFile(trip.id, user.id);
|
||||
const [link] = svc.createFileLink(file.id, { reservation_id: reservation.id }) as Record<string, unknown>[];
|
||||
|
||||
svc.deleteFileLink(link.id, other.id); // wrong file — no-op
|
||||
expect(svc.getFileLinks(file.id)).toHaveLength(1);
|
||||
svc.deleteFileLink(link.id, file.id);
|
||||
expect(svc.getFileLinks(file.id)).toHaveLength(0);
|
||||
});
|
||||
});
|
||||
|
||||
// ── download auth & glue ──────────────────────────────────────────────────────
|
||||
|
||||
describe('authenticateDownload', () => {
|
||||
it('FILE-SVC-032: a valid session cookie wins over a bearer token', () => {
|
||||
verifyJwtAndLoadUser.mockReturnValue({ id: 42 });
|
||||
const result = svc.authenticateDownload(req({ cookie: 'cookie-jwt', bearer: 'bearer-jwt' }));
|
||||
expect(result).toEqual({ userId: 42 });
|
||||
expect(verifyJwtAndLoadUser).toHaveBeenCalledWith('cookie-jwt');
|
||||
});
|
||||
|
||||
it('FILE-SVC-033: a bearer token is used when no cookie is present; invalid JWTs 401', () => {
|
||||
verifyJwtAndLoadUser.mockReturnValue({ id: 7 });
|
||||
expect(svc.authenticateDownload(req({ bearer: 'bearer-jwt' }))).toEqual({ userId: 7 });
|
||||
expect(verifyJwtAndLoadUser).toHaveBeenCalledWith('bearer-jwt');
|
||||
|
||||
verifyJwtAndLoadUser.mockReturnValue(null);
|
||||
expect(svc.authenticateDownload(req({ bearer: 'stale' }))).toEqual({ error: 'Invalid or expired token', status: 401 });
|
||||
});
|
||||
|
||||
it('FILE-SVC-034: a ?token= ephemeral token is consumed with the download purpose', () => {
|
||||
consumeEphemeralToken.mockReturnValue(9);
|
||||
expect(svc.authenticateDownload(req({ token: 'eph' }))).toEqual({ userId: 9 });
|
||||
expect(consumeEphemeralToken).toHaveBeenCalledWith('eph', 'download');
|
||||
|
||||
consumeEphemeralToken.mockReturnValue(null);
|
||||
expect(svc.authenticateDownload(req({ token: 'spent' }))).toEqual({ error: 'Invalid or expired token', status: 401 });
|
||||
});
|
||||
|
||||
it('FILE-SVC-035: no credentials at all is a 401 Authentication required', () => {
|
||||
expect(svc.authenticateDownload(req({}))).toEqual({ error: 'Authentication required', status: 401 });
|
||||
expect(verifyJwtAndLoadUser).not.toHaveBeenCalled();
|
||||
expect(consumeEphemeralToken).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
describe('verifyTripAccess / can / files.bridge', () => {
|
||||
it('FILE-SVC-036: verifyTripAccess resolves owner and member, refuses strangers', () => {
|
||||
const { user: owner } = createUser(testDb);
|
||||
const { user: member } = createUser(testDb);
|
||||
const { user: stranger } = createUser(testDb);
|
||||
const trip = createTrip(testDb, owner.id);
|
||||
addTripMember(testDb, trip.id, member.id);
|
||||
|
||||
expect(svc.verifyTripAccess(trip.id, owner.id)?.id).toBe(trip.id);
|
||||
expect(svc.verifyTripAccess(trip.id, member.id)).toBeDefined();
|
||||
expect(svc.verifyTripAccess(trip.id, stranger.id)).toBeFalsy();
|
||||
});
|
||||
|
||||
it('FILE-SVC-037: can() forwards to checkPermission with the shared-trip flag', () => {
|
||||
const { user, trip } = seedTrip();
|
||||
const guest = { id: user.id + 1, role: 'user' } as unknown as User;
|
||||
checkPermission.mockReturnValue(true);
|
||||
const tripRow = { id: trip.id, user_id: user.id } as Record<string, unknown>;
|
||||
|
||||
expect(svc.can('file_edit', tripRow, guest)).toBe(true);
|
||||
expect(checkPermission).toHaveBeenCalledWith('file_edit', 'user', user.id, guest.id, true);
|
||||
|
||||
svc.can('file_upload', tripRow, { id: user.id, role: 'user' } as unknown as User);
|
||||
expect(checkPermission).toHaveBeenLastCalledWith('file_upload', 'user', user.id, user.id, false);
|
||||
});
|
||||
|
||||
it('FILE-SVC-038: files.bridge getAllowedExtensions delegates to the service over the shared db', () => {
|
||||
setAppSetting(testDb, 'allowed_file_types', 'md,markdown');
|
||||
expect(bridgeGetAllowedExtensions()).toBe('md,markdown');
|
||||
});
|
||||
});
|
||||
|
||||
@@ -32,17 +32,18 @@ vi.mock('../../../src/services/budgetService', () => ({
|
||||
rebaseTripCurrency: vi.fn(async () => {}),
|
||||
}));
|
||||
vi.mock('../../../src/services/reservationService', () => ({ listReservations: () => [] }));
|
||||
vi.mock('../../../src/services/fileService', () => ({ listFiles: () => [] }));
|
||||
|
||||
import { TripsService } from '../../../src/nest/trips/trips.service';
|
||||
import type { TodoService } from '../../../src/nest/todo/todo.service';
|
||||
import type { PackingService } from '../../../src/nest/packing/packing.service';
|
||||
import type { FilesService } from '../../../src/nest/files/files.service';
|
||||
import { rebaseTripCurrency } from '../../../src/services/budgetService';
|
||||
|
||||
const todoStub = { listItems: () => [] } as unknown as TodoService;
|
||||
const packingListItems = vi.fn(() => []);
|
||||
const packingStub = { listItems: packingListItems } as unknown as PackingService;
|
||||
function svc() { return new TripsService(new DatabaseService(dbConn), todoStub, packingStub); }
|
||||
const filesStub = { listFiles: () => [] } as unknown as FilesService;
|
||||
function svc() { return new TripsService(new DatabaseService(dbConn), todoStub, packingStub, filesStub); }
|
||||
beforeEach(() => vi.clearAllMocks());
|
||||
|
||||
describe('TripsService (wrapper delegation + bundle/copy/notify helpers)', () => {
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
* per-plugin data db is cached, a granted db:own call works through the wired
|
||||
* host, and trip broadcasts are force-namespaced to plugin:{id}:{event}.
|
||||
* DI-native domains (budget/reservations/tags/categories/todo/packing/
|
||||
* day-notes/assignments/oauth/llm-config) are constructor-injected stubs;
|
||||
* day-notes/assignments/oauth/llm-config/files) are constructor-injected stubs;
|
||||
* legacy services/* domains stay path-mocked until their own DI migration lands.
|
||||
*/
|
||||
import { describe, it, expect, beforeAll, beforeEach, afterAll, vi } from 'vitest';
|
||||
@@ -177,10 +177,17 @@ const { testFilesDir } = vi.hoisted(() => {
|
||||
const pm = require('node:path') as typeof import('node:path');
|
||||
return { testFilesDir: pm.join(osm.tmpdir(), 'trek-crh-files-test') };
|
||||
});
|
||||
vi.mock('../../../src/services/fileService', () => ({
|
||||
listFiles: vi.fn((tid: number, trash: boolean) => [{ id: 2, trip_id: tid, trash }]),
|
||||
// The load-time constants the factory imports from files.constants — mocked so
|
||||
// createTripFile's mkdirSync/writeFileSync land in the tmpdir, never in the
|
||||
// real server/uploads/files (same redirection the old fileService path mock did).
|
||||
vi.mock('../../../src/nest/files/files.constants', () => ({
|
||||
filesDir: testFilesDir,
|
||||
BLOCKED_EXTENSIONS: ['.exe', '.bat', '.sh'],
|
||||
}));
|
||||
// Files: injected stub since the fileService DI migration (same behaviors as
|
||||
// the old path mock).
|
||||
const filesStub = {
|
||||
listFiles: vi.fn((tid: number, trash: boolean) => [{ id: 2, trip_id: tid, trash }]),
|
||||
createFile: vi.fn((tid: number, file: { filename: string; originalname: string; size: number }, uploadedBy: number) => ({ id: 130, trip_id: Number(tid), ...file, uploaded_by: uploadedBy })),
|
||||
createFileLink: vi.fn(() => [{ file_id: 130 }]),
|
||||
getFileById: vi.fn((id: number) => (Number(id) === 404 ? undefined : Number(id) === 500 ? { id: 500, filename: 'huge.mp4', original_name: 'huge.mp4', mime_type: 'video/mp4', file_size: 400 * 1024 * 1024, deleted_at: null } : { id: Number(id), filename: 'visa.pdf', original_name: 'visa.pdf', mime_type: 'application/pdf', file_size: 3, deleted_at: null, description: 'old', place_id: null, reservation_id: null })),
|
||||
@@ -190,7 +197,7 @@ vi.mock('../../../src/services/fileService', () => ({
|
||||
// reservation_id/place_id 999 = belongs to another trip
|
||||
findForeignLinkTarget: vi.fn((_tid: number, opts: { reservation_id?: number | null; place_id?: number | null }) =>
|
||||
(Number(opts.reservation_id) === 999 ? 'reservation_id' : Number(opts.place_id) === 999 ? 'place_id' : null)),
|
||||
}));
|
||||
} as unknown as FilesService;
|
||||
vi.mock('../../../src/services/collabService', () => ({
|
||||
listNotes: vi.fn((tid: number) => [{ id: 1, trip_id: Number(tid), title: 'Note' }]),
|
||||
listPolls: vi.fn((tid: number) => [{ id: 2, trip_id: Number(tid), question: 'Q?' }]),
|
||||
@@ -301,12 +308,13 @@ import type { DayNotesService } from '../../../src/nest/days/day-notes.service';
|
||||
import type { AssignmentsService } from '../../../src/nest/assignments/assignments.service';
|
||||
import type { PluginOAuthService } from '../../../src/nest/plugins/plugin-oauth.service';
|
||||
import type { LlmConfigResolver } from '../../../src/nest/llm-parse/llm-config.resolver';
|
||||
import type { FilesService } from '../../../src/nest/files/files.service';
|
||||
import { DatabaseService } from '../../../src/nest/database/database.service';
|
||||
|
||||
// The factory under test, wired exactly like PluginsModule does — but with the
|
||||
// DI-native domain services replaced by the stubs above. The shim keeps the
|
||||
// ~45 historical call sites unchanged and supplies a default no-op router.
|
||||
const factory = new PluginHostDepsFactory(budgetStub, reservationsStub, tagsStub, categoriesStub, todoStub, packingStub, oauthStub, dayNotesStub, assignmentsStub, llmConfigStub, new DatabaseService(mockDb));
|
||||
const factory = new PluginHostDepsFactory(budgetStub, reservationsStub, tagsStub, categoriesStub, todoStub, packingStub, oauthStub, dayNotesStub, assignmentsStub, llmConfigStub, new DatabaseService(mockDb), filesStub);
|
||||
const stubRouter: PluginCallRouter = { callPlugin: async () => undefined, emitPluginEvent: () => {} };
|
||||
const createRealRpcHost = (id: string, granted: ReadonlySet<string>, router: PluginCallRouter = stubRouter) => factory.create(id, granted, router);
|
||||
|
||||
|
||||
Reference in New Issue
Block a user