mirror of
https://github.com/mauriceboe/TREK.git
synced 2026-12-06 18:54:17 +00:00
fix(collab): keep every panel on screen, and stop leaking spool and links
The desktop layout rendered notes and links as a pair and dropped whichever of the two was on its own, so turning the new Links feature off on an otherwise default install made the Notes panel disappear. Both rows are now split by kind and rendered only when they hold something, and one function decides what a panel id renders, because the branch that lost a panel did so by not listing it. The message and its attachment rows are written in one transaction. The caller has already committed the image bytes by then, so a message that landed without them left those bytes with nothing pointing at them and nothing to sweep them. Deleting one now drops the blobs after the rows are gone rather than before. A body the Zod pipe rejects used to leave up to four spooled images on disk: pipes run after interceptors, so multer had already written them and the handler's own cleanup was never reached. An interceptor removes them on any failure before the handler, which also covers every other schema mismatch, and the length check that could never fire is gone. Adding, pinning and deleting a link now says something when it fails instead of raising an unhandled rejection, the list has real types, and the rejected-image toast is translated in all 23 locales rather than shipping English everywhere. The picking, previewing and clearing of chat images moved into one hook both shells use: it was copied into two, and both rebuilt every preview on each change and leaked an object URL per image per pick. Tests: the four link routes end to end with the validation pipe the harness was missing, the image filter against the disguised-extension case, and the layout combinations that drop a panel.
This commit is contained in:
@@ -36,6 +36,7 @@ import { JwtAuthGuard } from '../auth/jwt-auth.guard';
|
||||
import { CurrentUser } from '../auth/current-user.decorator';
|
||||
import { RequirePermission, TripAccessGuard } from '../permissions/trip-access.guard';
|
||||
import { BLOCKED_EXTENSIONS } from '../files/files.constants';
|
||||
import { SpoolCleanupInterceptor } from '../common/spool-cleanup.interceptor';
|
||||
|
||||
export const MAX_NOTE_FILE_SIZE = 50 * 1024 * 1024;
|
||||
const MAX_CHAT_IMAGES = 4;
|
||||
@@ -330,14 +331,17 @@ export class CollabController {
|
||||
// client is still streaming the body and the socket dies as ECONNRESET
|
||||
// instead of carrying the error envelope. Both checks happen in the handler.
|
||||
@Post('messages')
|
||||
@UseInterceptors(FilesInterceptor('images', MAX_CHAT_IMAGES, { fileFilter: collabChatImageFilter, limits: { files: MAX_CHAT_IMAGES, fileSize: 10 * 1024 * 1024 } }))
|
||||
// SpoolCleanupInterceptor sits after the file one on purpose: the Zod pipe
|
||||
// runs when the handler's parameters are resolved, which is after both have
|
||||
// been entered, so a rejected body would otherwise leave up to four spooled
|
||||
// images on disk with nothing to sweep them.
|
||||
@UseInterceptors(
|
||||
FilesInterceptor('images', MAX_CHAT_IMAGES, { fileFilter: collabChatImageFilter, limits: { files: MAX_CHAT_IMAGES, fileSize: 10 * 1024 * 1024 } }),
|
||||
SpoolCleanupInterceptor,
|
||||
)
|
||||
async createMessage(@CurrentUser() user: User, @Param('tripId') tripId: string, @Body() body: CollabMessageCreateDto, @UploadedFiles() files: Express.Multer.File[] | undefined, @Headers('x-socket-id') socketId?: string) {
|
||||
const uploaded = files || [];
|
||||
const cleanupSpool = () => uploaded.forEach(file => { if (file.path) { try { fs.unlinkSync(file.path); } catch { /* best-effort */ } } });
|
||||
if (body.text && body.text.length > 5000) {
|
||||
cleanupSpool();
|
||||
throw new HttpException({ error: 'text must be 5000 characters or less' }, 400);
|
||||
}
|
||||
let trip;
|
||||
try {
|
||||
trip = this.requireTrip(tripId, user);
|
||||
|
||||
@@ -561,17 +561,23 @@ export class CollabService {
|
||||
if (!replyMsg) return { error: 'reply_not_found' };
|
||||
}
|
||||
|
||||
const result = this.db.run(`
|
||||
// One transaction: the caller has already committed the image bytes to
|
||||
// storage, so a message row that lands without its attachment rows would
|
||||
// leave those bytes with nothing pointing at them and nothing to sweep them.
|
||||
const result = this.db.transaction(() => {
|
||||
const inserted = this.db.run(`
|
||||
INSERT INTO collab_messages (trip_id, user_id, text, reply_to) VALUES (?, ?, ?, ?)
|
||||
`, tripId, userId, text.trim(), replyTo || null);
|
||||
|
||||
for (const file of files) {
|
||||
this.db.run(
|
||||
`INSERT INTO trip_files (trip_id, message_id, filename, original_name, file_size, mime_type, uploaded_by)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?)`,
|
||||
tripId, result.lastInsertRowid, file.filename, file.originalname, file.size, file.mimetype, userId,
|
||||
);
|
||||
}
|
||||
for (const file of files) {
|
||||
this.db.run(
|
||||
`INSERT INTO trip_files (trip_id, message_id, filename, original_name, file_size, mime_type, uploaded_by)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?)`,
|
||||
tripId, inserted.lastInsertRowid, file.filename, file.originalname, file.size, file.mimetype, userId,
|
||||
);
|
||||
}
|
||||
return inserted;
|
||||
});
|
||||
|
||||
const message = this.db.get<CollabMessage>(`
|
||||
SELECT m.*, u.username, u.avatar,
|
||||
@@ -593,11 +599,16 @@ export class CollabService {
|
||||
if (Number(message.user_id) !== Number(userId)) return { error: 'not_owner' };
|
||||
|
||||
const attachments = this.db.all<{ filename: string }>('SELECT filename FROM trip_files WHERE message_id = ? AND trip_id = ?', messageId, tripId);
|
||||
this.db.transaction(() => {
|
||||
this.db.run('DELETE FROM trip_files WHERE message_id = ? AND trip_id = ?', messageId, tripId);
|
||||
this.db.run('UPDATE collab_messages SET deleted = 1 WHERE id = ?', messageId);
|
||||
});
|
||||
// Only once the rows are actually gone. Dropping the blobs first left a
|
||||
// live message pointing at attachments whose bytes no longer existed
|
||||
// whenever the second statement failed.
|
||||
for (const file of attachments) {
|
||||
void this.storage.delete('files', path.basename(file.filename)).catch(() => { /* best effort */ });
|
||||
}
|
||||
this.db.run('DELETE FROM trip_files WHERE message_id = ? AND trip_id = ?', messageId, tripId);
|
||||
this.db.run('UPDATE collab_messages SET deleted = 1 WHERE id = ?', messageId);
|
||||
return { username: message.username };
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,38 @@
|
||||
import { CallHandler, ExecutionContext, Injectable, NestInterceptor } from '@nestjs/common';
|
||||
import { Observable, catchError, throwError } from 'rxjs';
|
||||
import * as fs from 'fs';
|
||||
|
||||
/**
|
||||
* Unlink whatever multer spooled when the request dies before the handler.
|
||||
*
|
||||
* Nest resolves handler parameters, and therefore runs the validation pipe,
|
||||
* only after every interceptor has been entered. `FilesInterceptor` has already
|
||||
* written the parts to the spool directory by then, so a body the Zod pipe
|
||||
* rejects throws with the bytes on disk and the handler's own cleanup never
|
||||
* reached. Nothing sweeps that directory, and the request is repeatable, so it
|
||||
* is a disk-fill anybody with upload rights can trigger in a loop.
|
||||
*
|
||||
* Register it AFTER the file interceptor on a route, so `req.files` is
|
||||
* populated by the time this one wraps the call. It only cleans up on failure:
|
||||
* a handler that succeeds owns the spooled files and moves them itself.
|
||||
*/
|
||||
@Injectable()
|
||||
export class SpoolCleanupInterceptor implements NestInterceptor {
|
||||
intercept(context: ExecutionContext, next: CallHandler): Observable<unknown> {
|
||||
return next.handle().pipe(
|
||||
catchError(err => {
|
||||
const req = context.switchToHttp().getRequest<{ files?: Array<{ path?: string }>; file?: { path?: string } }>();
|
||||
const spooled = [...(req.files ?? []), ...(req.file ? [req.file] : [])];
|
||||
for (const file of spooled) {
|
||||
if (!file?.path) continue;
|
||||
try {
|
||||
fs.unlinkSync(file.path);
|
||||
} catch {
|
||||
// Best effort: the handler may already have moved or removed it.
|
||||
}
|
||||
}
|
||||
return throwError(() => err);
|
||||
}),
|
||||
);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user