From 48e54d5a62f6638ba9a332ce020f763e2e8da2b4 Mon Sep 17 00:00:00 2001 From: Maurice Date: Mon, 23 Nov 2026 15:02:17 +0100 Subject: [PATCH] fix(files): keep booking, place and expense files reachable with Documents off The Documents addon now gates only the file manager: the list leaves out loose files, and the trash, starring and loose files answer 404, while uploads, deletes and every file a booking, place, expense, note or message carries stay reachable over REST, the download route, MCP and the offline bundle. --- .../nest/files/files-download.controller.ts | 10 +- server/src/nest/files/files.controller.ts | 43 +++++--- server/src/nest/files/files.mcp.ts | 44 +++++--- server/src/nest/files/files.service.ts | 25 ++++- .../trip-read-model.service.ts | 9 +- .../e2e/trip-addons-enforcement.e2e.test.ts | 73 ++++++++++--- .../tests/unit/nest/files.controller.test.ts | 103 +++++++++++++----- server/tests/unit/nest/files.service.test.ts | 16 +++ 8 files changed, 240 insertions(+), 83 deletions(-) diff --git a/server/src/nest/files/files-download.controller.ts b/server/src/nest/files/files-download.controller.ts index 9b7084596..f9c38e81b 100644 --- a/server/src/nest/files/files-download.controller.ts +++ b/server/src/nest/files/files-download.controller.ts @@ -19,8 +19,8 @@ import path from 'path'; * 401 token, 404 trip/file, .pkpass served inline for Wallet. Bytes come from * storage.sendToResponse, whose local branch is the root-relative res.sendFile * form this route needs under the ExpressAdapter. A trip that has Documents off - * answers 404 "Documents addon is not enabled" after the trip check, like every - * other files route. + * still serves the files of its bookings, places, expenses, notes and messages, + * and answers 404 "Documents addon is not enabled" for the rest. */ @Public('authenticates itself: the download link carries a short-lived ?token the client mints') @Controller('api/trips/:tripId/files') @@ -45,14 +45,14 @@ export class FilesDownloadController { if (!trip) { throw new HttpException({ error: 'Trip not found' }, 404); } - if (!(await this.addons.isEnabledForTrip(trip.id, ADDON_IDS.DOCUMENTS))) { - throw new HttpException({ error: addonOffMessage(ADDON_IDS.DOCUMENTS) }, 404); - } const file = await this.files.getFileById(id, tripId); if (!file) { throw new HttpException({ error: 'File not found' }, 404); } + if (!(await this.addons.isEnabledForTrip(trip.id, ADDON_IDS.DOCUMENTS)) && !(await this.files.isAttached(file))) { + throw new HttpException({ error: addonOffMessage(ADDON_IDS.DOCUMENTS) }, 404); + } // basename() tolerates a stray prefixed row (legacy rows sometimes stored // a relative path); the storage layer's key validation refuses the rest. diff --git a/server/src/nest/files/files.controller.ts b/server/src/nest/files/files.controller.ts index dbcc476d5..c7680833f 100644 --- a/server/src/nest/files/files.controller.ts +++ b/server/src/nest/files/files.controller.ts @@ -1,4 +1,5 @@ import { ADDON_IDS } from '../../addons'; +import type { TripFileRow } from '../../db/repositories/TripFiles.repository'; import type { TripAccess } from '../../db/repositories/Trips.repository'; import type { User } from '../../types'; import { addonOffMessage } from '../addons/addons.constants'; @@ -122,9 +123,11 @@ export function filesUploadFileFilter(allowedTypes: AllowedFileTypesService): Op // the body has been read costs the bandwidth but keeps the answer readable, which is // the behaviour every client already handles. // -// Documents is a trip addon: a trip it is off for answers 404 "Documents addon is -// not enabled" on every route, after the trip check, with TripAddonGuard beside -// TripAccessGuard and inline in the upload. The files themselves stay. +// Documents is a trip addon, and it is the file manager: while a trip has it off, +// the list leaves out the files only the manager shows, and the trash, starring +// and any route on such a file answer 404 "Documents addon is not enabled". A file +// that belongs to a booking, place, expense, note or message stays reachable, and +// uploads and deletes stay open so those features can attach and roll back. @UseGuards(JwtAuthGuard) @RequireAddon(ADDON_IDS.DOCUMENTS, 'Documents') export class FilesController { @@ -152,7 +155,14 @@ export class FilesController { } } - @UseGuards(TripAccessGuard, TripAddonGuard) + /** 404 for a file only the file manager shows, while the trip has Documents off. */ + private async assertReachable(trip: TripAccess, file: TripFileRow) { + if (await this.addons.isEnabledForTrip(trip.id, ADDON_IDS.DOCUMENTS)) return; + if (await this.files.isAttached(file)) return; + throw new HttpException({ error: addonOffMessage(ADDON_IDS.DOCUMENTS) }, 404); + } + + @UseGuards(TripAccessGuard) @Get() @ResponseContract(tripFilesResponseSchema) async list( @@ -161,7 +171,11 @@ export class FilesController { @Param('tripId') tripId: string, @Query('trash') trash?: string, ) { - return { files: await this.files.listFiles(tripId, trash === 'true') }; + const documentsOn = await this.addons.isEnabledForTrip(trip.id, ADDON_IDS.DOCUMENTS); + if (!documentsOn && trash === 'true') { + throw new HttpException({ error: addonOffMessage(ADDON_IDS.DOCUMENTS) }, 404); + } + return { files: await this.files.listFiles(tripId, trash === 'true', !documentsOn) }; } @Post() @@ -191,9 +205,6 @@ export class FilesController { if (!trip) { throw new HttpException({ error: 'Trip not found' }, 404); } - if (!(await this.addons.isEnabledForTrip(trip.id, ADDON_IDS.DOCUMENTS))) { - throw new HttpException({ error: addonOffMessage(ADDON_IDS.DOCUMENTS) }, 404); - } // Inline rather than DemoWriteGuard: the 404 above has to come first, so a demo // user still cannot learn which trips exist. if (isDemoWriteBlocked(this.env, user.email)) { @@ -245,7 +256,7 @@ export class FilesController { return { file: created }; } - @UseGuards(TripAccessGuard, TripAddonGuard) + @UseGuards(TripAccessGuard) @Put(':id') @ResponseContract(tripFileResponseSchema) async update( @@ -263,6 +274,7 @@ export class FilesController { if (!file) { throw new HttpException({ error: 'File not found' }, 404); } + await this.assertReachable(trip, file); await this.assertLinkTargets(tripId, { reservation_id: body.reservation_id, place_id: body.place_id, @@ -311,7 +323,7 @@ export class FilesController { return { success: true, deleted }; } - @UseGuards(TripAccessGuard, TripAddonGuard) + @UseGuards(TripAccessGuard) @Delete(':id/permanent') @ResponseContract(successResponseSchema) async permanent( @@ -333,7 +345,7 @@ export class FilesController { return { success: true }; } - @UseGuards(TripAccessGuard, TripAddonGuard) + @UseGuards(TripAccessGuard) @Delete(':id') @ResponseContract(successResponseSchema) async remove( @@ -378,7 +390,7 @@ export class FilesController { return { file: restored }; } - @UseGuards(TripAccessGuard, TripAddonGuard) + @UseGuards(TripAccessGuard) @Post(':id/link') @HttpCode(200) // Express answers link with res.json (200). @ResponseContract(fileLinkCreateResponseSchema) @@ -397,6 +409,7 @@ export class FilesController { if (!file) { throw new HttpException({ error: 'File not found' }, 404); } + await this.assertReachable(trip, file); await this.assertLinkTargets(tripId, { reservation_id: body.reservation_id, assignment_id: body.assignment_id, @@ -416,7 +429,7 @@ export class FilesController { return { success: true, links }; } - @UseGuards(TripAccessGuard, TripAddonGuard) + @UseGuards(TripAccessGuard) @Delete(':id/link/:linkId') @ResponseContract(successResponseSchema) async unlink( @@ -437,11 +450,12 @@ export class FilesController { if (!file) { throw new HttpException({ error: 'File not found' }, 404); } + await this.assertReachable(trip, file); await this.files.unlinkFile(id, linkId, this.files.restWriter(tripId, user, socketId)); return { success: true }; } - @UseGuards(TripAccessGuard, TripAddonGuard) + @UseGuards(TripAccessGuard) @Get(':id/links') @ResponseContract(fileLinksResponseSchema) async links( @@ -454,6 +468,7 @@ export class FilesController { if (!file) { throw new HttpException({ error: 'File not found' }, 404); } + await this.assertReachable(trip, file); return { links: await this.files.getFileLinks(id) }; } } diff --git a/server/src/nest/files/files.mcp.ts b/server/src/nest/files/files.mcp.ts index 8365f87df..a53c8e807 100644 --- a/server/src/nest/files/files.mcp.ts +++ b/server/src/nest/files/files.mcp.ts @@ -1,4 +1,5 @@ import { ADDON_IDS } from '../../addons'; +import type { TripFileRow } from '../../db/repositories/TripFiles.repository'; import { noAccess, permissionDenied } from '../../mcp/tools/_shared'; import { McpController, @@ -10,7 +11,7 @@ import { errorResult, ok, } from '../../nest-mcp'; -import { addonGate } from '../addons/addon-gate'; +import { addonOffMessage } from '../addons/addons.constants'; import { AddonsService } from '../addons/addons.service'; import { McpToolGuardsService } from '../mcp-shared/mcp-tool-guards.service'; import { contentTypeFor } from '../storage/content-type'; @@ -24,12 +25,6 @@ import { z } from 'zod'; const CONTENT_MAX_MB = Math.round(FILE_CONTENT_MAX / (1024 * 1024)); -/** - * The trip file manager is the Documents addon: its tools are offered while it is on for the - * instance or a trip of the caller, and each call needs it on for the trip it names (the host's - * tool gate), as every files route answers 404 "Documents addon is not enabled" otherwise. - */ -const documentsAddonOn = addonGate(ADDON_IDS.DOCUMENTS); /** * The upload tool's cap: the same 10 MB a read hands back, or the operator's * upload limit when that is lower. The bytes travel base64 inside one JSON-RPC @@ -72,6 +67,11 @@ function contentRefusal(err: FileContentError): string { * transport. It is policed like the multipart route: the same extension rules * through isUploadTypeAllowed, the file_upload right, the demo block and the * same-trip check on what it attaches to, plus a tighter size cap. + * + * The Documents addon is the file manager, gated as the REST routes gate it: while + * the trip has it off, the list leaves out the files only the manager shows, the + * trash is refused, and so is any tool on such a file. A file that belongs to a + * booking, place, expense, note or message stays reachable, and the upload stays open. */ @McpController() export class FilesMcp { @@ -82,6 +82,10 @@ export class FilesMcp { readonly addons: AddonsService, ) {} + private async reachable(tripId: number, file: TripFileRow): Promise { + return (await this.addons.isEnabledForTrip(tripId, ADDON_IDS.DOCUMENTS)) || (await this.files.isAttached(file)); + } + @Tool({ name: 'list_trip_files', description: @@ -92,11 +96,12 @@ export class FilesMcp { }, annotations: TOOL_ANNOTATIONS_READONLY, access: { group: 'files', mode: 'read' }, - when: documentsAddonOn, }) async listTripFiles({ tripId, trash }: { tripId: number; trash?: boolean }, ctx: McpContext) { if (!(await this.files.verifyTripAccess(tripId, ctx.userId))) return noAccess(); - return ok({ files: await this.files.listFiles(tripId, trash === true) }); + const documentsOn = await this.addons.isEnabledForTrip(tripId, ADDON_IDS.DOCUMENTS); + if (!documentsOn && trash === true) return errorResult(addonOffMessage(ADDON_IDS.DOCUMENTS)); + return ok({ files: await this.files.listFiles(tripId, trash === true, !documentsOn) }); } @Tool({ @@ -111,10 +116,11 @@ export class FilesMcp { // passport scan are different privileges, and the plugin host draws the same // line (db:read:files vs db:read:files:content). access: { group: 'files', mode: 'content' }, - when: documentsAddonOn, }) async readTripFile({ tripId, fileId }: { tripId: number; fileId: number }, ctx: McpContext) { if (!(await this.files.verifyTripAccess(tripId, ctx.userId))) return noAccess(); + const file = await this.files.getFileById(fileId, tripId); + if (file && !(await this.reachable(tripId, file))) return errorResult(addonOffMessage(ADDON_IDS.DOCUMENTS)); try { const { name, mimetype, bytes } = await this.files.readContent(tripId, fileId); const asText = isTextual(mimetype); @@ -156,7 +162,6 @@ export class FilesMcp { }, annotations: TOOL_ANNOTATIONS_WRITE, access: { group: 'files', mode: 'write' }, - when: documentsAddonOn, }) async uploadTripFile( { @@ -223,7 +228,6 @@ export class FilesMcp { }, annotations: TOOL_ANNOTATIONS_WRITE, access: { group: 'files', mode: 'write' }, - when: documentsAddonOn, }) async updateTripFile( { tripId, fileId, ...fields }: { tripId: number; fileId: number } & FileUpdateRequest, @@ -233,6 +237,7 @@ export class FilesMcp { if (!(await this.guards.hasTripPermission('file_edit', tripId, ctx.userId))) return permissionDenied(); const current = await this.files.getFileById(fileId, tripId); if (!current) return errorResult('File not found.'); + if (!(await this.reachable(tripId, current))) return errorResult(addonOffMessage(ADDON_IDS.DOCUMENTS)); // Same enforcement as the REST route's assertLinkTargets, through the same // service method: a foreign reservation id would otherwise come back with its // title attached the next time this file is listed. @@ -266,7 +271,6 @@ export class FilesMcp { }, annotations: TOOL_ANNOTATIONS_WRITE, access: { group: 'files', mode: 'write' }, - when: documentsAddonOn, }) async linkTripFile( { tripId, fileId, ...targets }: { tripId: number; fileId: number } & FileLinkRequest, @@ -274,7 +278,9 @@ export class FilesMcp { ) { if (!(await this.files.verifyTripAccess(tripId, ctx.userId))) return noAccess(); if (!(await this.guards.hasTripPermission('file_edit', tripId, ctx.userId))) return permissionDenied(); - if (!(await this.files.getFileById(fileId, tripId))) return errorResult('File not found.'); + const file = await this.files.getFileById(fileId, tripId); + if (!file) return errorResult('File not found.'); + if (!(await this.reachable(tripId, file))) return errorResult(addonOffMessage(ADDON_IDS.DOCUMENTS)); // The REST body allows all three to be absent and stores a link row pointing at // nothing. A tool caller that gets here with no target made a mistake, and saying // so is more useful than a success that attached the file to nothing. @@ -298,7 +304,6 @@ export class FilesMcp { }, annotations: TOOL_ANNOTATIONS_DELETE, access: { group: 'files', mode: 'write' }, - when: documentsAddonOn, }) async unlinkTripFile( { tripId, fileId, linkId }: { tripId: number; fileId: number; linkId: number }, @@ -309,7 +314,9 @@ export class FilesMcp { // deleteFileLink scopes by (linkId, fileId) only, so the file has to be resolved // against :tripId first, exactly as the REST route does it. Otherwise a member of // any trip could drop a link row belonging to a foreign trip's file. - if (!(await this.files.getFileById(fileId, tripId))) return errorResult('File not found.'); + const file = await this.files.getFileById(fileId, tripId); + if (!file) return errorResult('File not found.'); + if (!(await this.reachable(tripId, file))) return errorResult(addonOffMessage(ADDON_IDS.DOCUMENTS)); await this.files.unlinkFile(fileId, linkId, await this.guards.tripWriter(tripId, ctx.userId)); return ok({ success: true }); } @@ -324,11 +331,12 @@ export class FilesMcp { }, annotations: TOOL_ANNOTATIONS_READONLY, access: { group: 'files', mode: 'read' }, - when: documentsAddonOn, }) async listTripFileLinks({ tripId, fileId }: { tripId: number; fileId: number }, ctx: McpContext) { if (!(await this.files.verifyTripAccess(tripId, ctx.userId))) return noAccess(); - if (!(await this.files.getFileById(fileId, tripId))) return errorResult('File not found.'); + const file = await this.files.getFileById(fileId, tripId); + if (!file) return errorResult('File not found.'); + if (!(await this.reachable(tripId, file))) return errorResult(addonOffMessage(ADDON_IDS.DOCUMENTS)); return ok({ links: await this.files.getFileLinks(fileId) }); } } diff --git a/server/src/nest/files/files.service.ts b/server/src/nest/files/files.service.ts index 4b9439d6f..ef1e0a08e 100644 --- a/server/src/nest/files/files.service.ts +++ b/server/src/nest/files/files.service.ts @@ -61,6 +61,16 @@ function withLinkedIds(file: TripFileJoinRow, fileLinks: FileLinkTargetRow[]) { }; } +/** + * Whether a file belongs to something besides the Documents file manager: a + * booking, place, expense, collab note or chat message. Such a file stays + * reachable while a trip has Documents off. + */ +function isAttachedFile(file: TripFileRow, fileLinks: FileLinkTargetRow[]): boolean { + if (file.reservation_id || file.place_id || file.note_id || file.message_id) return true; + return fileLinks.some((l) => l.reservation_id || l.assignment_id || l.place_id || l.budget_item_id); +} + export interface FileLink { file_id: number; reservation_id: number | null; @@ -349,11 +359,17 @@ export class FilesService { }; } - async listFiles(tripId: string | number, showTrash: boolean) { - const tripIdNum = toRowId(tripId) ?? -1; - const files = await this.tripFilesRepo.listForTrip(tripIdNum, showTrash); + /** Whether the file belongs to a booking, place, expense, note or message rather than to the file manager alone. */ + async isAttached(file: TripFileRow): Promise { + return isAttachedFile(file, await this.fileLinksRepo.listForFiles([file.id])); + } - const fileIds = files.map((f) => f.id); + /** `attachedOnly` leaves out the files only the file manager shows, for a trip that has Documents off. */ + async listFiles(tripId: string | number, showTrash: boolean, attachedOnly = false) { + const tripIdNum = toRowId(tripId) ?? -1; + const all = await this.tripFilesRepo.listForTrip(tripIdNum, showTrash); + + const fileIds = all.map((f) => f.id); const links = await this.fileLinksRepo.listForFiles(fileIds); const linksMap: Record = {}; for (const link of links) { @@ -361,6 +377,7 @@ export class FilesService { linksMap[link.file_id].push(link); } + const files = attachedOnly ? all.filter((f) => isAttachedFile(f, linksMap[f.id] || [])) : all; return files.map((f) => withLinkedIds(f, linksMap[f.id] || [])); } diff --git a/server/src/nest/trip-read-model/trip-read-model.service.ts b/server/src/nest/trip-read-model/trip-read-model.service.ts index 9b3773d75..cf80e0d00 100644 --- a/server/src/nest/trip-read-model/trip-read-model.service.ts +++ b/server/src/nest/trip-read-model/trip-read-model.service.ts @@ -106,9 +106,10 @@ export class TripReadModelService { * Aggregates every trip sub-collection for offline caching (legacy /:id/bundle). * * A section whose addon is off for this trip (Lists for packing and todos, - * Costs, Documents) goes out as an empty list rather than being left out, so - * a client that replaces its cache from the bundle drops what it may no - * longer show, and one that expects every key still finds it. + * Costs) goes out as an empty list rather than being left out, so a client + * that replaces its cache from the bundle drops what it may no longer show, + * and one that expects every key still finds it. With Documents off the files + * keep the ones a booking, place, expense, note or message carries. */ async bundle(tripId: string, trip: { id: number; user_id: number }, viewerId: number) { const { days } = await this.days.list(tripId); @@ -125,7 +126,7 @@ export class TripReadModelService { todoItems: packingOn ? await this.todo.listItems(tripId) : [], budgetItems: (await on(ADDON_IDS.BUDGET)) ? await this.budget.listBudgetItems(tripId) : [], reservations: await this.reservations.list(tripId), - files: (await on(ADDON_IDS.DOCUMENTS)) ? await this.files.listFiles(tripId, false) : [], + files: await this.files.listFiles(tripId, false, !(await on(ADDON_IDS.DOCUMENTS))), accommodations: await this.accommodations.list(tripId), members: [owner, ...(members || [])].filter(Boolean), }; diff --git a/server/tests/e2e/trip-addons-enforcement.e2e.test.ts b/server/tests/e2e/trip-addons-enforcement.e2e.test.ts index 16358f74e..105dc6f2d 100644 --- a/server/tests/e2e/trip-addons-enforcement.e2e.test.ts +++ b/server/tests/e2e/trip-addons-enforcement.e2e.test.ts @@ -7,7 +7,9 @@ * trip switched it on (allowed), and the instance has it on and the trip * switched it off (refused with `