cm-tunnel 1.0.0 → 1.1.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 +8 -2
- package/dist/Provider.d.ts +7 -1
- package/dist/Provider.js +4 -2
- package/dist/RateLimiter.d.ts +15 -0
- package/dist/RateLimiter.js +114 -0
- package/dist/Tunnel.d.ts +3 -0
- package/dist/Tunnel.js +17 -4
- package/dist/providers/cloudflare.d.ts +2 -2
- package/dist/providers/cloudflare.js +2 -2
- package/dist/providers/localtunnel.d.ts +2 -2
- package/dist/providers/localtunnel.js +3 -3
- package/package.json +4 -1
package/README.md
CHANGED
|
@@ -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
|
|
|
@@ -23,7 +24,12 @@ import tunnel from 'cm-tunnel';
|
|
|
23
24
|
try {
|
|
24
25
|
const t = await tunnel({
|
|
25
26
|
provider: 'cloudflare', // ou 'localtunnel'
|
|
26
|
-
port: 3000
|
|
27
|
+
port: 3000,
|
|
28
|
+
subdomain: 'meu-app-unico', // Opcional (apenas para localtunnel)
|
|
29
|
+
rateLimit: { // Opcional: Bloqueia IPs por excesso de requisições
|
|
30
|
+
maxRequestsPerMinute: 60,
|
|
31
|
+
routes: ['/api/'] // Se vazio, aplica globalmente
|
|
32
|
+
}
|
|
27
33
|
});
|
|
28
34
|
|
|
29
35
|
console.log('Túnel público:', t.url);
|
|
@@ -71,4 +77,4 @@ A arquitetura de `cm-tunnel` é modular. Para adicionar um novo provedor:
|
|
|
71
77
|
|
|
72
78
|
## Licença
|
|
73
79
|
|
|
74
|
-
MIT
|
|
80
|
+
MIT
|
package/dist/Provider.d.ts
CHANGED
|
@@ -6,8 +6,14 @@ export interface TunnelResult {
|
|
|
6
6
|
stop: () => void;
|
|
7
7
|
process?: unknown;
|
|
8
8
|
}
|
|
9
|
+
export interface ProviderOptions {
|
|
10
|
+
port: number;
|
|
11
|
+
subdomain?: string;
|
|
12
|
+
[key: string]: any;
|
|
13
|
+
}
|
|
9
14
|
export declare abstract class Provider extends EventEmitter {
|
|
15
|
+
protected options: ProviderOptions;
|
|
10
16
|
protected port: number;
|
|
11
|
-
constructor(
|
|
17
|
+
constructor(options: ProviderOptions);
|
|
12
18
|
abstract start(): Promise<TunnelResult>;
|
|
13
19
|
}
|
package/dist/Provider.js
CHANGED
|
@@ -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,11 @@
|
|
|
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
|
+
rateLimit?: RateLimitOptions | boolean;
|
|
6
9
|
}
|
|
7
10
|
export interface TunnelInstance extends TunnelResult, EventEmitter {
|
|
8
11
|
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
|
-
|
|
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", () =>
|
|
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:
|
|
37
|
-
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;
|
|
@@ -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(
|
|
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(
|
|
7
|
-
super(
|
|
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(
|
|
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(
|
|
6
|
-
super(
|
|
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
|
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "cm-tunnel",
|
|
3
|
-
"version": "1.
|
|
3
|
+
"version": "1.1.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,12 @@
|
|
|
49
49
|
"LICENSE"
|
|
50
50
|
],
|
|
51
51
|
"dependencies": {
|
|
52
|
+
"bancoz": "^2.2.8",
|
|
53
|
+
"http-proxy": "^1.18.1",
|
|
52
54
|
"localtunnel": "^2.0.2"
|
|
53
55
|
},
|
|
54
56
|
"devDependencies": {
|
|
57
|
+
"@types/http-proxy": "^1.17.17",
|
|
55
58
|
"@types/localtunnel": "^2.0.4",
|
|
56
59
|
"@types/node": "^20.12.7",
|
|
57
60
|
"eslint": "^9.1.1",
|