Files
TREK/server/src/nest/files/files-download.controller.ts
T
Maurice 3f38621024 feat(server): let a trip owner switch trip addons for one trip
A trip can now turn a trip addon (lists, costs, documents, collab, road
trip, tours) on or off for itself, whatever the instance switch says. No
row in the new trip_addon_overrides table means the trip follows the
instance; a row is the owner's choice. Going back to the instance setting
deletes the row, and no addon data is touched either way.

- GET/PUT /api/trips/:tripId/addons[/:addonId] (every member reads, the
  owner writes) and the MCP tools get_trip_addons and set_trip_addon, on
  the shared tripAddons contract; tripAddons:changed tells the members.
- Every trip-scoped addon surface asks the trip: REST through
  TripAddonGuard, MCP through a per-call gate on the named or pinned trip,
  plugin RPC and events, the share link, the offline bundle, reminders,
  doc sync, the assistant (tools, keep_attached_file), booking costs, the
  trip summary prompt, and the cross-trip tour reads (library, Atlas
  stats, collection save).
- Routes without a trip open while the addon is on in any of the user's
  trips. Switching an addon on that the instance has off ends the members'
  MCP sessions so they reconnect with its tools.
- A copied trip takes its owner's choices along.

Behaviour changes: an anonymous call to an addon route that is off now
gets 401 instead of 404, and with an instance switch off the packing,
todo and files plugin RPC methods, the files MCP tools, todo reminder
mails, core plugin events, plugin view contributions, the share link's
lists, costs and chat sections and the offline bundle's lists follow it.
2026-11-21 13:23:09 +01:00

88 lines
3.5 KiB
TypeScript

import { ADDON_IDS } from '../../addons';
import { addonOffMessage } from '../addons/addons.constants';
import { AddonsService } from '../addons/addons.service';
import { Public } from '../auth-core/public.decorator';
import { contentDisposition } from '../common/content-disposition';
import { StorageService } from '../storage/storage.service';
import { FilesService } from './files.service';
import { Controller, Get, HttpException, Param, Req, Res } from '@nestjs/common';
import type { Request, Response } from 'express';
import path from 'path';
/**
* GET /api/trips/:tripId/files/:id/download — authenticated file download.
*
* Deliberately NOT behind the JwtAuthGuard: it accepts a cookie, a Bearer header
* OR a one-shot `?token=` query param (so links can be opened directly), all via
* the legacy authenticateDownload helper. Byte-identical to the legacy route:
* 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.
*/
@Public('authenticates itself: the download link carries a short-lived ?token the client mints')
@Controller('api/trips/:tripId/files')
export class FilesDownloadController {
constructor(
private readonly files: FilesService,
private readonly storage: StorageService,
private readonly addons: AddonsService,
) {}
// response-contract-exempt: streams the file through @Res(), there is no JSON body to check.
@Get(':id/download')
async download(
@Req() req: Request,
@Res() res: Response,
@Param('tripId') tripId: string,
@Param('id') id: string,
): Promise<void> {
const auth = await this.files.authenticateDownload(req);
const trip = await this.files.verifyTripAccess(tripId, auth.userId);
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);
}
// basename() tolerates a stray prefixed row (legacy rows sometimes stored
// a relative path); the storage layer's key validation refuses the rest.
const name = path.basename(file.filename);
if (!(await this.storage.exists('files', name).catch(() => false))) {
throw new HttpException({ error: 'File not found' }, 404);
}
// Serve Apple Wallet passes inline with the canonical MIME type so Safari
// (iOS/macOS) hands them to Wallet instead of downloading as a blob. A
// `.pkpasses` bundle (a ZIP of multiple passes) is a distinct type with its
// own plural MIME type — without it Wallet won't offer to add the passes.
const ext = path.extname(name).toLowerCase();
const walletMime =
ext === '.pkpass'
? 'application/vnd.apple.pkpass'
: ext === '.pkpasses'
? 'application/vnd.apple.pkpasses'
: null;
await this.storage.sendToResponse(
'files',
name,
res,
walletMime
? {
contentType: walletMime,
disposition: contentDisposition(path.basename(file.original_name || name), 'inline'),
}
: undefined,
);
}
}