cm-tunnel 1.3.1 → 1.3.3

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
@@ -126,12 +126,15 @@ console.log(t.url); // https://api.meudominio.com.br
126
126
  | `domain` | `string` | — | Domínio personalizado (obrigatório para named tunnels). |
127
127
  | `tunnelId` | `string` | — | ID do túnel Cloudflare (obrigatório para named tunnels, alternativa a `tunnelName`). |
128
128
  | `tunnelName` | `string` | — | Nome do túnel Cloudflare (alternativa ao `tunnelId`). |
129
+ | `token` | `string` | — | Token do túnel (dashboard ou `cloudflared tunnel token <TUNNEL>`). Alternativa a `tunnelId` + `credentialsFile`. |
129
130
  | `credentialsFile` | `string` | — | Caminho para o arquivo de credenciais `.json` do túnel. |
130
131
  | `cloudflaredPath` | `string` | `'cloudflared'` | Caminho personalizado para o executável `cloudflared`. |
131
132
  | `timeout` | `number` | `30000` | Timeout em milissegundos para aguardar a inicialização do túnel. |
132
133
 
133
134
  > **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
 
136
+ > **Atenção:** `credentialsFile` deve apontar para o JSON do túnel (`~/.cloudflared/<tunnel-id>.json`), gerado por `cloudflared tunnel create`. O `cert.pem` criado por `cloudflared tunnel login` serve apenas para gerenciar túneis e **não funciona** para executar o túnel. Para túneis criados pelo dashboard, use `token`.
137
+
135
138
  ### Servidor HTML/Estático Standalone (Sem Túnel)
136
139
 
137
140
  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):
package/dist/Tunnel.js CHANGED
@@ -1,28 +1,50 @@
1
1
  import { EventEmitter } from "events";
2
2
  import { RateLimiter } from "./RateLimiter.js";
3
3
  import { StaticServer } from "./StaticServer.js";
4
+ import { validateCredentialsFile } from "./providers/cloudflare.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
+ }
4
16
  /**
5
17
  * 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.
18
+ * Erros de configuração são capturados aqui, antes do spawn do processo.
7
19
  */
8
20
  function validateCloudflareOptions(options) {
9
21
  if (options.provider?.toLowerCase() !== "cloudflare" || !options.cloudflare) {
10
22
  return;
11
23
  }
12
24
  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
- }
25
+ const mode = resolveCloudflareMode(cf);
18
26
  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: "..." }');
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.");
22
44
  }
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" }');
45
+ // Validar existência e formato do arquivo de credenciais quando informado
46
+ if (hasCredentials) {
47
+ validateCredentialsFile(cf.credentialsFile);
26
48
  }
27
49
  }
28
50
  }
@@ -36,20 +58,18 @@ export async function createTunnel(options) {
36
58
  // Valida opções do Cloudflare antes de tentar carregar o provider
37
59
  validateCloudflareOptions(options);
38
60
  const providerName = options.provider.toLowerCase();
39
- let ProviderClass;
40
- try {
41
- // Dynamic import to load the provider dynamically based on name
42
- const module = await import(`./providers/${providerName}.js`);
43
- ProviderClass = module.default;
44
- }
45
- catch (err) {
46
- if (err.code === "ERR_MODULE_NOT_FOUND" ||
47
- err.message.includes("Cannot find module") ||
48
- err.message.includes("Unknown variable dynamic import")) {
49
- throw new Error(`Provider inexistente: "${providerName}".`);
50
- }
51
- throw err;
61
+ // Mapa explícito de loaders: import() com variável não é resolvido por
62
+ // bundlers/test runners (ex: Vite), além de dificultar o tree-shaking.
63
+ const providerLoaders = {
64
+ cloudflare: () => import("./providers/cloudflare.js"),
65
+ localtunnel: () => import("./providers/localtunnel.js"),
66
+ ngrok: () => import("./providers/ngrok.js"),
67
+ };
68
+ const loadProvider = providerLoaders[providerName];
69
+ if (!loadProvider) {
70
+ throw new Error(`Provider inexistente: "${providerName}".`);
52
71
  }
72
+ const ProviderClass = (await loadProvider()).default;
53
73
  let rateLimiterInstance = null;
54
74
  let staticServerInstance = null;
55
75
  // A porta do usuário (ou gerada pelo StaticServer) que o túnel/proxy vai mirar
@@ -66,15 +86,23 @@ export async function createTunnel(options) {
66
86
  const providerInstance = new ProviderClass({ ...options, port: targetPort });
67
87
  // We wrap the result in an EventEmitter to match the required API
68
88
  const emitter = new EventEmitter();
89
+ let started = false;
69
90
  providerInstance.on("ready", (url) => emitter.emit("ready", url));
70
91
  providerInstance.on("close", () => {
71
92
  rateLimiterInstance?.stop();
72
93
  staticServerInstance?.stop();
73
94
  emitter.emit("close");
74
95
  });
75
- providerInstance.on("error", (err) => emitter.emit("error", err));
96
+ providerInstance.on("error", (err) => {
97
+ // Durante a inicialização o erro já é propagado pela rejeição de start().
98
+ // Reemitir aqui, antes de o consumidor receber o emitter, derrubaria o
99
+ // processo com um evento "error" sem listener.
100
+ if (started)
101
+ emitter.emit("error", err);
102
+ });
76
103
  try {
77
104
  const result = await providerInstance.start();
105
+ started = true;
78
106
  // Assign properties from result to the emitter instance to conform to TunnelInstance
79
107
  Object.assign(emitter, {
80
108
  provider: result.provider,
package/dist/index.d.ts CHANGED
@@ -2,20 +2,24 @@ import { TunnelOptions, TunnelInstance, CloudflareOptions, CloudflareMode } from
2
2
  import { ServeOptions } from './StaticServer.js';
3
3
  type OmitProvider<T> = Omit<T, "provider">;
4
4
  interface CloudflareShortcutOptions extends OmitProvider<TunnelOptions> {
5
- /** Domínio personalizado para Named Tunnels */
5
+ /** Domínio personalizado para Named Tunnels (DNS deve estar previamente configurado na Cloudflare) */
6
6
  domain?: string;
7
7
  /** ID do túnel Cloudflare */
8
8
  tunnelId?: string;
9
- /** Nome do túnel Cloudflare */
9
+ /** Nome do túnel Cloudflare (alternativa ao tunnelId) */
10
10
  tunnelName?: string;
11
- /** Arquivo de credenciais */
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) */
12
14
  credentialsFile?: string;
13
15
  /** Caminho do executável cloudflared */
14
16
  cloudflaredPath?: string;
15
- /** Timeout em ms */
17
+ /** Timeout em ms (padrão: 30000) */
16
18
  timeout?: number;
17
- /** Modo: "quick" ou "named" */
19
+ /** Modo: "quick" ou "named" (inferido automaticamente) */
18
20
  mode?: CloudflareMode;
21
+ /** Protocolo da URL (padrão: "https") */
22
+ protocol?: string;
19
23
  }
20
24
  interface TunnelAPI {
21
25
  (options: TunnelOptions): Promise<TunnelInstance>;
package/dist/index.js CHANGED
@@ -2,7 +2,7 @@ import { createTunnel } from './Tunnel.js';
2
2
  import { serve } from './StaticServer.js';
3
3
  const tunnel = createTunnel;
4
4
  tunnel.cloudflare = (options) => {
5
- const { domain, tunnelId, tunnelName, credentialsFile, cloudflaredPath, timeout, mode, ...rest } = options;
5
+ const { domain, tunnelId, tunnelName, token, credentialsFile, cloudflaredPath, timeout, mode, protocol, ...rest } = options;
6
6
  // Monta o objeto cloudflare a partir das opções de atalho
7
7
  const cloudflareOpts = {};
8
8
  if (mode !== undefined)
@@ -13,12 +13,16 @@ tunnel.cloudflare = (options) => {
13
13
  cloudflareOpts.tunnelId = tunnelId;
14
14
  if (tunnelName !== undefined)
15
15
  cloudflareOpts.tunnelName = tunnelName;
16
+ if (token !== undefined)
17
+ cloudflareOpts.token = token;
16
18
  if (credentialsFile !== undefined)
17
19
  cloudflareOpts.credentialsFile = credentialsFile;
18
20
  if (cloudflaredPath !== undefined)
19
21
  cloudflareOpts.cloudflaredPath = cloudflaredPath;
20
22
  if (timeout !== undefined)
21
23
  cloudflareOpts.timeout = timeout;
24
+ if (protocol !== undefined)
25
+ cloudflareOpts.protocol = protocol;
22
26
  // Merge: se o usuário já passou cloudflare: {...}, combina
23
27
  const existingCloudflare = rest.cloudflare || {};
24
28
  const mergedCloudflare = { ...existingCloudflare, ...cloudflareOpts };
@@ -1,40 +1,72 @@
1
1
  import { Provider, ProviderOptions, TunnelResult } from "../Provider.js";
2
2
  export type CloudflareMode = "quick" | "named";
3
3
  export interface CloudflareOptions {
4
- /** Modo do túnel: "quick" (padrão) ou "named" */
4
+ /** Modo do túnel: "quick" (padrão) ou "named". Inferido automaticamente se token, tunnelId ou tunnelName forem fornecidos. */
5
5
  mode?: CloudflareMode;
6
- /** Domínio personalizado para Named Tunnels (ex: "api.meudominio.com.br") */
6
+ /** Domínio personalizado associado ao túnel (ex: "api.meudominio.com.br"). O DNS deve estar previamente configurado na Cloudflare. */
7
7
  domain?: string;
8
8
  /** ID do túnel Cloudflare previamente criado */
9
9
  tunnelId?: string;
10
10
  /** Nome do túnel Cloudflare (alternativa ao tunnelId) */
11
11
  tunnelName?: string;
12
- /** Caminho para o arquivo de credenciais do túnel (.json) */
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) */
13
15
  credentialsFile?: string;
14
16
  /** Caminho para o executável cloudflared (se não estiver no PATH) */
15
17
  cloudflaredPath?: string;
16
18
  /** Timeout em ms para aguardar a inicialização (padrão: 30000) */
17
19
  timeout?: number;
20
+ /** Protocolo da URL retornada (padrão: "https") */
21
+ protocol?: string;
18
22
  }
19
23
  interface CloudflareProviderOptions extends ProviderOptions {
20
24
  cloudflare?: CloudflareOptions;
21
25
  }
26
+ /**
27
+ * Valida o arquivo de credenciais do túnel Cloudflare.
28
+ *
29
+ * O cloudflared exige o JSON gerado por `cloudflared tunnel create`.
30
+ * O cert.pem gerado por `cloudflared tunnel login` serve apenas para
31
+ * gerenciar túneis (criar, listar, apagar) e não pode ser usado no `run`.
32
+ */
33
+ export declare function validateCredentialsFile(file: string): void;
22
34
  export default class CloudflareProvider extends Provider {
23
35
  private cp;
24
36
  private urlRegex;
25
37
  private cloudflareOpts;
26
38
  private mode;
39
+ /** Últimas linhas emitidas pelo cloudflared, usadas para enriquecer erros. */
40
+ private lastOutput;
27
41
  constructor(options: CloudflareProviderOptions);
42
+ /**
43
+ * Determina o modo efetivo com base nas opções fornecidas.
44
+ */
45
+ private resolveMode;
28
46
  private get executable();
29
- private get timeout();
47
+ private get timeoutMs();
48
+ private get protocol();
30
49
  /**
31
- * Valida as opções antes de iniciar, lançando erros claros.
50
+ * Valida as opções antes de iniciar, lançando erros claros e específicos.
32
51
  */
33
52
  private validateOptions;
34
53
  /**
35
- * Monta os argumentos do cloudflared conforme o modo.
54
+ * Monta os argumentos do cloudflared conforme o modo e método de autenticação.
55
+ *
56
+ * Quick Tunnel:
57
+ * cloudflared tunnel --url http://localhost:PORT
58
+ *
59
+ * Named Tunnel com token:
60
+ * cloudflared tunnel --url http://localhost:PORT run --token <TOKEN>
61
+ *
62
+ * Named Tunnel com credenciais:
63
+ * cloudflared tunnel --credentials-file <FILE> --url http://localhost:PORT run <TUNNEL_ID|NAME>
36
64
  */
37
65
  private buildArgs;
66
+ /**
67
+ * Constrói a URL pública do túnel named.
68
+ */
69
+ private buildNamedUrl;
38
70
  start(): Promise<TunnelResult>;
39
71
  stop(): void;
40
72
  }
@@ -1,46 +1,129 @@
1
1
  import { spawn } from "child_process";
2
+ import { existsSync } from "fs";
3
+ import { basename, extname } from "path";
2
4
  import { Provider } from "../Provider.js";
5
+ /**
6
+ * Remove tokens e segredos de uma string de log/erro.
7
+ */
8
+ function sanitizeOutput(text, token) {
9
+ let sanitized = text;
10
+ if (token && token.length > 8) {
11
+ sanitized = sanitized.replace(new RegExp(escapeRegex(token), "g"), "[TOKEN OCULTO]");
12
+ }
13
+ // Remove padrões comuns de JWT tokens em logs do cloudflared
14
+ sanitized = sanitized.replace(/eyJ[A-Za-z0-9_-]+\.eyJ[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+/g, "[TOKEN OCULTO]");
15
+ return sanitized;
16
+ }
17
+ function escapeRegex(str) {
18
+ return str.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
19
+ }
20
+ /**
21
+ * Valida o arquivo de credenciais do túnel Cloudflare.
22
+ *
23
+ * O cloudflared exige o JSON gerado por `cloudflared tunnel create`.
24
+ * O cert.pem gerado por `cloudflared tunnel login` serve apenas para
25
+ * gerenciar túneis (criar, listar, apagar) e não pode ser usado no `run`.
26
+ */
27
+ export function validateCredentialsFile(file) {
28
+ if (extname(file).toLowerCase() !== ".json") {
29
+ throw new Error(`credentialsFile inválido: "${file}". O cloudflared exige o arquivo .json de credenciais do túnel ` +
30
+ `(ex: ~/.cloudflared/<tunnel-id>.json), mas foi informado "${basename(file)}". ` +
31
+ 'O cert.pem gerado por "cloudflared tunnel login" não serve para executar o túnel. ' +
32
+ 'Gere as credenciais com "cloudflared tunnel create" ou use autenticação por token.');
33
+ }
34
+ if (!existsSync(file)) {
35
+ throw new Error(`Arquivo de credenciais não encontrado: "${file}". ` +
36
+ "Verifique o caminho ou use autenticação por token.");
37
+ }
38
+ }
3
39
  export default class CloudflareProvider extends Provider {
4
40
  cp = null;
5
- urlRegex = /(https:\/\/[a-zA-Z0-9-]+\.trycloudflare\.com)/;
41
+ urlRegex = /(https:\/\/([a-zA-Z0-9-]+)\.trycloudflare\.com)/;
6
42
  cloudflareOpts;
7
43
  mode;
44
+ /** Últimas linhas emitidas pelo cloudflared, usadas para enriquecer erros. */
45
+ lastOutput = "";
8
46
  constructor(options) {
9
47
  super(options);
10
48
  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";
49
+ this.mode = this.resolveMode();
50
+ }
51
+ /**
52
+ * Determina o modo efetivo com base nas opções fornecidas.
53
+ */
54
+ resolveMode() {
55
+ if (this.cloudflareOpts.mode) {
56
+ return this.cloudflareOpts.mode;
57
+ }
58
+ if (this.cloudflareOpts.token ||
59
+ this.cloudflareOpts.tunnelId ||
60
+ this.cloudflareOpts.tunnelName ||
61
+ this.cloudflareOpts.credentialsFile ||
62
+ this.cloudflareOpts.domain) {
63
+ return "named";
16
64
  }
65
+ return "quick";
17
66
  }
18
67
  get executable() {
19
68
  return this.cloudflareOpts.cloudflaredPath || "cloudflared";
20
69
  }
21
- get timeout() {
70
+ get timeoutMs() {
22
71
  return this.cloudflareOpts.timeout || 30000;
23
72
  }
73
+ get protocol() {
74
+ return this.cloudflareOpts.protocol || "https";
75
+ }
24
76
  /**
25
- * Valida as opções antes de iniciar, lançando erros claros.
77
+ * Valida as opções antes de iniciar, lançando erros claros e específicos.
26
78
  */
27
79
  validateOptions() {
28
80
  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: "..." }');
81
+ const hasToken = !!this.cloudflareOpts.token;
82
+ const hasCredentials = !!this.cloudflareOpts.credentialsFile;
83
+ const hasTunnelRef = !!(this.cloudflareOpts.tunnelId || this.cloudflareOpts.tunnelName);
84
+ if (!hasToken) {
85
+ if (!hasTunnelRef) {
86
+ throw new Error('Cloudflare Named Tunnel requer "token" ou "tunnelId"/"tunnelName". ' +
87
+ "Use token: process.env.CLOUDFLARE_TOKEN ou forneça tunnelId com credentialsFile.");
88
+ }
89
+ if (!hasCredentials) {
90
+ throw new Error("Cloudflare Named Tunnel sem token requer credentialsFile. " +
91
+ "Forneça o caminho do arquivo JSON de credenciais ou use autenticação por token.");
92
+ }
93
+ }
94
+ // Validar existência e formato do arquivo de credenciais quando informado
95
+ if (hasCredentials) {
96
+ validateCredentialsFile(this.cloudflareOpts.credentialsFile);
32
97
  }
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" }');
98
+ // Token e credenciais não devem ser usados simultaneamente
99
+ if (hasToken && hasCredentials) {
100
+ throw new Error("Não utilize token e credentialsFile simultaneamente. Escolha um método de autenticação.");
36
101
  }
37
102
  }
38
103
  }
39
104
  /**
40
- * Monta os argumentos do cloudflared conforme o modo.
105
+ * Monta os argumentos do cloudflared conforme o modo e método de autenticação.
106
+ *
107
+ * Quick Tunnel:
108
+ * cloudflared tunnel --url http://localhost:PORT
109
+ *
110
+ * Named Tunnel com token:
111
+ * cloudflared tunnel --url http://localhost:PORT run --token <TOKEN>
112
+ *
113
+ * Named Tunnel com credenciais:
114
+ * cloudflared tunnel --credentials-file <FILE> --url http://localhost:PORT run <TUNNEL_ID|NAME>
41
115
  */
42
116
  buildArgs() {
43
117
  if (this.mode === "named") {
118
+ if (this.cloudflareOpts.token) {
119
+ return [
120
+ "tunnel",
121
+ "--url", `http://localhost:${this.port}`,
122
+ "run",
123
+ "--token", this.cloudflareOpts.token,
124
+ ];
125
+ }
126
+ // Credentials mode
44
127
  const args = ["tunnel"];
45
128
  if (this.cloudflareOpts.credentialsFile) {
46
129
  args.push("--credentials-file", this.cloudflareOpts.credentialsFile);
@@ -55,20 +138,42 @@ export default class CloudflareProvider extends Provider {
55
138
  }
56
139
  return args;
57
140
  }
58
- // Modo quick (padrão) — mantém o comportamento original
141
+ // Quick Tunnel
59
142
  return ["tunnel", "--url", `http://localhost:${this.port}`];
60
143
  }
144
+ /**
145
+ * Constrói a URL pública do túnel named.
146
+ */
147
+ buildNamedUrl() {
148
+ if (this.cloudflareOpts.domain) {
149
+ return `${this.protocol}://${this.cloudflareOpts.domain}`;
150
+ }
151
+ const tunnelRef = this.cloudflareOpts.tunnelId || this.cloudflareOpts.tunnelName || "tunnel";
152
+ return `${this.protocol}://${tunnelRef}.cfargotunnel.com`;
153
+ }
61
154
  start() {
62
155
  this.validateOptions();
63
156
  return new Promise((resolve, reject) => {
64
157
  let isResolved = false;
65
158
  let timeoutId = null;
159
+ const token = this.cloudflareOpts.token;
66
160
  const cleanup = () => {
67
161
  if (timeoutId) {
68
162
  clearTimeout(timeoutId);
69
163
  timeoutId = null;
70
164
  }
71
165
  };
166
+ const finish = (err) => {
167
+ if (!isResolved) {
168
+ isResolved = true;
169
+ cleanup();
170
+ reject(err);
171
+ this.stop();
172
+ }
173
+ else {
174
+ this.emit("error", err);
175
+ }
176
+ };
72
177
  const makeResult = (url) => ({
73
178
  provider: "cloudflare",
74
179
  url,
@@ -80,136 +185,134 @@ export default class CloudflareProvider extends Provider {
80
185
  timeoutId = setTimeout(() => {
81
186
  if (!isResolved) {
82
187
  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.`);
188
+ const err = new Error(`Timeout: Cloudflare Tunnel não iniciou em ${this.timeoutMs / 1000}s. ` +
189
+ "Verifique se o cloudflared está configurado corretamente e se as credenciais são válidas.");
85
190
  this.stop();
86
191
  reject(err);
87
192
  }
88
- }, this.timeout);
193
+ }, this.timeoutMs);
194
+ // Spawn do processo
89
195
  try {
90
196
  this.cp = spawn(this.executable, this.buildArgs());
91
197
  }
92
198
  catch (err) {
93
199
  cleanup();
94
- reject(new Error(`Falha ao executar cloudflared: ${err.message}`));
200
+ reject(new Error(`Falha ao executar cloudflared: ${sanitizeOutput(err.message, token)}`));
95
201
  return;
96
202
  }
203
+ // Erro de spawn (ENOENT, permissão, etc.)
97
204
  this.cp.on("error", (err) => {
98
205
  cleanup();
99
206
  if (err.code === "ENOENT") {
100
207
  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/";
103
- if (!isResolved) {
104
- isResolved = true;
105
- reject(new Error(errorMsg));
106
- }
107
- else {
108
- this.emit("error", new Error(errorMsg));
109
- }
208
+ ? `Cloudflared não encontrado em: "${this.cloudflareOpts.cloudflaredPath}". Verifique se o caminho está correto.`
209
+ : "Cloudflared não encontrado. Instale a partir de: https://developers.cloudflare.com/cloudflare-one/connections/connect-networks/downloads/";
210
+ finish(new Error(errorMsg));
110
211
  }
111
212
  else {
112
- if (!isResolved) {
113
- isResolved = true;
114
- reject(err);
115
- }
116
- else {
117
- this.emit("error", err);
118
- }
213
+ finish(new Error(sanitizeOutput(err.message, token)));
119
214
  }
120
215
  });
121
- // Escuta em stderr (cloudflared emite logs em stderr)
216
+ // Handler unificado para stdout e stderr
122
217
  const handleOutput = (data) => {
123
218
  const text = data.toString();
219
+ const lowerText = text.toLowerCase();
220
+ // Guarda as últimas saídas para enriquecer a mensagem de erro caso
221
+ // o processo encerre sem que nenhum padrão conhecido seja detectado.
222
+ this.lastOutput = (this.lastOutput + sanitizeOutput(text, token)).slice(-4000);
223
+ // ---- Detecção de sucesso ----
124
224
  if (this.mode === "quick") {
125
- // Quick tunnel: busca a URL trycloudflare.com na saída
126
225
  const match = text.match(this.urlRegex);
127
- if (match && match[1]) {
226
+ // "api.trycloudflare.com" é o endpoint da API da Cloudflare e aparece
227
+ // justamente em mensagens de erro (ex: falha ao criar o quick tunnel).
228
+ // Só a URL com subdomínio aleatório é a URL pública do túnel.
229
+ if (match && match[1] && match[2].toLowerCase() !== "api" && !isResolved) {
230
+ isResolved = true;
231
+ cleanup();
128
232
  const url = match[1];
129
- if (!isResolved) {
130
- isResolved = true;
131
- cleanup();
132
- this.emit("ready", url);
133
- resolve(makeResult(url));
134
- }
233
+ this.emit("ready", url);
234
+ resolve(makeResult(url));
235
+ return;
135
236
  }
136
237
  }
137
238
  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") ||
239
+ // Named tunnel: detecta conexão estabelecida
240
+ if ((text.includes("Registered tunnel connection") ||
142
241
  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
- }
242
+ (text.includes("Connection") && text.includes("registered"))) &&
243
+ !isResolved) {
244
+ isResolved = true;
245
+ cleanup();
246
+ const url = this.buildNamedUrl();
247
+ this.emit("ready", url);
248
+ resolve(makeResult(url));
249
+ return;
151
250
  }
152
251
  }
153
- // Detecta erros conhecidos nos dois modos
154
- const lowerText = text.toLowerCase();
252
+ // ---- Detecção de erros específicos ----
155
253
  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
- }
254
+ finish(new Error(`A porta ${this.port} não possui nenhum servidor ativo. Inicie seu servidor antes de criar o túnel.`));
255
+ return;
166
256
  }
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");
170
- if (!isResolved) {
171
- cleanup();
172
- isResolved = true;
173
- reject(err);
174
- this.stop();
175
- }
176
- else {
177
- this.emit("error", err);
178
- }
257
+ if (lowerText.includes("should be .json") ||
258
+ (lowerText.includes("credentials file") && lowerText.includes(".pem")) ||
259
+ lowerText.includes("cert.pem")) {
260
+ finish(new Error("credentialsFile inválido: o cloudflared exige o arquivo .json de credenciais do túnel, não o cert.pem. " +
261
+ 'Gere as credenciais com "cloudflared tunnel create" ou use autenticação por token.'));
262
+ return;
263
+ }
264
+ if (lowerText.includes("invalid token") ||
265
+ lowerText.includes("token is expired") ||
266
+ lowerText.includes("failed to parse token") ||
267
+ lowerText.includes("error parsing token")) {
268
+ finish(new Error("Token do túnel Cloudflare inválido ou expirado. " +
269
+ "Gere um novo token na dashboard da Cloudflare ou com: cloudflared tunnel token <TUNNEL_NAME>"));
270
+ return;
271
+ }
272
+ if ((lowerText.includes("error") && lowerText.includes("credential")) ||
273
+ lowerText.includes("unauthorized") ||
274
+ lowerText.includes("authentication error")) {
275
+ finish(new Error("Credenciais do túnel Cloudflare inválidas. " +
276
+ "Verifique o arquivo de credenciais ou reconfigure com: cloudflared tunnel login"));
277
+ return;
278
+ }
279
+ if (lowerText.includes("credentials") && lowerText.includes("not found")) {
280
+ finish(new Error("Arquivo de credenciais do túnel não encontrado pelo cloudflared. " +
281
+ "Verifique o caminho em credentialsFile ou use autenticação por token."));
282
+ return;
179
283
  }
180
284
  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.");
183
- if (!isResolved) {
184
- cleanup();
185
- isResolved = true;
186
- reject(err);
187
- this.stop();
188
- }
189
- else {
190
- this.emit("error", err);
191
- }
285
+ finish(new Error(`Túnel "${this.cloudflareOpts.tunnelId || this.cloudflareOpts.tunnelName}" não encontrado. ` +
286
+ "Verifique se o ID ou nome do túnel está correto e se ele existe na sua conta Cloudflare."));
287
+ return;
192
288
  }
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
- }
289
+ if (lowerText.includes("failed to connect to edge") ||
290
+ lowerText.includes("cannot connect to") ||
291
+ lowerText.includes("connection timed out") ||
292
+ lowerText.includes("network is unreachable")) {
293
+ finish(new Error("Falha na conexão com a Cloudflare. Verifique sua conexão com a internet e tente novamente."));
294
+ return;
295
+ }
296
+ if ((lowerText.includes("hostname") && lowerText.includes("not found")) ||
297
+ lowerText.includes("no ingress rules") ||
298
+ lowerText.includes("no matching ingress")) {
299
+ finish(new Error("Hostname ou regra de ingress não configurados para este túnel. " +
300
+ "Configure o Public Hostname na dashboard da Cloudflare ou no arquivo de configuração local."));
301
+ return;
204
302
  }
205
303
  };
206
304
  this.cp.stderr?.on("data", handleOutput);
207
305
  this.cp.stdout?.on("data", handleOutput);
306
+ // Encerramento do processo
208
307
  this.cp.on("close", (code) => {
209
308
  cleanup();
210
309
  if (!isResolved && code !== 0) {
211
310
  isResolved = true;
212
- reject(new Error(`Falha ao iniciar o túnel. Cloudflared encerrou com código ${code}.`));
311
+ const details = this.lastOutput.trim();
312
+ reject(new Error(`Cloudflared encerrou inesperadamente (código ${code}). ` +
313
+ (details
314
+ ? `Saída do cloudflared:\n${details}`
315
+ : "Verifique se o cloudflared está instalado e configurado corretamente.")));
213
316
  }
214
317
  this.emit("close");
215
318
  });
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "cm-tunnel",
3
- "version": "1.3.1",
3
+ "version": "1.3.3",
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",