@feng3d/ctc 0.0.20 → 0.2.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.
Files changed (56) hide show
  1. package/README.md +82 -106
  2. package/dist/cli.d.ts +13 -12
  3. package/dist/cli.d.ts.map +1 -1
  4. package/dist/cli.js +190 -966
  5. package/dist/cli.js.map +1 -1
  6. package/dist/config.d.ts +18 -51
  7. package/dist/config.d.ts.map +1 -1
  8. package/dist/config.js +42 -180
  9. package/dist/config.js.map +1 -1
  10. package/dist/controller.d.ts +47 -5
  11. package/dist/controller.d.ts.map +1 -1
  12. package/dist/controller.js +10 -23
  13. package/dist/controller.js.map +1 -1
  14. package/dist/handlers/unified-handler.d.ts.map +1 -1
  15. package/dist/handlers/unified-handler.js +3 -1
  16. package/dist/handlers/unified-handler.js.map +1 -1
  17. package/dist/index.d.ts +7 -5
  18. package/dist/index.d.ts.map +1 -1
  19. package/dist/index.js +5 -4
  20. package/dist/index.js.map +1 -1
  21. package/dist/proxy-manager.d.ts +32 -32
  22. package/dist/proxy-manager.d.ts.map +1 -1
  23. package/dist/proxy-manager.js +81 -111
  24. package/dist/proxy-manager.js.map +1 -1
  25. package/package.json +5 -10
  26. package/admin-ui/dist/app.js +0 -29
  27. package/admin-ui/dist/index.html +0 -222
  28. package/admin-ui/dist/style.css +0 -1
  29. package/dist/admin-server.d.ts +0 -149
  30. package/dist/admin-server.d.ts.map +0 -1
  31. package/dist/admin-server.js +0 -426
  32. package/dist/admin-server.js.map +0 -1
  33. package/dist/app.d.ts +0 -17
  34. package/dist/app.d.ts.map +0 -1
  35. package/dist/app.js +0 -97
  36. package/dist/app.js.map +0 -1
  37. package/dist/daemon-entry.d.ts +0 -8
  38. package/dist/daemon-entry.d.ts.map +0 -1
  39. package/dist/daemon-entry.js +0 -15
  40. package/dist/daemon-entry.js.map +0 -1
  41. package/dist/daemon.d.ts +0 -32
  42. package/dist/daemon.d.ts.map +0 -1
  43. package/dist/daemon.js +0 -370
  44. package/dist/daemon.js.map +0 -1
  45. package/dist/forward-proxy.d.ts +0 -100
  46. package/dist/forward-proxy.d.ts.map +0 -1
  47. package/dist/forward-proxy.js +0 -407
  48. package/dist/forward-proxy.js.map +0 -1
  49. package/dist/ipc-handler.d.ts +0 -124
  50. package/dist/ipc-handler.d.ts.map +0 -1
  51. package/dist/ipc-handler.js +0 -305
  52. package/dist/ipc-handler.js.map +0 -1
  53. package/dist/process-utils.d.ts +0 -31
  54. package/dist/process-utils.d.ts.map +0 -1
  55. package/dist/process-utils.js +0 -87
  56. package/dist/process-utils.js.map +0 -1
package/dist/cli.js CHANGED
@@ -1,1006 +1,230 @@
1
1
  #!/usr/bin/env node
2
2
  /**
3
3
  * @module cli
4
- * @description 穿透客户端 CLI - 简洁的命令行工具
5
4
  *
6
- * 使用方法:
7
- * npx @feng3d/cts start # 启动客户端(后台守护进程)
8
- * npx @feng3d/cts stop # 停止客户端
9
- * npx @feng3d/cts restart # 重启客户端
10
- * npx @feng3d/cts status # 查看状态
11
- * npx @feng3d/cts proxies # 管理代理映射
12
- * npx @feng3d/cts forward # 管理正向穿透
13
- * npx @feng3d/cts config # 管理配置
14
- * npx @feng3d/cts boot # 管理开机自启动
15
- * npx @feng3d/cts logs # 查看日志
16
- * npx @feng3d/cts open # 打开管理页面
5
+ * 穿透客户端命令行入口。
6
+ *
7
+ * 提供两条命令:
8
+ *
9
+ * 1. 设置服务端访问信息(写入配置文件):
10
+ * npx -y @feng3d/ctc set -ip <serverip> -p <serverport> -t <token> [--tls]
11
+ *
12
+ * 2. 映射本地端口到服务端(服务端自动分配端口并返回):
13
+ * npx -y @feng3d/ctc -p <localPort> [-d]
14
+ *
15
+ * 运行模式:
16
+ * - 默认前台:进程依附终端,终端关闭即停止
17
+ * - -d / --detach:后台运行,脱离终端;停止用系统 kill <pid>
17
18
  */
18
19
  import { Command } from 'commander';
19
- import chalk from 'chalk';
20
- import { readFileSync, writeFileSync, mkdirSync, unlinkSync, existsSync, openSync, closeSync, readSync, statSync } from 'fs';
21
- import { join, dirname } from 'path';
20
+ import { spawn } from 'child_process';
21
+ import { writeFileSync, openSync, unlinkSync, mkdirSync, existsSync, readFileSync } from 'fs';
22
22
  import { homedir, platform } from 'os';
23
- import { spawn, execSync } from 'child_process';
23
+ import { join } from 'path';
24
24
  import { fileURLToPath } from 'url';
25
- import { getActiveBootLevel, hasSystemPrivileges } from '@feng3d/chuantou-shared';
26
- import { registerBoot, unregisterBoot, isBootRegistered } from '@feng3d/chuantou-shared';
27
- import { killProcess } from './process-utils.js';
28
- /** 数据目录 */
25
+ import chalk from 'chalk';
26
+ import { PROTOCOL, DEFAULT_CONFIG } from '@feng3d/chuantou-shared';
27
+ import { Controller } from './controller.js';
28
+ import { ProxyManager } from './proxy-manager.js';
29
+ import { loadConfig, saveConfig } from './config.js';
30
+ /** chuantou 运行时目录:~/.chuantou */
29
31
  const DATA_DIR = join(homedir(), '.chuantou');
30
- /** IPC 请求目录 */
31
- const IPC_REQUEST_DIR = join(homedir(), '.chuantou', 'proxy-requests');
32
- /**
33
- * 通过 IPC 向守护进程发送请求
34
- * @param type - 请求类型
35
- * @param payload - 请求负载
36
- * @param timeout - 超时时间(毫秒)
37
- * @returns 响应数据
38
- */
39
- async function sendIpcRequest(type, payload = {}, timeout = 5000) {
40
- const requestId = `${Date.now()}_${Math.random().toString(36).substring(7)}`;
41
- const requestPath = join(IPC_REQUEST_DIR, `${requestId}.json`);
42
- const responsePath = join(IPC_REQUEST_DIR, `${requestId}.resp`);
43
- try {
44
- // 写入请求文件
45
- mkdirSync(IPC_REQUEST_DIR, { recursive: true });
46
- writeFileSync(requestPath, JSON.stringify({ type, ...payload }));
47
- // 轮询响应文件
48
- const startTime = Date.now();
49
- while (Date.now() - startTime < timeout) {
50
- if (existsSync(responsePath)) {
51
- const response = JSON.parse(readFileSync(responsePath, 'utf-8'));
52
- // 删除响应文件
53
- unlinkSync(responsePath);
54
- return response;
55
- }
56
- await new Promise(resolve => setTimeout(resolve, 100));
57
- }
58
- return { success: false, error: '请求超时' };
59
- }
60
- catch (err) {
61
- return { success: false, error: err.message };
62
- }
63
- }
64
- /** 客户端目录 */
65
- const CLIENT_DIR = join(DATA_DIR, 'client');
66
- /** 配置文件 */
67
- const CONFIG_FILE = join(CLIENT_DIR, 'config.json');
68
- /** PID 文件 */
69
- const PID_FILE = join(CLIENT_DIR, 'client.pid');
70
- /** 日志文件 */
71
- const LOG_FILE = join(CLIENT_DIR, 'client.log');
72
- /** 管理服务器 URL 默认值 */
73
- const ADMIN_URL_DEFAULT = 'http://127.0.0.1:9001';
74
- /** 管理服务器端口默认值 */
75
- const ADMIN_PORT_DEFAULT = 9001;
76
- /**
77
- * 帮助文本
78
- */
79
- const HELP_TEXT = `
80
- ${chalk.bold('用法:')} cts <${chalk.bold('命令')}> [选项]
81
-
82
- ${chalk.bold('命令:')}
83
- ${chalk.cyan('start')} 启动客户端(后台守护进程)
84
- ${chalk.cyan('stop')} 关闭客户端
85
- ${chalk.cyan('restart')} 重启客户端
86
- ${chalk.cyan('status')} 查看运行状态
87
- ${chalk.cyan('proxies')} 管理反向代理映射
88
- ${chalk.cyan('forward')} 管理正向穿透代理
89
- ${chalk.cyan('config')} 管理配置
90
- ${chalk.cyan('boot')} 管理开机自启动
91
- ${chalk.cyan('logs')} 查看日志
92
- ${chalk.cyan('open')} 打开管理页面
93
-
94
- ${chalk.bold('全局选项:')}
95
- ${chalk.yellow('-h, --help')} 显示帮助信息
96
- ${chalk.yellow('-v, --version')} 显示版本号
97
-
98
- ${chalk.bold('start 命令选项:')}
99
- ${chalk.yellow('-s, --server <url>')} 服务器地址 (默认: ws://localhost:9000)
100
- ${chalk.yellow('-t, --token <token>')} 认证令牌
101
- ${chalk.yellow('-p, --proxies <proxies>')} 代理配置 (如: 8080:3000,8081:3001)
102
- ${chalk.yellow('--no-boot')} 不注册开机自启动
103
-
104
- ${chalk.bold('proxies 命令(反向代理):')}
105
- ${chalk.yellow('list')} 列出所有代理映射
106
- ${chalk.yellow('add <remote:local>')} 添加代理 (如: 8080:3000)
107
- ${chalk.yellow('remove <port>')} 移除指定端口的代理
108
- ${chalk.yellow('clear')} 清空所有代理
109
-
110
- ${chalk.bold('forward 命令(正向穿透):')}
111
- ${chalk.yellow('list')} 列出所有正向穿透代理
112
- ${chalk.yellow('add <local:remote:client>')} 添加穿透 (如: 8080:3000:clientB)
113
- ${chalk.yellow('remove <localPort>')} 移除指定本地端口的穿透
114
- ${chalk.yellow('clients')} 查看在线客户端列表
115
- ${chalk.yellow('register')} 注册到服务器启用正向穿透
116
-
117
- ${chalk.bold('config 命令选项:')}
118
- ${chalk.yellow('get [key]')} 获取配置项
119
- ${chalk.yellow('set <key> <value>')} 设置配置项
120
- ${chalk.yellow('list')} 列出所有配置
121
- ${chalk.yellow('edit')} 编辑配置文件
122
-
123
- ${chalk.bold('boot 命令选项:')}
124
- ${chalk.yellow('enable')} 启用开机自启动
125
- ${chalk.yellow('disable')} 禁用开机自启动
126
-
127
- ${chalk.dim('配置文件位置:')} ${CONFIG_FILE}
128
- ${chalk.dim('日志文件位置:')} ${LOG_FILE}
129
-
130
- ${chalk.dim('示例:')}
131
- ${chalk.gray('# 启动客户端')}
132
- cts start --server ws://192.168.1.100:9000 --token mytoken
133
-
134
- ${chalk.gray('# 正向穿透模式:注册并添加映射')}
135
- cts forward register --description "我的电脑"
136
- cts forward clients
137
- cts forward add 8080:3000:clientB
138
- cts forward list
139
-
140
- ${chalk.gray('# 反向代理模式:暴露本地服务')}
141
- cts proxies add 8080:3000
142
- cts proxies list
143
-
144
- ${chalk.gray('# 管理配置')}
145
- cts config set serverUrl ws://localhost:9000
146
- cts config set token mytoken
147
-
148
- ${chalk.gray('# 开机自启动')}
149
- cts boot enable
150
- `;
151
- /**
152
- * 版本号
153
- */
154
- const VERSION = '0.1.0';
155
- /**
156
- * 显示帮助信息
157
- */
158
- function showHelp() {
159
- console.log(HELP_TEXT);
160
- }
161
- /**
162
- * 显示版本号
163
- */
164
- function showVersion() {
165
- console.log(`@feng3d/cts v${VERSION}`);
166
- }
167
- /**
168
- * 读取配置文件
169
- */
170
- function readConfig() {
171
- try {
172
- const content = readFileSync(CONFIG_FILE, 'utf-8');
173
- return JSON.parse(content);
174
- }
175
- catch {
176
- return null;
177
- }
178
- }
179
- /**
180
- * 写入配置文件
181
- */
182
- function writeConfig(config) {
183
- mkdirSync(CLIENT_DIR, { recursive: true });
184
- writeFileSync(CONFIG_FILE, JSON.stringify(config, null, 2));
185
- }
186
- /**
187
- * 读取 PID 文件
188
- */
189
- function readPidFile() {
190
- try {
191
- return JSON.parse(readFileSync(PID_FILE, 'utf-8'));
192
- }
193
- catch {
194
- return null;
195
- }
196
- }
197
- /**
198
- * 写入 PID 文件
199
- */
200
- function writePidFile(info) {
201
- mkdirSync(CLIENT_DIR, { recursive: true });
202
- writeFileSync(PID_FILE, JSON.stringify(info, null, 2));
203
- }
204
- /**
205
- * 删除 PID 文件
206
- */
207
- function removePidFile() {
208
- try {
209
- unlinkSync(PID_FILE);
210
- }
211
- catch {
212
- // ignore
213
- }
214
- }
215
- /**
216
- * 检查客户端是否正在运行
217
- */
218
- function isClientRunning() {
219
- const info = readPidFile();
220
- if (!info)
221
- return false;
222
- try {
223
- process.kill(info.pid, 0);
224
- return true;
225
- }
226
- catch {
227
- return false;
228
- }
229
- }
230
- /**
231
- * 获取客户端状态
232
- */
233
- async function getClientStatus(adminPort = ADMIN_PORT_DEFAULT) {
234
- try {
235
- const res = await fetch(`http://127.0.0.1:${adminPort}/_ctc/status`, { method: 'GET' });
236
- if (!res.ok)
237
- return null;
238
- const data = await res.json();
239
- return data;
240
- }
241
- catch {
242
- return null;
243
- }
244
- }
245
- /**
246
- * 脚本路径
247
- */
248
- const cliPath = fileURLToPath(import.meta.url);
249
- // daemon-entry.js 是守护进程入口
250
- const daemonEntryPath = join(dirname(cliPath), 'daemon-entry.js');
251
- const nodePath = process.execPath;
252
- /**
253
- * 主程序入口
254
- */
32
+ const PID_FILE = join(DATA_DIR, 'client.pid');
33
+ const LOG_FILE = join(DATA_DIR, 'client.log');
34
+ /** 标记已是后台子进程,避免无限 spawn */
35
+ const DETACHED_ENV = '__CHUANTOU_DETACHED';
255
36
  const program = new Command();
256
37
  program
257
- .name('@feng3d/cts')
38
+ .name('feng3d-ctc')
258
39
  .description(chalk.blue('穿透 - 内网穿透客户端'))
259
- .version(VERSION)
260
- .option('-h, --help', '显示帮助信息')
261
- .hook('preAction', (thisCommand) => {
262
- const options = thisCommand.opts();
263
- if (options.help) {
264
- showHelp();
265
- process.exit(0);
40
+ .version('0.1.0');
41
+ // ---- 子命令:set ----
42
+ // 注意:commander 短选项只能是单字符,无法直接支持 "-ip"。
43
+ // 通过在 parse 前将 "-ip" 重写为 "--ip" 来兼容用户习惯的 "-ip <serverip>" 写法。
44
+ const setCmd = program.command('set').description('设置服务端访问信息');
45
+ setCmd.requiredOption('--ip <ip>', '服务端 IP 或域名(可用 -ip 简写)');
46
+ setCmd.requiredOption('-p, --server-port <port>', '服务端控制端口');
47
+ setCmd.requiredOption('-t, --token <token>', '认证 token');
48
+ setCmd.option('--tls', '服务端启用 TLS(使用 wss/https)', false);
49
+ setCmd.action(async (options) => {
50
+ const config = {
51
+ serverIp: options.ip,
52
+ serverPort: parseInt(options.serverPort, 10),
53
+ token: options.token,
54
+ tls: !!options.tls,
55
+ };
56
+ try {
57
+ await saveConfig(config);
58
+ const scheme = config.tls ? 'wss' : 'ws';
59
+ console.log(chalk.green('配置已保存到 ~/.chuantou/config.json'));
60
+ console.log(chalk.gray(` 服务端: ${scheme}://${config.serverIp}:${config.serverPort}`));
61
+ console.log(chalk.gray(` 下一步: feng3d-ctc -p <本地端口> 映射本地端口`));
62
+ }
63
+ catch (error) {
64
+ const msg = error instanceof Error ? error.message : String(error);
65
+ console.error(chalk.red(`保存配置失败: ${msg}`));
66
+ process.exit(1);
266
67
  }
267
68
  });
268
- // ==================== start 命令 ====================
269
- const startCmd = program.command('start')
270
- .description('启动客户端(后台守护进程)')
271
- .option('-s, --server <url>', '服务器地址')
272
- .option('-t, --token <token>', '认证令牌')
273
- .option('-p, --proxies <proxies>', '代理配置(格式:remotePort:localPort[:localHost],多个用逗号分隔)')
274
- .option('--no-boot', '不注册开机自启动')
69
+ // ---- 默认动作:映射本地端口 ----
70
+ program
71
+ .option('-p, --port <localPort>', '要映射的本地端口')
72
+ .option('-d, --detach', '后台运行(终端关闭不停止)')
275
73
  .action(async (options) => {
276
- // 检查是否已在运行
277
- if (isClientRunning()) {
278
- const info = readPidFile();
279
- console.log(chalk.yellow('客户端已在运行中'));
280
- console.log(chalk.gray(` PID: ${info?.pid}`));
281
- console.log(chalk.gray(` 服务器: ${info?.serverUrl}`));
74
+ // 没有 -p 时显示帮助
75
+ if (!options.port) {
76
+ program.help();
282
77
  return;
283
78
  }
284
- // 加载配置
285
- let serverUrl = options.server;
286
- let token = options.token;
287
- const proxiesArg = options.proxies;
288
- // 如果命令行没有指定,从配置文件读取
289
- if (!serverUrl || !token) {
290
- const config = readConfig();
291
- if (config) {
292
- if (!serverUrl)
293
- serverUrl = config.serverUrl;
294
- if (!token)
295
- token = config.token || '';
296
- }
297
- }
298
- // 如果仍然没有服务器地址,使用默认值
299
- if (!serverUrl) {
300
- serverUrl = 'ws://localhost:9000';
301
- console.log(chalk.yellow('未指定服务器地址,使用默认值:ws://localhost:9000'));
302
- }
303
- // 解析代理配置
304
- if (proxiesArg) {
305
- const defaultConfig = {
306
- serverUrl: '',
307
- token: '',
308
- reconnectInterval: 30000,
309
- maxReconnectAttempts: 10,
310
- proxies: []
311
- };
312
- const config = readConfig() || defaultConfig;
313
- config.serverUrl = serverUrl;
314
- config.token = token;
315
- // 解析代理配置:remotePort:localPort[:localHost],多个用逗号分隔
316
- const proxyList = proxiesArg.split(',').map((p) => p.trim()).filter((p) => p);
317
- for (const proxyStr of proxyList) {
318
- const parts = proxyStr.split(':');
319
- if (parts.length < 2) {
320
- console.log(chalk.yellow(`忽略无效的代理配置: ${proxyStr}`));
321
- continue;
322
- }
323
- const remotePort = parseInt(parts[0], 10);
324
- const localPort = parseInt(parts[1], 10);
325
- const localHost = parts.length >= 3 ? parts[2] : 'localhost';
326
- if (isNaN(remotePort) || isNaN(localPort)) {
327
- console.log(chalk.yellow(`忽略无效的代理配置: ${proxyStr}`));
328
- continue;
329
- }
330
- if (!config.proxies)
331
- config.proxies = [];
332
- // 检查是否已存在相同 remotePort
333
- const existingIndex = config.proxies.findIndex(p => p.remotePort === remotePort);
334
- if (existingIndex !== -1) {
335
- config.proxies[existingIndex] = { remotePort, localPort, localHost };
336
- }
337
- else {
338
- config.proxies.push({ remotePort, localPort, localHost });
339
- }
340
- }
341
- writeConfig(config);
342
- }
343
- // 启动参数
344
- const serveArgs = ['--config', CONFIG_FILE];
345
- if (serverUrl)
346
- serveArgs.push('--server', serverUrl);
347
- if (token)
348
- serveArgs.push('--token', token);
349
- // 确保目录存在并打开日志文件
350
- mkdirSync(CLIENT_DIR, { recursive: true });
351
- const logFd = openSync(LOG_FILE, 'a');
352
- // 启动守护进程
353
- const child = spawn(nodePath, [daemonEntryPath, ...serveArgs], {
354
- detached: true,
355
- stdio: ['ignore', logFd, logFd],
356
- });
357
- // PID 文件由子进程(守护进程)在 checkSingleInstance 中自行写入
358
- child.unref();
359
- closeSync(logFd);
360
- console.log(chalk.green('客户端已在后台启动'));
361
- console.log(chalk.gray(` PID: ${child.pid}`));
362
- console.log(chalk.gray(` 服务器: ${serverUrl}`));
363
- console.log(chalk.gray(` 配置: ${CONFIG_FILE}`));
364
- console.log(chalk.gray(` 日志: ${LOG_FILE}`));
365
- // 如果需要开机自启动(智能选择级别)
366
- if (options.boot !== false) {
367
- try {
368
- const result = registerBoot({
369
- isServer: false,
370
- nodePath,
371
- scriptPath: daemonEntryPath,
372
- args: serveArgs,
373
- }, { level: 'auto' }); // 默认使用 auto 智能选择
374
- if (result.level === 'system') {
375
- console.log(chalk.green('已启用开机自启动(系统级)'));
376
- console.log(chalk.gray(' 启动时机: 系统启动时(无需登录桌面)'));
377
- }
378
- else {
379
- console.log(chalk.green('已启用开机自启动(用户级)'));
380
- if (result.needsElevation) {
381
- console.log(chalk.yellow(' 提示: 当前为用户级启动。如需登录前启动,请以管理员/root权限重试'));
382
- }
383
- }
384
- }
385
- catch (err) {
386
- console.log(chalk.yellow(`注册开机自启动失败: ${err.message}`));
387
- }
79
+ const localPort = parseInt(options.port, 10);
80
+ if (!localPort || localPort < 1 || localPort > 65535) {
81
+ console.error(chalk.red(`无效的本地端口: ${options.port}`));
82
+ process.exit(1);
388
83
  }
389
- });
390
- // ==================== stop 命令 ====================
391
- const stopCmd = program.command('stop')
392
- .description('关闭客户端')
393
- .action(async () => {
394
- const info = readPidFile();
395
- if (!info) {
396
- console.log(chalk.yellow('客户端未在运行'));
84
+ // 后台模式:父进程 spawn 自身后退出
85
+ if (options.detach && process.env[DETACHED_ENV] !== '1') {
86
+ spawnDetached(localPort);
397
87
  return;
398
88
  }
399
- // 降级关闭:kill → 检测存在性
400
- const result = await killProcess(info.pid);
401
- if (result.success) {
402
- removePidFile();
403
- // 取消开机自启动
404
- try {
405
- unregisterBoot();
406
- }
407
- catch {
408
- // ignore
409
- }
410
- if (result.method === 'already-dead') {
411
- console.log(chalk.yellow('进程已不存在,已清理状态'));
412
- }
413
- else {
414
- console.log(chalk.green('客户端已关闭'));
415
- }
416
- }
417
- else {
418
- console.log(chalk.red(`关闭失败: ${result.error || '未知错误'}`));
419
- }
89
+ await runProxy(localPort);
420
90
  });
421
- // ==================== restart 命令 ====================
422
- const restartCmd = program.command('restart')
423
- .description('重启客户端')
424
- .action(async () => {
425
- console.log(chalk.blue('正在重启客户端...'));
426
- const info = readPidFile();
427
- const pid = info?.pid;
428
- // 先停止
429
- if (pid) {
91
+ // 兼容用户习惯的 "-ip" "set -p" 简写:
92
+ // 1. commander 短选项只能是单字符,"-ip" 不合法 → 重写为 "--ip"
93
+ // 2. 默认动作与 set 子命令都用 "-p",program 级别的 "-p" 会拦截子命令参数。
94
+ // 在 set 上下文中把 "-p" 重写为 "--server-port" 以正确路由到子命令。
95
+ const rawArgv = process.argv.slice(2);
96
+ const isSetCtx = rawArgv[0] === 'set';
97
+ const argvRewritten = process.argv.map((arg) => {
98
+ if (arg === '-ip')
99
+ return '--ip';
100
+ if (isSetCtx && arg === '-p')
101
+ return '--server-port';
102
+ return arg;
103
+ });
104
+ program.parseAsync(argvRewritten).catch((error) => {
105
+ const msg = error instanceof Error ? error.message : String(error);
106
+ console.error(chalk.red(`错误: ${msg}`));
107
+ process.exit(1);
108
+ });
109
+ /**
110
+ * 运行端口映射:连接服务端 → 认证 → 注册代理(服务端自动分配端口)→ 打印结果
111
+ *
112
+ * @param localPort - 要映射的本地端口
113
+ */
114
+ async function runProxy(localPort) {
115
+ let config;
116
+ try {
117
+ config = await loadConfig();
118
+ }
119
+ catch (error) {
120
+ const msg = error instanceof Error ? error.message : String(error);
121
+ console.error(chalk.red(msg));
122
+ process.exit(1);
123
+ }
124
+ const scheme = config.tls ? 'wss' : 'ws';
125
+ const serverUrl = `${scheme}://${config.serverIp}:${config.serverPort}${PROTOCOL.CONTROL_PATH}`;
126
+ const controller = new Controller({
127
+ serverUrl,
128
+ token: config.token,
129
+ reconnectInterval: DEFAULT_CONFIG.RECONNECT_INTERVAL,
130
+ maxReconnectAttempts: DEFAULT_CONFIG.MAX_RECONNECT_ATTEMPTS,
131
+ });
132
+ const proxyManager = new ProxyManager(controller);
133
+ // 认证成功后注册代理
134
+ controller.on('authenticated', async () => {
430
135
  try {
431
- // Windows 不支持 SIGTERM,需要使用 taskkill 命令
432
- if (platform() === 'win32') {
433
- execSync(`taskkill /F /PID ${pid}`, { stdio: 'ignore' });
434
- }
435
- else {
436
- process.kill(pid, 'SIGTERM');
437
- }
438
- console.log(chalk.gray(`已发送停止信号到 PID ${pid}`));
136
+ await proxyManager.registerProxy({ localPort });
439
137
  }
440
- catch (err) {
441
- console.log(chalk.yellow(`停止失败: ${err.message}`));
138
+ catch (error) {
139
+ const msg = error instanceof Error ? error.message : String(error);
140
+ console.error(chalk.red(`映射失败: ${msg}`));
141
+ process.exit(1);
442
142
  }
443
- }
444
- // 等待进程结束
445
- await new Promise(resolve => setTimeout(resolve, 2000));
446
- // 清除 PID 文件,让 start 命令重新读取
447
- removePidFile();
448
- // 重新启动(不带参数,使用配置文件)
449
- // 启动一个新的 start 命令进程
450
- const startChild = spawn(nodePath, [cliPath, 'start'], {
451
- detached: true,
452
- stdio: 'ignore',
453
143
  });
454
- startChild.unref();
455
- console.log(chalk.green('客户端已重启'));
456
- // 等待客户端启动并显示状态
457
- await new Promise(resolve => setTimeout(resolve, 2000));
458
- const newInfo = readPidFile();
459
- if (newInfo) {
460
- console.log(chalk.gray(` PID: ${newInfo.pid}`));
461
- console.log(chalk.gray(` 管理页面: http://127.0.0.1:${newInfo.adminPort}`));
462
- }
463
- else {
464
- console.log(chalk.yellow(' 启动状态: 未知'));
465
- }
466
- });
467
- // ==================== status 命令 ====================
468
- const statusCmd = program.command('status')
469
- .description('查看运行状态')
470
- .action(async () => {
471
- const info = readPidFile();
472
- if (!info) {
473
- console.log(chalk.yellow('客户端未在运行'));
474
- console.log(chalk.gray('状态: 已停止'));
475
- return;
476
- }
477
- console.log(chalk.blue.bold('穿透客户端状态'));
478
- console.log(chalk.gray(` PID: ${info.pid}`));
479
- console.log(chalk.gray(` 服务器: ${info.serverUrl}`));
480
- console.log(chalk.gray(` 配置: ${CONFIG_FILE}`));
481
- console.log(chalk.gray(` 日志: ${LOG_FILE}`));
482
- console.log(chalk.gray(` 启动时间: ${new Date(info.startedAt).toLocaleString('zh-CN')}`));
483
- console.log(chalk.gray(` 开机启动: ${isBootRegistered() ? '已启用' : '未启用'}`));
484
- // 通过 IPC 获取详细状态
485
- const response = await sendIpcRequest('get-status');
486
- if (response.success && response.status) {
487
- const status = response.status;
488
- const uptime = Math.floor(status.uptime / 1000);
489
- const minutes = Math.floor(uptime / 60);
490
- const seconds = uptime % 60;
491
- console.log(chalk.gray(` 连接状态: ${status.authenticated ? '已认证' : status.connected ? '已连接' : '未连接'}`));
492
- if (uptime > 0) {
493
- console.log(chalk.gray(` 运行时长: ${minutes}分${seconds}秒`));
494
- }
495
- if (status.reconnectAttempts && status.reconnectAttempts > 0) {
496
- console.log(chalk.gray(` 重连次数: ${status.reconnectAttempts}次`));
497
- }
498
- if (status.proxies.length === 0) {
499
- console.log(chalk.gray(' 代理映射: 无'));
500
- }
501
- else {
502
- console.log(chalk.gray(` 代理映射: ${status.proxies.length}个`));
503
- for (const proxy of status.proxies) {
504
- const index = proxy.index ? `#${proxy.index}` : ' -';
505
- const target = proxy.localHost || 'localhost';
506
- const registered = proxy.registered === false ? chalk.yellow(' (待注册)') : '';
507
- console.log(chalk.gray(` ${index} ${proxy.remotePort} -> ${target}:${proxy.localPort}`) + registered);
508
- }
509
- }
510
- if (status.forwardProxies && status.forwardProxies.length > 0) {
511
- console.log(chalk.gray(` 正向穿透: ${status.forwardProxies.length}个`));
512
- for (const fp of status.forwardProxies) {
513
- console.log(chalk.gray(` :${fp.localPort} -> ${fp.targetClientId}:${fp.targetPort}`));
514
- }
515
- }
516
- }
517
- else {
518
- console.log(chalk.yellow(`无法获取状态: ${response.error || '守护进程未就绪'}`));
519
- }
520
- });
521
- // ==================== proxies 命令 ====================
522
- const proxiesCmd = program.command('proxies')
523
- .description('管理代理映射')
524
- .argument('[command]', '子命令:list, add, remove, clear', { default: 'list' });
525
- // proxies list 子命令
526
- proxiesCmd.command('list')
527
- .description('列出现有代理映射')
528
- .action(async () => {
529
- const config = readConfig();
530
- const proxies = config?.proxies || [];
531
- if (proxies.length === 0) {
532
- console.log(chalk.yellow('暂无代理映射'));
533
- return;
534
- }
535
- console.log(chalk.blue.bold('代理映射列表:'));
536
- for (let i = 0; i < proxies.length; i++) {
537
- const proxy = proxies[i];
538
- const index = proxy.index ? `#${proxy.index}` : ' -';
539
- const target = proxy.localHost || 'localhost';
540
- console.log(` ${chalk.cyan(index)} ${chalk.cyan(proxy.remotePort.toString())} -> ${chalk.cyan(target)}:${chalk.cyan(proxy.localPort.toString())}`);
541
- }
542
- });
543
- // proxies add 子命令
544
- proxiesCmd.command('add')
545
- .description('添加代理映射')
546
- .argument('<remote:local>', '远程端口:本地端口 (如: 8080:3000 或 8080:3000:192.168.1.100)')
547
- .option('-h, --host <address>', '本地主机地址 (默认为 localhost)')
548
- .action(async (remoteLocal, options) => {
549
- // 解析参数
550
- const parts = remoteLocal.split(':');
551
- if (parts.length < 2) {
552
- console.log(chalk.yellow('参数格式错误,应为:远程端口:本地端口'));
553
- console.log(chalk.gray('示例:8080:3000 或 8080:3000:192.168.1.100'));
554
- return;
555
- }
556
- const remotePort = parseInt(parts[0], 10);
557
- let localPort;
558
- let localHost = 'localhost';
559
- // 检查是否有第三部分(主机地址)
560
- if (parts.length >= 3) {
561
- localPort = parseInt(parts[1], 10);
562
- localHost = parts[2];
563
- }
564
- else {
565
- localPort = parseInt(parts[1], 10);
566
- }
567
- // 验证端口
568
- if (isNaN(remotePort) || remotePort < 1024 || remotePort > 65535) {
569
- console.log(chalk.yellow('远程端口无效:1024-65535'));
570
- return;
571
- }
572
- if (isNaN(localPort) || localPort < 1 || localPort > 65535) {
573
- console.log(chalk.yellow('本地端口无效:1-65535'));
574
- return;
575
- }
576
- // 通过 IPC 添加
577
- const response = await sendIpcRequest('add-proxy', {
578
- proxy: { remotePort, localPort, localHost }
144
+ // 注册成功后打印映射端口
145
+ proxyManager.on('registered', (assignedPort) => {
146
+ // 代理端口启用 TLS(自签),访问地址用 https;控制端口仍为 ws/http
147
+ const accessScheme = 'https';
148
+ console.log('');
149
+ console.log(chalk.green(' 端口映射成功'));
150
+ console.log(chalk.gray(' ───────────────────────────────────'));
151
+ console.log(` ${chalk.cyan('本地端口')}: ${localPort}`);
152
+ console.log(` ${chalk.cyan('服务端映射端口')}: ${chalk.yellow(assignedPort)}`);
153
+ console.log(` ${chalk.cyan('访问地址')}: ${accessScheme}://${config.serverIp}:${assignedPort}`);
154
+ console.log(chalk.gray(` 提示: 首次访问会有证书警告,在教程页(${config.serverIp}:${config.serverPort})下载安装证书后可消除`));
155
+ console.log(chalk.gray(' ───────────────────────────────────'));
156
+ console.log('');
579
157
  });
580
- if (response.success) {
581
- console.log(chalk.green('代理映射已添加'));
582
- const target = localHost || 'localhost';
583
- console.log(chalk.gray(` ${remotePort} -> ${target}:${localPort}`));
584
- }
585
- else {
586
- console.log(chalk.red(`添加失败: ${response.error || '未知错误'}`));
587
- }
588
- });
589
- // proxies remove 子命令
590
- proxiesCmd.command('remove')
591
- .description('移除指定端口的代理映射')
592
- .argument('<port>', '远程端口号')
593
- .action(async (remotePort) => {
594
- const port = parseInt(remotePort, 10);
595
- if (isNaN(port) || port < 1024 || port > 65535) {
596
- console.log(chalk.yellow('端口号无效:1024-65535'));
597
- return;
598
- }
599
- // 通过 IPC 删除
600
- const response = await sendIpcRequest('remove-proxy', { remotePort: port });
601
- if (response.success) {
602
- console.log(chalk.green(`端口 ${port} 的代理映射已移除`));
603
- }
604
- else {
605
- console.log(chalk.red(`移除失败: ${response.error || '未知错误'}`));
606
- }
607
- });
608
- // proxies clear 子命令
609
- proxiesCmd.command('clear')
610
- .description('清空所有代理映射')
611
- .action(async () => {
612
- const response = await sendIpcRequest('clear-proxies');
613
- if (response.success) {
614
- console.log(chalk.green('所有代理映射已清空'));
615
- }
616
- else {
617
- console.log(chalk.red(`清空失败: ${response.error || '未知错误'}`));
618
- }
619
- });
620
- // ==================== config 命令 ====================
621
- const configCmd = program.command('config')
622
- .description('管理配置')
623
- .argument('[command]', '子命令:get, set, list, edit', { default: 'list' });
624
- // config get 子命令
625
- configCmd.command('get')
626
- .description('获取配置项')
627
- .argument('<key>', '配置项名称 (如: serverUrl, token, reconnectInterval, maxReconnectAttempts)')
628
- .action(async (key) => {
629
- const config = readConfig();
630
- if (!config) {
631
- console.log(chalk.yellow('配置文件不存在'));
632
- return;
633
- }
634
- const value = config[key];
635
- if (value === undefined) {
636
- console.log(chalk.yellow(`配置项 "${key}" 不存在`));
637
- console.log(chalk.gray('可用配置项:serverUrl, token, reconnectInterval, maxReconnectAttempts, proxies'));
638
- return;
639
- }
640
- // 显示值
641
- if (typeof value === 'object') {
642
- console.log(chalk.green(`${key}:`));
643
- console.log(chalk.gray(JSON.stringify(value, null, 2)));
644
- }
645
- else {
646
- console.log(chalk.green(`${key}: ${value}`));
647
- }
648
- });
649
- // config set 子命令
650
- configCmd.command('set')
651
- .description('设置配置项')
652
- .argument('<key>', '配置项名称')
653
- .argument('<value>', '配置值')
654
- .action(async (key, value) => {
655
- // 读取现有配置
656
- const config = readConfig() || {};
657
- const oldValue = config[key];
658
- // 解析值
659
- let parsedValue = value;
660
- if (key === 'serverUrl' || key === 'token') {
661
- parsedValue = value;
662
- }
663
- else if (key === 'reconnectInterval' || key === 'maxReconnectAttempts') {
664
- parsedValue = parseInt(value, 10);
665
- }
666
- else if (key === 'proxies') {
158
+ // 写入 PID 文件
159
+ mkdirSync(DATA_DIR, { recursive: true });
160
+ writeFileSync(PID_FILE, String(process.pid), 'utf-8');
161
+ console.log(chalk.gray(`PID: ${process.pid}`));
162
+ // 优雅退出
163
+ const shutdown = async (signal) => {
164
+ console.log(chalk.yellow(`\n收到 ${signal},正在停止...`));
667
165
  try {
668
- parsedValue = JSON.parse(value);
166
+ await proxyManager.destroy();
669
167
  }
670
- catch {
671
- console.log(chalk.yellow('proxies 必须是有效的 JSON 数组'));
672
- return;
168
+ catch { /* ignore */ }
169
+ controller.destroy();
170
+ try {
171
+ if (existsSync(PID_FILE))
172
+ unlinkSync(PID_FILE);
673
173
  }
674
- }
675
- // 更新配置
676
- config[key] = parsedValue;
677
- writeConfig(config);
678
- if (oldValue !== undefined) {
679
- console.log(chalk.green(`已更新:${key}`));
680
- console.log(chalk.gray(` 旧值: ${typeof oldValue === 'object' ? JSON.stringify(oldValue) : oldValue}`));
681
- console.log(chalk.gray(` 新值: ${typeof parsedValue === 'object' ? JSON.stringify(parsedValue) : parsedValue}`));
682
- }
683
- else {
684
- console.log(chalk.green(`已设置:${key} = ${typeof parsedValue === 'object' ? JSON.stringify(parsedValue) : parsedValue}`));
685
- }
686
- });
687
- // config list 子命令
688
- configCmd.command('list')
689
- .description('列出所有配置项')
690
- .action(async () => {
691
- const config = readConfig();
692
- if (!config) {
693
- console.log(chalk.yellow('配置文件不存在'));
694
- return;
695
- }
696
- console.log(chalk.blue.bold('配置列表:'));
697
- console.log(` ${chalk.cyan('serverUrl')}: ${chalk.gray(config.serverUrl || '(未设置)')}`);
698
- console.log(` ${chalk.cyan('token')}: ${chalk.gray(config.token || '(未设置)')}`);
699
- console.log(` ${chalk.cyan('proxies')}: ${chalk.gray(`[${config.proxies?.map(p => `${p.remotePort}:${p.localPort}`).join(', ') || '(空)'}]`)}`);
700
- console.log(` ${chalk.cyan('reconnectInterval')}: ${chalk.gray(config.reconnectInterval || 30000)}ms`);
701
- console.log(` ${chalk.cyan('maxReconnectAttempts')}: ${chalk.gray(config.maxReconnectAttempts || 10)}`);
702
- });
703
- // config edit 子命令
704
- configCmd.command('edit')
705
- .description('编辑配置文件')
706
- .action(async () => {
707
- const editors = {
708
- win32: 'notepad',
709
- darwin: 'open -a TextEdit',
710
- linux: 'nano',
174
+ catch { /* ignore */ }
175
+ process.exit(0);
711
176
  };
712
- const editor = editors[platform()] || 'vi';
713
- const configPath = CONFIG_FILE;
714
- console.log(chalk.gray(`打开配置文件:${configPath}`));
715
- console.log(chalk.gray(`使用编辑器:${editor}`));
177
+ process.on('SIGINT', () => void shutdown('SIGINT'));
178
+ process.on('SIGTERM', () => void shutdown('SIGTERM'));
179
+ // 启动连接
716
180
  try {
717
- execSync(`${editor} "${configPath}"`, { stdio: 'ignore' });
181
+ await controller.connect();
718
182
  }
719
- catch (err) {
720
- console.log(chalk.yellow(`打开失败: ${err.message}`));
721
- console.log(chalk.gray(`请手动打开:`));
183
+ catch (error) {
184
+ const msg = error instanceof Error ? error.message : String(error);
185
+ console.error(chalk.red(`连接服务端失败: ${msg}`));
186
+ process.exit(1);
722
187
  }
723
- });
724
- // ==================== forward 命令(正向穿透模式)====================
725
- const forwardCmd = program.command('forward')
726
- .description('管理正向穿透代理(本地端口 -> 远程客户端端口)')
727
- .argument('[command]', '子命令:list, add, remove, clients, register', { default: 'list' });
728
- // forward list 子命令
729
- forwardCmd.command('list')
730
- .description('列出所有正向穿透代理')
731
- .action(async () => {
732
- const response = await sendIpcRequest('forward-list');
733
- if (!response.success) {
734
- console.log(chalk.yellow(`无法获取代理列表: ${response.error || '客户端未运行'}`));
735
- return;
736
- }
737
- const proxies = response.proxies || [];
738
- if (proxies.length === 0) {
739
- console.log(chalk.yellow('暂无正向穿透代理'));
740
- return;
741
- }
742
- console.log(chalk.blue.bold('正向穿透代理列表:'));
743
- for (const proxy of proxies) {
744
- console.log(` ${chalk.green('●')} 本地 :${proxy.localPort} → ${chalk.cyan(proxy.targetClientId)}:${proxy.targetPort}`);
745
- }
746
- });
747
- // forward add 子命令
748
- forwardCmd.command('add')
749
- .description('添加正向穿透代理')
750
- .argument('<mapping>', '映射格式:localPort:targetPort:targetClientId (如: 8080:3000:clientB)')
751
- .action(async (mapping) => {
752
- const parts = mapping.split(':');
753
- if (parts.length !== 3) {
754
- console.log(chalk.yellow('参数格式错误,应为:localPort:targetPort:targetClientId'));
755
- console.log(chalk.gray('示例:8080:3000:clientB'));
756
- return;
757
- }
758
- const localPort = parseInt(parts[0], 10);
759
- const targetPort = parseInt(parts[1], 10);
760
- const targetClientId = parts[2];
761
- if (isNaN(localPort) || localPort < 1 || localPort > 65535) {
762
- console.log(chalk.yellow('本地端口无效:1-65535'));
763
- return;
764
- }
765
- if (isNaN(targetPort) || targetPort < 1 || targetPort > 65535) {
766
- console.log(chalk.yellow('目标端口无效:1-65535'));
767
- return;
768
- }
769
- if (!targetClientId || targetClientId.length === 0) {
770
- console.log(chalk.yellow('目标客户端 ID 不能为空'));
771
- return;
772
- }
773
- const response = await sendIpcRequest('forward-add', {
774
- forwardEntry: { localPort, targetPort, targetClientId }
188
+ // 前台驻留
189
+ process.stdin.resume();
190
+ }
191
+ /**
192
+ * 以后台模式 spawn 自身
193
+ */
194
+ function spawnDetached(localPort) {
195
+ mkdirSync(DATA_DIR, { recursive: true });
196
+ cleanupStalePid(PID_FILE);
197
+ const logFd = openSync(LOG_FILE, 'a');
198
+ const nodePath = process.execPath;
199
+ const scriptPath = fileURLToPath(import.meta.url);
200
+ const child = spawn(nodePath, [scriptPath, '-p', String(localPort)], {
201
+ detached: true,
202
+ stdio: ['ignore', logFd, logFd],
203
+ env: { ...process.env, [DETACHED_ENV]: '1' },
775
204
  });
776
- if (response.success) {
777
- console.log(chalk.green('正向穿透代理已添加'));
778
- console.log(chalk.gray(` 本地 :${localPort} → ${targetClientId}:${targetPort}`));
779
- }
780
- else {
781
- console.log(chalk.red(`添加失败: ${response.error || '未知错误'}`));
782
- }
783
- });
784
- // forward remove 子命令
785
- forwardCmd.command('remove')
786
- .description('移除正向穿透代理')
787
- .argument('<localPort>', '本地端口号')
788
- .action(async (localPort) => {
789
- const port = parseInt(localPort, 10);
790
- if (isNaN(port) || port < 1 || port > 65535) {
791
- console.log(chalk.yellow('端口号无效:1-65535'));
792
- return;
793
- }
794
- const response = await sendIpcRequest('forward-remove', { localPort: port });
795
- if (response.success) {
796
- console.log(chalk.green(`本地端口 ${port} 的正向穿透代理已移除`));
797
- }
798
- else {
799
- console.log(chalk.red(`移除失败: ${response.error || '未知错误'}`));
800
- }
801
- });
802
- // forward clients 子命令
803
- forwardCmd.command('clients')
804
- .description('查看在线客户端列表')
805
- .action(async () => {
806
- const response = await sendIpcRequest('forward-clients');
807
- if (!response.success) {
808
- console.log(chalk.yellow(`无法获取客户端列表: ${response.error || '未知错误'}`));
809
- return;
810
- }
811
- const clients = response.clients || [];
812
- if (clients.length === 0) {
813
- console.log(chalk.yellow('暂无在线客户端'));
814
- return;
815
- }
816
- console.log(chalk.blue.bold('在线客户端列表:'));
817
- for (const client of clients) {
818
- const desc = client.description ? ` (${client.description})` : '';
819
- console.log(` ${chalk.cyan(client.id)}${desc}`);
820
- }
821
- });
822
- // forward register 子命令
823
- forwardCmd.command('register')
824
- .description('注册到服务器(启用正向穿透模式)')
825
- .option('-d, --description <desc>', '客户端描述')
826
- .action(async (options) => {
827
- const response = await sendIpcRequest('forward-register', { description: options.description || '' });
828
- if (response.success) {
829
- console.log(chalk.green('已注册到服务器,正向穿透模式已启用'));
830
- }
831
- else {
832
- console.log(chalk.red(`注册失败: ${response.error || '未知错误'}`));
833
- }
834
- });
835
- // ==================== boot 命令 ====================
836
- const bootCmd = program.command('boot')
837
- .description('管理开机自启动')
838
- .argument('[command]', '子命令:enable, disable, status', { default: 'status' });
839
- // boot status 子命令
840
- bootCmd.command('status')
841
- .description('查看开机自启动状态')
842
- .action(async () => {
843
- const activeLevel = getActiveBootLevel();
844
- const hasSystemPriv = hasSystemPrivileges();
845
- console.log(chalk.blue('开机自启动状态:'));
846
- if (activeLevel === 'system') {
847
- console.log(chalk.green(' 状态: 已启用(系统级)'));
848
- console.log(chalk.gray(' 启动时机: 系统启动时(无需登录桌面)'));
849
- console.log(chalk.gray(' 配置路径: ' + (platform() === 'win32' ? 'C:\\ProgramData\\chuantou' : '/etc/chuantou')));
850
- }
851
- else if (activeLevel === 'user') {
852
- console.log(chalk.yellow(' 状态: 已启用(用户级)'));
853
- console.log(chalk.gray(' 启动时机: 用户登录后'));
854
- if (hasSystemPriv) {
855
- console.log(chalk.dim(' 提示: 可升级到系统级启动(登录前启动)'));
856
- }
857
- }
858
- else {
859
- console.log(chalk.yellow(' 状态: 未启用'));
860
- }
861
- // 显示权限状态
862
- if (!activeLevel) {
863
- console.log(chalk.gray(` 当前权限: ${hasSystemPriv ? '有管理员权限(可注册系统级)' : '普通用户(仅可注册用户级)'}`));
864
- }
865
- });
866
- // boot enable 子命令
867
- bootCmd.command('enable')
868
- .description('启用开机自启动(智能选择系统级/用户级)')
869
- .option('--system', '强制使用系统级启动(需要管理员权限)')
870
- .option('--user', '强制使用用户级启动(登录后启动)')
871
- .action(async (options) => {
872
- const info = readPidFile();
873
- if (!info) {
874
- console.log(chalk.yellow('客户端未启动过,请先使用 start 命令启动'));
205
+ child.unref();
206
+ console.log(chalk.green(`客户端已在后台启动(PID: ${child.pid})`));
207
+ console.log(chalk.gray(`日志: ${LOG_FILE}`));
208
+ console.log(chalk.gray(`停止: ${platform() === 'win32' ? `taskkill /F /PID ${child.pid}` : `kill ${child.pid}`}`));
209
+ setTimeout(() => process.exit(0), 100);
210
+ }
211
+ /**
212
+ * 清理已失效的 PID 文件(对应进程已不存在)
213
+ */
214
+ function cleanupStalePid(pidFile) {
215
+ if (!existsSync(pidFile))
875
216
  return;
876
- }
877
217
  try {
878
- const level = options.system ? 'system' : options.user ? 'user' : 'auto';
879
- const result = registerBoot({
880
- isServer: false,
881
- nodePath,
882
- scriptPath: daemonEntryPath,
883
- args: info.args || [],
884
- }, { level });
885
- if (result.level === 'system') {
886
- console.log(chalk.green('开机自启动已启用(系统级)'));
887
- console.log(chalk.gray(' 启动时机: 系统启动时(无需登录桌面)'));
888
- console.log(chalk.gray(' 配置路径: ' + (platform() === 'win32' ? 'C:\\ProgramData\\chuantou' : '/etc/chuantou')));
889
- }
890
- else {
891
- console.log(chalk.green('开机自启动已启用(用户级)'));
892
- console.log(chalk.gray(' 启动时机: 用户登录后'));
893
- if (result.needsElevation) {
894
- console.log(chalk.yellow(' 提示: 当前为用户级启动。如需登录前启动,请以管理员/root权限重试:'));
895
- console.log(chalk.gray(` ${platform() === 'win32' ? '右键 → 以管理员身份运行' : 'sudo npx @feng3d/ctc boot enable'}`));
896
- }
218
+ const pid = parseInt(readFileSync(pidFile, 'utf-8').trim(), 10);
219
+ if (pid) {
220
+ process.kill(pid, 0);
897
221
  }
898
222
  }
899
- catch (err) {
900
- console.log(chalk.red(`启用失败: ${err.message}`));
901
- }
902
- });
903
- // boot disable 子命令
904
- bootCmd.command('disable')
905
- .description('禁用开机自启动(自动检测并禁用当前级别)')
906
- .option('--system', '禁用系统级启动')
907
- .option('--user', '禁用用户级启动')
908
- .action(async (options) => {
909
- try {
910
- const level = options.system ? 'system' : options.user ? 'user' : 'auto';
911
- unregisterBoot(undefined, { level });
912
- console.log(chalk.green('已禁用开机自启动'));
913
- }
914
- catch (err) {
915
- console.log(chalk.red(`禁用失败: ${err.message}`));
916
- }
917
- });
918
- // ==================== open 命令 ====================
919
- const openCmd = program.command('open')
920
- .description('在浏览器中打开管理页面')
921
- .action(async () => {
922
- const info = readPidFile();
923
- const adminPort = info?.adminPort ?? ADMIN_PORT_DEFAULT;
924
- const adminPage = `http://127.0.0.1:${adminPort}`;
925
- const openCmd = platform() === 'win32' ? 'start' : 'open';
926
- console.log(chalk.gray(`打开管理页面: ${adminPage}`));
927
- try {
928
- execSync(`${openCmd} ${adminPage}`, { stdio: 'ignore' });
929
- console.log(chalk.green('管理页面已在浏览器中打开'));
930
- }
931
- catch (err) {
932
- console.log(chalk.yellow(`提示: 请确保客户端正在运行`));
933
- }
934
- });
935
- // ==================== logs 命令 ====================
936
- const logsCmd = program.command('logs')
937
- .description('查看或跟踪日志')
938
- .option('-f, --follow', '跟踪日志输出(类似 tail -f)')
939
- .action(async (options) => {
940
- if (!existsSync(LOG_FILE)) {
941
- console.log(chalk.yellow('日志文件不存在'));
942
- return;
943
- }
944
- if (options.follow) {
945
- console.log(chalk.blue('跟踪日志输出 (Ctrl+C 退出)...'));
946
- console.log(chalk.dim('---'));
947
- const logFd = openSync(LOG_FILE, 'r');
948
- const buffer = Buffer.alloc(1024);
949
- let pos = 0;
950
- const readLog = () => {
951
- try {
952
- const bytesRead = readSync(logFd, buffer, 0, buffer.length, pos);
953
- if (bytesRead > 0) {
954
- const content = buffer.toString('utf-8', 0, bytesRead);
955
- process.stdout.write(content);
956
- pos += bytesRead;
957
- }
958
- }
959
- catch {
960
- // ignore
961
- }
962
- };
963
- // 读取最新内容
964
- readLog();
965
- // 监控文件变化
966
- const watcher = () => {
967
- try {
968
- const stat = statSync(LOG_FILE);
969
- const newSize = stat.size;
970
- if (newSize > pos) {
971
- readLog();
972
- }
973
- }
974
- catch (err) {
975
- // ignore
976
- }
977
- };
978
- // 每秒检查一次
979
- const interval = setInterval(watcher, 1000);
980
- // 处理退出
981
- process.on('SIGINT', () => {
982
- clearInterval(interval);
983
- closeSync(logFd);
984
- process.stdout.write('\n');
985
- console.log(chalk.gray('\n--- 日志跟踪已结束'));
986
- process.exit(0);
987
- });
988
- }
989
- else {
990
- // 显示所有日志
991
- const content = readFileSync(LOG_FILE, 'utf-8');
992
- console.log(chalk.blue('最近日志:'));
993
- console.log(chalk.dim('---'));
994
- console.log(content.split('\n').slice(-30).join('\n'));
995
- console.log(chalk.dim('---'));
996
- console.log(chalk.gray(`(日志文件:${LOG_FILE})`));
223
+ catch {
224
+ try {
225
+ unlinkSync(pidFile);
226
+ }
227
+ catch { /* ignore */ }
997
228
  }
998
- });
999
- // ==================== 默认处理 ====================
1000
- // 当没有指定命令时显示帮助
1001
- program.action(() => {
1002
- showHelp();
1003
- });
1004
- // 解析命令行参数
1005
- program.parse();
229
+ }
1006
230
  //# sourceMappingURL=cli.js.map