Repository navigation
Expand file tree
/
Copy pathserver.js
More file actions
200 lines (167 loc) · 6.6 KB
/
Copy pathserver.js
File metadata and controls
200 lines (167 loc) · 6.6 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
194
195
196
197
198
199
200
/**
* Strava Auto Activity Generator - Main Server
*/
require('dotenv').config();
const express = require('express');
const path = require('path');
const cors = require('cors');
const helmet = require('helmet');
const rateLimit = require('express-rate-limit');
const cookieParser = require('cookie-parser');
const authRoutes = require('./src/routes/auth');
const publicApiRoutes = require('./src/routes/publicApi');
const apiRoutes = require('./src/routes/api');
const db = require('./src/db/database');
const scheduler = require('./src/services/scheduler');
const { authenticateToken, requirePageAuth } = require('./src/middleware/auth');
const app = express();
const PORT = process.env.PORT || 3000;
// Trust proxy for accurate client IP behind 1Panel/Nginx/LiteSpeed
app.set('trust proxy', 1);
// Advanced Security Headers
app.use(helmet({
contentSecurityPolicy: false, // Disabled for simplicity with inline scripts/styles in this UI
}));
// Basic Security Headers for caching & CSP
app.use((req, res, next) => {
res.setHeader('Cache-Control', 'no-store, no-cache, must-revalidate, private');
res.setHeader('Content-Security-Policy', "default-src 'self' https: 'unsafe-inline' 'unsafe-eval'; img-src 'self' https: data: blob:; font-src 'self' https: data:; connect-src 'self' https: wss: ws:;");
next();
});
// Global Rate Limiting (Prevent DDoS)
const globalLimiter = rateLimit({
windowMs: 15 * 60 * 1000, // 15 minutes
max: 1000, // Headroom for dashboard assets, polling, and generation bursts while still bounding abuse
message: { error: 'Too many requests from this IP, please try again later.', code: 'GLOBAL_RATE_LIMIT_EXCEEDED' },
statusCode: 429,
standardHeaders: true,
legacyHeaders: false,
});
app.use(globalLimiter);
// Anti-Brute Force for Authentication (Login)
const authLoginLimiter = rateLimit({
windowMs: 15 * 60 * 1000, // 15 minutes
max: 5, // Limit each IP to 5 failed auth attempts per windowMs
skipSuccessfulRequests: true, // Only count failed attempts
message: { error: 'Too many failed login attempts, your IP has been temporarily locked out.', code: 'AUTH_BRUTE_FORCE_LOCKOUT' },
statusCode: 429,
standardHeaders: true,
legacyHeaders: false,
});
// Prevention of registration spam
const authRegisterLimiter = rateLimit({
windowMs: 15 * 60 * 1000, // 15 minutes
max: 5, // Limit each IP to 5 registrations per windowMs
message: { error: 'Too many registration attempts from this IP, please try again later.', code: 'AUTH_REGISTER_LIMIT_EXCEEDED' },
statusCode: 429,
standardHeaders: true,
legacyHeaders: false,
});
// Limit OAuth & connection actions to prevent loop abuse
const authGeneralLimiter = rateLimit({
windowMs: 15 * 60 * 1000, // 15 minutes
max: 15, // Limit each IP to 15 connection requests per windowMs
message: { error: 'Too many auth connection attempts from this IP, please try again later.', code: 'AUTH_GENERAL_LIMIT_EXCEEDED' },
statusCode: 429,
standardHeaders: true,
legacyHeaders: false,
});
app.use(cookieParser());
app.use(cors({
origin: process.env.BASE_URL || 'http://localhost:3000',
credentials: true
}));
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
// Serve login and register pages unauthenticated
app.get('/login.html', (req, res) => {
res.sendFile(path.join(__dirname, 'public', 'login.html'));
});
app.get('/register.html', (req, res) => {
res.sendFile(path.join(__dirname, 'public', 'register.html'));
});
// Explicitly serve district data GeoJSON
app.get('/geo/hanoi_urban_districts.geojson', (req, res) => {
res.sendFile(path.join(__dirname, 'public', 'geo', 'hanoi_urban_districts.geojson'));
});
// Favicon handler: fallback to runner.svg
app.get('/favicon.ico', (req, res) => {
res.sendFile(path.join(__dirname, 'public', 'icons', 'runner.svg'));
});
// Health check endpoint (public)
app.get('/health', (req, res) => {
res.json({ status: 'ok', uptime: process.uptime() });
});
// Serve static files with strict no-cache headers to ensure clients always get latest assets
app.use(express.static(path.join(__dirname, 'public'), {
index: false,
setHeaders: (res) => {
res.setHeader('Cache-Control', 'no-cache, no-store, must-revalidate, max-age=0');
res.setHeader('Pragma', 'no-cache');
res.setHeader('Expires', '0');
}
}));
// Routes
// Apply strict brute force protection and rate limiters to authentication endpoints
app.use('/auth/system/login', authLoginLimiter);
app.use('/auth/system/register', authRegisterLimiter);
app.use('/auth/connect', authGeneralLimiter);
app.use('/auth/callback', authGeneralLimiter);
app.use('/auth/disconnect', authGeneralLimiter);
// Auth Routes (connect, callback, login, logout are public, others might need auth)
app.use('/auth', authRoutes);
// Public API Routes (Token Authenticated)
app.use('/api/public', publicApiRoutes);
// Protect API routes
app.use('/api', authenticateToken, apiRoutes);
// Serve main page (protected)
app.get('/', requirePageAuth, (req, res) => {
res.sendFile(path.join(__dirname, 'public', 'index.html'));
});
// Start server
const server = app.listen(PORT, async () => {
console.log(`\n${'═'.repeat(60)}`);
console.log(` 🏃 Strava Auto Activity Generator`);
console.log(` 📡 Server running at http://localhost:${PORT}`);
console.log(`${'═'.repeat(60)}\n`);
// Initialize scheduler on startup
try {
await scheduler.startAllSchedulers();
console.log(' ⏰ Multi-tenant schedulers initialized');
} catch (err) {
console.error(' ⏰ Scheduler initialization skipped:', err.message);
}
console.log('');
});
// Graceful shutdown handler
const handleShutdown = async (signal) => {
console.log(`\n[Server] Received ${signal}, starting graceful shutdown...`);
// Stop all scheduler cron tasks and wait for running jobs
try {
await scheduler.stopAll();
} catch (err) {
console.error('[Server] Error stopping schedulers:', err.message);
}
server.close(async () => {
console.log('[Server] HTTP server closed.');
try {
if (db.closeDb) await db.closeDb();
} catch (e) {
console.error('[Server] Error closing database:', e.message);
}
process.exit(0);
});
// Force shutdown after 10 seconds
setTimeout(() => {
console.warn('[Server] Graceful shutdown timeout reached, force exiting...');
process.exit(1);
}, 10000);
};
process.on('SIGTERM', () => handleShutdown('SIGTERM'));
process.on('SIGINT', () => handleShutdown('SIGINT'));
process.on('unhandledRejection', (reason, promise) => {
console.error('[Server] Unhandled Rejection at:', promise, 'reason:', reason);
});
process.on('uncaughtException', (err) => {
console.error('[Server] Uncaught Exception:', err);
});