-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathsetup.ts
More file actions
261 lines (230 loc) · 8.23 KB
/
setup.ts
File metadata and controls
261 lines (230 loc) · 8.23 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
#!/usr/bin/env bun
/**
* WeChat Channel Setup
*
* Usage:
* bun setup.ts — 扫码登录微信
* bun setup.ts --allow ID [昵称] — 添加 sender 到 allowlist(可选昵称)
* bun setup.ts --nick ID 昵称 — 修改已有 sender 的昵称
* bun setup.ts --list — 查看 allowlist
* bun setup.ts --allow-all — 首次收到消息时自动添加(方便调试)
*/
import fs from "node:fs";
import path from "node:path";
const BASE_URL = "https://ilinkai.weixin.qq.com";
const BOT_TYPE = "3";
const DIR = path.join(process.env.HOME || "~", ".claude", "channels", "wechat");
const CRED_FILE = path.join(DIR, "account.json");
const ALLOW_FILE = path.join(DIR, "allowlist.json");
// ── Allowlist management ─────────────────────────────────────────────────────
interface AllowEntry {
id: string;
nickname: string;
}
interface Allowlist {
allowed: AllowEntry[];
auto_allow_next: boolean;
}
function migrateAllowlist(raw: any): Allowlist {
if (!raw || !raw.allowed) return { allowed: [], auto_allow_next: false };
const allowed: AllowEntry[] = raw.allowed.map((entry: any) => {
if (typeof entry === "string") {
return { id: entry, nickname: entry.split("@")[0] };
}
return entry as AllowEntry;
});
return { allowed, auto_allow_next: raw.auto_allow_next ?? false };
}
function loadAllowlist(): Allowlist {
try {
if (fs.existsSync(ALLOW_FILE)) {
return migrateAllowlist(JSON.parse(fs.readFileSync(ALLOW_FILE, "utf-8")));
}
} catch {}
return { allowed: [], auto_allow_next: false };
}
function saveAllowlist(list: Allowlist): void {
fs.mkdirSync(DIR, { recursive: true });
fs.writeFileSync(ALLOW_FILE, JSON.stringify(list, null, 2), { encoding: "utf-8", mode: 0o600 });
}
// ── CLI subcommands ──────────────────────────────────────────────────────────
const args = process.argv.slice(2);
if (args[0] === "--allow" && args[1]) {
const list = loadAllowlist();
const id = args[1];
const nickname = args[2] || id.split("@")[0];
const existing = list.allowed.find((e) => e.id === id);
if (!existing) {
list.allowed.push({ id, nickname });
saveAllowlist(list);
console.log(`✅ 已添加到 allowlist: ${nickname} (${id})`);
} else {
if (args[2]) {
existing.nickname = args[2];
saveAllowlist(list);
console.log(`✅ 已更新昵称: ${existing.nickname} (${id})`);
} else {
console.log(`已在 allowlist 中: ${existing.nickname} (${id})`);
}
}
process.exit(0);
}
if (args[0] === "--nick" && args[1] && args[2]) {
const list = loadAllowlist();
const entry = list.allowed.find((e) => e.id === args[1]);
if (entry) {
entry.nickname = args[2];
saveAllowlist(list);
console.log(`✅ 昵称已更新: ${entry.nickname} (${entry.id})`);
} else {
console.log(`未找到 ID: ${args[1]}`);
}
process.exit(0);
}
if (args[0] === "--allow-all") {
const list = loadAllowlist();
list.auto_allow_next = true;
saveAllowlist(list);
console.log("✅ 已开启自动添加模式:下一个发消息的 sender 将自动加入 allowlist");
process.exit(0);
}
if (args[0] === "--list") {
const list = loadAllowlist();
if (list.allowed.length === 0) {
console.log("allowlist 为空。");
console.log("使用 bun setup.ts --allow-all 开启自动添加,然后从微信发一条消息。");
} else {
console.log("当前 allowlist:");
for (const entry of list.allowed) {
console.log(` - ${entry.nickname} (${entry.id})`);
}
}
if (list.auto_allow_next) {
console.log("\n[自动添加模式已开启]");
}
process.exit(0);
}
// ── QR Login ─────────────────────────────────────────────────────────────────
interface QRCodeResponse {
qrcode: string;
qrcode_img_content: string;
}
interface QRStatusResponse {
status: "wait" | "scaned" | "confirmed" | "expired";
bot_token?: string;
ilink_bot_id?: string;
baseurl?: string;
ilink_user_id?: string;
}
async function fetchQRCode(): Promise<QRCodeResponse> {
const url = `${BASE_URL}/ilink/bot/get_bot_qrcode?bot_type=${BOT_TYPE}`;
const res = await fetch(url);
if (!res.ok) throw new Error(`QR fetch failed: ${res.status}`);
return (await res.json()) as QRCodeResponse;
}
async function pollQRStatus(qrcode: string): Promise<QRStatusResponse> {
const url = `${BASE_URL}/ilink/bot/get_qrcode_status?qrcode=${encodeURIComponent(qrcode)}`;
const controller = new AbortController();
const timer = setTimeout(() => controller.abort(), 35_000);
try {
const res = await fetch(url, {
headers: { "iLink-App-ClientVersion": "1" },
signal: controller.signal,
});
clearTimeout(timer);
if (!res.ok) throw new Error(`QR status failed: ${res.status}`);
return (await res.json()) as QRStatusResponse;
} catch (err) {
clearTimeout(timer);
if (err instanceof Error && err.name === "AbortError") {
return { status: "wait" };
}
throw err;
}
}
// ── Main: QR login flow ──────────────────────────────────────────────────────
if (fs.existsSync(CRED_FILE)) {
try {
const existing = JSON.parse(fs.readFileSync(CRED_FILE, "utf-8"));
console.log(`已有保存的账号: ${existing.accountId}`);
console.log(`保存时间: ${existing.savedAt}`);
console.log();
const readline = await import("node:readline");
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout,
});
const answer = await new Promise<string>((resolve) => {
rl.question("是否重新登录?(y/N) ", resolve);
});
rl.close();
if (answer.toLowerCase() !== "y") {
console.log("保持现有凭据,退出。");
process.exit(0);
}
} catch {}
}
console.log("正在获取微信登录二维码...\n");
const qrResp = await fetchQRCode();
try {
const qrterm = await import("qrcode-terminal");
await new Promise<void>((resolve) => {
qrterm.default.generate(
qrResp.qrcode_img_content,
{ small: true },
(qr: string) => {
console.log(qr);
resolve();
},
);
});
} catch {
console.log(`请在浏览器中打开此链接扫码: ${qrResp.qrcode_img_content}\n`);
}
console.log("请用微信扫描上方二维码...\n");
const deadline = Date.now() + 480_000;
let scannedPrinted = false;
while (Date.now() < deadline) {
const status = await pollQRStatus(qrResp.qrcode);
switch (status.status) {
case "wait":
process.stdout.write(".");
break;
case "scaned":
if (!scannedPrinted) {
console.log("\n已扫码,请在微信中确认...");
scannedPrinted = true;
}
break;
case "expired":
console.log("\n二维码已过期,请重新运行。");
process.exit(1);
break;
case "confirmed": {
if (!status.ilink_bot_id || !status.bot_token) {
console.error("\n登录失败:服务器未返回完整信息。");
process.exit(1);
}
const account = {
token: status.bot_token,
baseUrl: status.baseurl || BASE_URL,
accountId: status.ilink_bot_id,
userId: status.ilink_user_id,
savedAt: new Date().toISOString(),
};
fs.mkdirSync(DIR, { recursive: true });
fs.writeFileSync(CRED_FILE, JSON.stringify(account, null, 2), { encoding: "utf-8", mode: 0o600 });
console.log(`\n✅ 微信连接成功!`);
console.log(` 账号 ID: ${account.accountId}`);
console.log(` 凭据保存至: ${CRED_FILE}`);
console.log();
console.log("下一步:");
console.log(" 1. bun setup.ts --allow-all (开启自动 allowlist)");
console.log(" 2. claude --dangerously-load-development-channels server:wechat");
process.exit(0);
}
}
await new Promise((r) => setTimeout(r, 1000));
}
console.log("\n登录超时,请重新运行。");
process.exit(1);