cm-tunnel 1.2.0 → 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/README.md CHANGED
@@ -27,6 +27,10 @@ try {
27
27
  port: 3000,
28
28
  subdomain: 'meu-app-unico', // Opcional (para localtunnel e ngrok)
29
29
  authtoken: 'token_aqui', // Opcional (recomendado para ngrok)
30
+ serve: { // Opcional: Servidor Estático Interno
31
+ html: '<h1>Online!</h1>', // String HTML para servir
32
+ // directory: './public' // Alternativa: Serve uma pasta inteira
33
+ },
30
34
  rateLimit: { // Opcional: Bloqueia IPs por excesso de requisições
31
35
  maxRequestsPerMinute: 60,
32
36
  routes: ['/api/'] // Se vazio, aplica globalmente
@@ -59,6 +63,92 @@ const t2 = await tunnel.localtunnel({ port: 3000 });
59
63
  const t3 = await tunnel.ngrok({ port: 3000, authtoken: 'seu_token' });
60
64
  ```
61
65
 
66
+ ### Cloudflare Quick Tunnel (padrão)
67
+
68
+ Cria um túnel temporário com URL aleatória `trycloudflare.com`. É o comportamento padrão — não precisa de nenhuma configuração extra.
69
+
70
+ ```javascript
71
+ import tunnel from 'cm-tunnel';
72
+
73
+ const t = await tunnel.cloudflare({ port: 3000 });
74
+ console.log(t.url); // https://random-words.trycloudflare.com
75
+ ```
76
+
77
+ ### Cloudflare Named Tunnel (domínio personalizado)
78
+
79
+ Utiliza um túnel Cloudflare previamente criado e configurado para servir em um domínio próprio.
80
+
81
+ **Pré-requisitos:**
82
+
83
+ 1. Instale o `cloudflared`: [Download](https://developers.cloudflare.com/cloudflare-one/connections/connect-networks/downloads/)
84
+ 2. Autentique: `cloudflared tunnel login`
85
+ 3. Crie um túnel: `cloudflared tunnel create meu-tunnel`
86
+ 4. Configure o DNS: `cloudflared tunnel route dns meu-tunnel api.meudominio.com.br`
87
+
88
+ **Uso com a API simplificada (recomendado):**
89
+
90
+ ```javascript
91
+ import tunnel from 'cm-tunnel';
92
+
93
+ const t = await tunnel.cloudflare({
94
+ port: 3000,
95
+ domain: 'api.meudominio.com.br',
96
+ tunnelId: 'ID_DO_TUNNEL',
97
+ });
98
+
99
+ console.log(t.url); // https://api.meudominio.com.br
100
+ ```
101
+
102
+ **Uso com a API principal:**
103
+
104
+ ```javascript
105
+ import tunnel from 'cm-tunnel';
106
+
107
+ const t = await tunnel({
108
+ provider: 'cloudflare',
109
+ port: 3000,
110
+ cloudflare: {
111
+ mode: 'named',
112
+ domain: 'api.meudominio.com.br',
113
+ tunnelId: 'ID_DO_TUNNEL',
114
+ credentialsFile: '/home/user/.cloudflared/abc-123.json', // Opcional
115
+ },
116
+ });
117
+
118
+ console.log(t.url); // https://api.meudominio.com.br
119
+ ```
120
+
121
+ #### Opções do Cloudflare
122
+
123
+ | Opção | Tipo | Padrão | Descrição |
124
+ |-------|------|--------|-----------|
125
+ | `mode` | `'quick' \| 'named'` | `'quick'` | Modo do túnel. Inferido automaticamente se `domain` ou `tunnelId` forem fornecidos. |
126
+ | `domain` | `string` | — | Domínio personalizado (obrigatório para named tunnels). |
127
+ | `tunnelId` | `string` | — | ID do túnel Cloudflare (obrigatório para named tunnels, alternativa a `tunnelName`). |
128
+ | `tunnelName` | `string` | — | Nome do túnel Cloudflare (alternativa ao `tunnelId`). |
129
+ | `credentialsFile` | `string` | — | Caminho para o arquivo de credenciais `.json` do túnel. |
130
+ | `cloudflaredPath` | `string` | `'cloudflared'` | Caminho personalizado para o executável `cloudflared`. |
131
+ | `timeout` | `number` | `30000` | Timeout em milissegundos para aguardar a inicialização do túnel. |
132
+
133
+ > **Nota:** Na API simplificada (`tunnel.cloudflare()`), as opções podem ser passadas diretamente no mesmo objeto. Na API principal (`tunnel()`), devem ser passadas dentro da chave `cloudflare`.
134
+
135
+ ### Servidor HTML/Estático Standalone (Sem Túnel)
136
+
137
+ Você também pode usar a nossa engine de servidor embutida apenas para testar páginas locais rapidamente, sem expô-las à internet (útil para desenvolvimento local):
138
+
139
+ ```javascript
140
+ import tunnel from 'cm-tunnel';
141
+
142
+ const localServer = await tunnel.serve({
143
+ html: '<h1>Teste Local</h1>',
144
+ // directory: './public',
145
+ port: 8080 // Opcional
146
+ });
147
+
148
+ console.log('Rodando localmente em:', localServer.url);
149
+ // localServer.stop() para encerrar
150
+ ```
151
+
62
152
  ## Objeto de Retorno
63
153
 
64
154
  A função retorna uma Promise que resolve em um objeto `TunnelInstance` contendo:
@@ -71,6 +161,18 @@ A função retorna uma Promise que resolve em um objeto `TunnelInstance` contend
71
161
 
72
162
  O objeto retornado também é um `EventEmitter`, emitindo os eventos `ready`, `close` e `error`.
73
163
 
164
+ ## Tratamento de Erros
165
+
166
+ A biblioteca trata automaticamente os seguintes cenários:
167
+
168
+ - **`cloudflared` não instalado** — erro claro com link para download.
169
+ - **Porta local sem servidor** — detecta "connection refused" e emite erro.
170
+ - **Túnel não encontrado** — identifica IDs/nomes inválidos.
171
+ - **Credenciais ausentes/inválidas** — orienta a reconfigurar com `cloudflared tunnel login`.
172
+ - **Timeout na inicialização** — configurável via opção `timeout`.
173
+ - **Processo encerrado inesperadamente** — emite evento `close` e limpa recursos.
174
+ - **Caminho personalizado inválido** — erro específico quando `cloudflaredPath` não existe.
175
+
74
176
  ## Adicionando novos provedores
75
177
 
76
178
  A arquitetura de `cm-tunnel` é modular. Para adicionar um novo provedor:
@@ -81,4 +183,4 @@ A arquitetura de `cm-tunnel` é modular. Para adicionar um novo provedor:
81
183
 
82
184
  ## Licença
83
185
 
84
- MIT
186
+ MIT
@@ -0,0 +1,23 @@
1
+ export interface ServeOptions {
2
+ html?: string;
3
+ directory?: string;
4
+ port?: number;
5
+ }
6
+ export declare class StaticServer {
7
+ private options;
8
+ private server;
9
+ port: number;
10
+ url: string;
11
+ constructor(options: ServeOptions);
12
+ start(): Promise<{
13
+ port: number;
14
+ url: string;
15
+ stop: () => void;
16
+ }>;
17
+ stop(): void;
18
+ }
19
+ export declare function serve(options: ServeOptions): Promise<{
20
+ port: number;
21
+ url: string;
22
+ stop: () => void;
23
+ }>;
@@ -0,0 +1,93 @@
1
+ import http from 'http';
2
+ import fs from 'fs';
3
+ import path from 'path';
4
+ const MIME_TYPES = {
5
+ '.html': 'text/html',
6
+ '.css': 'text/css',
7
+ '.js': 'text/javascript',
8
+ '.json': 'application/json',
9
+ '.png': 'image/png',
10
+ '.jpg': 'image/jpeg',
11
+ '.jpeg': 'image/jpeg',
12
+ '.gif': 'image/gif',
13
+ '.svg': 'image/svg+xml',
14
+ '.txt': 'text/plain',
15
+ '.ico': 'image/x-icon',
16
+ };
17
+ export class StaticServer {
18
+ options;
19
+ server = null;
20
+ port = 0;
21
+ url = '';
22
+ constructor(options) {
23
+ this.options = options;
24
+ }
25
+ start() {
26
+ return new Promise((resolve, reject) => {
27
+ this.server = http.createServer((req, res) => {
28
+ if (this.options.html) {
29
+ res.writeHead(200, { 'Content-Type': 'text/html' });
30
+ res.end(this.options.html);
31
+ return;
32
+ }
33
+ if (this.options.directory) {
34
+ let filePath = path.join(this.options.directory, req.url === '/' ? 'index.html' : (req.url || ''));
35
+ // Basic security check to prevent directory traversal
36
+ if (!filePath.startsWith(path.resolve(this.options.directory))) {
37
+ res.writeHead(403);
38
+ return res.end('Forbidden');
39
+ }
40
+ fs.stat(filePath, (err, stats) => {
41
+ if (err) {
42
+ res.writeHead(404);
43
+ return res.end('Not Found');
44
+ }
45
+ if (stats.isDirectory()) {
46
+ filePath = path.join(filePath, 'index.html');
47
+ }
48
+ const ext = path.extname(filePath).toLowerCase();
49
+ const contentType = MIME_TYPES[ext] || 'application/octet-stream';
50
+ fs.readFile(filePath, (err, content) => {
51
+ if (err) {
52
+ res.writeHead(500);
53
+ return res.end('Internal Server Error');
54
+ }
55
+ res.writeHead(200, { 'Content-Type': contentType });
56
+ res.end(content);
57
+ });
58
+ });
59
+ return;
60
+ }
61
+ res.writeHead(400);
62
+ res.end('No serve options provided (html or directory).');
63
+ });
64
+ this.server.on('error', reject);
65
+ const targetPort = this.options.port || 0;
66
+ this.server.listen(targetPort, '127.0.0.1', () => {
67
+ const address = this.server?.address();
68
+ if (address && typeof address !== 'string') {
69
+ this.port = address.port;
70
+ this.url = `http://127.0.0.1:${this.port}`;
71
+ resolve({
72
+ port: this.port,
73
+ url: this.url,
74
+ stop: this.stop.bind(this)
75
+ });
76
+ }
77
+ else {
78
+ reject(new Error('Failed to get server address'));
79
+ }
80
+ });
81
+ });
82
+ }
83
+ stop() {
84
+ if (this.server) {
85
+ this.server.close();
86
+ this.server = null;
87
+ }
88
+ }
89
+ }
90
+ export async function serve(options) {
91
+ const server = new StaticServer(options);
92
+ return await server.start();
93
+ }
package/dist/Tunnel.d.ts CHANGED
@@ -1,12 +1,17 @@
1
1
  import { EventEmitter } from "events";
2
2
  import { TunnelResult } from "./Provider.js";
3
3
  import { RateLimitOptions } from "./RateLimiter.js";
4
+ import { ServeOptions } from "./StaticServer.js";
5
+ import type { CloudflareMode, CloudflareOptions } from "./providers/cloudflare.js";
6
+ export type { CloudflareMode, CloudflareOptions };
4
7
  export interface TunnelOptions {
5
8
  provider: string;
6
- port: number;
9
+ port?: number;
7
10
  subdomain?: string;
8
11
  authtoken?: string;
9
12
  rateLimit?: RateLimitOptions | boolean;
13
+ serve?: ServeOptions;
14
+ cloudflare?: CloudflareOptions;
10
15
  }
11
16
  export interface TunnelInstance extends TunnelResult, EventEmitter {
12
17
  on(event: "ready", listener: (url: string) => void): this;
package/dist/Tunnel.js CHANGED
@@ -1,5 +1,31 @@
1
1
  import { EventEmitter } from "events";
2
2
  import { RateLimiter } from "./RateLimiter.js";
3
+ import { StaticServer } from "./StaticServer.js";
4
+ /**
5
+ * Valida as opções do Cloudflare antes de carregar o provider.
6
+ * Isso evita que erros de configuração só apareçam após o spawn do processo.
7
+ */
8
+ function validateCloudflareOptions(options) {
9
+ if (options.provider?.toLowerCase() !== "cloudflare" || !options.cloudflare) {
10
+ return;
11
+ }
12
+ const cf = options.cloudflare;
13
+ // Determina o modo efetivo
14
+ let mode = cf.mode || "quick";
15
+ if (mode === "quick" && (cf.domain || cf.tunnelId || cf.tunnelName)) {
16
+ mode = "named";
17
+ }
18
+ if (mode === "named") {
19
+ if (!cf.tunnelId && !cf.tunnelName) {
20
+ throw new Error('Cloudflare Named Tunnel requer "tunnelId" ou "tunnelName". ' +
21
+ 'Configure nas opções: cloudflare: { tunnelId: "...", domain: "..." }');
22
+ }
23
+ if (!cf.domain) {
24
+ throw new Error('Cloudflare Named Tunnel requer "domain" para identificar a URL pública. ' +
25
+ 'Configure nas opções: cloudflare: { domain: "api.meudominio.com.br" }');
26
+ }
27
+ }
28
+ }
3
29
  export async function createTunnel(options) {
4
30
  if (!options.port || isNaN(options.port)) {
5
31
  throw new Error("Porta inválida.");
@@ -7,6 +33,8 @@ export async function createTunnel(options) {
7
33
  if (!options.provider) {
8
34
  throw new Error("Provider inexistente.");
9
35
  }
36
+ // Valida opções do Cloudflare antes de tentar carregar o provider
37
+ validateCloudflareOptions(options);
10
38
  const providerName = options.provider.toLowerCase();
11
39
  let ProviderClass;
12
40
  try {
@@ -23,10 +51,17 @@ export async function createTunnel(options) {
23
51
  throw err;
24
52
  }
25
53
  let rateLimiterInstance = null;
26
- let targetPort = options.port;
54
+ let staticServerInstance = null;
55
+ // A porta do usuário (ou gerada pelo StaticServer) que o túnel/proxy vai mirar
56
+ let targetPort = options.port || 3000;
57
+ if (options.serve) {
58
+ staticServerInstance = new StaticServer(options.serve);
59
+ const serveResult = await staticServerInstance.start();
60
+ targetPort = serveResult.port; // O túnel ou proxy apontará para o StaticServer
61
+ }
27
62
  if (options.rateLimit) {
28
- rateLimiterInstance = new RateLimiter(options.port, options.rateLimit);
29
- targetPort = await rateLimiterInstance.start();
63
+ rateLimiterInstance = new RateLimiter(targetPort, options.rateLimit);
64
+ targetPort = await rateLimiterInstance.start(); // O túnel apontará para o proxy
30
65
  }
31
66
  const providerInstance = new ProviderClass({ ...options, port: targetPort });
32
67
  // We wrap the result in an EventEmitter to match the required API
@@ -34,6 +69,7 @@ export async function createTunnel(options) {
34
69
  providerInstance.on("ready", (url) => emitter.emit("ready", url));
35
70
  providerInstance.on("close", () => {
36
71
  rateLimiterInstance?.stop();
72
+ staticServerInstance?.stop();
37
73
  emitter.emit("close");
38
74
  });
39
75
  providerInstance.on("error", (err) => emitter.emit("error", err));
@@ -43,9 +79,10 @@ export async function createTunnel(options) {
43
79
  Object.assign(emitter, {
44
80
  provider: result.provider,
45
81
  url: result.url,
46
- port: options.port, // Return original user port
82
+ port: options.port || targetPort, // Return original user port or dynamic port
47
83
  stop: () => {
48
84
  rateLimiterInstance?.stop();
85
+ staticServerInstance?.stop();
49
86
  result.stop();
50
87
  },
51
88
  process: result.process,
package/dist/index.d.ts CHANGED
@@ -1,10 +1,33 @@
1
- import { TunnelOptions, TunnelInstance } from "./Tunnel.js";
1
+ import { TunnelOptions, TunnelInstance, CloudflareOptions, CloudflareMode } from './Tunnel.js';
2
+ import { ServeOptions } from './StaticServer.js';
2
3
  type OmitProvider<T> = Omit<T, "provider">;
4
+ interface CloudflareShortcutOptions extends OmitProvider<TunnelOptions> {
5
+ /** Domínio personalizado para Named Tunnels */
6
+ domain?: string;
7
+ /** ID do túnel Cloudflare */
8
+ tunnelId?: string;
9
+ /** Nome do túnel Cloudflare */
10
+ tunnelName?: string;
11
+ /** Arquivo de credenciais */
12
+ credentialsFile?: string;
13
+ /** Caminho do executável cloudflared */
14
+ cloudflaredPath?: string;
15
+ /** Timeout em ms */
16
+ timeout?: number;
17
+ /** Modo: "quick" ou "named" */
18
+ mode?: CloudflareMode;
19
+ }
3
20
  interface TunnelAPI {
4
21
  (options: TunnelOptions): Promise<TunnelInstance>;
5
- cloudflare: (options: OmitProvider<TunnelOptions>) => Promise<TunnelInstance>;
22
+ cloudflare: (options: CloudflareShortcutOptions) => Promise<TunnelInstance>;
6
23
  localtunnel: (options: OmitProvider<TunnelOptions>) => Promise<TunnelInstance>;
7
24
  ngrok: (options: OmitProvider<TunnelOptions>) => Promise<TunnelInstance>;
25
+ serve: (options: ServeOptions) => Promise<{
26
+ port: number;
27
+ url: string;
28
+ stop: () => void;
29
+ }>;
8
30
  }
9
31
  declare const tunnel: TunnelAPI;
10
32
  export default tunnel;
33
+ export type { TunnelOptions, TunnelInstance, CloudflareOptions, CloudflareMode, CloudflareShortcutOptions };
package/dist/index.js CHANGED
@@ -1,6 +1,34 @@
1
- import { createTunnel } from "./Tunnel.js";
1
+ import { createTunnel } from './Tunnel.js';
2
+ import { serve } from './StaticServer.js';
2
3
  const tunnel = createTunnel;
3
- tunnel.cloudflare = (options) => createTunnel({ ...options, provider: 'cloudflare' });
4
+ tunnel.cloudflare = (options) => {
5
+ const { domain, tunnelId, tunnelName, credentialsFile, cloudflaredPath, timeout, mode, ...rest } = options;
6
+ // Monta o objeto cloudflare a partir das opções de atalho
7
+ const cloudflareOpts = {};
8
+ if (mode !== undefined)
9
+ cloudflareOpts.mode = mode;
10
+ if (domain !== undefined)
11
+ cloudflareOpts.domain = domain;
12
+ if (tunnelId !== undefined)
13
+ cloudflareOpts.tunnelId = tunnelId;
14
+ if (tunnelName !== undefined)
15
+ cloudflareOpts.tunnelName = tunnelName;
16
+ if (credentialsFile !== undefined)
17
+ cloudflareOpts.credentialsFile = credentialsFile;
18
+ if (cloudflaredPath !== undefined)
19
+ cloudflareOpts.cloudflaredPath = cloudflaredPath;
20
+ if (timeout !== undefined)
21
+ cloudflareOpts.timeout = timeout;
22
+ // Merge: se o usuário já passou cloudflare: {...}, combina
23
+ const existingCloudflare = rest.cloudflare || {};
24
+ const mergedCloudflare = { ...existingCloudflare, ...cloudflareOpts };
25
+ return createTunnel({
26
+ ...rest,
27
+ provider: 'cloudflare',
28
+ cloudflare: Object.keys(mergedCloudflare).length > 0 ? mergedCloudflare : undefined,
29
+ });
30
+ };
4
31
  tunnel.localtunnel = (options) => createTunnel({ ...options, provider: 'localtunnel' });
5
32
  tunnel.ngrok = (options) => createTunnel({ ...options, provider: 'ngrok' });
33
+ tunnel.serve = serve;
6
34
  export default tunnel;
@@ -1,8 +1,41 @@
1
1
  import { Provider, ProviderOptions, TunnelResult } from "../Provider.js";
2
+ export type CloudflareMode = "quick" | "named";
3
+ export interface CloudflareOptions {
4
+ /** Modo do túnel: "quick" (padrão) ou "named" */
5
+ mode?: CloudflareMode;
6
+ /** Domínio personalizado para Named Tunnels (ex: "api.meudominio.com.br") */
7
+ domain?: string;
8
+ /** ID do túnel Cloudflare previamente criado */
9
+ tunnelId?: string;
10
+ /** Nome do túnel Cloudflare (alternativa ao tunnelId) */
11
+ tunnelName?: string;
12
+ /** Caminho para o arquivo de credenciais do túnel (.json) */
13
+ credentialsFile?: string;
14
+ /** Caminho para o executável cloudflared (se não estiver no PATH) */
15
+ cloudflaredPath?: string;
16
+ /** Timeout em ms para aguardar a inicialização (padrão: 30000) */
17
+ timeout?: number;
18
+ }
19
+ interface CloudflareProviderOptions extends ProviderOptions {
20
+ cloudflare?: CloudflareOptions;
21
+ }
2
22
  export default class CloudflareProvider extends Provider {
3
23
  private cp;
4
24
  private urlRegex;
5
- constructor(options: ProviderOptions);
25
+ private cloudflareOpts;
26
+ private mode;
27
+ constructor(options: CloudflareProviderOptions);
28
+ private get executable();
29
+ private get timeout();
30
+ /**
31
+ * Valida as opções antes de iniciar, lançando erros claros.
32
+ */
33
+ private validateOptions;
34
+ /**
35
+ * Monta os argumentos do cloudflared conforme o modo.
36
+ */
37
+ private buildArgs;
6
38
  start(): Promise<TunnelResult>;
7
39
  stop(): void;
8
40
  }
41
+ export {};
@@ -3,21 +3,105 @@ import { Provider } from "../Provider.js";
3
3
  export default class CloudflareProvider extends Provider {
4
4
  cp = null;
5
5
  urlRegex = /(https:\/\/[a-zA-Z0-9-]+\.trycloudflare\.com)/;
6
+ cloudflareOpts;
7
+ mode;
6
8
  constructor(options) {
7
9
  super(options);
10
+ this.cloudflareOpts = options.cloudflare || {};
11
+ this.mode = this.cloudflareOpts.mode || "quick";
12
+ // Se o usuário forneceu domain ou tunnelId sem especificar mode, assume "named"
13
+ if (this.mode === "quick" &&
14
+ (this.cloudflareOpts.domain || this.cloudflareOpts.tunnelId || this.cloudflareOpts.tunnelName)) {
15
+ this.mode = "named";
16
+ }
17
+ }
18
+ get executable() {
19
+ return this.cloudflareOpts.cloudflaredPath || "cloudflared";
20
+ }
21
+ get timeout() {
22
+ return this.cloudflareOpts.timeout || 30000;
23
+ }
24
+ /**
25
+ * Valida as opções antes de iniciar, lançando erros claros.
26
+ */
27
+ validateOptions() {
28
+ if (this.mode === "named") {
29
+ if (!this.cloudflareOpts.tunnelId && !this.cloudflareOpts.tunnelName) {
30
+ throw new Error('Cloudflare Named Tunnel requer "tunnelId" ou "tunnelName". ' +
31
+ 'Configure nas opções: cloudflare: { tunnelId: "...", domain: "..." }');
32
+ }
33
+ if (!this.cloudflareOpts.domain) {
34
+ throw new Error('Cloudflare Named Tunnel requer "domain" para identificar a URL pública. ' +
35
+ 'Configure nas opções: cloudflare: { domain: "api.meudominio.com.br" }');
36
+ }
37
+ }
38
+ }
39
+ /**
40
+ * Monta os argumentos do cloudflared conforme o modo.
41
+ */
42
+ buildArgs() {
43
+ if (this.mode === "named") {
44
+ const args = ["tunnel"];
45
+ if (this.cloudflareOpts.credentialsFile) {
46
+ args.push("--credentials-file", this.cloudflareOpts.credentialsFile);
47
+ }
48
+ args.push("--url", `http://localhost:${this.port}`);
49
+ args.push("run");
50
+ if (this.cloudflareOpts.tunnelId) {
51
+ args.push(this.cloudflareOpts.tunnelId);
52
+ }
53
+ else if (this.cloudflareOpts.tunnelName) {
54
+ args.push(this.cloudflareOpts.tunnelName);
55
+ }
56
+ return args;
57
+ }
58
+ // Modo quick (padrão) — mantém o comportamento original
59
+ return ["tunnel", "--url", `http://localhost:${this.port}`];
8
60
  }
9
61
  start() {
62
+ this.validateOptions();
10
63
  return new Promise((resolve, reject) => {
11
- this.cp = spawn("cloudflared", [
12
- "tunnel",
13
- "--url",
14
- `http://localhost:${this.port}`,
15
- ]);
16
64
  let isResolved = false;
65
+ let timeoutId = null;
66
+ const cleanup = () => {
67
+ if (timeoutId) {
68
+ clearTimeout(timeoutId);
69
+ timeoutId = null;
70
+ }
71
+ };
72
+ const makeResult = (url) => ({
73
+ provider: "cloudflare",
74
+ url,
75
+ port: this.port,
76
+ stop: this.stop.bind(this),
77
+ process: this.cp,
78
+ });
79
+ // Timeout de inicialização
80
+ timeoutId = setTimeout(() => {
81
+ if (!isResolved) {
82
+ isResolved = true;
83
+ const err = new Error(`Timeout: Cloudflare Tunnel não iniciou em ${this.timeout / 1000}s. ` +
84
+ `Verifique se o cloudflared está configurado corretamente.`);
85
+ this.stop();
86
+ reject(err);
87
+ }
88
+ }, this.timeout);
89
+ try {
90
+ this.cp = spawn(this.executable, this.buildArgs());
91
+ }
92
+ catch (err) {
93
+ cleanup();
94
+ reject(new Error(`Falha ao executar cloudflared: ${err.message}`));
95
+ return;
96
+ }
17
97
  this.cp.on("error", (err) => {
98
+ cleanup();
18
99
  if (err.code === "ENOENT") {
19
- const errorMsg = "Cloudflared não encontrado. Por favor, instale-o a partir de https://developers.cloudflare.com/cloudflare-one/connections/connect-networks/downloads/";
100
+ const errorMsg = this.cloudflareOpts.cloudflaredPath
101
+ ? `Cloudflared não encontrado no caminho especificado: "${this.cloudflareOpts.cloudflaredPath}". Verifique se o caminho está correto.`
102
+ : "Cloudflared não encontrado. Por favor, instale-o a partir de https://developers.cloudflare.com/cloudflare-one/connections/connect-networks/downloads/";
20
103
  if (!isResolved) {
104
+ isResolved = true;
21
105
  reject(new Error(errorMsg));
22
106
  }
23
107
  else {
@@ -26,6 +110,7 @@ export default class CloudflareProvider extends Provider {
26
110
  }
27
111
  else {
28
112
  if (!isResolved) {
113
+ isResolved = true;
29
114
  reject(err);
30
115
  }
31
116
  else {
@@ -33,27 +118,71 @@ export default class CloudflareProvider extends Provider {
33
118
  }
34
119
  }
35
120
  });
36
- this.cp.stderr?.on("data", (data) => {
121
+ // Escuta em stderr (cloudflared emite logs em stderr)
122
+ const handleOutput = (data) => {
37
123
  const text = data.toString();
38
- const match = text.match(this.urlRegex);
39
- if (match && match[1]) {
40
- const url = match[1];
124
+ if (this.mode === "quick") {
125
+ // Quick tunnel: busca a URL trycloudflare.com na saída
126
+ const match = text.match(this.urlRegex);
127
+ if (match && match[1]) {
128
+ const url = match[1];
129
+ if (!isResolved) {
130
+ isResolved = true;
131
+ cleanup();
132
+ this.emit("ready", url);
133
+ resolve(makeResult(url));
134
+ }
135
+ }
136
+ }
137
+ else {
138
+ // Named tunnel: detecta que a conexão foi estabelecida
139
+ // O cloudflared emite "Registered tunnel connection" ou "Connection ... registered"
140
+ // quando está pronto para aceitar tráfego
141
+ if (text.includes("Registered tunnel connection") ||
142
+ text.includes("registered connIndex=") ||
143
+ (text.includes("Connection") && text.includes("registered"))) {
144
+ if (!isResolved) {
145
+ isResolved = true;
146
+ cleanup();
147
+ const url = `https://${this.cloudflareOpts.domain}`;
148
+ this.emit("ready", url);
149
+ resolve(makeResult(url));
150
+ }
151
+ }
152
+ }
153
+ // Detecta erros conhecidos nos dois modos
154
+ const lowerText = text.toLowerCase();
155
+ if (lowerText.includes("connection refused")) {
156
+ const err = new Error(`A porta ${this.port} não possui nenhum servidor ativo.`);
157
+ if (!isResolved) {
158
+ cleanup();
159
+ isResolved = true;
160
+ reject(err);
161
+ this.stop();
162
+ }
163
+ else {
164
+ this.emit("error", err);
165
+ }
166
+ }
167
+ if (lowerText.includes("tunnel credentials file") && lowerText.includes("not found")) {
168
+ const err = new Error("Arquivo de credenciais do túnel não encontrado. " +
169
+ "Verifique o caminho em 'credentialsFile' ou configure o túnel com: cloudflared tunnel login");
41
170
  if (!isResolved) {
171
+ cleanup();
42
172
  isResolved = true;
43
- this.emit("ready", url);
44
- resolve({
45
- provider: "cloudflare",
46
- url,
47
- port: this.port,
48
- stop: this.stop.bind(this),
49
- process: this.cp,
50
- });
173
+ reject(err);
174
+ this.stop();
175
+ }
176
+ else {
177
+ this.emit("error", err);
51
178
  }
52
179
  }
53
- // Detect known errors like connection refused
54
- if (text.toLowerCase().includes("connection refused")) {
55
- const err = new Error(`A porta ${this.port} não possui nenhum servidor ativo.`);
180
+ if (lowerText.includes("tunnel not found") || lowerText.includes("does not exist")) {
181
+ const err = new Error(`Túnel "${this.cloudflareOpts.tunnelId || this.cloudflareOpts.tunnelName}" não encontrado. ` +
182
+ "Verifique se o ID ou nome do túnel está correto.");
56
183
  if (!isResolved) {
184
+ cleanup();
185
+ isResolved = true;
57
186
  reject(err);
58
187
  this.stop();
59
188
  }
@@ -61,9 +190,25 @@ export default class CloudflareProvider extends Provider {
61
190
  this.emit("error", err);
62
191
  }
63
192
  }
64
- });
193
+ if (lowerText.includes("error") && lowerText.includes("credential")) {
194
+ const err = new Error("Credenciais do túnel Cloudflare inválidas. Reconfigure com: cloudflared tunnel login");
195
+ if (!isResolved) {
196
+ cleanup();
197
+ isResolved = true;
198
+ reject(err);
199
+ this.stop();
200
+ }
201
+ else {
202
+ this.emit("error", err);
203
+ }
204
+ }
205
+ };
206
+ this.cp.stderr?.on("data", handleOutput);
207
+ this.cp.stdout?.on("data", handleOutput);
65
208
  this.cp.on("close", (code) => {
209
+ cleanup();
66
210
  if (!isResolved && code !== 0) {
211
+ isResolved = true;
67
212
  reject(new Error(`Falha ao iniciar o túnel. Cloudflared encerrou com código ${code}.`));
68
213
  }
69
214
  this.emit("close");
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "cm-tunnel",
3
- "version": "1.2.0",
3
+ "version": "1.3.1",
4
4
  "description": "Exponha seu servidor HTTP local para a internet através do Cloudflare ou LocalTunnel de forma simples",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",
@@ -30,7 +30,7 @@
30
30
  "http",
31
31
  "localhost"
32
32
  ],
33
- "author": "",
33
+ "author": "caiomultiversando",
34
34
  "license": "MIT",
35
35
  "repository": {
36
36
  "type": "git",