JavaScript/Node.js Security

JavaScript

JavaScript runs both client-side (XSS) and server-side (Node.js). Each environment has unique security concerns.

Client-Side XSS

xss-client.js
javascript
// VULNERABLE - innerHTML with user data
document.getElementById('output').innerHTML = userInput;

// VULNERABLE - document.write
document.write(userInput);

// VULNERABLE - eval
eval(userInput);

// VULNERABLE - jQuery html()
$('#output').html(userInput);

// SECURE - textContent (no HTML parsing)
document.getElementById('output').textContent = userInput;

// SECURE - jQuery text()
$('#output').text(userInput);

// React - Usually safe (auto-escapes)
// VULNERABLE - dangerouslySetInnerHTML
<div dangerouslySetInnerHTML={{__html: userInput}} />

// SECURE - Normal rendering
<div>{userInput}</div>

Node.js Vulnerabilities

nodejs-vulns.js
javascript
// VULNERABLE - Command injection
const exec = require('child_process').exec;
exec('ls ' + userInput);  // OS command injection

// SECURE - Use execFile with arguments array
const execFile = require('child_process').execFile;
execFile('ls', [userInput]);

// VULNERABLE - Path traversal
const path = require('path');
const file = path.join('/uploads', userInput);
fs.readFile(file);  // ../../../etc/passwd

// SECURE - Validate path stays in directory
const safePath = path.join('/uploads', path.basename(userInput));

// VULNERABLE - Prototype pollution
const merge = require('lodash').merge;
merge({}, JSON.parse('{"__proto__":{"admin":true}}'));

// VULNERABLE - eval in templates (EJS)
// <%- include(userInput) %>

// Check package.json for vulnerable dependencies
npm audit