在 Debian 上运行 Node.js 时,“安全加固”通常分为 系统层、Node 运行时、应用层、依赖与运维 四个方面。下面给出一套可落地的最佳实践。
避免使用未知 PPA:
# 使用 NodeSource(推荐)
curl -fsSL https://deb.nodesource.com/setup_20.x | bash -
apt install -y nodejs
或直接使用 Debian backports 中的版本。
useradd -r -s /usr/sbin/nologin nodeapp
ufw 或 nftablesufw allow 443/tcp
ufw enable
apt update && apt upgrade -y
unattended-upgrades
su nodeapp -s /bin/bash -c "node server.js"
或用 systemd:
[Service]
User=nodeapp
Group=nodeapp
避免使用 EOL 版本(如 Node 14/16)。
--disable-proto=delete 防止原型污染(Node 12+)npm audit
npm audit fix
使用:
npm ci(锁定版本)package-lock.json 提交到仓库进阶:
npx snyk test
使用 Express 时:
const helmet = require('helmet');
app.use(helmet());
防注入:
joi / zodexpress.json({ limit: '100kb' })
winston / pino[Service]
ExecStart=/usr/bin/node /opt/app/server.js
Restart=on-failure
NoNewPrivileges=true
ProtectSystem=strict
add_header Strict-Transport-Security "max-age=31536000";
node:20-slim✅ 非 root 运行
✅ LTS Node
✅ npm audit 0 高危
✅ helmet
✅ 输入校验
✅ TLS
✅ 自动更新
✅ 日志审计
如果你愿意,我可以:
你当前是哪种使用场景?(Web 服务 / CLI / 微服务)