在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());