entexto-cli 1.4.4 → 1.4.6

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/entexto.js CHANGED
@@ -77,6 +77,14 @@ program
77
77
  .option('-f, --full', 'Subir todos los archivos en el delta inicial (sin comparación)')
78
78
  .action(require('../lib/commands/sync'));
79
79
 
80
+ // ─── entexto tunnel ──────────────────────────────────────────
81
+ program
82
+ .command('tunnel [target]')
83
+ .description('Exponer un servidor local en una URL pública de entexto.com')
84
+ .action((target) => {
85
+ require('../lib/commands/tunnel')({ target: target || '3000' });
86
+ });
87
+
80
88
  program.parse(process.argv);
81
89
 
82
90
  if (!process.argv.slice(2).length) {
@@ -0,0 +1,188 @@
1
+ 'use strict';
2
+
3
+ const http = require('http');
4
+ const https = require('https');
5
+ const chalk = require('chalk');
6
+ const ora = require('ora');
7
+
8
+ module.exports = async function tunnel(opts) {
9
+ // Parsear target: puede ser un puerto, una URL, o un hostname
10
+ const target = opts.target || 'localhost:3000';
11
+ let targetUrl;
12
+
13
+ if (/^\d+$/.test(target)) {
14
+ targetUrl = `http://localhost:${target}`;
15
+ } else if (/^https?:\/\//.test(target)) {
16
+ targetUrl = target;
17
+ } else {
18
+ targetUrl = `http://${target}`;
19
+ }
20
+
21
+ // Validar que la URL es parseable
22
+ let parsedTarget;
23
+ try {
24
+ parsedTarget = new URL(targetUrl);
25
+ } catch {
26
+ console.error(chalk.red(`URL inválida: ${target}`));
27
+ process.exit(1);
28
+ }
29
+
30
+ const { getConfig } = require('../utils/config');
31
+ const cfg = getConfig();
32
+ const baseUrl = (cfg.baseUrl || 'https://entexto.com').replace(/\/$/, '');
33
+
34
+ // Calcular URL del WebSocket
35
+ const wsUrl = baseUrl.replace(/^http/, 'ws') + '/tunnel';
36
+
37
+ const spinner = ora('Conectando al servidor de túneles...').start();
38
+
39
+ // Cargar socket.io-client
40
+ let ioClient;
41
+ try {
42
+ ioClient = require('socket.io-client');
43
+ } catch {
44
+ spinner.fail('Falta socket.io-client. Ejecuta: npm install socket.io-client');
45
+ process.exit(1);
46
+ }
47
+
48
+ const socket = ioClient(wsUrl, {
49
+ transports: ['websocket'],
50
+ reconnection: true,
51
+ reconnectionDelay: 2000,
52
+ reconnectionAttempts: Infinity, // reintentar indefinidamente
53
+ });
54
+
55
+ // Mantener el mismo tunnelId entre reconexiones
56
+ let currentTunnelId = null;
57
+ let publicUrl = null;
58
+ let heartbeatTimer = null;
59
+
60
+ function startHeartbeat() {
61
+ clearInterval(heartbeatTimer);
62
+ // Ping cada 25s para evitar el timeout de 60s de Cloudflare/proxies
63
+ heartbeatTimer = setInterval(() => {
64
+ if (socket.connected) socket.emit('ping-tunnel');
65
+ }, 25000);
66
+ }
67
+
68
+ socket.on('connect', () => {
69
+ const meta = { target: targetUrl };
70
+ if (currentTunnelId) meta.reclaimId = currentTunnelId; // intentar recuperar el mismo ID
71
+
72
+ socket.emit('open-tunnel', meta, (res) => {
73
+ if (!res || !res.ok) {
74
+ spinner.fail('No se pudo abrir el túnel: ' + JSON.stringify(res));
75
+ process.exit(1);
76
+ }
77
+
78
+ const isNew = res.tunnelId !== currentTunnelId;
79
+ currentTunnelId = res.tunnelId;
80
+ publicUrl = `${baseUrl}/t/${currentTunnelId}`;
81
+
82
+ startHeartbeat();
83
+
84
+ if (isNew) {
85
+ spinner.succeed('Túnel activo');
86
+ console.log('');
87
+ console.log(chalk.bold(' 🚇 URL pública:'), chalk.cyan.underline(publicUrl));
88
+ console.log(chalk.gray(` → ${targetUrl}`));
89
+ console.log('');
90
+ console.log(chalk.gray(' Presiona Ctrl+C para cerrar'));
91
+ console.log('');
92
+ } else {
93
+ console.log(chalk.green(' ✔ Reconectado — misma URL: ') + chalk.cyan(publicUrl));
94
+ }
95
+ });
96
+ });
97
+
98
+ // Procesar requests del server
99
+ socket.on('tunnel-request', (payload, cb) => {
100
+ const { method, path: reqPath, headers, body, id } = payload;
101
+
102
+ // Construir URL completa al target local
103
+ const localUrl = new URL(reqPath, targetUrl);
104
+
105
+ // Preparar headers — reescribir host al target local
106
+ const fwdHeaders = { ...headers };
107
+ fwdHeaders.host = parsedTarget.host;
108
+ delete fwdHeaders['accept-encoding']; // Evitar compresión para simplificar relay
109
+
110
+ const proto = parsedTarget.protocol === 'https:' ? https : http;
111
+
112
+ const reqOpts = {
113
+ method: method,
114
+ hostname: parsedTarget.hostname,
115
+ port: parsedTarget.port || (parsedTarget.protocol === 'https:' ? 443 : 80),
116
+ path: localUrl.pathname + localUrl.search,
117
+ headers: fwdHeaders,
118
+ rejectUnauthorized: false, // Permitir self-signed certs en localhost
119
+ };
120
+
121
+ const timestamp = new Date().toLocaleTimeString();
122
+ process.stdout.write(chalk.gray(` [${timestamp}] `) + chalk.yellow(method.padEnd(6)) + chalk.white(reqPath) + ' ');
123
+
124
+ const localReq = proto.request(reqOpts, (localRes) => {
125
+ const chunks = [];
126
+ localRes.on('data', (chunk) => chunks.push(chunk));
127
+ localRes.on('end', () => {
128
+ const bodyBuf = Buffer.concat(chunks);
129
+
130
+ // Color del status
131
+ const status = localRes.statusCode;
132
+ const statusColor = status < 300 ? chalk.green(status) : status < 400 ? chalk.cyan(status) : chalk.red(status);
133
+ console.log(statusColor + chalk.gray(` (${bodyBuf.length}B)`));
134
+
135
+ cb({
136
+ status: status,
137
+ headers: localRes.headers,
138
+ body: bodyBuf.toString('base64'),
139
+ });
140
+ });
141
+ });
142
+
143
+ localReq.on('error', (err) => {
144
+ console.log(chalk.red('ERR ') + chalk.gray(err.message));
145
+ cb({ error: err.message, status: 502 });
146
+ });
147
+
148
+ localReq.setTimeout(25000, () => {
149
+ localReq.destroy();
150
+ console.log(chalk.red('TIMEOUT'));
151
+ cb({ error: 'Local server timeout', status: 504 });
152
+ });
153
+
154
+ if (body) {
155
+ localReq.write(Buffer.from(body, 'base64'));
156
+ }
157
+ localReq.end();
158
+ });
159
+
160
+ socket.on('connect_error', (err) => {
161
+ if (spinner.isSpinning) {
162
+ spinner.fail('No se pudo conectar al servidor: ' + err.message);
163
+ } else {
164
+ console.error(chalk.red(' Conexión perdida: ' + err.message));
165
+ }
166
+ });
167
+
168
+ socket.on('disconnect', (reason) => {
169
+ clearInterval(heartbeatTimer);
170
+ console.log(chalk.yellow('\n Desconectado: ' + reason));
171
+ if (reason === 'io client disconnect') {
172
+ // Cierre manual (Ctrl+C)
173
+ process.exit(0);
174
+ }
175
+ if (publicUrl) {
176
+ console.log(chalk.gray(' Reintentando... (la URL se mantendrá: ') + chalk.cyan(publicUrl) + chalk.gray(')'));
177
+ } else {
178
+ console.log(chalk.gray(' Reintentando...'));
179
+ }
180
+ });
181
+
182
+ // Ctrl+C
183
+ process.on('SIGINT', () => {
184
+ console.log(chalk.gray('\n Cerrando túnel...'));
185
+ socket.disconnect();
186
+ process.exit(0);
187
+ });
188
+ };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "entexto-cli",
3
- "version": "1.4.4",
3
+ "version": "1.4.6",
4
4
  "description": "CLI oficial de Entexto — Deploy y gestión de proyectos desde tu terminal",
5
5
  "main": "lib/index.js",
6
6
  "bin": {
@@ -29,6 +29,7 @@
29
29
  "commander": "^11.0.0",
30
30
  "form-data": "^4.0.0",
31
31
  "inquirer": "^8.2.6",
32
- "ora": "^5.4.1"
32
+ "ora": "^5.4.1",
33
+ "socket.io-client": "^4.8.3"
33
34
  }
34
35
  }