Files
wekan/models/avatars.js
T
Lauri Ojansivu 582a22c291 Fix GitHub code scanning code-quality findings.
Real faults: a card's original-position description formatted a promise
because it did not await the history; the attachment swipe distances and
two drag-scroll locals were undeclared globals; a file that cannot be read
during a GridFS upload left the upload open; api.py called exit() instead of
sys.exit(); a rules test redefined a property and a security-log test kept
an unreachable branch. Also 31 missing semicolons, unused imports in the
card details, exporters and attachment API, unused Python imports, and
comments on empty except clauses. The list-sync scanner test cut its source
at the last Meteor.startup, which the new index startup of #6855 had moved.

Thanks to GitHub CodeQL and xet7 !
2026-11-02 14:15:02 +02:00

153 lines
5.6 KiB
JavaScript

import { Meteor } from 'meteor/meteor';
import { FilesCollection } from 'meteor/ostrio:files';
import { Random } from 'meteor/random';
const { safeUploadFileId } = require('/models/lib/uploadFileId');
const { isFilesRoot } = require('/models/lib/filesRoot');
import { generateUniversalAvatarUrl } from '/models/lib/universalUrlGenerator';
const { cleanFileName } = require('/imports/lib/fileNameDisplay');
const { filesize } = require('filesize');
const getTAPi18n = () => require('/imports/i18n').TAPi18n;
let avatarsUploadSize = 72000;
// Compute storage path:
// - Docker (WRITABLE_PATH=/data): /data/files/avatars
// - Snap (WRITABLE_PATH=$SNAP_COMMON/files): $SNAP_COMMON/files/avatars
const computeAvatarStoragePath = () => {
const basePath = process.env.WRITABLE_PATH || process.cwd();
const endsWithFiles = isFilesRoot(basePath);
if (endsWithFiles) {
// Snap: WRITABLE_PATH already includes /files
return basePath + '/avatars';
} else {
// Docker & Dev: append /files/avatars
return basePath + '/files/avatars';
}
};
const storagePath = Meteor.isServer ? computeAvatarStoragePath() : 'assets/app/uploads/avatars';
const Avatars = new FilesCollection({
debug: false, // Change to `true` for debugging
collectionName: 'avatars',
// CacheBleed (GHSA-w3qg-pf27-g68r): Meteor-Files' default is a public, one-year
// cache; this file is served only after an access check.
cacheControl: require('/models/lib/fileCacheHeaders').PRIVATE_FILE_CACHE_CONTROL,
// WeKan serves current and legacy avatars through its guarded canonical
// /cdn/storage/avatars route. Meteor-Files' broad middleware must not
// intercept that URL first and reject an authenticated legacy file.
downloadRoute: '/meteor-files-internal',
allowClientCode: true,
storagePath: storagePath,
namingFunction(opts) {
let filenameWithoutExtension = "";
let fileId = "";
if (opts?.name) {
// Client
filenameWithoutExtension = opts.name.replace(/(.+)\..+/, "$1");
fileId = opts.meta.fileId;
delete opts.meta.fileId;
} else if (opts?.file?.name) {
// Server
if (opts.file.extension) {
// A literal suffix, never a RegExp built from the uploaded name.
const name = opts.file.name;
const suffix = opts.file.extensionWithDot;
filenameWithoutExtension = name.endsWith(suffix) ? name.slice(0, -suffix.length) : name;
} else {
// file has no extension, so don't replace anything, otherwise the last character is removed (because extensionWithDot = '.')
filenameWithoutExtension = opts.file.name;
}
fileId = opts.fileId;
}
else {
// should never reach here
filenameWithoutExtension = Math.random().toString(36).slice(2);
fileId = Math.random().toString(36).slice(2);
}
// UploadPathBleed, avatar sibling (2026-10-02): the id is client-supplied
// and starts the on-disk name, so "../../x" wrote outside the store.
fileId = safeUploadFileId(fileId, { source: 'Avatars.namingFunction', fresh: () => Random.id(), isServer: Meteor.isServer });
// Strip shell metacharacters and path-traversal sequences from the
// user-supplied portion of the filename. The result is used as part of
// the on-disk path passed to external commands, so only safe characters
// (alphanumerics, hyphens, underscores, and dots) are kept.
const safeName = filenameWithoutExtension.replace(/[^a-zA-Z0-9_.\-]/g, '_');
const ret = fileId + "-original-" + safeName;
return ret;
},
sanitize(str, max, replacement) {
// Strip characters that are dangerous in shell contexts and filesystem paths.
return str.replace(/[^a-zA-Z0-9_.\-]/g, '_');
},
onBeforeUpload(file) {
// An avatar belongs to a signed-in user; nobody else uploads one.
if (!this.userId) return 'Please sign in to upload an avatar.';
file.name = cleanFileName(file && file.name) || 'image';
// SVG is allowed (#6802, maintainer decision 2026-10-25): every uploaded SVG
// is sanitized on the server before it is stored - no script, event handler,
// javascript: URI, foreignObject or DOCTYPE/ENTITY XML loop
// (models/lib/sanitizeUploadedFile.js) - and sanitized again whenever it is
// served, inline under a script-free sandbox (server/lib/svgResponse.js).
// It used to be refused here after JVN#74210258.
if (file.size <= avatarsUploadSize && file.type.startsWith('image/')) {
return true;
}
return getTAPi18n().__('avatar-too-big', {size: filesize(avatarsUploadSize)});
},
});
function normalizeRemovedFiles(filesInput) {
if (!filesInput) {
return [];
}
if (Array.isArray(filesInput)) {
return filesInput;
}
if (typeof filesInput.fetch === 'function') {
return filesInput.fetch();
}
if (Array.isArray(filesInput.files)) {
return filesInput.files;
}
if (typeof filesInput === 'string') {
return Avatars.find({ _id: filesInput }).fetch();
}
if (filesInput && typeof filesInput === 'object') {
if (filesInput._id && (filesInput.versions || filesInput.userId)) {
return [filesInput];
}
return Avatars.find(filesInput).fetch();
}
return [];
}
// Export normalizeRemovedFiles and avatarsUploadSize setter for use in server file
export { normalizeRemovedFiles };
export function setAvatarsUploadSize(size) {
avatarsUploadSize = size;
}
// Override the link method to use universal URLs
if (Meteor.isClient) {
// Add custom link method to avatar documents
Avatars.collection.helpers({
link(version = 'original') {
// Use universal URL generator for consistent, URL-agnostic URLs
return generateUniversalAvatarUrl(this._id, version);
}
});
}
export default Avatars;