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:
jubnl
2026-07-26 23:19:26 +02:00
parent dd3c03ba0f
commit f3e5be78c9
21 changed files with 1013 additions and 530 deletions
+1 -1
View File
@@ -23,7 +23,7 @@ import type { User } from '../../types';
import { CollabService } from './collab.service';
import { JwtAuthGuard } from '../auth/jwt-auth.guard';
import { CurrentUser } from '../auth/current-user.decorator';
import { BLOCKED_EXTENSIONS } from '../../services/fileService';
import { BLOCKED_EXTENSIONS } from '../files/files.constants';
const MAX_NOTE_FILE_SIZE = 50 * 1024 * 1024;
const filesDir = path.join(__dirname, '../../../uploads/files');
@@ -74,9 +74,6 @@ export const BODY_CONTRACT_ALLOW_LIST: string[] = [
'DaysController.reorder',
'DaysController.transport',
'DaysController.update',
'FilesController.link',
'FilesController.update',
'FilesController.upload',
'ImmichMemoriesController.putSettings',
'ImmichMemoriesController.search',
'ImmichMemoriesController.test',
+21
View File
@@ -0,0 +1,21 @@
import { db } from '../../db/database';
import { DatabaseService } from '../database/database.service';
import { FilesService } from './files.service';
/**
* Non-Nest entry point for the files domain. Unlike todo.bridge.ts this does
* NOT serve a legacy MCP registrar (files has no MCP surface) — it exists only
* because multer interceptor options are module-scope object literals (the
* UPLOAD configs in files.controller.ts and journey.controller.ts are built
* before any DI container exists), yet their fileFilter closures need the
* request-time app_settings read. Everything else injects FilesService.
* Delete this file if uploads ever move to MulterModule.registerAsync.
*
* Module-level construction is safe: `db` is the reinitialize-proof Proxy onto
* the shared better-sqlite3 singleton.
*/
const files = new FilesService(new DatabaseService(db));
export function getAllowedExtensions(): string {
return files.getAllowedExtensions();
}
+44
View File
@@ -0,0 +1,44 @@
import path from 'path';
/**
* File-domain constants and pure helpers, split out of FilesService because
* they are consumed at module-load time (multer interceptor configs in the
* files/collab/journey controllers and the plugin host factory) where no DI
* container exists yet. Everything here is DB-free and side-effect-free at
* import; the one request-time DB read those configs need lives in
* files.bridge.ts.
*/
export const MAX_FILE_SIZE = 50 * 1024 * 1024; // 50 MB
export const DEFAULT_ALLOWED_EXTENSIONS = 'jpg,jpeg,png,gif,webp,heic,pdf,doc,docx,xls,xlsx,txt,csv,pkpass,pkpasses,md,markdown';
// Video support (#823). Gallery/media uploads accept these in addition to images,
// independent of the admin doc-types allowlist. Videos are stored as-is and
// streamed with HTTP Range; the cap is higher than images because phone clips are
// large.
export const VIDEO_EXTENSIONS = ['mp4', 'm4v', 'webm', 'mov'];
export const MAX_VIDEO_SIZE = 500 * 1024 * 1024; // 500 MB
export function isVideoMime(mime: string | undefined | null): boolean {
return !!mime && mime.startsWith('video/');
}
export function isVideoExtension(ext: string): boolean {
return VIDEO_EXTENSIONS.includes(ext.toLowerCase().replace(/^\./, ''));
}
// Single authoritative blocklist for every file-upload surface (main
// file manager + collab attachments). When the admin setting
// `allowed_file_types` is `*`, this list is still enforced so the
// wildcard doesn't silently admit executables/scripts.
export const BLOCKED_EXTENSIONS = [
// Server-rendered / scripted content that could XSS a viewer
'.svg', '.html', '.htm', '.xml', '.xhtml',
// Scripts
'.js', '.jsx', '.ts', '.tsx', '.mjs', '.cjs', '.php', '.py', '.rb', '.pl',
// Executables
'.exe', '.bat', '.sh', '.cmd', '.msi', '.dll', '.com', '.vbs', '.ps1', '.app',
];
// One directory level deeper than the legacy src/services/fileService.ts, so
// the extra '..' keeps the same absolute <server>/uploads/files under both the
// src (vitest) and dist (runtime) layouts.
export const filesDir = path.join(__dirname, '../../../uploads/files');
+7 -5
View File
@@ -25,7 +25,9 @@ import type { User } from '../../types';
import { FilesService } from './files.service';
import { JwtAuthGuard } from '../auth/jwt-auth.guard';
import { CurrentUser } from '../auth/current-user.decorator';
import { MAX_FILE_SIZE, MAX_VIDEO_SIZE, BLOCKED_EXTENSIONS, filesDir, getAllowedExtensions, isVideoExtension } from '../../services/fileService';
import { MAX_FILE_SIZE, MAX_VIDEO_SIZE, BLOCKED_EXTENSIONS, filesDir, isVideoExtension } from './files.constants';
import { getAllowedExtensions } from './files.bridge';
import { FileUploadDto, FileUpdateDto, FileLinkDto } from './files.dto';
import { isDemoEmail } from '../../services/demo';
const UPLOAD = {
@@ -80,7 +82,7 @@ export class FilesController {
// A file may only point at reservations/assignments/places from its own trip.
// Reject cross-trip ids before they are stored — the reservation JOIN would
// otherwise leak the foreign reservation's title back to the caller.
private assertLinkTargets(tripId: string, body: { reservation_id?: string | null; assignment_id?: string | null; place_id?: string | null }) {
private assertLinkTargets(tripId: string, body: { reservation_id?: string | number | null; assignment_id?: string | number | null; place_id?: string | number | null }) {
if (this.files.findForeignLinkTarget(tripId, body)) {
throw new HttpException({ error: 'Linked item does not belong to this trip' }, 400);
}
@@ -98,7 +100,7 @@ export class FilesController {
@CurrentUser() user: User,
@Param('tripId') tripId: string,
@UploadedFile() file: Express.Multer.File | undefined,
@Body() body: { place_id?: string; description?: string; reservation_id?: string },
@Body() body: FileUploadDto,
@Headers('x-socket-id') socketId?: string,
) {
// multer (diskStorage) has already written the upload by the time we get here,
@@ -144,7 +146,7 @@ export class FilesController {
}
@Put(':id')
update(@CurrentUser() user: User, @Param('tripId') tripId: string, @Param('id') id: string, @Body() body: { description?: string; place_id?: string | null; reservation_id?: string | null }, @Headers('x-socket-id') socketId?: string) {
update(@CurrentUser() user: User, @Param('tripId') tripId: string, @Param('id') id: string, @Body() body: FileUpdateDto, @Headers('x-socket-id') socketId?: string) {
const trip = this.requireTrip(tripId, user);
if (!this.files.can('file_edit', trip, user)) {
throw new HttpException({ error: 'No permission to edit files' }, 403);
@@ -232,7 +234,7 @@ export class FilesController {
@Post(':id/link')
@HttpCode(200) // Express answers link with res.json (200).
link(@CurrentUser() user: User, @Param('tripId') tripId: string, @Param('id') id: string, @Body() body: { reservation_id?: string | null; assignment_id?: string | null; place_id?: string | null }) {
link(@CurrentUser() user: User, @Param('tripId') tripId: string, @Param('id') id: string, @Body() body: FileLinkDto) {
const trip = this.requireTrip(tripId, user);
if (!this.files.can('file_edit', trip, user)) {
throw new HttpException({ error: 'No permission' }, 403);
+18
View File
@@ -0,0 +1,18 @@
import { createZodDto } from 'nestjs-zod';
import {
fileUploadRequestSchema,
fileUpdateRequestSchema,
fileLinkRequestSchema,
} from '@trek/shared';
/**
* Server-side createZodDto wrappers over the @trek/shared file contracts. The
* global ZodValidationPipe (APP_PIPE in app.module.ts) validates any @Body()
* parameter typed with one of these classes by metatype — the Zod schemas in
* shared/ remain the single source of truth for the wire contract. Upload is
* multipart: FileInterceptor populates req.body with the text fields before
* the pipe runs, so the DTO sees plain strings.
*/
export class FileUploadDto extends createZodDto(fileUploadRequestSchema) {}
export class FileUpdateDto extends createZodDto(fileUpdateRequestSchema) {}
export class FileLinkDto extends createZodDto(fileLinkRequestSchema) {}
+1
View File
@@ -6,5 +6,6 @@ import { FilesService } from './files.service';
@Module({
controllers: [FilesController, FilesDownloadController],
providers: [FilesService],
exports: [FilesService],
})
export class FilesModule {}
+290 -26
View File
@@ -1,22 +1,63 @@
import { Injectable } from '@nestjs/common';
import path from 'path';
import fs from 'fs';
import type { Request } from 'express';
import { broadcast } from '../../websocket';
import { checkPermission } from '../../services/permissions';
import { avatarUrl } from '../../services/avatarUrl';
import { consumeEphemeralToken } from '../../services/ephemeralTokens';
import { verifyJwtAndLoadUser } from '../../middleware/auth';
import type { User, TripFile } from '../../types';
import * as svc from '../../services/fileService';
import { DatabaseService, type TripAccess } from '../database/database.service';
import { DEFAULT_ALLOWED_EXTENSIONS, filesDir } from './files.constants';
type Trip = NonNullable<ReturnType<typeof svc.verifyTripAccess>>;
type Trip = TripAccess;
type FilePermission = 'file_upload' | 'file_edit' | 'file_delete';
const FILE_SELECT = `
SELECT f.*, r.title as reservation_title, u.username as uploaded_by_name, u.avatar as uploaded_by_avatar
FROM trip_files f
LEFT JOIN reservations r ON f.reservation_id = r.id
LEFT JOIN users u ON f.uploaded_by = u.id
`;
function formatFile(file: TripFile & { uploaded_by_avatar?: string | null }) {
const tripId = file.trip_id;
return {
...file,
url: `/api/trips/${tripId}/files/${file.id}/download`,
uploaded_by_avatar: avatarUrl({ avatar: file.uploaded_by_avatar }),
};
}
export interface FileLink {
file_id: number;
reservation_id: number | null;
place_id: number | null;
}
/**
* Thin Nest wrapper around the existing file service. Trip access, the
* file_* permissions, the SQL, the path-resolution guard, the download-token
* auth and the WebSocket broadcasts reuse the legacy code unchanged.
* File domain service — owns the file SQL (moved 1:1 from the legacy
* services/fileService.ts: identical statements, the `||` falsy-coercion
* defaults, the post-write FILE_SELECT re-selects, the dynamic IN batches and
* the unlink-first delete semantics). Trip access goes through the injected
* DatabaseService's canAccessTrip (the legacy verifyTripAccess re-export was a
* plain wrapper over the same helper); the file_* permissions, path-resolution
* guard, download-token auth and WebSocket broadcasts are unchanged. The
* load-time constants live in files.constants.ts; the one out-of-DI consumer
* path (module-scope multer configs) reaches getAllowedExtensions through
* files.bridge.ts.
*
* Two deliberate post-migration fixes over the legacy behavior: createFileLink
* no longer swallows insert errors, and updateFile coerces an empty-string
* description to NULL exactly like createFile does.
*/
@Injectable()
export class FilesService {
verifyTripAccess(tripId: string, userId: number) {
return svc.verifyTripAccess(tripId, userId);
constructor(private readonly db: DatabaseService) {}
verifyTripAccess(tripId: string | number, userId: number) {
return this.db.canAccessTrip(tripId, userId);
}
can(action: FilePermission, trip: Trip, user: User): boolean {
@@ -27,24 +68,247 @@ export class FilesService {
broadcast(tripId, event, payload, socketId);
}
// Download-token auth + safe path resolution (used by the unguarded download route).
authenticateDownload(req: Request) { return svc.authenticateDownload(req); }
resolveFilePath(filename: string) { return svc.resolveFilePath(filename); }
listFiles(tripId: string, showTrash: boolean) { return svc.listFiles(tripId, showTrash); }
getFileById(id: string, tripId: string) { return svc.getFileById(id, tripId); }
getDeletedFile(id: string, tripId: string) { return svc.getDeletedFile(id, tripId); }
createFile(tripId: string, file: Parameters<typeof svc.createFile>[1], userId: number, opts: Parameters<typeof svc.createFile>[3]) {
return svc.createFile(tripId, file, userId, opts);
getAllowedExtensions(): string {
try {
const row = this.db.get<{ value: string }>("SELECT value FROM app_settings WHERE key = 'allowed_file_types'");
return row?.value || DEFAULT_ALLOWED_EXTENSIONS;
} catch { return DEFAULT_ALLOWED_EXTENSIONS; }
}
// ---------------------------------------------------------------------------
// Token-based download auth & safe path resolution (used by the unguarded
// download route)
// ---------------------------------------------------------------------------
authenticateDownload(req: Request): { userId: number } | { error: string; status: number } {
const cookieToken = (req as { cookies?: Record<string, string> }).cookies?.trek_session;
const authHeader = req.headers['authorization'];
const bearerToken = authHeader ? (authHeader.split(' ')[1] || undefined) : undefined;
const queryToken = req.query.token as string | undefined;
// Cookie and Bearer both carry a full JWT — try them first (cookie wins).
const jwtToken = cookieToken || bearerToken;
if (jwtToken) {
// Use the shared helper so the password_version gate applies here too;
// previously this bypassed the check and stolen download tokens stayed
// valid across a password reset.
const user = verifyJwtAndLoadUser(jwtToken);
if (!user) return { error: 'Invalid or expired token', status: 401 };
return { userId: user.id };
}
if (queryToken) {
const uid = consumeEphemeralToken(queryToken, 'download');
if (!uid) return { error: 'Invalid or expired token', status: 401 };
return { userId: uid };
}
return { error: 'Authentication required', status: 401 };
}
resolveFilePath(filename: string): { resolved: string; safe: boolean } {
const safeName = path.basename(filename);
const filePath = path.join(filesDir, safeName);
const resolved = path.resolve(filePath);
const safe = resolved.startsWith(path.resolve(filesDir));
return { resolved, safe };
}
// ---------------------------------------------------------------------------
// Trip-scoped link validation
// ---------------------------------------------------------------------------
/**
* A file, and any reservation / day-assignment / place it points at, must all
* live in the same trip. FILE_SELECT and getFileLinks join the reservation and
* return its title, so without this guard a member of trip A could aim a file
* (or a file_link) at trip B's reservation id and read the title back. Returns
* the first field that escapes `tripId`, or null when every supplied id belongs
* to the trip. Absent / null / zero ids are ignored (they clear the link).
*/
findForeignLinkTarget(
tripId: string | number,
opts: { reservation_id?: string | number | null; assignment_id?: string | number | null; place_id?: string | number | null }
): 'reservation_id' | 'assignment_id' | 'place_id' | null {
if (opts.reservation_id && !this.db.get('SELECT 1 FROM reservations WHERE id = ? AND trip_id = ?', opts.reservation_id, tripId)) {
return 'reservation_id';
}
if (opts.place_id && !this.db.get('SELECT 1 FROM places WHERE id = ? AND trip_id = ?', opts.place_id, tripId)) {
return 'place_id';
}
if (opts.assignment_id && !this.db.get('SELECT 1 FROM day_assignments a JOIN days d ON a.day_id = d.id WHERE a.id = ? AND d.trip_id = ?', opts.assignment_id, tripId)) {
return 'assignment_id';
}
return null;
}
// ---------------------------------------------------------------------------
// CRUD
// ---------------------------------------------------------------------------
getFileById(id: string | number, tripId: string | number): TripFile | undefined {
return this.db.get<TripFile>('SELECT * FROM trip_files WHERE id = ? AND trip_id = ?', id, tripId);
}
getDeletedFile(id: string | number, tripId: string | number): TripFile | undefined {
return this.db.get<TripFile>('SELECT * FROM trip_files WHERE id = ? AND trip_id = ? AND deleted_at IS NOT NULL', id, tripId);
}
listFiles(tripId: string | number, showTrash: boolean) {
const where = showTrash ? 'f.trip_id = ? AND f.deleted_at IS NOT NULL' : 'f.trip_id = ? AND f.deleted_at IS NULL';
const files = this.db.all<TripFile>(`${FILE_SELECT} WHERE ${where} ORDER BY f.starred DESC, f.created_at DESC`, tripId);
const fileIds = files.map(f => f.id);
const linksMap: Record<number, FileLink[]> = {};
if (fileIds.length > 0) {
const placeholders = fileIds.map(() => '?').join(',');
const links = this.db.all<FileLink>(`SELECT file_id, reservation_id, place_id FROM file_links WHERE file_id IN (${placeholders})`, ...fileIds);
for (const link of links) {
if (!linksMap[link.file_id]) linksMap[link.file_id] = [];
linksMap[link.file_id].push(link);
}
}
return files.map(f => {
const fileLinks = linksMap[f.id] || [];
return {
...formatFile(f),
linked_reservation_ids: fileLinks.filter(l => l.reservation_id).map(l => l.reservation_id),
linked_place_ids: fileLinks.filter(l => l.place_id).map(l => l.place_id),
};
});
}
createFile(
tripId: string | number,
file: { filename: string; originalname: string; size: number; mimetype: string },
uploadedBy: number,
opts: { place_id?: string | number | null; reservation_id?: string | number | null; description?: string | null }
) {
const result = this.db.run(`
INSERT INTO trip_files (trip_id, place_id, reservation_id, filename, original_name, file_size, mime_type, description, uploaded_by)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
`,
tripId,
opts.place_id || null,
opts.reservation_id || null,
file.filename,
file.originalname,
file.size,
file.mimetype,
opts.description || null,
uploadedBy
);
const created = this.db.get<TripFile>(`${FILE_SELECT} WHERE f.id = ?`, result.lastInsertRowid)!;
return formatFile(created);
}
updateFile(
id: string | number,
current: TripFile,
updates: { description?: string; place_id?: string | number | null; reservation_id?: string | number | null }
) {
this.db.run(`
UPDATE trip_files SET
description = ?,
place_id = ?,
reservation_id = ?
WHERE id = ?
`,
updates.description !== undefined ? (updates.description || null) : current.description,
updates.place_id !== undefined ? (updates.place_id || null) : current.place_id,
updates.reservation_id !== undefined ? (updates.reservation_id || null) : current.reservation_id,
id
);
const updated = this.db.get<TripFile>(`${FILE_SELECT} WHERE f.id = ?`, id)!;
return formatFile(updated);
}
toggleStarred(id: string | number, currentStarred: number | undefined) {
const newStarred = currentStarred ? 0 : 1;
this.db.run('UPDATE trip_files SET starred = ? WHERE id = ?', newStarred, id);
const updated = this.db.get<TripFile>(`${FILE_SELECT} WHERE f.id = ?`, id)!;
return formatFile(updated);
}
softDeleteFile(id: string | number) {
this.db.run('UPDATE trip_files SET deleted_at = CURRENT_TIMESTAMP WHERE id = ?', id);
}
restoreFile(id: string | number) {
this.db.run('UPDATE trip_files SET deleted_at = NULL WHERE id = ?', id);
const restored = this.db.get<TripFile>(`${FILE_SELECT} WHERE f.id = ?`, id)!;
return formatFile(restored);
}
async permanentDeleteFile(file: TripFile): Promise<void> {
const { resolved } = this.resolveFilePath(file.filename);
// `force: true` swallows ENOENT, replacing the prior existsSync+unlink
// double-call that blocked the event loop twice per deletion. Only
// drop the DB row when the on-disk unlink either succeeded or the
// file was already gone — otherwise a permission / ENOSPC failure
// would orphan the bytes on disk with no DB pointer left to clean it.
try {
await fs.promises.rm(resolved, { force: true });
} catch (e) {
console.error(`[files] unlink failed for ${file.filename}, keeping DB row:`, e);
throw e;
}
this.db.run('DELETE FROM trip_files WHERE id = ?', file.id);
}
async emptyTrash(tripId: string | number): Promise<number> {
const trashed = this.db.all<TripFile>('SELECT * FROM trip_files WHERE trip_id = ? AND deleted_at IS NOT NULL', tripId);
// Collect successful IDs separately so we only DELETE rows whose disk
// content was actually removed — failing unlinks keep their DB row
// and a retry via the single-file delete path can try again.
const successfullyUnlinked: number[] = [];
await Promise.all(trashed.map(async (file) => {
const { resolved } = this.resolveFilePath(file.filename);
try {
await fs.promises.rm(resolved, { force: true });
successfullyUnlinked.push(Number(file.id));
} catch (e) {
console.error(`[files] unlink failed for ${file.filename}, keeping DB row:`, e);
}
}));
if (successfullyUnlinked.length > 0) {
const placeholders = successfullyUnlinked.map(() => '?').join(',');
this.db.run(`DELETE FROM trip_files WHERE id IN (${placeholders})`, ...successfullyUnlinked);
}
return successfullyUnlinked.length;
}
// ---------------------------------------------------------------------------
// File links (many-to-many)
// ---------------------------------------------------------------------------
// Dedupe rides INSERT OR IGNORE + the UNIQUE(file_id, <target>) constraints;
// a genuine insert failure propagates to the global exception filter instead
// of returning a success-shaped links list (the legacy catch swallowed it).
createFileLink(
fileId: string | number,
opts: { reservation_id?: string | number | null; assignment_id?: string | number | null; place_id?: string | number | null }
) {
this.db.run('INSERT OR IGNORE INTO file_links (file_id, reservation_id, assignment_id, place_id) VALUES (?, ?, ?, ?)',
fileId, opts.reservation_id || null, opts.assignment_id || null, opts.place_id || null
);
return this.db.all('SELECT * FROM file_links WHERE file_id = ?', fileId);
}
deleteFileLink(linkId: string | number, fileId: string | number) {
this.db.run('DELETE FROM file_links WHERE id = ? AND file_id = ?', linkId, fileId);
}
getFileLinks(fileId: string | number) {
return this.db.all(`
SELECT fl.*, r.title as reservation_title
FROM file_links fl
LEFT JOIN reservations r ON fl.reservation_id = r.id
WHERE fl.file_id = ?
`, fileId);
}
updateFile(id: string, current: TripFile, updates: Parameters<typeof svc.updateFile>[2]) { return svc.updateFile(id, current, updates); }
toggleStarred(id: string, currentStarred: number | undefined) { return svc.toggleStarred(id, currentStarred); }
softDeleteFile(id: string) { return svc.softDeleteFile(id); }
restoreFile(id: string) { return svc.restoreFile(id); }
permanentDeleteFile(file: TripFile) { return svc.permanentDeleteFile(file); }
emptyTrash(tripId: string) { return svc.emptyTrash(tripId); }
findForeignLinkTarget(tripId: string, opts: Parameters<typeof svc.findForeignLinkTarget>[1]) { return svc.findForeignLinkTarget(tripId, opts); }
createFileLink(id: string, opts: Parameters<typeof svc.createFileLink>[1]) { return svc.createFileLink(id, opts); }
deleteFileLink(linkId: string, id: string) { return svc.deleteFileLink(linkId, id); }
getFileLinks(id: string) { return svc.getFileLinks(id); }
}
@@ -25,7 +25,8 @@ import { JourneyService } from './journey.service';
import { JourneyAddonGuard } from './journey-addon.guard';
import { JwtAuthGuard } from '../auth/jwt-auth.guard';
import { CurrentUser } from '../auth/current-user.decorator';
import { getAllowedExtensions, isVideoMime, isVideoExtension, MAX_VIDEO_SIZE } from '../../services/fileService';
import { isVideoMime, isVideoExtension, MAX_VIDEO_SIZE } from '../files/files.constants';
import { getAllowedExtensions } from '../files/files.bridge';
const uploadsBase = path.join(__dirname, '../../../uploads/journey');
const IMAGE_UPLOAD = {
@@ -4,7 +4,7 @@ import { broadcast, broadcastToUser } from '../../../websocket';
import { listBudgetItems } from '../../../services/budgetService';
import { isUpdateConflict } from '../../../services/conflictResult';
import { getWeather } from '../../../services/weatherService';
import { listFiles, createFile, createFileLink, getFileById, updateFile, softDeleteFile, findForeignLinkTarget, resolveFilePath, BLOCKED_EXTENSIONS, filesDir } from '../../../services/fileService';
import { BLOCKED_EXTENSIONS, filesDir } from '../../files/files.constants';
import { createNote as createCollabNoteSvc, createPoll as createCollabPollSvc, votePoll as voteCollabPollSvc, createMessage as createCollabMessageSvc, listNotes as listCollabNotesSvc, listPolls as listCollabPollsSvc, listMessages as listCollabMessagesSvc } from '../../../services/collabService';
import { getRates as getExchangeRates } from '../../../services/exchangeRateService';
import { joinTripAsMember } from '../../../services/tripMembership';
@@ -36,6 +36,7 @@ import { DayNotesService } from '../../days/day-notes.service';
import { AssignmentsService } from '../../assignments/assignments.service';
import { LlmConfigResolver } from '../../llm-parse/llm-config.resolver';
import { DatabaseService } from '../../database/database.service';
import { FilesService } from '../../files/files.service';
import { notifyBookingChange } from '../../../services/reservationService';
import { PluginRpcHost, ForbiddenResource, BadParams } from './rpc-host';
import { appendAudit } from './plugin-audit';
@@ -136,8 +137,8 @@ export interface PluginCallRouter {
* `plugin:{id}:{event}` so a plugin can't forge a core event.
*
* DI-native domain services (budget, reservations, tags, categories, todo,
* packing, day-notes, assignments, oauth, the LLM config resolver) and the
* DatabaseService (all inline SQL + the trip-access helper) are
* packing, day-notes, assignments, oauth, files, the LLM config resolver) and
* the DatabaseService (all inline SQL + the trip-access helper) are
* constructor-injected; legacy `services/*` domains stay plain function
* imports until their own migration lands (DI-MIGRATION.md), at which point
* each swaps one import for one injected service.
@@ -156,6 +157,7 @@ export class PluginHostDepsFactory {
private readonly assignments: AssignmentsService,
private readonly llmConfig: LlmConfigResolver,
private readonly db: DatabaseService,
private readonly files: FilesService,
) {}
/**
@@ -217,16 +219,16 @@ export class PluginHostDepsFactory {
// --- Read scopes (packing/files). Membership is checked by the host (tripRead);
// these just delegate to the same services the REST paths use. ---
listPackingItems: (tripId, userId) => this.packing.listItems(tripId, userId),
listTripFiles: (tripId) => listFiles(tripId, false),
listTripFiles: (tripId) => this.files.listFiles(tripId, false),
// A file's bytes as base64, size-capped BEFORE the read so a 500MB video can't
// be pulled (~667MB base64) through the IPC pipe. 10MB matches the plugin upload
// cap; trashed files (deleted_at set) are refused like the download path.
getTripFileContent: async (tripId, fileId) => {
const CONTENT_MAX = 10 * 1024 * 1024;
const file = getFileById(fileId, tripId) as { filename: string; original_name: string; mime_type: string | null; file_size: number | null; deleted_at: string | null } | undefined;
const file = this.files.getFileById(fileId, tripId) as { filename: string; original_name: string; mime_type: string | null; file_size: number | null; deleted_at: string | null } | undefined;
if (!file || file.deleted_at) throw new ForbiddenResource(`no file ${fileId} on trip ${tripId}`);
if ((file.file_size ?? 0) > CONTENT_MAX) throw new BadParams(`file too large to read (>${CONTENT_MAX} bytes); use the download UI`);
const { resolved, safe } = resolveFilePath(file.filename);
const { resolved, safe } = this.files.resolveFilePath(file.filename);
if (!safe) throw new ForbiddenResource('file path is not accessible');
// Read off the event loop — a 10MB read + base64 on the host thread would
// otherwise stall every other plugin RPC and request for its duration.
@@ -256,12 +258,12 @@ export class PluginHostDepsFactory {
const buf = Buffer.from(i.content_base64, 'base64');
if (buf.length === 0) throw new BadParams('file content is empty');
if (buf.length > 10 * 1024 * 1024) throw new BadParams('file exceeds the 10MB plugin upload cap');
const foreign = findForeignLinkTarget(tripId, { reservation_id: i.reservation_id ?? null, place_id: i.place_id ?? null });
const foreign = this.files.findForeignLinkTarget(tripId, { reservation_id: i.reservation_id ?? null, place_id: i.place_id ?? null });
if (foreign) throw new ForbiddenResource(`${foreign} does not belong to trip ${tripId}`);
const filename = `${randomUUID()}${ext}`;
fsMod.mkdirSync(filesDir, { recursive: true });
fsMod.writeFileSync(pathMod.join(filesDir, filename), buf);
const file = createFile(
const file = this.files.createFile(
tripId,
{ filename, originalname: original, size: buf.length, mimetype: i.mimetype || 'application/octet-stream' },
actingUserId,
@@ -271,25 +273,25 @@ export class PluginHostDepsFactory {
return file;
},
createTripFileLink: (tripId, fileId, opts) => {
if (!getFileById(fileId, tripId)) throw new ForbiddenResource(`no file ${fileId} on trip ${tripId}`);
if (!this.files.getFileById(fileId, tripId)) throw new ForbiddenResource(`no file ${fileId} on trip ${tripId}`);
const o = opts as { reservation_id?: number; assignment_id?: number; place_id?: number };
const foreign = findForeignLinkTarget(tripId, o);
const foreign = this.files.findForeignLinkTarget(tripId, o);
if (foreign) throw new ForbiddenResource(`${foreign} does not belong to trip ${tripId}`);
return createFileLink(fileId, { reservation_id: o.reservation_id != null ? String(o.reservation_id) : null, assignment_id: o.assignment_id != null ? String(o.assignment_id) : null, place_id: o.place_id != null ? String(o.place_id) : null });
return this.files.createFileLink(fileId, { reservation_id: o.reservation_id != null ? String(o.reservation_id) : null, assignment_id: o.assignment_id != null ? String(o.assignment_id) : null, place_id: o.place_id != null ? String(o.place_id) : null });
},
updateTripFile: (tripId, fileId, input) => {
const current = getFileById(fileId, tripId);
const current = this.files.getFileById(fileId, tripId);
if (!current) throw new ForbiddenResource(`no file ${fileId} on trip ${tripId}`);
const i = input as { description?: string; place_id?: number | null; reservation_id?: number | null };
const foreign = findForeignLinkTarget(tripId, { reservation_id: i.reservation_id ?? null, place_id: i.place_id ?? null });
const foreign = this.files.findForeignLinkTarget(tripId, { reservation_id: i.reservation_id ?? null, place_id: i.place_id ?? null });
if (foreign) throw new ForbiddenResource(`${foreign} does not belong to trip ${tripId}`);
const file = updateFile(fileId, current, { description: i.description, place_id: i.place_id != null ? String(i.place_id) : i.place_id === null ? null : undefined, reservation_id: i.reservation_id != null ? String(i.reservation_id) : i.reservation_id === null ? null : undefined });
const file = this.files.updateFile(fileId, current, { description: i.description, place_id: i.place_id != null ? String(i.place_id) : i.place_id === null ? null : undefined, reservation_id: i.reservation_id != null ? String(i.reservation_id) : i.reservation_id === null ? null : undefined });
broadcast(tripId, 'file:updated', { file }, undefined);
return file;
},
softDeleteTripFile: (tripId, fileId) => {
if (!getFileById(fileId, tripId)) throw new ForbiddenResource(`no file ${fileId} on trip ${tripId}`);
softDeleteFile(fileId);
if (!this.files.getFileById(fileId, tripId)) throw new ForbiddenResource(`no file ${fileId} on trip ${tripId}`);
this.files.softDeleteFile(fileId);
broadcast(tripId, 'file:deleted', { fileId }, undefined);
return { deleted: true };
},
+2 -1
View File
@@ -33,6 +33,7 @@ import { PackingModule } from '../packing/packing.module';
import { DaysModule } from '../days/days.module';
import { AssignmentsModule } from '../assignments/assignments.module';
import { LlmParseModule } from '../llm-parse/llm-parse.module';
import { FilesModule } from '../files/files.module';
/**
* Plugin system (#plugins). M0 read side + M2 isolated runtime + M3 frontend:
@@ -44,7 +45,7 @@ import { LlmParseModule } from '../llm-parse/llm-parse.module';
@Module({
// The DI-native domain services the plugin host wiring injects
// (PluginHostDepsFactory); DatabaseModule is @Global, so not listed.
imports: [TagsModule, CategoriesModule, BudgetModule, ReservationsModule, TodoModule, PackingModule, DaysModule, AssignmentsModule, LlmParseModule],
imports: [TagsModule, CategoriesModule, BudgetModule, ReservationsModule, TodoModule, PackingModule, DaysModule, AssignmentsModule, LlmParseModule, FilesModule],
controllers: [PluginsController, PluginsFeedController, PluginsProxyController, PluginFrameController, PlaceDetailsController, TripWarningsController, ViewContributionsController, TripCardContributionsController, PluginPhotosController, PluginCalendarController, MapMarkersController, MapLayersController, PluginRoutesController, DayScheduleController, PdfSectionsController, AtlasLayersController, JournalEntryRowsController, PluginUserSettingsController, PluginOAuthController, PluginActivityController],
providers: [PluginsService, PluginRuntimeService, PluginRegistryService, PluginOAuthService, PluginHostDepsFactory],
// Exported so the admin addon-toggle handler can cascade-disable plugins whose
+2 -1
View File
@@ -1,4 +1,5 @@
import { Module } from '@nestjs/common';
import { FilesModule } from '../files/files.module';
import { PackingModule } from '../packing/packing.module';
import { TodoModule } from '../todo/todo.module';
import { TripsController } from './trips.controller';
@@ -7,7 +8,7 @@ import { TripsService } from './trips.service';
/** Trips aggregate root (C1 — Phase 3). Uses exact strangler prefixes so it does
* not capture the nested sub-domain mounts (collab, files, ...). */
@Module({
imports: [TodoModule, PackingModule],
imports: [TodoModule, PackingModule, FilesModule],
controllers: [TripsController],
providers: [TripsService],
})
+3 -2
View File
@@ -10,7 +10,7 @@ import { PackingService } from '../packing/packing.service';
import { TodoService } from '../todo/todo.service';
import { listBudgetItems, rebaseTripCurrency } from '../../services/budgetService';
import { listReservations } from '../../services/reservationService';
import { listFiles } from '../../services/fileService';
import { FilesService } from '../files/files.service';
import { searchUnsplashPhotos, getUnsplashKey } from '../../services/unsplashService';
/**
@@ -26,6 +26,7 @@ export class TripsService {
private readonly dbs: DatabaseService,
private readonly todo: TodoService,
private readonly packing: PackingService,
private readonly files: FilesService,
) {}
private get db() {
@@ -143,7 +144,7 @@ export class TripsService {
todoItems: this.todo.listItems(tripId),
budgetItems: listBudgetItems(tripId),
reservations: listReservations(tripId),
files: listFiles(tripId, false),
files: this.files.listFiles(tripId, false),
accommodations: listAccommodations(tripId),
members: [owner, ...(members || [])].filter(Boolean),
};
-319
View File
@@ -1,319 +0,0 @@
import path from 'path';
import { avatarUrl } from './avatarUrl';
import fs from 'fs';
import type { Request } from 'express';
import { db } from '../db/database';
import { consumeEphemeralToken } from './ephemeralTokens';
import { verifyJwtAndLoadUser } from '../middleware/auth';
import { TripFile } from '../types';
// ---------------------------------------------------------------------------
// Constants
// ---------------------------------------------------------------------------
export const MAX_FILE_SIZE = 50 * 1024 * 1024; // 50 MB
export const DEFAULT_ALLOWED_EXTENSIONS = 'jpg,jpeg,png,gif,webp,heic,pdf,doc,docx,xls,xlsx,txt,csv,pkpass,pkpasses,md,markdown';
// Video support (#823). Gallery/media uploads accept these in addition to images,
// independent of the admin doc-types allowlist. Videos are stored as-is and
// streamed with HTTP Range; the cap is higher than images because phone clips are
// large.
export const VIDEO_EXTENSIONS = ['mp4', 'm4v', 'webm', 'mov'];
export const MAX_VIDEO_SIZE = 500 * 1024 * 1024; // 500 MB
export function isVideoMime(mime: string | undefined | null): boolean {
return !!mime && mime.startsWith('video/');
}
export function isVideoExtension(ext: string): boolean {
return VIDEO_EXTENSIONS.includes(ext.toLowerCase().replace(/^\./, ''));
}
// Single authoritative blocklist for every file-upload surface (main
// file manager + collab attachments). When the admin setting
// `allowed_file_types` is `*`, this list is still enforced so the
// wildcard doesn't silently admit executables/scripts.
export const BLOCKED_EXTENSIONS = [
// Server-rendered / scripted content that could XSS a viewer
'.svg', '.html', '.htm', '.xml', '.xhtml',
// Scripts
'.js', '.jsx', '.ts', '.tsx', '.mjs', '.cjs', '.php', '.py', '.rb', '.pl',
// Executables
'.exe', '.bat', '.sh', '.cmd', '.msi', '.dll', '.com', '.vbs', '.ps1', '.app',
];
export const filesDir = path.join(__dirname, '../../uploads/files');
// ---------------------------------------------------------------------------
// Helpers
// ---------------------------------------------------------------------------
export { verifyTripAccess } from './tripAccess';
export function getAllowedExtensions(): string {
try {
const row = db.prepare("SELECT value FROM app_settings WHERE key = 'allowed_file_types'").get() as { value: string } | undefined;
return row?.value || DEFAULT_ALLOWED_EXTENSIONS;
} catch { return DEFAULT_ALLOWED_EXTENSIONS; }
}
const FILE_SELECT = `
SELECT f.*, r.title as reservation_title, u.username as uploaded_by_name, u.avatar as uploaded_by_avatar
FROM trip_files f
LEFT JOIN reservations r ON f.reservation_id = r.id
LEFT JOIN users u ON f.uploaded_by = u.id
`;
export function formatFile(file: TripFile & { trip_id?: number; uploaded_by_avatar?: string | null }) {
const tripId = file.trip_id;
return {
...file,
url: `/api/trips/${tripId}/files/${file.id}/download`,
uploaded_by_avatar: avatarUrl({ avatar: file.uploaded_by_avatar }),
};
}
// ---------------------------------------------------------------------------
// Trip-scoped link validation
// ---------------------------------------------------------------------------
/**
* A file, and any reservation / day-assignment / place it points at, must all
* live in the same trip. FILE_SELECT and getFileLinks join the reservation and
* return its title, so without this guard a member of trip A could aim a file
* (or a file_link) at trip B's reservation id and read the title back. Returns
* the first field that escapes `tripId`, or null when every supplied id belongs
* to the trip. Absent / null / zero ids are ignored (they clear the link).
*/
export function findForeignLinkTarget(
tripId: string | number,
opts: { reservation_id?: string | number | null; assignment_id?: string | number | null; place_id?: string | number | null }
): 'reservation_id' | 'assignment_id' | 'place_id' | null {
if (opts.reservation_id && !db.prepare('SELECT 1 FROM reservations WHERE id = ? AND trip_id = ?').get(opts.reservation_id, tripId)) {
return 'reservation_id';
}
if (opts.place_id && !db.prepare('SELECT 1 FROM places WHERE id = ? AND trip_id = ?').get(opts.place_id, tripId)) {
return 'place_id';
}
if (opts.assignment_id && !db.prepare('SELECT 1 FROM day_assignments a JOIN days d ON a.day_id = d.id WHERE a.id = ? AND d.trip_id = ?').get(opts.assignment_id, tripId)) {
return 'assignment_id';
}
return null;
}
// ---------------------------------------------------------------------------
// File path resolution & validation
// ---------------------------------------------------------------------------
export function resolveFilePath(filename: string): { resolved: string; safe: boolean } {
const safeName = path.basename(filename);
const filePath = path.join(filesDir, safeName);
const resolved = path.resolve(filePath);
const safe = resolved.startsWith(path.resolve(filesDir));
return { resolved, safe };
}
// ---------------------------------------------------------------------------
// Token-based download auth
// ---------------------------------------------------------------------------
export function authenticateDownload(req: Request): { userId: number } | { error: string; status: number } {
const cookieToken = (req as any).cookies?.trek_session as string | undefined;
const authHeader = req.headers['authorization'];
const bearerToken = authHeader ? (authHeader.split(' ')[1] || undefined) : undefined;
const queryToken = req.query.token as string | undefined;
// Cookie and Bearer both carry a full JWT — try them first (cookie wins).
const jwtToken = cookieToken || bearerToken;
if (jwtToken) {
// Use the shared helper so the password_version gate applies here too;
// previously this bypassed the check and stolen download tokens stayed
// valid across a password reset.
const user = verifyJwtAndLoadUser(jwtToken);
if (!user) return { error: 'Invalid or expired token', status: 401 };
return { userId: user.id };
}
if (queryToken) {
const uid = consumeEphemeralToken(queryToken, 'download');
if (!uid) return { error: 'Invalid or expired token', status: 401 };
return { userId: uid };
}
return { error: 'Authentication required', status: 401 };
}
// ---------------------------------------------------------------------------
// CRUD
// ---------------------------------------------------------------------------
export interface FileLink {
file_id: number;
reservation_id: number | null;
place_id: number | null;
}
export function getFileById(id: string | number, tripId: string | number): TripFile | undefined {
return db.prepare('SELECT * FROM trip_files WHERE id = ? AND trip_id = ?').get(id, tripId) as TripFile | undefined;
}
export function getDeletedFile(id: string | number, tripId: string | number): TripFile | undefined {
return db.prepare('SELECT * FROM trip_files WHERE id = ? AND trip_id = ? AND deleted_at IS NOT NULL').get(id, tripId) as TripFile | undefined;
}
export function listFiles(tripId: string | number, showTrash: boolean) {
const where = showTrash ? 'f.trip_id = ? AND f.deleted_at IS NOT NULL' : 'f.trip_id = ? AND f.deleted_at IS NULL';
const files = db.prepare(`${FILE_SELECT} WHERE ${where} ORDER BY f.starred DESC, f.created_at DESC`).all(tripId) as TripFile[];
const fileIds = files.map(f => f.id);
const linksMap: Record<number, FileLink[]> = {};
if (fileIds.length > 0) {
const placeholders = fileIds.map(() => '?').join(',');
const links = db.prepare(`SELECT file_id, reservation_id, place_id FROM file_links WHERE file_id IN (${placeholders})`).all(...fileIds) as FileLink[];
for (const link of links) {
if (!linksMap[link.file_id]) linksMap[link.file_id] = [];
linksMap[link.file_id].push(link);
}
}
return files.map(f => {
const fileLinks = linksMap[f.id] || [];
return {
...formatFile(f),
linked_reservation_ids: fileLinks.filter(l => l.reservation_id).map(l => l.reservation_id),
linked_place_ids: fileLinks.filter(l => l.place_id).map(l => l.place_id),
};
});
}
export function createFile(
tripId: string | number,
file: { filename: string; originalname: string; size: number; mimetype: string },
uploadedBy: number,
opts: { place_id?: string | null; reservation_id?: string | null; description?: string | null }
) {
const result = db.prepare(`
INSERT INTO trip_files (trip_id, place_id, reservation_id, filename, original_name, file_size, mime_type, description, uploaded_by)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
`).run(
tripId,
opts.place_id || null,
opts.reservation_id || null,
file.filename,
file.originalname,
file.size,
file.mimetype,
opts.description || null,
uploadedBy
);
const created = db.prepare(`${FILE_SELECT} WHERE f.id = ?`).get(result.lastInsertRowid) as TripFile;
return formatFile(created);
}
export function updateFile(
id: string | number,
current: TripFile,
updates: { description?: string; place_id?: string | null; reservation_id?: string | null }
) {
db.prepare(`
UPDATE trip_files SET
description = ?,
place_id = ?,
reservation_id = ?
WHERE id = ?
`).run(
updates.description !== undefined ? updates.description : current.description,
updates.place_id !== undefined ? (updates.place_id || null) : current.place_id,
updates.reservation_id !== undefined ? (updates.reservation_id || null) : current.reservation_id,
id
);
const updated = db.prepare(`${FILE_SELECT} WHERE f.id = ?`).get(id) as TripFile;
return formatFile(updated);
}
export function toggleStarred(id: string | number, currentStarred: number | undefined) {
const newStarred = currentStarred ? 0 : 1;
db.prepare('UPDATE trip_files SET starred = ? WHERE id = ?').run(newStarred, id);
const updated = db.prepare(`${FILE_SELECT} WHERE f.id = ?`).get(id) as TripFile;
return formatFile(updated);
}
export function softDeleteFile(id: string | number) {
db.prepare('UPDATE trip_files SET deleted_at = CURRENT_TIMESTAMP WHERE id = ?').run(id);
}
export function restoreFile(id: string | number) {
db.prepare('UPDATE trip_files SET deleted_at = NULL WHERE id = ?').run(id);
const restored = db.prepare(`${FILE_SELECT} WHERE f.id = ?`).get(id) as TripFile;
return formatFile(restored);
}
export async function permanentDeleteFile(file: TripFile): Promise<void> {
const { resolved } = resolveFilePath(file.filename);
// `force: true` swallows ENOENT, replacing the prior existsSync+unlink
// double-call that blocked the event loop twice per deletion. Only
// drop the DB row when the on-disk unlink either succeeded or the
// file was already gone — otherwise a permission / ENOSPC failure
// would orphan the bytes on disk with no DB pointer left to clean it.
try {
await fs.promises.rm(resolved, { force: true });
} catch (e) {
console.error(`[files] unlink failed for ${file.filename}, keeping DB row:`, e);
throw e;
}
db.prepare('DELETE FROM trip_files WHERE id = ?').run(file.id);
}
export async function emptyTrash(tripId: string | number): Promise<number> {
const trashed = db.prepare('SELECT * FROM trip_files WHERE trip_id = ? AND deleted_at IS NOT NULL').all(tripId) as TripFile[];
// Collect successful IDs separately so we only DELETE rows whose disk
// content was actually removed — failing unlinks keep their DB row
// and a retry via the single-file delete path can try again.
const successfullyUnlinked: number[] = [];
await Promise.all(trashed.map(async (file) => {
const { resolved } = resolveFilePath(file.filename);
try {
await fs.promises.rm(resolved, { force: true });
successfullyUnlinked.push(Number(file.id));
} catch (e) {
console.error(`[files] unlink failed for ${file.filename}, keeping DB row:`, e);
}
}));
if (successfullyUnlinked.length > 0) {
const placeholders = successfullyUnlinked.map(() => '?').join(',');
db.prepare(`DELETE FROM trip_files WHERE id IN (${placeholders})`).run(...successfullyUnlinked);
}
return successfullyUnlinked.length;
}
// ---------------------------------------------------------------------------
// File links (many-to-many)
// ---------------------------------------------------------------------------
export function createFileLink(
fileId: string | number,
opts: { reservation_id?: string | null; assignment_id?: string | null; place_id?: string | null }
) {
try {
db.prepare('INSERT OR IGNORE INTO file_links (file_id, reservation_id, assignment_id, place_id) VALUES (?, ?, ?, ?)').run(
fileId, opts.reservation_id || null, opts.assignment_id || null, opts.place_id || null
);
} catch (err) {
console.error('[Files] Error creating file link:', err instanceof Error ? err.message : err);
}
return db.prepare('SELECT * FROM file_links WHERE file_id = ?').all(fileId);
}
export function deleteFileLink(linkId: string | number, fileId: string | number) {
db.prepare('DELETE FROM file_links WHERE id = ? AND file_id = ?').run(linkId, fileId);
}
export function getFileLinks(fileId: string | number) {
return db.prepare(`
SELECT fl.*, r.title as reservation_title
FROM file_links fl
LEFT JOIN reservations r ON fl.reservation_id = r.id
WHERE fl.file_id = ?
`).all(fileId);
}