Files
wekan/server/migrations/correctFileExtensions.js
T
Lauri Ojansivu 81dbecfb87 Safe filename handling: display, upload, existing files, migrations
One unified filename subsystem, used everywhere a name is shown, uploaded,
served, or migrated. Design: docs/Features/Filename/Filename.md.

Display (imports/lib/fileNameDisplay.js, general cleanFileName + global
{{cleanFilename}}/{{downloadFilename}} helpers): URL-decode, normalize to
generally-used characters (NFKC + confusable-homoglyph folding so typosquatting
"payp<Cyrillic-a>l.exe" shows as "paypal.exe", only in a Latin-majority base so
genuine non-Latin names are preserved), remove invisible/control/bidi chars,
strip HTML/JS/XML/template markup. Removed the earlier invisible-char filter
button, warning triangle, inline descriptions, legend and server invisibleOnly
filter.

Upload (attachments + avatars, all backends): reject exploit-looking filenames
and EICAR virus test files; strip invisible chars; correct the extension to the
real detected type (double-click opens the right app); type-based name when
empty; cap length to a portable max (30, Amiga OS FFS) preserving the extension;
sanitize SVG JS / XML-loop content at the staging location before promoting to
final storage and delete the temp file after; enough-disk-space check with
small-RAM streaming and stop-and-remove-partial on any write error.

Existing files: general storage-agnostic detector streams a small header to
WRITABLE_PATH/files/temp, runs `file`, deletes the temp file; admin-only bounded
batch extension corrector; serve-time on-the-fly exploit sanitizer wired into
httpStreamOutput (sniffs the start, rewrites only dangerous markup, streams the
rest unchanged).

Migrations (moveToStorage/copyFile): sanitize content, finalize the name with
the same general function (detected type, corrected extension, folded
homoglyphs, capped length), save it at the destination, and number
same-name/different-content collisions (document.pdf, document-1.pdf, ...).

Tests: rewrote fileNameDisplay.test.cjs; added uploadFileName, diskSpace,
fileTypeCorrection and fileHardeningGuards unit tests (positive + negative);
updated Playwright spec 41 to the clean-name model. CHANGELOG + design doc.
2026-07-20 03:11:07 +03:00

76 lines
3.0 KiB
JavaScript

import { Meteor } from 'meteor/meteor';
import { check, Match } from 'meteor/check';
import { ReactiveCache } from '/imports/reactiveCache';
import Attachments from '/models/attachments';
import { fileStoreStrategyFactory as attachmentsFactory } from '/models/attachments.server';
import { fileStoreStrategyFactory as avatarsFactory } from '/models/avatars.server';
import { rename } from '/models/lib/fileStoreStrategy';
import { correctedNameForStoredFile } from '/models/lib/fileTypeCorrection';
// Correct the extensions of ALREADY-uploaded files.
//
// New uploads are corrected in the onAfterUpload hooks; this method fixes files
// that were stored BEFORE that hook existed (the field problem: a file saved with
// the wrong/missing extension opens the wrong app on double-click). It reuses the
// general, storage-agnostic detector (fileTypeCorrection.js) which streams only a
// small header of each file to WRITABLE_PATH/files/temp, detects the type with the
// `file` command, then deletes the temp file — so it works for filesystem, GridFS
// and cloud storage without loading whole files into RAM.
//
// Admin-only and BOUNDED (processes at most `limit` files per call) so it never
// stalls a large instance; call repeatedly until `remaining` is 0.
async function correctBatch(collection, factory, limit) {
const result = { checked: 0, corrected: 0, errors: 0, examples: [] };
// Read directly from the collection so this works for both Attachments and Avatars.
const cursor = collection.find({}, { limit });
const docs = await cursor.fetchAsync();
for (const fileObj of docs) {
result.checked++;
try {
const { name, changed } = await correctedNameForStoredFile(fileObj, factory);
if (changed && name) {
rename(fileObj, name, factory);
result.corrected++;
if (result.examples.length < 20) {
result.examples.push({ from: fileObj.name, to: name });
}
}
} catch (error) {
result.errors++;
console.error('[correctFileExtensions] failed for', fileObj && fileObj._id, error);
}
}
return result;
}
Meteor.methods({
// Correct up to `limit` attachment (and optionally avatar) extensions. Returns
// per-collection counts. Admin only.
async 'correctFileExtensions.run'(limit = 200, includeAvatars = true) {
check(limit, Match.Optional(Number));
check(includeAvatars, Match.Optional(Boolean));
const user = await ReactiveCache.getCurrentUser();
if (!(user && user.isAdmin)) {
throw new Meteor.Error('not-authorized', 'Only admins can correct file extensions');
}
const cap = Math.max(1, Math.min(1000, Number(limit) || 200));
const attachments = await correctBatch(Attachments, attachmentsFactory, cap);
let avatars = null;
if (includeAvatars) {
try {
const Avatars = require('/models/avatars').default;
avatars = await correctBatch(Avatars, avatarsFactory, cap);
} catch (e) {
console.error('[correctFileExtensions] avatars pass failed:', e);
}
}
return { attachments, avatars };
},
});