import { Meteor } from 'meteor/meteor';
import { exec } from 'node:child_process';
import { promisify } from 'node:util';
import fs from 'fs';
const { detectMimeFile } = require('./lib/mimeDetection');
let asyncExec;
if (Meteor.isServer) {
// Shell-based exec, used only for the admin-configured external scanner
// command line below (which intentionally contains an arbitrary command and
// a {file} placeholder). Shared MIME detection uses execFile or bundled libmagic, never a shell.
asyncExec = promisify(exec);
}
// POSIX-safe shell quoting for a single argument. Wraps the value in single
// quotes and escapes any embedded single quote as '\'' . Inside single quotes
// the shell interprets no metacharacters ($ ` \ ; | & > < * ? ( ) etc.), so the
// value cannot break out of the argument or inject additional commands. This is
// used for the file path interpolated into the admin-configured external scanner
// command line, which is executed through /bin/sh (CWE-78 shell injection).
function shellQuote(value) {
return "'" + String(value).replace(/'/g, "'\\''") + "'";
}
// Dependency-free content sniff used as a fallback when the `file` binary is
// unavailable (GHSA-jhph-whx8-wq6p). It looks for definitive HTML / SVG / XML /
// script signatures — deliberately NOT looser event-handler heuristics — so it
// does not misfire on a genuine binary upload (e.g. a real PNG) read as text. A
// match forces the dangerous-content scan regardless of the client-supplied MIME
// type, closing the spoofed-"image/png" stored-XSS bypass. Exported for testing.
export function looksLikeDangerousMarkup(text) {
if (!text) return false;
if (/<\s*(script|html|svg|iframe|object|embed|foreignobject|meta\b)/i.test(text)) return true;
// HTML permits a slash between a tag name and its first attribute, and event
// handler values may be unquoted. `
` therefore executes even
// though checks that require whitespace and quotes miss it.
if (/<[^>]*[\s/]on[a-z-]{1,40}\s*=\s*(?:["'][^"']*|[^\s>]+)/i.test(text)) return true;
if (/<[^>]*(?:href|src|action|formaction)\s*=\s*["']?\s*javascript\s*:/i.test(text)) return true;
if (/^\s*(<\?xml| Problems -> Security.
logUploadBlock(
externalCommandLine ? 'injection.shell' : 'file.name',
externalCommandLine
? 'rejected exploit-looking filename before external scanner command'
: 'rejected exploit-looking filename',
);
return false;
}
let isValid = true;
// Always validate uploads. The previous migration flag disabled validation and enabled XSS.
try {
// Helper: read up to a limit from a file as UTF-8 text
const readTextHead = (filePath, limit = parseInt(process.env.UPLOAD_DANGEROUS_MIME_SCAN_LIMIT || '1048576')) => new Promise((resolve, reject) => {
try {
const stream = fs.createReadStream(filePath, { encoding: 'utf8', highWaterMark: 64 * 1024 });
let data = '';
let exceeded = false;
stream.on('data', chunk => {
data += chunk;
if (data.length >= limit) {
exceeded = true;
stream.destroy();
}
});
stream.on('error', err => reject(err));
stream.on('close', () => {
if (exceeded) {
// If file exceeds scan limit, treat as unsafe
resolve({ text: data.slice(0, limit), complete: false });
} else {
resolve({ text: data, complete: true });
}
});
} catch (e) {
reject(e);
}
});
// Helper: quick content safety checks for HTML/SVG/XML
const containsJsOrXmlBombs = (text) => {
if (!text) return false;
const t = text.toLowerCase();
// JavaScript execution vectors
const patterns = [
/