node-proxylens 1.1.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/README.md ADDED
@@ -0,0 +1,45 @@
1
+ # ProxyLens Node SDK
2
+
3
+ Connect your local Node.js/Express application to the ProxyLens AI Inspector.
4
+
5
+ ## Installation
6
+
7
+ ```bash
8
+ npm install proxylens-node
9
+ ```
10
+
11
+ ## Usage with Express
12
+
13
+ ```javascript
14
+ const express = require('express');
15
+ const http = require('http');
16
+ const ProxyLens = require('proxylens-node');
17
+
18
+ const app = express();
19
+ const server = http.createServer(app);
20
+
21
+ // 1. Initialize ProxyLens with your HTTP server
22
+ const lens = new ProxyLens(server);
23
+
24
+ // 2. Add Middleware (before your routes)
25
+ app.use(express.json()); // Ensure body parsing is enabled if needed
26
+ app.use(lens.middleware());
27
+
28
+ // Your Routes
29
+ app.get('/api/users', (req, res) => {
30
+ res.json([{ name: 'Alice' }, { name: 'Bob' }]);
31
+ });
32
+
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');
37
+ });
38
+ ```
39
+
40
+ ## Connecting the UI
41
+
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,127 @@
1
+ #!/usr/bin/env node
2
+
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
9
+ 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
+ }
17
+
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}`;
23
+ }
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
+
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 });
45
+
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.
56
+
57
+ const start = Date.now();
58
+ const id = uuidv4();
59
+
60
+ // Capture Response Body via response wrapping (similar to middleware)
61
+ const oldWrite = res.write;
62
+ const oldEnd = res.end;
63
+ const resChunks = [];
64
+
65
+ res.write = (...restArgs) => {
66
+ if (restArgs[0]) resChunks.push(Buffer.from(restArgs[0]));
67
+ return oldWrite.apply(res, restArgs);
68
+ };
69
+
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
+ }
87
+
88
+ // Decode Request Body
89
+ let reqBody = null;
90
+ if (reqBuffer.length > 0) {
91
+ try { reqBody = reqBuffer.toString('utf8'); } catch(e) {}
92
+ }
93
+
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
+ });
126
+
127
+ server.listen(LISTEN_PORT);
package/index.js ADDED
@@ -0,0 +1,120 @@
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
+ */
10
+ constructor(server, options = {}) {
11
+ this.history = [];
12
+ this.historyLimit = options.historyLimit || 50;
13
+
14
+ this.wss = new WebSocket.Server({ server, path: '/_proxylens' });
15
+ this.wss.on('connection', (ws) => {
16
+ // Send history immediately upon connection
17
+ if (this.history.length > 0) {
18
+ ws.send(JSON.stringify(this.history));
19
+ }
20
+ });
21
+ }
22
+
23
+ /**
24
+ * Express/Connect middleware to capture traffic
25
+ */
26
+ middleware() {
27
+ return (req, res, next) => {
28
+ const start = Date.now();
29
+ const id = uuidv4();
30
+
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
+
35
+ const oldWrite = res.write;
36
+ const oldEnd = res.end;
37
+ const chunks = [];
38
+
39
+ res.write = (...restArgs) => {
40
+ if (restArgs[0]) {
41
+ chunks.push(Buffer.from(restArgs[0]));
42
+ }
43
+ return oldWrite.apply(res, restArgs);
44
+ };
45
+
46
+ res.end = (...restArgs) => {
47
+ if (restArgs[0]) {
48
+ chunks.push(Buffer.from(restArgs[0]));
49
+ }
50
+
51
+ const buffer = Buffer.concat(chunks);
52
+ let body = '';
53
+
54
+ const contentType = res.getHeader('content-type') || '';
55
+ const isBinary = /image|audio|video|application\/octet-stream|application\/pdf/i.test(contentType);
56
+
57
+ if (isBinary && buffer.length > 0) {
58
+ body = `data:${contentType};base64,${buffer.toString('base64')}`;
59
+ } else {
60
+ try {
61
+ body = buffer.toString('utf8');
62
+ } catch (e) {
63
+ body = '[Error decoding text content]';
64
+ }
65
+ }
66
+
67
+ const logEntry = {
68
+ id: id,
69
+ timestamp: Date.now(),
70
+ duration: Date.now() - start,
71
+ clientIp: req.ip || req.connection.remoteAddress,
72
+ request: {
73
+ method: req.method,
74
+ path: req.originalUrl || req.url,
75
+ headers: req.headers,
76
+ // If request body was attached by a previous middleware (like body-parser)
77
+ body: req.body ? (typeof req.body === 'object' ? JSON.stringify(req.body) : req.body.toString()) : null,
78
+ queryParams: req.query || {}
79
+ },
80
+ response: {
81
+ status: res.statusCode,
82
+ statusText: res.statusMessage || 'OK',
83
+ headers: res.getHeaders ? res.getHeaders() : res._headers,
84
+ body: body
85
+ }
86
+ };
87
+
88
+ this.logTransaction(logEntry);
89
+ oldEnd.apply(res, restArgs);
90
+ };
91
+
92
+ next();
93
+ };
94
+ }
95
+
96
+ /**
97
+ * Manually log a transaction (used by CLI or custom integrations)
98
+ * @param {Object} logEntry
99
+ */
100
+ logTransaction(logEntry) {
101
+ // 1. Add to history
102
+ this.history.push(logEntry);
103
+ if (this.history.length > this.historyLimit) {
104
+ this.history.shift();
105
+ }
106
+
107
+ // 2. Broadcast to connected clients
108
+ this.broadcast(logEntry);
109
+ }
110
+
111
+ broadcast(data) {
112
+ this.wss.clients.forEach(client => {
113
+ if (client.readyState === WebSocket.OPEN) {
114
+ client.send(JSON.stringify(data));
115
+ }
116
+ });
117
+ }
118
+ }
119
+
120
+ module.exports = ProxyLens;
package/package.json ADDED
@@ -0,0 +1,27 @@
1
+ {
2
+ "name": "node-proxylens",
3
+ "version": "1.1.0",
4
+ "description": "Node.js SDK and CLI for ProxyLens AI Traffic Inspector",
5
+ "main": "index.js",
6
+ "bin": {
7
+ "proxylens": "./bin/proxylens.js"
8
+ },
9
+ "scripts": {
10
+ "test": "echo \"Error: no test specified\" && exit 1"
11
+ },
12
+ "keywords": [
13
+ "proxy",
14
+ "debug",
15
+ "http",
16
+ "inspector",
17
+ "express",
18
+ "cli"
19
+ ],
20
+ "author": "ProxyLens AI",
21
+ "license": "MIT",
22
+ "dependencies": {
23
+ "ws": "^8.16.0",
24
+ "uuid": "^9.0.1",
25
+ "http-proxy": "^1.18.1"
26
+ }
27
+ }