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 CHANGED
@@ -1,100 +1,45 @@
1
- # ProxyLens CLI
1
+ # ProxyLens Node SDK
2
2
 
3
- **[ProxyLens](https://proxylens.dev)** is an AI-powered traffic inspector for your local development environment. This package provides the CLI and Node.js SDK to connect your local applications to the ProxyLens dashboard.
4
-
5
- ## Features
6
-
7
- - **Traffic Inspection**: View and analyze HTTP/HTTPS requests in real-time.
8
- - **Tunneling**: Expose your local server to the internet with a secure tunnel.
9
- - **Request Replay**: Replay requests to test your backend.
10
- - **AI Analysis**: Get AI-driven insights into your API traffic (via dashboard).
3
+ Connect your local Node.js/Express application to the ProxyLens AI Inspector.
11
4
 
12
5
  ## Installation
13
6
 
14
7
  ```bash
15
- npm install -g node-proxylens
16
- ```
17
-
18
- ## CLI Usage
19
-
20
- ### Start Proxying
21
-
22
- To start proxying traffic to your local server:
23
-
24
- ```bash
25
- # Proxy to a local port (e.g., 3000)
26
- proxylens 3000
27
-
28
- # Proxy to a specific URL
29
- proxylens http://localhost:8080
30
- ```
31
-
32
- Running this command will start a proxy server (default port 8000) and open the web dashboard.
33
-
34
- ### Public Tunneling
35
-
36
- To expose your local server to the internet using a public subdomain:
37
-
38
- ```bash
39
- # Expose port 3000 with a random or shared subdomain
40
- proxylens 3000 -d my-app
8
+ npm install proxylens-node
41
9
  ```
42
10
 
43
- *Note: You may need to login to use custom subdomains.*
11
+ ## Usage with Express
44
12
 
45
- ### ProxyLens Dashboard
46
-
47
- Visit [proxylens.dev](https://proxylens.dev) to:
48
- - Get your authentication token for the CLI.
49
- - Manage your domains and tunnels.
50
- - View and analyze your traffic history.
51
- - Collaborate with your team.
52
-
53
- **View Live Traffic:** Go to [proxylens.dev/interceptor](https://proxylens.dev/interceptor) to see all your traffic in real-time.
54
-
55
- ### Authentication
56
-
57
- Manage your ProxyLens account directly from the CLI.
58
-
59
- ```bash
60
- # Login with your authentication token
61
- proxylens login <your-token>
62
-
63
- # Check which account you are logged in as
64
- proxylens whoami
65
-
66
- # Logout from the CLI
67
- proxylens logout
68
- ```
69
-
70
- ### Options
13
+ ```javascript
14
+ const express = require('express');
15
+ const http = require('http');
16
+ const ProxyLens = require('proxylens-node');
71
17
 
72
- | Flag | Description |
73
- |------|-------------|
74
- | `target` | The target URL or port to proxy to (e.g., `3000` or `http://localhost:3000`). |
75
- | `[port]` | Optional. The port for ProxyLens to listen on (default: `8000`). usage: `proxylens <target> <port>` |
76
- | `-d <subdomain>` | Request a specific subdomain for the public tunnel. |
77
- | `-u <url>` | Specify a custom server URL (for self-hosted ProxyLens instances, Enterprise option). |
78
- | `--domain <domain>` | Specify a custom root domain (advanced usage). |
18
+ const app = express();
19
+ const server = http.createServer(app);
79
20
 
80
- ## Node.js SDK (COMING SOON)
81
- You can also use ProxyLens programmatically in your Node.js applications.
21
+ // 1. Initialize ProxyLens with your HTTP server
22
+ const lens = new ProxyLens(server);
82
23
 
83
- ```javascript
84
- const { ProxyLens } = require('node-proxylens');
85
- const http = require('http');
24
+ // 2. Add Middleware (before your routes)
25
+ app.use(express.json()); // Ensure body parsing is enabled if needed
26
+ app.use(lens.middleware());
86
27
 
87
- const uiServer = http.createServer();
88
- const lens = new ProxyLens(uiServer, {
89
- proxyTarget: 'http://localhost:3000'
28
+ // Your Routes
29
+ app.get('/api/users', (req, res) => {
30
+ res.json([{ name: 'Alice' }, { name: 'Bob' }]);
90
31
  });
91
32
 
92
- // Start the UI server
93
- uiServer.listen(8000, () => {
94
- console.log('ProxyLens dashboard running at http://localhost:8000');
33
+ // Start Server
34
+ server.listen(3000, () => {
35
+ console.log('Server running on port 3000');
36
+ console.log('ProxyLens Inspector WebSocket available at ws://localhost:3000/_proxylens');
95
37
  });
96
38
  ```
97
39
 
98
- ## License
40
+ ## Connecting the UI
99
41
 
100
- Copyright (c) 2025 ProxyLens. All rights reserved.
42
+ 1. Open ProxyLens Web App.
43
+ 2. Click **Connect Local** in the header.
44
+ 3. Enter `ws://localhost:3000/_proxylens` (default).
45
+ 4. Watch your traffic appear in real-time!
@@ -0,0 +1,91 @@
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 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;