Move the file surface onto the decorators

Six more methods, so the registry owns 30 of 113, and the deps factory is down to
660 lines from 944.

Files are the awkward corner of the plugin surface and stay that way on purpose.
Reading a file's bytes is a separate grant from reading its metadata, because a
passport scan is more sensitive than its filename, and the three writes use three
distinct rights instead of one domain action. FILES-RPC-006 pins that by watching
which permission each operation actually asks for.

This is also the only plugin path that touches disk, so the tests lean on it: the
extension blocklist, the size cap checked before the read rather than after, a
path that resolves outside the uploads root, and the demo-account upload refusal
that mirrors the REST guard.
This commit is contained in:
Maurice
2026-08-09 12:49:01 +02:00
committed by Maurice
parent ca88676858
commit dbb0016cac
9 changed files with 470 additions and 209 deletions
+5 -2
View File
@@ -2,13 +2,16 @@ import { Module } from '@nestjs/common';
import { FilesController } from './files.controller';
import { FilesDownloadController } from './files-download.controller';
import { FilesService } from './files.service';
import { FilesRpc } from './files.rpc';
import { PluginGuardsModule } from '../plugins/host/plugin-guards.module';
import { RealtimeModule } from '../realtime/realtime.module';
import { PermissionsModule } from '../permissions/permissions.module';
import { AppConfigModule } from '../app-config/app-config.module';
@Module({
imports: [PermissionsModule, AppConfigModule],
imports: [PermissionsModule, AppConfigModule, RealtimeModule, PluginGuardsModule],
controllers: [FilesController, FilesDownloadController],
providers: [FilesService],
providers: [FilesService, FilesRpc],
exports: [FilesService],
})
export class FilesModule {}
+210
View File
@@ -0,0 +1,210 @@
import fsMod from 'node:fs';
import pathMod from 'node:path';
import { randomUUID } from 'node:crypto';
import { PluginController, PluginMethod } from '../plugins/host/rpc-kit/decorators';
import { PluginGuards } from '../plugins/host/plugin-guards.service';
import { BadParams, ForbiddenResource } from '../plugins/host/rpc-errors';
import { asPayload, num } from '../plugins/host/rpc-params';
import type { PluginRpcContext } from '../plugins/host/rpc-kit/types';
import { RealtimeService } from '../realtime/realtime.service';
import { DatabaseService } from '../database/database.service';
import { readEnv } from '../../app-config';
import { isDemoEmail } from '../common/demo';
import { BLOCKED_EXTENSIONS, filesDir } from './files.constants';
import { FilesService } from './files.service';
/** Files use three separate rights, one per operation, unlike every other domain. */
const UPLOAD_ACTION = 'file_upload';
const EDIT_ACTION = 'file_edit';
const DELETE_ACTION = 'file_delete';
/** Decoded bytes a plugin may read or write in one call. */
const CONTENT_MAX = 10 * 1024 * 1024;
type FileRow = {
filename: string;
original_name: string;
mime_type: string | null;
file_size: number | null;
deleted_at: string | null;
};
type CreateInput = {
name: string;
content_base64: string;
mimetype?: string;
description?: string;
place_id?: number;
reservation_id?: number;
};
/**
* The file surface a plugin may reach (#plugins).
*
* Two things here are unlike the rest of the plugin surface. Reading a file's BYTES
* is a separate grant from reading its metadata, because a passport scan is more
* sensitive than its filename. And the three write operations use three distinct
* rights (file_upload / file_edit / file_delete) rather than one domain action.
*
* The upload path is the only one in the plugin surface that touches disk, so the
* extension is checked against the central blocklist and the size is capped before
* anything is written, and a demo user is refused outright.
*/
@PluginController()
export class FilesRpc {
constructor(
private readonly files: FilesService,
private readonly realtime: RealtimeService,
private readonly db: DatabaseService,
private readonly guards: PluginGuards,
) {}
@PluginMethod('files.list', { permission: 'db:read:files' })
list(params: Record<string, unknown>, ctx: PluginRpcContext): unknown {
// Trash excluded, the same view the files tab shows.
return this.guards.tripRead(params, ctx, () => this.files.listFiles(num(params.tripId, 'tripId'), false));
}
@PluginMethod('files.getContent', { permission: 'db:read:files:content' })
getContent(params: Record<string, unknown>, ctx: PluginRpcContext): unknown {
return this.guards.tripRead(params, ctx, () =>
this.readContent(num(params.tripId, 'tripId'), num(params.fileId, 'fileId')),
);
}
/**
* Size-capped BEFORE the read, so a 500MB video cannot be pulled through the IPC
* pipe as ~667MB of base64. The read itself runs off the event loop: 10MB of
* readFile plus base64 on the host thread would stall every other plugin RPC and
* every HTTP request for its duration.
*/
private async readContent(tripId: number, fileId: number): Promise<unknown> {
const file = this.files.getFileById(fileId, tripId) as FileRow | 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 } = this.files.resolveFilePath(file.filename);
if (!safe) throw new ForbiddenResource('file path is not accessible');
const buf = await fsMod.promises.readFile(resolved);
if (buf.length > CONTENT_MAX) throw new BadParams('file too large to read');
return {
name: file.original_name,
mimetype: file.mime_type ?? 'application/octet-stream',
size: buf.length,
content_base64: buf.toString('base64'),
};
}
@PluginMethod('files.create', { permission: 'db:write:files' })
create(params: Record<string, unknown>, ctx: PluginRpcContext): unknown {
const tripId = num(params.tripId, 'tripId');
const actor = this.guards.requireActor(ctx, 'file');
const input = asPayload(params.input);
if (typeof input.name !== 'string' || input.name.trim() === '' || input.name.length > 255) {
throw new BadParams('file name is required (max 255 chars)');
}
if (typeof input.content_base64 !== 'string' || input.content_base64 === '') {
throw new BadParams('content_base64 is required');
}
// Bound the ENCODED length first: 14MB of base64 is roughly the 10MB cap, and
// rejecting here avoids decoding an oversized payload just to measure it.
if (input.content_base64.length > 14 * 1024 * 1024) {
throw new BadParams('file exceeds the 10MB plugin upload cap');
}
this.guards.requireTripEdit(tripId, actor, UPLOAD_ACTION);
return this.writeFile(tripId, input as unknown as CreateInput, actor);
}
private writeFile(tripId: number, input: CreateInput, actingUserId: number): unknown {
// Mirrors the REST upload guard: a demo user must not write bytes to the shared
// demo instance, not even through a plugin's db:write:files. The email is only
// resolved when demo mode is actually on, so self-hosted installs pay nothing.
if (readEnv().demo.enabled) {
const uploader = this.db.prepare('SELECT email FROM users WHERE id = ?').get(actingUserId) as { email?: string } | undefined;
if (isDemoEmail(uploader?.email)) throw new ForbiddenResource('Uploads are disabled in demo mode.');
}
const original = pathMod.basename(input.name);
const ext = pathMod.extname(original).toLowerCase();
if (!ext || BLOCKED_EXTENSIONS.includes(ext)) {
throw new BadParams(`file extension '${ext || '(none)'}' is not allowed`);
}
const buf = Buffer.from(input.content_base64, 'base64');
if (buf.length === 0) throw new BadParams('file content is empty');
if (buf.length > CONTENT_MAX) throw new BadParams('file exceeds the 10MB plugin upload cap');
const foreign = this.files.findForeignLinkTarget(tripId, {
reservation_id: input.reservation_id ?? null,
place_id: input.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 = this.files.createFile(
tripId,
{ filename, originalname: original, size: buf.length, mimetype: input.mimetype || 'application/octet-stream' },
actingUserId,
{
place_id: input.place_id != null ? String(input.place_id) : null,
reservation_id: input.reservation_id != null ? String(input.reservation_id) : null,
description: input.description ?? null,
},
);
this.realtime.broadcast(tripId, 'file:created', { file }, undefined);
return file;
}
@PluginMethod('files.createLink', { permission: 'db:write:files' })
createLink(params: Record<string, unknown>, ctx: PluginRpcContext): unknown {
const tripId = num(params.tripId, 'tripId');
const fileId = num(params.fileId, 'fileId');
const actor = this.guards.requireActor(ctx, 'file link');
this.guards.requireTripEdit(tripId, actor, EDIT_ACTION);
if (!this.files.getFileById(fileId, tripId)) throw new ForbiddenResource(`no file ${fileId} on trip ${tripId}`);
const opts = asPayload(params.opts) as { reservation_id?: number; assignment_id?: number; place_id?: number };
// A link target on another trip would otherwise attach this trip's file to it.
const foreign = this.files.findForeignLinkTarget(tripId, opts);
if (foreign) throw new ForbiddenResource(`${foreign} does not belong to trip ${tripId}`);
return this.files.createFileLink(fileId, {
reservation_id: opts.reservation_id != null ? String(opts.reservation_id) : null,
assignment_id: opts.assignment_id != null ? String(opts.assignment_id) : null,
place_id: opts.place_id != null ? String(opts.place_id) : null,
});
}
@PluginMethod('files.update', { permission: 'db:write:files' })
update(params: Record<string, unknown>, ctx: PluginRpcContext): unknown {
const tripId = num(params.tripId, 'tripId');
const fileId = num(params.fileId, 'fileId');
const actor = this.guards.requireActor(ctx, 'file');
this.guards.requireTripEdit(tripId, actor, EDIT_ACTION);
const current = this.files.getFileById(fileId, tripId);
if (!current) throw new ForbiddenResource(`no file ${fileId} on trip ${tripId}`);
const input = asPayload(params.input) as { description?: string; place_id?: number | null; reservation_id?: number | null };
const foreign = this.files.findForeignLinkTarget(tripId, {
reservation_id: input.reservation_id ?? null,
place_id: input.place_id ?? null,
});
if (foreign) throw new ForbiddenResource(`${foreign} does not belong to trip ${tripId}`);
const file = this.files.updateFile(fileId, current, {
description: input.description,
// null clears the link, undefined leaves it alone: the two are distinct here.
place_id: input.place_id != null ? String(input.place_id) : input.place_id === null ? null : undefined,
reservation_id: input.reservation_id != null ? String(input.reservation_id) : input.reservation_id === null ? null : undefined,
});
this.realtime.broadcast(tripId, 'file:updated', { file }, undefined);
return file;
}
@PluginMethod('files.softDelete', { permission: 'db:write:files' })
softDelete(params: Record<string, unknown>, ctx: PluginRpcContext): unknown {
const tripId = num(params.tripId, 'tripId');
const fileId = num(params.fileId, 'fileId');
const actor = this.guards.requireActor(ctx, 'file');
this.guards.requireTripEdit(tripId, actor, DELETE_ACTION);
if (!this.files.getFileById(fileId, tripId)) throw new ForbiddenResource(`no file ${fileId} on trip ${tripId}`);
this.files.softDeleteFile(fileId);
this.realtime.broadcast(tripId, 'file:deleted', { fileId }, undefined);
return { deleted: true };
}
}
@@ -196,82 +196,12 @@ 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. ---
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 = 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 } = 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.
const buf = await fsMod.promises.readFile(resolved);
if (buf.length > CONTENT_MAX) throw new BadParams('file too large to read');
return { name: file.original_name, mimetype: file.mime_type ?? 'application/octet-stream', size: buf.length, content_base64: buf.toString('base64') };
},
// --- Files write. Bytes arrive as bounded base64; the extension is validated
// against the central blocklist BEFORE anything touches disk, and link targets
// must live on the same trip (findForeignLinkTarget). Same events as the app. ---
canUploadFiles: (tripId, userId) => this.canEditTripAs('file_upload', tripId, userId),
canEditFiles: (tripId, userId) => this.canEditTripAs('file_edit', tripId, userId),
canDeleteFiles: (tripId, userId) => this.canEditTripAs('file_delete', tripId, userId),
createTripFile: (tripId, input, actingUserId) => {
// Mirror the REST upload guard (files.controller): a demo user must not write
// bytes to the shared demo instance, even through a plugin's db:write:files.
// Only resolve the email when demo mode is actually on — keeps the hot path
// (and the schema surface) untouched for self-hosted installs.
if (readEnv().demo.enabled) {
const uploader = this.db.prepare('SELECT email FROM users WHERE id = ?').get(actingUserId) as { email?: string } | undefined;
if (isDemoEmail(uploader?.email)) throw new ForbiddenResource('Uploads are disabled in demo mode.');
}
const i = input as { name: string; content_base64: string; mimetype?: string; description?: string; place_id?: number; reservation_id?: number };
const original = pathMod.basename(i.name);
const ext = pathMod.extname(original).toLowerCase();
if (!ext || BLOCKED_EXTENSIONS.includes(ext)) throw new BadParams(`file extension '${ext || '(none)'}' is not allowed`);
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 = 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 = this.files.createFile(
tripId,
{ filename, originalname: original, size: buf.length, mimetype: i.mimetype || 'application/octet-stream' },
actingUserId,
{ place_id: i.place_id != null ? String(i.place_id) : null, reservation_id: i.reservation_id != null ? String(i.reservation_id) : null, description: i.description ?? null },
);
this.realtime.broadcast(tripId, 'file:created', { file }, undefined);
return file;
},
createTripFileLink: (tripId, fileId, opts) => {
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 = this.files.findForeignLinkTarget(tripId, o);
if (foreign) throw new ForbiddenResource(`${foreign} does not belong to trip ${tripId}`);
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 = 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 = 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 = 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 });
this.realtime.broadcast(tripId, 'file:updated', { file }, undefined);
return file;
},
softDeleteTripFile: (tripId, fileId) => {
if (!this.files.getFileById(fileId, tripId)) throw new ForbiddenResource(`no file ${fileId} on trip ${tripId}`);
this.files.softDeleteFile(fileId);
this.realtime.broadcast(tripId, 'file:deleted', { fileId }, undefined);
return { deleted: true };
},
// --- Collab reads (collab addon; membership checked by the host). Same hydrated
// shapes as the REST GETs, so a collab plugin can finally read what it writes. ---
listCollabNotes: (tripId) => { requireAddon(ADDON_IDS.COLLAB, 'collab'); return this.collab.listNotes(tripId) as unknown[]; },
+1 -61
View File
@@ -92,21 +92,12 @@ export interface HostDeps {
canEditCosts(tripId: number, userId: number): boolean;
/** A trip's packing items visible to `userId` (#858 private-item filter), for `packing.list`. */
/** A trip's files (trash excluded), for `files.list`. */
listTripFiles(tripId: number): unknown[];
/** One trip file's bytes as base64 (size-capped), for `files.getContent`. Throws if it's not on the trip or exceeds the cap. */
getTripFileContent(tripId: number, fileId: number): unknown;
// --- Files write (the app's file_upload / file_edit / file_delete permissions) ---
canUploadFiles(tripId: number, userId: number): boolean;
canEditFiles(tripId: number, userId: number): boolean;
canDeleteFiles(tripId: number, userId: number): boolean;
/** Store a bounded base64 payload as a trip file (extension + size validated); broadcasts file:created. */
createTripFile(tripId: number, input: Record<string, unknown>, actingUserId: number): unknown;
/** Link an existing trip file to a reservation/place/assignment on the SAME trip. */
createTripFileLink(tripId: number, fileId: number, opts: Record<string, unknown>): unknown;
/** Update a file's description/links (same-trip targets enforced); broadcasts file:updated. */
updateTripFile(tripId: number, fileId: number, input: Record<string, unknown>): unknown;
/** Move a trip file to the trash; broadcasts file:deleted. */
softDeleteTripFile(tripId: number, fileId: number): unknown;
// --- Collab reads (membership + collab addon; no separate right, like the REST GETs) ---
listCollabNotes(tripId: number): unknown[];
listCollabPolls(tripId: number): unknown[];
@@ -315,58 +306,7 @@ export class PluginRpcHost {
// The trip's member roster (ids + display fields only), membership-checked.
this.methods.set('trips.members', (p, uid) => this.tripRead(p, uid, () => deps.tripMembers(num(p.tripId, 'tripId'))));
}
if (has('db:read:files')) {
// Trip files, trash excluded — same view the files tab shows.
this.methods.set('files.list', (p, uid) =>
this.tripRead(p, uid, () => deps.listTripFiles(num(p.tripId, 'tripId'))),
);
}
if (has('db:read:files:content')) {
// Reading a file's BYTES is a step up from its metadata (a passport scan is
// more sensitive than its filename), so it's a separate grant. Membership-
// checked like files.list; the wiring caps the size before base64-ing it
// through the IPC pipe.
this.methods.set('files.getContent', (p, uid) =>
this.tripRead(p, uid, () => deps.getTripFileContent(num(p.tripId, 'tripId'), num(p.fileId, 'fileId'))),
);
}
if (has('db:write:files')) {
// Files write, under the app's separate file_upload / file_edit / file_delete
// rights. A created file arrives as bounded base64 (10MB decoded cap — well
// under the app's 50MB upload limit); the wiring validates the extension
// against the central blocklist before anything touches disk.
this.methods.set('files.create', (p, uid) => {
const tripId = num(p.tripId, 'tripId');
const actor = this.requireActor(uid, 'file');
const input = asPayload(p.input);
if (typeof input.name !== 'string' || input.name.trim() === '' || input.name.length > 255) throw new BadParams('file name is required (max 255 chars)');
if (typeof input.content_base64 !== 'string' || input.content_base64 === '') throw new BadParams('content_base64 is required');
if (input.content_base64.length > 14 * 1024 * 1024) throw new BadParams('file exceeds the 10MB plugin upload cap');
this.requireTripEdit(tripId, actor, deps.canUploadFiles);
return deps.createTripFile(tripId, input, actor);
});
this.methods.set('files.createLink', (p, uid) => {
const tripId = num(p.tripId, 'tripId');
const fileId = num(p.fileId, 'fileId');
const actor = this.requireActor(uid, 'file link');
this.requireTripEdit(tripId, actor, deps.canEditFiles);
return deps.createTripFileLink(tripId, fileId, asPayload(p.opts));
});
this.methods.set('files.update', (p, uid) => {
const tripId = num(p.tripId, 'tripId');
const fileId = num(p.fileId, 'fileId');
const actor = this.requireActor(uid, 'file');
this.requireTripEdit(tripId, actor, deps.canEditFiles);
return deps.updateTripFile(tripId, fileId, asPayload(p.input));
});
this.methods.set('files.softDelete', (p, uid) => {
const tripId = num(p.tripId, 'tripId');
const fileId = num(p.fileId, 'fileId');
const actor = this.requireActor(uid, 'file');
this.requireTripEdit(tripId, actor, deps.canDeleteFiles);
return deps.softDeleteTripFile(tripId, fileId);
});
}
// files.* now lives in src/nest/files/files.rpc.ts.
if (has('db:write:collab')) {
// Collab content (notes/polls/messages) under the app's collab_edit right.
this.methods.set('collab.createNote', (p, uid) => {