-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathcli.ts
More file actions
executable file
·791 lines (705 loc) · 31.9 KB
/
Copy pathcli.ts
File metadata and controls
executable file
·791 lines (705 loc) · 31.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
#!/usr/bin/env bun
/**
* forge-hub CLI — package-level setup / install / doctor.
*
* 注意:这是**安装管理**入口,不是日常 hub 操作。日常用 `fh hub *`(forge-cli/forge.ts)。
*
* Commands:
* forge-hub install 一键部署 hub-server + hub-client + launchd plist + MCP 注册
* forge-hub uninstall 反向操作(保留 ~/.forge-hub state,不删 allowlist 等)
* forge-hub doctor 诊断 install 状态 + connectivity
* forge-hub --help 帮助
*/
import * as fs from "node:fs";
import * as path from "node:path";
import * as os from "node:os";
import * as crypto from "node:crypto";
import { execFileSync } from "node:child_process";
import { fileURLToPath } from "node:url";
import {
parseHubStatusResponse,
parsePublicHealthResponse,
} from "./forge-cli/doctor.js";
const HOME = os.homedir();
const HUB_DIR = path.join(HOME, ".forge-hub");
const PACKAGE_RUNTIME = path.join(HUB_DIR, "package");
const CHANNELS_RUNTIME = path.join(HOME, ".forge-hub", "channels");
const HUB_CLIENT_RUNTIME = path.join(HOME, ".claude", "channels", "hub");
const HUB_DASHBOARD_RUNTIME = path.join(HUB_DIR, "hub-dashboard");
const LAUNCHD_PLIST = path.join(HOME, "Library", "LaunchAgents", "com.forge-hub.plist");
const CLAUDE_JSON = path.join(HOME, ".claude.json");
const API_TOKEN_FILE = path.join(HUB_DIR, "api-token");
export const HUB_INSTALL_PRESERVE_ENTRIES = [
"state",
"hub-config.json",
"lock-phrase.json",
"lock.json",
"api-token",
"hub.log",
"hub.log.1",
"hub.log.2",
"hub.log.3",
"hub-stderr.log",
"hub.pid",
"package",
"sendable",
"evidence",
"security-events.jsonl",
"audit.jsonl",
"engine-data",
"server",
"_legacy",
"hub-client.log",
".DS_Store",
];
// 用户运行时配置——sync 时绝不允许从源码 cpDir 覆盖。
// (install 走 cleanDirContents preserve set,sync 不 clean 但要防同名 .json 静默覆盖。)
const SYNC_SKIP = new Set(["hub-config.json", "lock-phrase.json", "lock.json"]);
// 找包根目录(从 cli.ts 的位置反推)
const PKG_ROOT = path.dirname(fileURLToPath(import.meta.url));
function log(msg: string): void { console.log(msg); }
function die(msg: string): never { console.error(`❌ ${msg}`); process.exit(1); }
function resolveBunPath(): string {
return process.execPath && process.execPath.includes("bun")
? process.execPath
: which("bun") ?? "bun";
}
// ── install ─────────────────────────────────────────────────────────────────
function installCmd(): void {
log("🔧 Forge Hub install\n");
const bunPath = resolveBunPath();
// 1. Check Bun
try {
execFileSync(bunPath, ["--version"], { stdio: "ignore" });
} catch {
die("Bun 未安装。请先安装 Bun: https://bun.sh/docs/installation");
}
log("✓ Bun 已安装");
const packageRoot = stagePackageRuntime();
const configDoc = path.join(packageRoot, "配置.md");
// 2. Install hub-server
// redteam r2 M1: mkdirSync 带 mode 0o700,缩小 mkdir 默认 0o755 到 chmod
// 0o700 之间的窗口(attacker 可在此毫秒级窗口写 api-token symlink 预埋)。
fs.mkdirSync(CHANNELS_RUNTIME, { recursive: true, mode: 0o700 });
cleanDirContents(HUB_DIR, new Set(HUB_INSTALL_PRESERVE_ENTRIES));
cleanDirContents(CHANNELS_RUNTIME);
const serverSrc = path.join(packageRoot, "hub-server");
copyFilteredTree(serverSrc, HUB_DIR, [".ts", ".json", ".lock"]);
cpDir(path.join(serverSrc, "channels"), CHANNELS_RUNTIME, [".ts"]);
// Security (redteam B3): chmod 700 CHANNELS_RUNTIME——防其他 user-level 进程
// 写入恶意 plugin。fs.watch 已默认关闭(hub-server/channel-loader.ts),
// 目录权限是第二层防御。
try {
fs.chmodSync(HUB_DIR, 0o700);
fs.chmodSync(CHANNELS_RUNTIME, 0o700);
} catch (err) {
console.warn(`⚠️ chmod 700 失败: ${String(err)}`);
}
log(`✓ hub-server 部署到 ${HUB_DIR} (chmod 700)`);
// 3. Install hub-client
fs.rmSync(HUB_CLIENT_RUNTIME, { recursive: true, force: true });
fs.mkdirSync(HUB_CLIENT_RUNTIME, { recursive: true });
const clientSrc = path.join(packageRoot, "hub-client");
cpDir(clientSrc, HUB_CLIENT_RUNTIME, [".ts", ".json", ".lock", ".mcp.json"]);
log(`✓ hub-client 部署到 ${HUB_CLIENT_RUNTIME}`);
// 3.5 Install dashboard source so Hub can serve a built dist at runtime
const dashboardSrc = path.join(packageRoot, "hub-dashboard");
fs.rmSync(HUB_DASHBOARD_RUNTIME, { recursive: true, force: true });
copyFilteredTree(dashboardSrc, HUB_DASHBOARD_RUNTIME, [".ts", ".tsx", ".js", ".json", ".css", ".html", ".svg", ".lock", ".md"]);
log(`✓ hub-dashboard 源码部署到 ${HUB_DASHBOARD_RUNTIME}`);
// 4. Install dependencies
log("⏳ 安装依赖(bun install)...");
try {
execFileSync(bunPath, ["install"], { cwd: HUB_DIR, stdio: "inherit" });
execFileSync(bunPath, ["install"], { cwd: HUB_CLIENT_RUNTIME, stdio: "inherit" });
execFileSync(bunPath, ["install"], { cwd: HUB_DASHBOARD_RUNTIME, stdio: "inherit" });
} catch (err) {
die(`依赖安装失败: ${String(err)}\n部署未完成——运行时文件已复制但依赖未装。请手动在 ${HUB_DIR}、${HUB_CLIENT_RUNTIME}、${HUB_DASHBOARD_RUNTIME} 运行 bun install 后重试。`);
}
log("✓ 依赖装好");
log("⏳ 构建 dashboard...");
try {
execFileSync(bunPath, ["run", "build"], { cwd: HUB_DASHBOARD_RUNTIME, stdio: "inherit" });
} catch (err) {
die(`Dashboard 构建失败: ${String(err)}\n依赖已装,但 dashboard 未构建。请手动在 ${HUB_DASHBOARD_RUNTIME} 运行 bun run build。`);
}
log("✓ hub-dashboard dist 已构建");
// 5. Write launchd plist (Mac only)
if (os.platform() === "darwin") {
const plist = `<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>Label</key>
<string>com.forge-hub</string>
<key>ProgramArguments</key>
<array>
<string>${bunPath}</string>
<string>${path.join(HUB_DIR, "hub.ts")}</string>
</array>
<key>RunAtLoad</key>
<true/>
<key>KeepAlive</key>
<true/>
<key>ThrottleInterval</key>
<integer>30</integer>
<key>StandardOutPath</key>
<string>${path.join(HUB_DIR, "hub.log")}</string>
<key>StandardErrorPath</key>
<string>${path.join(HUB_DIR, "hub-stderr.log")}</string>
<key>EnvironmentVariables</key>
<dict>
<key>PATH</key>
<string>/opt/homebrew/bin:/usr/local/bin:/usr/bin:/bin</string>
</dict>
</dict>
</plist>
`;
fs.mkdirSync(path.dirname(LAUNCHD_PLIST), { recursive: true });
fs.writeFileSync(LAUNCHD_PLIST, plist, "utf-8");
log(`✓ launchd plist 写入 ${LAUNCHD_PLIST}`);
// Bootstrap
try {
const uid = String(process.getuid?.() ?? 501);
try { execFileSync("launchctl", ["bootout", `gui/${uid}/com.forge-hub`], { stdio: "ignore" }); } catch {}
execFileSync("launchctl", ["bootstrap", `gui/${uid}`, LAUNCHD_PLIST], { stdio: "inherit" });
log("✓ Hub Server 已启动(launchd)");
} catch (err) {
console.warn(`⚠️ launchctl bootstrap 失败: ${String(err)}\n 你可以手动跑:launchctl bootstrap gui/$(id -u) ${LAUNCHD_PLIST}`);
}
} else {
log(`ℹ️ 非 macOS 平台(${os.platform()}),跳过 launchd 配置。请用 systemd / supervisor / pm2 等保活 \`bun ${HUB_DIR}/hub.ts\``);
}
// 6. Register MCP server in ~/.claude.json
registerMcp();
log("✓ MCP server 已注册到 ~/.claude.json");
// 6.5 Sync HUB_API_TOKEN from env to ~/.forge-hub/api-token (chmod 600).
// MCP subprocess inherits Claude Code env, not Hub's launchd env, so we can't
// rely on env alone. The file gives hub-client / forge CLI a canonical fallback.
// Rerun `forge-hub install` (or write the file manually) if you rotate the token.
syncApiTokenFile();
// 6.6 Create $HUB_DIR/sendable/ for /send-file path sandbox (redteam B2).
// 任何本地文件必须放这里才能被 /send-file 发出;HTTP(S) URL 不受此限制。
try {
const sendableDir = path.join(HUB_DIR, "sendable");
fs.mkdirSync(sendableDir, { recursive: true });
fs.chmodSync(sendableDir, 0o700);
log(`✓ sendable 目录创建: ${sendableDir} (chmod 700)`);
} catch (err) {
console.warn(`⚠️ sendable 目录创建失败: ${String(err)}`);
}
// 7. Symlink short alias `fh` for daily `fh hub allow` etc.
// 之前用 `forge`——但和 Foundry (Ethereum 生态,200k+ stars) 的主命令冲突
// (redteam 终审 P1-2)。改 `fh` 名字冲突概率接近零,且仍短。
// 清理老的 `forge` symlink(如果存在)避免留孤儿。
const fhBin = path.join(HOME, "bin", "fh");
const oldForgeBin = path.join(HOME, "bin", "forge");
try {
fs.mkdirSync(path.dirname(fhBin), { recursive: true });
// 清理老 forge symlink(只删指向本包的那种,避免误删用户其他 forge 工具)
try {
if (fs.lstatSync(oldForgeBin).isSymbolicLink()) {
const target = fs.readlinkSync(oldForgeBin);
if (target.includes("forge-hub") || target.includes("forge-cli/forge.ts")) {
fs.unlinkSync(oldForgeBin);
log(`✓ 清理老 symlink ~/bin/forge(指向本包)`);
}
}
} catch { /* 不存在 / 其他工具的 forge 都不管 */ }
if (fs.existsSync(fhBin)) fs.unlinkSync(fhBin);
fs.symlinkSync(path.join(packageRoot, "forge-cli", "forge.ts"), fhBin);
log(`✓ fh CLI symlink: ${fhBin}(用 \`fh hub allow/status/peers\` 等)`);
// S1b: surface approval_channels prerequisite for server:hub mode.
// Without this hint, first-time users launching with `--dangerously-load-development-channels
// server:hub` will hit auto-deny on every Bash tool call (no approval_channels → 503 →
// hub-channel autoDenyPermission), with no clue what to fix.
try {
const hubConfigPath = path.join(HUB_DIR, "hub-config.json");
const cfg = fs.existsSync(hubConfigPath)
? JSON.parse(fs.readFileSync(hubConfigPath, "utf-8"))
: {};
const approvalChannels = Array.isArray(cfg.approval_channels) ? cfg.approval_channels : [];
if (approvalChannels.length === 0) {
log("");
log("💡 提示:要用 server:hub 模式(远程审批 → 手机)需要配 approval_channels:");
log(" 编辑 ~/.forge-hub/hub-config.json 加:");
log(' { "approval_channels": ["wechat"] } // 或你配好的其他通道');
log(" 不配的话,server:hub 模式下所有需要审批的工具会被 auto-deny。详见 配置.md §审批推送配置。");
}
} catch { /* cfg 读取失败不阻塞 install,doctor 会再次报 */ }
} catch (err) {
console.warn(`⚠️ fh symlink 失败: ${String(err)}\n 你可以手动: ln -sf ${path.join(packageRoot, "forge-cli/forge.ts")} ${fhBin}`);
}
// 7.5 symlink `forge-hub` 指向 cli.ts——让文档里的 `forge-hub install/uninstall/doctor`
// 变成真能跑的命令(首次 bootstrap 必须 `bun cli.ts install`,之后走 symlink)。
const forgeHubBin = path.join(HOME, "bin", "forge-hub");
try {
if (fs.existsSync(forgeHubBin)) fs.unlinkSync(forgeHubBin);
fs.symlinkSync(path.join(packageRoot, "cli.ts"), forgeHubBin);
log(`✓ forge-hub CLI symlink: ${forgeHubBin}(用 \`forge-hub install/uninstall/doctor\`)`);
} catch (err) {
console.warn(`⚠️ forge-hub symlink 失败: ${String(err)}\n 你可以手动: ln -sf ${path.join(packageRoot, "cli.ts")} ${forgeHubBin}`);
}
// redteam r2 L4: 检测 ~/bin 在不在 PATH。现代 macOS 默认 zsh PATH 不含
// $HOME/bin,新用户 install 完跑 `fh hub status` 会 command not found,
// 第一印象灾难。显式提示加 export。
const homeBinDir = path.dirname(fhBin);
const pathDirs = (process.env.PATH ?? "").split(":");
if (!pathDirs.includes(homeBinDir)) {
log(`
⚠️ 注意:${homeBinDir} 不在你的 PATH——\`fh\` 命令将无法直接调用。
加到 shell 配置(zsh 默认):
echo 'export PATH="$HOME/bin:$PATH"' >> ~/.zshrc && source ~/.zshrc
然后重开 shell 或 source,再跑 \`fh hub status\` 验证。`);
}
log(`
✅ Install 完成
下一步:
1. 配通道凭证(微信 / Telegram / 飞书 / iMessage,按你要用的配一个就行)
→ ${configDoc}
2. 启动 Claude Code:
claude --dangerously-load-development-channels server:hub
3. 验证:
fh hub status
可选:
• 启用远程审批 hook → README.md §启用远程审批
• Touch ID 二次确认:export FORGE_HUB_AUTH_MODE=touchid(需自行装 touchid-verify)
• 搭配 forge-launcher 使用可精细控制每通道历史回放条数
💡 如果你使用系统代理(Clash / V2Ray 等),Hub 已自动跳过本地请求代理。
若仍遇到 502,请确认 NO_PROXY 包含 127.0.0.1,localhost。
💡 如果启用了远程审批 hook,建议检查 ~/.claude/settings.local.json
确保 Write / Edit / Bash 等常用工具在 permissions.allow 白名单内,
避免日常操作也触发远程审批。
`);
}
// ── sync ────────────────────────────────────────────────────────────────────
function syncCmd(): void {
log("🔄 Forge Hub sync\n");
// 1. Re-stage package snapshot from current source
const packageRoot = stagePackageRuntime();
const serverSrc = path.join(packageRoot, "hub-server");
// 2. Copy hub-server .ts/.json/.lock files to runtime
// SYNC_SKIP 防止 hub-server/ 下未来若出现同名 .json 静默覆盖用户运行时配置(hub-config.json 等)。
copyFilteredTree(serverSrc, HUB_DIR, [".ts", ".json", ".lock"], SYNC_SKIP);
cleanDirContents(CHANNELS_RUNTIME);
cpDir(path.join(serverSrc, "channels"), CHANNELS_RUNTIME, [".ts"]);
// Security: maintain 700 permissions
try {
fs.chmodSync(HUB_DIR, 0o700);
fs.chmodSync(CHANNELS_RUNTIME, 0o700);
} catch (err) {
console.warn(`⚠️ chmod 700 失败: ${String(err)}`);
}
log("✓ hub-server runtime synced(channels/ 已更新)");
// 3. Restart hub via launchctl
// 复用 installCmd 的 bootout + bootstrap 模式(kickstart -k -p 不是合法 launchctl 语法;
// bootstrap 第一参数是 domain 不是完整 label)。
if (os.platform() === "darwin") {
const uid = os.userInfo().uid;
const domain = `gui/${uid}`;
const label = `${domain}/com.forge-hub`;
try {
execFileSync("launchctl", ["bootout", label], { stdio: "ignore" });
} catch { /* might not be bootstrapped */ }
try {
execFileSync("launchctl", ["bootstrap", domain, LAUNCHD_PLIST], { stdio: "inherit" });
log("✓ Hub 已重启");
} catch {
log(`⚠️ 无法重启 Hub。手动执行:launchctl bootout ${label} && launchctl bootstrap ${domain} ${LAUNCHD_PLIST}`);
}
}
log("\n✅ Sync 完成。hub-server 运行时已对齐源码。");
}
// ── uninstall ───────────────────────────────────────────────────────────────
function uninstallCmd(): void {
log("🗑️ Forge Hub uninstall\n(注意:不删 ~/.forge-hub/state(allowlist / pending / 历史),如要全清自行 rm)\n");
if (os.platform() === "darwin" && fs.existsSync(LAUNCHD_PLIST)) {
try {
const uid = String(process.getuid?.() ?? 501);
execFileSync("launchctl", ["bootout", `gui/${uid}/com.forge-hub`], { stdio: "ignore" });
} catch {}
fs.unlinkSync(LAUNCHD_PLIST);
log(`✓ launchd plist 已删除`);
}
if (fs.existsSync(HUB_DIR)) {
for (const f of fs.readdirSync(HUB_DIR)) {
if (f === "state") continue;
const p = path.join(HUB_DIR, f);
try {
fs.rmSync(p, { recursive: true, force: true });
} catch (err) {
console.warn(`无法删除 ${p}: ${String(err)}`);
}
}
log(`✓ ${HUB_DIR}/* 已清(保留 state/)`);
}
if (fs.existsSync(HUB_CLIENT_RUNTIME)) {
fs.rmSync(HUB_CLIENT_RUNTIME, { recursive: true, force: true });
log(`✓ ${HUB_CLIENT_RUNTIME} 已删`);
}
// 清理 ~/bin/ 下的 symlink——install 时建的两个入口
for (const binName of ["fh", "forge-hub"] as const) {
const binPath = path.join(HOME, "bin", binName);
try {
if (fs.lstatSync(binPath).isSymbolicLink()) {
const target = fs.readlinkSync(binPath);
const runtimeCli = path.join(PACKAGE_RUNTIME, "cli.ts");
const runtimeFh = path.join(PACKAGE_RUNTIME, "forge-cli", "forge.ts");
// 只删指向本包的 symlink(防误删同名其他工具)
if (
target.includes("forge-hub")
|| target.includes("forge-cli/forge.ts")
|| target === runtimeCli
|| target === runtimeFh
) {
fs.unlinkSync(binPath);
log(`✓ ${binPath} 已删`);
}
}
} catch { /* ENOENT or not a symlink: skip */ }
}
// 取消 MCP 注册
if (unregisterMcp()) {
log("✓ MCP server 已从 ~/.claude.json 取消注册");
} else {
log("ℹ️ 未删除 ~/.claude.json 的 mcpServers.hub(不存在或不属于当前 forge-hub runtime)");
}
log("\n✅ Uninstall 完成。state(~/.forge-hub/state/)保留,重装会复用。");
}
// ── doctor ──────────────────────────────────────────────────────────────────
async function fetchTextWithStatus(
url: string,
opts: { token?: string; timeoutMs?: number } = {},
): Promise<{ body: string; status: number }> {
const controller = new AbortController();
const timeout = setTimeout(() => controller.abort(), opts.timeoutMs ?? 2000);
try {
const res = await fetch(url, {
headers: opts.token ? { "Authorization": `Bearer ${opts.token}` } : {},
signal: controller.signal,
});
return { body: await res.text(), status: res.status };
} finally {
clearTimeout(timeout);
}
}
async function doctorCmd(): Promise<void> {
log("🩺 Forge Hub doctor\n");
let ok = true;
function check(name: string, pass: boolean, hint?: string): void {
if (pass) {
log(`✓ ${name}`);
} else {
log(`✗ ${name}${hint ? `\n ${hint}` : ""}`);
ok = false;
}
}
check("Bun installed", which("bun") !== null, "https://bun.sh");
check("Hub server runtime", fs.existsSync(path.join(HUB_DIR, "hub.ts")), "跑 forge-hub install");
check("Hub client runtime", fs.existsSync(path.join(HUB_CLIENT_RUNTIME, "hub-channel.ts")), "跑 forge-hub install");
check("LaunchAgent plist", os.platform() !== "darwin" || fs.existsSync(LAUNCHD_PLIST), "Mac 上跑 forge-hub install");
check("MCP registered", isMcpRegistered(), "Hub channel 没在 ~/.claude.json");
check("ffmpeg available(语音功能需要)", which("ffmpeg") !== null || !!process.env.FORGE_FFMPEG_PATH, "brew install ffmpeg 或设 FORGE_FFMPEG_PATH");
check("lark-cli available(飞书通道需要)", which("lark-cli") !== null || !!process.env.FORGE_LARK_CLI, "npm i -g @larksuite/cli 或设 FORGE_LARK_CLI");
// S1c: approval_channels check — informational warning, not a hard fail.
// Not everyone uses server:hub mode, so empty approval_channels is legitimate for
// local MCP tool usage. But surface it clearly so server:hub users can self-diagnose
// the auto-deny trap.
try {
const hubConfigPath = path.join(HUB_DIR, "hub-config.json");
const cfg = fs.existsSync(hubConfigPath)
? JSON.parse(fs.readFileSync(hubConfigPath, "utf-8"))
: {};
const approvalChannels = Array.isArray(cfg.approval_channels) ? cfg.approval_channels : [];
if (approvalChannels.length > 0) {
log(`✓ approval_channels configured: [${approvalChannels.join(", ")}]`);
} else {
log("⚠️ approval_channels 未配置(仅 server:hub 模式需要)");
log(" server:hub 模式下需要审批的工具会被 auto-deny。编辑 ~/.forge-hub/hub-config.json 加 approval_channels,或仅用本地 MCP tools 模式可以忽略。");
}
} catch {
log("⚠️ hub-config.json 读取失败,approval_channels 状态未知");
}
// Hub running?
try {
const baseUrl = process.env.FORGE_HUB_URL ?? "http://localhost:9900";
const health = await fetchTextWithStatus(`${baseUrl}/health`, { timeoutMs: 2000 });
const publicHealth = parsePublicHealthResponse(health.status, health.body);
if (publicHealth.kind !== "online") {
throw new Error(publicHealth.reason);
}
const token = readInstallAuthToken();
const detailed = await fetchTextWithStatus(`${baseUrl}/status`, { token, timeoutMs: 2000 });
const parsed = parseHubStatusResponse(detailed.status, detailed.body);
if (parsed.kind === "online") {
log(`✓ Hub server running (v${parsed.version}, uptime ${Math.round(parsed.uptime / 60)}min)`);
} else if (parsed.kind === "unauthorized") {
log(`✓ Hub server running (v${publicHealth.version}, uptime ${Math.round(publicHealth.uptime / 60)}min; /status 需要 HUB_API_TOKEN,详细状态未读取)`);
} else {
log(`⚠️ Hub server running,但 /status 解析失败: ${parsed.reason}`);
ok = false;
}
} catch {
log("✗ Hub server not responding\n 检查 launchctl list | grep forge-hub,或前台跑 bun ~/.forge-hub/hub.ts");
ok = false;
}
log(ok ? "\n✅ All checks passed" : "\n⚠️ 有检查未通过,按提示修");
if (!ok) process.exit(1);
}
// ── helpers ─────────────────────────────────────────────────────────────────
function cpDir(src: string, dst: string, exts: string[], skipNames = new Set<string>()): void {
if (!fs.existsSync(src)) die(`source 不存在: ${src}`);
fs.mkdirSync(dst, { recursive: true });
for (const f of fs.readdirSync(src)) {
if (skipNames.has(f)) continue;
const sp = path.join(src, f);
const dp = path.join(dst, f);
const stat = fs.statSync(sp);
if (stat.isFile() && exts.some((e) => f.endsWith(e))) {
fs.copyFileSync(sp, dp);
}
}
}
export function cleanDirContents(dir: string, preserve = new Set<string>()): void {
if (!fs.existsSync(dir)) return;
for (const entry of fs.readdirSync(dir)) {
if (preserve.has(entry)) continue;
fs.rmSync(path.join(dir, entry), { recursive: true, force: true });
}
}
function copyFilteredTree(src: string, dst: string, exts: string[], skipNames = new Set<string>()): void {
if (!fs.existsSync(src)) die(`source 不存在: ${src}`);
fs.mkdirSync(dst, { recursive: true });
for (const entry of fs.readdirSync(src, { withFileTypes: true })) {
if (entry.name === "node_modules" || entry.name === ".git" || entry.name === "dist") continue;
if (skipNames.has(entry.name)) continue;
const sp = path.join(src, entry.name);
const dp = path.join(dst, entry.name);
if (entry.isDirectory()) {
copyFilteredTree(sp, dp, exts, skipNames);
continue;
}
if (entry.isFile() && exts.some((ext) => entry.name.endsWith(ext))) {
fs.mkdirSync(path.dirname(dp), { recursive: true });
fs.copyFileSync(sp, dp);
}
}
}
function copyFileIfExists(src: string, dst: string): void {
if (!fs.existsSync(src)) return;
fs.mkdirSync(path.dirname(dst), { recursive: true });
fs.copyFileSync(src, dst);
}
function stagePackageRuntime(): string {
const sourceRoot = path.resolve(PKG_ROOT);
const runtimeRoot = path.resolve(PACKAGE_RUNTIME);
if (sourceRoot === runtimeRoot) return runtimeRoot;
fs.mkdirSync(HUB_DIR, { recursive: true, mode: 0o700 });
fs.chmodSync(HUB_DIR, 0o700);
fs.rmSync(runtimeRoot, { recursive: true, force: true });
fs.mkdirSync(runtimeRoot, { recursive: true, mode: 0o700 });
copyFilteredTree(path.join(sourceRoot, "hub-server"), path.join(runtimeRoot, "hub-server"), [".ts", ".json", ".lock"]);
copyFilteredTree(path.join(sourceRoot, "hub-client"), path.join(runtimeRoot, "hub-client"), [".ts", ".json", ".lock", ".mcp.json"]);
copyFilteredTree(path.join(sourceRoot, "hub-dashboard"), path.join(runtimeRoot, "hub-dashboard"), [".ts", ".tsx", ".js", ".json", ".css", ".html", ".svg", ".lock", ".md"]);
copyFilteredTree(path.join(sourceRoot, "forge-cli"), path.join(runtimeRoot, "forge-cli"), [".ts", ".md"]);
copyFilteredTree(path.join(sourceRoot, "hub-test-harness"), path.join(runtimeRoot, "hub-test-harness"), [".ts"]);
copyFileIfExists(path.join(sourceRoot, "cli.ts"), path.join(runtimeRoot, "cli.ts"));
copyFileIfExists(path.join(sourceRoot, "README.md"), path.join(runtimeRoot, "README.md"));
copyFileIfExists(path.join(sourceRoot, "配置.md"), path.join(runtimeRoot, "配置.md"));
copyFileIfExists(path.join(sourceRoot, "部署.md"), path.join(runtimeRoot, "部署.md"));
return runtimeRoot;
}
function which(cmd: string): string | null {
try {
return execFileSync("/usr/bin/which", [cmd], { encoding: "utf-8" }).trim() || null;
} catch {
return null;
}
}
function readInstallAuthToken(): string {
const fromEnv = process.env.HUB_API_TOKEN;
if (fromEnv) return fromEnv;
try {
if (fs.existsSync(API_TOKEN_FILE)) {
return fs.readFileSync(API_TOKEN_FILE, "utf-8").trim();
}
} catch {}
return "";
}
function readClaudeJson(): Record<string, unknown> {
if (!fs.existsSync(CLAUDE_JSON)) return {};
try {
return JSON.parse(fs.readFileSync(CLAUDE_JSON, "utf-8"));
} catch (err) {
die(`~/.claude.json 损坏,无法继续: ${String(err)}`);
}
}
function writeClaudeJson(data: Record<string, unknown>): void {
// redteam r2 M2: 原子写入。直接 writeFileSync 中途被 kill -9 / 断电 / 磁盘满
// 会留半截 JSON 或空文件——用户所有 MCP server 配置全挂(不止 hub)。
// 方案: 写 .tmp 再 rename(POSIX rename 是原子操作)。失败清理 tmp。
const tmp = `${CLAUDE_JSON}.tmp.${process.pid}`;
const content = JSON.stringify(data, null, 2);
try {
fs.writeFileSync(tmp, content, { encoding: "utf-8", mode: 0o600 });
fs.renameSync(tmp, CLAUDE_JSON);
} catch (err) {
try { fs.unlinkSync(tmp); } catch {}
throw err;
}
}
function registerMcp(): void {
const data = readClaudeJson();
const mcpServers = (data.mcpServers ?? {}) as Record<string, unknown>;
const expectedArgs = [path.join(HUB_CLIENT_RUNTIME, "hub-channel.ts")];
// Conflict check (redteam 终审 P1-5): 如果用户已有 mcpServers.hub 指向
// 非本包的路径,静默覆盖会破坏用户另一项目。refuse + 明确 next-step。
const existing = mcpServers.hub as { args?: unknown[] } | undefined;
if (existing && Array.isArray(existing.args)) {
const existingArg0 = String(existing.args[0] ?? "");
if (existingArg0 !== expectedArgs[0]) {
die(
`~/.claude.json 已有名为 'hub' 的 MCP server,但 args 指向不同路径:\n` +
` 现有: ${existingArg0}\n` +
` 预期: ${expectedArgs[0]}\n` +
`如果你另有项目占用 'hub' 这个名字,请手动处理:\n` +
` 方案 1: 重命名你的其他 MCP server(~/.claude.json 里改 mcpServers.<你的名字>)\n` +
` 方案 2: 跑 forge-hub uninstall 后再 install(如果老的 'hub' 就是本包的残留)\n`,
);
}
// 相同路径——不是真冲突,是重装 refresh,放行
}
// Resolve bun to an absolute path for the MCP server command.
// Claude Code spawns MCP subprocesses without inheriting the user's shell PATH
// (e.g. launchd-started CC sees only the system default PATH). A bare "bun"
// command would fail to resolve when bun is installed under ~/.bun/bin/ or
// other non-system paths, resulting in the MCP server silently failing to
// start. process.execPath is the bun binary currently running this install
// script — using it guarantees the same bun that ran install will be used
// by the MCP subprocess.
const bunPath = resolveBunPath();
mcpServers.hub = {
command: bunPath,
args: expectedArgs,
env: {},
};
data.mcpServers = mcpServers;
writeClaudeJson(data);
}
export function syncApiTokenFileAt(params: {
hubDir: string;
apiTokenFile: string;
token?: string;
log?: (msg: string) => void;
}): void {
const { hubDir, apiTokenFile, token } = params;
const writeLog = params.log ?? (() => {});
if (!token) {
// No env token: leave any existing file alone (user may manage it manually).
if (fs.existsSync(apiTokenFile)) {
writeLog(`✓ API token 文件已存在(沿用): ${apiTokenFile}`);
}
return;
}
fs.mkdirSync(hubDir, { recursive: true, mode: 0o700 });
fs.chmodSync(hubDir, 0o700);
try {
const lst = fs.lstatSync(apiTokenFile);
if (lst.isSymbolicLink()) {
fs.unlinkSync(apiTokenFile);
} else if (!lst.isFile()) {
throw new Error(`${apiTokenFile} 已存在但不是普通文件,请手动处理后重跑 install`);
}
} catch (err) {
if ((err as { code?: string })?.code !== "ENOENT") throw err;
}
const tmp = path.join(hubDir, `.api-token.tmp.${process.pid}.${crypto.randomUUID()}`);
try {
fs.writeFileSync(tmp, token, { encoding: "utf-8", mode: 0o600, flag: "wx" });
fs.renameSync(tmp, apiTokenFile);
fs.chmodSync(apiTokenFile, 0o600);
writeLog(`✓ API token 写入 ${apiTokenFile}(chmod 600,原子替换,MCP 子进程将从此文件读 token)`);
} catch (err) {
try { fs.rmSync(tmp, { force: true }); } catch {}
throw err;
}
}
function syncApiTokenFile(): void {
try {
syncApiTokenFileAt({
hubDir: HUB_DIR,
apiTokenFile: API_TOKEN_FILE,
token: process.env.HUB_API_TOKEN,
log,
});
} catch (err) {
die(`API token 写入失败: ${String(err)}\n 请确认 ${HUB_DIR} 权限正常后重跑 forge-hub install。`);
}
}
function unregisterMcp(): boolean {
const data = readClaudeJson();
const mcpServers = (data.mcpServers ?? {}) as Record<string, unknown>;
const existing = mcpServers.hub as { command?: unknown; args?: unknown[] } | undefined;
if (!existing) return false;
const expectedArg = path.join(HUB_CLIENT_RUNTIME, "hub-channel.ts");
const existingArg0 = Array.isArray(existing.args) ? String(existing.args[0] ?? "") : "";
if (existingArg0 !== expectedArg) {
console.warn(
`⚠️ 保留 mcpServers.hub:它不指向当前 forge-hub runtime。\n` +
` 现有 args[0]: ${existingArg0 || "(缺失)"}\n` +
` 预期 args[0]: ${expectedArg}`,
);
return false;
}
delete mcpServers.hub;
data.mcpServers = mcpServers;
writeClaudeJson(data);
return true;
}
function isMcpRegistered(): boolean {
const data = readClaudeJson();
const mcpServers = (data.mcpServers ?? {}) as Record<string, unknown>;
return "hub" in mcpServers;
}
// ── dispatch ────────────────────────────────────────────────────────────────
if (import.meta.main) {
const cmd = process.argv[2];
switch (cmd) {
case "install":
installCmd();
break;
case "sync":
syncCmd();
break;
case "uninstall":
uninstallCmd();
break;
case "doctor":
await doctorCmd();
break;
case "--help":
case "-h":
case undefined:
log(`forge-hub — Multi-channel messaging hub for Claude Code
USAGE:
forge-hub <command>
COMMANDS:
install 一键部署到 ~/.forge-hub/ + ~/.claude/channels/hub/ + launchd + MCP 注册
sync 仅同步 hub-server 运行时文件(git pull 后跑这个,不重装 deps/dashboard)
uninstall 反向操作(保留 state)
doctor 诊断 install 状态 + connectivity
--help 显示此帮助
REQUIREMENTS:
- Bun >= 1.0
- Claude Code CLI
- macOS(Linux 部分功能可用,iMessage 通道仅 mac)
DOCS:
README.md — 总览 + 远程审批接入
部署.md — 详细部署步骤(手动方案)
hub-docs/channel-plugin-guide.md — 写新通道插件
`);
break;
default:
die(`未知命令: ${cmd}。试 forge-hub --help`);
}
}