Files
wekan/models/avatars.js
T
Lauri Ojansivu 31e569a18e Single-file WeKan for every platform with a Node.js bundle.
One executable per platform: that platform's published bundle repackaged
as a Node.js single executable application whose ZIP Node 26.11 mounts as
a virtual file system (useVfs + vfsArchive). Only FerretDB is copied out,
once and verified, to wekan-files/bin; native addons load from the VFS.

Everything WeKan writes is in wekan-files beside the executable, which
WRITABLE_PATH points at: attachments, avatars, db, bin, backup, logs,
versions. WeKan now treats a WRITABLE_PATH named wekan-files as the files
root (models/lib/filesRoot.js, shared by every place that derived it).

Started in a terminal it shows a menu: start, stop, status, version info
as Admin Panel / Version shows it, update to the newest release or change
to any other (checksum verified, backed up first, the old executable
kept), backup to wekan-files/backup/YYYY-MM-DD_HH-MM-SS, run at boot
(systemd, launchd, Task Scheduler, cron, Termux:Boot), log, settings.
Every entry is also a command. start runs the start-wekan.sh loop:
recovery, requested restore, FerretDB, recovery page, WeKan, restart.

Meteor's main.js chdir()s into the bundle, which a VFS cannot be, so the
server role keeps a virtual working directory. Node 26.11.1 breaks
fs.writev/readv while any VFS is mounted; they are rebuilt on fs.write
and fs.read.

single-file.yml builds every target in releases/single-file/targets.json
from its verified bundle (Macs on a Mac, to re-sign), starts it where a
runner exists with browser tests on amd64, and attaches what started.
Release All and Release All Missing call it.

Thanks to xet7 !
2026-10-13 21:08:09 +03:00

161 lines
5.8 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';
// Block SVG files for avatars to prevent XSS attacks
if (file.name && file.name.toLowerCase().endsWith('.svg')) {
if (process.env.DEBUG === 'true') {
console.warn('Blocked SVG file upload for avatar:', file.name);
}
return 'SVG files are not allowed for avatars due to security reasons. Please use PNG, JPG, or GIF format.';
}
if (file.type === 'image/svg+xml') {
if (process.env.DEBUG === 'true') {
console.warn('Blocked SVG MIME type upload for avatar:', file.type);
}
return 'SVG files are not allowed for avatars due to security reasons. Please use PNG, JPG, or GIF format.';
}
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;