-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathserver.ts
More file actions
193 lines (170 loc) · 6.1 KB
/
Copy pathserver.ts
File metadata and controls
193 lines (170 loc) · 6.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
// server.ts (Refactored)
import './lib/env.js' // Triggers validation immediately
import express, { type RequestHandler } from 'express'
import { createServer } from 'http'
import next from 'next'
import { env } from './lib/env.js' // New import
import { httpLogger } from './utils/logger.server.js'
import logger from './utils/logger.server.js'
import { AppServices, createServices } from './lib/services.js' // New import
import { WebSocketManager } from './lib/websocket.js' // New import
import { initSocketManager, resetSocketManager } from './utils/socketManager.js'
import { StateSnapshot } from './types/websocket.js'
import { Socket } from 'net'
import { checkTimerService, checkWebSocketService } from './lib/healthCheck.js'
import rateLimit from 'express-rate-limit'
import path from 'path'
const app = next({
dev: env.NODE_ENV !== 'production',
dir: process.cwd(),
hostname: env.HOST,
port: env.PORT,
})
const handle = app.getRequestHandler()
const expressApp = express()
app.prepare().then(async () => {
const server = createServer(expressApp)
// --- Logger Setup ---
// Must be the first middleware to capture all requests
expressApp.use(httpLogger as RequestHandler)
// Global body parsing is intentionally omitted here.
// Next.js API routes handle their own body parsing, and adding a global
// `express.json()` middleware can cause conflicts, such as the
// "TypeError: Response body object should not be disturbed or locked" error,
// by attempting to parse the request body twice.
// --- Rate Limiting Setup ---
if (env.NODE_ENV !== 'test') {
const spotifyApiLimiter = rateLimit({
windowMs: env.RATE_LIMIT_WINDOW_MS,
max: env.SPOTIFY_API_MAX_REQUESTS,
standardHeaders: true,
legacyHeaders: false,
keyGenerator: (req) => {
return (
(req.headers['x-forwarded-for'] as string)?.split(',')[0] ||
req.socket.remoteAddress ||
'unknown'
)
},
message: {
error: 'Too many requests to Spotify API, please try again later.',
},
})
const internalApiLimiter = rateLimit({
windowMs: env.RATE_LIMIT_WINDOW_MS,
max: env.INTERNAL_API_MAX_REQUESTS,
standardHeaders: true,
legacyHeaders: false,
keyGenerator: (req) => {
return (
(req.headers['x-forwarded-for'] as string)?.split(',')[0] ||
req.socket.remoteAddress ||
'unknown'
)
},
message: {
error: 'Too many requests to internal API, please try again later.',
},
})
const generalApiLimiter = rateLimit({
windowMs: env.RATE_LIMIT_WINDOW_MS,
max: env.GENERAL_API_MAX_REQUESTS,
standardHeaders: true,
legacyHeaders: false,
keyGenerator: (req) => {
return (
(req.headers['x-forwarded-for'] as string)?.split(',')[0] ||
req.socket.remoteAddress ||
'unknown'
)
},
message: { error: 'Too many requests, please try again later.' },
skip: (req) =>
req.path.startsWith('/api/spotify') ||
req.path.startsWith('/api/internal'),
})
// Apply the rate limiters to specific routes
expressApp.use('/api/spotify/', spotifyApiLimiter)
expressApp.use('/api/internal/', internalApiLimiter)
expressApp.use('/api/', generalApiLimiter)
}
// --- Static Asset Serving (Production Only) ---
if (env.NODE_ENV === 'production') {
const isDeployment = process.env.IS_DEPLOYMENT === 'true'
const nextDir = isDeployment ? '.next_prod' : '.next'
const staticPath = path.join(process.cwd(), nextDir, 'static')
expressApp.use(
'/_next/static',
express.static(staticPath, {
immutable: true,
maxAge: '1y',
})
)
}
// WebSocket Infrastructure
const wsManager = new WebSocketManager()
// Services
const services: AppServices = await createServices(
wsManager.createBroadcaster()
)
// Socket Logic
const getUnifiedStateSnapshot = (): StateSnapshot => ({
timerData: services.tabataService.getState(),
spotifyData: services.spotifyService.getState(),
spotifyServiceInitialized: services.isSpotifyInitialized,
})
initSocketManager(wsManager.wss, getUnifiedStateSnapshot, services)
// Routes
expressApp.get('/api/health', (_req, res) => {
res.status(200).json({ status: 'ok' })
})
// POST /api/debug/reset - Reset the server-side HRM session state (for testing)
// Gated to prevent accidental use in production
expressApp.post('/api/debug/reset', (_req, res) => {
if (env.NODE_ENV === 'production' && !env.ALLOW_DEBUG_RESET) {
return res
.status(403)
.json({ error: 'Debug reset not allowed in production' })
}
resetSocketManager()
logger.info('Server-side HRM state has been reset via /api/debug/reset')
return res.status(200).json({ status: 'reset' })
})
expressApp.get('/api/internal/health/services', async (_req, res) => {
const timerCheck = checkTimerService(services.tabataService)
const wsCheck = await checkWebSocketService()
const healthy = timerCheck.healthy && wsCheck.healthy
const details = {
timer: timerCheck,
websocket: wsCheck,
}
res.status(200).json({ healthy, details })
})
expressApp.use((req, res) => handle(req, res))
// Upgrade Handling
const wsConnections = new Map<string, number>()
server.on('upgrade', (req, socket, head) => {
const ip =
(req.headers['x-forwarded-for'] as string)?.split(',').shift()?.trim() ||
req.socket.remoteAddress
if (env.NODE_ENV !== 'test' && ip) {
const count = wsConnections.get(ip) || 0
if (count >= env.WS_MAX_CONNECTIONS) {
socket.write('HTTP/1.1 429 Too Many Requests\r\n\r\n')
socket.destroy()
return
}
wsConnections.set(ip, count + 1)
socket.on('close', () => {
const currentCount = wsConnections.get(ip) || 0
if (currentCount > 0) {
wsConnections.set(ip, currentCount - 1)
}
})
}
wsManager.handleUpgrade(req, socket as Socket, head)
})
server.listen(env.PORT, () => {
logger.info(`> Ready on http://${env.HOST}:${env.PORT}`)
})
})