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.
This commit is contained in:
Maurice
2026-11-23 15:02:17 +01:00
parent d83841f53b
commit 48e54d5a62
8 changed files with 240 additions and 83 deletions
@@ -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.
+29 -14
View File
@@ -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) };
}
}
+26 -18
View File
@@ -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<boolean> {
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) });
}
}
+21 -4
View File
@@ -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<boolean> {
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<number, FileLinkTargetRow[]> = {};
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] || []));
}
@@ -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),
};