node-proxylens 0.0.2 → 1.1.1
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/README.md +27 -82
- package/bin/proxylens.js +91 -0
- package/index.js +289 -0
- package/lib/ProxyLens.js +289 -0
- package/lib/api.js +51 -0
- package/lib/commands/login.js +24 -0
- package/lib/commands/logout.js +32 -0
- package/lib/commands/whoami.js +30 -0
- package/lib/config.js +30 -0
- package/lib/constants.js +15 -0
- package/lib/modes/local.js +86 -0
- package/lib/modes/tunnel.js +197 -0
- package/lib/ui.js +32 -0
- package/package.json +8 -14
- package/LICENSE +0 -7
- package/out/dist-obf/proxylens.js +0 -61
package/lib/ProxyLens.js
ADDED
|
@@ -0,0 +1,289 @@
|
|
|
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/api.js
ADDED
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
const { API_URL } = require('./constants');
|
|
2
|
+
|
|
3
|
+
async function verifyToken(token) {
|
|
4
|
+
try {
|
|
5
|
+
const fetch = global.fetch || require('node-fetch');
|
|
6
|
+
const res = await fetch(`${API_URL}/api/cli/verify`, {
|
|
7
|
+
method: 'POST',
|
|
8
|
+
headers: { 'Content-Type': 'application/json' },
|
|
9
|
+
body: JSON.stringify({ token })
|
|
10
|
+
});
|
|
11
|
+
const data = await res.json();
|
|
12
|
+
return data;
|
|
13
|
+
} catch (e) {
|
|
14
|
+
return { valid: false, error: e.message };
|
|
15
|
+
}
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
async function verifyDomain(token, subdomain, rootDomain) {
|
|
19
|
+
try {
|
|
20
|
+
const fetch = global.fetch || require('node-fetch');
|
|
21
|
+
const res = await fetch(`${API_URL}/api/cli/verify-domain`, {
|
|
22
|
+
method: 'POST',
|
|
23
|
+
headers: { 'Content-Type': 'application/json' },
|
|
24
|
+
body: JSON.stringify({ token, subdomain, rootDomain })
|
|
25
|
+
});
|
|
26
|
+
const data = await res.json();
|
|
27
|
+
return data;
|
|
28
|
+
} catch (e) {
|
|
29
|
+
return { valid: false, error: 'Verification server unavailable: ' + e.message };
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
async function revokeToken(token) {
|
|
34
|
+
try {
|
|
35
|
+
const fetch = global.fetch || require('node-fetch');
|
|
36
|
+
await fetch(`${API_URL}/api/cli/logout`, {
|
|
37
|
+
method: 'POST',
|
|
38
|
+
headers: { 'Content-Type': 'application/json' },
|
|
39
|
+
body: JSON.stringify({ token })
|
|
40
|
+
});
|
|
41
|
+
return true;
|
|
42
|
+
} catch (serverErr) {
|
|
43
|
+
throw serverErr;
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
module.exports = {
|
|
48
|
+
verifyToken,
|
|
49
|
+
verifyDomain,
|
|
50
|
+
revokeToken
|
|
51
|
+
};
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
const { verifyToken } = require('../api');
|
|
2
|
+
const { saveToken } = require('../config');
|
|
3
|
+
const { logInfo, logSuccess, logError } = require('../ui');
|
|
4
|
+
|
|
5
|
+
async function handleLogin(token) {
|
|
6
|
+
if (!token) {
|
|
7
|
+
console.error('\nUsage: proxylens login <token>\n');
|
|
8
|
+
process.exit(1);
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
logInfo(`\nVerifying token...`);
|
|
12
|
+
const result = await verifyToken(token);
|
|
13
|
+
|
|
14
|
+
if (result.valid) {
|
|
15
|
+
saveToken(token);
|
|
16
|
+
logSuccess(`✔ Logged in as: ${result.user.email} (${result.subscription.plan})`);
|
|
17
|
+
process.exit(0);
|
|
18
|
+
} else {
|
|
19
|
+
logError(`✖ Login Failed: ${result.error}`);
|
|
20
|
+
process.exit(1);
|
|
21
|
+
}
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
module.exports = handleLogin;
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
const fs = require('fs');
|
|
2
|
+
const { getToken, removeConfig } = require('../config');
|
|
3
|
+
const { revokeToken } = require('../api');
|
|
4
|
+
const { CONFIG_FILE } = require('../constants');
|
|
5
|
+
const { logSuccess, logError, logInfo, logWarning } = require('../ui');
|
|
6
|
+
|
|
7
|
+
async function handleLogout() {
|
|
8
|
+
if (fs.existsSync(CONFIG_FILE)) {
|
|
9
|
+
try {
|
|
10
|
+
const token = getToken();
|
|
11
|
+
if (token) {
|
|
12
|
+
logInfo(`\nRevoking token...`);
|
|
13
|
+
try {
|
|
14
|
+
await revokeToken(token);
|
|
15
|
+
} catch (serverErr) {
|
|
16
|
+
logWarning(`⚠ Warning: Could not revoke token on server (${serverErr.message}). Deleting local config anyway.`);
|
|
17
|
+
}
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
removeConfig();
|
|
21
|
+
logSuccess('✔ Logged out successfully.\n');
|
|
22
|
+
} catch (e) {
|
|
23
|
+
logError(`✖ Failed to logout: ${e.message}`);
|
|
24
|
+
process.exit(1);
|
|
25
|
+
}
|
|
26
|
+
} else {
|
|
27
|
+
logWarning('\nYou are already logged out.\n');
|
|
28
|
+
}
|
|
29
|
+
process.exit(0);
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
module.exports = handleLogout;
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
const { getToken } = require('../config');
|
|
2
|
+
const { verifyToken } = require('../api');
|
|
3
|
+
const { logInfo, logError } = require('../ui');
|
|
4
|
+
|
|
5
|
+
async function handleWhoAmI() {
|
|
6
|
+
const token = getToken();
|
|
7
|
+
if (!token) {
|
|
8
|
+
logError(`You are not logged in.`);
|
|
9
|
+
console.error(`Run: \x1b[33mproxylens login <token>\x1b[0m\n`);
|
|
10
|
+
process.exit(1);
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
logInfo(`\nChecking authentication...`);
|
|
14
|
+
const result = await verifyToken(token);
|
|
15
|
+
|
|
16
|
+
if (result.valid) {
|
|
17
|
+
console.log(`\n----------------------------------------`);
|
|
18
|
+
console.log(`User: \x1b[32m${result.user.email}\x1b[0m`);
|
|
19
|
+
console.log(`UID: ${result.user.uid}`);
|
|
20
|
+
console.log(`Plan: \x1b[35m${result.subscription.name} (${result.subscription.status})\x1b[0m`);
|
|
21
|
+
console.log(`Limits: ${JSON.stringify(result.subscription.limits)}`);
|
|
22
|
+
console.log(`----------------------------------------\n`);
|
|
23
|
+
} else {
|
|
24
|
+
logError(`✖ Token Invalid or Expired.`);
|
|
25
|
+
console.error(`Please log in again.\n`);
|
|
26
|
+
}
|
|
27
|
+
process.exit(0);
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
module.exports = handleWhoAmI;
|
package/lib/config.js
ADDED
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
const fs = require('fs');
|
|
2
|
+
const { CONFIG_DIR, CONFIG_FILE } = require('./constants');
|
|
3
|
+
const { logSuccess } = require('./ui');
|
|
4
|
+
|
|
5
|
+
function saveToken(token) {
|
|
6
|
+
if (!fs.existsSync(CONFIG_DIR)) fs.mkdirSync(CONFIG_DIR);
|
|
7
|
+
fs.writeFileSync(CONFIG_FILE, JSON.stringify({ token }));
|
|
8
|
+
logSuccess(`✔ Logged in successfully.`);
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
function getToken() {
|
|
12
|
+
try {
|
|
13
|
+
if (fs.existsSync(CONFIG_FILE)) {
|
|
14
|
+
return JSON.parse(fs.readFileSync(CONFIG_FILE)).token;
|
|
15
|
+
}
|
|
16
|
+
} catch (e) { }
|
|
17
|
+
return null;
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
function removeConfig() {
|
|
21
|
+
if (fs.existsSync(CONFIG_FILE)) {
|
|
22
|
+
fs.unlinkSync(CONFIG_FILE);
|
|
23
|
+
}
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
module.exports = {
|
|
27
|
+
saveToken,
|
|
28
|
+
getToken,
|
|
29
|
+
removeConfig
|
|
30
|
+
};
|
package/lib/constants.js
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
const os = require('os');
|
|
2
|
+
const path = require('path');
|
|
3
|
+
|
|
4
|
+
const DEFAULT_SERVER = 'wss://connect.proxylens.dev';
|
|
5
|
+
const API_URL = process.env.API_URL || 'http://localhost:8081';
|
|
6
|
+
|
|
7
|
+
const CONFIG_DIR = path.join(os.homedir(), '.proxylens');
|
|
8
|
+
const CONFIG_FILE = path.join(CONFIG_DIR, 'config.json');
|
|
9
|
+
|
|
10
|
+
module.exports = {
|
|
11
|
+
DEFAULT_SERVER,
|
|
12
|
+
API_URL,
|
|
13
|
+
CONFIG_DIR,
|
|
14
|
+
CONFIG_FILE
|
|
15
|
+
};
|
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
const httpProxy = require('http-proxy');
|
|
2
|
+
const { v4: uuidv4 } = require('uuid');
|
|
3
|
+
const { printBanner } = require('../ui');
|
|
4
|
+
|
|
5
|
+
function handleRequestLog(req, res, lensInstance, next) {
|
|
6
|
+
const start = Date.now();
|
|
7
|
+
const id = uuidv4();
|
|
8
|
+
const reqChunks = [];
|
|
9
|
+
req.on('data', chunk => reqChunks.push(chunk));
|
|
10
|
+
|
|
11
|
+
lensInstance.broadcast({
|
|
12
|
+
id, timestamp: start, clientIp: req.socket.remoteAddress,
|
|
13
|
+
request: { method: req.method, path: req.url, headers: req.headers, body: null, queryParams: {} },
|
|
14
|
+
pending: true
|
|
15
|
+
});
|
|
16
|
+
|
|
17
|
+
const oldWrite = res.write;
|
|
18
|
+
const oldEnd = res.end;
|
|
19
|
+
const resChunks = [];
|
|
20
|
+
|
|
21
|
+
res.write = (...args) => {
|
|
22
|
+
if (args[0]) resChunks.push(Buffer.from(args[0]));
|
|
23
|
+
return oldWrite.apply(res, args);
|
|
24
|
+
};
|
|
25
|
+
|
|
26
|
+
res.end = (...args) => {
|
|
27
|
+
if (args[0]) resChunks.push(Buffer.from(args[0]));
|
|
28
|
+
const resBuffer = Buffer.concat(resChunks);
|
|
29
|
+
const reqBuffer = Buffer.concat(reqChunks);
|
|
30
|
+
|
|
31
|
+
let resBody = '';
|
|
32
|
+
const resType = res.getHeader('content-type') || '';
|
|
33
|
+
const isResBinary = /image|audio|video|application\/octet-stream|application\/pdf/i.test(resType);
|
|
34
|
+
|
|
35
|
+
if (isResBinary && resBuffer.length > 0) {
|
|
36
|
+
resBody = `data:${resType};base64,${resBuffer.toString('base64')}`;
|
|
37
|
+
} else {
|
|
38
|
+
try { resBody = resBuffer.toString('utf8'); } catch (e) { resBody = '[Error]'; }
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
let reqBody = null;
|
|
42
|
+
if (reqBuffer.length > 0) {
|
|
43
|
+
const reqType = req.headers['content-type'] || '';
|
|
44
|
+
const isReqBinary = /multipart\/form-data|image|audio|video|application\/octet-stream/i.test(reqType);
|
|
45
|
+
if (isReqBinary) {
|
|
46
|
+
reqBody = `data:${reqType};base64,${reqBuffer.toString('base64')}`;
|
|
47
|
+
} else {
|
|
48
|
+
try { reqBody = reqBuffer.toString('utf8'); } catch (e) { }
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
const logEntry = {
|
|
53
|
+
id, timestamp: start, duration: Date.now() - start,
|
|
54
|
+
clientIp: req.socket.remoteAddress,
|
|
55
|
+
request: { method: req.method, path: req.url, headers: req.headers, body: reqBody, queryParams: {} },
|
|
56
|
+
response: { status: res.statusCode, statusText: res.statusMessage || '', headers: res.getHeaders(), body: resBody },
|
|
57
|
+
pending: false
|
|
58
|
+
};
|
|
59
|
+
lensInstance.logTransaction(logEntry);
|
|
60
|
+
|
|
61
|
+
oldEnd.apply(res, args);
|
|
62
|
+
};
|
|
63
|
+
|
|
64
|
+
next();
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
function runLocalProxyMode(target, port, uiServer, lens) {
|
|
68
|
+
const proxy = httpProxy.createProxyServer({});
|
|
69
|
+
uiServer.on('request', (req, res) => {
|
|
70
|
+
if (req.url.startsWith('/_proxylens')) return;
|
|
71
|
+
handleRequestLog(req, res, lens, () => {
|
|
72
|
+
proxy.web(req, res, { target, changeOrigin: true }, (e) => {
|
|
73
|
+
console.error(`Proxy Error: ${e.message}`);
|
|
74
|
+
if (!res.headersSent) { res.statusCode = 502; res.end('Proxy Error'); }
|
|
75
|
+
});
|
|
76
|
+
});
|
|
77
|
+
});
|
|
78
|
+
uiServer.listen(port, () => {
|
|
79
|
+
printBanner(target, `http://localhost:${port}`, port, false);
|
|
80
|
+
});
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
module.exports = {
|
|
84
|
+
runLocalProxyMode,
|
|
85
|
+
handleRequestLog
|
|
86
|
+
};
|