diff --git a/README.md b/README.md index 4fa3aa9..3e290e6 100644 --- a/README.md +++ b/README.md @@ -62,9 +62,11 @@ psql -U forumlify -d forumlify -f schema.sql | 变量 | 默认值 | 说明 | |------|--------|------| -| `DATABASE_URL` | `postgresql://forumlify:123456@localhost:5432/forumlify` | PostgreSQL 连接串 | +| `DATABASE_URL` | `postgresql://forumlify:***@localhost:5432/forumlify` | PostgreSQL 连接串 | | `PORT` | `3000` | HTTP 监听端口 | -| `JWT_SECRET` | `forumlify-secret-key-change-me-in-production` | JWT 签名密钥,**生产环境务必修改** | +| `JWT_SECRET` | 本地开发使用内置值 | JWT 签名密钥;`NODE_ENV=production` 时必须显式设置 | +| `ALLOWED_ORIGINS` | 空 | 允许跨域访问的来源,多个值用逗号分隔;为空时仅支持同源访问 | +| `TRUST_PROXY` | `false` | 位于可信反向代理后时设为 `true`,用于正确识别限流 IP | 4. **启动** diff --git a/package-lock.json b/package-lock.json index b7740d6..0ed74ce 100644 --- a/package-lock.json +++ b/package-lock.json @@ -11,6 +11,8 @@ "bcrypt": "^5.1.1", "cors": "^2.8.5", "express": "^4.18.2", + "express-rate-limit": "8.1.0", + "helmet": "8.1.0", "jsonwebtoken": "^9.0.2", "multer": "^1.4.5-lts.1", "pg": "^8.11.3" @@ -542,6 +544,24 @@ "url": "https://opencollective.com/express" } }, + "node_modules/express-rate-limit": { + "version": "8.1.0", + "resolved": "https://registry.npmjs.org/express-rate-limit/-/express-rate-limit-8.1.0.tgz", + "integrity": "sha512-4nLnATuKupnmwqiJc27b4dCFmB/T60ExgmtDD7waf4LdrbJ8CPZzZRHYErDYNhoz+ql8fUdYwM/opf90PoPAQA==", + "license": "MIT", + "dependencies": { + "ip-address": "10.0.1" + }, + "engines": { + "node": ">= 16" + }, + "funding": { + "url": "https://github.com/sponsors/express-rate-limit" + }, + "peerDependencies": { + "express": ">= 4.11" + } + }, "node_modules/finalhandler": { "version": "1.3.2", "resolved": "https://registry.npmjs.org/finalhandler/-/finalhandler-1.3.2.tgz", @@ -738,6 +758,15 @@ "node": ">= 0.4" } }, + "node_modules/helmet": { + "version": "8.1.0", + "resolved": "https://registry.npmjs.org/helmet/-/helmet-8.1.0.tgz", + "integrity": "sha512-jOiHyAZsmnr8LqoPGmCjYAaiuWwjAPLgY8ZX2XrmHawt99/u1y6RgrZMTeoPfpUbV96HOalYgz1qzkRbw54Pmg==", + "license": "MIT", + "engines": { + "node": ">=18.0.0" + } + }, "node_modules/http-errors": { "version": "2.0.1", "resolved": "https://registry.npmjs.org/http-errors/-/http-errors-2.0.1.tgz", @@ -823,6 +852,15 @@ "integrity": "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==", "license": "ISC" }, + "node_modules/ip-address": { + "version": "10.0.1", + "resolved": "https://registry.npmjs.org/ip-address/-/ip-address-10.0.1.tgz", + "integrity": "sha512-NWv9YLW4PoW2B7xtzaS3NCot75m6nK7Icdv0o3lfMceJVRfSoQwqD4wEH5rLwoKJwUiZ/rfpiVBhnaF0FK4HoA==", + "license": "MIT", + "engines": { + "node": ">= 12" + } + }, "node_modules/ipaddr.js": { "version": "1.9.1", "resolved": "https://registry.npmjs.org/ipaddr.js/-/ipaddr.js-1.9.1.tgz", diff --git a/package.json b/package.json index d37aaa2..d44730c 100644 --- a/package.json +++ b/package.json @@ -11,8 +11,10 @@ "bcrypt": "^5.1.1", "cors": "^2.8.5", "express": "^4.18.2", + "express-rate-limit": "8.1.0", + "helmet": "8.1.0", "jsonwebtoken": "^9.0.2", "multer": "^1.4.5-lts.1", "pg": "^8.11.3" } -} \ No newline at end of file +} diff --git a/server.js b/server.js index 18f2df8..89d9e6e 100644 --- a/server.js +++ b/server.js @@ -5,6 +5,8 @@ const express = require('express'); const cors = require('cors'); +const helmet = require('helmet'); +const { rateLimit } = require('express-rate-limit'); const bcrypt = require('bcrypt'); const jwt = require('jsonwebtoken'); const { Pool } = require('pg'); @@ -19,7 +21,12 @@ const CONFIG = require('./config'); // 监听端口:环境变量 PORT 优先,其次 config.js 的 SERVER_PORT,最后默认 3000 const PORT = process.env.PORT || CONFIG.SERVER_PORT || 3000; -const JWT_SECRET = process.env.JWT_SECRET || 'forumlify-secret-key-change-me-in-production'; +const DEFAULT_JWT_SECRET = 'forumlify-secret-key-change-me-in-production'; +const JWT_SECRET = process.env.JWT_SECRET || DEFAULT_JWT_SECRET; + +if (process.env.NODE_ENV === 'production' && JWT_SECRET === DEFAULT_JWT_SECRET) { + throw new Error('JWT_SECRET must be set to a unique value in production'); +} // ============================================================ // 数据库 @@ -31,13 +38,56 @@ const pool = new Pool({ // ============================================================ // 中间件 // ============================================================ -app.use(cors()); -app.use(express.json()); -app.use(express.urlencoded({ extended: true })); +app.disable('x-powered-by'); +if (process.env.TRUST_PROXY === 'true') app.set('trust proxy', 1); + +// The existing UI relies on inline styles/scripts and a CDN-hosted Markdown +// parser, so CSP is left for a dedicated frontend migration. +app.use(helmet({ + contentSecurityPolicy: false, + crossOriginEmbedderPolicy: false, +})); + +const allowedOrigins = (process.env.ALLOWED_ORIGINS || '') + .split(',') + .map(origin => origin.trim()) + .filter(Boolean); +if (allowedOrigins.length > 0) { + app.use(cors({ + origin(origin, callback) { + if (!origin || allowedOrigins.includes(origin)) return callback(null, true); + return callback(new Error('Origin is not allowed by CORS')); + }, + })); +} + +const apiLimiter = rateLimit({ + windowMs: 15 * 60 * 1000, + limit: 300, + standardHeaders: 'draft-8', + legacyHeaders: false, + handler: (req, res) => res.status(429).json({ error: '请求过于频繁,请稍后重试' }), +}); +const authLimiter = rateLimit({ + windowMs: 15 * 60 * 1000, + limit: 20, + standardHeaders: 'draft-8', + legacyHeaders: false, + handler: (req, res) => res.status(429).json({ error: '尝试次数过多,请稍后重试' }), +}); + +app.use('/api', apiLimiter); +app.use(['/api/auth/login', '/api/auth/register', '/api/auth/reset-password'], authLimiter); +app.use(express.json({ limit: '100kb' })); +app.use(express.urlencoded({ extended: true, limit: '100kb' })); // 确保上传目录存在 if (!fs.existsSync('uploads')) fs.mkdirSync('uploads'); -app.use('/uploads', express.static('uploads')); +app.use('/uploads', express.static(path.join(__dirname, 'uploads'), { + dotfiles: 'deny', + fallthrough: false, + index: false, +})); // ============================================================ // 认证中间件 @@ -1401,15 +1451,37 @@ app.post('/api/auth/reset-password', async (req, res) => { }); // ============================================================ -// 托管前端文件 +// 托管公开前端文件 // ============================================================ -app.use(express.static('.')); +app.use('/js', express.static(path.join(__dirname, 'js'), { + dotfiles: 'deny', + fallthrough: false, + index: false, +})); +app.get('/style.css', (req, res) => res.sendFile(path.join(__dirname, 'style.css'))); +app.get('/config.js', (req, res) => res.sendFile(path.join(__dirname, 'config.js'))); app.get('*', (req, res) => { - if (!req.path.startsWith('/api')) { - res.sendFile(path.join(__dirname, 'index.html')); + if (req.path.startsWith('/api')) { + return res.status(404).json({ error: '接口不存在' }); } + if (path.extname(req.path)) { + return res.status(404).send('Not found'); + } + return res.sendFile(path.join(__dirname, 'index.html')); +}); + +app.use((err, req, res, next) => { + if (res.headersSent) return next(err); + if (err.type === 'entity.too.large') { + return res.status(413).json({ error: '请求内容过大' }); + } + if (err.message === 'Origin is not allowed by CORS') { + return res.status(403).json({ error: '不允许的跨域来源' }); + } + console.error(err); + return res.status(500).json({ error: '服务器错误' }); }); // ============================================================