Spaces:
Sleeping
Sleeping
| /** | |
| * Express服务入口 - 安全加固版 | |
| * LongShu/右枢 HF Space Backend | |
| */ | |
| import express from 'express'; | |
| import cors from 'cors'; | |
| import compression from 'compression'; | |
| import path from 'path'; | |
| import { gatewayAuth } from './middleware/auth'; | |
| import { errorHandler } from './middleware/errorHandler'; | |
| import { initCookieParser, requireAdmin, requireAdminApi } from './middleware/adminAuth'; | |
| import chatRouter from './routes/chat'; | |
| import healthRouter from './routes/health'; | |
| import dashboardRouter from './routes/dashboard'; | |
| import authRouter from './routes/auth'; | |
| import { startHeartbeatMonitor } from './lib/keepalive'; | |
| import { cleanupExpiredSessions } from './middleware/adminAuth'; | |
| const app = express(); | |
| const PORT = process.env.PORT || 3000; | |
| // ─── 全局中间件 ─── | |
| app.use(cors({ | |
| origin: [ | |
| 'https://chat.5e1.com', | |
| 'https://game.5e1.com', | |
| 'https://www.5e1.com', | |
| 'http://localhost:3000', | |
| 'http://localhost:3001', | |
| ], | |
| methods: ['GET', 'POST', 'OPTIONS'], | |
| allowedHeaders: ['Content-Type', 'x-5e1-secret', 'Authorization'], | |
| })); | |
| app.use(compression()); | |
| app.use(initCookieParser()); | |
| app.use(express.json({ limit: '10mb' })); | |
| app.use(express.urlencoded({ extended: true })); | |
| // ─── 静态文件 ─── | |
| app.use('/public', express.static(path.join(process.cwd(), 'public'))); | |
| // ─── 公开路由 ─── | |
| // 根路径 - 障眼法首页 | |
| app.get('/', (req, res) => { | |
| res.sendFile(path.join(process.cwd(), 'public', 'index.html')); | |
| }); | |
| // 登录页面 | |
| app.get('/login', (req, res) => { | |
| res.sendFile(path.join(process.cwd(), 'public', 'login.html')); | |
| }); | |
| // 健康检查(公开) | |
| app.use('/internal/health', healthRouter); | |
| // 登录 API(公开) | |
| app.use('/api/auth', authRouter); | |
| // ─── 保护路由 ─── | |
| // Dashboard 页面(Session 保护) | |
| app.get('/dashboard', requireAdmin, (req, res) => { | |
| res.sendFile(path.join(process.cwd(), 'public', 'dashboard.html')); | |
| }); | |
| // Dashboard API(Session 保护) | |
| app.use('/internal/dashboard', dashboardRouter); | |
| // ─── 内部通信路由(API Secret 保护) ─── | |
| // Chat API | |
| app.use('/internal/chat', gatewayAuth, chatRouter); | |
| // ─── 错误处理 ─── | |
| app.use(errorHandler); | |
| // ─── 启动服务 ─── | |
| app.listen(PORT, () => { | |
| console.log(`[Backend] Server running on port ${PORT}`); | |
| console.log(`[Backend] Environment: ${process.env.NODE_ENV || 'development'}`); | |
| // 启动心跳监控 | |
| startHeartbeatMonitor(); | |
| // 定期清理过期 Session(每小时) | |
| setInterval(cleanupExpiredSessions, 60 * 60 * 1000); | |
| }); | |
| export default app; |