node-proxylens 1.1.0 → 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/bin/proxylens.js CHANGED
@@ -1,127 +1,91 @@
1
1
  #!/usr/bin/env node
2
2
 
3
3
  const http = require('http');
4
- const httpProxy = require('http-proxy');
5
- const ProxyLens = require('../index');
6
- const { v4: uuidv4 } = require('uuid');
7
-
8
- // Parse Arguments
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 ---
9
13
  const args = process.argv.slice(2);
10
- if (args.length === 0) {
11
- console.error('\nUsage: proxylens <target_port_or_url> [listen_port]\n');
12
- console.error('Examples:');
13
- console.error(' proxylens 3000 -> Proxies localhost:4150 to localhost:3000');
14
- console.error(' proxylens api.dev.com -> Proxies localhost:4150 to api.dev.com');
15
- process.exit(1);
16
- }
14
+ const command = args[0] ? args[0].trim() : null;
17
15
 
18
- // Configuration
19
- let target = args[0];
20
- // If target is just a number, assume localhost port
21
- if (/^\d+$/.test(target)) {
22
- target = `http://localhost:${target}`;
16
+ // --- Commands ---
17
+ if (command === 'login') {
18
+ handleLogin(args[1]);
19
+ return;
23
20
  }
24
- // Ensure protocol
25
- if (!target.startsWith('http')) {
26
- target = `http://${target}`;
27
- }
28
-
29
- const LISTEN_PORT = args[1] || 4150;
30
- const INSPECTOR_PATH = '/_proxylens';
31
21
 
32
- console.log(`\n\x1b[36mšŸ”­ ProxyLens AI Inspector\x1b[0m`);
33
- console.log(`----------------------------------------`);
34
- console.log(`Target: \x1b[33m${target}\x1b[0m`);
35
- console.log(`Proxy URL: \x1b[32mhttp://localhost:${LISTEN_PORT}\x1b[0m`);
36
- console.log(`Inspector: \x1b[35mws://localhost:${LISTEN_PORT}${INSPECTOR_PATH}\x1b[0m`);
37
- console.log(`----------------------------------------\n`);
38
-
39
- // Create Proxy Server
40
- const proxy = httpProxy.createProxyServer({});
41
- const server = http.createServer();
42
-
43
- // Initialize ProxyLens SDK
44
- const lens = new ProxyLens(server, { historyLimit: 100 });
22
+ if (command === 'whoami') {
23
+ handleWhoAmI();
24
+ return;
25
+ }
45
26
 
46
- // Handle Traffic
47
- server.on('request', (req, res) => {
48
- // Capture Request Body Manually since we are a raw proxy
49
- const reqChunks = [];
50
- req.on('data', (chunk) => reqChunks.push(chunk));
51
-
52
- // We need to pause/resume or clone the stream, but for logging we can just tap data
53
- // However, tapping 'data' switches stream to flowing mode.
54
- // http-proxy handles the stream piping, so we need to be careful.
55
- // Strategy: We will listen to the proxy events to log.
27
+ if (command === 'logout') {
28
+ handleLogout();
29
+ return;
30
+ }
56
31
 
57
- const start = Date.now();
58
- const id = uuidv4();
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
+ }
59
49
 
60
- // Capture Response Body via response wrapping (similar to middleware)
61
- const oldWrite = res.write;
62
- const oldEnd = res.end;
63
- const resChunks = [];
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
+ }
64
58
 
65
- res.write = (...restArgs) => {
66
- if (restArgs[0]) resChunks.push(Buffer.from(restArgs[0]));
67
- return oldWrite.apply(res, restArgs);
68
- };
59
+ if (/^\d+$/.test(target)) target = `http://localhost:${target}`;
60
+ if (!target.startsWith('http')) target = `http://${target}`;
69
61
 
70
- res.end = (...restArgs) => {
71
- if (restArgs[0]) resChunks.push(Buffer.from(restArgs[0]));
72
-
73
- // Construct Log Entry
74
- const resBuffer = Buffer.concat(resChunks);
75
- const reqBuffer = Buffer.concat(reqChunks); // Captured from 'data' listener below
76
-
77
- // Decode Response Body
78
- let resBody = '';
79
- const resType = res.getHeader('content-type') || '';
80
- const isResBinary = /image|audio|video|application\/octet-stream|application\/pdf/i.test(resType);
81
-
82
- if (isResBinary && resBuffer.length > 0) {
83
- resBody = `data:${resType};base64,${resBuffer.toString('base64')}`;
84
- } else {
85
- try { resBody = resBuffer.toString('utf8'); } catch(e) { resBody = '[Error]'; }
86
- }
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(':');
87
67
 
88
- // Decode Request Body
89
- let reqBody = null;
90
- if (reqBuffer.length > 0) {
91
- try { reqBody = reqBuffer.toString('utf8'); } catch(e) {}
68
+ if (!looksLikeDomain) {
69
+ if (hostname === 'login') {
70
+ console.error('\nUsage: proxylens login <token>\n');
71
+ process.exit(1);
92
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
+ }
93
81
 
94
- const logEntry = {
95
- id,
96
- timestamp: Date.now(),
97
- duration: Date.now() - start,
98
- clientIp: req.socket.remoteAddress,
99
- request: {
100
- method: req.method,
101
- path: req.url,
102
- headers: req.headers,
103
- body: reqBody,
104
- queryParams: {} // Not fully parsed for CLI yet, keep simple
105
- },
106
- response: {
107
- status: res.statusCode,
108
- statusText: res.statusMessage || '',
109
- headers: res.getHeaders(),
110
- body: resBody
111
- }
112
- };
113
-
114
- lens.logTransaction(logEntry);
115
- oldEnd.apply(res, restArgs);
116
- };
117
-
118
- // Proxy the request
119
- proxy.web(req, res, { target, changeOrigin: true }, (e) => {
120
- console.error(`Proxy Error: ${e.message}`);
121
- res.statusCode = 502;
122
- res.end('Proxy Error');
123
- });
124
-
125
- });
82
+ // --- Setup ProxyLens SDK ---
83
+ const uiServer = http.createServer();
84
+ const lens = new ProxyLens(uiServer, { historyLimit: 100, proxyTarget: target });
126
85
 
127
- server.listen(LISTEN_PORT);
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 CHANGED
@@ -6,18 +6,175 @@ class ProxyLens {
6
6
  * @param {import('http').Server} server - The HTTP server instance to attach WebSocket to
7
7
  * @param {Object} options - Configuration options
8
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)
9
10
  */
10
11
  constructor(server, options = {}) {
11
12
  this.history = [];
12
13
  this.historyLimit = options.historyLimit || 50;
14
+ this.proxyTarget = options.proxyTarget;
13
15
 
14
16
  this.wss = new WebSocket.Server({ server, path: '/_proxylens' });
17
+
15
18
  this.wss.on('connection', (ws) => {
19
+ ws.isAlive = true;
20
+ ws.on('pong', () => { ws.isAlive = true; });
21
+
16
22
  // Send history immediately upon connection
17
23
  if (this.history.length > 0) {
18
24
  ws.send(JSON.stringify(this.history));
19
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
+ });
20
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
+ }
21
178
  }
22
179
 
23
180
  /**
@@ -28,10 +185,22 @@ class ProxyLens {
28
185
  const start = Date.now();
29
186
  const id = uuidv4();
30
187
 
31
- // Request body capture for middleware is tricky without buffering.
32
- // We rely on express.json() being used before this, OR manual handling.
33
- // For the CLI proxy, we pass the body explicitly.
34
-
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
+
35
204
  const oldWrite = res.write;
36
205
  const oldEnd = res.end;
37
206
  const chunks = [];
@@ -66,14 +235,13 @@ class ProxyLens {
66
235
 
67
236
  const logEntry = {
68
237
  id: id,
69
- timestamp: Date.now(),
238
+ timestamp: start,
70
239
  duration: Date.now() - start,
71
240
  clientIp: req.ip || req.connection.remoteAddress,
72
241
  request: {
73
242
  method: req.method,
74
243
  path: req.originalUrl || req.url,
75
244
  headers: req.headers,
76
- // If request body was attached by a previous middleware (like body-parser)
77
245
  body: req.body ? (typeof req.body === 'object' ? JSON.stringify(req.body) : req.body.toString()) : null,
78
246
  queryParams: req.query || {}
79
247
  },
@@ -82,7 +250,8 @@ class ProxyLens {
82
250
  statusText: res.statusMessage || 'OK',
83
251
  headers: res.getHeaders ? res.getHeaders() : res._headers,
84
252
  body: body
85
- }
253
+ },
254
+ pending: false
86
255
  };
87
256
 
88
257
  this.logTransaction(logEntry);
@@ -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
+ };
@@ -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
+ };
@@ -0,0 +1,197 @@
1
+ const WebSocket = require('ws');
2
+ const readline = require('readline');
3
+ const { DEFAULT_SERVER } = require('../constants');
4
+ const { getToken } = require('../config');
5
+ const { verifyDomain } = require('../api');
6
+ const { printBanner, logError, logInfo, logWarning, logSuccess } = require('../ui');
7
+
8
+ async function verifyAndRunTunnel(target, listenPort, uiServer, flags, lens) {
9
+ // Determine Root Domain (Default or Custom)
10
+ const serverUrl = flags.serverUrl || DEFAULT_SERVER;
11
+ let rootDomain = flags.rootDomain;
12
+
13
+ if (!rootDomain) {
14
+ // Smart Default: If connecting to connect.proxylens.dev, default tunnels to proxylens.dev
15
+ try {
16
+ const hostname = new URL(serverUrl.replace(/^ws/, 'http')).hostname;
17
+ if (hostname === 'connect.proxylens.dev') {
18
+ rootDomain = 'proxylens.dev';
19
+ } else {
20
+ rootDomain = hostname === 'localhost' ? 'localhost' : hostname;
21
+ }
22
+ } catch (e) {
23
+ rootDomain = 'proxylens.dev';
24
+ }
25
+ }
26
+
27
+ const token = getToken();
28
+
29
+ // Strict Auth for Custom Subdomains
30
+ if (!token && flags.subdomain) {
31
+ logError(`ā›” Authentication Required`);
32
+ console.error(`To use a custom subdomain, you must be logged in.`);
33
+ console.error(`Run: \x1b[33mproxylens login <your_token>\x1b[0m\n`);
34
+ process.exit(1);
35
+ }
36
+
37
+ // Verify Domain Ownership BEFORE connecting
38
+ logInfo(`Verifying ownership of ${flags.subdomain}${rootDomain === 'proxylens.dev' ? '.proxylens.dev' : ' on ' + rootDomain}...`);
39
+ const domainCheck = await verifyDomain(token, flags.subdomain, rootDomain);
40
+
41
+ if (!domainCheck.valid) {
42
+ logError(`ā›” Access Denied: ${domainCheck.error}`);
43
+ console.error(`Please register this subdomain in your dashboard first.\nhttps://proxylens.dev/dashboard`);
44
+ process.exit(1);
45
+ }
46
+
47
+ runTunnelMode(target, listenPort, flags.subdomain, rootDomain, serverUrl, token, false, lens);
48
+
49
+ // In Tunnel Mode, handle root request to show status
50
+ uiServer.listen(listenPort);
51
+ uiServer.on('request', (req, res) => {
52
+ if (!req.url.startsWith('/_proxylens')) {
53
+ res.writeHead(200);
54
+ res.end('ProxyLens Tunnel Running. Go to /_proxylens to view traffic.');
55
+ }
56
+ });
57
+ }
58
+
59
+ function runTunnelMode(target, listenPort, subdomain, rootDomain, serverUrl, token, force, lens) {
60
+ if (!serverUrl.startsWith('ws')) serverUrl = `ws://${serverUrl}`;
61
+
62
+ // Construct URL with extra params
63
+ let tunnelUrl = `${serverUrl}/register?subdomain=${subdomain}&domain=${rootDomain}`;
64
+ if (force) tunnelUrl += '&force=true';
65
+ if (token) tunnelUrl += `&token=${token}`;
66
+
67
+ logInfo(`\nšŸ”­ ProxyLens Tunnel Connecting to ${rootDomain}...`);
68
+
69
+ const ws = new WebSocket(tunnelUrl);
70
+ let pingInterval;
71
+
72
+ ws.on('open', () => {
73
+ logSuccess(`āœ” Connected! Public: https://${subdomain}.${rootDomain}`);
74
+ printBanner(target, `https://${subdomain}.${rootDomain}`, listenPort, true);
75
+
76
+ // Keep Alive
77
+ pingInterval = setInterval(() => ws.ping(), 30000);
78
+ });
79
+
80
+ ws.on('message', async (data) => {
81
+ try {
82
+ const msg = JSON.parse(data);
83
+ if (msg.type === 'REQUEST') {
84
+ handleTunnelRequest(msg, ws, target, lens);
85
+ }
86
+ } catch (e) { }
87
+ });
88
+
89
+ ws.on('error', (e) => {
90
+ if (e.message.includes('409')) {
91
+ logWarning(`\n⚠ The subdomain '${subdomain}' is already in use.`);
92
+ askUserForceConnect(target, listenPort, subdomain, rootDomain, serverUrl, lens);
93
+ return;
94
+ }
95
+ if (e.message.includes('403')) {
96
+ logError(`\nā›” Access Denied: Subdomain not allowed or Token invalid.`);
97
+ process.exit(1);
98
+ }
99
+ logError('Tunnel Error: ' + e.message);
100
+ });
101
+
102
+ ws.on('close', (code, reason) => {
103
+ clearInterval(pingInterval);
104
+ const reasonStr = reason.toString();
105
+
106
+ if (reasonStr === "Session Replaced") {
107
+ logError('\nā›” Disconnected: Another client claimed this subdomain.');
108
+ process.exit(0);
109
+ } else if (!code || code === 1006) {
110
+ logError('Connection lost. Retrying in 3s...');
111
+ setTimeout(() => runTunnelMode(target, listenPort, subdomain, rootDomain, serverUrl, token, force, lens), 3000);
112
+ }
113
+ });
114
+ }
115
+
116
+ function askUserForceConnect(target, listenPort, subdomain, rootDomain, serverUrl, lens) {
117
+ const rl = readline.createInterface({
118
+ input: process.stdin,
119
+ output: process.stdout
120
+ });
121
+
122
+ rl.question('Do you want to close the remote connection and take over? (y/N) ', (answer) => {
123
+ rl.close();
124
+ if (answer.toLowerCase() === 'y') {
125
+ runTunnelMode(target, listenPort, subdomain, rootDomain, serverUrl, getToken(), true, lens); // Force = true
126
+ } else {
127
+ console.log("Aborted.");
128
+ process.exit(0);
129
+ }
130
+ });
131
+ }
132
+
133
+ async function handleTunnelRequest(msg, ws, targetHost, lens) {
134
+ const { id, method, path, headers, body } = msg.payload;
135
+ const start = Date.now();
136
+
137
+ const baseUrl = targetHost.replace(/\/$/, '');
138
+ const reqPath = path.startsWith('/') ? path : '/' + path;
139
+ const targetUrl = `${baseUrl}${reqPath}`;
140
+
141
+ lens.broadcast({
142
+ id, timestamp: start, clientIp: 'Tunnel User',
143
+ request: { method, path, headers, body: body || null, queryParams: {} },
144
+ pending: true
145
+ });
146
+
147
+ const cleanHeaders = {};
148
+ const forbiddenHeaders = ['connection', 'host', 'upgrade', 'keep-alive', 'transfer-encoding', 'content-length'];
149
+ for (const [key, value] of Object.entries(headers)) {
150
+ if (!forbiddenHeaders.includes(key.toLowerCase())) cleanHeaders[key] = value;
151
+ }
152
+
153
+ const reqOptions = { method, headers: cleanHeaders };
154
+ if (body) reqOptions.body = body;
155
+
156
+ try {
157
+ const fetch = global.fetch || require('node-fetch');
158
+ const res = await fetch(targetUrl, reqOptions);
159
+ const resBuffer = await res.arrayBuffer();
160
+ const nodeBuffer = Buffer.from(resBuffer);
161
+ const resHeaders = {};
162
+ res.headers.forEach((v, k) => resHeaders[k] = v);
163
+
164
+ const logEntry = {
165
+ id, timestamp: start, duration: Date.now() - start,
166
+ clientIp: 'Tunnel User',
167
+ request: { method, path, headers, body },
168
+ response: {
169
+ status: res.status, statusText: res.statusText, headers: resHeaders, body: nodeBuffer.toString('utf8')
170
+ },
171
+ pending: false
172
+ };
173
+ lens.logTransaction(logEntry);
174
+
175
+ ws.send(JSON.stringify({
176
+ type: 'RESPONSE', reqId: id,
177
+ payload: { status: res.status, headers: resHeaders, body: nodeBuffer.toString('base64') }
178
+ }));
179
+
180
+ } catch (err) {
181
+ const logEntry = {
182
+ id, timestamp: start, duration: Date.now() - start,
183
+ clientIp: 'Tunnel User',
184
+ request: { method, path, headers, body },
185
+ response: { status: 502, statusText: 'Bad Gateway', headers: {}, body: `Error connecting to ${targetHost}: ${err.message}` },
186
+ pending: false
187
+ };
188
+ lens.logTransaction(logEntry);
189
+
190
+ ws.send(JSON.stringify({
191
+ type: 'RESPONSE', reqId: id,
192
+ payload: { status: 502, headers: {}, body: Buffer.from('Target connection failed').toString('base64') }
193
+ }));
194
+ }
195
+ }
196
+
197
+ module.exports = { verifyAndRunTunnel };
package/lib/ui.js ADDED
@@ -0,0 +1,32 @@
1
+ function logError(message) {
2
+ console.error(`\n\x1b[31m${message}\x1b[0m\n`);
3
+ }
4
+
5
+ function logSuccess(message) {
6
+ console.log(`\x1b[32m${message}\x1b[0m`);
7
+ }
8
+
9
+ function logInfo(message) {
10
+ console.log(`\x1b[36m${message}\x1b[0m`);
11
+ }
12
+
13
+ function logWarning(message) {
14
+ console.log(`\x1b[33m${message}\x1b[0m`);
15
+ }
16
+
17
+ function printBanner(target, proxyUrl, uiPort, isTunnel) {
18
+ console.log(`\n\x1b[36mšŸ”­ ProxyLens AI Inspector\x1b[0m`);
19
+ console.log(`----------------------------------------`);
20
+ console.log(`Target: \x1b[33m${target}\x1b[0m`);
21
+ console.log(`${isTunnel ? 'Public URL:' : 'Proxy URL:'} \x1b[32m${proxyUrl}\x1b[0m`);
22
+ console.log(`Inspector: \x1b[35mhttp://localhost:${uiPort}/_proxylens\x1b[0m`);
23
+ console.log(`----------------------------------------\n`);
24
+ }
25
+
26
+ module.exports = {
27
+ logError,
28
+ logSuccess,
29
+ logInfo,
30
+ logWarning,
31
+ printBanner
32
+ };
package/package.json CHANGED
@@ -1,13 +1,14 @@
1
1
  {
2
2
  "name": "node-proxylens",
3
- "version": "1.1.0",
3
+ "version": "1.1.1",
4
4
  "description": "Node.js SDK and CLI for ProxyLens AI Traffic Inspector",
5
- "main": "index.js",
5
+ "main": "lib/ProxyLens.js",
6
6
  "bin": {
7
7
  "proxylens": "./bin/proxylens.js"
8
8
  },
9
9
  "scripts": {
10
- "test": "echo \"Error: no test specified\" && exit 1"
10
+ "test": "echo \"Error: no test specified\" && exit 1",
11
+ "publish": "npm publish"
11
12
  },
12
13
  "keywords": [
13
14
  "proxy",