cm-tunnel 1.5.0 → 1.7.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 +190 -13
- package/dist/StaticServer.d.ts +26 -0
- package/dist/StaticServer.js +151 -7
- package/dist/Tunnel.d.ts +2 -0
- package/dist/cli-utils.d.ts +59 -0
- package/dist/cli-utils.js +135 -2
- package/dist/cli.js +126 -129
- package/dist/config.d.ts +7 -0
- package/dist/config.js +95 -0
- package/dist/dashboard.d.ts +23 -0
- package/dist/dashboard.js +163 -0
- package/dist/doctor.d.ts +2 -0
- package/dist/doctor.js +152 -0
- package/dist/net-utils.d.ts +6 -0
- package/dist/net-utils.js +40 -0
- package/dist/providers/cloudflare.js +3 -1
- package/package.json +6 -5
package/README.md
CHANGED
|
@@ -23,11 +23,13 @@ Sem Express, sem configurar servidor: aponte as pastas `public` e `api` (ou uma
|
|
|
23
23
|
- [Estrutura de pastas e rotas](#estrutura-de-pastas-e-rotas)
|
|
24
24
|
- [Handlers de API](#handlers-de-api)
|
|
25
25
|
- [Referência do CLI](#referência-do-cli)
|
|
26
|
+
- [Comandos: doctor, dashboard e logs](#comandos-doctor-dashboard-e-logs)
|
|
26
27
|
- [API programática](#api-programática)
|
|
27
28
|
- [Segurança](#segurança)
|
|
28
29
|
- [Problemas comuns](#problemas-comuns)
|
|
29
30
|
- [FAQ](#faq)
|
|
30
31
|
- [Desenvolvimento](#desenvolvimento)
|
|
32
|
+
- [Arquitetura e dívida técnica](https://github.com/cmstudioapps/cm-tunnel/blob/main/ARCHITECTURE.md)
|
|
31
33
|
- [Licença](#licença)
|
|
32
34
|
|
|
33
35
|
---
|
|
@@ -50,7 +52,7 @@ Se não tiver o `cloudflared`:
|
|
|
50
52
|
npx cm-tunnel
|
|
51
53
|
```
|
|
52
54
|
|
|
53
|
-
> O CLI
|
|
55
|
+
> O CLI existe desde a **1.5.0**. `doctor`, `dashboard` e `apiMode: server` exigem a **1.7.0+**. Se o `npx` baixar uma versão antiga, use `npx cm-tunnel@latest` (ou `@1.7.0`).
|
|
54
56
|
|
|
55
57
|
O CLI pergunta:
|
|
56
58
|
|
|
@@ -60,12 +62,16 @@ O CLI pergunta:
|
|
|
60
62
|
Só API (funções de servidor)
|
|
61
63
|
❯ Site + API
|
|
62
64
|
Servidor já rodando (informar a porta)
|
|
65
|
+
? Como sua API funciona? ›
|
|
66
|
+
Funções por arquivo (handlers)
|
|
67
|
+
❯ Servidor normal (Express, Fastify, Node)
|
|
68
|
+
? Arquivo de entrada da API › api/index.js
|
|
63
69
|
? Como você quer publicar? ›
|
|
64
70
|
❯ URL temporária (trycloudflare.com) — sem configuração
|
|
65
71
|
Domínio próprio (túnel Cloudflare)
|
|
66
72
|
```
|
|
67
73
|
|
|
68
|
-
> Se `public/` e `api/` não existirem, ele
|
|
74
|
+
> As perguntas de pasta, `apiMode` e `apiEntry` só aparecem quando fazem sentido. Se `public/` e `api/` não existirem, ele oferece criar com arquivos de exemplo (`index.html`, `hello.js` ou um `index.js` de servidor).
|
|
69
75
|
|
|
70
76
|
No fim:
|
|
71
77
|
|
|
@@ -79,7 +85,7 @@ Túnel no ar: https://algum-nome-aleatorio.trycloudflare.com
|
|
|
79
85
|
Pressione Ctrl+C para encerrar.
|
|
80
86
|
```
|
|
81
87
|
|
|
82
|
-
As escolhas
|
|
88
|
+
As escolhas são salvas em `.cm-tunnel.json` **depois que o túnel sobe com sucesso**. Na próxima vez é só:
|
|
83
89
|
|
|
84
90
|
```bash
|
|
85
91
|
npx cm-tunnel
|
|
@@ -97,6 +103,7 @@ npx cm-tunnel --yes
|
|
|
97
103
|
| Só site estático | `npx cm-tunnel` → **Só site** |
|
|
98
104
|
| Só API | `npx cm-tunnel` → **Só API** |
|
|
99
105
|
| Meu Express já roda na porta 3000 | `npx cm-tunnel --yes --quick --target 3000` |
|
|
106
|
+
| Minha API é um Express normal dentro de `api/` | `npx cm-tunnel --yes --quick --api-mode server` |
|
|
100
107
|
| Testar rápido, sem configurar nada | `npx cm-tunnel --yes --quick` |
|
|
101
108
|
| Domínio próprio | `npx cm-tunnel --domain api.meudominio.com.br` |
|
|
102
109
|
|
|
@@ -184,6 +191,74 @@ serve: { public: './public' } // só site
|
|
|
184
191
|
serve: { api: './api' } // só API
|
|
185
192
|
```
|
|
186
193
|
|
|
194
|
+
### API em modo servidor (Express, Fastify ou `http`)
|
|
195
|
+
|
|
196
|
+
Se sua pasta `api/` é uma aplicação normal — e não funções por arquivo — use `apiMode: "server"`.
|
|
197
|
+
|
|
198
|
+
```text
|
|
199
|
+
api/
|
|
200
|
+
└── index.js # app.listen(process.env.PORT)
|
|
201
|
+
```
|
|
202
|
+
|
|
203
|
+
```bash
|
|
204
|
+
npx cm-tunnel --yes --quick --api-mode server
|
|
205
|
+
```
|
|
206
|
+
|
|
207
|
+
No modo interativo, o CLI pergunta:
|
|
208
|
+
|
|
209
|
+
```
|
|
210
|
+
? Como sua API funciona? ›
|
|
211
|
+
Funções por arquivo (handlers)
|
|
212
|
+
❯ Servidor normal (Express, Fastify, Node)
|
|
213
|
+
? Arquivo de entrada da API › api/index.js
|
|
214
|
+
```
|
|
215
|
+
|
|
216
|
+
O que a lib faz:
|
|
217
|
+
|
|
218
|
+
- injeta `PORT` e inicia `node api/index.js`
|
|
219
|
+
- serve `public/` normalmente
|
|
220
|
+
- encaminha `/api/*` para o app, removendo o prefixo
|
|
221
|
+
- espera o app responder antes de subir o túnel
|
|
222
|
+
- encerra o app no `Ctrl+C`
|
|
223
|
+
|
|
224
|
+
Exemplo de `api/index.js`:
|
|
225
|
+
|
|
226
|
+
```javascript
|
|
227
|
+
import express from 'express';
|
|
228
|
+
|
|
229
|
+
const app = express();
|
|
230
|
+
|
|
231
|
+
app.get('/hello', (req, res) => {
|
|
232
|
+
res.json({ ok: true });
|
|
233
|
+
});
|
|
234
|
+
|
|
235
|
+
app.listen(process.env.PORT);
|
|
236
|
+
```
|
|
237
|
+
|
|
238
|
+
Com o padrão `stripApiPrefix: true`:
|
|
239
|
+
|
|
240
|
+
```text
|
|
241
|
+
GET /api/hello → app recebe /hello
|
|
242
|
+
GET /api/users → app recebe /users
|
|
243
|
+
```
|
|
244
|
+
|
|
245
|
+
> O app precisa escutar em `process.env.PORT`. Se ele já usa uma porta fixa, use o modo `--target <porta>`.
|
|
246
|
+
|
|
247
|
+
**Equivalente em código:**
|
|
248
|
+
|
|
249
|
+
```javascript
|
|
250
|
+
const t = await tunnel({
|
|
251
|
+
provider: 'cloudflare',
|
|
252
|
+
serve: {
|
|
253
|
+
public: './public',
|
|
254
|
+
api: './api',
|
|
255
|
+
apiMode: 'server',
|
|
256
|
+
apiEntry: './api/index.js',
|
|
257
|
+
// stripApiPrefix: false, // mantém /api no app
|
|
258
|
+
},
|
|
259
|
+
});
|
|
260
|
+
```
|
|
261
|
+
|
|
187
262
|
---
|
|
188
263
|
|
|
189
264
|
## Tunelar um servidor que já existe
|
|
@@ -202,7 +277,7 @@ Ou, no modo interativo, escolha:
|
|
|
202
277
|
? Porta em que seu servidor já está rodando › 3000
|
|
203
278
|
```
|
|
204
279
|
|
|
205
|
-
Nesse modo o `cm-tunnel` **não** inicia servidor nem aplica rate limit próprio — ele só aponta o túnel para a porta informada.
|
|
280
|
+
Nesse modo o `cm-tunnel` **não** inicia servidor nem aplica rate limit próprio — ele só aponta o túnel para a porta informada. Use quando você já roda o processo e quer controle total dele.
|
|
206
281
|
|
|
207
282
|
**Equivalente em código:**
|
|
208
283
|
|
|
@@ -282,6 +357,8 @@ cloudflared tunnel token <nome-ou-id-do-tunel>
|
|
|
282
357
|
|
|
283
358
|
## Estrutura de pastas e rotas
|
|
284
359
|
|
|
360
|
+
No modo `handlers` (padrão):
|
|
361
|
+
|
|
285
362
|
| Arquivo | Rota |
|
|
286
363
|
|---|---|
|
|
287
364
|
| `public/index.html` | `/` |
|
|
@@ -291,6 +368,7 @@ cloudflared tunnel token <nome-ou-id-do-tunel>
|
|
|
291
368
|
| `api/index.js` | `/api` |
|
|
292
369
|
|
|
293
370
|
- `/api` é reservado: **nunca** cai no estático, mesmo que exista `public/api`.
|
|
371
|
+
- No modo `apiMode: "server"`, tudo em `/api/*` é encaminhado para o seu app (com o prefixo removido por padrão).
|
|
294
372
|
- Funciona com só `public`, só `api`, ou com as duas.
|
|
295
373
|
- `apiPrefix` muda o prefixo padrão (`/api` → `/v1`, por exemplo).
|
|
296
374
|
|
|
@@ -298,7 +376,7 @@ cloudflared tunnel token <nome-ou-id-do-tunel>
|
|
|
298
376
|
|
|
299
377
|
## Handlers de API
|
|
300
378
|
|
|
301
|
-
|
|
379
|
+
No modo `handlers` (padrão), use `.js`, `.mjs` ou `.cjs`. TypeScript precisa ser compilado antes.
|
|
302
380
|
|
|
303
381
|
**Função default (qualquer método):**
|
|
304
382
|
|
|
@@ -341,6 +419,8 @@ npx cm-tunnel [opções]
|
|
|
341
419
|
| `--mode site\|api\|both` | O que publicar (pastas) |
|
|
342
420
|
| `--public <pasta>` | Pasta do site (padrão: `public`) |
|
|
343
421
|
| `--api <pasta>` | Pasta da API (padrão: `api`) |
|
|
422
|
+
| `--api-mode handlers\|server` | API por arquivo (`handlers`) ou servidor normal (`server`) |
|
|
423
|
+
| `--api-entry <arquivo>` | Entrypoint no modo server (detectado ou `<api>/index.js`) |
|
|
344
424
|
| `--api-prefix <prefixo>` | Prefixo da API (padrão: `/api`) |
|
|
345
425
|
| `--target <porta>` | Tunelar um servidor que já está rodando |
|
|
346
426
|
| `--port <porta>` | Porta do servidor interno (pastas + domínio) |
|
|
@@ -349,6 +429,7 @@ npx cm-tunnel [opções]
|
|
|
349
429
|
| `--quick` | URL temporária, sem configuração |
|
|
350
430
|
| `--yes`, `-y` | Não perguntar (usa flags/padrões) |
|
|
351
431
|
| `--dry-run` | Mostra o plano, não cria nada e não inicia |
|
|
432
|
+
| `--logs`, `-l` | Mostra logs do `cloudflared` e do servidor de API (no modo `server`) |
|
|
352
433
|
| `--no-save` | Não salva `.cm-tunnel.json` nem o token |
|
|
353
434
|
| `--lang pt\|en` | Idioma (padrão: detecta pelo `LANG`) |
|
|
354
435
|
| `-h`, `--help` | Ajuda |
|
|
@@ -380,11 +461,78 @@ npx cm-tunnel --lang en
|
|
|
380
461
|
|
|
381
462
|
| Arquivo | Conteúdo |
|
|
382
463
|
|---------|----------|
|
|
383
|
-
| `.cm-tunnel.json` | modo, pastas (ou porta), domínio (sem token) |
|
|
464
|
+
| `.cm-tunnel.json` | modo, pastas (ou porta), `apiMode`/`apiEntry`, domínio (sem token) |
|
|
384
465
|
| `.env` | `CLOUDFLARE_TOKEN` (permissão `600`) |
|
|
385
466
|
|
|
386
467
|
---
|
|
387
468
|
|
|
469
|
+
## Comandos: doctor, dashboard e logs
|
|
470
|
+
|
|
471
|
+
### `doctor` — diagnóstico completo
|
|
472
|
+
|
|
473
|
+
```bash
|
|
474
|
+
npx cm-tunnel doctor
|
|
475
|
+
```
|
|
476
|
+
|
|
477
|
+
Verifica:
|
|
478
|
+
|
|
479
|
+
- versão do Node
|
|
480
|
+
- `cloudflared` instalado
|
|
481
|
+
- `.cm-tunnel.json` válido
|
|
482
|
+
- token presente (quando usa domínio)
|
|
483
|
+
- pastas `public`/`api`
|
|
484
|
+
- entrypoint da API (quando `apiMode = "server"`)
|
|
485
|
+
- porta livre (ou servidor respondendo no modo `--target`)
|
|
486
|
+
- DNS do domínio
|
|
487
|
+
- lembrete do Public Hostname
|
|
488
|
+
|
|
489
|
+
Exemplo de saída:
|
|
490
|
+
|
|
491
|
+
```text
|
|
492
|
+
cm-tunnel doctor
|
|
493
|
+
|
|
494
|
+
✔ Node.js 20.19.2: ok
|
|
495
|
+
✔ cloudflared: cloudflared version 2026.11.1
|
|
496
|
+
✔ Configuração: mode=both, publish=domain, domain=escola.exemplo.com, port=3000
|
|
497
|
+
✔ Token: presente (184 caracteres)
|
|
498
|
+
✔ Pasta public: ok
|
|
499
|
+
✔ Pasta api: ok
|
|
500
|
+
✔ Porta 3000: livre
|
|
501
|
+
✖ DNS escola.exemplo.com: não resolve
|
|
502
|
+
! Public Hostname: confira no dashboard (escola.exemplo.com -> http://localhost:3000)
|
|
503
|
+
|
|
504
|
+
Resumo: 7 ok, 1 aviso(s), 1 erro(s)
|
|
505
|
+
Corrija os itens com ✖ antes de publicar.
|
|
506
|
+
```
|
|
507
|
+
|
|
508
|
+
Sai com código `1` se houver erro.
|
|
509
|
+
|
|
510
|
+
### `dashboard` — painel com logs ao vivo
|
|
511
|
+
|
|
512
|
+
```bash
|
|
513
|
+
npx cm-tunnel dashboard
|
|
514
|
+
```
|
|
515
|
+
|
|
516
|
+
Mostra em tela cheia:
|
|
517
|
+
|
|
518
|
+
- status (iniciando / online / parado)
|
|
519
|
+
- URL pública
|
|
520
|
+
- modo (site, API, site + API ou servidor)
|
|
521
|
+
- porta local
|
|
522
|
+
- últimas 10 linhas do `cloudflared` e do servidor de API (no modo `server`)
|
|
523
|
+
|
|
524
|
+
`Ctrl+C` encerra o túnel e restaura o terminal. Se não houver TTY, cai automaticamente para logs em texto.
|
|
525
|
+
|
|
526
|
+
### `--logs` — logs sem painel
|
|
527
|
+
|
|
528
|
+
```bash
|
|
529
|
+
npx cm-tunnel --logs
|
|
530
|
+
```
|
|
531
|
+
|
|
532
|
+
Mostra a saída do `cloudflared` e do servidor de API direto no terminal. A saída do `cloudflared` é sanitizada (token oculto); os logs do seu app são repassados como estão — evite imprimir segredos neles.
|
|
533
|
+
|
|
534
|
+
---
|
|
535
|
+
|
|
388
536
|
## API programática
|
|
389
537
|
|
|
390
538
|
### Publicar pastas
|
|
@@ -474,6 +622,11 @@ console.log(local.url); // http://127.0.0.1:<porta>
|
|
|
474
622
|
| `public` | `string` | — | Pasta de arquivos estáticos |
|
|
475
623
|
| `directory` | `string` | — | Alias legado de `public` |
|
|
476
624
|
| `api` | `string` | — | Pasta com handlers; nunca é servida como estático |
|
|
625
|
+
| `apiMode` | `'handlers' \| 'server'` | `'handlers'` | `handlers` = um arquivo por rota; `server` = app normal (Express/Fastify/http) |
|
|
626
|
+
| `apiEntry` | `string` | `<api>/index.js` | Arquivo de entrada no modo `server` |
|
|
627
|
+
| `stripApiPrefix` | `boolean` | `true` | Remove `/api` antes de encaminhar ao servidor |
|
|
628
|
+
| `apiTimeout` | `number` | `30000` | Tempo para o servidor ficar pronto |
|
|
629
|
+
| `onLog` | `(line: string) => void` | — | Recebe logs do servidor de API |
|
|
477
630
|
| `apiPrefix` | `string` | `'/api'` | Prefixo das rotas de API |
|
|
478
631
|
| `html` | `string` | — | HTML fixo para rotas não-API (prioridade sobre `public`) |
|
|
479
632
|
| `port` | `number` | aleatória | Porta local do servidor interno |
|
|
@@ -509,6 +662,8 @@ O rate limit do modo pastas é aplicado por IP em `/api` (padrão: 60 req/min) q
|
|
|
509
662
|
|
|
510
663
|
## Problemas comuns
|
|
511
664
|
|
|
665
|
+
> **Antes de tudo:** rode `npx cm-tunnel doctor`. Ele mostra Node, `cloudflared`, configuração, pastas, porta, token e DNS de uma vez.
|
|
666
|
+
|
|
512
667
|
### `cloudflared: command not found`
|
|
513
668
|
|
|
514
669
|
Instale o `cloudflared` e garanta que ele está no `PATH`:
|
|
@@ -559,9 +714,9 @@ Enquanto a zona estiver `pending` na Cloudflare, nada resolve publicamente.
|
|
|
559
714
|
|
|
560
715
|
### `npx cm-tunnel` diz que o comando não existe ou abre uma versão antiga
|
|
561
716
|
|
|
562
|
-
-
|
|
717
|
+
- O CLI existe desde a **1.5.0**; `doctor`, `dashboard` e `apiMode: server` exigem **1.7.0+**.
|
|
563
718
|
```bash
|
|
564
|
-
npx cm-tunnel@
|
|
719
|
+
npx cm-tunnel@latest --version
|
|
565
720
|
```
|
|
566
721
|
- Confirme a versão:
|
|
567
722
|
```bash
|
|
@@ -596,6 +751,8 @@ npm run deploy
|
|
|
596
751
|
|
|
597
752
|
### A API responde 404
|
|
598
753
|
|
|
754
|
+
No modo `handlers`:
|
|
755
|
+
|
|
599
756
|
- O arquivo precisa estar em `api/` com extensão `.js`, `.mjs` ou `.cjs`.
|
|
600
757
|
- A rota segue o caminho do arquivo:
|
|
601
758
|
- `api/hello.js` → `/api/hello`
|
|
@@ -606,6 +763,19 @@ npm run deploy
|
|
|
606
763
|
```
|
|
607
764
|
- Se mudou o prefixo, use o prefixo configurado (`/v1`, etc.).
|
|
608
765
|
|
|
766
|
+
No modo `server`, o 404 vem do **seu** app — confira as rotas dele e se o prefixo `/api` está sendo removido (`stripApiPrefix`).
|
|
767
|
+
|
|
768
|
+
---
|
|
769
|
+
|
|
770
|
+
### A API em modo server não sobe (502 ou timeout)
|
|
771
|
+
|
|
772
|
+
- **`API encerrou antes de ficar pronta (código 0)`**: o entry não abriu servidor. Ele precisa chamar `app.listen(process.env.PORT)`. Se o arquivo exporta só uma função `(req, res)`, use `apiMode: "handlers"` / `--api-mode handlers`.
|
|
773
|
+
- O app precisa escutar em **`process.env.PORT`** — a lib injeta a porta.
|
|
774
|
+
- O `apiEntry` precisa existir (padrão: `api/index.js`).
|
|
775
|
+
- Rode com `--logs` para ver a saída do seu app.
|
|
776
|
+
- Se o app demorar, aumente `apiTimeout` (padrão: 30s).
|
|
777
|
+
- Se o app usa uma porta fixa, use `--target <porta>` em vez de `apiMode: "server"`.
|
|
778
|
+
|
|
609
779
|
---
|
|
610
780
|
|
|
611
781
|
### Minha pasta `api` está sendo servida como estático
|
|
@@ -629,7 +799,7 @@ Ou no dashboard: **Configure → Refresh token**. Atualize o `.env`.
|
|
|
629
799
|
## FAQ
|
|
630
800
|
|
|
631
801
|
**Preciso de Express?**
|
|
632
|
-
Não.
|
|
802
|
+
Não. Você pode usar handlers por arquivo, apontar `apiMode: "server"` para um app Express/Fastify seu, ou rodar o app você mesmo e usar `--target <porta>`.
|
|
633
803
|
|
|
634
804
|
**Posso publicar só o site ou só a API?**
|
|
635
805
|
Sim. No CLI escolha “Só site” ou “Só API”, ou use `--mode site` / `--mode api`.
|
|
@@ -638,13 +808,13 @@ Sim. No CLI escolha “Só site” ou “Só API”, ou use `--mode site` / `--m
|
|
|
638
808
|
Não. A pasta `api/` só é carregada no servidor. `/api` nunca é servido como arquivo estático.
|
|
639
809
|
|
|
640
810
|
**Funciona com TypeScript?**
|
|
641
|
-
Os handlers precisam
|
|
811
|
+
Os handlers e o entry do modo `server` precisam ser JavaScript executável (`.js`, `.mjs` ou `.cjs`). Compile o TypeScript antes.
|
|
642
812
|
|
|
643
813
|
**Como atualizo o site?**
|
|
644
|
-
Basta alterar os arquivos em `public/`.
|
|
814
|
+
Basta alterar os arquivos em `public/`. No modo `handlers`, os arquivos em `api/` recarregam sozinhos quando mudam. No modo `server`, o seu processo decide (reinicie se ele não tiver hot reload).
|
|
645
815
|
|
|
646
816
|
**Como paro o túnel?**
|
|
647
|
-
`Ctrl+C`. O CLI encerra o `cloudflared`
|
|
817
|
+
`Ctrl+C`. O CLI encerra o `cloudflared` e, no modo `server`, também encerra o processo da API.
|
|
648
818
|
|
|
649
819
|
**Onde ficam as preferências?**
|
|
650
820
|
Em `.cm-tunnel.json`, na pasta onde você rodou o CLI. O token fica no `.env`.
|
|
@@ -659,11 +829,14 @@ Sim, desde que o binário `cloudflared` esteja no `PATH`. `npx` e `npm run` são
|
|
|
659
829
|
|
|
660
830
|
## Desenvolvimento
|
|
661
831
|
|
|
832
|
+
> Arquitetura interna, fluxos, decisões e dívida técnica: [ARCHITECTURE.md](https://github.com/cmstudioapps/cm-tunnel/blob/main/ARCHITECTURE.md)
|
|
833
|
+
|
|
662
834
|
```bash
|
|
663
835
|
npm install
|
|
664
836
|
npm test # roda a suíte
|
|
665
837
|
npm run lint
|
|
666
838
|
npm run build # gera dist/ e deixa dist/cli.js executável
|
|
839
|
+
npm run check:self # impede self-dependency e node_modules/cm-tunnel
|
|
667
840
|
```
|
|
668
841
|
|
|
669
842
|
Estrutura principal:
|
|
@@ -672,8 +845,12 @@ Estrutura principal:
|
|
|
672
845
|
src/
|
|
673
846
|
├── cli.ts # executável do CLI
|
|
674
847
|
├── cli-utils.ts # i18n, flags, plano
|
|
848
|
+
├── config.ts # .env e .cm-tunnel.json
|
|
849
|
+
├── net-utils.ts # portas livres/em uso
|
|
850
|
+
├── doctor.ts # diagnóstico
|
|
851
|
+
├── dashboard.ts # painel TUI
|
|
675
852
|
├── Tunnel.ts # orquestração dos provedores
|
|
676
|
-
├── StaticServer.ts #
|
|
853
|
+
├── StaticServer.ts # static + handlers + proxy para api server
|
|
677
854
|
├── RateLimiter.ts # rate limit por IP
|
|
678
855
|
└── providers/ # cloudflare, localtunnel, ngrok
|
|
679
856
|
```
|
package/dist/StaticServer.d.ts
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
export type ApiMode = 'handlers' | 'server';
|
|
1
2
|
export interface ServeOptions {
|
|
2
3
|
/** HTML fixo servido em qualquer rota não-API */
|
|
3
4
|
html?: string;
|
|
@@ -10,9 +11,23 @@ export interface ServeOptions {
|
|
|
10
11
|
* como estáticos; cada arquivo vira uma rota (`api/hello.js` → `/api/hello`).
|
|
11
12
|
*/
|
|
12
13
|
api?: string;
|
|
14
|
+
/**
|
|
15
|
+
* Como a API funciona:
|
|
16
|
+
* - `handlers` (padrão): cada arquivo em `api/` exporta uma função
|
|
17
|
+
* - `server`: roda um servidor normal (Express, Fastify, http) a partir de `apiEntry`
|
|
18
|
+
*/
|
|
19
|
+
apiMode?: ApiMode;
|
|
20
|
+
/** Arquivo de entrada do servidor de API (padrão: `<api>/index.js`) */
|
|
21
|
+
apiEntry?: string;
|
|
22
|
+
/** Remove o prefixo da API antes de encaminhar para o servidor (padrão: true) */
|
|
23
|
+
stripApiPrefix?: boolean;
|
|
24
|
+
/** Timeout em ms para o servidor de API ficar pronto (padrão: 30000) */
|
|
25
|
+
apiTimeout?: number;
|
|
13
26
|
/** Prefixo das rotas de API (padrão: `/api`) */
|
|
14
27
|
apiPrefix?: string;
|
|
15
28
|
port?: number;
|
|
29
|
+
/** Recebe logs do servidor de API quando apiMode = "server" */
|
|
30
|
+
onLog?: (line: string) => void;
|
|
16
31
|
}
|
|
17
32
|
export declare class StaticServer {
|
|
18
33
|
private options;
|
|
@@ -22,11 +37,22 @@ export declare class StaticServer {
|
|
|
22
37
|
private staticRealRoot;
|
|
23
38
|
private apiRealRoot;
|
|
24
39
|
private apiPrefix;
|
|
40
|
+
private apiMode;
|
|
41
|
+
private apiEntry;
|
|
42
|
+
private stripApiPrefix;
|
|
43
|
+
private apiProcess;
|
|
44
|
+
private apiProxy;
|
|
45
|
+
private apiPort;
|
|
46
|
+
private stopping;
|
|
25
47
|
private moduleCache;
|
|
26
48
|
port: number;
|
|
27
49
|
url: string;
|
|
28
50
|
constructor(options: ServeOptions);
|
|
29
51
|
private prepareRoots;
|
|
52
|
+
private startApiServer;
|
|
53
|
+
private stopApiServer;
|
|
54
|
+
private rewriteApiUrl;
|
|
55
|
+
private handleApiServer;
|
|
30
56
|
start(): Promise<{
|
|
31
57
|
port: number;
|
|
32
58
|
url: string;
|
package/dist/StaticServer.js
CHANGED
|
@@ -2,6 +2,9 @@ import http from 'http';
|
|
|
2
2
|
import fs from 'fs';
|
|
3
3
|
import path from 'path';
|
|
4
4
|
import { pathToFileURL } from 'url';
|
|
5
|
+
import { spawn } from 'child_process';
|
|
6
|
+
import httpProxy from 'http-proxy';
|
|
7
|
+
import { findFreePort, isPortInUse } from './net-utils.js';
|
|
5
8
|
const API_EXTENSIONS = ['.js', '.mjs', '.cjs'];
|
|
6
9
|
const MIME_TYPES = {
|
|
7
10
|
'.html': 'text/html; charset=utf-8',
|
|
@@ -83,6 +86,13 @@ export class StaticServer {
|
|
|
83
86
|
staticRealRoot = null;
|
|
84
87
|
apiRealRoot = null;
|
|
85
88
|
apiPrefix;
|
|
89
|
+
apiMode;
|
|
90
|
+
apiEntry = null;
|
|
91
|
+
stripApiPrefix;
|
|
92
|
+
apiProcess = null;
|
|
93
|
+
apiProxy = null;
|
|
94
|
+
apiPort = null;
|
|
95
|
+
stopping = false;
|
|
86
96
|
moduleCache = new Map();
|
|
87
97
|
port = 0;
|
|
88
98
|
url = '';
|
|
@@ -95,6 +105,15 @@ export class StaticServer {
|
|
|
95
105
|
if (!prefix.startsWith('/'))
|
|
96
106
|
prefix = `/${prefix}`;
|
|
97
107
|
this.apiPrefix = prefix.replace(/\/+$/, '') || '/api';
|
|
108
|
+
this.apiMode = options.apiMode === 'server' ? 'server' : 'handlers';
|
|
109
|
+
this.stripApiPrefix = options.stripApiPrefix !== false;
|
|
110
|
+
if (this.apiMode === 'server') {
|
|
111
|
+
this.apiEntry = options.apiEntry
|
|
112
|
+
? path.resolve(options.apiEntry)
|
|
113
|
+
: this.apiRoot
|
|
114
|
+
? path.join(this.apiRoot, 'index.js')
|
|
115
|
+
: null;
|
|
116
|
+
}
|
|
98
117
|
}
|
|
99
118
|
prepareRoots() {
|
|
100
119
|
if (this.staticRoot) {
|
|
@@ -109,16 +128,126 @@ export class StaticServer {
|
|
|
109
128
|
}
|
|
110
129
|
this.apiRealRoot = fs.realpathSync(this.apiRoot);
|
|
111
130
|
}
|
|
131
|
+
if (this.apiMode === 'server') {
|
|
132
|
+
if (!this.apiEntry) {
|
|
133
|
+
throw new Error('apiMode "server" requer a opção "api" ou "apiEntry".');
|
|
134
|
+
}
|
|
135
|
+
if (!fs.existsSync(this.apiEntry) || !fs.statSync(this.apiEntry).isFile()) {
|
|
136
|
+
throw new Error(`Arquivo de entrada da API não encontrado: "${this.apiEntry}".`);
|
|
137
|
+
}
|
|
138
|
+
}
|
|
112
139
|
}
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
140
|
+
async startApiServer() {
|
|
141
|
+
if (!this.apiEntry) {
|
|
142
|
+
throw new Error('apiMode "server" requer um arquivo de entrada.');
|
|
143
|
+
}
|
|
144
|
+
const port = await findFreePort();
|
|
145
|
+
this.apiPort = port;
|
|
146
|
+
const child = spawn(process.execPath, [this.apiEntry], {
|
|
147
|
+
cwd: process.cwd(),
|
|
148
|
+
env: {
|
|
149
|
+
...process.env,
|
|
150
|
+
PORT: String(port),
|
|
151
|
+
CM_TUNNEL_API_PORT: String(port),
|
|
152
|
+
},
|
|
153
|
+
stdio: ['ignore', 'pipe', 'pipe'],
|
|
154
|
+
});
|
|
155
|
+
this.apiProcess = child;
|
|
156
|
+
let output = '';
|
|
157
|
+
let exited = false;
|
|
158
|
+
let ready = false;
|
|
159
|
+
let exitInfo = '';
|
|
160
|
+
const forward = (data) => {
|
|
161
|
+
const text = data.toString();
|
|
162
|
+
output = `${output}${text}`.slice(-4000);
|
|
163
|
+
this.options.onLog?.(text);
|
|
164
|
+
};
|
|
165
|
+
child.stdout?.on('data', forward);
|
|
166
|
+
child.stderr?.on('data', forward);
|
|
167
|
+
child.once('exit', (code, signal) => {
|
|
168
|
+
exited = true;
|
|
169
|
+
exitInfo = code !== null ? `código ${code}` : `sinal ${signal}`;
|
|
170
|
+
if (!this.stopping && ready) {
|
|
171
|
+
console.error(`[cm-tunnel] A API encerrou inesperadamente (${exitInfo}).`);
|
|
172
|
+
}
|
|
173
|
+
});
|
|
174
|
+
const timeoutMs = this.options.apiTimeout ?? 30000;
|
|
175
|
+
const deadline = Date.now() + timeoutMs;
|
|
176
|
+
while (Date.now() < deadline) {
|
|
177
|
+
if (exited) {
|
|
178
|
+
this.stopApiServer();
|
|
179
|
+
throw new Error(`API encerrou antes de ficar pronta (${exitInfo || 'sem código'}).\n` +
|
|
180
|
+
'O arquivo de entrada precisa iniciar um servidor HTTP em process.env.PORT ' +
|
|
181
|
+
'(ex: app.listen(process.env.PORT)). Se ele exporta apenas uma função (req, res), ' +
|
|
182
|
+
'use apiMode: "handlers" ou --api-mode handlers.' +
|
|
183
|
+
(output ? `\nSaída:\n${output}` : ''));
|
|
117
184
|
}
|
|
118
|
-
|
|
119
|
-
|
|
185
|
+
if (await isPortInUse(port)) {
|
|
186
|
+
this.apiProxy = httpProxy.createProxyServer({
|
|
187
|
+
target: `http://127.0.0.1:${port}`,
|
|
188
|
+
ws: true,
|
|
189
|
+
});
|
|
190
|
+
this.apiProxy.on('error', (_err, _req, res) => {
|
|
191
|
+
const response = res;
|
|
192
|
+
if (response && typeof response.writeHead === 'function' && !response.headersSent) {
|
|
193
|
+
response.writeHead(502, {
|
|
194
|
+
'Content-Type': 'application/json; charset=utf-8',
|
|
195
|
+
});
|
|
196
|
+
response.end(JSON.stringify({ error: 'Bad Gateway' }));
|
|
197
|
+
}
|
|
198
|
+
});
|
|
199
|
+
ready = true;
|
|
120
200
|
return;
|
|
121
201
|
}
|
|
202
|
+
await new Promise((resolveWait) => setTimeout(resolveWait, 100));
|
|
203
|
+
}
|
|
204
|
+
this.stopApiServer();
|
|
205
|
+
throw new Error(`API não ficou pronta em ${timeoutMs / 1000}s. ` +
|
|
206
|
+
'Verifique se o entry chama app.listen(process.env.PORT).' +
|
|
207
|
+
(output ? `\nSaída:\n${output}` : ''));
|
|
208
|
+
}
|
|
209
|
+
stopApiServer() {
|
|
210
|
+
this.stopping = true;
|
|
211
|
+
if (this.apiProxy) {
|
|
212
|
+
try {
|
|
213
|
+
this.apiProxy.close();
|
|
214
|
+
}
|
|
215
|
+
catch {
|
|
216
|
+
// ignora
|
|
217
|
+
}
|
|
218
|
+
this.apiProxy = null;
|
|
219
|
+
}
|
|
220
|
+
if (this.apiProcess) {
|
|
221
|
+
try {
|
|
222
|
+
this.apiProcess.kill();
|
|
223
|
+
}
|
|
224
|
+
catch {
|
|
225
|
+
// ignora
|
|
226
|
+
}
|
|
227
|
+
this.apiProcess = null;
|
|
228
|
+
}
|
|
229
|
+
this.apiPort = null;
|
|
230
|
+
}
|
|
231
|
+
rewriteApiUrl(url) {
|
|
232
|
+
if (!this.stripApiPrefix)
|
|
233
|
+
return url;
|
|
234
|
+
const rest = url.slice(this.apiPrefix.length);
|
|
235
|
+
return rest.startsWith('/') ? rest || '/' : `/${rest}`;
|
|
236
|
+
}
|
|
237
|
+
handleApiServer(req, res) {
|
|
238
|
+
if (!this.apiProxy || !this.apiPort) {
|
|
239
|
+
this.sendJson(res, 502, { error: 'API server not ready' });
|
|
240
|
+
return;
|
|
241
|
+
}
|
|
242
|
+
req.url = this.rewriteApiUrl(req.url || '/');
|
|
243
|
+
this.apiProxy.web(req, res);
|
|
244
|
+
}
|
|
245
|
+
async start() {
|
|
246
|
+
this.prepareRoots();
|
|
247
|
+
if (this.apiMode === 'server') {
|
|
248
|
+
await this.startApiServer();
|
|
249
|
+
}
|
|
250
|
+
return new Promise((resolve, reject) => {
|
|
122
251
|
this.server = http.createServer((req, res) => {
|
|
123
252
|
this.handle(req, res).catch((err) => {
|
|
124
253
|
console.error('[cm-tunnel] Erro ao processar requisição:', err);
|
|
@@ -128,6 +257,17 @@ export class StaticServer {
|
|
|
128
257
|
res.end(JSON.stringify({ error: 'Internal Server Error' }));
|
|
129
258
|
});
|
|
130
259
|
});
|
|
260
|
+
this.server.on('upgrade', (req, socket, head) => {
|
|
261
|
+
const url = req.url || '';
|
|
262
|
+
const isApi = url === this.apiPrefix || url.startsWith(`${this.apiPrefix}/`);
|
|
263
|
+
if (this.apiMode === 'server' && this.apiProxy && isApi) {
|
|
264
|
+
req.url = this.rewriteApiUrl(url);
|
|
265
|
+
this.apiProxy.ws(req, socket, head);
|
|
266
|
+
}
|
|
267
|
+
else {
|
|
268
|
+
socket.destroy();
|
|
269
|
+
}
|
|
270
|
+
});
|
|
131
271
|
this.server.on('error', reject);
|
|
132
272
|
const targetPort = this.options.port || 0;
|
|
133
273
|
this.server.listen(targetPort, '127.0.0.1', () => {
|
|
@@ -154,7 +294,10 @@ export class StaticServer {
|
|
|
154
294
|
return;
|
|
155
295
|
}
|
|
156
296
|
if (pathname === this.apiPrefix || pathname.startsWith(`${this.apiPrefix}/`)) {
|
|
157
|
-
if (this.
|
|
297
|
+
if (this.apiMode === 'server') {
|
|
298
|
+
this.handleApiServer(req, res);
|
|
299
|
+
}
|
|
300
|
+
else if (this.apiRoot) {
|
|
158
301
|
await this.handleApi(req, res, pathname);
|
|
159
302
|
}
|
|
160
303
|
else {
|
|
@@ -376,6 +519,7 @@ export class StaticServer {
|
|
|
376
519
|
res.end(JSON.stringify(body));
|
|
377
520
|
}
|
|
378
521
|
stop() {
|
|
522
|
+
this.stopApiServer();
|
|
379
523
|
if (this.server) {
|
|
380
524
|
this.server.close();
|
|
381
525
|
this.server = null;
|
package/dist/Tunnel.d.ts
CHANGED
|
@@ -12,6 +12,8 @@ export interface TunnelOptions {
|
|
|
12
12
|
rateLimit?: RateLimitOptions | boolean;
|
|
13
13
|
serve?: ServeOptions;
|
|
14
14
|
cloudflare?: CloudflareOptions;
|
|
15
|
+
/** Recebe a saída bruta (sanitizada) do provedor, útil para logs ao vivo. */
|
|
16
|
+
onLog?: (line: string) => void;
|
|
15
17
|
}
|
|
16
18
|
export interface TunnelInstance extends TunnelResult, EventEmitter {
|
|
17
19
|
on(event: "ready", listener: (url: string) => void): this;
|