node-proxylens 1.2.1 → 1.3.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/lib/api.js DELETED
@@ -1,51 +0,0 @@
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
- };
@@ -1,24 +0,0 @@
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;
@@ -1,32 +0,0 @@
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;
@@ -1,30 +0,0 @@
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 DELETED
@@ -1,30 +0,0 @@
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 DELETED
@@ -1,15 +0,0 @@
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
- };
@@ -1,86 +0,0 @@
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
- };
@@ -1,197 +0,0 @@
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 DELETED
@@ -1,32 +0,0 @@
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
- };