cm-tunnel 1.3.0 → 1.3.2

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
@@ -63,6 +63,75 @@ const t2 = await tunnel.localtunnel({ port: 3000 });
63
63
  const t3 = await tunnel.ngrok({ port: 3000, authtoken: 'seu_token' });
64
64
  ```
65
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
+
66
135
  ### Servidor HTML/Estático Standalone (Sem Túnel)
67
136
 
68
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):
@@ -92,6 +161,18 @@ A função retorna uma Promise que resolve em um objeto `TunnelInstance` contend
92
161
 
93
162
  O objeto retornado também é um `EventEmitter`, emitindo os eventos `ready`, `close` e `error`.
94
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
+
95
176
  ## Adicionando novos provedores
96
177
 
97
178
  A arquitetura de `cm-tunnel` é modular. Para adicionar um novo provedor:
@@ -102,4 +183,4 @@ A arquitetura de `cm-tunnel` é modular. Para adicionar um novo provedor:
102
183
 
103
184
  ## Licença
104
185
 
105
- MIT
186
+ MIT
package/dist/Tunnel.d.ts CHANGED
@@ -2,6 +2,8 @@ import { EventEmitter } from "events";
2
2
  import { TunnelResult } from "./Provider.js";
3
3
  import { RateLimitOptions } from "./RateLimiter.js";
4
4
  import { ServeOptions } from "./StaticServer.js";
5
+ import type { CloudflareMode, CloudflareOptions } from "./providers/cloudflare.js";
6
+ export type { CloudflareMode, CloudflareOptions };
5
7
  export interface TunnelOptions {
6
8
  provider: string;
7
9
  port?: number;
@@ -9,6 +11,7 @@ export interface TunnelOptions {
9
11
  authtoken?: string;
10
12
  rateLimit?: RateLimitOptions | boolean;
11
13
  serve?: ServeOptions;
14
+ cloudflare?: CloudflareOptions;
12
15
  }
13
16
  export interface TunnelInstance extends TunnelResult, EventEmitter {
14
17
  on(event: "ready", listener: (url: string) => void): this;
package/dist/Tunnel.js CHANGED
@@ -1,6 +1,54 @@
1
1
  import { EventEmitter } from "events";
2
+ import { existsSync } from "fs";
2
3
  import { RateLimiter } from "./RateLimiter.js";
3
4
  import { StaticServer } from "./StaticServer.js";
5
+ /**
6
+ * Determina o modo efetivo do Cloudflare com base nas opções.
7
+ */
8
+ function resolveCloudflareMode(cf) {
9
+ if (cf.mode)
10
+ return cf.mode;
11
+ if (cf.token || cf.tunnelId || cf.tunnelName || cf.credentialsFile || cf.domain) {
12
+ return "named";
13
+ }
14
+ return "quick";
15
+ }
16
+ /**
17
+ * Valida as opções do Cloudflare antes de carregar o provider.
18
+ * Erros de configuração são capturados aqui, antes do spawn do processo.
19
+ */
20
+ function validateCloudflareOptions(options) {
21
+ if (options.provider?.toLowerCase() !== "cloudflare" || !options.cloudflare) {
22
+ return;
23
+ }
24
+ const cf = options.cloudflare;
25
+ const mode = resolveCloudflareMode(cf);
26
+ if (mode === "named") {
27
+ const hasToken = !!cf.token;
28
+ const hasCredentials = !!cf.credentialsFile;
29
+ const hasTunnelRef = !!(cf.tunnelId || cf.tunnelName);
30
+ // Com token: não precisa de tunnelId/credenciais (token já contém tudo)
31
+ if (!hasToken) {
32
+ if (!hasTunnelRef) {
33
+ throw new Error('Cloudflare Named Tunnel requer "token" ou "tunnelId"/"tunnelName". ' +
34
+ "Use token: process.env.CLOUDFLARE_TOKEN ou forneça tunnelId com credentialsFile.");
35
+ }
36
+ if (!hasCredentials) {
37
+ throw new Error("Cloudflare Named Tunnel sem token requer credentialsFile. " +
38
+ "Forneça o caminho do arquivo JSON de credenciais ou use autenticação por token.");
39
+ }
40
+ }
41
+ // Token e credenciais não devem ser usados juntos
42
+ if (hasToken && hasCredentials) {
43
+ throw new Error("Não utilize token e credentialsFile simultaneamente. Escolha um método de autenticação.");
44
+ }
45
+ // Validar se o arquivo de credenciais existe quando informado
46
+ if (hasCredentials && !existsSync(cf.credentialsFile)) {
47
+ throw new Error(`Arquivo de credenciais não encontrado: "${cf.credentialsFile}". ` +
48
+ "Verifique o caminho ou use autenticação por token.");
49
+ }
50
+ }
51
+ }
4
52
  export async function createTunnel(options) {
5
53
  if (!options.port || isNaN(options.port)) {
6
54
  throw new Error("Porta inválida.");
@@ -8,6 +56,8 @@ export async function createTunnel(options) {
8
56
  if (!options.provider) {
9
57
  throw new Error("Provider inexistente.");
10
58
  }
59
+ // Valida opções do Cloudflare antes de tentar carregar o provider
60
+ validateCloudflareOptions(options);
11
61
  const providerName = options.provider.toLowerCase();
12
62
  let ProviderClass;
13
63
  try {
package/dist/index.d.ts CHANGED
@@ -1,9 +1,29 @@
1
- import { TunnelOptions, TunnelInstance } from './Tunnel.js';
1
+ import { TunnelOptions, TunnelInstance, CloudflareOptions, CloudflareMode } from './Tunnel.js';
2
2
  import { ServeOptions } from './StaticServer.js';
3
3
  type OmitProvider<T> = Omit<T, "provider">;
4
+ interface CloudflareShortcutOptions extends OmitProvider<TunnelOptions> {
5
+ /** Domínio personalizado para Named Tunnels (DNS deve estar previamente configurado na Cloudflare) */
6
+ domain?: string;
7
+ /** ID do túnel Cloudflare */
8
+ tunnelId?: string;
9
+ /** Nome do túnel Cloudflare (alternativa ao tunnelId) */
10
+ tunnelName?: string;
11
+ /** Token de autenticação do túnel. Recomendado usar variável de ambiente (ex: process.env.CLOUDFLARE_TOKEN) */
12
+ token?: string;
13
+ /** Arquivo de credenciais JSON (alternativa ao token) */
14
+ credentialsFile?: string;
15
+ /** Caminho do executável cloudflared */
16
+ cloudflaredPath?: string;
17
+ /** Timeout em ms (padrão: 30000) */
18
+ timeout?: number;
19
+ /** Modo: "quick" ou "named" (inferido automaticamente) */
20
+ mode?: CloudflareMode;
21
+ /** Protocolo da URL (padrão: "https") */
22
+ protocol?: string;
23
+ }
4
24
  interface TunnelAPI {
5
25
  (options: TunnelOptions): Promise<TunnelInstance>;
6
- cloudflare: (options: OmitProvider<TunnelOptions>) => Promise<TunnelInstance>;
26
+ cloudflare: (options: CloudflareShortcutOptions) => Promise<TunnelInstance>;
7
27
  localtunnel: (options: OmitProvider<TunnelOptions>) => Promise<TunnelInstance>;
8
28
  ngrok: (options: OmitProvider<TunnelOptions>) => Promise<TunnelInstance>;
9
29
  serve: (options: ServeOptions) => Promise<{
@@ -14,3 +34,4 @@ interface TunnelAPI {
14
34
  }
15
35
  declare const tunnel: TunnelAPI;
16
36
  export default tunnel;
37
+ export type { TunnelOptions, TunnelInstance, CloudflareOptions, CloudflareMode, CloudflareShortcutOptions };
package/dist/index.js CHANGED
@@ -1,7 +1,37 @@
1
1
  import { createTunnel } from './Tunnel.js';
2
2
  import { serve } from './StaticServer.js';
3
3
  const tunnel = createTunnel;
4
- tunnel.cloudflare = (options) => createTunnel({ ...options, provider: 'cloudflare' });
4
+ tunnel.cloudflare = (options) => {
5
+ const { domain, tunnelId, tunnelName, token, credentialsFile, cloudflaredPath, timeout, mode, protocol, ...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 (token !== undefined)
17
+ cloudflareOpts.token = token;
18
+ if (credentialsFile !== undefined)
19
+ cloudflareOpts.credentialsFile = credentialsFile;
20
+ if (cloudflaredPath !== undefined)
21
+ cloudflareOpts.cloudflaredPath = cloudflaredPath;
22
+ if (timeout !== undefined)
23
+ cloudflareOpts.timeout = timeout;
24
+ if (protocol !== undefined)
25
+ cloudflareOpts.protocol = protocol;
26
+ // Merge: se o usuário já passou cloudflare: {...}, combina
27
+ const existingCloudflare = rest.cloudflare || {};
28
+ const mergedCloudflare = { ...existingCloudflare, ...cloudflareOpts };
29
+ return createTunnel({
30
+ ...rest,
31
+ provider: 'cloudflare',
32
+ cloudflare: Object.keys(mergedCloudflare).length > 0 ? mergedCloudflare : undefined,
33
+ });
34
+ };
5
35
  tunnel.localtunnel = (options) => createTunnel({ ...options, provider: 'localtunnel' });
6
36
  tunnel.ngrok = (options) => createTunnel({ ...options, provider: 'ngrok' });
7
37
  tunnel.serve = serve;
@@ -1,8 +1,63 @@
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". Inferido automaticamente se token, tunnelId ou tunnelName forem fornecidos. */
5
+ mode?: CloudflareMode;
6
+ /** Domínio personalizado associado ao túnel (ex: "api.meudominio.com.br"). O DNS deve estar previamente configurado na Cloudflare. */
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
+ /** Token de autenticação do túnel (obtido na dashboard ou via `cloudflared tunnel token <TUNNEL>`). Recomendado usar variável de ambiente. */
13
+ token?: string;
14
+ /** Caminho para o arquivo de credenciais JSON do túnel (alternativa ao token) */
15
+ credentialsFile?: string;
16
+ /** Caminho para o executável cloudflared (se não estiver no PATH) */
17
+ cloudflaredPath?: string;
18
+ /** Timeout em ms para aguardar a inicialização (padrão: 30000) */
19
+ timeout?: number;
20
+ /** Protocolo da URL retornada (padrão: "https") */
21
+ protocol?: string;
22
+ }
23
+ interface CloudflareProviderOptions extends ProviderOptions {
24
+ cloudflare?: CloudflareOptions;
25
+ }
2
26
  export default class CloudflareProvider extends Provider {
3
27
  private cp;
4
28
  private urlRegex;
5
- constructor(options: ProviderOptions);
29
+ private cloudflareOpts;
30
+ private mode;
31
+ constructor(options: CloudflareProviderOptions);
32
+ /**
33
+ * Determina o modo efetivo com base nas opções fornecidas.
34
+ */
35
+ private resolveMode;
36
+ private get executable();
37
+ private get timeoutMs();
38
+ private get protocol();
39
+ /**
40
+ * Valida as opções antes de iniciar, lançando erros claros e específicos.
41
+ */
42
+ private validateOptions;
43
+ /**
44
+ * Monta os argumentos do cloudflared conforme o modo e método de autenticação.
45
+ *
46
+ * Quick Tunnel:
47
+ * cloudflared tunnel --url http://localhost:PORT
48
+ *
49
+ * Named Tunnel com token:
50
+ * cloudflared tunnel --url http://localhost:PORT run --token <TOKEN>
51
+ *
52
+ * Named Tunnel com credenciais:
53
+ * cloudflared tunnel --credentials-file <FILE> --url http://localhost:PORT run <TUNNEL_ID|NAME>
54
+ */
55
+ private buildArgs;
56
+ /**
57
+ * Constrói a URL pública do túnel named.
58
+ */
59
+ private buildNamedUrl;
6
60
  start(): Promise<TunnelResult>;
7
61
  stop(): void;
8
62
  }
63
+ export {};
@@ -1,70 +1,281 @@
1
1
  import { spawn } from "child_process";
2
+ import { existsSync } from "fs";
2
3
  import { Provider } from "../Provider.js";
4
+ /**
5
+ * Remove tokens e segredos de uma string de log/erro.
6
+ */
7
+ function sanitizeOutput(text, token) {
8
+ let sanitized = text;
9
+ if (token && token.length > 8) {
10
+ sanitized = sanitized.replace(new RegExp(escapeRegex(token), "g"), "[TOKEN OCULTO]");
11
+ }
12
+ // Remove padrões comuns de JWT tokens em logs do cloudflared
13
+ sanitized = sanitized.replace(/eyJ[A-Za-z0-9_-]+\.eyJ[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+/g, "[TOKEN OCULTO]");
14
+ return sanitized;
15
+ }
16
+ function escapeRegex(str) {
17
+ return str.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
18
+ }
3
19
  export default class CloudflareProvider extends Provider {
4
20
  cp = null;
5
21
  urlRegex = /(https:\/\/[a-zA-Z0-9-]+\.trycloudflare\.com)/;
22
+ cloudflareOpts;
23
+ mode;
6
24
  constructor(options) {
7
25
  super(options);
26
+ this.cloudflareOpts = options.cloudflare || {};
27
+ this.mode = this.resolveMode();
28
+ }
29
+ /**
30
+ * Determina o modo efetivo com base nas opções fornecidas.
31
+ */
32
+ resolveMode() {
33
+ if (this.cloudflareOpts.mode) {
34
+ return this.cloudflareOpts.mode;
35
+ }
36
+ if (this.cloudflareOpts.token ||
37
+ this.cloudflareOpts.tunnelId ||
38
+ this.cloudflareOpts.tunnelName ||
39
+ this.cloudflareOpts.credentialsFile ||
40
+ this.cloudflareOpts.domain) {
41
+ return "named";
42
+ }
43
+ return "quick";
44
+ }
45
+ get executable() {
46
+ return this.cloudflareOpts.cloudflaredPath || "cloudflared";
47
+ }
48
+ get timeoutMs() {
49
+ return this.cloudflareOpts.timeout || 30000;
50
+ }
51
+ get protocol() {
52
+ return this.cloudflareOpts.protocol || "https";
53
+ }
54
+ /**
55
+ * Valida as opções antes de iniciar, lançando erros claros e específicos.
56
+ */
57
+ validateOptions() {
58
+ if (this.mode === "named") {
59
+ const hasToken = !!this.cloudflareOpts.token;
60
+ const hasCredentials = !!this.cloudflareOpts.credentialsFile;
61
+ const hasTunnelRef = !!(this.cloudflareOpts.tunnelId || this.cloudflareOpts.tunnelName);
62
+ if (!hasToken) {
63
+ if (!hasTunnelRef) {
64
+ throw new Error('Cloudflare Named Tunnel requer "token" ou "tunnelId"/"tunnelName". ' +
65
+ "Use token: process.env.CLOUDFLARE_TOKEN ou forneça tunnelId com credentialsFile.");
66
+ }
67
+ if (!hasCredentials) {
68
+ throw new Error("Cloudflare Named Tunnel sem token requer credentialsFile. " +
69
+ "Forneça o caminho do arquivo JSON de credenciais ou use autenticação por token.");
70
+ }
71
+ }
72
+ // Validar se o arquivo de credenciais existe quando informado
73
+ if (hasCredentials && !existsSync(this.cloudflareOpts.credentialsFile)) {
74
+ throw new Error(`Arquivo de credenciais não encontrado: "${this.cloudflareOpts.credentialsFile}". ` +
75
+ "Verifique o caminho ou use autenticação por token.");
76
+ }
77
+ // Token e credenciais não devem ser usados simultaneamente
78
+ if (hasToken && hasCredentials) {
79
+ throw new Error("Não utilize token e credentialsFile simultaneamente. Escolha um método de autenticação.");
80
+ }
81
+ }
82
+ }
83
+ /**
84
+ * Monta os argumentos do cloudflared conforme o modo e método de autenticação.
85
+ *
86
+ * Quick Tunnel:
87
+ * cloudflared tunnel --url http://localhost:PORT
88
+ *
89
+ * Named Tunnel com token:
90
+ * cloudflared tunnel --url http://localhost:PORT run --token <TOKEN>
91
+ *
92
+ * Named Tunnel com credenciais:
93
+ * cloudflared tunnel --credentials-file <FILE> --url http://localhost:PORT run <TUNNEL_ID|NAME>
94
+ */
95
+ buildArgs() {
96
+ if (this.mode === "named") {
97
+ if (this.cloudflareOpts.token) {
98
+ return [
99
+ "tunnel",
100
+ "--url", `http://localhost:${this.port}`,
101
+ "run",
102
+ "--token", this.cloudflareOpts.token,
103
+ ];
104
+ }
105
+ // Credentials mode
106
+ const args = ["tunnel"];
107
+ if (this.cloudflareOpts.credentialsFile) {
108
+ args.push("--credentials-file", this.cloudflareOpts.credentialsFile);
109
+ }
110
+ args.push("--url", `http://localhost:${this.port}`);
111
+ args.push("run");
112
+ if (this.cloudflareOpts.tunnelId) {
113
+ args.push(this.cloudflareOpts.tunnelId);
114
+ }
115
+ else if (this.cloudflareOpts.tunnelName) {
116
+ args.push(this.cloudflareOpts.tunnelName);
117
+ }
118
+ return args;
119
+ }
120
+ // Quick Tunnel
121
+ return ["tunnel", "--url", `http://localhost:${this.port}`];
122
+ }
123
+ /**
124
+ * Constrói a URL pública do túnel named.
125
+ */
126
+ buildNamedUrl() {
127
+ if (this.cloudflareOpts.domain) {
128
+ return `${this.protocol}://${this.cloudflareOpts.domain}`;
129
+ }
130
+ const tunnelRef = this.cloudflareOpts.tunnelId || this.cloudflareOpts.tunnelName || "tunnel";
131
+ return `${this.protocol}://${tunnelRef}.cfargotunnel.com`;
8
132
  }
9
133
  start() {
134
+ this.validateOptions();
10
135
  return new Promise((resolve, reject) => {
11
- this.cp = spawn("cloudflared", [
12
- "tunnel",
13
- "--url",
14
- `http://localhost:${this.port}`,
15
- ]);
16
136
  let isResolved = false;
137
+ let timeoutId = null;
138
+ const token = this.cloudflareOpts.token;
139
+ const cleanup = () => {
140
+ if (timeoutId) {
141
+ clearTimeout(timeoutId);
142
+ timeoutId = null;
143
+ }
144
+ };
145
+ const finish = (err) => {
146
+ if (!isResolved) {
147
+ isResolved = true;
148
+ cleanup();
149
+ reject(err);
150
+ this.stop();
151
+ }
152
+ else {
153
+ this.emit("error", err);
154
+ }
155
+ };
156
+ const makeResult = (url) => ({
157
+ provider: "cloudflare",
158
+ url,
159
+ port: this.port,
160
+ stop: this.stop.bind(this),
161
+ process: this.cp,
162
+ });
163
+ // Timeout de inicialização
164
+ timeoutId = setTimeout(() => {
165
+ if (!isResolved) {
166
+ isResolved = true;
167
+ const err = new Error(`Timeout: Cloudflare Tunnel não iniciou em ${this.timeoutMs / 1000}s. ` +
168
+ "Verifique se o cloudflared está configurado corretamente e se as credenciais são válidas.");
169
+ this.stop();
170
+ reject(err);
171
+ }
172
+ }, this.timeoutMs);
173
+ // Spawn do processo
174
+ try {
175
+ this.cp = spawn(this.executable, this.buildArgs());
176
+ }
177
+ catch (err) {
178
+ cleanup();
179
+ reject(new Error(`Falha ao executar cloudflared: ${sanitizeOutput(err.message, token)}`));
180
+ return;
181
+ }
182
+ // Erro de spawn (ENOENT, permissão, etc.)
17
183
  this.cp.on("error", (err) => {
184
+ cleanup();
18
185
  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/";
20
- if (!isResolved) {
21
- reject(new Error(errorMsg));
22
- }
23
- else {
24
- this.emit("error", new Error(errorMsg));
25
- }
186
+ const errorMsg = this.cloudflareOpts.cloudflaredPath
187
+ ? `Cloudflared não encontrado em: "${this.cloudflareOpts.cloudflaredPath}". Verifique se o caminho está correto.`
188
+ : "Cloudflared não encontrado. Instale a partir de: https://developers.cloudflare.com/cloudflare-one/connections/connect-networks/downloads/";
189
+ finish(new Error(errorMsg));
26
190
  }
27
191
  else {
28
- if (!isResolved) {
29
- reject(err);
30
- }
31
- else {
32
- this.emit("error", err);
33
- }
192
+ finish(new Error(sanitizeOutput(err.message, token)));
34
193
  }
35
194
  });
36
- this.cp.stderr?.on("data", (data) => {
195
+ // Handler unificado para stdout e stderr
196
+ const handleOutput = (data) => {
37
197
  const text = data.toString();
38
- const match = text.match(this.urlRegex);
39
- if (match && match[1]) {
40
- const url = match[1];
41
- if (!isResolved) {
198
+ const lowerText = text.toLowerCase();
199
+ // ---- Detecção de sucesso ----
200
+ if (this.mode === "quick") {
201
+ const match = text.match(this.urlRegex);
202
+ if (match && match[1] && !isResolved) {
42
203
  isResolved = true;
204
+ cleanup();
205
+ const url = match[1];
43
206
  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
- });
207
+ resolve(makeResult(url));
208
+ return;
51
209
  }
52
210
  }
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.`);
56
- if (!isResolved) {
57
- reject(err);
58
- this.stop();
59
- }
60
- else {
61
- this.emit("error", err);
211
+ else {
212
+ // Named tunnel: detecta conexão estabelecida
213
+ if ((text.includes("Registered tunnel connection") ||
214
+ text.includes("registered connIndex=") ||
215
+ (text.includes("Connection") && text.includes("registered"))) &&
216
+ !isResolved) {
217
+ isResolved = true;
218
+ cleanup();
219
+ const url = this.buildNamedUrl();
220
+ this.emit("ready", url);
221
+ resolve(makeResult(url));
222
+ return;
62
223
  }
63
224
  }
64
- });
225
+ // ---- Detecção de erros específicos ----
226
+ if (lowerText.includes("connection refused")) {
227
+ finish(new Error(`A porta ${this.port} não possui nenhum servidor ativo. Inicie seu servidor antes de criar o túnel.`));
228
+ return;
229
+ }
230
+ if (lowerText.includes("invalid token") ||
231
+ lowerText.includes("token is expired") ||
232
+ lowerText.includes("failed to parse token") ||
233
+ lowerText.includes("error parsing token")) {
234
+ finish(new Error("Token do túnel Cloudflare inválido ou expirado. " +
235
+ "Gere um novo token na dashboard da Cloudflare ou com: cloudflared tunnel token <TUNNEL_NAME>"));
236
+ return;
237
+ }
238
+ if ((lowerText.includes("error") && lowerText.includes("credential")) ||
239
+ lowerText.includes("unauthorized") ||
240
+ lowerText.includes("authentication error")) {
241
+ finish(new Error("Credenciais do túnel Cloudflare inválidas. " +
242
+ "Verifique o arquivo de credenciais ou reconfigure com: cloudflared tunnel login"));
243
+ return;
244
+ }
245
+ if (lowerText.includes("credentials") && lowerText.includes("not found")) {
246
+ finish(new Error("Arquivo de credenciais do túnel não encontrado pelo cloudflared. " +
247
+ "Verifique o caminho em credentialsFile ou use autenticação por token."));
248
+ return;
249
+ }
250
+ if (lowerText.includes("tunnel not found") || lowerText.includes("does not exist")) {
251
+ finish(new Error(`Túnel "${this.cloudflareOpts.tunnelId || this.cloudflareOpts.tunnelName}" não encontrado. ` +
252
+ "Verifique se o ID ou nome do túnel está correto e se ele existe na sua conta Cloudflare."));
253
+ return;
254
+ }
255
+ if (lowerText.includes("failed to connect to edge") ||
256
+ lowerText.includes("cannot connect to") ||
257
+ lowerText.includes("connection timed out") ||
258
+ lowerText.includes("network is unreachable")) {
259
+ finish(new Error("Falha na conexão com a Cloudflare. Verifique sua conexão com a internet e tente novamente."));
260
+ return;
261
+ }
262
+ if ((lowerText.includes("hostname") && lowerText.includes("not found")) ||
263
+ lowerText.includes("no ingress rules") ||
264
+ lowerText.includes("no matching ingress")) {
265
+ finish(new Error("Hostname ou regra de ingress não configurados para este túnel. " +
266
+ "Configure o Public Hostname na dashboard da Cloudflare ou no arquivo de configuração local."));
267
+ return;
268
+ }
269
+ };
270
+ this.cp.stderr?.on("data", handleOutput);
271
+ this.cp.stdout?.on("data", handleOutput);
272
+ // Encerramento do processo
65
273
  this.cp.on("close", (code) => {
274
+ cleanup();
66
275
  if (!isResolved && code !== 0) {
67
- reject(new Error(`Falha ao iniciar o túnel. Cloudflared encerrou com código ${code}.`));
276
+ isResolved = true;
277
+ reject(new Error(`Cloudflared encerrou inesperadamente (código ${code}). ` +
278
+ "Verifique os logs acima para mais detalhes sobre o erro."));
68
279
  }
69
280
  this.emit("close");
70
281
  });
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "cm-tunnel",
3
- "version": "1.3.0",
3
+ "version": "1.3.2",
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",