cm-tunnel 1.3.3 → 1.7.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 +775 -106
- package/dist/StaticServer.d.ts +51 -0
- package/dist/StaticServer.js +480 -41
- package/dist/Tunnel.d.ts +2 -0
- package/dist/Tunnel.js +10 -3
- package/dist/cli-utils.d.ts +148 -0
- package/dist/cli-utils.js +400 -0
- package/dist/cli.d.ts +2 -0
- package/dist/cli.js +423 -0
- 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 +13 -7
package/dist/StaticServer.d.ts
CHANGED
|
@@ -1,19 +1,70 @@
|
|
|
1
|
+
export type ApiMode = 'handlers' | 'server';
|
|
1
2
|
export interface ServeOptions {
|
|
3
|
+
/** HTML fixo servido em qualquer rota não-API */
|
|
2
4
|
html?: string;
|
|
5
|
+
/** Pasta de arquivos estáticos (compatibilidade) */
|
|
3
6
|
directory?: string;
|
|
7
|
+
/** Pasta de arquivos estáticos (estilo Vercel). Tem prioridade sobre `directory` */
|
|
8
|
+
public?: string;
|
|
9
|
+
/**
|
|
10
|
+
* Pasta com handlers de API. Os arquivos dessa pasta nunca são servidos
|
|
11
|
+
* como estáticos; cada arquivo vira uma rota (`api/hello.js` → `/api/hello`).
|
|
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;
|
|
26
|
+
/** Prefixo das rotas de API (padrão: `/api`) */
|
|
27
|
+
apiPrefix?: string;
|
|
4
28
|
port?: number;
|
|
29
|
+
/** Recebe logs do servidor de API quando apiMode = "server" */
|
|
30
|
+
onLog?: (line: string) => void;
|
|
5
31
|
}
|
|
6
32
|
export declare class StaticServer {
|
|
7
33
|
private options;
|
|
8
34
|
private server;
|
|
35
|
+
private staticRoot;
|
|
36
|
+
private apiRoot;
|
|
37
|
+
private staticRealRoot;
|
|
38
|
+
private apiRealRoot;
|
|
39
|
+
private apiPrefix;
|
|
40
|
+
private apiMode;
|
|
41
|
+
private apiEntry;
|
|
42
|
+
private stripApiPrefix;
|
|
43
|
+
private apiProcess;
|
|
44
|
+
private apiProxy;
|
|
45
|
+
private apiPort;
|
|
46
|
+
private stopping;
|
|
47
|
+
private moduleCache;
|
|
9
48
|
port: number;
|
|
10
49
|
url: string;
|
|
11
50
|
constructor(options: ServeOptions);
|
|
51
|
+
private prepareRoots;
|
|
52
|
+
private startApiServer;
|
|
53
|
+
private stopApiServer;
|
|
54
|
+
private rewriteApiUrl;
|
|
55
|
+
private handleApiServer;
|
|
12
56
|
start(): Promise<{
|
|
13
57
|
port: number;
|
|
14
58
|
url: string;
|
|
15
59
|
stop: () => void;
|
|
16
60
|
}>;
|
|
61
|
+
private handle;
|
|
62
|
+
private handleApi;
|
|
63
|
+
private findApiFile;
|
|
64
|
+
private loadHandler;
|
|
65
|
+
private handleStatic;
|
|
66
|
+
private sendHtml;
|
|
67
|
+
private sendJson;
|
|
17
68
|
stop(): void;
|
|
18
69
|
}
|
|
19
70
|
export declare function serve(options: ServeOptions): Promise<{
|
package/dist/StaticServer.js
CHANGED
|
@@ -1,65 +1,272 @@
|
|
|
1
1
|
import http from 'http';
|
|
2
2
|
import fs from 'fs';
|
|
3
3
|
import path from 'path';
|
|
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';
|
|
8
|
+
const API_EXTENSIONS = ['.js', '.mjs', '.cjs'];
|
|
4
9
|
const MIME_TYPES = {
|
|
5
|
-
'.html': 'text/html',
|
|
6
|
-
'.css': 'text/css',
|
|
7
|
-
'.js': 'text/javascript',
|
|
8
|
-
'.
|
|
10
|
+
'.html': 'text/html; charset=utf-8',
|
|
11
|
+
'.css': 'text/css; charset=utf-8',
|
|
12
|
+
'.js': 'text/javascript; charset=utf-8',
|
|
13
|
+
'.mjs': 'text/javascript; charset=utf-8',
|
|
14
|
+
'.json': 'application/json; charset=utf-8',
|
|
15
|
+
'.xml': 'application/xml; charset=utf-8',
|
|
16
|
+
'.txt': 'text/plain; charset=utf-8',
|
|
17
|
+
'.csv': 'text/csv; charset=utf-8',
|
|
18
|
+
'.svg': 'image/svg+xml',
|
|
9
19
|
'.png': 'image/png',
|
|
10
20
|
'.jpg': 'image/jpeg',
|
|
11
21
|
'.jpeg': 'image/jpeg',
|
|
12
22
|
'.gif': 'image/gif',
|
|
13
|
-
'.
|
|
14
|
-
'.
|
|
23
|
+
'.webp': 'image/webp',
|
|
24
|
+
'.avif': 'image/avif',
|
|
15
25
|
'.ico': 'image/x-icon',
|
|
26
|
+
'.woff': 'font/woff',
|
|
27
|
+
'.woff2': 'font/woff2',
|
|
28
|
+
'.ttf': 'font/ttf',
|
|
29
|
+
'.otf': 'font/otf',
|
|
30
|
+
'.pdf': 'application/pdf',
|
|
31
|
+
'.wasm': 'application/wasm',
|
|
32
|
+
'.mp4': 'video/mp4',
|
|
33
|
+
'.webm': 'video/webm',
|
|
34
|
+
'.mp3': 'audio/mpeg',
|
|
16
35
|
};
|
|
36
|
+
/** Garante que `target` está dentro de `root` (sem escapar por `..`). */
|
|
37
|
+
function isInside(root, target) {
|
|
38
|
+
const rel = path.relative(root, target);
|
|
39
|
+
return rel === '' || (!rel.startsWith('..') && !path.isAbsolute(rel));
|
|
40
|
+
}
|
|
41
|
+
/** Decodifica e normaliza o pathname; retorna null se for inválido. */
|
|
42
|
+
function parsePathname(rawUrl) {
|
|
43
|
+
let pathname;
|
|
44
|
+
try {
|
|
45
|
+
pathname = decodeURIComponent(new URL(rawUrl, 'http://localhost').pathname);
|
|
46
|
+
}
|
|
47
|
+
catch {
|
|
48
|
+
return null;
|
|
49
|
+
}
|
|
50
|
+
if (pathname.includes('\0'))
|
|
51
|
+
return null;
|
|
52
|
+
return path.posix.normalize(pathname);
|
|
53
|
+
}
|
|
54
|
+
function hasDotSegment(relativePath) {
|
|
55
|
+
return relativePath
|
|
56
|
+
.split(/[\\/]+/)
|
|
57
|
+
.some((segment) => segment.startsWith('.'));
|
|
58
|
+
}
|
|
59
|
+
function decorateResponse(res) {
|
|
60
|
+
const decorated = res;
|
|
61
|
+
decorated.status = (code) => {
|
|
62
|
+
res.statusCode = code;
|
|
63
|
+
return decorated;
|
|
64
|
+
};
|
|
65
|
+
decorated.json = (body) => {
|
|
66
|
+
if (!res.headersSent) {
|
|
67
|
+
res.setHeader('Content-Type', 'application/json; charset=utf-8');
|
|
68
|
+
}
|
|
69
|
+
res.end(JSON.stringify(body));
|
|
70
|
+
return decorated;
|
|
71
|
+
};
|
|
72
|
+
decorated.send = (body) => {
|
|
73
|
+
if (body !== null && typeof body === 'object') {
|
|
74
|
+
return decorated.json(body);
|
|
75
|
+
}
|
|
76
|
+
res.end(String(body));
|
|
77
|
+
return decorated;
|
|
78
|
+
};
|
|
79
|
+
return decorated;
|
|
80
|
+
}
|
|
17
81
|
export class StaticServer {
|
|
18
82
|
options;
|
|
19
83
|
server = null;
|
|
84
|
+
staticRoot;
|
|
85
|
+
apiRoot;
|
|
86
|
+
staticRealRoot = null;
|
|
87
|
+
apiRealRoot = null;
|
|
88
|
+
apiPrefix;
|
|
89
|
+
apiMode;
|
|
90
|
+
apiEntry = null;
|
|
91
|
+
stripApiPrefix;
|
|
92
|
+
apiProcess = null;
|
|
93
|
+
apiProxy = null;
|
|
94
|
+
apiPort = null;
|
|
95
|
+
stopping = false;
|
|
96
|
+
moduleCache = new Map();
|
|
20
97
|
port = 0;
|
|
21
98
|
url = '';
|
|
22
99
|
constructor(options) {
|
|
23
100
|
this.options = options;
|
|
101
|
+
const publicDir = options.public ?? options.directory;
|
|
102
|
+
this.staticRoot = publicDir ? path.resolve(publicDir) : null;
|
|
103
|
+
this.apiRoot = options.api ? path.resolve(options.api) : null;
|
|
104
|
+
let prefix = options.apiPrefix || '/api';
|
|
105
|
+
if (!prefix.startsWith('/'))
|
|
106
|
+
prefix = `/${prefix}`;
|
|
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
|
+
}
|
|
117
|
+
}
|
|
118
|
+
prepareRoots() {
|
|
119
|
+
if (this.staticRoot) {
|
|
120
|
+
if (!fs.existsSync(this.staticRoot) || !fs.statSync(this.staticRoot).isDirectory()) {
|
|
121
|
+
throw new Error(`Pasta pública não encontrada: "${this.staticRoot}".`);
|
|
122
|
+
}
|
|
123
|
+
this.staticRealRoot = fs.realpathSync(this.staticRoot);
|
|
124
|
+
}
|
|
125
|
+
if (this.apiRoot) {
|
|
126
|
+
if (!fs.existsSync(this.apiRoot) || !fs.statSync(this.apiRoot).isDirectory()) {
|
|
127
|
+
throw new Error(`Pasta de API não encontrada: "${this.apiRoot}".`);
|
|
128
|
+
}
|
|
129
|
+
this.apiRealRoot = fs.realpathSync(this.apiRoot);
|
|
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
|
+
}
|
|
24
139
|
}
|
|
25
|
-
|
|
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}` : ''));
|
|
184
|
+
}
|
|
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;
|
|
200
|
+
return;
|
|
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
|
+
}
|
|
26
250
|
return new Promise((resolve, reject) => {
|
|
27
251
|
this.server = http.createServer((req, res) => {
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
res.
|
|
31
|
-
|
|
32
|
-
}
|
|
33
|
-
if (this.options.directory) {
|
|
34
|
-
let filePath = path.join(this.options.directory, req.url === '/' ? 'index.html' : (req.url || ''));
|
|
35
|
-
// Basic security check to prevent directory traversal
|
|
36
|
-
if (!filePath.startsWith(path.resolve(this.options.directory))) {
|
|
37
|
-
res.writeHead(403);
|
|
38
|
-
return res.end('Forbidden');
|
|
252
|
+
this.handle(req, res).catch((err) => {
|
|
253
|
+
console.error('[cm-tunnel] Erro ao processar requisição:', err);
|
|
254
|
+
if (!res.headersSent) {
|
|
255
|
+
res.writeHead(500, { 'Content-Type': 'application/json; charset=utf-8' });
|
|
39
256
|
}
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
res.writeHead(500);
|
|
53
|
-
return res.end('Internal Server Error');
|
|
54
|
-
}
|
|
55
|
-
res.writeHead(200, { 'Content-Type': contentType });
|
|
56
|
-
res.end(content);
|
|
57
|
-
});
|
|
58
|
-
});
|
|
59
|
-
return;
|
|
257
|
+
res.end(JSON.stringify({ error: 'Internal Server Error' }));
|
|
258
|
+
});
|
|
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();
|
|
60
269
|
}
|
|
61
|
-
res.writeHead(400);
|
|
62
|
-
res.end('No serve options provided (html or directory).');
|
|
63
270
|
});
|
|
64
271
|
this.server.on('error', reject);
|
|
65
272
|
const targetPort = this.options.port || 0;
|
|
@@ -71,7 +278,7 @@ export class StaticServer {
|
|
|
71
278
|
resolve({
|
|
72
279
|
port: this.port,
|
|
73
280
|
url: this.url,
|
|
74
|
-
stop: this.stop.bind(this)
|
|
281
|
+
stop: this.stop.bind(this),
|
|
75
282
|
});
|
|
76
283
|
}
|
|
77
284
|
else {
|
|
@@ -80,7 +287,239 @@ export class StaticServer {
|
|
|
80
287
|
});
|
|
81
288
|
});
|
|
82
289
|
}
|
|
290
|
+
async handle(req, res) {
|
|
291
|
+
const pathname = parsePathname(req.url || '/');
|
|
292
|
+
if (pathname === null) {
|
|
293
|
+
this.sendJson(res, 400, { error: 'Bad Request' });
|
|
294
|
+
return;
|
|
295
|
+
}
|
|
296
|
+
if (pathname === this.apiPrefix || pathname.startsWith(`${this.apiPrefix}/`)) {
|
|
297
|
+
if (this.apiMode === 'server') {
|
|
298
|
+
this.handleApiServer(req, res);
|
|
299
|
+
}
|
|
300
|
+
else if (this.apiRoot) {
|
|
301
|
+
await this.handleApi(req, res, pathname);
|
|
302
|
+
}
|
|
303
|
+
else {
|
|
304
|
+
// /api é reservado: nunca cai no estático, mesmo sem pasta de API configurada.
|
|
305
|
+
this.sendJson(res, 404, { error: 'Not found' });
|
|
306
|
+
}
|
|
307
|
+
return;
|
|
308
|
+
}
|
|
309
|
+
await this.handleStatic(req, res, pathname);
|
|
310
|
+
}
|
|
311
|
+
async handleApi(req, res, pathname) {
|
|
312
|
+
const method = (req.method || 'GET').toUpperCase();
|
|
313
|
+
const relative = pathname
|
|
314
|
+
.slice(this.apiPrefix.length)
|
|
315
|
+
.replace(/^\/+|\/+$/g, '');
|
|
316
|
+
const file = await this.findApiFile(relative);
|
|
317
|
+
if (!file) {
|
|
318
|
+
this.sendJson(res, 404, { error: 'Not found' });
|
|
319
|
+
return;
|
|
320
|
+
}
|
|
321
|
+
let lookup;
|
|
322
|
+
try {
|
|
323
|
+
lookup = await this.loadHandler(file, method);
|
|
324
|
+
}
|
|
325
|
+
catch (err) {
|
|
326
|
+
console.error(`[cm-tunnel] Falha ao carregar handler "${file}":`, err);
|
|
327
|
+
this.sendJson(res, 500, { error: 'Invalid API handler' });
|
|
328
|
+
return;
|
|
329
|
+
}
|
|
330
|
+
if (!lookup.handler) {
|
|
331
|
+
if (lookup.methodNotAllowed) {
|
|
332
|
+
res.writeHead(405, { Allow: 'GET, POST, PUT, PATCH, DELETE, OPTIONS' });
|
|
333
|
+
res.end(JSON.stringify({ error: 'Method not allowed' }));
|
|
334
|
+
}
|
|
335
|
+
else {
|
|
336
|
+
this.sendJson(res, 500, {
|
|
337
|
+
error: `Handler de API inválido em "${path.relative(this.apiRoot, file)}". ` +
|
|
338
|
+
'Exporte uma função default (req, res) ou funções por método (GET, POST...).',
|
|
339
|
+
});
|
|
340
|
+
}
|
|
341
|
+
return;
|
|
342
|
+
}
|
|
343
|
+
const handler = lookup.handler;
|
|
344
|
+
const decorated = decorateResponse(res);
|
|
345
|
+
try {
|
|
346
|
+
const result = await handler(req, decorated);
|
|
347
|
+
if (!res.writableEnded) {
|
|
348
|
+
if (result !== undefined) {
|
|
349
|
+
if (typeof result === 'string') {
|
|
350
|
+
res.end(result);
|
|
351
|
+
}
|
|
352
|
+
else {
|
|
353
|
+
decorated.json(result);
|
|
354
|
+
}
|
|
355
|
+
}
|
|
356
|
+
else {
|
|
357
|
+
res.end();
|
|
358
|
+
}
|
|
359
|
+
}
|
|
360
|
+
}
|
|
361
|
+
catch (err) {
|
|
362
|
+
console.error(`[cm-tunnel] Erro no handler de API "${file}":`, err);
|
|
363
|
+
if (!res.headersSent) {
|
|
364
|
+
decorated.status(500).json({ error: 'Internal Server Error' });
|
|
365
|
+
}
|
|
366
|
+
else {
|
|
367
|
+
res.end();
|
|
368
|
+
}
|
|
369
|
+
}
|
|
370
|
+
}
|
|
371
|
+
async findApiFile(relative) {
|
|
372
|
+
const candidates = relative ? [relative, path.join(relative, 'index')] : ['index'];
|
|
373
|
+
for (const candidate of candidates) {
|
|
374
|
+
for (const extension of API_EXTENSIONS) {
|
|
375
|
+
const file = path.resolve(this.apiRoot, `${candidate}${extension}`);
|
|
376
|
+
if (!isInside(this.apiRoot, file))
|
|
377
|
+
continue;
|
|
378
|
+
try {
|
|
379
|
+
const stat = await fs.promises.stat(file);
|
|
380
|
+
if (!stat.isFile())
|
|
381
|
+
continue;
|
|
382
|
+
// Resolve symlinks e garante que o arquivo real continua dentro da pasta de API.
|
|
383
|
+
const real = await fs.promises.realpath(file);
|
|
384
|
+
if (!isInside(this.apiRealRoot, real))
|
|
385
|
+
continue;
|
|
386
|
+
return file;
|
|
387
|
+
}
|
|
388
|
+
catch {
|
|
389
|
+
// Arquivo não existe, tenta o próximo candidato.
|
|
390
|
+
}
|
|
391
|
+
}
|
|
392
|
+
}
|
|
393
|
+
return null;
|
|
394
|
+
}
|
|
395
|
+
async loadHandler(file, method) {
|
|
396
|
+
const stat = await fs.promises.stat(file);
|
|
397
|
+
let entry = this.moduleCache.get(file);
|
|
398
|
+
if (!entry || entry.mtimeMs !== stat.mtimeMs) {
|
|
399
|
+
// O query param com mtime invalida o cache do ESM quando o arquivo muda,
|
|
400
|
+
// permitindo editar handlers sem reiniciar o processo.
|
|
401
|
+
const href = `${pathToFileURL(file).href}?v=${stat.mtimeMs}`;
|
|
402
|
+
// @vite-ignore mantém o import em runtime (funciona no Node e no Vitest).
|
|
403
|
+
const module = await import(/* @vite-ignore */ href);
|
|
404
|
+
entry = { mtimeMs: stat.mtimeMs, module };
|
|
405
|
+
this.moduleCache.set(file, entry);
|
|
406
|
+
}
|
|
407
|
+
const mod = entry.module;
|
|
408
|
+
// Export por método: export const GET = ..., export const POST = ...
|
|
409
|
+
const byMethod = mod[method] ?? mod[method.toLowerCase()] ?? mod.all;
|
|
410
|
+
if (typeof byMethod === 'function') {
|
|
411
|
+
return { handler: byMethod, methodNotAllowed: false };
|
|
412
|
+
}
|
|
413
|
+
// Export default: export default function handler(req, res) {}
|
|
414
|
+
const fallback = mod.default ?? mod;
|
|
415
|
+
if (typeof fallback === 'function') {
|
|
416
|
+
return { handler: fallback, methodNotAllowed: false };
|
|
417
|
+
}
|
|
418
|
+
if (fallback && typeof fallback === 'object') {
|
|
419
|
+
const fn = fallback[method] ?? fallback[method.toLowerCase()] ?? fallback.all;
|
|
420
|
+
if (typeof fn === 'function') {
|
|
421
|
+
return { handler: fn, methodNotAllowed: false };
|
|
422
|
+
}
|
|
423
|
+
}
|
|
424
|
+
const methodNames = ['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'HEAD', 'OPTIONS', 'ALL'];
|
|
425
|
+
const hasAnyHandler = methodNames.some((name) => {
|
|
426
|
+
const lower = name.toLowerCase();
|
|
427
|
+
return (typeof mod[name] === 'function' ||
|
|
428
|
+
typeof mod[lower] === 'function' ||
|
|
429
|
+
(fallback &&
|
|
430
|
+
typeof fallback === 'object' &&
|
|
431
|
+
(typeof fallback[name] === 'function' || typeof fallback[lower] === 'function')));
|
|
432
|
+
});
|
|
433
|
+
return { handler: null, methodNotAllowed: hasAnyHandler };
|
|
434
|
+
}
|
|
435
|
+
async handleStatic(req, res, pathname) {
|
|
436
|
+
const method = (req.method || 'GET').toUpperCase();
|
|
437
|
+
if (this.options.html) {
|
|
438
|
+
if (method !== 'GET' && method !== 'HEAD') {
|
|
439
|
+
res.writeHead(405, { Allow: 'GET, HEAD' });
|
|
440
|
+
res.end();
|
|
441
|
+
return;
|
|
442
|
+
}
|
|
443
|
+
this.sendHtml(res, this.options.html, method === 'HEAD');
|
|
444
|
+
return;
|
|
445
|
+
}
|
|
446
|
+
if (!this.staticRoot) {
|
|
447
|
+
this.sendJson(res, 404, { error: 'Not found' });
|
|
448
|
+
return;
|
|
449
|
+
}
|
|
450
|
+
if (method !== 'GET' && method !== 'HEAD') {
|
|
451
|
+
res.writeHead(405, { Allow: 'GET, HEAD' });
|
|
452
|
+
res.end();
|
|
453
|
+
return;
|
|
454
|
+
}
|
|
455
|
+
let relative = pathname.replace(/^\/+/, '');
|
|
456
|
+
if (!relative || relative.endsWith('/')) {
|
|
457
|
+
relative += 'index.html';
|
|
458
|
+
}
|
|
459
|
+
if (hasDotSegment(relative)) {
|
|
460
|
+
this.sendJson(res, 404, { error: 'Not found' });
|
|
461
|
+
return;
|
|
462
|
+
}
|
|
463
|
+
let file = path.resolve(this.staticRoot, relative);
|
|
464
|
+
if (!isInside(this.staticRoot, file)) {
|
|
465
|
+
this.sendJson(res, 403, { error: 'Forbidden' });
|
|
466
|
+
return;
|
|
467
|
+
}
|
|
468
|
+
try {
|
|
469
|
+
let stat = await fs.promises.stat(file);
|
|
470
|
+
if (stat.isDirectory()) {
|
|
471
|
+
file = path.join(file, 'index.html');
|
|
472
|
+
stat = await fs.promises.stat(file);
|
|
473
|
+
}
|
|
474
|
+
if (!stat.isFile()) {
|
|
475
|
+
this.sendJson(res, 404, { error: 'Not found' });
|
|
476
|
+
return;
|
|
477
|
+
}
|
|
478
|
+
// Proteção extra: nunca servir nada que esteja dentro da pasta de API,
|
|
479
|
+
// mesmo via symlink ou configuração equivocada (ex: public: '.').
|
|
480
|
+
const real = await fs.promises.realpath(file);
|
|
481
|
+
if (this.apiRealRoot && isInside(this.apiRealRoot, real)) {
|
|
482
|
+
this.sendJson(res, 404, { error: 'Not found' });
|
|
483
|
+
return;
|
|
484
|
+
}
|
|
485
|
+
if (this.staticRealRoot && !isInside(this.staticRealRoot, real)) {
|
|
486
|
+
this.sendJson(res, 403, { error: 'Forbidden' });
|
|
487
|
+
return;
|
|
488
|
+
}
|
|
489
|
+
const contentType = MIME_TYPES[path.extname(file).toLowerCase()] || 'application/octet-stream';
|
|
490
|
+
res.writeHead(200, {
|
|
491
|
+
'Content-Type': contentType,
|
|
492
|
+
'Content-Length': stat.size,
|
|
493
|
+
});
|
|
494
|
+
if (method === 'HEAD') {
|
|
495
|
+
res.end();
|
|
496
|
+
return;
|
|
497
|
+
}
|
|
498
|
+
const stream = fs.createReadStream(file);
|
|
499
|
+
stream.on('error', () => {
|
|
500
|
+
if (!res.writableEnded)
|
|
501
|
+
res.end();
|
|
502
|
+
});
|
|
503
|
+
stream.pipe(res);
|
|
504
|
+
}
|
|
505
|
+
catch {
|
|
506
|
+
this.sendJson(res, 404, { error: 'Not found' });
|
|
507
|
+
}
|
|
508
|
+
}
|
|
509
|
+
sendHtml(res, html, headOnly) {
|
|
510
|
+
res.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8' });
|
|
511
|
+
res.end(headOnly ? undefined : html);
|
|
512
|
+
}
|
|
513
|
+
sendJson(res, status, body) {
|
|
514
|
+
if (res.headersSent) {
|
|
515
|
+
res.end();
|
|
516
|
+
return;
|
|
517
|
+
}
|
|
518
|
+
res.writeHead(status, { 'Content-Type': 'application/json; charset=utf-8' });
|
|
519
|
+
res.end(JSON.stringify(body));
|
|
520
|
+
}
|
|
83
521
|
stop() {
|
|
522
|
+
this.stopApiServer();
|
|
84
523
|
if (this.server) {
|
|
85
524
|
this.server.close();
|
|
86
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;
|
package/dist/Tunnel.js
CHANGED
|
@@ -49,7 +49,8 @@ function validateCloudflareOptions(options) {
|
|
|
49
49
|
}
|
|
50
50
|
}
|
|
51
51
|
export async function createTunnel(options) {
|
|
52
|
-
|
|
52
|
+
// Com `serve`, a porta é opcional: um servidor interno é iniciado em porta aleatória.
|
|
53
|
+
if (!options.serve && (!options.port || isNaN(options.port))) {
|
|
53
54
|
throw new Error("Porta inválida.");
|
|
54
55
|
}
|
|
55
56
|
if (!options.provider) {
|
|
@@ -72,11 +73,13 @@ export async function createTunnel(options) {
|
|
|
72
73
|
const ProviderClass = (await loadProvider()).default;
|
|
73
74
|
let rateLimiterInstance = null;
|
|
74
75
|
let staticServerInstance = null;
|
|
76
|
+
let servedPort = null;
|
|
75
77
|
// A porta do usuário (ou gerada pelo StaticServer) que o túnel/proxy vai mirar
|
|
76
78
|
let targetPort = options.port || 3000;
|
|
77
79
|
if (options.serve) {
|
|
78
80
|
staticServerInstance = new StaticServer(options.serve);
|
|
79
81
|
const serveResult = await staticServerInstance.start();
|
|
82
|
+
servedPort = serveResult.port;
|
|
80
83
|
targetPort = serveResult.port; // O túnel ou proxy apontará para o StaticServer
|
|
81
84
|
}
|
|
82
85
|
if (options.rateLimit) {
|
|
@@ -87,7 +90,11 @@ export async function createTunnel(options) {
|
|
|
87
90
|
// We wrap the result in an EventEmitter to match the required API
|
|
88
91
|
const emitter = new EventEmitter();
|
|
89
92
|
let started = false;
|
|
90
|
-
providerInstance.on("ready", (url) =>
|
|
93
|
+
providerInstance.on("ready", (url) => {
|
|
94
|
+
// Os providers emitem "ready" antes de start() resolver. Adiamos a
|
|
95
|
+
// reemissão para que listeners registrados depois do await recebam o evento.
|
|
96
|
+
setImmediate(() => emitter.emit("ready", url));
|
|
97
|
+
});
|
|
91
98
|
providerInstance.on("close", () => {
|
|
92
99
|
rateLimiterInstance?.stop();
|
|
93
100
|
staticServerInstance?.stop();
|
|
@@ -107,7 +114,7 @@ export async function createTunnel(options) {
|
|
|
107
114
|
Object.assign(emitter, {
|
|
108
115
|
provider: result.provider,
|
|
109
116
|
url: result.url,
|
|
110
|
-
port: options.port
|
|
117
|
+
port: options.port ?? servedPort ?? targetPort, // Porta original, do servidor interno ou do proxy
|
|
111
118
|
stop: () => {
|
|
112
119
|
rateLimiterInstance?.stop();
|
|
113
120
|
staticServerInstance?.stop();
|