cm-tunnel 1.0.0 → 1.2.0

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
@@ -1,6 +1,6 @@
1
1
  # cm-tunnel
2
2
 
3
- Exponha seu servidor HTTP local para a internet através de uma API extremamente simples. Suporta **Cloudflare** e **LocalTunnel**.
3
+ Exponha seu servidor HTTP local para a internet através de uma API extremamente simples. Suporta **Cloudflare**, **LocalTunnel** e **Ngrok**.
4
4
 
5
5
  ## Instalação
6
6
 
@@ -10,6 +10,7 @@ npm install cm-tunnel
10
10
 
11
11
  ## Requisitos
12
12
 
13
+
13
14
  - Node.js >= 18
14
15
  - Para usar o provedor do Cloudflare, o executável `cloudflared` deve estar instalado no sistema e disponível no `PATH`. Caso não esteja, a biblioteca emitirá um erro amigável.
15
16
 
@@ -22,8 +23,14 @@ import tunnel from 'cm-tunnel';
22
23
 
23
24
  try {
24
25
  const t = await tunnel({
25
- provider: 'cloudflare', // ou 'localtunnel'
26
- port: 3000
26
+ provider: 'cloudflare', // 'cloudflare', 'localtunnel' ou 'ngrok'
27
+ port: 3000,
28
+ subdomain: 'meu-app-unico', // Opcional (para localtunnel e ngrok)
29
+ authtoken: 'token_aqui', // Opcional (recomendado para ngrok)
30
+ rateLimit: { // Opcional: Bloqueia IPs por excesso de requisições
31
+ maxRequestsPerMinute: 60,
32
+ routes: ['/api/'] // Se vazio, aplica globalmente
33
+ }
27
34
  });
28
35
 
29
36
  console.log('Túnel público:', t.url);
@@ -47,6 +54,9 @@ const t1 = await tunnel.cloudflare({ port: 3000 });
47
54
 
48
55
  // Usando localtunnel
49
56
  const t2 = await tunnel.localtunnel({ port: 3000 });
57
+
58
+ // Usando ngrok
59
+ const t3 = await tunnel.ngrok({ port: 3000, authtoken: 'seu_token' });
50
60
  ```
51
61
 
52
62
  ## Objeto de Retorno
@@ -71,4 +81,4 @@ A arquitetura de `cm-tunnel` é modular. Para adicionar um novo provedor:
71
81
 
72
82
  ## Licença
73
83
 
74
- MIT
84
+ MIT
@@ -6,8 +6,15 @@ export interface TunnelResult {
6
6
  stop: () => void;
7
7
  process?: unknown;
8
8
  }
9
+ export interface ProviderOptions {
10
+ port: number;
11
+ subdomain?: string;
12
+ authtoken?: string;
13
+ [key: string]: any;
14
+ }
9
15
  export declare abstract class Provider extends EventEmitter {
16
+ protected options: ProviderOptions;
10
17
  protected port: number;
11
- constructor(port: number);
18
+ constructor(options: ProviderOptions);
12
19
  abstract start(): Promise<TunnelResult>;
13
20
  }
package/dist/Provider.js CHANGED
@@ -1,8 +1,10 @@
1
1
  import { EventEmitter } from "events";
2
2
  export class Provider extends EventEmitter {
3
+ options;
3
4
  port;
4
- constructor(port) {
5
+ constructor(options) {
5
6
  super();
6
- this.port = port;
7
+ this.options = options;
8
+ this.port = options.port;
7
9
  }
8
10
  }
@@ -0,0 +1,15 @@
1
+ export interface RateLimitOptions {
2
+ maxRequestsPerMinute: number;
3
+ routes?: string[];
4
+ }
5
+ export declare class RateLimiter {
6
+ private targetPort;
7
+ private options;
8
+ private server;
9
+ private proxy;
10
+ private port;
11
+ private isGlobal;
12
+ constructor(targetPort: number, options: RateLimitOptions | true);
13
+ start(): Promise<number>;
14
+ stop(): void;
15
+ }
@@ -0,0 +1,114 @@
1
+ import http from 'http';
2
+ import httpProxy from 'http-proxy';
3
+ import bancoz from 'bancoz';
4
+ export class RateLimiter {
5
+ targetPort;
6
+ options;
7
+ server = null;
8
+ proxy = null;
9
+ port = 0;
10
+ isGlobal;
11
+ constructor(targetPort, options) {
12
+ this.targetPort = targetPort;
13
+ this.options = options;
14
+ this.isGlobal = options === true || !options.routes || options.routes.length === 0;
15
+ }
16
+ async start() {
17
+ this.proxy = httpProxy.createProxyServer({
18
+ target: `http://localhost:${this.targetPort}`,
19
+ ws: true
20
+ });
21
+ this.proxy.on('error', (err, req, res) => {
22
+ if (res && res.writeHead) {
23
+ const resp = res;
24
+ if (!resp.headersSent) {
25
+ resp.writeHead(502);
26
+ resp.end('Bad Gateway');
27
+ }
28
+ }
29
+ });
30
+ this.server = http.createServer(async (req, res) => {
31
+ try {
32
+ const url = req.url || '/';
33
+ let shouldApplyLimit = this.isGlobal;
34
+ if (!shouldApplyLimit && typeof this.options === 'object' && this.options.routes) {
35
+ shouldApplyLimit = this.options.routes.some(route => url.startsWith(route));
36
+ }
37
+ if (shouldApplyLimit) {
38
+ const ip = req.headers['cf-connecting-ip'] ||
39
+ req.headers['x-forwarded-for']?.split(',')[0].trim() ||
40
+ req.socket.remoteAddress || 'unknown';
41
+ const maxReqs = typeof this.options === 'object' ? this.options.maxRequestsPerMinute : 100;
42
+ // Lógica de Rate Limit com Bancoz
43
+ const key = ip.replace(/[^a-zA-Z0-9_-]/g, '_'); // Sanitizar chave para o bancoz
44
+ let data = {};
45
+ try {
46
+ data = await bancoz.ler('ratelimit', key);
47
+ }
48
+ catch (err) {
49
+ // Se não existe, ignora e cria
50
+ }
51
+ const now = Date.now();
52
+ if (data && data.blockedUntil && data.blockedUntil > now) {
53
+ res.writeHead(429, { 'Content-Type': 'text/plain' });
54
+ return res.end('Too Many Requests. IP Bloqueado Temporariamente.');
55
+ }
56
+ if (!data || !data.count || !data.windowStart || (now - data.windowStart > 60000)) {
57
+ // Nova janela de tempo
58
+ await bancoz.criar('ratelimit', key, {
59
+ count: 1,
60
+ windowStart: now
61
+ });
62
+ }
63
+ else {
64
+ // Incrementa contador
65
+ const newCount = data.count + 1;
66
+ if (newCount > maxReqs) {
67
+ // Bloquear por 1 minuto
68
+ await bancoz.atualizar('ratelimit', key, {
69
+ blockedUntil: now + 60000
70
+ });
71
+ res.writeHead(429, { 'Content-Type': 'text/plain' });
72
+ return res.end('Too Many Requests. Limite Excedido.');
73
+ }
74
+ else {
75
+ await bancoz.atualizar('ratelimit', key, {
76
+ count: newCount
77
+ });
78
+ }
79
+ }
80
+ }
81
+ // Repassar a requisição
82
+ this.proxy?.web(req, res);
83
+ }
84
+ catch (err) {
85
+ console.error('Erro no proxy interno:', err);
86
+ if (!res.headersSent) {
87
+ res.writeHead(500);
88
+ res.end('Internal Proxy Error');
89
+ }
90
+ }
91
+ });
92
+ this.server.on('upgrade', (req, socket, head) => {
93
+ this.proxy?.ws(req, socket, head);
94
+ });
95
+ return new Promise((resolve, reject) => {
96
+ this.server.listen(0, '127.0.0.1', () => {
97
+ const address = this.server.address();
98
+ this.port = address.port;
99
+ resolve(this.port);
100
+ });
101
+ this.server.on('error', reject);
102
+ });
103
+ }
104
+ stop() {
105
+ if (this.proxy) {
106
+ this.proxy.close();
107
+ this.proxy = null;
108
+ }
109
+ if (this.server) {
110
+ this.server.close();
111
+ this.server = null;
112
+ }
113
+ }
114
+ }
package/dist/Tunnel.d.ts CHANGED
@@ -1,8 +1,12 @@
1
1
  import { EventEmitter } from "events";
2
2
  import { TunnelResult } from "./Provider.js";
3
+ import { RateLimitOptions } from "./RateLimiter.js";
3
4
  export interface TunnelOptions {
4
5
  provider: string;
5
6
  port: number;
7
+ subdomain?: string;
8
+ authtoken?: string;
9
+ rateLimit?: RateLimitOptions | boolean;
6
10
  }
7
11
  export interface TunnelInstance extends TunnelResult, EventEmitter {
8
12
  on(event: "ready", listener: (url: string) => void): this;
package/dist/Tunnel.js CHANGED
@@ -1,4 +1,5 @@
1
1
  import { EventEmitter } from "events";
2
+ import { RateLimiter } from "./RateLimiter.js";
2
3
  export async function createTunnel(options) {
3
4
  if (!options.port || isNaN(options.port)) {
4
5
  throw new Error("Porta inválida.");
@@ -21,11 +22,20 @@ export async function createTunnel(options) {
21
22
  }
22
23
  throw err;
23
24
  }
24
- const providerInstance = new ProviderClass(options.port);
25
+ let rateLimiterInstance = null;
26
+ let targetPort = options.port;
27
+ if (options.rateLimit) {
28
+ rateLimiterInstance = new RateLimiter(options.port, options.rateLimit);
29
+ targetPort = await rateLimiterInstance.start();
30
+ }
31
+ const providerInstance = new ProviderClass({ ...options, port: targetPort });
25
32
  // We wrap the result in an EventEmitter to match the required API
26
33
  const emitter = new EventEmitter();
27
34
  providerInstance.on("ready", (url) => emitter.emit("ready", url));
28
- providerInstance.on("close", () => emitter.emit("close"));
35
+ providerInstance.on("close", () => {
36
+ rateLimiterInstance?.stop();
37
+ emitter.emit("close");
38
+ });
29
39
  providerInstance.on("error", (err) => emitter.emit("error", err));
30
40
  try {
31
41
  const result = await providerInstance.start();
@@ -33,8 +43,11 @@ export async function createTunnel(options) {
33
43
  Object.assign(emitter, {
34
44
  provider: result.provider,
35
45
  url: result.url,
36
- port: result.port,
37
- stop: result.stop,
46
+ port: options.port, // Return original user port
47
+ stop: () => {
48
+ rateLimiterInstance?.stop();
49
+ result.stop();
50
+ },
38
51
  process: result.process,
39
52
  });
40
53
  return emitter;
package/dist/index.d.ts CHANGED
@@ -4,6 +4,7 @@ interface TunnelAPI {
4
4
  (options: TunnelOptions): Promise<TunnelInstance>;
5
5
  cloudflare: (options: OmitProvider<TunnelOptions>) => Promise<TunnelInstance>;
6
6
  localtunnel: (options: OmitProvider<TunnelOptions>) => Promise<TunnelInstance>;
7
+ ngrok: (options: OmitProvider<TunnelOptions>) => Promise<TunnelInstance>;
7
8
  }
8
9
  declare const tunnel: TunnelAPI;
9
10
  export default tunnel;
package/dist/index.js CHANGED
@@ -1,5 +1,6 @@
1
1
  import { createTunnel } from "./Tunnel.js";
2
2
  const tunnel = createTunnel;
3
- tunnel.cloudflare = (options) => createTunnel({ ...options, provider: "cloudflare" });
4
- tunnel.localtunnel = (options) => createTunnel({ ...options, provider: "localtunnel" });
3
+ tunnel.cloudflare = (options) => createTunnel({ ...options, provider: 'cloudflare' });
4
+ tunnel.localtunnel = (options) => createTunnel({ ...options, provider: 'localtunnel' });
5
+ tunnel.ngrok = (options) => createTunnel({ ...options, provider: 'ngrok' });
5
6
  export default tunnel;
@@ -1,8 +1,8 @@
1
- import { Provider, TunnelResult } from "../Provider.js";
1
+ import { Provider, ProviderOptions, TunnelResult } from "../Provider.js";
2
2
  export default class CloudflareProvider extends Provider {
3
3
  private cp;
4
4
  private urlRegex;
5
- constructor(port: number);
5
+ constructor(options: ProviderOptions);
6
6
  start(): Promise<TunnelResult>;
7
7
  stop(): void;
8
8
  }
@@ -3,8 +3,8 @@ import { Provider } from "../Provider.js";
3
3
  export default class CloudflareProvider extends Provider {
4
4
  cp = null;
5
5
  urlRegex = /(https:\/\/[a-zA-Z0-9-]+\.trycloudflare\.com)/;
6
- constructor(port) {
7
- super(port);
6
+ constructor(options) {
7
+ super(options);
8
8
  }
9
9
  start() {
10
10
  return new Promise((resolve, reject) => {
@@ -1,7 +1,7 @@
1
- import { Provider, TunnelResult } from "../Provider.js";
1
+ import { Provider, ProviderOptions, TunnelResult } from "../Provider.js";
2
2
  export default class LocalTunnelProvider extends Provider {
3
3
  private tunnel;
4
- constructor(port: number);
4
+ constructor(options: ProviderOptions);
5
5
  start(): Promise<TunnelResult>;
6
6
  stop(): void;
7
7
  }
@@ -2,13 +2,13 @@ import localtunnel from "localtunnel";
2
2
  import { Provider } from "../Provider.js";
3
3
  export default class LocalTunnelProvider extends Provider {
4
4
  tunnel = null;
5
- constructor(port) {
6
- super(port);
5
+ constructor(options) {
6
+ super(options);
7
7
  }
8
8
  start() {
9
9
  return new Promise(async (resolve, reject) => {
10
10
  try {
11
- this.tunnel = await localtunnel({ port: this.port });
11
+ this.tunnel = await localtunnel({ port: this.port, subdomain: this.options.subdomain });
12
12
  if (!this.tunnel.url) {
13
13
  return reject(new Error("Falha ao obter URL do LocalTunnel."));
14
14
  }
@@ -0,0 +1,8 @@
1
+ import { Provider, ProviderOptions, TunnelResult } from '../Provider.js';
2
+ export default class NgrokProvider extends Provider {
3
+ private url;
4
+ private listener;
5
+ constructor(options: ProviderOptions);
6
+ start(): Promise<TunnelResult>;
7
+ stop(): void;
8
+ }
@@ -0,0 +1,44 @@
1
+ import ngrok from '@ngrok/ngrok';
2
+ import { Provider } from '../Provider.js';
3
+ export default class NgrokProvider extends Provider {
4
+ url = null;
5
+ listener = null;
6
+ constructor(options) {
7
+ super(options);
8
+ }
9
+ start() {
10
+ return new Promise(async (resolve, reject) => {
11
+ try {
12
+ if (this.options.authtoken) {
13
+ ngrok.authtoken(this.options.authtoken);
14
+ }
15
+ this.listener = await ngrok.forward({ addr: this.port, authtoken: this.options.authtoken, domain: this.options.subdomain });
16
+ this.url = this.listener.url() || null;
17
+ if (!this.url) {
18
+ return reject(new Error('Falha ao obter URL do Ngrok.'));
19
+ }
20
+ this.emit('ready', this.url);
21
+ resolve({
22
+ provider: 'ngrok',
23
+ url: this.url,
24
+ port: this.port,
25
+ stop: this.stop.bind(this),
26
+ process: this.listener,
27
+ });
28
+ }
29
+ catch (err) {
30
+ reject(new Error(`Falha ao iniciar o túnel Ngrok: ${err.message}`));
31
+ }
32
+ });
33
+ }
34
+ stop() {
35
+ if (this.listener) {
36
+ this.listener.close().then(() => {
37
+ this.emit('close');
38
+ }).catch((err) => {
39
+ this.emit('error', err);
40
+ });
41
+ this.listener = null;
42
+ }
43
+ }
44
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "cm-tunnel",
3
- "version": "1.0.0",
3
+ "version": "1.2.0",
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",
@@ -49,9 +49,13 @@
49
49
  "LICENSE"
50
50
  ],
51
51
  "dependencies": {
52
+ "@ngrok/ngrok": "^1.7.0",
53
+ "bancoz": "^2.2.8",
54
+ "http-proxy": "^1.18.1",
52
55
  "localtunnel": "^2.0.2"
53
56
  },
54
57
  "devDependencies": {
58
+ "@types/http-proxy": "^1.17.17",
55
59
  "@types/localtunnel": "^2.0.4",
56
60
  "@types/node": "^20.12.7",
57
61
  "eslint": "^9.1.1",