The most complete open-source travel planner: real-time collaboration, bookings, budgets, packing lists, journals, offline PWA, SSO and an AI-ready MCP server, with planet-wide place search and routing built in.
TypeScript budget-trackercollaborativedockeritinerarymcp-serveroffline-firstopen-sourceopenstreetmappacking-listpwareal-timeself-hostedselfhostedtraveltravel-apptravel-journaltravel-plannertripitwanderlog
fix(files): attach a loose file while the trip has Documents off
Mauricea0d66eb89896
diff --git a/server/src/nest/files/files.controller.ts b/server/src/nest/files/files.controller.tsindex c7680833f..a8aaf5917 100644--- a/server/src/nest/files/files.controller.ts+++ b/server/src/nest/files/files.controller.ts@@ -18,7 +18,7 @@ import { StorageService } from '../storage/storage.service';import { AllowedFileTypesService } from './allowed-file-types.service';import { MAX_FILE_SIZE, BLOCKED_EXTENSIONS, isUploadTypeAllowed, isVideoExtension } from './files.constants';import { FileUploadDto, FileUpdateDto, FileLinkDto } from './files.dto';-import { FilesService } from './files.service';+import { FilesService, attachesFile } from './files.service';import {Body,Controller,@@ -155,8 +155,9 @@ export class FilesController {}}- /** 404 for a file only the file manager shows, while the trip has Documents off. */- private async assertReachable(trip: TripAccess, file: TripFileRow) {+ /** 404 for a file only the file manager shows, while the trip has Documents off and the request does not attach it. */+ private async assertReachable(trip: TripAccess, file: TripFileRow, targets: Parameters<typeof attachesFile>[0] = {}) {+ if (attachesFile(targets)) return;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);@@ -274,7 +275,7 @@ export class FilesController {if (!file) {throw new HttpException({ error: 'File not found' }, 404);}- await this.assertReachable(trip, file);+ await this.assertReachable(trip, file, body);await this.assertLinkTargets(tripId, {reservation_id: body.reservation_id,place_id: body.place_id,@@ -409,7 +410,7 @@ export class FilesController {if (!file) {throw new HttpException({ error: 'File not found' }, 404);}- await this.assertReachable(trip, file);+ await this.assertReachable(trip, file, body);await this.assertLinkTargets(tripId, {reservation_id: body.reservation_id,assignment_id: body.assignment_id,diff --git a/server/src/nest/files/files.mcp.ts b/server/src/nest/files/files.mcp.tsindex a53c8e807..19e80c587 100644--- a/server/src/nest/files/files.mcp.ts+++ b/server/src/nest/files/files.mcp.ts@@ -17,7 +17,7 @@ import { McpToolGuardsService } from '../mcp-shared/mcp-tool-guards.service';import { contentTypeFor } from '../storage/content-type';import { AllowedFileTypesService } from './allowed-file-types.service';import { MAX_FILE_SIZE, isUploadTypeAllowed } from './files.constants';-import { FilesService, FileContentError, FILE_CONTENT_MAX } from './files.service';+import { FilesService, FileContentError, FILE_CONTENT_MAX, attachesFile } from './files.service';import { idSchema, fileLinkRequestSchema, fileUpdateRequestSchema } from '@trek/shared';import type { FileLinkRequest, FileUpdateRequest } from '@trek/shared';@@ -70,8 +70,9 @@ function contentRefusal(err: FileContentError): string {** 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.+ * trash is refused, and so is any tool on such a file unless the call itself attaches+ * it. A file that belongs to a booking, place, expense, note or message stays+ * reachable, and the upload stays open.*/@McpController()export class FilesMcp {@@ -82,7 +83,8 @@ export class FilesMcp {readonly addons: AddonsService,) {}- private async reachable(tripId: number, file: TripFileRow): Promise<boolean> {+ private async reachable(tripId: number, file: TripFileRow, targets: FileLinkRequest = {}): Promise<boolean> {+ if (attachesFile(targets)) return true;return (await this.addons.isEnabledForTrip(tripId, ADDON_IDS.DOCUMENTS)) || (await this.files.isAttached(file));}@@ -142,7 +144,7 @@ export class FilesMcp {@Tool({name: 'upload_trip_file',- description: `Add a document to a trip, e.g. a booking confirmation PDF or a ticket, and optionally attach it to a booking or a place in the same call. Pass the bytes base64-encoded in content, up to ${UPLOAD_MAX_MB} MB decoded. The file name has to carry an extension the trip's file manager accepts; the type is derived from it. Returns the new file, whose ID works with read_trip_file and link_trip_file.`,+ description: `Add a document to a trip, e.g. a booking confirmation PDF or a ticket, and optionally attach it to a booking, a place or an expense in the same call. Pass the bytes base64-encoded in content, up to ${UPLOAD_MAX_MB} MB decoded. The file name has to carry an extension the trip's file manager accepts; the type is derived from it. Returns the new file, whose ID works with read_trip_file and link_trip_file.`,inputSchema: {tripId: idSchema,filename: z@@ -159,6 +161,7 @@ export class FilesMcp {description: z.string().max(1000).optional().describe('Free-text description'),reservation_id: idSchema.optional().describe('Booking on the same trip to attach the file to'),place_id: idSchema.optional().describe('Place on the same trip to attach the file to'),+ budget_item_id: idSchema.optional().describe('Expense on the same trip to attach the file to (a receipt)'),},annotations: TOOL_ANNOTATIONS_WRITE,access: { group: 'files', mode: 'write' },@@ -171,6 +174,7 @@ export class FilesMcp {description,reservation_id,place_id,+ budget_item_id,}: {tripId: number;filename: string;@@ -178,6 +182,7 @@ export class FilesMcp {description?: string;reservation_id?: number;place_id?: number;+ budget_item_id?: number;},ctx: McpContext,) {@@ -195,11 +200,12 @@ export class FilesMcp {if (bytes.length === 0) return errorResult('The file is empty.');if (bytes.length > UPLOAD_MAX)return errorResult(`File is too large (over ${UPLOAD_MAX_MB} MB). Ask the user to upload it in TREK instead.`);- const foreign = await this.files.findForeignLinkTarget(tripId, { reservation_id, place_id });+ const foreign = await this.files.findForeignLinkTarget(tripId, { reservation_id, place_id, budget_item_id });if (foreign) return errorResult(`Linked item does not belong to this trip (${foreign}).`);const file = await this.files.createFileFromBytes(tripId, { originalname, mimetype, bytes }, ctx.userId, {reservation_id: reservation_id ?? null,place_id: place_id ?? null,+ budget_item_id: budget_item_id ?? null,description: description ?? null,});this.guards.safeBroadcast(tripId, 'file:created', { file });@@ -237,7 +243,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));+ if (!(await this.reachable(tripId, current, fields))) 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.@@ -280,7 +286,7 @@ export class FilesMcp {if (!(await this.guards.hasTripPermission('file_edit', tripId, ctx.userId))) return permissionDenied();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));+ if (!(await this.reachable(tripId, file, targets))) 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.diff --git a/server/src/nest/files/files.service.ts b/server/src/nest/files/files.service.tsindex ef1e0a08e..ea983bb9f 100644--- a/server/src/nest/files/files.service.ts+++ b/server/src/nest/files/files.service.ts@@ -71,6 +71,22 @@ function isAttachedFile(file: TripFileRow, fileLinks: FileLinkTargetRow[]): boolreturn fileLinks.some((l) => l.reservation_id || l.assignment_id || l.place_id || l.budget_item_id);}+/**+ * Whether a write names a booking, place, stop or expense to attach the file to.+ * Such a write makes a loose file one that belongs somewhere, so it goes through+ * while the trip has Documents off.+ */+export function attachesFile(targets: {+ reservation_id?: string | number | null;+ assignment_id?: string | number | null;+ place_id?: string | number | null;+ budget_item_id?: string | number | null;+}): boolean {+ return [targets.reservation_id, targets.assignment_id, targets.place_id, targets.budget_item_id].some(+ (id) => coerceLinkId(id) !== null,+ );+}+export interface FileLink {file_id: number;reservation_id: number | null;@@ -426,7 +442,12 @@ export class FilesService {tripId: string | number,upload: { originalname: string; mimetype: string; bytes: Buffer },uploadedBy: number,- opts: { place_id?: number | null; reservation_id?: number | null; description?: string | null },+ opts: {+ place_id?: number | null;+ reservation_id?: number | null;+ budget_item_id?: number | null;+ description?: string | null;+ },) {const filename = await this.storeBytes(upload);return this.createFile(diff --git a/server/tests/unit/mcp/tools-files.test.ts b/server/tests/unit/mcp/tools-files.test.tsindex 7733cfab6..332c094b3 100644--- a/server/tests/unit/mcp/tools-files.test.ts+++ b/server/tests/unit/mcp/tools-files.test.ts@@ -16,12 +16,13 @@ import { FilesModule } from '../../../src/nest/files/files.module';import { FILE_CONTENT_MAX } from '../../../src/nest/files/files.service';import { invalidatePermissionsCache } from '../../../src/nest/permissions/permissions-cache';import { StorageService } from '../../../src/nest/storage/storage.service';+import { makeBudgetItem } from '../../helpers/factories/budget';import { linkFile, makeTripFile } from '../../helpers/factories/files';import { makeDayAssignment } from '../../helpers/factories/itinerary';import { makePlace } from '../../helpers/factories/places';import { makeReservation } from '../../helpers/factories/reservations';import { countRows, findRow, findRows, updateRows } from '../../helpers/factories/rows';-import { setAppSetting } from '../../helpers/factories/settings';+import { setAppSetting, setTripAddon } from '../../helpers/factories/settings';import { addTripMember, makeDay, makeTrip } from '../../helpers/factories/trips';import { makeUser } from '../../helpers/factories/users';import { FakeRealtimeService } from '../../helpers/fake-realtime';@@ -676,6 +677,68 @@ describe('Tool: upload_trip_file', () => {expect(await countRows(orm, TripFiles)).toBe(0);});+ it('attaches a receipt to an expense in the upload itself', async () => {+ const { user } = await makeUser(orm);+ const trip = await makeTrip(orm, user.id);+ const expense = await makeBudgetItem(orm, trip.id);+ const foreignExpense = await makeBudgetItem(orm, (await makeTrip(orm, user.id)).id);+ await withHarness(user.id, async (h) => {+ const data = parseToolResult(+ await h.client.callTool({+ name: 'upload_trip_file',+ arguments: { tripId: trip.id, filename: 'receipt.pdf', content: pdf, budget_item_id: expense.id },+ }),+ ) as any;+ expect((await linkRows(data.file.id)).map((l) => l.budget_item_id)).toEqual([expense.id]);+ const foreign = await h.client.callTool({+ name: 'upload_trip_file',+ arguments: { tripId: trip.id, filename: 'receipt.pdf', content: pdf, budget_item_id: foreignExpense.id },+ });+ expect(JSON.stringify(foreign.content)).toContain('does not belong to this trip (budget_item_id)');+ });+ expect(await countRows(orm, TripFiles)).toBe(1);+ });++ it('with Documents off, a loose upload can still be attached by the next call, and nothing else', async () => {+ const { user } = await makeUser(orm);+ const trip = await makeTrip(orm, user.id);+ const expense = await makeBudgetItem(orm, trip.id);+ const booking = await makeReservation(orm, trip.id);+ await setTripAddon(orm, trip.id, 'documents', false);+ await withHarness(user.id, async (h) => {+ const upload = async () =>+ (+ parseToolResult(+ await h.client.callTool({+ name: 'upload_trip_file',+ arguments: { tripId: trip.id, filename: 'ticket.pdf', content: pdf },+ }),+ ) as any+ ).file.id as number;+ const receipt = await upload();+ const refused = await h.client.callTool({+ name: 'update_trip_file',+ arguments: { tripId: trip.id, fileId: receipt, description: 'Lunch' },+ });+ expect(JSON.stringify(refused.content)).toContain('Documents addon is not enabled');+ const updated = await h.client.callTool({+ name: 'update_trip_file',+ arguments: { tripId: trip.id, fileId: receipt, budget_item_id: expense.id },+ });+ expect(updated.isError).toBeFalsy();+ expect((await linkRows(receipt)).map((l) => l.budget_item_id)).toEqual([expense.id]);++ const ticket = await upload();+ const linked = await h.client.callTool({+ name: 'link_trip_file',+ arguments: { tripId: trip.id, fileId: ticket, reservation_id: booking.id },+ });+ expect(linked.isError).toBeFalsy();+ const read = await h.client.callTool({ name: 'read_trip_file', arguments: { tripId: trip.id, fileId: ticket } });+ expect(read.isError).toBeFalsy();+ });+ });+it('refuses a member once file_upload is owner-only', async () => {const { user: owner } = await makeUser(orm);const { user: member } = await makeUser(orm);diff --git a/server/tests/unit/nest/files.controller.test.ts b/server/tests/unit/nest/files.controller.test.tsindex c3f6cebcf..4e08e1438 100644--- a/server/tests/unit/nest/files.controller.test.ts+++ b/server/tests/unit/nest/files.controller.test.ts@@ -140,6 +140,24 @@ describe('FilesController (parity with the legacy /api/trips/:tripId/files routeexpect(await fc(attached, addonsOff).links(user, trip, '5', '9')).toEqual({ links: [{ id: 3 }] });});+ it('while Documents is off, a write that attaches a loose file goes through', async () => {+ const svc = fsvc({+ getFileById: vi.fn().mockReturnValue({ id: 9 }),+ isAttached: vi.fn().mockResolvedValue(false),+ updateFile: vi.fn().mockReturnValue({ id: 9 }),+ linkFile: vi.fn().mockReturnValue([{ id: 3 }]),+ restWriter: vi.fn(),+ } as Partial<FilesService>);+ expect(await fc(svc, addonsOff).update(user, trip, '5', '9', { budget_item_id: 7 })).toEqual({ file: { id: 9 } });+ expect(await fc(svc, addonsOff).link(user, trip, '5', '9', { reservation_id: 4 })).toEqual({+ success: true,+ links: [{ id: 3 }],+ });+ expect(+ await rejected(fc(svc, addonsOff).update(user, trip, '5', '9', { description: 'x', place_id: null })),+ ).toEqual({ status: 404, body: { error: 'Documents addon is not enabled' } });+ });+describe('POST / (upload)', () => {it('404 without trip access — upload keeps its own check so the body is read first', async () => {// The guard would answer before multer, and a response sent mid-upload destroysdiff --git a/wiki/Documents-and-Files.md b/wiki/Documents-and-Files.mdindex 94f71111a..e061d5fb6 100644--- a/wiki/Documents-and-Files.md+++ b/wiki/Documents-and-Files.md@@ -34,7 +34,7 @@ Files also reach this tab from elsewhere: **Attach file** in a booking or transpThe in-app AI assistant can keep a file you attach to the chat in Files (**Keep it in Files**), alone or together with a booking (**Keep the file with this booking**) or an expense.-An AI assistant connected through MCP can add files too: the `upload_trip_file` tool uploads a document to a trip (and can attach it to a booking or a place in the same call) under the same type rules and the `file_upload` permission as the upload area, up to 10 MB per file (or the upload limit, if that is lower). See [MCP-Tools-and-Resources](MCP-Tools-and-Resources).+An AI assistant connected through MCP can add files too: the `upload_trip_file` tool uploads a document to a trip (and can attach it to a booking, a place or an expense in the same call) under the same type rules and the `file_upload` permission as the upload area, up to 10 MB per file (or the upload limit, if that is lower). See [MCP-Tools-and-Resources](MCP-Tools-and-Resources).## Browsing and filteringdiff --git a/wiki/MCP-Tools-and-Resources.md b/wiki/MCP-Tools-and-Resources.mdindex f496e4d3a..9172ff876 100644--- a/wiki/MCP-Tools-and-Resources.md+++ b/wiki/MCP-Tools-and-Resources.md@@ -229,7 +229,7 @@ Requires `files:read` or `files:write`. Reading what is inside a document needs|---|---|| `list_trip_files` | List a trip's documents: name, type, size, uploader, description, what they are linked to, starred and trash state. Pass `trash` to list the trash instead. || `read_trip_file` | Read one document's contents. Text comes back as text, anything else base64, with an `encoding` field saying which. Files over 10 MB are refused; use the download link in the app. |-| `upload_trip_file` | Add a document to a trip, base64-encoded, up to 10 MB (or the instance's upload limit if lower). The name needs an extension the file manager accepts. Optionally attach it to a booking or place right away. Needs the file upload right. |+| `upload_trip_file` | Add a document to a trip, base64-encoded, up to 10 MB (or the instance's upload limit if lower). The name needs an extension the file manager accepts. Optionally attach it to a booking, place or expense right away. Needs the file upload right. || `update_trip_file` | Set a file's description and the booking, place or expense (`budget_item_id`, a receipt) it belongs to. Pass null to detach. || `link_trip_file` | Link a file to one more booking, place, day assignment or expense (`budget_item_id`, a receipt). || `unlink_trip_file` | Remove one link. The file stays. |