cm-tunnel 1.3.1 → 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/dist/Tunnel.js +35 -12
- package/dist/index.d.ts +9 -5
- package/dist/index.js +5 -1
- package/dist/providers/cloudflare.d.ts +28 -6
- package/dist/providers/cloudflare.js +169 -103
- package/package.json +1 -1
package/dist/Tunnel.js
CHANGED
|
@@ -1,28 +1,51 @@
|
|
|
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
|
+
}
|
|
4
16
|
/**
|
|
5
17
|
* Valida as opções do Cloudflare antes de carregar o provider.
|
|
6
|
-
*
|
|
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
|
-
|
|
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
|
-
|
|
20
|
-
|
|
21
|
-
|
|
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
|
-
|
|
24
|
-
|
|
25
|
-
|
|
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.");
|
|
26
49
|
}
|
|
27
50
|
}
|
|
28
51
|
}
|
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
|
-
/**
|
|
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,20 +1,24 @@
|
|
|
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
|
|
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
|
-
/**
|
|
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;
|
|
@@ -25,16 +29,34 @@ export default class CloudflareProvider extends Provider {
|
|
|
25
29
|
private cloudflareOpts;
|
|
26
30
|
private mode;
|
|
27
31
|
constructor(options: CloudflareProviderOptions);
|
|
32
|
+
/**
|
|
33
|
+
* Determina o modo efetivo com base nas opções fornecidas.
|
|
34
|
+
*/
|
|
35
|
+
private resolveMode;
|
|
28
36
|
private get executable();
|
|
29
|
-
private get
|
|
37
|
+
private get timeoutMs();
|
|
38
|
+
private get protocol();
|
|
30
39
|
/**
|
|
31
|
-
* Valida as opções antes de iniciar, lançando erros claros.
|
|
40
|
+
* Valida as opções antes de iniciar, lançando erros claros e específicos.
|
|
32
41
|
*/
|
|
33
42
|
private validateOptions;
|
|
34
43
|
/**
|
|
35
|
-
* Monta os argumentos do cloudflared conforme o modo.
|
|
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>
|
|
36
54
|
*/
|
|
37
55
|
private buildArgs;
|
|
56
|
+
/**
|
|
57
|
+
* Constrói a URL pública do túnel named.
|
|
58
|
+
*/
|
|
59
|
+
private buildNamedUrl;
|
|
38
60
|
start(): Promise<TunnelResult>;
|
|
39
61
|
stop(): void;
|
|
40
62
|
}
|
|
@@ -1,5 +1,21 @@
|
|
|
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)/;
|
|
@@ -8,39 +24,85 @@ export default class CloudflareProvider extends Provider {
|
|
|
8
24
|
constructor(options) {
|
|
9
25
|
super(options);
|
|
10
26
|
this.cloudflareOpts = options.cloudflare || {};
|
|
11
|
-
this.mode = this.
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
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";
|
|
16
42
|
}
|
|
43
|
+
return "quick";
|
|
17
44
|
}
|
|
18
45
|
get executable() {
|
|
19
46
|
return this.cloudflareOpts.cloudflaredPath || "cloudflared";
|
|
20
47
|
}
|
|
21
|
-
get
|
|
48
|
+
get timeoutMs() {
|
|
22
49
|
return this.cloudflareOpts.timeout || 30000;
|
|
23
50
|
}
|
|
51
|
+
get protocol() {
|
|
52
|
+
return this.cloudflareOpts.protocol || "https";
|
|
53
|
+
}
|
|
24
54
|
/**
|
|
25
|
-
* Valida as opções antes de iniciar, lançando erros claros.
|
|
55
|
+
* Valida as opções antes de iniciar, lançando erros claros e específicos.
|
|
26
56
|
*/
|
|
27
57
|
validateOptions() {
|
|
28
58
|
if (this.mode === "named") {
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
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.");
|
|
32
76
|
}
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
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.");
|
|
36
80
|
}
|
|
37
81
|
}
|
|
38
82
|
}
|
|
39
83
|
/**
|
|
40
|
-
* Monta os argumentos do cloudflared conforme o modo.
|
|
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>
|
|
41
94
|
*/
|
|
42
95
|
buildArgs() {
|
|
43
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
|
|
44
106
|
const args = ["tunnel"];
|
|
45
107
|
if (this.cloudflareOpts.credentialsFile) {
|
|
46
108
|
args.push("--credentials-file", this.cloudflareOpts.credentialsFile);
|
|
@@ -55,20 +117,42 @@ export default class CloudflareProvider extends Provider {
|
|
|
55
117
|
}
|
|
56
118
|
return args;
|
|
57
119
|
}
|
|
58
|
-
//
|
|
120
|
+
// Quick Tunnel
|
|
59
121
|
return ["tunnel", "--url", `http://localhost:${this.port}`];
|
|
60
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`;
|
|
132
|
+
}
|
|
61
133
|
start() {
|
|
62
134
|
this.validateOptions();
|
|
63
135
|
return new Promise((resolve, reject) => {
|
|
64
136
|
let isResolved = false;
|
|
65
137
|
let timeoutId = null;
|
|
138
|
+
const token = this.cloudflareOpts.token;
|
|
66
139
|
const cleanup = () => {
|
|
67
140
|
if (timeoutId) {
|
|
68
141
|
clearTimeout(timeoutId);
|
|
69
142
|
timeoutId = null;
|
|
70
143
|
}
|
|
71
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
|
+
};
|
|
72
156
|
const makeResult = (url) => ({
|
|
73
157
|
provider: "cloudflare",
|
|
74
158
|
url,
|
|
@@ -80,136 +164,118 @@ export default class CloudflareProvider extends Provider {
|
|
|
80
164
|
timeoutId = setTimeout(() => {
|
|
81
165
|
if (!isResolved) {
|
|
82
166
|
isResolved = true;
|
|
83
|
-
const err = new Error(`Timeout: Cloudflare Tunnel não iniciou em ${this.
|
|
84
|
-
|
|
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.");
|
|
85
169
|
this.stop();
|
|
86
170
|
reject(err);
|
|
87
171
|
}
|
|
88
|
-
}, this.
|
|
172
|
+
}, this.timeoutMs);
|
|
173
|
+
// Spawn do processo
|
|
89
174
|
try {
|
|
90
175
|
this.cp = spawn(this.executable, this.buildArgs());
|
|
91
176
|
}
|
|
92
177
|
catch (err) {
|
|
93
178
|
cleanup();
|
|
94
|
-
reject(new Error(`Falha ao executar cloudflared: ${err.message}`));
|
|
179
|
+
reject(new Error(`Falha ao executar cloudflared: ${sanitizeOutput(err.message, token)}`));
|
|
95
180
|
return;
|
|
96
181
|
}
|
|
182
|
+
// Erro de spawn (ENOENT, permissão, etc.)
|
|
97
183
|
this.cp.on("error", (err) => {
|
|
98
184
|
cleanup();
|
|
99
185
|
if (err.code === "ENOENT") {
|
|
100
186
|
const errorMsg = this.cloudflareOpts.cloudflaredPath
|
|
101
|
-
? `Cloudflared não encontrado
|
|
102
|
-
: "Cloudflared não encontrado.
|
|
103
|
-
|
|
104
|
-
isResolved = true;
|
|
105
|
-
reject(new Error(errorMsg));
|
|
106
|
-
}
|
|
107
|
-
else {
|
|
108
|
-
this.emit("error", new Error(errorMsg));
|
|
109
|
-
}
|
|
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));
|
|
110
190
|
}
|
|
111
191
|
else {
|
|
112
|
-
|
|
113
|
-
isResolved = true;
|
|
114
|
-
reject(err);
|
|
115
|
-
}
|
|
116
|
-
else {
|
|
117
|
-
this.emit("error", err);
|
|
118
|
-
}
|
|
192
|
+
finish(new Error(sanitizeOutput(err.message, token)));
|
|
119
193
|
}
|
|
120
194
|
});
|
|
121
|
-
//
|
|
195
|
+
// Handler unificado para stdout e stderr
|
|
122
196
|
const handleOutput = (data) => {
|
|
123
197
|
const text = data.toString();
|
|
198
|
+
const lowerText = text.toLowerCase();
|
|
199
|
+
// ---- Detecção de sucesso ----
|
|
124
200
|
if (this.mode === "quick") {
|
|
125
|
-
// Quick tunnel: busca a URL trycloudflare.com na saída
|
|
126
201
|
const match = text.match(this.urlRegex);
|
|
127
|
-
if (match && match[1]) {
|
|
202
|
+
if (match && match[1] && !isResolved) {
|
|
203
|
+
isResolved = true;
|
|
204
|
+
cleanup();
|
|
128
205
|
const url = match[1];
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
this.emit("ready", url);
|
|
133
|
-
resolve(makeResult(url));
|
|
134
|
-
}
|
|
206
|
+
this.emit("ready", url);
|
|
207
|
+
resolve(makeResult(url));
|
|
208
|
+
return;
|
|
135
209
|
}
|
|
136
210
|
}
|
|
137
211
|
else {
|
|
138
|
-
// Named tunnel: detecta
|
|
139
|
-
|
|
140
|
-
// quando está pronto para aceitar tráfego
|
|
141
|
-
if (text.includes("Registered tunnel connection") ||
|
|
212
|
+
// Named tunnel: detecta conexão estabelecida
|
|
213
|
+
if ((text.includes("Registered tunnel connection") ||
|
|
142
214
|
text.includes("registered connIndex=") ||
|
|
143
|
-
(text.includes("Connection") && text.includes("registered")))
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
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;
|
|
151
223
|
}
|
|
152
224
|
}
|
|
153
|
-
//
|
|
154
|
-
const lowerText = text.toLowerCase();
|
|
225
|
+
// ---- Detecção de erros específicos ----
|
|
155
226
|
if (lowerText.includes("connection refused")) {
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
cleanup();
|
|
159
|
-
isResolved = true;
|
|
160
|
-
reject(err);
|
|
161
|
-
this.stop();
|
|
162
|
-
}
|
|
163
|
-
else {
|
|
164
|
-
this.emit("error", err);
|
|
165
|
-
}
|
|
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;
|
|
166
229
|
}
|
|
167
|
-
if (lowerText.includes("
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
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;
|
|
179
249
|
}
|
|
180
250
|
if (lowerText.includes("tunnel not found") || lowerText.includes("does not exist")) {
|
|
181
|
-
|
|
182
|
-
"Verifique se o ID ou nome do túnel está correto.");
|
|
183
|
-
|
|
184
|
-
cleanup();
|
|
185
|
-
isResolved = true;
|
|
186
|
-
reject(err);
|
|
187
|
-
this.stop();
|
|
188
|
-
}
|
|
189
|
-
else {
|
|
190
|
-
this.emit("error", err);
|
|
191
|
-
}
|
|
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;
|
|
192
254
|
}
|
|
193
|
-
if (lowerText.includes("
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
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;
|
|
204
268
|
}
|
|
205
269
|
};
|
|
206
270
|
this.cp.stderr?.on("data", handleOutput);
|
|
207
271
|
this.cp.stdout?.on("data", handleOutput);
|
|
272
|
+
// Encerramento do processo
|
|
208
273
|
this.cp.on("close", (code) => {
|
|
209
274
|
cleanup();
|
|
210
275
|
if (!isResolved && code !== 0) {
|
|
211
276
|
isResolved = true;
|
|
212
|
-
reject(new Error(`
|
|
277
|
+
reject(new Error(`Cloudflared encerrou inesperadamente (código ${code}). ` +
|
|
278
|
+
"Verifique os logs acima para mais detalhes sobre o erro."));
|
|
213
279
|
}
|
|
214
280
|
this.emit("close");
|
|
215
281
|
});
|
package/package.json
CHANGED