pi-wechat-session-hub 0.1.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.
- package/LICENSE +661 -0
- package/README.md +365 -0
- package/docs/decisions/0001-ilink-context-token-queue.md +41 -0
- package/docs/handoff-next-session.md +134 -0
- package/docs/implementation-spec.md +147 -0
- package/extensions/wechat-session-hub.ts +589 -0
- package/package.json +67 -0
- package/scripts/pi-rpc-smoke.mjs +150 -0
- package/scripts/probe-wt-capability.mjs +27 -0
- package/scripts/start-ui-worker.ps1 +37 -0
- package/src/commands/ilink-qr-login-component.ts +148 -0
- package/src/commands/project-command-parser.ts +108 -0
- package/src/commands/tokenizer.ts +71 -0
- package/src/commands/wechat-manager-command-parser.ts +143 -0
- package/src/config/defaults.ts +30 -0
- package/src/config/paths.ts +56 -0
- package/src/config/store.ts +311 -0
- package/src/config/types.ts +33 -0
- package/src/config/validation.ts +221 -0
- package/src/gateway/channel-types.ts +47 -0
- package/src/gateway/command-parser.ts +291 -0
- package/src/gateway/command-router.ts +1449 -0
- package/src/gateway/credential-store.ts +611 -0
- package/src/gateway/durable-message-queue.ts +1043 -0
- package/src/gateway/gateway-control-ipc.ts +687 -0
- package/src/gateway/gateway-runtime.ts +726 -0
- package/src/gateway/ui-worker-extension-bridge.ts +1070 -0
- package/src/gateway/ui-worker-ipc.ts +1483 -0
- package/src/gateway/ui-worker-types.ts +50 -0
- package/src/gateway/wechat-ilink/api-client.ts +390 -0
- package/src/gateway/wechat-ilink/channel-adapter.ts +320 -0
- package/src/gateway/wechat-ilink/cursor-store.ts +134 -0
- package/src/gateway/wechat-ilink/qr-login.ts +612 -0
- package/src/gateway/wechat-ilink/typing-indicator.ts +133 -0
- package/src/gateway/windows-terminal-launcher.ts +247 -0
- package/src/projects/project-service.ts +483 -0
- package/src/registry/gateway-lease.ts +348 -0
- package/src/registry/manager-registry.ts +466 -0
- package/src/registry/types.ts +61 -0
- package/src/runtime/background-pi-worker.ts +309 -0
- package/src/runtime/background-worker-manager.ts +594 -0
- package/src/runtime/gateway-daemon.ts +281 -0
- package/src/runtime/gateway-lifecycle-operation.ts +308 -0
- package/src/runtime/gateway-service-controller.ts +339 -0
- package/src/runtime/gateway-worker-manager.ts +181 -0
- package/src/runtime/pi-cli.ts +56 -0
- package/src/runtime/pi-rpc-client.ts +427 -0
- package/src/runtime/ui-worker-manager.ts +1186 -0
- package/src/runtime/windows-logon-task-manager.ts +212 -0
- package/src/system/process-liveness.ts +88 -0
- package/tsconfig.json +19 -0
|
@@ -0,0 +1,612 @@
|
|
|
1
|
+
import { randomBytes } from "node:crypto";
|
|
2
|
+
import { createRequire } from "node:module";
|
|
3
|
+
import { lstat } from "node:fs/promises";
|
|
4
|
+
import { join, resolve } from "node:path";
|
|
5
|
+
import {
|
|
6
|
+
ConfigurationBusyError,
|
|
7
|
+
ConfigurationStore,
|
|
8
|
+
} from "../../config/store.ts";
|
|
9
|
+
import { GatewayLease, GatewayLeaseError } from "../../registry/gateway-lease.ts";
|
|
10
|
+
import {
|
|
11
|
+
createIlinkCredentialFile,
|
|
12
|
+
IlinkCredentialStoreError,
|
|
13
|
+
verifyCredentialDirectoryPermissions,
|
|
14
|
+
type IlinkCredentialStoreOptions,
|
|
15
|
+
} from "../credential-store.ts";
|
|
16
|
+
|
|
17
|
+
const ILINK_BASE_URL = "https://ilinkai.weixin.qq.com";
|
|
18
|
+
const ILINK_APP_ID = "bot";
|
|
19
|
+
const ILINK_APP_CLIENT_VERSION = "1";
|
|
20
|
+
const QR_REQUEST_TIMEOUT_MS = 15000;
|
|
21
|
+
const QR_STATUS_TIMEOUT_MS = 45000;
|
|
22
|
+
const LOGIN_TIMEOUT_MS = 5 * 60 * 1000;
|
|
23
|
+
const MAX_QR_REFRESHES = 3;
|
|
24
|
+
const require = createRequire(import.meta.url);
|
|
25
|
+
const qrcodeTerminal = require("qrcode-terminal") as typeof import("qrcode-terminal");
|
|
26
|
+
|
|
27
|
+
type QrStatus =
|
|
28
|
+
| "wait"
|
|
29
|
+
| "scaned"
|
|
30
|
+
| "confirmed"
|
|
31
|
+
| "expired"
|
|
32
|
+
| "scaned_but_redirect"
|
|
33
|
+
| "need_verifycode"
|
|
34
|
+
| "verify_code_blocked"
|
|
35
|
+
| "binded_redirect";
|
|
36
|
+
|
|
37
|
+
interface QrCodeResponse {
|
|
38
|
+
qrcode: string;
|
|
39
|
+
qrcode_img_content: string;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
interface QrStatusResponse {
|
|
43
|
+
status: QrStatus;
|
|
44
|
+
bot_token?: string;
|
|
45
|
+
ilink_bot_id?: string;
|
|
46
|
+
ilink_user_id?: string;
|
|
47
|
+
baseurl?: string;
|
|
48
|
+
redirect_host?: string;
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
export type IlinkQrLoginErrorCode =
|
|
52
|
+
| "gateway_running"
|
|
53
|
+
| "credential_exists"
|
|
54
|
+
| "credential_path_unsafe"
|
|
55
|
+
| "qr_api_unavailable"
|
|
56
|
+
| "qr_response_invalid"
|
|
57
|
+
| "qr_expired"
|
|
58
|
+
| "account_already_bound"
|
|
59
|
+
| "verification_required"
|
|
60
|
+
| "verification_invalid"
|
|
61
|
+
| "authorized_user_mismatch"
|
|
62
|
+
| "login_timeout"
|
|
63
|
+
| "login_cancelled";
|
|
64
|
+
|
|
65
|
+
/**
|
|
66
|
+
* 表示独立 iLink QR 登录未能安全完成。
|
|
67
|
+
*/
|
|
68
|
+
export class IlinkQrLoginError extends Error {
|
|
69
|
+
/**
|
|
70
|
+
* 创建不包含二维码、token 或原始响应正文的登录错误。
|
|
71
|
+
*
|
|
72
|
+
* @param code 稳定错误代码。
|
|
73
|
+
* @param message 可安全显示给本地用户的中文说明。
|
|
74
|
+
*/
|
|
75
|
+
constructor(readonly code: IlinkQrLoginErrorCode, message: string) {
|
|
76
|
+
super(message);
|
|
77
|
+
this.name = "IlinkQrLoginError";
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
/**
|
|
82
|
+
* 描述独立 iLink 登录完成结果。
|
|
83
|
+
*/
|
|
84
|
+
export interface IlinkQrLoginResult {
|
|
85
|
+
authorizedUserId: string;
|
|
86
|
+
botId: string;
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
/**
|
|
90
|
+
* 在终端 TUI 中以 ANSI 文本形式渲染 iLink 扫码链接。
|
|
91
|
+
*
|
|
92
|
+
* @param qrContent iLink QR 响应中的 qrcode_img_content。
|
|
93
|
+
* @returns 可显示在 Pi TUI 的二维码文本。
|
|
94
|
+
*/
|
|
95
|
+
export function renderIlinkQrCode(qrContent: string): Promise<string> {
|
|
96
|
+
return new Promise((resolveQr) => {
|
|
97
|
+
qrcodeTerminal.generate(qrContent, { small: true }, resolveQr);
|
|
98
|
+
});
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
/**
|
|
102
|
+
* 通过微信扫码为 Pi Hub 创建独立 iLink 授权, 不读取其他客户端凭证。
|
|
103
|
+
*/
|
|
104
|
+
export class IlinkQrLoginService {
|
|
105
|
+
/**
|
|
106
|
+
* 创建独立 iLink QR 登录服务。
|
|
107
|
+
*
|
|
108
|
+
* @param options Hub 私有目录、配置存储及可注入测试传输。
|
|
109
|
+
*/
|
|
110
|
+
constructor(private readonly options: {
|
|
111
|
+
managerDirectory: string;
|
|
112
|
+
configStore: ConfigurationStore;
|
|
113
|
+
fetcher?: typeof fetch;
|
|
114
|
+
credentialStoreOptions?: IlinkCredentialStoreOptions;
|
|
115
|
+
}) {}
|
|
116
|
+
|
|
117
|
+
/**
|
|
118
|
+
* 执行本地 QR 授权, 并只创建 Hub 自有的 credentials.json。
|
|
119
|
+
*
|
|
120
|
+
* @param callbacks 二维码、状态、取消和可选验证码回调。
|
|
121
|
+
* @returns 新授权的 userId 和 botId。
|
|
122
|
+
* @throws {IlinkQrLoginError} 授权失败、现有凭证冲突或超时时抛出。
|
|
123
|
+
*/
|
|
124
|
+
async login(callbacks: {
|
|
125
|
+
signal: AbortSignal;
|
|
126
|
+
onQrCode: (content: string, terminalQr: string) => void;
|
|
127
|
+
onStatus: (status: string) => void;
|
|
128
|
+
requestVerificationCode?: () => Promise<string | undefined>;
|
|
129
|
+
}): Promise<IlinkQrLoginResult> {
|
|
130
|
+
const managerDirectory = resolve(this.options.managerDirectory);
|
|
131
|
+
let lease: GatewayLease;
|
|
132
|
+
try {
|
|
133
|
+
lease = await GatewayLease.acquire(managerDirectory);
|
|
134
|
+
} catch (error) {
|
|
135
|
+
if (error instanceof GatewayLeaseError && error.code === "gateway_already_running") {
|
|
136
|
+
throw new IlinkQrLoginError(
|
|
137
|
+
"gateway_running",
|
|
138
|
+
"请先停止 Pi Hub Gateway, 再进行扫码授权。",
|
|
139
|
+
);
|
|
140
|
+
}
|
|
141
|
+
throw error;
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
try {
|
|
145
|
+
await verifyCredentialDirectoryPermissions(
|
|
146
|
+
managerDirectory,
|
|
147
|
+
this.options.credentialStoreOptions,
|
|
148
|
+
);
|
|
149
|
+
const credentialFile = join(managerDirectory, "credentials.json");
|
|
150
|
+
if (await pathExists(credentialFile)) {
|
|
151
|
+
throw new IlinkQrLoginError(
|
|
152
|
+
"credential_exists",
|
|
153
|
+
"Pi Hub 已有 credentials.json, 为避免覆盖任何凭证, 扫码授权已停止。",
|
|
154
|
+
);
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
const { config } = await this.options.configStore.load();
|
|
158
|
+
const existingAuthorizedUserId = config.wechat.authorizedUserId.trim();
|
|
159
|
+
callbacks.onStatus("正在连接微信 iLink 授权服务...");
|
|
160
|
+
const login = await this.performLogin(callbacks);
|
|
161
|
+
if (existingAuthorizedUserId && existingAuthorizedUserId !== login.userId) {
|
|
162
|
+
throw new IlinkQrLoginError(
|
|
163
|
+
"authorized_user_mismatch",
|
|
164
|
+
"扫码账号与配置中的 authorizedUserId 不一致, 未写入凭证。",
|
|
165
|
+
);
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
await lease.assertOwned();
|
|
169
|
+
await this.options.configStore.update((current) => {
|
|
170
|
+
const configuredUserId = current.wechat.authorizedUserId.trim();
|
|
171
|
+
if (configuredUserId && configuredUserId !== login.userId) {
|
|
172
|
+
throw new IlinkQrLoginError(
|
|
173
|
+
"authorized_user_mismatch",
|
|
174
|
+
"配置中的微信授权用户已改变, 未更新配置。",
|
|
175
|
+
);
|
|
176
|
+
}
|
|
177
|
+
return {
|
|
178
|
+
...current,
|
|
179
|
+
wechat: {
|
|
180
|
+
...current.wechat,
|
|
181
|
+
authorizedUserId: login.userId,
|
|
182
|
+
credentialFile,
|
|
183
|
+
},
|
|
184
|
+
};
|
|
185
|
+
});
|
|
186
|
+
await lease.assertOwned();
|
|
187
|
+
await createIlinkCredentialFile(
|
|
188
|
+
managerDirectory,
|
|
189
|
+
{
|
|
190
|
+
schemaVersion: 1,
|
|
191
|
+
authorizedUserId: login.userId,
|
|
192
|
+
token: login.token,
|
|
193
|
+
baseUrl: login.baseUrl,
|
|
194
|
+
},
|
|
195
|
+
this.options.credentialStoreOptions,
|
|
196
|
+
);
|
|
197
|
+
callbacks.onStatus("Pi Hub 专属 iLink 凭证已安全保存。");
|
|
198
|
+
return { authorizedUserId: login.userId, botId: login.botId };
|
|
199
|
+
} catch (error) {
|
|
200
|
+
if (callbacks.signal.aborted) {
|
|
201
|
+
throw new IlinkQrLoginError("login_cancelled", "扫码授权已取消, 没有启动微信轮询。");
|
|
202
|
+
}
|
|
203
|
+
if (
|
|
204
|
+
error instanceof IlinkQrLoginError ||
|
|
205
|
+
error instanceof IlinkCredentialStoreError ||
|
|
206
|
+
error instanceof ConfigurationBusyError ||
|
|
207
|
+
error instanceof GatewayLeaseError
|
|
208
|
+
) {
|
|
209
|
+
throw error;
|
|
210
|
+
}
|
|
211
|
+
throw new IlinkQrLoginError(
|
|
212
|
+
"qr_api_unavailable",
|
|
213
|
+
"扫码授权未完成; Pi Hub 未启动微信轮询, 请稍后重试。",
|
|
214
|
+
);
|
|
215
|
+
} finally {
|
|
216
|
+
await lease.release();
|
|
217
|
+
}
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
/**
|
|
221
|
+
* 轮询 iLink QR 状态并返回服务端签发的独立凭证。
|
|
222
|
+
*
|
|
223
|
+
* @param callbacks 状态和验证码交互回调。
|
|
224
|
+
* @returns 服务端确认的用户、bot、token 和 baseUrl。
|
|
225
|
+
*/
|
|
226
|
+
private async performLogin(callbacks: {
|
|
227
|
+
signal: AbortSignal;
|
|
228
|
+
onQrCode: (content: string, terminalQr: string) => void;
|
|
229
|
+
onStatus: (status: string) => void;
|
|
230
|
+
requestVerificationCode?: () => Promise<string | undefined>;
|
|
231
|
+
}): Promise<{ userId: string; botId: string; token: string; baseUrl: string }> {
|
|
232
|
+
const deadline = Date.now() + LOGIN_TIMEOUT_MS;
|
|
233
|
+
let qrRefreshes = 0;
|
|
234
|
+
let currentBaseUrl = ILINK_BASE_URL;
|
|
235
|
+
let verifyCode: string | undefined;
|
|
236
|
+
let qr = await this.fetchQrCode(callbacks.signal);
|
|
237
|
+
await this.publishQr(qr, callbacks);
|
|
238
|
+
|
|
239
|
+
while (Date.now() < deadline) {
|
|
240
|
+
if (callbacks.signal.aborted) {
|
|
241
|
+
throw new IlinkQrLoginError("login_cancelled", "扫码授权已取消。 ");
|
|
242
|
+
}
|
|
243
|
+
let response: QrStatusResponse;
|
|
244
|
+
try {
|
|
245
|
+
response = await this.fetchQrStatus(currentBaseUrl, qr.qrcode, verifyCode, callbacks.signal);
|
|
246
|
+
} catch (error) {
|
|
247
|
+
if (error instanceof IlinkQrLoginError || callbacks.signal.aborted) {
|
|
248
|
+
throw error;
|
|
249
|
+
}
|
|
250
|
+
callbacks.onStatus("iLink 暂时无响应, 正在安全重试...");
|
|
251
|
+
await delay(1500, callbacks.signal);
|
|
252
|
+
continue;
|
|
253
|
+
}
|
|
254
|
+
|
|
255
|
+
switch (response.status) {
|
|
256
|
+
case "wait":
|
|
257
|
+
callbacks.onStatus("请用微信扫描二维码, 等待确认...");
|
|
258
|
+
break;
|
|
259
|
+
case "scaned":
|
|
260
|
+
verifyCode = undefined;
|
|
261
|
+
callbacks.onStatus("已扫码, 请在微信中确认授权...");
|
|
262
|
+
break;
|
|
263
|
+
case "scaned_but_redirect":
|
|
264
|
+
if (response.redirect_host) {
|
|
265
|
+
currentBaseUrl = validateRedirectHost(response.redirect_host);
|
|
266
|
+
callbacks.onStatus("微信已扫码, 正在切换到授权服务节点...");
|
|
267
|
+
} else {
|
|
268
|
+
callbacks.onStatus("微信已扫码, 正在等待授权服务确认...");
|
|
269
|
+
}
|
|
270
|
+
break;
|
|
271
|
+
case "need_verifycode": {
|
|
272
|
+
if (!callbacks.requestVerificationCode) {
|
|
273
|
+
throw new IlinkQrLoginError(
|
|
274
|
+
"verification_required",
|
|
275
|
+
"微信要求输入配对验证码; 当前 Pi TUI 无可用输入界面, 授权未完成。",
|
|
276
|
+
);
|
|
277
|
+
}
|
|
278
|
+
const code = await callbacks.requestVerificationCode();
|
|
279
|
+
if (!code) {
|
|
280
|
+
throw new IlinkQrLoginError("login_cancelled", "验证码输入已取消, 未写入凭证。");
|
|
281
|
+
}
|
|
282
|
+
if (!/^\d{1,16}$/.test(code.trim())) {
|
|
283
|
+
throw new IlinkQrLoginError("verification_invalid", "验证码必须是 1 至 16 位数字。");
|
|
284
|
+
}
|
|
285
|
+
verifyCode = code.trim();
|
|
286
|
+
callbacks.onStatus("正在验证配对码...");
|
|
287
|
+
continue;
|
|
288
|
+
}
|
|
289
|
+
case "verify_code_blocked":
|
|
290
|
+
case "expired":
|
|
291
|
+
qrRefreshes += 1;
|
|
292
|
+
if (qrRefreshes >= MAX_QR_REFRESHES) {
|
|
293
|
+
throw new IlinkQrLoginError(
|
|
294
|
+
"qr_expired",
|
|
295
|
+
"二维码已多次过期或验证码失败, 授权已停止, 请重新开始。",
|
|
296
|
+
);
|
|
297
|
+
}
|
|
298
|
+
callbacks.onStatus("二维码已过期, 正在申请新的二维码...");
|
|
299
|
+
qr = await this.fetchQrCode(callbacks.signal);
|
|
300
|
+
currentBaseUrl = ILINK_BASE_URL;
|
|
301
|
+
verifyCode = undefined;
|
|
302
|
+
await this.publishQr(qr, callbacks);
|
|
303
|
+
continue;
|
|
304
|
+
case "binded_redirect":
|
|
305
|
+
throw new IlinkQrLoginError(
|
|
306
|
+
"account_already_bound",
|
|
307
|
+
"iLink 未签发新的 Pi 凭证, 该账号仍报告已有绑定. 请按服务官方方式处理已有绑定; 本流程不会停止其他客户端或修改其本地数据。",
|
|
308
|
+
);
|
|
309
|
+
case "confirmed": {
|
|
310
|
+
const token = response.bot_token?.trim();
|
|
311
|
+
const userId = response.ilink_user_id?.trim();
|
|
312
|
+
const botId = response.ilink_bot_id?.trim();
|
|
313
|
+
const baseUrl = validateBaseUrl(response.baseurl ?? currentBaseUrl);
|
|
314
|
+
if (!token || !userId || !botId) {
|
|
315
|
+
throw new IlinkQrLoginError(
|
|
316
|
+
"qr_response_invalid",
|
|
317
|
+
"微信确认成功但没有返回完整 iLink 凭证; 未写入任何凭证。",
|
|
318
|
+
);
|
|
319
|
+
}
|
|
320
|
+
callbacks.onStatus("微信授权已确认, 正在安全保存 Pi Hub 专属凭证...");
|
|
321
|
+
return { token, userId, botId, baseUrl };
|
|
322
|
+
}
|
|
323
|
+
default:
|
|
324
|
+
throw new IlinkQrLoginError("qr_response_invalid", "iLink 返回了不支持的扫码状态。");
|
|
325
|
+
}
|
|
326
|
+
}
|
|
327
|
+
throw new IlinkQrLoginError("login_timeout", "扫码授权超时, 没有写入凭证或启动轮询。");
|
|
328
|
+
}
|
|
329
|
+
|
|
330
|
+
/**
|
|
331
|
+
* 请求新的 iLink QR, 不提交或读取任何已有 bot token。
|
|
332
|
+
*
|
|
333
|
+
* @param signal 本地取消信号。
|
|
334
|
+
* @returns iLink QR 标识及供手机扫描的内容。
|
|
335
|
+
*/
|
|
336
|
+
private async fetchQrCode(signal: AbortSignal): Promise<QrCodeResponse> {
|
|
337
|
+
const response = await requestJson(
|
|
338
|
+
this.options.fetcher ?? fetch,
|
|
339
|
+
`${ILINK_BASE_URL}/ilink/bot/get_bot_qrcode?bot_type=3`,
|
|
340
|
+
"POST",
|
|
341
|
+
signal,
|
|
342
|
+
QR_REQUEST_TIMEOUT_MS,
|
|
343
|
+
JSON.stringify({ local_token_list: [] }),
|
|
344
|
+
);
|
|
345
|
+
if (
|
|
346
|
+
typeof response.qrcode !== "string" || !response.qrcode.trim() || response.qrcode.length > 4096 ||
|
|
347
|
+
typeof response.qrcode_img_content !== "string" || !response.qrcode_img_content.trim() ||
|
|
348
|
+
response.qrcode_img_content.length > 8192
|
|
349
|
+
) {
|
|
350
|
+
throw new IlinkQrLoginError("qr_response_invalid", "iLink QR 响应字段无效, 未显示二维码。");
|
|
351
|
+
}
|
|
352
|
+
const qrContent = validateQrContent(response.qrcode_img_content);
|
|
353
|
+
return { qrcode: response.qrcode, qrcode_img_content: qrContent };
|
|
354
|
+
}
|
|
355
|
+
|
|
356
|
+
/**
|
|
357
|
+
* 长轮询 QR 状态并校验服务端字段。
|
|
358
|
+
*
|
|
359
|
+
* @param baseUrl 当前受信任 iLink 服务地址。
|
|
360
|
+
* @param qrcode 服务端 QR id, 不写入日志。
|
|
361
|
+
* @param verifyCode 可选的微信配对验证码。
|
|
362
|
+
* @param signal 本地取消信号。
|
|
363
|
+
* @returns 状态响应。
|
|
364
|
+
*/
|
|
365
|
+
private async fetchQrStatus(
|
|
366
|
+
baseUrl: string,
|
|
367
|
+
qrcode: string,
|
|
368
|
+
verifyCode: string | undefined,
|
|
369
|
+
signal: AbortSignal,
|
|
370
|
+
): Promise<QrStatusResponse> {
|
|
371
|
+
const query = new URLSearchParams({ qrcode });
|
|
372
|
+
if (verifyCode) {
|
|
373
|
+
query.set("verify_code", verifyCode);
|
|
374
|
+
}
|
|
375
|
+
const response = await requestJson(
|
|
376
|
+
this.options.fetcher ?? fetch,
|
|
377
|
+
`${baseUrl}/ilink/bot/get_qrcode_status?${query.toString()}`,
|
|
378
|
+
"GET",
|
|
379
|
+
signal,
|
|
380
|
+
QR_STATUS_TIMEOUT_MS,
|
|
381
|
+
);
|
|
382
|
+
const allowedStatuses = new Set<QrStatus>([
|
|
383
|
+
"wait",
|
|
384
|
+
"scaned",
|
|
385
|
+
"confirmed",
|
|
386
|
+
"expired",
|
|
387
|
+
"scaned_but_redirect",
|
|
388
|
+
"need_verifycode",
|
|
389
|
+
"verify_code_blocked",
|
|
390
|
+
"binded_redirect",
|
|
391
|
+
]);
|
|
392
|
+
if (typeof response.status !== "string" || !allowedStatuses.has(response.status as QrStatus)) {
|
|
393
|
+
throw new IlinkQrLoginError("qr_response_invalid", "iLink 扫码状态响应无效。");
|
|
394
|
+
}
|
|
395
|
+
return response as unknown as QrStatusResponse;
|
|
396
|
+
}
|
|
397
|
+
|
|
398
|
+
/**
|
|
399
|
+
* 将新二维码和 ANSI 终端渲染结果交给 Pi 本地 UI。
|
|
400
|
+
*
|
|
401
|
+
* @param qr iLink QR 响应。
|
|
402
|
+
* @param callbacks 本地 UI 回调。
|
|
403
|
+
* @returns 二维码内容发送到本地 UI 后结束。
|
|
404
|
+
*/
|
|
405
|
+
private async publishQr(
|
|
406
|
+
qr: QrCodeResponse,
|
|
407
|
+
callbacks: {
|
|
408
|
+
onQrCode: (content: string, terminalQr: string) => void;
|
|
409
|
+
onStatus: (status: string) => void;
|
|
410
|
+
},
|
|
411
|
+
): Promise<void> {
|
|
412
|
+
const terminalQr = await renderIlinkQrCode(qr.qrcode_img_content);
|
|
413
|
+
callbacks.onQrCode(qr.qrcode_img_content, terminalQr);
|
|
414
|
+
callbacks.onStatus("请用微信扫描二维码; 如账号正在被其他客户端轮询, 请先停止冲突轮询器。");
|
|
415
|
+
}
|
|
416
|
+
}
|
|
417
|
+
|
|
418
|
+
/**
|
|
419
|
+
* 构造 iLink 公共请求头, 不包含 Authorization token。
|
|
420
|
+
*
|
|
421
|
+
* @param method HTTP method。
|
|
422
|
+
* @returns 可供 fetch 使用的头字段。
|
|
423
|
+
*/
|
|
424
|
+
function buildQrHeaders(method: "GET" | "POST"): HeadersInit {
|
|
425
|
+
return {
|
|
426
|
+
...(method === "POST" ? {
|
|
427
|
+
"Content-Type": "application/json",
|
|
428
|
+
AuthorizationType: "ilink_bot_token",
|
|
429
|
+
"X-WECHAT-UIN": randomWechatUin(),
|
|
430
|
+
} : {}),
|
|
431
|
+
"iLink-App-Id": ILINK_APP_ID,
|
|
432
|
+
"iLink-App-ClientVersion": ILINK_APP_CLIENT_VERSION,
|
|
433
|
+
};
|
|
434
|
+
}
|
|
435
|
+
|
|
436
|
+
/**
|
|
437
|
+
* 执行超时和取消受控的 iLink QR HTTP 请求。
|
|
438
|
+
*
|
|
439
|
+
* @param fetcher 注入的 fetch 实现。
|
|
440
|
+
* @param url iLink 登录 endpoint。
|
|
441
|
+
* @param method HTTP method。
|
|
442
|
+
* @param parentSignal 上层取消信号。
|
|
443
|
+
* @param timeoutMs 本次请求超时。
|
|
444
|
+
* @param body 可选 JSON body。
|
|
445
|
+
* @returns JSON object 响应。
|
|
446
|
+
*/
|
|
447
|
+
async function requestJson(
|
|
448
|
+
fetcher: typeof fetch,
|
|
449
|
+
url: string,
|
|
450
|
+
method: "GET" | "POST",
|
|
451
|
+
parentSignal: AbortSignal,
|
|
452
|
+
timeoutMs: number,
|
|
453
|
+
body?: string,
|
|
454
|
+
): Promise<Record<string, unknown>> {
|
|
455
|
+
const controller = new AbortController();
|
|
456
|
+
const timeout = setTimeout(() => controller.abort(), timeoutMs);
|
|
457
|
+
timeout.unref();
|
|
458
|
+
const abortFromParent = (): void => controller.abort();
|
|
459
|
+
if (parentSignal.aborted) {
|
|
460
|
+
controller.abort();
|
|
461
|
+
} else {
|
|
462
|
+
parentSignal.addEventListener("abort", abortFromParent, { once: true });
|
|
463
|
+
}
|
|
464
|
+
try {
|
|
465
|
+
const response = await fetcher(url, {
|
|
466
|
+
method,
|
|
467
|
+
headers: buildQrHeaders(method),
|
|
468
|
+
...(body === undefined ? {} : { body }),
|
|
469
|
+
signal: controller.signal,
|
|
470
|
+
});
|
|
471
|
+
if (!response.ok) {
|
|
472
|
+
throw new Error("http_error");
|
|
473
|
+
}
|
|
474
|
+
const payload = await response.json() as unknown;
|
|
475
|
+
if (typeof payload !== "object" || payload === null || Array.isArray(payload)) {
|
|
476
|
+
throw new IlinkQrLoginError("qr_response_invalid", "iLink QR API 返回了无效 JSON 对象。");
|
|
477
|
+
}
|
|
478
|
+
return payload as Record<string, unknown>;
|
|
479
|
+
} catch (error) {
|
|
480
|
+
if (error instanceof IlinkQrLoginError) {
|
|
481
|
+
throw error;
|
|
482
|
+
}
|
|
483
|
+
if (parentSignal.aborted) {
|
|
484
|
+
throw new IlinkQrLoginError("login_cancelled", "扫码授权已取消。");
|
|
485
|
+
}
|
|
486
|
+
throw new Error("ilink_qr_request_failed");
|
|
487
|
+
} finally {
|
|
488
|
+
clearTimeout(timeout);
|
|
489
|
+
parentSignal.removeEventListener("abort", abortFromParent);
|
|
490
|
+
}
|
|
491
|
+
}
|
|
492
|
+
|
|
493
|
+
/**
|
|
494
|
+
* 延迟到下一轮长轮询, 并支持 Escape 取消。
|
|
495
|
+
*
|
|
496
|
+
* @param delayMs 延迟时长。
|
|
497
|
+
* @param signal 本地取消信号。
|
|
498
|
+
* @returns 延迟结束后完成。
|
|
499
|
+
*/
|
|
500
|
+
function delay(delayMs: number, signal: AbortSignal): Promise<void> {
|
|
501
|
+
return new Promise((resolveDelay, rejectDelay) => {
|
|
502
|
+
if (signal.aborted) {
|
|
503
|
+
rejectDelay(new IlinkQrLoginError("login_cancelled", "扫码授权已取消。"));
|
|
504
|
+
return;
|
|
505
|
+
}
|
|
506
|
+
const timer = setTimeout(() => {
|
|
507
|
+
signal.removeEventListener("abort", abort);
|
|
508
|
+
resolveDelay();
|
|
509
|
+
}, delayMs);
|
|
510
|
+
timer.unref();
|
|
511
|
+
const abort = (): void => {
|
|
512
|
+
clearTimeout(timer);
|
|
513
|
+
rejectDelay(new IlinkQrLoginError("login_cancelled", "扫码授权已取消。"));
|
|
514
|
+
};
|
|
515
|
+
signal.addEventListener("abort", abort, { once: true });
|
|
516
|
+
});
|
|
517
|
+
}
|
|
518
|
+
|
|
519
|
+
/**
|
|
520
|
+
* 验证 QR 扫描目标为微信官方 HTTPS 域名。
|
|
521
|
+
*
|
|
522
|
+
* @param value iLink 返回的二维码内容。
|
|
523
|
+
* @returns 可安全展示给用户的 URL。
|
|
524
|
+
*/
|
|
525
|
+
function validateQrContent(value: string): string {
|
|
526
|
+
let url: URL;
|
|
527
|
+
try {
|
|
528
|
+
url = new URL(value);
|
|
529
|
+
} catch {
|
|
530
|
+
throw new IlinkQrLoginError("qr_response_invalid", "iLink 返回了无效二维码内容。");
|
|
531
|
+
}
|
|
532
|
+
if (
|
|
533
|
+
url.protocol !== "https:" ||
|
|
534
|
+
(url.hostname !== "weixin.qq.com" && !url.hostname.endsWith(".weixin.qq.com")) ||
|
|
535
|
+
url.username || url.password || url.port
|
|
536
|
+
) {
|
|
537
|
+
throw new IlinkQrLoginError("qr_response_invalid", "二维码扫描目标不属于微信官方 HTTPS 域名。");
|
|
538
|
+
}
|
|
539
|
+
return url.toString();
|
|
540
|
+
}
|
|
541
|
+
|
|
542
|
+
/**
|
|
543
|
+
* 校验二维码确认返回的 iLink baseUrl。
|
|
544
|
+
*
|
|
545
|
+
* @param value 服务端 baseUrl。
|
|
546
|
+
* @returns 受信任的 HTTPS endpoint。
|
|
547
|
+
*/
|
|
548
|
+
function validateBaseUrl(value: string): string {
|
|
549
|
+
let url: URL;
|
|
550
|
+
try {
|
|
551
|
+
url = new URL(value);
|
|
552
|
+
} catch {
|
|
553
|
+
throw new IlinkQrLoginError("qr_response_invalid", "iLink 返回了无效 baseUrl。");
|
|
554
|
+
}
|
|
555
|
+
if (
|
|
556
|
+
url.protocol !== "https:" ||
|
|
557
|
+
(url.hostname !== "ilinkai.weixin.qq.com" && !url.hostname.endsWith(".ilinkai.weixin.qq.com")) ||
|
|
558
|
+
url.username || url.password || url.port || url.search || url.hash || url.pathname !== "/"
|
|
559
|
+
) {
|
|
560
|
+
throw new IlinkQrLoginError("qr_response_invalid", "iLink baseUrl 不属于受信任的官方 endpoint。");
|
|
561
|
+
}
|
|
562
|
+
return url.origin;
|
|
563
|
+
}
|
|
564
|
+
|
|
565
|
+
/**
|
|
566
|
+
* 将服务端 redirect_host 限制在 iLink 官方域名下。
|
|
567
|
+
*
|
|
568
|
+
* @param host 服务端返回的 redirect host。
|
|
569
|
+
* @returns HTTPS baseUrl。
|
|
570
|
+
*/
|
|
571
|
+
function validateRedirectHost(host: string): string {
|
|
572
|
+
const candidate = `https://${host}`;
|
|
573
|
+
return validateBaseUrl(candidate);
|
|
574
|
+
}
|
|
575
|
+
|
|
576
|
+
/**
|
|
577
|
+
* 生成 iLink 要求的随机 X-WECHAT-UIN。
|
|
578
|
+
*
|
|
579
|
+
* @returns 随机 uint32 的十进制文本 Base64。
|
|
580
|
+
*/
|
|
581
|
+
function randomWechatUin(): string {
|
|
582
|
+
const uint32 = randomBytes(4).readUInt32BE(0);
|
|
583
|
+
return Buffer.from(String(uint32), "utf8").toString("base64");
|
|
584
|
+
}
|
|
585
|
+
|
|
586
|
+
/**
|
|
587
|
+
* 检查路径是否存在, 不读取文件内容。
|
|
588
|
+
*
|
|
589
|
+
* @param filePath 待检查路径。
|
|
590
|
+
* @returns lstat 成功时返回 true。
|
|
591
|
+
*/
|
|
592
|
+
async function pathExists(filePath: string): Promise<boolean> {
|
|
593
|
+
try {
|
|
594
|
+
await lstat(filePath);
|
|
595
|
+
return true;
|
|
596
|
+
} catch (error) {
|
|
597
|
+
if (isNodeError(error) && error.code === "ENOENT") {
|
|
598
|
+
return false;
|
|
599
|
+
}
|
|
600
|
+
throw error;
|
|
601
|
+
}
|
|
602
|
+
}
|
|
603
|
+
|
|
604
|
+
/**
|
|
605
|
+
* 判断值是否带有 Node.js error code。
|
|
606
|
+
*
|
|
607
|
+
* @param error 待判断值。
|
|
608
|
+
* @returns Node.js 错误对象时返回 true。
|
|
609
|
+
*/
|
|
610
|
+
function isNodeError(error: unknown): error is NodeJS.ErrnoException {
|
|
611
|
+
return error instanceof Error && "code" in error;
|
|
612
|
+
}
|