node-proxylens 1.2.1 → 1.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +7 -0
- package/README.md +82 -27
- package/out/dist-obf/proxylens.js +61 -0
- package/package.json +14 -8
- package/bin/proxylens.js +0 -91
- package/index.js +0 -289
- package/lib/ProxyLens.js +0 -289
- package/lib/api.js +0 -51
- package/lib/commands/login.js +0 -24
- package/lib/commands/logout.js +0 -32
- package/lib/commands/whoami.js +0 -30
- package/lib/config.js +0 -30
- package/lib/constants.js +0 -15
- package/lib/modes/local.js +0 -86
- package/lib/modes/tunnel.js +0 -197
- package/lib/ui.js +0 -32
package/package.json
CHANGED
|
@@ -1,13 +1,15 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "node-proxylens",
|
|
3
|
-
"version": "1.
|
|
4
|
-
"description": "
|
|
5
|
-
"main": "lib/
|
|
3
|
+
"version": "1.3.0",
|
|
4
|
+
"description": "CLI for ProxyLens AI Traffic Inspector",
|
|
5
|
+
"main": "lib/index.js",
|
|
6
6
|
"bin": {
|
|
7
|
-
"proxylens": "
|
|
7
|
+
"proxylens": "out/dist-obf/proxylens.js"
|
|
8
8
|
},
|
|
9
9
|
"scripts": {
|
|
10
|
-
"
|
|
10
|
+
"build-dist": "esbuild src/bin/proxylens.js --bundle --platform=node --target=node18 --minify --outfile=out/dist/proxylens.js",
|
|
11
|
+
"obfuscate": "javascript-obfuscator out/dist/proxylens.js --output out/dist-obf/proxylens.js",
|
|
12
|
+
"build": "npm run build-dist && npm run obfuscate",
|
|
11
13
|
"publish": "npm publish"
|
|
12
14
|
},
|
|
13
15
|
"keywords": [
|
|
@@ -19,10 +21,14 @@
|
|
|
19
21
|
"cli"
|
|
20
22
|
],
|
|
21
23
|
"author": "ProxyLens AI",
|
|
22
|
-
"license": "
|
|
24
|
+
"license": "UNLICENSED",
|
|
23
25
|
"dependencies": {
|
|
24
|
-
"
|
|
26
|
+
"http-proxy": "^1.18.1",
|
|
25
27
|
"uuid": "^9.0.1",
|
|
26
|
-
"
|
|
28
|
+
"ws": "^8.16.0"
|
|
29
|
+
},
|
|
30
|
+
"devDependencies": {
|
|
31
|
+
"javascript-obfuscator": "^5.0.1",
|
|
32
|
+
"esbuild": "^0.19.0"
|
|
27
33
|
}
|
|
28
34
|
}
|
package/bin/proxylens.js
DELETED
|
@@ -1,91 +0,0 @@
|
|
|
1
|
-
#!/usr/bin/env node
|
|
2
|
-
|
|
3
|
-
const http = require('http');
|
|
4
|
-
const ProxyLens = require('../lib/ProxyLens');
|
|
5
|
-
const handleLogin = require('../lib/commands/login');
|
|
6
|
-
const handleLogout = require('../lib/commands/logout');
|
|
7
|
-
const handleWhoAmI = require('../lib/commands/whoami');
|
|
8
|
-
const { runLocalProxyMode } = require('../lib/modes/local');
|
|
9
|
-
const { verifyAndRunTunnel } = require('../lib/modes/tunnel');
|
|
10
|
-
const { logError } = require('../lib/ui');
|
|
11
|
-
|
|
12
|
-
// --- Argument Parsing ---
|
|
13
|
-
const args = process.argv.slice(2);
|
|
14
|
-
const command = args[0] ? args[0].trim() : null;
|
|
15
|
-
|
|
16
|
-
// --- Commands ---
|
|
17
|
-
if (command === 'login') {
|
|
18
|
-
handleLogin(args[1]);
|
|
19
|
-
return;
|
|
20
|
-
}
|
|
21
|
-
|
|
22
|
-
if (command === 'whoami') {
|
|
23
|
-
handleWhoAmI();
|
|
24
|
-
return;
|
|
25
|
-
}
|
|
26
|
-
|
|
27
|
-
if (command === 'logout') {
|
|
28
|
-
handleLogout();
|
|
29
|
-
return;
|
|
30
|
-
}
|
|
31
|
-
|
|
32
|
-
const flags = {};
|
|
33
|
-
let target = null;
|
|
34
|
-
let listenPort = 4152;
|
|
35
|
-
|
|
36
|
-
for (let i = 0; i < args.length; i++) {
|
|
37
|
-
if (args[i] === '-d') {
|
|
38
|
-
flags.subdomain = args[++i];
|
|
39
|
-
} else if (args[i] === '-u') {
|
|
40
|
-
flags.serverUrl = args[++i];
|
|
41
|
-
} else if (args[i] === '--domain') {
|
|
42
|
-
flags.rootDomain = args[++i];
|
|
43
|
-
} else if (!target) {
|
|
44
|
-
target = args[i];
|
|
45
|
-
} else if (!isNaN(args[i])) {
|
|
46
|
-
listenPort = parseInt(args[i]);
|
|
47
|
-
}
|
|
48
|
-
}
|
|
49
|
-
|
|
50
|
-
// Validation
|
|
51
|
-
if (!target) {
|
|
52
|
-
console.error('\nUsage: proxylens <target> [port] [-d subdomain] [--domain root_domain]');
|
|
53
|
-
console.error(' proxylens login <token>');
|
|
54
|
-
console.error(' proxylens logout');
|
|
55
|
-
console.error(' proxylens whoami\n');
|
|
56
|
-
process.exit(1);
|
|
57
|
-
}
|
|
58
|
-
|
|
59
|
-
if (/^\d+$/.test(target)) target = `http://localhost:${target}`;
|
|
60
|
-
if (!target.startsWith('http')) target = `http://${target}`;
|
|
61
|
-
|
|
62
|
-
// Sanity Check
|
|
63
|
-
try {
|
|
64
|
-
const url = new URL(target);
|
|
65
|
-
const hostname = url.hostname;
|
|
66
|
-
const looksLikeDomain = hostname.includes('.') || hostname === 'localhost' || hostname.includes(':');
|
|
67
|
-
|
|
68
|
-
if (!looksLikeDomain) {
|
|
69
|
-
if (hostname === 'login') {
|
|
70
|
-
console.error('\nUsage: proxylens login <token>\n');
|
|
71
|
-
process.exit(1);
|
|
72
|
-
}
|
|
73
|
-
logError(`Error: Invalid target '${hostname}'`);
|
|
74
|
-
console.error(`Target must be a port number, 'localhost', or a valid domain (e.g. example.com).\n`);
|
|
75
|
-
process.exit(1);
|
|
76
|
-
}
|
|
77
|
-
} catch (e) {
|
|
78
|
-
logError(`Error: Invalid URL format '${target}'\n`);
|
|
79
|
-
process.exit(1);
|
|
80
|
-
}
|
|
81
|
-
|
|
82
|
-
// --- Setup ProxyLens SDK ---
|
|
83
|
-
const uiServer = http.createServer();
|
|
84
|
-
const lens = new ProxyLens(uiServer, { historyLimit: 100, proxyTarget: target });
|
|
85
|
-
|
|
86
|
-
// --- Mode Selection ---
|
|
87
|
-
if (flags.subdomain) {
|
|
88
|
-
verifyAndRunTunnel(target, listenPort, uiServer, flags, lens);
|
|
89
|
-
} else {
|
|
90
|
-
runLocalProxyMode(target, listenPort, uiServer, lens);
|
|
91
|
-
}
|
package/index.js
DELETED
|
@@ -1,289 +0,0 @@
|
|
|
1
|
-
const WebSocket = require('ws');
|
|
2
|
-
const { v4: uuidv4 } = require('uuid');
|
|
3
|
-
|
|
4
|
-
class ProxyLens {
|
|
5
|
-
/**
|
|
6
|
-
* @param {import('http').Server} server - The HTTP server instance to attach WebSocket to
|
|
7
|
-
* @param {Object} options - Configuration options
|
|
8
|
-
* @param {number} options.historyLimit - Number of past requests to keep (default: 50)
|
|
9
|
-
* @param {string} options.proxyTarget - The target URL if running in proxy mode (optional)
|
|
10
|
-
*/
|
|
11
|
-
constructor(server, options = {}) {
|
|
12
|
-
this.history = [];
|
|
13
|
-
this.historyLimit = options.historyLimit || 50;
|
|
14
|
-
this.proxyTarget = options.proxyTarget;
|
|
15
|
-
|
|
16
|
-
this.wss = new WebSocket.Server({ server, path: '/_proxylens' });
|
|
17
|
-
|
|
18
|
-
this.wss.on('connection', (ws) => {
|
|
19
|
-
ws.isAlive = true;
|
|
20
|
-
ws.on('pong', () => { ws.isAlive = true; });
|
|
21
|
-
|
|
22
|
-
// Send history immediately upon connection
|
|
23
|
-
if (this.history.length > 0) {
|
|
24
|
-
ws.send(JSON.stringify(this.history));
|
|
25
|
-
}
|
|
26
|
-
|
|
27
|
-
// Handle incoming messages (e.g., REPLAY)
|
|
28
|
-
ws.on('message', async (data) => {
|
|
29
|
-
try {
|
|
30
|
-
const message = JSON.parse(data);
|
|
31
|
-
if (message.type === 'REPLAY' && message.request) {
|
|
32
|
-
await this.handleReplay(message.request);
|
|
33
|
-
}
|
|
34
|
-
} catch (e) {
|
|
35
|
-
console.error('Error handling WebSocket message:', e);
|
|
36
|
-
}
|
|
37
|
-
});
|
|
38
|
-
});
|
|
39
|
-
|
|
40
|
-
// Heartbeat to keep connections alive
|
|
41
|
-
const interval = setInterval(() => {
|
|
42
|
-
this.wss.clients.forEach((ws) => {
|
|
43
|
-
if (ws.isAlive === false) return ws.terminate();
|
|
44
|
-
ws.isAlive = false;
|
|
45
|
-
ws.ping();
|
|
46
|
-
});
|
|
47
|
-
}, 30000);
|
|
48
|
-
|
|
49
|
-
this.wss.on('close', () => clearInterval(interval));
|
|
50
|
-
}
|
|
51
|
-
|
|
52
|
-
/**
|
|
53
|
-
* Executes a request sent from the UI against the actual target
|
|
54
|
-
*/
|
|
55
|
-
async handleReplay(reqData) {
|
|
56
|
-
const id = uuidv4();
|
|
57
|
-
const start = Date.now();
|
|
58
|
-
|
|
59
|
-
// 1. Determine Target URL
|
|
60
|
-
let url;
|
|
61
|
-
if (this.proxyTarget) {
|
|
62
|
-
// CLI/Proxy Mode: We know exactly where to send it
|
|
63
|
-
try {
|
|
64
|
-
const baseUrl = this.proxyTarget.replace(/\/$/, '');
|
|
65
|
-
const path = reqData.path.startsWith('/') ? reqData.path : '/' + reqData.path;
|
|
66
|
-
url = baseUrl + path;
|
|
67
|
-
} catch(e) {
|
|
68
|
-
url = reqData.path;
|
|
69
|
-
}
|
|
70
|
-
} else {
|
|
71
|
-
// Middleware Mode: We assume the server is localhost unless Host header says otherwise
|
|
72
|
-
const host = reqData.headers['host'] || 'localhost';
|
|
73
|
-
const protocol = 'http'; // Assumption for local dev
|
|
74
|
-
url = `${protocol}://${host}${reqData.path}`;
|
|
75
|
-
}
|
|
76
|
-
|
|
77
|
-
// 2. Broadcast Pending State
|
|
78
|
-
this.broadcast({
|
|
79
|
-
id,
|
|
80
|
-
timestamp: start,
|
|
81
|
-
clientIp: 'Replay (UI)',
|
|
82
|
-
request: reqData,
|
|
83
|
-
pending: true
|
|
84
|
-
});
|
|
85
|
-
|
|
86
|
-
try {
|
|
87
|
-
// 3. Prepare Fetch Options
|
|
88
|
-
const headers = { ...reqData.headers };
|
|
89
|
-
// Remove headers that might cause issues in a replay context
|
|
90
|
-
delete headers['content-length'];
|
|
91
|
-
delete headers['host'];
|
|
92
|
-
delete headers['connection'];
|
|
93
|
-
|
|
94
|
-
const options = {
|
|
95
|
-
method: reqData.method,
|
|
96
|
-
headers: headers,
|
|
97
|
-
};
|
|
98
|
-
|
|
99
|
-
if (reqData.body && ['POST', 'PUT', 'PATCH', 'DELETE'].includes(reqData.method)) {
|
|
100
|
-
// Handle Data URI (Binary/Multipart)
|
|
101
|
-
if (typeof reqData.body === 'string' && reqData.body.startsWith('data:')) {
|
|
102
|
-
const commaIndex = reqData.body.indexOf(',');
|
|
103
|
-
if (commaIndex > -1) {
|
|
104
|
-
// Extract base64 part and convert to Buffer
|
|
105
|
-
const base64Data = reqData.body.substring(commaIndex + 1);
|
|
106
|
-
options.body = Buffer.from(base64Data, 'base64');
|
|
107
|
-
} else {
|
|
108
|
-
options.body = reqData.body;
|
|
109
|
-
}
|
|
110
|
-
} else {
|
|
111
|
-
// Handle Standard Text/JSON
|
|
112
|
-
options.body = typeof reqData.body === 'object' ? JSON.stringify(reqData.body) : reqData.body;
|
|
113
|
-
}
|
|
114
|
-
}
|
|
115
|
-
|
|
116
|
-
// 4. Execute Request
|
|
117
|
-
const response = await fetch(url, options);
|
|
118
|
-
|
|
119
|
-
// 5. Process Response
|
|
120
|
-
const buffer = await response.arrayBuffer();
|
|
121
|
-
const nodeBuffer = Buffer.from(buffer);
|
|
122
|
-
|
|
123
|
-
let resBody = '';
|
|
124
|
-
const contentType = response.headers.get('content-type') || '';
|
|
125
|
-
const isBinary = /image|audio|video|application\/octet-stream|application\/pdf/i.test(contentType);
|
|
126
|
-
|
|
127
|
-
if (isBinary && nodeBuffer.length > 0) {
|
|
128
|
-
resBody = `data:${contentType};base64,${nodeBuffer.toString('base64')}`;
|
|
129
|
-
} else {
|
|
130
|
-
try {
|
|
131
|
-
resBody = nodeBuffer.toString('utf8');
|
|
132
|
-
} catch (e) {
|
|
133
|
-
resBody = '[Error decoding text content]';
|
|
134
|
-
}
|
|
135
|
-
}
|
|
136
|
-
|
|
137
|
-
// Convert Headers object to plain object
|
|
138
|
-
const resHeaders = {};
|
|
139
|
-
response.headers.forEach((value, key) => {
|
|
140
|
-
resHeaders[key] = value;
|
|
141
|
-
});
|
|
142
|
-
|
|
143
|
-
const logEntry = {
|
|
144
|
-
id,
|
|
145
|
-
timestamp: start,
|
|
146
|
-
duration: Date.now() - start,
|
|
147
|
-
clientIp: 'Replay (UI)',
|
|
148
|
-
request: reqData,
|
|
149
|
-
response: {
|
|
150
|
-
status: response.status,
|
|
151
|
-
statusText: response.statusText,
|
|
152
|
-
headers: resHeaders,
|
|
153
|
-
body: resBody
|
|
154
|
-
},
|
|
155
|
-
pending: false
|
|
156
|
-
};
|
|
157
|
-
|
|
158
|
-
this.logTransaction(logEntry);
|
|
159
|
-
|
|
160
|
-
} catch (error) {
|
|
161
|
-
// Log Failure
|
|
162
|
-
const logEntry = {
|
|
163
|
-
id,
|
|
164
|
-
timestamp: start,
|
|
165
|
-
duration: Date.now() - start,
|
|
166
|
-
clientIp: 'Replay (UI)',
|
|
167
|
-
request: reqData,
|
|
168
|
-
response: {
|
|
169
|
-
status: 0,
|
|
170
|
-
statusText: 'Network Error',
|
|
171
|
-
headers: {},
|
|
172
|
-
body: JSON.stringify({ error: error.message })
|
|
173
|
-
},
|
|
174
|
-
pending: false
|
|
175
|
-
};
|
|
176
|
-
this.logTransaction(logEntry);
|
|
177
|
-
}
|
|
178
|
-
}
|
|
179
|
-
|
|
180
|
-
/**
|
|
181
|
-
* Express/Connect middleware to capture traffic
|
|
182
|
-
*/
|
|
183
|
-
middleware() {
|
|
184
|
-
return (req, res, next) => {
|
|
185
|
-
const start = Date.now();
|
|
186
|
-
const id = uuidv4();
|
|
187
|
-
|
|
188
|
-
// Emit Pending Log
|
|
189
|
-
const startEntry = {
|
|
190
|
-
id: id,
|
|
191
|
-
timestamp: start,
|
|
192
|
-
clientIp: req.ip || req.connection.remoteAddress,
|
|
193
|
-
request: {
|
|
194
|
-
method: req.method,
|
|
195
|
-
path: req.originalUrl || req.url,
|
|
196
|
-
headers: req.headers,
|
|
197
|
-
body: null, // Body parsing usually happens later
|
|
198
|
-
queryParams: req.query || {}
|
|
199
|
-
},
|
|
200
|
-
pending: true
|
|
201
|
-
};
|
|
202
|
-
this.broadcast(startEntry);
|
|
203
|
-
|
|
204
|
-
const oldWrite = res.write;
|
|
205
|
-
const oldEnd = res.end;
|
|
206
|
-
const chunks = [];
|
|
207
|
-
|
|
208
|
-
res.write = (...restArgs) => {
|
|
209
|
-
if (restArgs[0]) {
|
|
210
|
-
chunks.push(Buffer.from(restArgs[0]));
|
|
211
|
-
}
|
|
212
|
-
return oldWrite.apply(res, restArgs);
|
|
213
|
-
};
|
|
214
|
-
|
|
215
|
-
res.end = (...restArgs) => {
|
|
216
|
-
if (restArgs[0]) {
|
|
217
|
-
chunks.push(Buffer.from(restArgs[0]));
|
|
218
|
-
}
|
|
219
|
-
|
|
220
|
-
const buffer = Buffer.concat(chunks);
|
|
221
|
-
let body = '';
|
|
222
|
-
|
|
223
|
-
const contentType = res.getHeader('content-type') || '';
|
|
224
|
-
const isBinary = /image|audio|video|application\/octet-stream|application\/pdf/i.test(contentType);
|
|
225
|
-
|
|
226
|
-
if (isBinary && buffer.length > 0) {
|
|
227
|
-
body = `data:${contentType};base64,${buffer.toString('base64')}`;
|
|
228
|
-
} else {
|
|
229
|
-
try {
|
|
230
|
-
body = buffer.toString('utf8');
|
|
231
|
-
} catch (e) {
|
|
232
|
-
body = '[Error decoding text content]';
|
|
233
|
-
}
|
|
234
|
-
}
|
|
235
|
-
|
|
236
|
-
const logEntry = {
|
|
237
|
-
id: id,
|
|
238
|
-
timestamp: start,
|
|
239
|
-
duration: Date.now() - start,
|
|
240
|
-
clientIp: req.ip || req.connection.remoteAddress,
|
|
241
|
-
request: {
|
|
242
|
-
method: req.method,
|
|
243
|
-
path: req.originalUrl || req.url,
|
|
244
|
-
headers: req.headers,
|
|
245
|
-
body: req.body ? (typeof req.body === 'object' ? JSON.stringify(req.body) : req.body.toString()) : null,
|
|
246
|
-
queryParams: req.query || {}
|
|
247
|
-
},
|
|
248
|
-
response: {
|
|
249
|
-
status: res.statusCode,
|
|
250
|
-
statusText: res.statusMessage || 'OK',
|
|
251
|
-
headers: res.getHeaders ? res.getHeaders() : res._headers,
|
|
252
|
-
body: body
|
|
253
|
-
},
|
|
254
|
-
pending: false
|
|
255
|
-
};
|
|
256
|
-
|
|
257
|
-
this.logTransaction(logEntry);
|
|
258
|
-
oldEnd.apply(res, restArgs);
|
|
259
|
-
};
|
|
260
|
-
|
|
261
|
-
next();
|
|
262
|
-
};
|
|
263
|
-
}
|
|
264
|
-
|
|
265
|
-
/**
|
|
266
|
-
* Manually log a transaction (used by CLI or custom integrations)
|
|
267
|
-
* @param {Object} logEntry
|
|
268
|
-
*/
|
|
269
|
-
logTransaction(logEntry) {
|
|
270
|
-
// 1. Add to history
|
|
271
|
-
this.history.push(logEntry);
|
|
272
|
-
if (this.history.length > this.historyLimit) {
|
|
273
|
-
this.history.shift();
|
|
274
|
-
}
|
|
275
|
-
|
|
276
|
-
// 2. Broadcast to connected clients
|
|
277
|
-
this.broadcast(logEntry);
|
|
278
|
-
}
|
|
279
|
-
|
|
280
|
-
broadcast(data) {
|
|
281
|
-
this.wss.clients.forEach(client => {
|
|
282
|
-
if (client.readyState === WebSocket.OPEN) {
|
|
283
|
-
client.send(JSON.stringify(data));
|
|
284
|
-
}
|
|
285
|
-
});
|
|
286
|
-
}
|
|
287
|
-
}
|
|
288
|
-
|
|
289
|
-
module.exports = ProxyLens;
|
package/lib/ProxyLens.js
DELETED
|
@@ -1,289 +0,0 @@
|
|
|
1
|
-
const WebSocket = require('ws');
|
|
2
|
-
const { v4: uuidv4 } = require('uuid');
|
|
3
|
-
|
|
4
|
-
class ProxyLens {
|
|
5
|
-
/**
|
|
6
|
-
* @param {import('http').Server} server - The HTTP server instance to attach WebSocket to
|
|
7
|
-
* @param {Object} options - Configuration options
|
|
8
|
-
* @param {number} options.historyLimit - Number of past requests to keep (default: 50)
|
|
9
|
-
* @param {string} options.proxyTarget - The target URL if running in proxy mode (optional)
|
|
10
|
-
*/
|
|
11
|
-
constructor(server, options = {}) {
|
|
12
|
-
this.history = [];
|
|
13
|
-
this.historyLimit = options.historyLimit || 50;
|
|
14
|
-
this.proxyTarget = options.proxyTarget;
|
|
15
|
-
|
|
16
|
-
this.wss = new WebSocket.Server({ server, path: '/_proxylens' });
|
|
17
|
-
|
|
18
|
-
this.wss.on('connection', (ws) => {
|
|
19
|
-
ws.isAlive = true;
|
|
20
|
-
ws.on('pong', () => { ws.isAlive = true; });
|
|
21
|
-
|
|
22
|
-
// Send history immediately upon connection
|
|
23
|
-
if (this.history.length > 0) {
|
|
24
|
-
ws.send(JSON.stringify(this.history));
|
|
25
|
-
}
|
|
26
|
-
|
|
27
|
-
// Handle incoming messages (e.g., REPLAY)
|
|
28
|
-
ws.on('message', async (data) => {
|
|
29
|
-
try {
|
|
30
|
-
const message = JSON.parse(data);
|
|
31
|
-
if (message.type === 'REPLAY' && message.request) {
|
|
32
|
-
await this.handleReplay(message.request);
|
|
33
|
-
}
|
|
34
|
-
} catch (e) {
|
|
35
|
-
console.error('Error handling WebSocket message:', e);
|
|
36
|
-
}
|
|
37
|
-
});
|
|
38
|
-
});
|
|
39
|
-
|
|
40
|
-
// Heartbeat to keep connections alive
|
|
41
|
-
const interval = setInterval(() => {
|
|
42
|
-
this.wss.clients.forEach((ws) => {
|
|
43
|
-
if (ws.isAlive === false) return ws.terminate();
|
|
44
|
-
ws.isAlive = false;
|
|
45
|
-
ws.ping();
|
|
46
|
-
});
|
|
47
|
-
}, 30000);
|
|
48
|
-
|
|
49
|
-
this.wss.on('close', () => clearInterval(interval));
|
|
50
|
-
}
|
|
51
|
-
|
|
52
|
-
/**
|
|
53
|
-
* Executes a request sent from the UI against the actual target
|
|
54
|
-
*/
|
|
55
|
-
async handleReplay(reqData) {
|
|
56
|
-
const id = uuidv4();
|
|
57
|
-
const start = Date.now();
|
|
58
|
-
|
|
59
|
-
// 1. Determine Target URL
|
|
60
|
-
let url;
|
|
61
|
-
if (this.proxyTarget) {
|
|
62
|
-
// CLI/Proxy Mode: We know exactly where to send it
|
|
63
|
-
try {
|
|
64
|
-
const baseUrl = this.proxyTarget.replace(/\/$/, '');
|
|
65
|
-
const path = reqData.path.startsWith('/') ? reqData.path : '/' + reqData.path;
|
|
66
|
-
url = baseUrl + path;
|
|
67
|
-
} catch(e) {
|
|
68
|
-
url = reqData.path;
|
|
69
|
-
}
|
|
70
|
-
} else {
|
|
71
|
-
// Middleware Mode: We assume the server is localhost unless Host header says otherwise
|
|
72
|
-
const host = reqData.headers['host'] || 'localhost';
|
|
73
|
-
const protocol = 'http'; // Assumption for local dev
|
|
74
|
-
url = `${protocol}://${host}${reqData.path}`;
|
|
75
|
-
}
|
|
76
|
-
|
|
77
|
-
// 2. Broadcast Pending State
|
|
78
|
-
this.broadcast({
|
|
79
|
-
id,
|
|
80
|
-
timestamp: start,
|
|
81
|
-
clientIp: 'Replay (UI)',
|
|
82
|
-
request: reqData,
|
|
83
|
-
pending: true
|
|
84
|
-
});
|
|
85
|
-
|
|
86
|
-
try {
|
|
87
|
-
// 3. Prepare Fetch Options
|
|
88
|
-
const headers = { ...reqData.headers };
|
|
89
|
-
// Remove headers that might cause issues in a replay context
|
|
90
|
-
delete headers['content-length'];
|
|
91
|
-
delete headers['host'];
|
|
92
|
-
delete headers['connection'];
|
|
93
|
-
|
|
94
|
-
const options = {
|
|
95
|
-
method: reqData.method,
|
|
96
|
-
headers: headers,
|
|
97
|
-
};
|
|
98
|
-
|
|
99
|
-
if (reqData.body && ['POST', 'PUT', 'PATCH', 'DELETE'].includes(reqData.method)) {
|
|
100
|
-
// Handle Data URI (Binary/Multipart)
|
|
101
|
-
if (typeof reqData.body === 'string' && reqData.body.startsWith('data:')) {
|
|
102
|
-
const commaIndex = reqData.body.indexOf(',');
|
|
103
|
-
if (commaIndex > -1) {
|
|
104
|
-
// Extract base64 part and convert to Buffer
|
|
105
|
-
const base64Data = reqData.body.substring(commaIndex + 1);
|
|
106
|
-
options.body = Buffer.from(base64Data, 'base64');
|
|
107
|
-
} else {
|
|
108
|
-
options.body = reqData.body;
|
|
109
|
-
}
|
|
110
|
-
} else {
|
|
111
|
-
// Handle Standard Text/JSON
|
|
112
|
-
options.body = typeof reqData.body === 'object' ? JSON.stringify(reqData.body) : reqData.body;
|
|
113
|
-
}
|
|
114
|
-
}
|
|
115
|
-
|
|
116
|
-
// 4. Execute Request
|
|
117
|
-
const response = await fetch(url, options);
|
|
118
|
-
|
|
119
|
-
// 5. Process Response
|
|
120
|
-
const buffer = await response.arrayBuffer();
|
|
121
|
-
const nodeBuffer = Buffer.from(buffer);
|
|
122
|
-
|
|
123
|
-
let resBody = '';
|
|
124
|
-
const contentType = response.headers.get('content-type') || '';
|
|
125
|
-
const isBinary = /image|audio|video|application\/octet-stream|application\/pdf/i.test(contentType);
|
|
126
|
-
|
|
127
|
-
if (isBinary && nodeBuffer.length > 0) {
|
|
128
|
-
resBody = `data:${contentType};base64,${nodeBuffer.toString('base64')}`;
|
|
129
|
-
} else {
|
|
130
|
-
try {
|
|
131
|
-
resBody = nodeBuffer.toString('utf8');
|
|
132
|
-
} catch (e) {
|
|
133
|
-
resBody = '[Error decoding text content]';
|
|
134
|
-
}
|
|
135
|
-
}
|
|
136
|
-
|
|
137
|
-
// Convert Headers object to plain object
|
|
138
|
-
const resHeaders = {};
|
|
139
|
-
response.headers.forEach((value, key) => {
|
|
140
|
-
resHeaders[key] = value;
|
|
141
|
-
});
|
|
142
|
-
|
|
143
|
-
const logEntry = {
|
|
144
|
-
id,
|
|
145
|
-
timestamp: start,
|
|
146
|
-
duration: Date.now() - start,
|
|
147
|
-
clientIp: 'Replay (UI)',
|
|
148
|
-
request: reqData,
|
|
149
|
-
response: {
|
|
150
|
-
status: response.status,
|
|
151
|
-
statusText: response.statusText,
|
|
152
|
-
headers: resHeaders,
|
|
153
|
-
body: resBody
|
|
154
|
-
},
|
|
155
|
-
pending: false
|
|
156
|
-
};
|
|
157
|
-
|
|
158
|
-
this.logTransaction(logEntry);
|
|
159
|
-
|
|
160
|
-
} catch (error) {
|
|
161
|
-
// Log Failure
|
|
162
|
-
const logEntry = {
|
|
163
|
-
id,
|
|
164
|
-
timestamp: start,
|
|
165
|
-
duration: Date.now() - start,
|
|
166
|
-
clientIp: 'Replay (UI)',
|
|
167
|
-
request: reqData,
|
|
168
|
-
response: {
|
|
169
|
-
status: 0,
|
|
170
|
-
statusText: 'Network Error',
|
|
171
|
-
headers: {},
|
|
172
|
-
body: JSON.stringify({ error: error.message })
|
|
173
|
-
},
|
|
174
|
-
pending: false
|
|
175
|
-
};
|
|
176
|
-
this.logTransaction(logEntry);
|
|
177
|
-
}
|
|
178
|
-
}
|
|
179
|
-
|
|
180
|
-
/**
|
|
181
|
-
* Express/Connect middleware to capture traffic
|
|
182
|
-
*/
|
|
183
|
-
middleware() {
|
|
184
|
-
return (req, res, next) => {
|
|
185
|
-
const start = Date.now();
|
|
186
|
-
const id = uuidv4();
|
|
187
|
-
|
|
188
|
-
// Emit Pending Log
|
|
189
|
-
const startEntry = {
|
|
190
|
-
id: id,
|
|
191
|
-
timestamp: start,
|
|
192
|
-
clientIp: req.ip || req.connection.remoteAddress,
|
|
193
|
-
request: {
|
|
194
|
-
method: req.method,
|
|
195
|
-
path: req.originalUrl || req.url,
|
|
196
|
-
headers: req.headers,
|
|
197
|
-
body: null, // Body parsing usually happens later
|
|
198
|
-
queryParams: req.query || {}
|
|
199
|
-
},
|
|
200
|
-
pending: true
|
|
201
|
-
};
|
|
202
|
-
this.broadcast(startEntry);
|
|
203
|
-
|
|
204
|
-
const oldWrite = res.write;
|
|
205
|
-
const oldEnd = res.end;
|
|
206
|
-
const chunks = [];
|
|
207
|
-
|
|
208
|
-
res.write = (...restArgs) => {
|
|
209
|
-
if (restArgs[0]) {
|
|
210
|
-
chunks.push(Buffer.from(restArgs[0]));
|
|
211
|
-
}
|
|
212
|
-
return oldWrite.apply(res, restArgs);
|
|
213
|
-
};
|
|
214
|
-
|
|
215
|
-
res.end = (...restArgs) => {
|
|
216
|
-
if (restArgs[0]) {
|
|
217
|
-
chunks.push(Buffer.from(restArgs[0]));
|
|
218
|
-
}
|
|
219
|
-
|
|
220
|
-
const buffer = Buffer.concat(chunks);
|
|
221
|
-
let body = '';
|
|
222
|
-
|
|
223
|
-
const contentType = res.getHeader('content-type') || '';
|
|
224
|
-
const isBinary = /image|audio|video|application\/octet-stream|application\/pdf/i.test(contentType);
|
|
225
|
-
|
|
226
|
-
if (isBinary && buffer.length > 0) {
|
|
227
|
-
body = `data:${contentType};base64,${buffer.toString('base64')}`;
|
|
228
|
-
} else {
|
|
229
|
-
try {
|
|
230
|
-
body = buffer.toString('utf8');
|
|
231
|
-
} catch (e) {
|
|
232
|
-
body = '[Error decoding text content]';
|
|
233
|
-
}
|
|
234
|
-
}
|
|
235
|
-
|
|
236
|
-
const logEntry = {
|
|
237
|
-
id: id,
|
|
238
|
-
timestamp: start,
|
|
239
|
-
duration: Date.now() - start,
|
|
240
|
-
clientIp: req.ip || req.connection.remoteAddress,
|
|
241
|
-
request: {
|
|
242
|
-
method: req.method,
|
|
243
|
-
path: req.originalUrl || req.url,
|
|
244
|
-
headers: req.headers,
|
|
245
|
-
body: req.body ? (typeof req.body === 'object' ? JSON.stringify(req.body) : req.body.toString()) : null,
|
|
246
|
-
queryParams: req.query || {}
|
|
247
|
-
},
|
|
248
|
-
response: {
|
|
249
|
-
status: res.statusCode,
|
|
250
|
-
statusText: res.statusMessage || 'OK',
|
|
251
|
-
headers: res.getHeaders ? res.getHeaders() : res._headers,
|
|
252
|
-
body: body
|
|
253
|
-
},
|
|
254
|
-
pending: false
|
|
255
|
-
};
|
|
256
|
-
|
|
257
|
-
this.logTransaction(logEntry);
|
|
258
|
-
oldEnd.apply(res, restArgs);
|
|
259
|
-
};
|
|
260
|
-
|
|
261
|
-
next();
|
|
262
|
-
};
|
|
263
|
-
}
|
|
264
|
-
|
|
265
|
-
/**
|
|
266
|
-
* Manually log a transaction (used by CLI or custom integrations)
|
|
267
|
-
* @param {Object} logEntry
|
|
268
|
-
*/
|
|
269
|
-
logTransaction(logEntry) {
|
|
270
|
-
// 1. Add to history
|
|
271
|
-
this.history.push(logEntry);
|
|
272
|
-
if (this.history.length > this.historyLimit) {
|
|
273
|
-
this.history.shift();
|
|
274
|
-
}
|
|
275
|
-
|
|
276
|
-
// 2. Broadcast to connected clients
|
|
277
|
-
this.broadcast(logEntry);
|
|
278
|
-
}
|
|
279
|
-
|
|
280
|
-
broadcast(data) {
|
|
281
|
-
this.wss.clients.forEach(client => {
|
|
282
|
-
if (client.readyState === WebSocket.OPEN) {
|
|
283
|
-
client.send(JSON.stringify(data));
|
|
284
|
-
}
|
|
285
|
-
});
|
|
286
|
-
}
|
|
287
|
-
}
|
|
288
|
-
|
|
289
|
-
module.exports = ProxyLens;
|