在Ubuntu上部署Node.js應用時,保證其安全性至關重要。以下是一些關鍵的安全措施和最佳實踐:
sudo apt update && sudo apt upgrade -y
unattended-upgrades
包實現系統的自動更新。sudo apt install unattended-upgrades
sudo adduser deploy
sudo usermod -aG sudo deploy
sudo visudo
curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.38.0/install.sh | bash
source ~/.bashrc
nvm install node
npm config set registry https://registry.npm.taobao.org
npm audit
和 snyk
等工具定期檢查和更新項目的依賴項。npm audit fix
DOMPurify
、express-validator
來防止XSS、SQL注入等攻擊。const { check, validationResult } = require('express-validator');
app.post('/upload', [
check('filename').isLength({ min: 1 }).withMessage('File name must be at least 1 character long'),
check('content').isLength({ min: 1 }).withMessage('File content must be at least 1 character long')
], (req, res) => {
const errors = validationResult(req);
if (!errors.isEmpty()) {
return res.status(422).json({ errors: errors.array() });
}
// Process the file upload
});
const helmet = require('helmet');
app.use(helmet());
const https = require('https');
const fs = require('fs');
const options = {
key: fs.readFileSync('path/to/key.pem'),
cert: fs.readFileSync('path/to/cert.pem')
};
https.createServer(options, (req, res) => {
res.writeHead(200);
res.end('Hello world\n');
}).listen(443);
const bunyan = require('bunyan');
const log = bunyan.createLogger({
name: 'my-app',
level: bunyan.INFO,
streams: [{ stream: process.stdout }]
});
sudo aa-status