const { spawn, execFile } = require('child_process');
// SECURE: spawn() with argument array, no shell
app.post('/convert', (req, res) => {
const filename = req.body.filename;
// Validate filename
if (!isValidFilename(filename)) {
return res.status(400).send('Invalid filename');
}
const child = spawn('convert', [filename, 'output.pdf']);
child.on('error', (error) => {
console.error('Process error:', error);
return res.status(500).send('Conversion failed');
});
child.on('close', (code) => {
if (code === 0) {
res.send('File converted');
} else {
res.status(500).send('Conversion failed');
}
});
});
function isValidFilename(filename) {
// Strict allowlist validation
const pattern = /^[a-zA-Z0-9._-]+\.(jpg|png|gif|pdf)$/;
return pattern.test(filename) && filename.length <= 255;
}
// SECURE: Allowlist of commands
const ALLOWED_OPERATIONS = {
'list': ['ls', ['-la']],
'status': ['git', ['status']],
'info': ['uname', ['-a']]
};
app.post('/process', (req, res) => {
const operation = req.body.operation;
if (!ALLOWED_OPERATIONS[operation]) {
return res.status(400).send('Invalid operation');
}
const [command, args] = ALLOWED_OPERATIONS[operation];
execFile(command, args, (error, stdout, stderr) => {
if (error) {
console.error('Error:', error);
return res.status(500).send('Operation failed');
}
res.send(stdout);
});
});