在Debian系统上设置Node.js环境并确保其安全性是一个重要的步骤。以下是一个详细的指南,涵盖了从安装Node.js到安全配置的各个方面:
sudo apt-get update
sudo apt-get install nodejs
node -v npm -v
const mongoose = require('mongoose');
const userSchema = new mongoose.Schema({
username: { type: String, required: true },
email: { type: String, required: true, unique: true },
password: { type: String, required: true }
});
const bcrypt = require('bcrypt');
const saltRounds = 10;
userSchema.pre('save', function (next) {
if (!this.isModified('password')) return next();
bcrypt.hash(this.password, saltRounds, (err, hash) => {
if (err) return next(err);
this.password = hash;
next();
});
});
express-rate-limit
来限制客户端发送的请求数量。const rateLimit = require("express-rate-limit");
const limiter = rateLimit({
windowMs: 15 * 60 * 1000, // 15 minutes
max: 100 // limit each IP to 100 requests per windowMs
});
app.use(limiter);
const cors = require('cors');
app.use(cors({
origin: 'https://yourwebsite.com', // 只允许来自特定域的请求
credentials: true, // 允许携带cookies等凭证信息
optionsSuccessStatus: 200 // 让预检请求返回200状态码
}));
app.use((err, req, res, next) => {
console.error(err.stack); // 记录错误到日志文件
res.status(500).send('Something went wrong!'); // 向用户显示通用错误消息
});
helmet
这样的库来设置适当的HTTP头部以防止跨站脚本攻击(XSS)。const helmet = require('helmet');
app.use(helmet());
csurf
这样的中间件来防止跨站请求伪造(CSRF)攻击。const csurf = require('csurf');
app.use(csurf());