-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
268 lines (227 loc) · 8.36 KB
/
Copy pathserver.js
File metadata and controls
268 lines (227 loc) · 8.36 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
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
// Main entry point - modular server
const fs = require('fs');
const path = require('path');
const https = require('https');
const express = require('express');
const config = require('./config');
const Router = require('./router');
const ProxyHandler = require('./proxy-handler');
const PluginSystem = require('./plugin-system');
const InstanceManager = require('./instance-manager');
const app = express();
// Initialize instance manager first (router depends on it)
const instanceManager = new InstanceManager('./instances.json');
const router = new Router(instanceManager);
const proxyHandler = new ProxyHandler();
const plugins = new PluginSystem(app, router, proxyHandler, instanceManager);
// API routes now handled by instance-manager plugin
// =========================
// SSL CONFIG
// =========================
const ssl = {
key: fs.readFileSync(config.SSL.keyPath),
cert: fs.readFileSync(config.SSL.certPath)
};
// =========================
// EXPRESS MIDDLEWARE (minimal for proxy performance)
// =========================
const cookieParser = require('cookie-parser');
app.use(cookieParser());
// Request logging
app.use((req, res, next) => {
console.log(`[${new Date().toISOString()}] ${req.method} ${req.url}`);
next();
});
// Instance and plugin middleware (lightweight)
app.use(instanceManager.middleware());
app.use(plugins.middleware());
// Body parsing only for API routes (not proxy)
// Applied specifically to API routes to avoid interfering with proxy body forwarding
const bodyParserJSON = express.json();
const bodyParserURL = express.urlencoded({ extended: true });
// Apply body parsers only to API routes
app.use('/_instances', bodyParserJSON, bodyParserURL);
app.use('/_plugins', bodyParserJSON, bodyParserURL);
app.use('/health', bodyParserJSON, bodyParserURL);
// =========================
// PROXY ROUTE HANDLER (registered after plugins in start())
// =========================
function setupProxyRoutes() {
app.all('*', (req, res) => {
// Skip if plugin or other handler already responded
if (res.headersSent) return;
const target = router.route(req);
req._target = target;
const isDiscord = target.startsWith('https://discord.com');
if (isDiscord) {
delete req.headers['accept-encoding'];
}
console.log(`[PROXY] ${req.method} ${req.url} → ${target} (Discord: ${isDiscord})`);
// Set timeout for proxy requests
req.socket.setTimeout(30000);
req.socket.on('timeout', () => {
console.error('Request timeout');
if (!res.headersSent) {
res.status(504).send('Gateway timeout');
}
req.socket.destroy();
});
// Check if target is valid
if (!target || target === 'undefined' || target === 'null') {
console.error('[Proxy] Invalid target for', req.url);
if (!res.headersSent) {
res.status(500).json({ error: 'Invalid upstream target' });
}
return;
}
let responseSent = false;
const originalEnd = res.end.bind(res);
res.end = function(...args) {
responseSent = true;
return originalEnd.apply(this, args);
};
const originalWriteHead = res.writeHead.bind(res);
res.writeHead = function(...args) {
if (!res.headersSent) {
return originalWriteHead.apply(this, args);
}
};
// Safety timeout - ensure we always send a response
const safetyTimeout = setTimeout(() => {
if (!responseSent && !res.headersSent) {
console.error('[Server] Safety timeout:', req.url);
try {
res.status(504).json({ error: 'Gateway timeout' });
} catch (e) {
console.error('[Server] Failed to send timeout response:', e.message);
}
}
}, 35000);
// Handle proxy completion/error
const onProxyDone = (err) => {
clearTimeout(safetyTimeout);
if (err && !responseSent && !res.headersSent) {
console.error('[Proxy] Error:', err.code || err.message, req.url, '→', target);
try {
res.status(502).json({ error: 'Bad gateway', code: err.code });
} catch (e) {
console.error('[Server] Failed to send error response:', e.message);
}
}
};
try {
proxyHandler.web(req, res, {
target,
changeOrigin: true,
selfHandleResponse: isDiscord,
timeout: 30000,
proxyTimeout: 30000
}, onProxyDone);
} catch (err) {
clearTimeout(safetyTimeout);
onProxyDone(err);
}
// Handle client disconnect
req.on('close', () => {
clearTimeout(safetyTimeout);
});
});
}
// Error handling
app.use((err, req, res, next) => {
console.error('Express error:', err);
if (!res.headersSent) {
res.status(500).send('Internal server error');
}
});
// =========================
// HTTPS SERVER + WEBSOCKET
// =========================
const server = https.createServer(ssl, app);
server.on('upgrade', (req, socket, head) => {
const target = router.route(req);
req._target = target;
console.log(`[WS] ${req.url} → ${target}`);
if (!target || target === 'undefined') {
console.error('[WS] Invalid target');
socket.destroy();
return;
}
// Set socket timeout for WebSocket
socket.setTimeout(60000);
socket.on('timeout', () => {
console.error('[WS] Socket timeout');
socket.destroy();
});
// Handle socket errors
socket.on('error', (err) => {
console.error('[WS] Socket error:', err.message);
socket.destroy();
});
try {
proxyHandler.ws(req, socket, head, { target });
} catch (err) {
console.error('[WS] Proxy error:', err.message);
socket.destroy();
}
});
// Clean up idle connections
server.on('connection', (socket) => {
socket.setTimeout(120000); // 2 minute idle timeout
socket.on('timeout', () => {
socket.end();
socket.destroy();
});
});
// =========================
// START
// =========================
function start() {
// Load all plugins from ./plugins directory
// (plugins register their routes via api.app.get() etc.)
plugins.loadAll();
// Now register proxy catch-all (plugins routes take precedence)
setupProxyRoutes();
server.listen(config.HTTPS_PORT, () => {
console.log(`🚀 Modular Express proxy server running: ${config.LOCAL_URL}`);
console.log(`🌐 Instances: ${instanceManager.listEnabled().length} enabled`);
instanceManager.listEnabled().forEach(i => console.log(` • ${i.id}: ${i.url}`));
console.log(`📦 Plugins: ${plugins.list().length} loaded`);
plugins.list().forEach(p => console.log(` • ${p.name} v${p.version}`));
console.log(' → /api, /gateway → Spacebar (via InstanceManager)');
console.log(' → /app, /login → Discord (rewritten)');
console.log(' → /_instances - Instance management API');
console.log(' → /_plugins/info - Plugin info endpoint');
});
}
// =========================
// GRACEFUL SHUTDOWN
// =========================
function gracefulShutdown(signal) {
console.log(`\n${signal} received. Shutting down gracefully...`);
// Close HTTPS server (stop accepting new connections)
server.close(() => {
console.log('HTTPS server closed');
});
// Destroy all active sockets
server.getConnections((err, count) => {
if (err) {
console.error('Error getting connections:', err);
} else {
console.log(`Closing ${count} active connections...`);
}
});
// Give connections a brief moment to close, then force exit
setTimeout(() => {
console.log('Forcing exit...');
process.exit(0);
}, 2000);
}
// Register signal handlers
process.on('SIGINT', () => gracefulShutdown('SIGINT'));
process.on('SIGTERM', () => gracefulShutdown('SIGTERM'));
// Auto-start if not imported
if (require.main === module) {
start();
}
module.exports = { app, server, router, proxyHandler, plugins, instanceManager, start };