@mahidsec/nest 1.0.1

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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Mohammad Mahid Alam
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,185 @@
1
+ <p align="center">
2
+ <img src="https://raw.githubusercontent.com/mahidsec/nest/main/assets/icon.png" alt="Nest" width="128" />
3
+ </p>
4
+
5
+ <h1 align="center">Nest</h1>
6
+
7
+ <p align="center">
8
+ A beautiful local course viewer with system tray, tunneling, and progress tracking.
9
+ </p>
10
+
11
+ <p align="center">
12
+ <a href="https://www.npmjs.com/package/@mahidsec/nest"><img src="https://img.shields.io/npm/v/@mahidsec/nest?label=npm&logo=npm" alt="npm version" /></a>
13
+ <img src="https://img.shields.io/badge/node-%3E%3D18-brightgreen?logo=node.js&logoColor=white" alt="Node.js" />
14
+ <img src="https://img.shields.io/badge/license-MIT-blue" alt="License" />
15
+ </p>
16
+
17
+ <p align="center">
18
+ If you find Nest useful, give it a ⭐ on <a href="https://github.com/mahidsec/nest">GitHub</a> — it helps others discover it!
19
+ </p>
20
+
21
+ ---
22
+
23
+ Browse and watch local course materials with beautiful themes, inline file previews, watch progress tracking, and one-click Cloudflare tunneling.
24
+
25
+ **[Install](#install)** · **[Preview](#preview)** · **[Features](#features)** · **[CLI Menu](#cli-menu)** · **[FAQ](#faq)** · **[Contributing](#contributing)**
26
+
27
+ ## Install
28
+
29
+ ```bash
30
+ npm install -g @mahidsec/nest
31
+ ```
32
+
33
+ Then just run:
34
+
35
+ ```bash
36
+ nest
37
+ ```
38
+
39
+ The server starts at **http://localhost:6969**. Open it from any device on your network using your local IP.
40
+
41
+ > On first run, Nest will automatically download [cloudflared](https://developers.cloudflare.com/cloudflare-one/connections/connect-networks/) if you choose to start a tunnel.
42
+
43
+ ## Preview
44
+
45
+ <p align="center">
46
+ <img src="https://raw.githubusercontent.com/mahidsec/nest/main/screenshots/dashboard.png" alt="Nest Dashboard" width="640" />
47
+ </p>
48
+
49
+ <p align="center">
50
+ <img src="https://raw.githubusercontent.com/mahidsec/nest/main/screenshots/home.png" alt="Home View" width="640" />
51
+ </p>
52
+
53
+ <p align="center">
54
+ <img src="https://raw.githubusercontent.com/mahidsec/nest/main/screenshots/course-adding.png" alt="Course Adding" width="640" />
55
+ </p>
56
+
57
+ ## Features
58
+
59
+ - **Course Management** — Import folders, organize by categories, track watch progress
60
+ - **File Viewer** — Inline preview for videos, images, PDFs, code, markdown, and CSV
61
+ - **Curriculum Sidebar** — Collapsible sections with progress tracking and expand/collapse all
62
+ - **Cloudflare Tunnel** — One-click tunneling from both CLI and web UI
63
+ - **QR Code** — In-browser QR generation for sharing tunnel URLs (no external APIs)
64
+ - **System Tray** — Runs in the background with a native tray icon
65
+ - **Multiple Themes** — Moonlight, Sakura, Matcha, Starry, Dusk, Aurora (dark & light)
66
+ - **Mobile Responsive** — Adaptive layout with touch-friendly navigation
67
+ - **LAN Access** — Open from any device on your network
68
+
69
+ ## CLI Menu
70
+
71
+ ```
72
+ 🪺 Nest (v1.0.0)
73
+ 🚀 Server: http://192.168.x.x:6969
74
+ ✅ Status: Running
75
+
76
+ ★ Web UI (Open in Browser)
77
+ ☆ Hide to Tray (Background)
78
+ ☆ Cloudflare Tunnel
79
+ ☆ Exit
80
+ ```
81
+
82
+ | Option | Description |
83
+ | --------------------- | ------------------------------------- |
84
+ | **Web UI** | Opens the app in your default browser |
85
+ | **Hide to Tray** | Runs in background via system tray |
86
+ | **Cloudflare Tunnel** | Creates a public URL with QR code |
87
+ | **Exit** | Gracefully shuts down the server |
88
+
89
+ Use ↑/↓ arrow keys to navigate and Enter to select.
90
+
91
+ ## FAQ
92
+
93
+ **Why is port 6969 used?**
94
+
95
+ It's the default port. You can override it by setting the `PORT` environment variable: `PORT=3000 nest`.
96
+
97
+ **Does Nest send any data externally?**
98
+
99
+ No. All data stays on your machine. The only external connection is when you explicitly start a Cloudflare Tunnel — that connection goes directly to Cloudflare's edge network. No telemetry, no analytics, no phone-home.
100
+
101
+ **Can I access Nest from my phone/tablet?**
102
+
103
+ Yes. Open `http://<your-local-ip>:6969` on any device on the same network. For remote access, use the built-in Cloudflare Tunnel feature.
104
+
105
+ **What file types can Nest preview?**
106
+
107
+ Videos (mp4, mkv, webm, mov, avi), images (jpg, png, gif, webp), code (js, ts, py, java, c, cpp, go, rs, and 20+ more), text (txt, md, csv, log), PDFs, and link files (.url, .webloc).
108
+
109
+ **What happens if I exit the CLI?**
110
+
111
+ The server shuts down gracefully — it closes all connections, stops any active tunnel, and frees the port.
112
+
113
+ **Does it work on Windows/Linux/macOS?**
114
+
115
+ Yes. Nest works on all three platforms. The system tray feature requires a desktop environment. On headless servers, the CLI menu still works.
116
+
117
+ ## Data Storage
118
+
119
+ All data is stored locally:
120
+
121
+ ```
122
+ ~/.nest/data/
123
+ ├── courses.json # Course registry
124
+ └── course_progress.json # Watch progress per course
125
+ ```
126
+
127
+ ## Contributing
128
+
129
+ Clone and run locally:
130
+
131
+ ```bash
132
+ git clone https://github.com/mahidsec/nest.git
133
+ cd nest
134
+ npm install
135
+ cd frontend && npm install && cd ..
136
+ ```
137
+
138
+ **Development:**
139
+
140
+ ```bash
141
+ npm run dev # Server with hot reload
142
+ npm run dev:frontend # Frontend dev server (separate terminal)
143
+ ```
144
+
145
+ **Production build:**
146
+
147
+ ```bash
148
+ npm run build
149
+ npm start
150
+ ```
151
+
152
+ **Project structure:**
153
+
154
+ ```
155
+ nest/
156
+ ├── assets/ # Icons and static assets
157
+ ├── bin/
158
+ │ └── nest.js # CLI entry point
159
+ ├── frontend/ # React + Vite frontend
160
+ │ └── src/
161
+ │ ├── App.tsx # Main application
162
+ │ └── index.css # Themes and styles
163
+ ├── screenshots/ # UI screenshots
164
+ ├── src/
165
+ │ ├── config.ts # Paths and data directory setup
166
+ │ ├── server.ts # Express API and tunnel
167
+ │ └── types.ts # TypeScript types
168
+ ├── esbuild.config.mjs # Backend build config
169
+ └── package.json
170
+ ```
171
+
172
+ ## Tech Stack
173
+
174
+ | Layer | Technology |
175
+ | -------- | ---------------------------------------------------------------------------------------------------------------------------------- |
176
+ | Backend | [Express](https://expressjs.com), [TypeScript](https://www.typescriptlang.org) |
177
+ | Frontend | [React 19](https://react.dev), [Vite](https://vitejs.dev), [DaisyUI](https://daisyui.com), [Tailwind CSS](https://tailwindcss.com) |
178
+ | Icons | [Lucide React](https://lucide.dev) |
179
+ | QR Code | [qrcode](https://www.npmjs.com/package/qrcode) (client-side) |
180
+ | Tunnel | [Cloudflare Tunnel](https://developers.cloudflare.com/cloudflare-one/connections/connect-networks/) via `cloudflared` |
181
+ | Tray | [systray2](https://www.npmjs.com/package/systray2) |
182
+
183
+ ## License
184
+
185
+ [MIT](LICENSE)
Binary file
package/bin/nest.js ADDED
@@ -0,0 +1,399 @@
1
+ #!/usr/bin/env node
2
+ import { spawn, execSync } from "child_process";
3
+ import { fileURLToPath } from "url";
4
+ import { dirname, join } from "path";
5
+ import { existsSync, mkdirSync, writeFileSync, readFileSync, chmodSync } from "fs";
6
+ import { homedir, networkInterfaces, platform, arch } from "os";
7
+
8
+ const __filename = fileURLToPath(import.meta.url);
9
+ const __dirname = dirname(__filename);
10
+ const root = join(__dirname, "..");
11
+ const distServer = join(root, "dist", "server.js");
12
+
13
+ // Ensure data directory exists
14
+ const dataDir = join(homedir(), ".nest", "data");
15
+ if (!existsSync(dataDir)) mkdirSync(dataDir, { recursive: true });
16
+
17
+ const coursesPath = join(dataDir, "courses.json");
18
+ const progressPath = join(dataDir, "course_progress.json");
19
+ if (!existsSync(coursesPath)) writeFileSync(coursesPath, "[]");
20
+ if (!existsSync(progressPath)) writeFileSync(progressPath, "{}");
21
+
22
+ const VERSION = "1.0.0";
23
+ const PORT = Number(process.env.PORT) || 6969;
24
+
25
+ let serverProcess = null;
26
+ let tunnelProcess = null;
27
+ let tunnelUrl = null;
28
+
29
+ // ─── Cloudflared auto-install ───
30
+ const NEST_BIN_DIR = join(homedir(), ".nest", "bin");
31
+ const CLOUDFLARED_PATH = join(NEST_BIN_DIR, "cloudflared");
32
+
33
+ function getCloudflaredUrl() {
34
+ const p = platform(); // linux, darwin
35
+ const a = arch(); // x64, arm64
36
+ const osMap = { linux: "linux", darwin: "darwin" };
37
+ const archMap = { x64: "amd64", arm64: "arm64" };
38
+ const os = osMap[p] || p;
39
+ const cpu = archMap[a] || a;
40
+ return `https://github.com/cloudflare/cloudflared/releases/latest/download/cloudflared-${os}-${cpu}`;
41
+ }
42
+
43
+ function ensureCloudflared() {
44
+ // 1. Check system PATH first
45
+ try {
46
+ const result = execSync("which cloudflared 2>/dev/null || command -v cloudflared 2>/dev/null").toString().trim();
47
+ if (result && existsSync(result)) return result;
48
+ } catch {}
49
+
50
+ // 2. Check ~/.nest/bin/cloudflared
51
+ if (existsSync(CLOUDFLARED_PATH)) return CLOUDFLARED_PATH;
52
+
53
+ // 3. Download
54
+ console.log(" \x1b[33m↓\x1b[0m Downloading cloudflared...");
55
+ if (!existsSync(NEST_BIN_DIR)) mkdirSync(NEST_BIN_DIR, { recursive: true });
56
+
57
+ const url = getCloudflaredUrl();
58
+ try {
59
+ execSync(`curl -fSL -o "${CLOUDFLARED_PATH}" "${url}"`, { stdio: "inherit" });
60
+ chmodSync(CLOUDFLARED_PATH, 0o755);
61
+ console.log(" \x1b[32m✓\x1b[0m cloudflared installed");
62
+ return CLOUDFLARED_PATH;
63
+ } catch {
64
+ console.log(" \x1b[31m✗\x1b[0m Failed to download cloudflared");
65
+ console.log(" \x1b[90mInstall manually: https://developers.cloudflare.com/cloudflare-one/connections/connect-networks/get-started/create-local-tunnel/\x1b[0m");
66
+ return null;
67
+ }
68
+ }
69
+
70
+ function stopTunnel() {
71
+ return fetch(`http://localhost:${PORT}/api/tunnel/stop`, { method: "POST" })
72
+ .catch(() => {})
73
+ .then(() => { tunnelUrl = null; });
74
+ }
75
+
76
+ const OPTIONS = [
77
+ { label: "\u2605 Web UI (Open in Browser)", action: "webui" },
78
+ { label: "\u2606 Hide to Tray (Background)", action: "background" },
79
+ { label: "\u2606 Cloudflare Tunnel", action: "tunnel" },
80
+ { label: "\u2606 Exit", action: "exit" },
81
+ ];
82
+
83
+ let selected = 0;
84
+
85
+ function getLocalIP() {
86
+ const nets = networkInterfaces();
87
+ for (const iface of Object.values(nets)) {
88
+ for (const info of iface) {
89
+ if (info.family === "IPv4" && !info.internal) return info.address;
90
+ }
91
+ }
92
+ return "localhost";
93
+ }
94
+
95
+ function killServer() {
96
+ return new Promise((resolve) => {
97
+ killPort(PORT);
98
+ const pid = serverProcess?.pid;
99
+ if (!pid) { resolve(); return; }
100
+ try { serverProcess.kill('SIGTERM'); } catch {}
101
+ const timer = setTimeout(() => {
102
+ try { process.kill(pid, 'SIGKILL'); } catch {}
103
+ serverProcess = null;
104
+ resolve();
105
+ }, 2000);
106
+ serverProcess.on('close', () => {
107
+ clearTimeout(timer);
108
+ serverProcess = null;
109
+ resolve();
110
+ });
111
+ });
112
+ }
113
+
114
+ function printMenu() {
115
+ const ip = getLocalIP();
116
+ process.stdout.write("\x1B[2J\x1B[0;0H");
117
+ console.log();
118
+ console.log(" \x1b[35m\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\x1b[0m");
119
+ console.log();
120
+ console.log(" \x1b[1;37m \uD83E\uDEBA Nest \x1b[90m(v" + VERSION + ")\x1b[0m");
121
+ console.log(" \x1b[32m \uD83D\uDE80 Server: http://" + ip + ":" + PORT + "\x1b[0m");
122
+ console.log(" \x1b[32m \u2705 Status: Running" + (tunnelUrl ? " \x1b[36m|\x1b[0m \U0001F517 Tunnel Active" : "") + "\x1b[0m");
123
+ console.log();
124
+ console.log(" \x1b[35m\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\x1b[0m");
125
+ console.log();
126
+
127
+ for (let i = 0; i < OPTIONS.length; i++) {
128
+ const arrow = i === selected ? " \x1b[1;37m \u27A4 \x1b[0m" : " ";
129
+ const text = i === selected
130
+ ? "\x1b[1;37m" + OPTIONS[i].label + "\x1b[0m"
131
+ : "\x1b[90m" + OPTIONS[i].label + "\x1b[0m";
132
+ console.log(arrow + text);
133
+ }
134
+
135
+ console.log();
136
+ console.log(" \x1b[90m\u2191/\u2193 navigate \u2022 Enter select \u2022 q quit\x1b[0m");
137
+ console.log();
138
+ }
139
+
140
+ function killPort(port) {
141
+ const cmds = [
142
+ `lsof -ti:${port} 2>/dev/null`,
143
+ `fuser ${port}/tcp 2>/dev/null | tr -s ' '`,
144
+ ];
145
+ for (const cmd of cmds) {
146
+ try {
147
+ const out = execSync(cmd).toString().trim();
148
+ if (out) {
149
+ for (const pid of out.split(/[\s\n]+/).filter(Boolean)) {
150
+ const n = Number(pid);
151
+ if (n > 0 && n !== process.pid) {
152
+ try { process.kill(n, "SIGKILL"); } catch {}
153
+ }
154
+ }
155
+ return;
156
+ }
157
+ } catch {}
158
+ }
159
+ }
160
+
161
+ function startServer(tunnel = false) {
162
+ killPort(PORT);
163
+ const env = { ...process.env };
164
+ if (tunnel) env.NEST_TUNNEL = "true";
165
+ const cmd = existsSync(distServer)
166
+ ? ["node", distServer]
167
+ : [join(root, "node_modules", ".bin", "tsx"), join(root, "src", "server.ts")];
168
+ serverProcess = spawn(cmd[0], cmd.slice(1), { stdio: "inherit", env });
169
+ serverProcess.on("error", () => {});
170
+ serverProcess.on("close", () => { serverProcess = null; });
171
+ }
172
+
173
+ async function openBrowser() {
174
+ try {
175
+ const open = (await import("open")).default;
176
+ await open("http://localhost:" + PORT);
177
+ } catch {
178
+ console.log(" \x1b[90mOpen http://localhost:" + PORT + " in your browser\x1b[0m");
179
+ }
180
+ }
181
+
182
+ // ─── Terminal QR via qrcode package ───
183
+ async function printTerminalQR(text) {
184
+ try {
185
+ const QRCode = (await import("qrcode")).default;
186
+ const qr = await QRCode.toString(text, { type: "terminal", small: true });
187
+ console.log(qr);
188
+ } catch {
189
+ // Fallback: just print the URL
190
+ console.log(" \x1b[36m" + text + "\x1b[0m");
191
+ }
192
+ }
193
+
194
+ // ─── Cloudflare Tunnel ───
195
+ async function startTunnel() {
196
+ // Ensure server is running
197
+ startServer();
198
+ console.log(" \x1b[33m↻\x1b[0m Starting server...");
199
+ await new Promise((r) => setTimeout(r, 1500));
200
+
201
+ console.log(" \x1b[33m⏳\x1b[0m Starting Cloudflare Tunnel...");
202
+
203
+ // Use server API — so UI and CLI share the same tunnel
204
+ try {
205
+ const res = await fetch(`http://localhost:${PORT}/api/tunnel/start`, { method: "POST" });
206
+ const data = await res.json();
207
+
208
+ if (data.success && data.url) {
209
+ tunnelUrl = data.url;
210
+ process.stdout.write("\x1B[2J\x1B[0;0H");
211
+ console.log();
212
+ console.log(" \x1b[35m\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\x1b[0m");
213
+ console.log();
214
+ console.log(" \x1b[1;37m \U0001F310 Cloudflare Tunnel Active\x1b[0m");
215
+ console.log();
216
+ await printTerminalQR(tunnelUrl);
217
+ console.log();
218
+ console.log(" \x1b[1;36m " + tunnelUrl + "\x1b[0m");
219
+ console.log();
220
+ console.log(" \x1b[90m Press any key to stop tunnel\x1b[0m");
221
+ console.log();
222
+ console.log(" \x1b[35m\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\x1b[0m");
223
+ console.log();
224
+ } else {
225
+ console.log(" \x1b[31m✗\x1b[0m " + (data.error || "Tunnel failed to start"));
226
+ }
227
+ } catch (err) {
228
+ console.log(" \x1b[31m✗\x1b[0m Could not reach server at localhost:" + PORT);
229
+ }
230
+
231
+ // Wait for any key to stop tunnel
232
+ const waitForKey = () => {
233
+ return new Promise((resolve) => {
234
+ const handler = (key) => {
235
+ process.stdin.removeListener("data", handler);
236
+ resolve();
237
+ };
238
+ process.stdin.on("data", handler);
239
+ });
240
+ };
241
+
242
+ await waitForKey();
243
+
244
+ // Stop tunnel via server API
245
+ try { await fetch(`http://localhost:${PORT}/api/tunnel/stop`, { method: "POST" }); } catch {}
246
+ tunnelUrl = null;
247
+ await new Promise((r) => setTimeout(r, 500));
248
+ printMenu();
249
+ }
250
+
251
+ // ─── System Tray ───
252
+ async function startTray() {
253
+ try {
254
+ const imported = await import("systray2");
255
+ const SysTray = imported.default?.default || imported.default || imported;
256
+ const iconPath = join(root, "assets", "icon.png");
257
+
258
+ if (!existsSync(iconPath)) {
259
+ console.log(" \x1b[33m\u26A0\x1b[0m icon.png not found at " + iconPath);
260
+ return;
261
+ }
262
+
263
+ const iconData = readFileSync(iconPath).toString("base64");
264
+
265
+ const systray = new SysTray({
266
+ menu: {
267
+ icon: iconData,
268
+ title: "Nest Server",
269
+ tooltip: "Nest Server \u2014 http://localhost:" + PORT,
270
+ items: [
271
+ { title: "Open Web UI", tooltip: "Open in browser", checked: false, enabled: true },
272
+ { title: "Exit", tooltip: "Stop server and exit", checked: false, enabled: true },
273
+ ],
274
+ },
275
+ debug: false,
276
+ copyDir: true,
277
+ });
278
+
279
+ systray.onClick((action) => {
280
+ if (action.item.title === "Open Web UI") {
281
+ openBrowser();
282
+ } else if (action.item.title === "Exit") {
283
+ (async () => {
284
+ await stopTunnel();
285
+ await killServer();
286
+ systray.kill(false);
287
+ process.exit(0);
288
+ })();
289
+ }
290
+ });
291
+
292
+ await systray.ready();
293
+ console.log(" \x1b[32m\u2713\x1b[0m System tray active");
294
+ return systray;
295
+ } catch (err) {
296
+ console.log(" \x1b[33m\u26A0\x1b[0m Tray unavailable (" + (err.message || err) + ")");
297
+ console.log(" \x1b[90mServer running in background. Stop with: kill $(lsof -ti:" + PORT + ")\x1b[0m");
298
+ return null;
299
+ }
300
+ }
301
+
302
+ async function handleSelect() {
303
+ const opt = OPTIONS[selected];
304
+
305
+ if (opt.action === "webui") {
306
+ openBrowser();
307
+ printMenu();
308
+ } else if (opt.action === "tunnel") {
309
+ startTunnel();
310
+ } else if (opt.action === "background") {
311
+ process.stdout.write("\x1B[2J\x1B[0;0H");
312
+ console.log();
313
+ console.log(" \x1b[32m\u2713\x1b[0m System tray active in background.");
314
+ console.log(" \x1b[90mServer: http://localhost:" + PORT + "\x1b[0m");
315
+ console.log();
316
+
317
+ if (serverProcess) serverProcess.unref();
318
+
319
+ spawn("node", [__filename, "--tray"], {
320
+ stdio: "ignore",
321
+ detached: true,
322
+ }).unref();
323
+
324
+ process.exit(0);
325
+ } else if (opt.action === "exit") {
326
+ process.stdout.write("\x1B[2J\x1B[0;0H");
327
+ console.log();
328
+ console.log(" \x1b[32m\u2713\x1b[0m Shutting down server...");
329
+ await stopTunnel();
330
+ await killServer();
331
+ console.log(" \x1b[90mBye!\x1b[0m");
332
+ console.log();
333
+ process.exit(0);
334
+ }
335
+ }
336
+
337
+ // ─── If --tray flag, just run tray ───
338
+ if (process.argv.includes("--tray")) {
339
+ startTray();
340
+ setInterval(() => {}, 1000 * 60 * 60);
341
+ } else {
342
+ // ─── If --auto flag, start silently ───
343
+ if (process.argv.includes("--auto")) {
344
+ startServer();
345
+ if (serverProcess) serverProcess.unref();
346
+ process.exit(0);
347
+ }
348
+
349
+ // ─── Start server immediately, then show menu ───
350
+ startServer();
351
+ let cleaning = false;
352
+
353
+ if (process.stdin.isTTY) {
354
+ process.stdin.setRawMode(true);
355
+ process.stdin.resume();
356
+ process.stdin.setEncoding("utf8");
357
+
358
+ setTimeout(() => { printMenu(); }, 800);
359
+
360
+ process.stdin.on("data", (key) => {
361
+ if (key === "\x1B[A") {
362
+ selected = (selected - 1 + OPTIONS.length) % OPTIONS.length;
363
+ printMenu();
364
+ } else if (key === "\x1B[B") {
365
+ selected = (selected + 1) % OPTIONS.length;
366
+ printMenu();
367
+ } else if (key === "\r" || key === "\n") {
368
+ handleSelect();
369
+ } else if (key === "q" || key === "Q") {
370
+ selected = OPTIONS.length - 1;
371
+ handleSelect();
372
+ } else if (key === "\x03") {
373
+ if (!cleaning) {
374
+ cleaning = true;
375
+ (async () => {
376
+ await stopTunnel();
377
+ await killServer();
378
+ console.log("\n \x1b[90mBye!\x1b[0m\n");
379
+ process.exit(0);
380
+ })();
381
+ }
382
+ }
383
+ });
384
+ } else {
385
+ if (serverProcess) serverProcess.unref();
386
+ process.exit(0);
387
+ }
388
+
389
+ // SIGINT handler — in raw mode, the stdin handler above catches Ctrl+C.
390
+ // This is a safety net for edge cases (e.g. SIGINT from another process).
391
+ process.on("SIGINT", async () => {
392
+ if (cleaning) return;
393
+ cleaning = true;
394
+ await stopTunnel();
395
+ await killServer();
396
+ console.log("\n \x1b[90mBye!\x1b[0m\n");
397
+ process.exit(0);
398
+ });
399
+ }