nport 1.0.6 → 2.0.2

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/index.js ADDED
@@ -0,0 +1,635 @@
1
+ #!/usr/bin/env node
2
+
3
+ import axios from "axios";
4
+ import { spawn } from "child_process";
5
+ import chalk from "chalk";
6
+ import ora from "ora";
7
+ import fs from "fs";
8
+ import path from "path";
9
+ import { fileURLToPath } from "url";
10
+ import { createRequire } from "module";
11
+ import { analytics } from "./analytics.js";
12
+
13
+ // ============================================================================
14
+ // Module Setup & Constants
15
+ // ============================================================================
16
+
17
+ const __filename = fileURLToPath(import.meta.url);
18
+ const __dirname = path.dirname(__filename);
19
+ const require = createRequire(import.meta.url);
20
+ const packageJson = require("./package.json");
21
+
22
+ // Application constants
23
+ const CONFIG = {
24
+ PACKAGE_NAME: packageJson.name,
25
+ CURRENT_VERSION: packageJson.version,
26
+ BACKEND_URL: "https://nport.tuanngocptn.workers.dev",
27
+ DEFAULT_PORT: 8080,
28
+ SUBDOMAIN_PREFIX: "user-",
29
+ TUNNEL_TIMEOUT_HOURS: 4,
30
+ UPDATE_CHECK_TIMEOUT: 3000,
31
+ };
32
+
33
+ // Platform-specific configuration
34
+ const PLATFORM = {
35
+ IS_WINDOWS: process.platform === "win32",
36
+ BIN_NAME: process.platform === "win32" ? "cloudflared.exe" : "cloudflared",
37
+ };
38
+
39
+ // Paths
40
+ const PATHS = {
41
+ BIN_DIR: path.join(__dirname, "bin"),
42
+ BIN_PATH: path.join(__dirname, "bin", PLATFORM.BIN_NAME),
43
+ };
44
+
45
+ // Log patterns for filtering cloudflared output
46
+ const LOG_PATTERNS = {
47
+ SUCCESS: ["Registered tunnel connection"],
48
+ ERROR: ["ERR", "error"],
49
+ IGNORE: [
50
+ "Cannot determine default origin certificate path",
51
+ "No file cert.pem",
52
+ "origincert option",
53
+ "TUNNEL_ORIGIN_CERT",
54
+ "context canceled",
55
+ "failed to run the datagram handler",
56
+ "failed to serve tunnel connection",
57
+ "Connection terminated",
58
+ "no more connections active and exiting",
59
+ "Serve tunnel error",
60
+ "accept stream listener encountered a failure",
61
+ "Retrying connection",
62
+ "icmp router terminated",
63
+ "use of closed network connection",
64
+ "Application error 0x0",
65
+ ],
66
+ };
67
+
68
+ // Computed constants
69
+ const TUNNEL_TIMEOUT_MS = CONFIG.TUNNEL_TIMEOUT_HOURS * 60 * 60 * 1000;
70
+
71
+ // ============================================================================
72
+ // Application State
73
+ // ============================================================================
74
+
75
+ class TunnelState {
76
+ constructor() {
77
+ this.tunnelId = null;
78
+ this.subdomain = null;
79
+ this.port = null;
80
+ this.tunnelProcess = null;
81
+ this.timeoutId = null;
82
+ this.connectionCount = 0;
83
+ this.startTime = null;
84
+ }
85
+
86
+ setTunnel(tunnelId, subdomain, port) {
87
+ this.tunnelId = tunnelId;
88
+ this.subdomain = subdomain;
89
+ this.port = port;
90
+ if (!this.startTime) {
91
+ this.startTime = Date.now();
92
+ }
93
+ }
94
+
95
+ setProcess(process) {
96
+ this.tunnelProcess = process;
97
+ }
98
+
99
+ setTimeout(timeoutId) {
100
+ this.timeoutId = timeoutId;
101
+ }
102
+
103
+ clearTimeout() {
104
+ if (this.timeoutId) {
105
+ clearTimeout(this.timeoutId);
106
+ this.timeoutId = null;
107
+ }
108
+ }
109
+
110
+ incrementConnection() {
111
+ this.connectionCount++;
112
+ return this.connectionCount;
113
+ }
114
+
115
+ hasTunnel() {
116
+ return this.tunnelId !== null;
117
+ }
118
+
119
+ hasProcess() {
120
+ return this.tunnelProcess && !this.tunnelProcess.killed;
121
+ }
122
+
123
+ getDurationSeconds() {
124
+ if (!this.startTime) return 0;
125
+ return (Date.now() - this.startTime) / 1000;
126
+ }
127
+
128
+ reset() {
129
+ this.clearTimeout();
130
+ this.tunnelId = null;
131
+ this.subdomain = null;
132
+ this.port = null;
133
+ this.tunnelProcess = null;
134
+ this.connectionCount = 0;
135
+ this.startTime = null;
136
+ }
137
+ }
138
+
139
+ const state = new TunnelState();
140
+
141
+ // ============================================================================
142
+ // Argument Parsing
143
+ // ============================================================================
144
+
145
+ class ArgumentParser {
146
+ static parse(argv) {
147
+ const port = this.parsePort(argv);
148
+ const subdomain = this.parseSubdomain(argv);
149
+ return { port, subdomain };
150
+ }
151
+
152
+ static parsePort(argv) {
153
+ const portArg = parseInt(argv[0]);
154
+ return portArg || CONFIG.DEFAULT_PORT;
155
+ }
156
+
157
+ static parseSubdomain(argv) {
158
+ // Try all subdomain formats
159
+ const formats = [
160
+ () => this.findFlagWithEquals(argv, "--subdomain="),
161
+ () => this.findFlagWithEquals(argv, "-s="),
162
+ () => this.findFlagWithValue(argv, "--subdomain"),
163
+ () => this.findFlagWithValue(argv, "-s"),
164
+ ];
165
+
166
+ for (const format of formats) {
167
+ const subdomain = format();
168
+ if (subdomain) return subdomain;
169
+ }
170
+
171
+ return this.generateRandomSubdomain();
172
+ }
173
+
174
+ static findFlagWithEquals(argv, flag) {
175
+ const arg = argv.find((a) => a.startsWith(flag));
176
+ return arg ? arg.split("=")[1] : null;
177
+ }
178
+
179
+ static findFlagWithValue(argv, flag) {
180
+ const index = argv.indexOf(flag);
181
+ return index !== -1 && argv[index + 1] ? argv[index + 1] : null;
182
+ }
183
+
184
+ static generateRandomSubdomain() {
185
+ return `${CONFIG.SUBDOMAIN_PREFIX}${Math.floor(Math.random() * 10000)}`;
186
+ }
187
+ }
188
+
189
+ // ============================================================================
190
+ // Binary Management
191
+ // ============================================================================
192
+
193
+ class BinaryManager {
194
+ static validate(binaryPath) {
195
+ if (fs.existsSync(binaryPath)) {
196
+ return true;
197
+ }
198
+
199
+ console.error(
200
+ chalk.red(`\nāŒ Error: Cloudflared binary not found at: ${binaryPath}`)
201
+ );
202
+ console.error(
203
+ chalk.yellow(
204
+ "šŸ‘‰ Please run 'npm install' again to download the binary.\n"
205
+ )
206
+ );
207
+ return false;
208
+ }
209
+
210
+ static spawn(binaryPath, token, port) {
211
+ return spawn(binaryPath, [
212
+ "tunnel",
213
+ "run",
214
+ "--token",
215
+ token,
216
+ "--url",
217
+ `http://localhost:${port}`,
218
+ ]);
219
+ }
220
+
221
+ static attachHandlers(process, spinner = null) {
222
+ process.stderr.on("data", (chunk) => this.handleStderr(chunk));
223
+ process.on("error", (err) => this.handleError(err, spinner));
224
+ process.on("close", (code) => this.handleClose(code));
225
+ }
226
+
227
+ static handleStderr(chunk) {
228
+ const msg = chunk.toString();
229
+
230
+ // Skip harmless warnings
231
+ if (LOG_PATTERNS.IGNORE.some((pattern) => msg.includes(pattern))) {
232
+ return;
233
+ }
234
+
235
+ // Show success messages with connection count
236
+ if (LOG_PATTERNS.SUCCESS.some((pattern) => msg.includes(pattern))) {
237
+ const count = state.incrementConnection();
238
+
239
+ const messages = [
240
+ "āœ” Connection established [1/4] - Establishing redundancy...",
241
+ "āœ” Connection established [2/4] - Building tunnel network...",
242
+ "āœ” Connection established [3/4] - Almost there...",
243
+ "āœ” Connection established [4/4] - Tunnel is fully active! šŸš€",
244
+ ];
245
+
246
+ if (count <= 4) {
247
+ console.log(chalk.blueBright(messages[count - 1]));
248
+ }
249
+ return;
250
+ }
251
+
252
+ // Show critical errors only
253
+ if (LOG_PATTERNS.ERROR.some((pattern) => msg.includes(pattern))) {
254
+ console.error(chalk.red(`[Cloudflared] ${msg.trim()}`));
255
+ }
256
+ }
257
+
258
+ static handleError(err, spinner) {
259
+ if (spinner) {
260
+ spinner.fail("Failed to spawn cloudflared process.");
261
+ }
262
+ console.error(chalk.red(`Process Error: ${err.message}`));
263
+ }
264
+
265
+ static handleClose(code) {
266
+ if (code !== 0 && code !== null) {
267
+ console.log(chalk.red(`Tunnel process exited with code ${code}`));
268
+ }
269
+ }
270
+ }
271
+
272
+ // ============================================================================
273
+ // API Client
274
+ // ============================================================================
275
+
276
+ class APIClient {
277
+ static async createTunnel(subdomain) {
278
+ try {
279
+ const { data } = await axios.post(CONFIG.BACKEND_URL, { subdomain });
280
+
281
+ if (!data.success) {
282
+ throw new Error(data.error || "Unknown error from backend");
283
+ }
284
+
285
+ return {
286
+ tunnelId: data.tunnelId,
287
+ tunnelToken: data.tunnelToken,
288
+ url: data.url,
289
+ };
290
+ } catch (error) {
291
+ throw this.handleError(error, subdomain);
292
+ }
293
+ }
294
+
295
+ static async deleteTunnel(subdomain, tunnelId) {
296
+ await axios.delete(CONFIG.BACKEND_URL, {
297
+ data: { subdomain, tunnelId },
298
+ });
299
+ }
300
+
301
+ static handleError(error, subdomain) {
302
+ if (error.response?.data?.error) {
303
+ const errorMsg = error.response.data.error;
304
+
305
+ // Check for duplicate tunnel error
306
+ if (
307
+ errorMsg.includes("already have a tunnel") ||
308
+ errorMsg.includes("[1013]")
309
+ ) {
310
+ return new Error(
311
+ `Subdomain "${subdomain}" is already taken or in use.\n\n` +
312
+ chalk.yellow(`šŸ’” Try one of these options:\n`) +
313
+ chalk.gray(` 1. Choose a different subdomain: `) +
314
+ chalk.cyan(`nport ${state.port || CONFIG.DEFAULT_PORT} -s ${subdomain}-v2\n`) +
315
+ chalk.gray(` 2. Use a random subdomain: `) +
316
+ chalk.cyan(`nport ${state.port || CONFIG.DEFAULT_PORT}\n`) +
317
+ chalk.gray(
318
+ ` 3. Wait a few minutes and retry if you just stopped a tunnel with this name`
319
+ )
320
+ );
321
+ }
322
+
323
+ return new Error(`Backend Error: ${errorMsg}`);
324
+ }
325
+
326
+ if (error.response) {
327
+ const errorMsg = JSON.stringify(error.response.data, null, 2);
328
+ return new Error(`Backend Error: ${errorMsg}`);
329
+ }
330
+
331
+ return error;
332
+ }
333
+ }
334
+
335
+ // ============================================================================
336
+ // Version Management
337
+ // ============================================================================
338
+
339
+ class VersionManager {
340
+ static async checkForUpdates() {
341
+ try {
342
+ const response = await axios.get(
343
+ `https://registry.npmjs.org/${CONFIG.PACKAGE_NAME}/latest`,
344
+ { timeout: CONFIG.UPDATE_CHECK_TIMEOUT }
345
+ );
346
+
347
+ const latestVersion = response.data.version;
348
+ const shouldUpdate =
349
+ this.compareVersions(latestVersion, CONFIG.CURRENT_VERSION) > 0;
350
+
351
+ // Track update notification if available
352
+ if (shouldUpdate) {
353
+ analytics.trackUpdateAvailable(CONFIG.CURRENT_VERSION, latestVersion);
354
+ }
355
+
356
+ return {
357
+ current: CONFIG.CURRENT_VERSION,
358
+ latest: latestVersion,
359
+ shouldUpdate,
360
+ };
361
+ } catch (error) {
362
+ // Silently fail if can't check for updates
363
+ return null;
364
+ }
365
+ }
366
+
367
+ static compareVersions(v1, v2) {
368
+ const parts1 = v1.split(".").map(Number);
369
+ const parts2 = v2.split(".").map(Number);
370
+
371
+ // Compare up to the maximum length of both version arrays
372
+ const maxLength = Math.max(parts1.length, parts2.length);
373
+
374
+ for (let i = 0; i < maxLength; i++) {
375
+ // Treat missing parts as 0 (e.g., "1.0" is "1.0.0")
376
+ const part1 = parts1[i] || 0;
377
+ const part2 = parts2[i] || 0;
378
+
379
+ if (part1 > part2) return 1;
380
+ if (part1 < part2) return -1;
381
+ }
382
+
383
+ return 0;
384
+ }
385
+ }
386
+
387
+ // ============================================================================
388
+ // UI Display
389
+ // ============================================================================
390
+
391
+ class UI {
392
+ static displayUpdateNotification(updateInfo) {
393
+ if (!updateInfo || !updateInfo.shouldUpdate) return;
394
+
395
+ const border = "═".repeat(59);
396
+ console.log(chalk.yellow(`\nā•”${border}ā•—`));
397
+ console.log(
398
+ chalk.yellow("ā•‘") +
399
+ chalk.bold.yellow(" šŸ“¦ Update Available!") +
400
+ " ".repeat(37) +
401
+ chalk.yellow("ā•‘")
402
+ );
403
+ console.log(chalk.yellow(`ā• ${border}ā•£`));
404
+ console.log(
405
+ chalk.yellow("ā•‘") +
406
+ chalk.gray(` Current version: `) +
407
+ chalk.red(`v${updateInfo.current}`) +
408
+ " ".repeat(26) +
409
+ chalk.yellow("ā•‘")
410
+ );
411
+ console.log(
412
+ chalk.yellow("ā•‘") +
413
+ chalk.gray(` Latest version: `) +
414
+ chalk.green(`v${updateInfo.latest}`) +
415
+ " ".repeat(26) +
416
+ chalk.yellow("ā•‘")
417
+ );
418
+ console.log(chalk.yellow(`ā• ${border}ā•£`));
419
+ console.log(
420
+ chalk.yellow("ā•‘") +
421
+ chalk.cyan(` Run: `) +
422
+ chalk.bold(`npm install -g ${CONFIG.PACKAGE_NAME}@latest`) +
423
+ " ".repeat(10) +
424
+ chalk.yellow("ā•‘")
425
+ );
426
+ console.log(chalk.yellow(`ā•š${border}ā•\n`));
427
+ }
428
+
429
+ static displayProjectInfo() {
430
+ const line = "─".repeat(65);
431
+ console.log(chalk.gray(`\n${line}`));
432
+ console.log(
433
+ chalk.cyan.bold("NPort") +
434
+ chalk.gray(" - ngrok who? (Free & Open Source from Vietnam)")
435
+ );
436
+ console.log(chalk.gray(line));
437
+ console.log(
438
+ chalk.magenta("⚔ Built different: ") +
439
+ chalk.white("No cap, actually free forever")
440
+ );
441
+ console.log(
442
+ chalk.gray("🌐 Website: ") +
443
+ chalk.blue("https://nport.link")
444
+ );
445
+ console.log(
446
+ chalk.gray("šŸ“¦ NPM: ") +
447
+ chalk.blue("npm i -g nport")
448
+ );
449
+ console.log(
450
+ chalk.gray("šŸ’» GitHub: ") +
451
+ chalk.blue("https://github.com/tuanngocptn/nport")
452
+ );
453
+ console.log(
454
+ chalk.gray("šŸ‘¤ Made by: ") +
455
+ chalk.cyan("@tuanngocptn") +
456
+ chalk.gray(" (") +
457
+ chalk.blue("https://github.com/tuanngocptn") +
458
+ chalk.gray(")")
459
+ );
460
+ console.log(
461
+ chalk.gray("ā˜• Buy me coffee: ") +
462
+ chalk.yellow("https://buymeacoffee.com/tuanngocptn")
463
+ );
464
+ console.log(chalk.gray(line));
465
+ console.log(chalk.dim("šŸ’­ No paywalls. No BS. Just vibes. ✨"));
466
+ console.log(chalk.gray(`${line}\n`));
467
+ }
468
+
469
+ static displayStartupBanner(port) {
470
+ this.displayProjectInfo();
471
+ console.log(chalk.green(`šŸš€ Starting Tunnel for port ${port}...`));
472
+ }
473
+
474
+ static displayTunnelSuccess(url) {
475
+ console.log(chalk.yellow(`šŸŒ Public URL: ${chalk.bold(url)}`));
476
+ console.log(chalk.gray(` (Using bundled binary)`));
477
+ console.log(
478
+ chalk.gray(` Auto-cleanup in ${CONFIG.TUNNEL_TIMEOUT_HOURS} hours`)
479
+ );
480
+ console.log(chalk.gray("Connecting to global network..."));
481
+ }
482
+
483
+ static displayTimeoutWarning() {
484
+ console.log(
485
+ chalk.yellow(
486
+ `\nā° Tunnel has been running for ${CONFIG.TUNNEL_TIMEOUT_HOURS} hours.`
487
+ )
488
+ );
489
+ console.log(chalk.yellow(" Automatically shutting down..."));
490
+ }
491
+
492
+ static displayError(error, spinner = null) {
493
+ if (spinner) {
494
+ spinner.fail("Failed to connect to server.");
495
+ }
496
+ console.error(chalk.red(error.message));
497
+ }
498
+
499
+ static displayCleanupStart() {
500
+ console.log(
501
+ chalk.yellow("\n\nšŸ›‘ Shutting down... Cleaning up resources...")
502
+ );
503
+ }
504
+
505
+ static displayCleanupSuccess() {
506
+ console.log(chalk.green("āœ” Cleanup successful. Subdomain released."));
507
+ }
508
+
509
+ static displayCleanupError() {
510
+ console.error(
511
+ chalk.red("āœ– Cleanup failed (Server might be down or busy).")
512
+ );
513
+ }
514
+ }
515
+
516
+ // ============================================================================
517
+ // Tunnel Orchestrator
518
+ // ============================================================================
519
+
520
+ class TunnelOrchestrator {
521
+ static async start(config) {
522
+ state.setTunnel(null, config.subdomain, config.port);
523
+
524
+ // Initialize analytics
525
+ await analytics.initialize();
526
+
527
+ // Track CLI start
528
+ analytics.trackCliStart(config.port, config.subdomain, CONFIG.CURRENT_VERSION);
529
+
530
+ // Display UI
531
+ UI.displayStartupBanner(config.port);
532
+
533
+ // Check for updates
534
+ const updateInfo = await VersionManager.checkForUpdates();
535
+ UI.displayUpdateNotification(updateInfo);
536
+
537
+ // Validate binary
538
+ if (!BinaryManager.validate(PATHS.BIN_PATH)) {
539
+ await analytics.trackTunnelError("binary_missing", "Cloudflared binary not found");
540
+ process.exit(1);
541
+ }
542
+
543
+ const spinner = ora("Requesting access...").start();
544
+
545
+ try {
546
+ // Create tunnel
547
+ const tunnel = await APIClient.createTunnel(config.subdomain);
548
+ state.setTunnel(tunnel.tunnelId, config.subdomain, config.port);
549
+
550
+ // Track successful tunnel creation
551
+ analytics.trackTunnelCreated(config.subdomain, config.port);
552
+
553
+ spinner.succeed(chalk.green("Tunnel created!"));
554
+ UI.displayTunnelSuccess(tunnel.url);
555
+
556
+ // Spawn cloudflared
557
+ const process = BinaryManager.spawn(
558
+ PATHS.BIN_PATH,
559
+ tunnel.tunnelToken,
560
+ config.port
561
+ );
562
+ state.setProcess(process);
563
+ BinaryManager.attachHandlers(process, spinner);
564
+
565
+ // Set timeout
566
+ const timeoutId = setTimeout(() => {
567
+ UI.displayTimeoutWarning();
568
+ this.cleanup("timeout");
569
+ }, TUNNEL_TIMEOUT_MS);
570
+ state.setTimeout(timeoutId);
571
+ } catch (error) {
572
+ // Track tunnel creation error
573
+ const errorType = error.message.includes("already taken")
574
+ ? "subdomain_taken"
575
+ : "tunnel_creation_failed";
576
+ analytics.trackTunnelError(errorType, error.message);
577
+
578
+ UI.displayError(error, spinner);
579
+ process.exit(1);
580
+ }
581
+ }
582
+
583
+ static async cleanup(reason = "manual") {
584
+ state.clearTimeout();
585
+
586
+ if (!state.hasTunnel()) {
587
+ process.exit(0);
588
+ }
589
+
590
+ UI.displayCleanupStart();
591
+
592
+ // Track tunnel shutdown with duration
593
+ const duration = state.getDurationSeconds();
594
+ analytics.trackTunnelShutdown(reason, duration);
595
+
596
+ try {
597
+ // Kill process
598
+ if (state.hasProcess()) {
599
+ state.tunnelProcess.kill();
600
+ }
601
+
602
+ // Delete tunnel
603
+ await APIClient.deleteTunnel(state.subdomain, state.tunnelId);
604
+ UI.displayCleanupSuccess();
605
+ } catch (err) {
606
+ UI.displayCleanupError();
607
+ }
608
+
609
+ // Give analytics a moment to send (non-blocking)
610
+ await new Promise(resolve => setTimeout(resolve, 100));
611
+
612
+ process.exit(0);
613
+ }
614
+ }
615
+
616
+ // ============================================================================
617
+ // Application Entry Point
618
+ // ============================================================================
619
+
620
+ async function main() {
621
+ try {
622
+ const config = ArgumentParser.parse(process.argv.slice(2));
623
+ await TunnelOrchestrator.start(config);
624
+ } catch (error) {
625
+ console.error(chalk.red(`Fatal Error: ${error.message}`));
626
+ process.exit(1);
627
+ }
628
+ }
629
+
630
+ // Register cleanup handlers
631
+ process.on("SIGINT", () => TunnelOrchestrator.cleanup());
632
+ process.on("SIGTERM", () => TunnelOrchestrator.cleanup());
633
+
634
+ // Start application
635
+ main();