baton-host 0.1.8 → 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 (2) hide show
  1. package/bin/baton-host.js +22 -770
  2. package/package.json +5 -5
package/bin/baton-host.js CHANGED
@@ -1,11 +1,7 @@
1
1
  #!/usr/bin/env node
2
2
 
3
- const { spawn, spawnSync } = require("node:child_process");
4
- const fs = require("node:fs");
5
- const net = require("node:net");
6
- const os = require("node:os");
3
+ const { spawn } = require("node:child_process");
7
4
  const path = require("node:path");
8
- const { createInterface } = require("node:readline/promises");
9
5
 
10
6
  const mapping = {
11
7
  "darwin-arm64": "baton-host-darwin-arm64",
@@ -14,781 +10,37 @@ const mapping = {
14
10
  "linux-x64": "baton-host-linux-x64"
15
11
  };
16
12
 
17
- const SERVICE_LABEL = "com.baton.host";
18
- const INSTALL_ROOT = path.join(os.homedir(), ".baton-host");
19
- const INSTALL_BIN_DIR = path.join(INSTALL_ROOT, "bin");
20
- const INSTALL_LOG_DIR = path.join(INSTALL_ROOT, "logs");
21
- const ENV_FILE_PATH = path.join(INSTALL_ROOT, ".env");
22
- const BRIDGE_INFO_PATH = path.join(INSTALL_ROOT, "bridge-info.json");
23
- const WRAPPER_PATH = path.join(INSTALL_ROOT, "run.sh");
24
- const INSTALL_META_PATH = path.join(INSTALL_ROOT, "install.json");
13
+ const key = `${process.platform}-${process.arch}`;
14
+ const pkg = mapping[key];
25
15
 
26
- function fail(message) {
27
- console.error(`❌ ${message}`);
16
+ if (!pkg) {
17
+ console.error(`❌ 当前平台暂不支持: ${key}`);
28
18
  process.exit(1);
29
19
  }
30
20
 
31
- function getCurrentPlatformKey() {
32
- return `${process.platform}-${process.arch}`;
33
- }
34
-
35
- function getMainPackageVersion() {
36
- const packageJsonPath = path.join(__dirname, "..", "package.json");
37
- const packageJson = JSON.parse(fs.readFileSync(packageJsonPath, "utf8"));
38
- return packageJson.version;
39
- }
40
-
41
- function resolveBundledAssets() {
42
- const key = getCurrentPlatformKey();
43
- const pkg = mapping[key];
44
-
45
- if (!pkg) {
46
- fail(`当前平台暂不支持: ${key}`);
47
- }
48
-
49
- let pkgJsonPath;
50
- try {
51
- pkgJsonPath = require.resolve(`${pkg}/package.json`);
52
- } catch (error) {
53
- fail(`未找到平台二进制包 ${pkg},请重新执行 npx baton-host@latest service install`);
54
- }
55
-
56
- const binaryPath = path.join(path.dirname(pkgJsonPath), "bin", "baton-host");
57
- const cloudflaredPath = path.join(
58
- path.dirname(binaryPath),
59
- process.platform === "win32" ? "cloudflared.exe" : "cloudflared"
60
- );
61
-
62
- if (!fs.existsSync(binaryPath)) {
63
- fail(`缺少 Baton Host 二进制: ${binaryPath}`);
64
- }
65
-
66
- if (!fs.existsSync(cloudflaredPath)) {
67
- fail(`缺少 cloudflared 二进制: ${cloudflaredPath}`);
68
- }
69
-
70
- return {
71
- binaryPath,
72
- cloudflaredPath,
73
- version: getMainPackageVersion()
74
- };
75
- }
76
-
77
- function ensureDir(dirPath) {
78
- fs.mkdirSync(dirPath, { recursive: true });
79
- }
80
-
81
- function copyExecutable(sourcePath, targetPath) {
82
- fs.copyFileSync(sourcePath, targetPath);
83
- fs.chmodSync(targetPath, 0o755);
84
- }
85
-
86
- function readInstallMeta() {
87
- if (!fs.existsSync(INSTALL_META_PATH)) {
88
- return null;
89
- }
90
-
91
- try {
92
- return JSON.parse(fs.readFileSync(INSTALL_META_PATH, "utf8"));
93
- } catch {
94
- return null;
95
- }
96
- }
97
-
98
- function writeInstallMeta(version) {
99
- const payload = {
100
- version,
101
- installedAt: new Date().toISOString(),
102
- platform: process.platform,
103
- arch: process.arch
104
- };
105
- fs.writeFileSync(INSTALL_META_PATH, `${JSON.stringify(payload, null, 2)}\n`, "utf8");
106
- }
107
-
108
- function ensureDefaultEnvFile() {
109
- if (fs.existsSync(ENV_FILE_PATH)) {
110
- return;
111
- }
112
-
113
- const defaultContent = [
114
- "# Baton Host 服务环境变量",
115
- "BATON_BRIDGE_MODE=cloudflare",
116
- "BRIDGE_LOG_PROFILE=core",
117
- "PORT=9977",
118
- ""
119
- ].join("\n");
120
-
121
- fs.writeFileSync(ENV_FILE_PATH, defaultContent, "utf8");
122
- }
123
-
124
- function readEnvFile() {
125
- if (!fs.existsSync(ENV_FILE_PATH)) {
126
- return {};
127
- }
128
-
129
- const result = {};
130
- const content = fs.readFileSync(ENV_FILE_PATH, "utf8");
131
- for (const rawLine of content.split(/\r?\n/)) {
132
- const line = rawLine.trim();
133
- if (!line || line.startsWith("#")) {
134
- continue;
135
- }
136
- const separatorIndex = line.indexOf("=");
137
- if (separatorIndex <= 0) {
138
- continue;
139
- }
140
- const key = line.slice(0, separatorIndex).trim();
141
- const value = line.slice(separatorIndex + 1).trim();
142
- result[key] = value;
143
- }
144
- return result;
145
- }
146
-
147
- function writeEnvFile(envVars) {
148
- const existingContent = fs.existsSync(ENV_FILE_PATH)
149
- ? fs.readFileSync(ENV_FILE_PATH, "utf8")
150
- : "# Baton Host 服务环境变量\n";
151
- const lines = existingContent.split(/\r?\n/);
152
- const keysToWrite = new Set(Object.keys(envVars));
153
- const seenKeys = new Set();
154
- const nextLines = lines.map((rawLine) => {
155
- const trimmed = rawLine.trim();
156
- if (!trimmed || trimmed.startsWith("#")) {
157
- return rawLine;
158
- }
159
- const separatorIndex = rawLine.indexOf("=");
160
- if (separatorIndex <= 0) {
161
- return rawLine;
162
- }
163
- const key = rawLine.slice(0, separatorIndex).trim();
164
- if (!keysToWrite.has(key)) {
165
- return rawLine;
166
- }
167
- seenKeys.add(key);
168
- return `${key}=${envVars[key]}`;
169
- });
170
-
171
- for (const key of keysToWrite) {
172
- if (!seenKeys.has(key)) {
173
- nextLines.push(`${key}=${envVars[key]}`);
174
- }
175
- }
176
-
177
- const content = `${nextLines.filter((line, index, array) => !(index === array.length - 1 && line === "")).join("\n")}\n`;
178
- fs.writeFileSync(ENV_FILE_PATH, content, "utf8");
179
- }
180
-
181
- function isInteractiveTerminal() {
182
- return Boolean(process.stdin.isTTY && process.stdout.isTTY);
183
- }
184
-
185
- function pickAvailablePort() {
186
- return new Promise((resolve, reject) => {
187
- const server = net.createServer();
188
- server.unref();
189
- server.on("error", reject);
190
- server.listen(0, "127.0.0.1", () => {
191
- const address = server.address();
192
- if (!address || typeof address === "string") {
193
- server.close(() => reject(new Error("随机端口分配失败")));
194
- return;
195
- }
196
- resolve(address.port);
197
- server.close();
198
- });
199
- });
200
- }
201
-
202
- function isValidPort(value) {
203
- const port = Number(value);
204
- return Number.isInteger(port) && port >= 1 && port <= 65535;
205
- }
206
-
207
- async function ensurePortAvailable(port) {
208
- await new Promise((resolve, reject) => {
209
- const server = net.createServer();
210
- server.unref();
211
- server.once("error", reject);
212
- server.listen(port, "127.0.0.1", () => {
213
- server.close((error) => {
214
- if (error) {
215
- reject(error);
216
- return;
217
- }
218
- resolve();
219
- });
220
- });
221
- });
222
- return port;
21
+ let binaryPath;
22
+ try {
23
+ const pkgJsonPath = require.resolve(`${pkg}/package.json`);
24
+ binaryPath = path.join(path.dirname(pkgJsonPath), "bin", "baton-host");
25
+ } catch (error) {
26
+ console.error(`❌ 未找到平台二进制包 ${pkg},请重装 baton-host`);
27
+ process.exit(1);
223
28
  }
224
29
 
225
- async function promptBridgeModeForInstall() {
226
- if (!isInteractiveTerminal()) {
227
- return "cloudflare";
228
- }
229
-
230
- const rl = createInterface({
231
- input: process.stdin,
232
- output: process.stdout
233
- });
30
+ const bundledCloudflaredPath = path.join(path.dirname(binaryPath), process.platform === "win32" ? "cloudflared.exe" : "cloudflared");
234
31
 
235
- try {
236
- while (true) {
237
- console.log("请选择连接方式:");
238
- console.log("1) 局域网(同一 Wi‑Fi 下用)");
239
- console.log("2) Cloudflare(推荐,直接回车也选这个)");
240
- console.log("3) Tailscale");
241
- const answer = (await rl.question("输入 1 / 2 / 3,直接回车默认 Cloudflare: ")).trim();
242
- if (!answer || answer === "2") {
243
- return "cloudflare";
244
- }
245
- if (answer === "1") {
246
- return "lan";
247
- }
248
- if (answer === "3") {
249
- return "tailscale";
250
- }
251
- console.log("⚠️ 请输入 1、2、3,或直接回车。\n");
252
- }
253
- } finally {
254
- rl.close();
255
- }
256
- }
257
-
258
- async function promptPortForInstall() {
259
- const randomPort = await pickAvailablePort();
260
- if (!isInteractiveTerminal()) {
261
- return randomPort;
262
- }
263
-
264
- const rl = createInterface({
265
- input: process.stdin,
266
- output: process.stdout
267
- });
268
-
269
- try {
270
- while (true) {
271
- console.log("\n请选择端口:");
272
- console.log(`直接回车:自动分配随机端口(推荐,当前候选 ${randomPort})`);
273
- console.log("输入端口号:使用自定义端口");
274
- const answer = (await rl.question("输入端口号,或直接回车使用随机端口: ")).trim();
275
- if (!answer) {
276
- return randomPort;
277
- }
278
- if (isValidPort(answer)) {
279
- try {
280
- return await ensurePortAvailable(Number(answer));
281
- } catch {
282
- console.log("⚠️ 这个端口当前不可用,请换一个。\n");
283
- continue;
284
- }
285
- }
286
- console.log("⚠️ 请输入 1-65535 的有效端口号,或直接回车。\n");
287
- }
288
- } finally {
289
- rl.close();
290
- }
291
- }
292
-
293
- function printBridgeInfoFromCache() {
294
- if (!fs.existsSync(BRIDGE_INFO_PATH)) {
295
- throw new Error("未找到已保存的连接信息,请稍后重试");
296
- }
297
-
298
- const envVars = readEnvFile();
299
- const env = {
32
+ const child = spawn(binaryPath, process.argv.slice(2), {
33
+ stdio: "inherit",
34
+ env: {
300
35
  ...process.env,
301
- ...envVars,
302
- BATON_CLOUDFLARED_BIN: path.join(INSTALL_BIN_DIR, "cloudflared")
303
- };
304
-
305
- runInheritedCommand(path.join(INSTALL_BIN_DIR, "baton-host"), ["--print-bridge-info"], { env });
306
- }
307
-
308
- async function waitForBridgeInfo(timeoutMs = 15000) {
309
- const start = Date.now();
310
- while (Date.now() - start < timeoutMs) {
311
- if (fs.existsSync(BRIDGE_INFO_PATH)) {
312
- return;
313
- }
314
- await new Promise((resolve) => setTimeout(resolve, 250));
315
- }
316
- throw new Error("等待连接信息生成超时,请稍后执行 service restart 再试");
317
- }
318
-
319
- async function runBridgePrintCommand() {
320
- await waitForBridgeInfo();
321
- printBridgeInfoFromCache();
322
- }
323
-
324
- function buildWrapperScript() {
325
- return `#!/bin/sh
326
- set -eu
327
-
328
- BATON_HOME="$HOME/.baton-host"
329
- ENV_FILE="$BATON_HOME/.env"
330
-
331
- if [ -f "$ENV_FILE" ]; then
332
- while IFS= read -r line || [ -n "$line" ]; do
333
- case "$line" in
334
- ''|'#'*) continue ;;
335
- *=*)
336
- key=\${line%%=*}
337
- value=\${line#*=}
338
- export "$key=$value"
339
- ;;
340
- esac
341
- done < "$ENV_FILE"
342
- fi
343
-
344
- export BATON_CLOUDFLARED_BIN="$BATON_HOME/bin/cloudflared"
345
- export PATH="$HOME/.local/bin:$HOME/Library/pnpm:/opt/homebrew/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin\${PATH:+:$PATH}"
346
-
347
- exec "$BATON_HOME/bin/baton-host" "$@"
348
- `;
349
- }
350
-
351
- function writeWrapperScript() {
352
- fs.writeFileSync(WRAPPER_PATH, buildWrapperScript(), { mode: 0o755 });
353
- fs.chmodSync(WRAPPER_PATH, 0o755);
354
- }
355
-
356
- function escapeXml(value) {
357
- return String(value)
358
- .replaceAll("&", "&amp;")
359
- .replaceAll("<", "&lt;")
360
- .replaceAll(">", "&gt;")
361
- .replaceAll('"', "&quot;")
362
- .replaceAll("'", "&apos;");
363
- }
364
-
365
- function getServicePathEnv() {
366
- return `${os.homedir()}/.local/bin:${os.homedir()}/Library/pnpm:/opt/homebrew/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin`;
367
- }
368
-
369
- function getLinuxServiceName() {
370
- return `${SERVICE_LABEL}.service`;
371
- }
372
-
373
- function getLinuxUnitPath() {
374
- return path.join(os.homedir(), ".config", "systemd", "user", getLinuxServiceName());
375
- }
376
-
377
- function buildLinuxUnit() {
378
- return `[Unit]
379
- Description=Baton Host
380
- After=network-online.target
381
- Wants=network-online.target
382
-
383
- [Service]
384
- Type=simple
385
- ExecStart=%h/.baton-host/run.sh
386
- WorkingDirectory=%h/.baton-host
387
- Restart=always
388
- RestartSec=2
389
- Environment=HOME=%h
390
- Environment=PATH=%h/.local/bin:%h/Library/pnpm:/opt/homebrew/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin
391
-
392
- [Install]
393
- WantedBy=default.target
394
- `;
395
- }
396
-
397
- function getMacPlistPath() {
398
- return path.join(os.homedir(), "Library", "LaunchAgents", `${SERVICE_LABEL}.plist`);
399
- }
400
-
401
- function buildMacPlist() {
402
- const stdoutPath = path.join(INSTALL_LOG_DIR, "stdout.log");
403
- const stderrPath = path.join(INSTALL_LOG_DIR, "stderr.log");
404
- const servicePathEnv = getServicePathEnv();
405
-
406
- return `<?xml version="1.0" encoding="UTF-8"?>
407
- <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
408
- <plist version="1.0">
409
- <dict>
410
- <key>Label</key>
411
- <string>${escapeXml(SERVICE_LABEL)}</string>
412
- <key>ProgramArguments</key>
413
- <array>
414
- <string>${escapeXml(WRAPPER_PATH)}</string>
415
- </array>
416
- <key>WorkingDirectory</key>
417
- <string>${escapeXml(INSTALL_ROOT)}</string>
418
- <key>RunAtLoad</key>
419
- <true/>
420
- <key>KeepAlive</key>
421
- <true/>
422
- <key>ProcessType</key>
423
- <string>Background</string>
424
- <key>EnvironmentVariables</key>
425
- <dict>
426
- <key>HOME</key>
427
- <string>${escapeXml(os.homedir())}</string>
428
- <key>PATH</key>
429
- <string>${escapeXml(servicePathEnv)}</string>
430
- </dict>
431
- <key>StandardOutPath</key>
432
- <string>${escapeXml(stdoutPath)}</string>
433
- <key>StandardErrorPath</key>
434
- <string>${escapeXml(stderrPath)}</string>
435
- </dict>
436
- </plist>
437
- `;
438
- }
439
-
440
- function runCommand(command, args, options = {}) {
441
- const result = spawnSync(command, args, {
442
- encoding: "utf8",
443
- stdio: ["ignore", "pipe", "pipe"]
444
- });
445
-
446
- if (result.error) {
447
- if (options.allowFailure) {
448
- return result;
449
- }
450
- throw result.error;
451
- }
452
-
453
- if (!options.allowFailure && result.status !== 0) {
454
- const output = (result.stderr || result.stdout || "").trim();
455
- throw new Error(output || `${command} ${args.join(" ")} 失败,退出码 ${result.status}`);
456
- }
457
-
458
- return result;
459
- }
460
-
461
- function runInheritedCommand(command, args, options = {}) {
462
- const result = spawnSync(command, args, {
463
- stdio: "inherit",
464
- env: options.env || process.env
465
- });
466
-
467
- if (result.error) {
468
- if (options.allowFailure) {
469
- return result;
470
- }
471
- throw result.error;
472
- }
473
-
474
- if (!options.allowFailure && result.status !== 0) {
475
- throw new Error(`${command} ${args.join(" ")} 失败,退出码 ${result.status}`);
476
- }
477
-
478
- return result;
479
- }
480
-
481
- function installLinuxService() {
482
- const unitPath = getLinuxUnitPath();
483
- ensureDir(path.dirname(unitPath));
484
- fs.writeFileSync(unitPath, buildLinuxUnit(), "utf8");
485
-
486
- runCommand("systemctl", ["--user", "daemon-reload"]);
487
- runCommand("systemctl", ["--user", "enable", getLinuxServiceName()]);
488
-
489
- const restartResult = runCommand(
490
- "systemctl",
491
- ["--user", "restart", getLinuxServiceName()],
492
- { allowFailure: true }
493
- );
494
-
495
- if (restartResult.status !== 0) {
496
- runCommand("systemctl", ["--user", "start", getLinuxServiceName()]);
497
- }
498
-
499
- return unitPath;
500
- }
501
-
502
- function installMacService() {
503
- const plistPath = getMacPlistPath();
504
- const launchTarget = `gui/${process.getuid()}`;
505
- ensureDir(path.dirname(plistPath));
506
- fs.writeFileSync(plistPath, buildMacPlist(), "utf8");
507
-
508
- runCommand("launchctl", ["bootout", launchTarget, plistPath], { allowFailure: true });
509
- runCommand("launchctl", ["bootstrap", launchTarget, plistPath]);
510
- runCommand("launchctl", ["enable", `${launchTarget}/${SERVICE_LABEL}`], { allowFailure: true });
511
- runCommand("launchctl", ["kickstart", "-k", `${launchTarget}/${SERVICE_LABEL}`], {
512
- allowFailure: true
513
- });
514
-
515
- return plistPath;
516
- }
517
-
518
- function removePathIfExists(targetPath) {
519
- if (!fs.existsSync(targetPath)) {
520
- return;
521
- }
522
- fs.rmSync(targetPath, { recursive: true, force: true });
523
- }
524
-
525
- function restartLinuxService() {
526
- if (!fs.existsSync(getLinuxUnitPath())) {
527
- fail("尚未安装 Baton Host systemd 服务,请先执行 npx baton-host@latest service install");
528
- }
529
- runCommand("systemctl", ["--user", "restart", getLinuxServiceName()]);
530
- }
531
-
532
- function restartMacService() {
533
- const plistPath = getMacPlistPath();
534
- if (!fs.existsSync(plistPath)) {
535
- fail("尚未安装 Baton Host LaunchAgent,请先执行 npx baton-host@latest service install");
536
- }
537
- const launchTarget = `gui/${process.getuid()}`;
538
- runCommand("launchctl", ["bootout", launchTarget, plistPath], { allowFailure: true });
539
- runCommand("launchctl", ["bootstrap", launchTarget, plistPath]);
540
- runCommand("launchctl", ["kickstart", "-k", `${launchTarget}/${SERVICE_LABEL}`], {
541
- allowFailure: true
542
- });
543
- }
544
-
545
- function uninstallLinuxService() {
546
- runCommand("systemctl", ["--user", "disable", "--now", getLinuxServiceName()], {
547
- allowFailure: true
548
- });
549
- removePathIfExists(getLinuxUnitPath());
550
- runCommand("systemctl", ["--user", "daemon-reload"], { allowFailure: true });
551
- }
552
-
553
- function uninstallMacService() {
554
- const plistPath = getMacPlistPath();
555
- const launchTarget = `gui/${process.getuid()}`;
556
- runCommand("launchctl", ["bootout", launchTarget, plistPath], { allowFailure: true });
557
- removePathIfExists(plistPath);
558
- }
559
-
560
- function cleanupInstallArtifacts() {
561
- removePathIfExists(path.join(INSTALL_BIN_DIR, "baton-host"));
562
- removePathIfExists(path.join(INSTALL_BIN_DIR, "cloudflared"));
563
- removePathIfExists(INSTALL_BIN_DIR);
564
- removePathIfExists(WRAPPER_PATH);
565
- removePathIfExists(INSTALL_META_PATH);
566
- removePathIfExists(INSTALL_LOG_DIR);
567
-
568
- try {
569
- const remaining = fs.existsSync(INSTALL_ROOT) ? fs.readdirSync(INSTALL_ROOT) : [];
570
- if (remaining.length === 0) {
571
- fs.rmdirSync(INSTALL_ROOT);
572
- }
573
- } catch {}
574
- }
575
-
576
- function readLinuxStatus() {
577
- const installed = fs.existsSync(getLinuxUnitPath());
578
- const enabledResult = installed
579
- ? runCommand("systemctl", ["--user", "is-enabled", getLinuxServiceName()], { allowFailure: true })
580
- : { stdout: "", status: 1 };
581
- const activeResult = installed
582
- ? runCommand("systemctl", ["--user", "is-active", getLinuxServiceName()], { allowFailure: true })
583
- : { stdout: "", status: 1 };
584
-
585
- const enabledState = (enabledResult.stdout || "").trim();
586
- const activeState = (activeResult.stdout || "").trim();
587
-
588
- return {
589
- installed,
590
- loaded: installed && ["enabled", "enabled-runtime", "static", "indirect"].includes(enabledState),
591
- running: activeState === "active",
592
- detail: activeState || enabledState || "not installed",
593
- serviceFile: getLinuxUnitPath()
594
- };
595
- }
596
-
597
- function readMacStatus() {
598
- const plistPath = getMacPlistPath();
599
- const installed = fs.existsSync(plistPath);
600
- const printResult = installed
601
- ? runCommand("launchctl", ["print", `gui/${process.getuid()}/${SERVICE_LABEL}`], { allowFailure: true })
602
- : { stdout: "", stderr: "", status: 1 };
603
-
604
- const output = `${printResult.stdout || ""}\n${printResult.stderr || ""}`;
605
- const pidMatch = output.match(/\bpid = (\d+)/);
606
- const stateMatch = output.match(/\bstate = ([^\n]+)/);
607
-
608
- return {
609
- installed,
610
- loaded: installed && printResult.status === 0,
611
- running: installed && printResult.status === 0 && !!pidMatch && pidMatch[1] !== "0",
612
- detail: stateMatch ? stateMatch[1].trim() : (printResult.status === 0 ? "loaded" : "not loaded"),
613
- serviceFile: plistPath
614
- };
615
- }
616
-
617
- function printServiceStatus() {
618
- const meta = readInstallMeta();
619
- const envVars = readEnvFile();
620
- const platformStatus = process.platform === "linux" ? readLinuxStatus() : readMacStatus();
621
-
622
- console.log("Baton Host Service Status");
623
- console.log("");
624
- console.log(`Installed: ${platformStatus.installed ? "yes" : "no"}`);
625
- console.log(`Loaded: ${platformStatus.loaded ? "yes" : "no"}`);
626
- console.log(`Running: ${platformStatus.running ? "yes" : "no"}`);
627
- console.log(`State: ${platformStatus.detail}`);
628
- if (meta?.version) {
629
- console.log(`Version: ${meta.version}`);
36
+ BATON_CLOUDFLARED_BIN: bundledCloudflaredPath
630
37
  }
631
- console.log(`Mode: ${envVars.BATON_BRIDGE_MODE || "lan"}`);
632
- console.log(`Port: ${envVars.PORT || "9966"}`);
633
- console.log(`Log profile: ${envVars.BRIDGE_LOG_PROFILE || "core"}`);
634
- console.log(`Binary: ${path.join(INSTALL_BIN_DIR, "baton-host")}`);
635
- console.log(`Env file: ${ENV_FILE_PATH}`);
636
- console.log(`Service file: ${platformStatus.serviceFile}`);
637
- }
638
-
639
- function ensureSupportedServicePlatform() {
640
- if (!["linux", "darwin"].includes(process.platform)) {
641
- fail(`当前平台不支持 service 子命令: ${process.platform}`);
642
- }
643
- }
644
-
645
- async function handleServiceInstall(options = {}) {
646
- ensureSupportedServicePlatform();
647
-
648
- const { preserveConfig = false } = options;
649
- const previousVersion = readInstallMeta()?.version || null;
650
- const { binaryPath, cloudflaredPath, version } = resolveBundledAssets();
651
-
652
- ensureDir(INSTALL_ROOT);
653
- ensureDir(INSTALL_BIN_DIR);
654
- ensureDir(INSTALL_LOG_DIR);
655
- ensureDefaultEnvFile();
656
-
657
- if (preserveConfig) {
658
- const envVars = readEnvFile();
659
- if (!envVars.BATON_BRIDGE_MODE || !envVars.PORT) {
660
- fail("现有配置不完整,无法直接 upgrade。请先执行 npx baton-host@latest service install");
661
- }
662
- } else {
663
- const mode = await promptBridgeModeForInstall();
664
- const port = await promptPortForInstall();
665
- writeEnvFile({
666
- BATON_BRIDGE_MODE: mode,
667
- PORT: String(port)
668
- });
669
- }
670
-
671
- copyExecutable(binaryPath, path.join(INSTALL_BIN_DIR, "baton-host"));
672
- copyExecutable(cloudflaredPath, path.join(INSTALL_BIN_DIR, "cloudflared"));
673
- writeWrapperScript();
674
- writeInstallMeta(version);
675
-
676
- const serviceFile = process.platform === "linux" ? installLinuxService() : installMacService();
677
- const action = preserveConfig
678
- ? (previousVersion && previousVersion !== version ? "升级并重启" : "覆盖并重启")
679
- : (previousVersion ? "覆盖并重启" : "安装并启动");
680
-
681
- console.log(`✅ Baton Host 服务已${action}`);
682
- console.log(`Version: ${version}`);
683
- console.log(`Env file: ${ENV_FILE_PATH}`);
684
- console.log(`Service file: ${serviceFile}`);
685
- await runBridgePrintCommand();
686
- }
687
-
688
- async function handleServiceRestart() {
689
- ensureSupportedServicePlatform();
690
- if (process.platform === "linux") {
691
- restartLinuxService();
692
- } else {
693
- restartMacService();
694
- }
695
- console.log("✅ Baton Host 服务已重启");
696
- await runBridgePrintCommand();
697
- }
698
-
699
- function handleServiceUninstall() {
700
- ensureSupportedServicePlatform();
701
- if (process.platform === "linux") {
702
- uninstallLinuxService();
703
- } else {
704
- uninstallMacService();
705
- }
706
- cleanupInstallArtifacts();
707
- console.log("✅ Baton Host 服务已卸载");
708
- console.log(`保留配置文件: ${ENV_FILE_PATH}`);
709
- }
710
-
711
- function printServiceUsage() {
712
- console.log("Usage:");
713
- console.log(" npx baton-host@latest service install");
714
- console.log(" npx baton-host@latest service upgrade");
715
- console.log(" npx baton-host@latest service restart");
716
- console.log(" npx baton-host@latest service status");
717
- console.log(" npx baton-host@latest service uninstall");
718
- console.log(" npx baton-host@latest service help");
719
- console.log("");
720
- console.log("配置文件: ~/.baton-host/.env");
721
- console.log(" BATON_BRIDGE_MODE=lan|tailscale|cloudflare");
722
- console.log(" PORT=9966");
723
- console.log("");
724
- console.log("说明: install 会进入模式/端口向导;upgrade 复用现有配置并重启服务");
725
- }
726
-
727
- async function handleServiceCommand(args) {
728
- const command = args[0] || "install";
729
-
730
- if (command === "install") {
731
- await handleServiceInstall();
732
- return;
733
- }
734
-
735
- if (command === "upgrade") {
736
- await handleServiceInstall({ preserveConfig: true });
737
- return;
738
- }
739
-
740
- if (command === "restart") {
741
- await handleServiceRestart();
742
- return;
743
- }
744
-
745
- if (command === "status") {
746
- printServiceStatus();
747
- return;
748
- }
749
-
750
- if (command === "uninstall") {
751
- handleServiceUninstall();
752
- return;
753
- }
754
-
755
- if (command === "help" || command === "--help" || command === "-h") {
756
- printServiceUsage();
757
- return;
758
- }
759
-
760
- printServiceUsage();
761
- process.exit(1);
762
- }
763
-
764
- function spawnHostBinary(args) {
765
- const { binaryPath, cloudflaredPath } = resolveBundledAssets();
766
- const child = spawn(binaryPath, args, {
767
- stdio: "inherit",
768
- env: {
769
- ...process.env,
770
- BATON_CLOUDFLARED_BIN: cloudflaredPath
771
- }
772
- });
773
-
774
- child.on("exit", (code, signal) => {
775
- if (signal) {
776
- process.kill(process.pid, signal);
777
- return;
778
- }
779
- process.exit(code ?? 0);
780
- });
781
- }
38
+ });
782
39
 
783
- async function main() {
784
- const args = process.argv.slice(2);
785
- if (args[0] === "service") {
786
- await handleServiceCommand(args.slice(1));
40
+ child.on("exit", (code, signal) => {
41
+ if (signal) {
42
+ process.kill(process.pid, signal);
787
43
  return;
788
44
  }
789
- spawnHostBinary(args);
790
- }
791
-
792
- void main().catch((error) => {
793
- fail(error instanceof Error ? error.message : String(error));
45
+ process.exit(code ?? 0);
794
46
  });
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "baton-host",
3
- "version": "0.1.8",
3
+ "version": "0.2.0",
4
4
  "description": "Baton Bridge Host CLI(二进制分发入口)",
5
5
  "license": "MIT",
6
6
  "bin": {
@@ -10,9 +10,9 @@
10
10
  "bin"
11
11
  ],
12
12
  "optionalDependencies": {
13
- "baton-host-darwin-arm64": "0.1.8",
14
- "baton-host-darwin-x64": "0.1.8",
15
- "baton-host-linux-arm64": "0.1.8",
16
- "baton-host-linux-x64": "0.1.8"
13
+ "baton-host-darwin-arm64": "0.2.0",
14
+ "baton-host-darwin-x64": "0.2.0",
15
+ "baton-host-linux-arm64": "0.2.0",
16
+ "baton-host-linux-x64": "0.2.0"
17
17
  }
18
18
  }