cm-tunnel 1.3.3 → 1.5.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.
@@ -1,19 +1,44 @@
1
1
  export interface ServeOptions {
2
+ /** HTML fixo servido em qualquer rota não-API */
2
3
  html?: string;
4
+ /** Pasta de arquivos estáticos (compatibilidade) */
3
5
  directory?: string;
6
+ /** Pasta de arquivos estáticos (estilo Vercel). Tem prioridade sobre `directory` */
7
+ public?: string;
8
+ /**
9
+ * Pasta com handlers de API. Os arquivos dessa pasta nunca são servidos
10
+ * como estáticos; cada arquivo vira uma rota (`api/hello.js` → `/api/hello`).
11
+ */
12
+ api?: string;
13
+ /** Prefixo das rotas de API (padrão: `/api`) */
14
+ apiPrefix?: string;
4
15
  port?: number;
5
16
  }
6
17
  export declare class StaticServer {
7
18
  private options;
8
19
  private server;
20
+ private staticRoot;
21
+ private apiRoot;
22
+ private staticRealRoot;
23
+ private apiRealRoot;
24
+ private apiPrefix;
25
+ private moduleCache;
9
26
  port: number;
10
27
  url: string;
11
28
  constructor(options: ServeOptions);
29
+ private prepareRoots;
12
30
  start(): Promise<{
13
31
  port: number;
14
32
  url: string;
15
33
  stop: () => void;
16
34
  }>;
35
+ private handle;
36
+ private handleApi;
37
+ private findApiFile;
38
+ private loadHandler;
39
+ private handleStatic;
40
+ private sendHtml;
41
+ private sendJson;
17
42
  stop(): void;
18
43
  }
19
44
  export declare function serve(options: ServeOptions): Promise<{
@@ -1,65 +1,132 @@
1
1
  import http from 'http';
2
2
  import fs from 'fs';
3
3
  import path from 'path';
4
+ import { pathToFileURL } from 'url';
5
+ const API_EXTENSIONS = ['.js', '.mjs', '.cjs'];
4
6
  const MIME_TYPES = {
5
- '.html': 'text/html',
6
- '.css': 'text/css',
7
- '.js': 'text/javascript',
8
- '.json': 'application/json',
7
+ '.html': 'text/html; charset=utf-8',
8
+ '.css': 'text/css; charset=utf-8',
9
+ '.js': 'text/javascript; charset=utf-8',
10
+ '.mjs': 'text/javascript; charset=utf-8',
11
+ '.json': 'application/json; charset=utf-8',
12
+ '.xml': 'application/xml; charset=utf-8',
13
+ '.txt': 'text/plain; charset=utf-8',
14
+ '.csv': 'text/csv; charset=utf-8',
15
+ '.svg': 'image/svg+xml',
9
16
  '.png': 'image/png',
10
17
  '.jpg': 'image/jpeg',
11
18
  '.jpeg': 'image/jpeg',
12
19
  '.gif': 'image/gif',
13
- '.svg': 'image/svg+xml',
14
- '.txt': 'text/plain',
20
+ '.webp': 'image/webp',
21
+ '.avif': 'image/avif',
15
22
  '.ico': 'image/x-icon',
23
+ '.woff': 'font/woff',
24
+ '.woff2': 'font/woff2',
25
+ '.ttf': 'font/ttf',
26
+ '.otf': 'font/otf',
27
+ '.pdf': 'application/pdf',
28
+ '.wasm': 'application/wasm',
29
+ '.mp4': 'video/mp4',
30
+ '.webm': 'video/webm',
31
+ '.mp3': 'audio/mpeg',
16
32
  };
33
+ /** Garante que `target` está dentro de `root` (sem escapar por `..`). */
34
+ function isInside(root, target) {
35
+ const rel = path.relative(root, target);
36
+ return rel === '' || (!rel.startsWith('..') && !path.isAbsolute(rel));
37
+ }
38
+ /** Decodifica e normaliza o pathname; retorna null se for inválido. */
39
+ function parsePathname(rawUrl) {
40
+ let pathname;
41
+ try {
42
+ pathname = decodeURIComponent(new URL(rawUrl, 'http://localhost').pathname);
43
+ }
44
+ catch {
45
+ return null;
46
+ }
47
+ if (pathname.includes('\0'))
48
+ return null;
49
+ return path.posix.normalize(pathname);
50
+ }
51
+ function hasDotSegment(relativePath) {
52
+ return relativePath
53
+ .split(/[\\/]+/)
54
+ .some((segment) => segment.startsWith('.'));
55
+ }
56
+ function decorateResponse(res) {
57
+ const decorated = res;
58
+ decorated.status = (code) => {
59
+ res.statusCode = code;
60
+ return decorated;
61
+ };
62
+ decorated.json = (body) => {
63
+ if (!res.headersSent) {
64
+ res.setHeader('Content-Type', 'application/json; charset=utf-8');
65
+ }
66
+ res.end(JSON.stringify(body));
67
+ return decorated;
68
+ };
69
+ decorated.send = (body) => {
70
+ if (body !== null && typeof body === 'object') {
71
+ return decorated.json(body);
72
+ }
73
+ res.end(String(body));
74
+ return decorated;
75
+ };
76
+ return decorated;
77
+ }
17
78
  export class StaticServer {
18
79
  options;
19
80
  server = null;
81
+ staticRoot;
82
+ apiRoot;
83
+ staticRealRoot = null;
84
+ apiRealRoot = null;
85
+ apiPrefix;
86
+ moduleCache = new Map();
20
87
  port = 0;
21
88
  url = '';
22
89
  constructor(options) {
23
90
  this.options = options;
91
+ const publicDir = options.public ?? options.directory;
92
+ this.staticRoot = publicDir ? path.resolve(publicDir) : null;
93
+ this.apiRoot = options.api ? path.resolve(options.api) : null;
94
+ let prefix = options.apiPrefix || '/api';
95
+ if (!prefix.startsWith('/'))
96
+ prefix = `/${prefix}`;
97
+ this.apiPrefix = prefix.replace(/\/+$/, '') || '/api';
98
+ }
99
+ prepareRoots() {
100
+ if (this.staticRoot) {
101
+ if (!fs.existsSync(this.staticRoot) || !fs.statSync(this.staticRoot).isDirectory()) {
102
+ throw new Error(`Pasta pública não encontrada: "${this.staticRoot}".`);
103
+ }
104
+ this.staticRealRoot = fs.realpathSync(this.staticRoot);
105
+ }
106
+ if (this.apiRoot) {
107
+ if (!fs.existsSync(this.apiRoot) || !fs.statSync(this.apiRoot).isDirectory()) {
108
+ throw new Error(`Pasta de API não encontrada: "${this.apiRoot}".`);
109
+ }
110
+ this.apiRealRoot = fs.realpathSync(this.apiRoot);
111
+ }
24
112
  }
25
113
  start() {
26
114
  return new Promise((resolve, reject) => {
115
+ try {
116
+ this.prepareRoots();
117
+ }
118
+ catch (err) {
119
+ reject(err);
120
+ return;
121
+ }
27
122
  this.server = http.createServer((req, res) => {
28
- if (this.options.html) {
29
- res.writeHead(200, { 'Content-Type': 'text/html' });
30
- res.end(this.options.html);
31
- return;
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');
123
+ this.handle(req, res).catch((err) => {
124
+ console.error('[cm-tunnel] Erro ao processar requisição:', err);
125
+ if (!res.headersSent) {
126
+ res.writeHead(500, { 'Content-Type': 'application/json; charset=utf-8' });
39
127
  }
40
- fs.stat(filePath, (err, stats) => {
41
- if (err) {
42
- res.writeHead(404);
43
- return res.end('Not Found');
44
- }
45
- if (stats.isDirectory()) {
46
- filePath = path.join(filePath, 'index.html');
47
- }
48
- const ext = path.extname(filePath).toLowerCase();
49
- const contentType = MIME_TYPES[ext] || 'application/octet-stream';
50
- fs.readFile(filePath, (err, content) => {
51
- if (err) {
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;
60
- }
61
- res.writeHead(400);
62
- res.end('No serve options provided (html or directory).');
128
+ res.end(JSON.stringify({ error: 'Internal Server Error' }));
129
+ });
63
130
  });
64
131
  this.server.on('error', reject);
65
132
  const targetPort = this.options.port || 0;
@@ -71,7 +138,7 @@ export class StaticServer {
71
138
  resolve({
72
139
  port: this.port,
73
140
  url: this.url,
74
- stop: this.stop.bind(this)
141
+ stop: this.stop.bind(this),
75
142
  });
76
143
  }
77
144
  else {
@@ -80,6 +147,234 @@ export class StaticServer {
80
147
  });
81
148
  });
82
149
  }
150
+ async handle(req, res) {
151
+ const pathname = parsePathname(req.url || '/');
152
+ if (pathname === null) {
153
+ this.sendJson(res, 400, { error: 'Bad Request' });
154
+ return;
155
+ }
156
+ if (pathname === this.apiPrefix || pathname.startsWith(`${this.apiPrefix}/`)) {
157
+ if (this.apiRoot) {
158
+ await this.handleApi(req, res, pathname);
159
+ }
160
+ else {
161
+ // /api é reservado: nunca cai no estático, mesmo sem pasta de API configurada.
162
+ this.sendJson(res, 404, { error: 'Not found' });
163
+ }
164
+ return;
165
+ }
166
+ await this.handleStatic(req, res, pathname);
167
+ }
168
+ async handleApi(req, res, pathname) {
169
+ const method = (req.method || 'GET').toUpperCase();
170
+ const relative = pathname
171
+ .slice(this.apiPrefix.length)
172
+ .replace(/^\/+|\/+$/g, '');
173
+ const file = await this.findApiFile(relative);
174
+ if (!file) {
175
+ this.sendJson(res, 404, { error: 'Not found' });
176
+ return;
177
+ }
178
+ let lookup;
179
+ try {
180
+ lookup = await this.loadHandler(file, method);
181
+ }
182
+ catch (err) {
183
+ console.error(`[cm-tunnel] Falha ao carregar handler "${file}":`, err);
184
+ this.sendJson(res, 500, { error: 'Invalid API handler' });
185
+ return;
186
+ }
187
+ if (!lookup.handler) {
188
+ if (lookup.methodNotAllowed) {
189
+ res.writeHead(405, { Allow: 'GET, POST, PUT, PATCH, DELETE, OPTIONS' });
190
+ res.end(JSON.stringify({ error: 'Method not allowed' }));
191
+ }
192
+ else {
193
+ this.sendJson(res, 500, {
194
+ error: `Handler de API inválido em "${path.relative(this.apiRoot, file)}". ` +
195
+ 'Exporte uma função default (req, res) ou funções por método (GET, POST...).',
196
+ });
197
+ }
198
+ return;
199
+ }
200
+ const handler = lookup.handler;
201
+ const decorated = decorateResponse(res);
202
+ try {
203
+ const result = await handler(req, decorated);
204
+ if (!res.writableEnded) {
205
+ if (result !== undefined) {
206
+ if (typeof result === 'string') {
207
+ res.end(result);
208
+ }
209
+ else {
210
+ decorated.json(result);
211
+ }
212
+ }
213
+ else {
214
+ res.end();
215
+ }
216
+ }
217
+ }
218
+ catch (err) {
219
+ console.error(`[cm-tunnel] Erro no handler de API "${file}":`, err);
220
+ if (!res.headersSent) {
221
+ decorated.status(500).json({ error: 'Internal Server Error' });
222
+ }
223
+ else {
224
+ res.end();
225
+ }
226
+ }
227
+ }
228
+ async findApiFile(relative) {
229
+ const candidates = relative ? [relative, path.join(relative, 'index')] : ['index'];
230
+ for (const candidate of candidates) {
231
+ for (const extension of API_EXTENSIONS) {
232
+ const file = path.resolve(this.apiRoot, `${candidate}${extension}`);
233
+ if (!isInside(this.apiRoot, file))
234
+ continue;
235
+ try {
236
+ const stat = await fs.promises.stat(file);
237
+ if (!stat.isFile())
238
+ continue;
239
+ // Resolve symlinks e garante que o arquivo real continua dentro da pasta de API.
240
+ const real = await fs.promises.realpath(file);
241
+ if (!isInside(this.apiRealRoot, real))
242
+ continue;
243
+ return file;
244
+ }
245
+ catch {
246
+ // Arquivo não existe, tenta o próximo candidato.
247
+ }
248
+ }
249
+ }
250
+ return null;
251
+ }
252
+ async loadHandler(file, method) {
253
+ const stat = await fs.promises.stat(file);
254
+ let entry = this.moduleCache.get(file);
255
+ if (!entry || entry.mtimeMs !== stat.mtimeMs) {
256
+ // O query param com mtime invalida o cache do ESM quando o arquivo muda,
257
+ // permitindo editar handlers sem reiniciar o processo.
258
+ const href = `${pathToFileURL(file).href}?v=${stat.mtimeMs}`;
259
+ // @vite-ignore mantém o import em runtime (funciona no Node e no Vitest).
260
+ const module = await import(/* @vite-ignore */ href);
261
+ entry = { mtimeMs: stat.mtimeMs, module };
262
+ this.moduleCache.set(file, entry);
263
+ }
264
+ const mod = entry.module;
265
+ // Export por método: export const GET = ..., export const POST = ...
266
+ const byMethod = mod[method] ?? mod[method.toLowerCase()] ?? mod.all;
267
+ if (typeof byMethod === 'function') {
268
+ return { handler: byMethod, methodNotAllowed: false };
269
+ }
270
+ // Export default: export default function handler(req, res) {}
271
+ const fallback = mod.default ?? mod;
272
+ if (typeof fallback === 'function') {
273
+ return { handler: fallback, methodNotAllowed: false };
274
+ }
275
+ if (fallback && typeof fallback === 'object') {
276
+ const fn = fallback[method] ?? fallback[method.toLowerCase()] ?? fallback.all;
277
+ if (typeof fn === 'function') {
278
+ return { handler: fn, methodNotAllowed: false };
279
+ }
280
+ }
281
+ const methodNames = ['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'HEAD', 'OPTIONS', 'ALL'];
282
+ const hasAnyHandler = methodNames.some((name) => {
283
+ const lower = name.toLowerCase();
284
+ return (typeof mod[name] === 'function' ||
285
+ typeof mod[lower] === 'function' ||
286
+ (fallback &&
287
+ typeof fallback === 'object' &&
288
+ (typeof fallback[name] === 'function' || typeof fallback[lower] === 'function')));
289
+ });
290
+ return { handler: null, methodNotAllowed: hasAnyHandler };
291
+ }
292
+ async handleStatic(req, res, pathname) {
293
+ const method = (req.method || 'GET').toUpperCase();
294
+ if (this.options.html) {
295
+ if (method !== 'GET' && method !== 'HEAD') {
296
+ res.writeHead(405, { Allow: 'GET, HEAD' });
297
+ res.end();
298
+ return;
299
+ }
300
+ this.sendHtml(res, this.options.html, method === 'HEAD');
301
+ return;
302
+ }
303
+ if (!this.staticRoot) {
304
+ this.sendJson(res, 404, { error: 'Not found' });
305
+ return;
306
+ }
307
+ if (method !== 'GET' && method !== 'HEAD') {
308
+ res.writeHead(405, { Allow: 'GET, HEAD' });
309
+ res.end();
310
+ return;
311
+ }
312
+ let relative = pathname.replace(/^\/+/, '');
313
+ if (!relative || relative.endsWith('/')) {
314
+ relative += 'index.html';
315
+ }
316
+ if (hasDotSegment(relative)) {
317
+ this.sendJson(res, 404, { error: 'Not found' });
318
+ return;
319
+ }
320
+ let file = path.resolve(this.staticRoot, relative);
321
+ if (!isInside(this.staticRoot, file)) {
322
+ this.sendJson(res, 403, { error: 'Forbidden' });
323
+ return;
324
+ }
325
+ try {
326
+ let stat = await fs.promises.stat(file);
327
+ if (stat.isDirectory()) {
328
+ file = path.join(file, 'index.html');
329
+ stat = await fs.promises.stat(file);
330
+ }
331
+ if (!stat.isFile()) {
332
+ this.sendJson(res, 404, { error: 'Not found' });
333
+ return;
334
+ }
335
+ // Proteção extra: nunca servir nada que esteja dentro da pasta de API,
336
+ // mesmo via symlink ou configuração equivocada (ex: public: '.').
337
+ const real = await fs.promises.realpath(file);
338
+ if (this.apiRealRoot && isInside(this.apiRealRoot, real)) {
339
+ this.sendJson(res, 404, { error: 'Not found' });
340
+ return;
341
+ }
342
+ if (this.staticRealRoot && !isInside(this.staticRealRoot, real)) {
343
+ this.sendJson(res, 403, { error: 'Forbidden' });
344
+ return;
345
+ }
346
+ const contentType = MIME_TYPES[path.extname(file).toLowerCase()] || 'application/octet-stream';
347
+ res.writeHead(200, {
348
+ 'Content-Type': contentType,
349
+ 'Content-Length': stat.size,
350
+ });
351
+ if (method === 'HEAD') {
352
+ res.end();
353
+ return;
354
+ }
355
+ const stream = fs.createReadStream(file);
356
+ stream.on('error', () => {
357
+ if (!res.writableEnded)
358
+ res.end();
359
+ });
360
+ stream.pipe(res);
361
+ }
362
+ catch {
363
+ this.sendJson(res, 404, { error: 'Not found' });
364
+ }
365
+ }
366
+ sendHtml(res, html, headOnly) {
367
+ res.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8' });
368
+ res.end(headOnly ? undefined : html);
369
+ }
370
+ sendJson(res, status, body) {
371
+ if (res.headersSent) {
372
+ res.end();
373
+ return;
374
+ }
375
+ res.writeHead(status, { 'Content-Type': 'application/json; charset=utf-8' });
376
+ res.end(JSON.stringify(body));
377
+ }
83
378
  stop() {
84
379
  if (this.server) {
85
380
  this.server.close();
package/dist/Tunnel.js CHANGED
@@ -49,7 +49,8 @@ function validateCloudflareOptions(options) {
49
49
  }
50
50
  }
51
51
  export async function createTunnel(options) {
52
- if (!options.port || isNaN(options.port)) {
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) => emitter.emit("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 || targetPort, // Return original user port or dynamic 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();
@@ -0,0 +1,89 @@
1
+ import type { TunnelOptions } from "./Tunnel.js";
2
+ export type Lang = "pt" | "en";
3
+ export type Mode = "site" | "api" | "both";
4
+ export type PublishMode = "quick" | "domain";
5
+ export interface CliOptions {
6
+ lang?: Lang;
7
+ help: boolean;
8
+ version: boolean;
9
+ yes: boolean;
10
+ dryRun: boolean;
11
+ mode?: Mode;
12
+ public?: string;
13
+ api?: string;
14
+ apiPrefix?: string;
15
+ target?: number;
16
+ port?: number;
17
+ domain?: string;
18
+ token?: string;
19
+ quick: boolean;
20
+ save: boolean;
21
+ }
22
+ export interface Plan {
23
+ mode: Mode;
24
+ public?: string;
25
+ api?: string;
26
+ apiPrefix: string;
27
+ publish: PublishMode;
28
+ domain?: string;
29
+ /** Porta de um servidor que já está rodando (modo proxy). */
30
+ target?: number;
31
+ /** Porta do servidor interno (modo pastas + domínio). */
32
+ port?: number;
33
+ }
34
+ export interface Strings {
35
+ needTty: string;
36
+ cloudflaredMissing: string;
37
+ whatPublish: string;
38
+ modeSite: string;
39
+ modeApi: string;
40
+ modeBoth: string;
41
+ modeServer: string;
42
+ publicPath: string;
43
+ apiPath: string;
44
+ serverPortPrompt: string;
45
+ serverNotRunning: (port: number) => string;
46
+ publishHow: string;
47
+ publishQuick: string;
48
+ publishDomain: string;
49
+ domainPrompt: string;
50
+ tokenPrompt: string;
51
+ portPrompt: string;
52
+ createFolder: (dir: string) => string;
53
+ folderNotDir: (dir: string) => string;
54
+ createdFolder: (dir: string) => string;
55
+ invalidDomain: string;
56
+ invalidPort: string;
57
+ portInUse: (port: number) => string;
58
+ missingToken: string;
59
+ summaryTitle: string;
60
+ summarySite: (dir: string) => string;
61
+ summaryApi: (dir: string, prefix: string) => string;
62
+ summaryServer: (port: number) => string;
63
+ summaryPublishQuick: string;
64
+ summaryPublishDomain: (domain: string) => string;
65
+ summaryPort: (port: number) => string;
66
+ confirm: string;
67
+ cancelled: string;
68
+ starting: string;
69
+ tunnelUrl: (url: string) => string;
70
+ siteServed: (dir: string) => string;
71
+ apiServed: (dir: string, prefix: string) => string;
72
+ domainHint: (domain: string, port: number) => string;
73
+ pressCtrlC: string;
74
+ useSaved: string;
75
+ savedConfig: (file: string) => string;
76
+ tokenSaved: string;
77
+ dryRun: string;
78
+ error: (message: string) => string;
79
+ }
80
+ export declare const STRINGS: Record<Lang, Strings>;
81
+ export declare const HELP: Record<Lang, string>;
82
+ export declare function detectLang(explicit?: string, env?: NodeJS.ProcessEnv): Lang;
83
+ export declare function parseCliArgs(argv: string[]): CliOptions;
84
+ export declare function isValidPort(port: number): boolean;
85
+ export declare function normalizeDomain(input: string): string;
86
+ export declare function isValidDomain(domain: string): boolean;
87
+ export declare function normalizePrefix(input?: string): string;
88
+ export declare function guessMode(publicExists: boolean, apiExists: boolean): Mode;
89
+ export declare function buildTunnelOptions(plan: Plan, token?: string): TunnelOptions;