-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathclient-proxy.js
More file actions
445 lines (378 loc) · 13.4 KB
/
Copy pathclient-proxy.js
File metadata and controls
445 lines (378 loc) · 13.4 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
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
/**
* Client-Side Proxy - Runs on the weak 2G device with Firefox
*
* This proxy runs on localhost and Firefox connects to it.
* It intercepts requests, compresses them, sends to backend server over 2G,
* receives compressed responses, decompresses them, and sends to Firefox.
*
* Firefox Proxy Settings:
* HTTP Proxy: localhost:8080
* HTTPS Proxy: localhost:8080
*/
const http = require('http');
const net = require('net');
const path = require('path');
const fs = require('fs');
// Load config from .env (manual parser - no dotenv dependency)
const loadEnv = () => {
try {
const envFilePath = path.join(__dirname, '.env');
if (fs.existsSync(envFilePath)) {
const envContent = fs.readFileSync(envFilePath, 'utf8');
const env = {};
envContent.split('\n').forEach(line => {
const trimmed = line.trim();
if (trimmed && !trimmed.startsWith('#')) {
const [key, ...val] = trimmed.split('=');
if (key) env[key.trim()] = val.join('=').trim();
}
});
return env;
}
} catch (err) {
console.error('Failed to load .env:', err.message);
}
return {};
};
const envConfig = loadEnv();
const CLIENT_PORT = process.env.CLIENT_PORT || envConfig.CLIENT_PORT || 8080;
const CLIENT_HOST = process.env.CLIENT_HOST || envConfig.CLIENT_HOST || '127.0.0.1';
const BACKEND_SERVER = process.env.BACKEND_SERVER || envConfig.BACKEND_SERVER || 'localhost:9000';
const LOG_VERBOSE = (process.env.LOG_VERBOSE || envConfig.LOG_VERBOSE) === 'true';
const LOG_TRAFFIC = (process.env.LOG_TRAFFIC || envConfig.LOG_TRAFFIC) === 'true';
const BACKEND_REQUEST_TIMEOUT_MS = Number(process.env.BACKEND_REQUEST_TIMEOUT_MS || envConfig.BACKEND_REQUEST_TIMEOUT_MS || 60000);
const CONNECT_HANDSHAKE_TIMEOUT_MS = Number(process.env.CONNECT_HANDSHAKE_TIMEOUT_MS || envConfig.CONNECT_HANDSHAKE_TIMEOUT_MS || 60000);
const SHUTDOWN_GRACE_MS = Number(process.env.SHUTDOWN_GRACE_MS || envConfig.SHUTDOWN_GRACE_MS || 5000);
// Parse backend server
const [backendHost, backendPort] = BACKEND_SERVER.split(':');
function log(level, message, data = null) {
const timestamp = new Date().toISOString();
const logMsg = `[${timestamp}] [${level.toUpperCase()}] ${message}`;
if (data) {
console.log(logMsg);
console.log(JSON.stringify(data, null, 2));
} else {
console.log(logMsg);
}
}
function createClientProxy() {
const activeSockets = new Set();
const activeTunnelSockets = new Set();
let isShuttingDown = false;
const trackSocket = (socket, collection) => {
collection.add(socket);
socket.on('close', () => collection.delete(socket));
};
const server = http.createServer(async (clientReq, clientRes) => {
const startTime = Date.now();
try {
// Get the full URL that Firefox wants
const targetUrl = clientReq.url;
log('info', `🔗 CLIENT REQUEST FROM FIREFOX`, {
method: clientReq.method,
url: targetUrl,
headers: LOG_VERBOSE ? clientReq.headers : '(hidden)',
});
// Create request to backend server
const backendReq = http.request(
{
hostname: backendHost,
port: backendPort || 9000,
path: targetUrl,
method: clientReq.method,
headers: {
...clientReq.headers,
'X-Forwarded-For': '127.0.0.1',
},
},
(backendRes) => {
const duration = Date.now() - startTime;
log('info', `📦 CLIENT GOT RESPONSE FROM BACKEND`, {
status: backendRes.statusCode,
duration_ms: duration,
contentType: backendRes.headers['content-type'],
});
// Forward response headers to Firefox
const headers = { ...backendRes.headers };
// Log size info if available
if (headers['x-original-size'] && headers['x-compressed-size']) {
const original = parseInt(headers['x-original-size']);
const compressed = parseInt(headers['x-compressed-size']);
const ratio = Math.round((1 - compressed / original) * 100);
log('info', `📊 COMPRESSION RATIO`, {
original_bytes: original,
compressed_bytes: compressed,
savings_percent: `${ratio}%`,
});
}
if (LOG_VERBOSE) {
log('debug', `Response headers from backend:`, headers);
}
// Remove backend-specific headers
delete headers['x-original-size'];
delete headers['x-compressed-size'];
delete headers['x-forwarded-for'];
clientRes.writeHead(backendRes.statusCode, headers);
let sentBytes = 0;
backendRes.on('data', (chunk) => {
sentBytes += chunk.length;
if (LOG_TRAFFIC) {
log('debug', `📤 Sent ${chunk.length} bytes to Firefox`);
}
});
backendRes.on('end', () => {
log('debug', `✓ Response piped to Firefox (${sentBytes} bytes sent)`);
});
backendRes.pipe(clientRes);
}
);
backendReq.on('error', (err) => {
log('error', `❌ BACKEND CONNECTION ERROR`, {
error: err.message,
code: err.code,
hostname: backendHost,
port: backendPort,
stack: LOG_VERBOSE ? err.stack : undefined,
});
if (clientRes.writableEnded || clientRes.destroyed) return;
if (!clientRes.headersSent) {
clientRes.writeHead(502, { 'content-type': 'application/json' });
clientRes.end(JSON.stringify({
error: 'Bad Gateway',
message: err.message,
backend: `${backendHost}:${backendPort}`,
}, null, 2));
} else {
clientRes.destroy();
}
});
backendReq.on('timeout', () => {
log('error', `⏱️ BACKEND TIMEOUT`, {
url: targetUrl,
timeout_ms: BACKEND_REQUEST_TIMEOUT_MS,
});
backendReq.destroy(new Error('Backend request timeout'));
if (clientRes.writableEnded || clientRes.destroyed) return;
if (!clientRes.headersSent) {
clientRes.writeHead(504, { 'content-type': 'text/plain' });
clientRes.end('Gateway Timeout');
} else {
clientRes.destroy();
}
});
backendReq.setTimeout(BACKEND_REQUEST_TIMEOUT_MS);
// Forward request body
clientReq.pipe(backendReq);
} catch (err) {
log('error', `❌ CLIENT HANDLER EXCEPTION`, {
error: err.message,
url: targetUrl,
stack: LOG_VERBOSE ? err.stack : undefined,
});
clientRes.writeHead(500);
clientRes.end(JSON.stringify({
error: 'Internal Server Error',
message: err.message,
}, null, 2));
}
});
// Handle CONNECT for HTTPS tunneling
server.on('connect', (clientReq, clientSocket, head) => {
const startTime = Date.now();
const parts = clientReq.url.split(':');
const hostname = parts[0];
const targetPort = parseInt(parts[1]) || 443;
log('info', `🔐 CLIENT HTTPS CONNECT`, {
hostname,
port: targetPort,
backend_target: `${backendHost}:${backendPort}`,
});
try {
// Create HTTP CONNECT request to backend (NOT raw socket!)
const backendReq = http.request({
hostname: backendHost,
port: backendPort || 9000,
method: 'CONNECT',
path: `${hostname}:${targetPort}`,
headers: {
'Host': `${hostname}:${targetPort}`,
},
});
backendReq.on('connect', (backendRes, backendSocket, backendHead) => {
const duration = Date.now() - startTime;
trackSocket(clientSocket, activeTunnelSockets);
trackSocket(backendSocket, activeTunnelSockets);
log('debug', `✓ Backend responded to CONNECT`, {
statusCode: backendRes.statusCode,
duration_ms: duration,
});
if (backendRes.statusCode !== 200) {
log('error', `❌ Backend rejected CONNECT`, {
statusCode: backendRes.statusCode,
hostname,
port: targetPort,
});
if (!clientSocket.destroyed) {
clientSocket.write(`HTTP/1.1 ${backendRes.statusCode} Bad Gateway\r\n\r\n`);
clientSocket.end();
}
backendSocket.destroy();
return;
}
// For CONNECT, send 200 to browser and then switch to raw tunnel mode.
clientSocket.write('HTTP/1.1 200 Connection Established\r\n\r\n', () => {
log('debug', `✓ Sent 200 to Firefox - starting tunnel`);
clientSocket.setKeepAlive(true, 30000);
backendSocket.setKeepAlive(true, 30000);
clientSocket.setTimeout(0);
backendSocket.setTimeout(0);
clientSocket.on('error', (err) => {
log('error', `❌ CLIENT SOCKET ERROR in tunnel`, {
hostname,
port: targetPort,
error: err.message,
});
backendSocket.destroy();
});
backendSocket.on('error', (err) => {
log('error', `❌ BACKEND SOCKET ERROR in tunnel`, {
hostname,
port: targetPort,
error: err.message,
});
clientSocket.destroy();
});
clientSocket.pipe(backendSocket);
backendSocket.pipe(clientSocket);
if (head && head.length > 0) {
backendSocket.write(head);
}
if (backendHead && backendHead.length > 0) {
clientSocket.write(backendHead);
}
});
});
backendReq.on('error', (err) => {
const duration = Date.now() - startTime;
log('error', `❌ BACKEND CONNECT ERROR`, {
hostname,
port: targetPort,
error: err.message,
code: err.code,
duration_ms: duration,
stack: LOG_VERBOSE ? err.stack : undefined,
});
clientSocket.write('HTTP/1.1 502 Bad Gateway\r\n\r\n');
clientSocket.end();
});
clientSocket.on('error', (err) => {
log('error', `❌ CLIENT CONNECT ERROR`, {
hostname,
port: targetPort,
error: err.message,
stack: LOG_VERBOSE ? err.stack : undefined,
});
backendReq.destroy();
});
backendReq.on('timeout', () => {
log('error', `⏱️ CONNECT TIMEOUT`, {
hostname,
port: targetPort,
timeout_ms: CONNECT_HANDSHAKE_TIMEOUT_MS,
});
backendReq.destroy(new Error('CONNECT timeout'));
if (!clientSocket.destroyed) {
clientSocket.write('HTTP/1.1 504 Gateway Timeout\r\n\r\n');
clientSocket.end();
}
});
backendReq.setTimeout(CONNECT_HANDSHAKE_TIMEOUT_MS);
// Send the CONNECT request (this is what triggers backend's server.on('connect'))
backendReq.end();
} catch (err) {
log('error', `❌ HTTPS CONNECT EXCEPTION`, {
hostname,
port: targetPort,
error: err.message,
stack: LOG_VERBOSE ? err.stack : undefined,
});
clientSocket.write('HTTP/1.1 500 Internal Server Error\r\n\r\n');
clientSocket.end();
}
});
server.listen(CLIENT_PORT, CLIENT_HOST, () => {
log('info', `🔗 CLIENT PROXY STARTED`, {
host: CLIENT_HOST,
port: CLIENT_PORT,
verbose_logging: LOG_VERBOSE,
traffic_logging: LOG_TRAFFIC,
backend_request_timeout_ms: BACKEND_REQUEST_TIMEOUT_MS,
connect_handshake_timeout_ms: CONNECT_HANDSHAKE_TIMEOUT_MS,
shutdown_grace_ms: SHUTDOWN_GRACE_MS,
});
log('info', `📱 Firefox Proxy Configuration`, {
http_proxy: `${CLIENT_HOST}:${CLIENT_PORT}`,
https_proxy: `${CLIENT_HOST}:${CLIENT_PORT}`,
backend_server: BACKEND_SERVER,
});
});
server.on('connection', (socket) => {
trackSocket(socket, activeSockets);
if (isShuttingDown) {
socket.destroy();
}
});
server.on('error', (err) => {
log('error', `❌ SERVER ERROR`, {
error: err.message,
code: err.code,
stack: LOG_VERBOSE ? err.stack : undefined,
});
});
const shutdown = (signal) => {
if (isShuttingDown) {
log('info', `⏹️ Shutdown already in progress`, { signal });
return;
}
isShuttingDown = true;
log('info', `⏹️ Shutting down client proxy...`, { signal });
server.close(() => {
log('info', `✓ Client proxy closed`);
process.exit(0);
});
for (const socket of activeTunnelSockets) {
socket.end();
}
for (const socket of activeSockets) {
socket.end();
}
const forceCloseTimer = setTimeout(() => {
log('warn', `⚠️ Force closing remaining sockets`, {
active_connections: activeSockets.size,
active_tunnels: activeTunnelSockets.size,
});
for (const socket of activeTunnelSockets) {
socket.destroy();
}
for (const socket of activeSockets) {
socket.destroy();
}
process.exit(0);
}, SHUTDOWN_GRACE_MS);
forceCloseTimer.unref();
};
process.once('SIGINT', () => shutdown('SIGINT'));
process.once('SIGTERM', () => shutdown('SIGTERM'));
process.on('uncaughtException', (err) => {
log('error', `❌ UNCAUGHT EXCEPTION`, {
error: err.message,
stack: err.stack,
});
process.exit(1);
});
return server;
}
if (require.main === module) {
createClientProxy();
}
module.exports = { createClientProxy };