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.
Files changed (51) hide show
  1. package/LICENSE +661 -0
  2. package/README.md +365 -0
  3. package/docs/decisions/0001-ilink-context-token-queue.md +41 -0
  4. package/docs/handoff-next-session.md +134 -0
  5. package/docs/implementation-spec.md +147 -0
  6. package/extensions/wechat-session-hub.ts +589 -0
  7. package/package.json +67 -0
  8. package/scripts/pi-rpc-smoke.mjs +150 -0
  9. package/scripts/probe-wt-capability.mjs +27 -0
  10. package/scripts/start-ui-worker.ps1 +37 -0
  11. package/src/commands/ilink-qr-login-component.ts +148 -0
  12. package/src/commands/project-command-parser.ts +108 -0
  13. package/src/commands/tokenizer.ts +71 -0
  14. package/src/commands/wechat-manager-command-parser.ts +143 -0
  15. package/src/config/defaults.ts +30 -0
  16. package/src/config/paths.ts +56 -0
  17. package/src/config/store.ts +311 -0
  18. package/src/config/types.ts +33 -0
  19. package/src/config/validation.ts +221 -0
  20. package/src/gateway/channel-types.ts +47 -0
  21. package/src/gateway/command-parser.ts +291 -0
  22. package/src/gateway/command-router.ts +1449 -0
  23. package/src/gateway/credential-store.ts +611 -0
  24. package/src/gateway/durable-message-queue.ts +1043 -0
  25. package/src/gateway/gateway-control-ipc.ts +687 -0
  26. package/src/gateway/gateway-runtime.ts +726 -0
  27. package/src/gateway/ui-worker-extension-bridge.ts +1070 -0
  28. package/src/gateway/ui-worker-ipc.ts +1483 -0
  29. package/src/gateway/ui-worker-types.ts +50 -0
  30. package/src/gateway/wechat-ilink/api-client.ts +390 -0
  31. package/src/gateway/wechat-ilink/channel-adapter.ts +320 -0
  32. package/src/gateway/wechat-ilink/cursor-store.ts +134 -0
  33. package/src/gateway/wechat-ilink/qr-login.ts +612 -0
  34. package/src/gateway/wechat-ilink/typing-indicator.ts +133 -0
  35. package/src/gateway/windows-terminal-launcher.ts +247 -0
  36. package/src/projects/project-service.ts +483 -0
  37. package/src/registry/gateway-lease.ts +348 -0
  38. package/src/registry/manager-registry.ts +466 -0
  39. package/src/registry/types.ts +61 -0
  40. package/src/runtime/background-pi-worker.ts +309 -0
  41. package/src/runtime/background-worker-manager.ts +594 -0
  42. package/src/runtime/gateway-daemon.ts +281 -0
  43. package/src/runtime/gateway-lifecycle-operation.ts +308 -0
  44. package/src/runtime/gateway-service-controller.ts +339 -0
  45. package/src/runtime/gateway-worker-manager.ts +181 -0
  46. package/src/runtime/pi-cli.ts +56 -0
  47. package/src/runtime/pi-rpc-client.ts +427 -0
  48. package/src/runtime/ui-worker-manager.ts +1186 -0
  49. package/src/runtime/windows-logon-task-manager.ts +212 -0
  50. package/src/system/process-liveness.ts +88 -0
  51. package/tsconfig.json +19 -0
@@ -0,0 +1,611 @@
1
+ import { execFile } from "node:child_process";
2
+ import { constants, type Stats } from "node:fs";
3
+ import { lstat, open, realpath, stat, unlink } from "node:fs/promises";
4
+ import { promisify } from "node:util";
5
+ import { basename, dirname, join, resolve } from "node:path";
6
+ import type { IlinkCredentials } from "./wechat-ilink/api-client.ts";
7
+
8
+ const MAX_CREDENTIAL_FILE_BYTES = 64 * 1024;
9
+ const WINDOWS_ACL_SCRIPT = [
10
+ "$ErrorActionPreference = 'Stop'",
11
+ "$currentSid = [System.Security.Principal.WindowsIdentity]::GetCurrent().User.Value",
12
+ "$allowedSids = @($currentSid, 'S-1-5-18', 'S-1-5-32-544')",
13
+ "$violations = @()",
14
+ "$parentDirectory = Split-Path -Parent $env:PI_WECHAT_MANAGER_DIRECTORY",
15
+ "$targets = @($parentDirectory, $env:PI_WECHAT_MANAGER_DIRECTORY)",
16
+ "$entries = @(Get-ChildItem -LiteralPath $env:PI_WECHAT_MANAGER_DIRECTORY -Force -Recurse -ErrorAction Stop)",
17
+ "foreach ($entry in $entries) {",
18
+ " if ($entry.Attributes -band [System.IO.FileAttributes]::ReparsePoint) { $violations += 'reparse_point'; continue }",
19
+ " $targets += $entry.FullName",
20
+ "}",
21
+ "foreach ($target in $targets) {",
22
+ " $item = Get-Item -LiteralPath $target -Force",
23
+ " $acl = [System.IO.FileSystemAclExtensions]::GetAccessControl($item)",
24
+ " $ownerSid = $acl.GetOwner([System.Security.Principal.SecurityIdentifier]).Value",
25
+ " if ($allowedSids -notcontains $ownerSid) { $violations += ('untrusted_owner:' + $target + ':' + $ownerSid) }",,,
26
+ " $rules = $acl.GetAccessRules($true, $true, [System.Security.Principal.SecurityIdentifier])",
27
+ " foreach ($rule in $rules) {",
28
+ " if ($rule.AccessControlType -ne [System.Security.AccessControl.AccessControlType]::Allow) { continue }",
29
+ " $sid = $rule.IdentityReference.Value",
30
+ " if ($allowedSids -contains $sid) { continue }",
31
+ " if ($target -eq $parentDirectory) {",
32
+ " $writeMask = [int]([System.Security.AccessControl.FileSystemRights]::WriteData -bor [System.Security.AccessControl.FileSystemRights]::AppendData -bor [System.Security.AccessControl.FileSystemRights]::CreateFiles -bor [System.Security.AccessControl.FileSystemRights]::CreateDirectories -bor [System.Security.AccessControl.FileSystemRights]::WriteAttributes -bor [System.Security.AccessControl.FileSystemRights]::WriteExtendedAttributes -bor [System.Security.AccessControl.FileSystemRights]::Delete -bor [System.Security.AccessControl.FileSystemRights]::DeleteSubdirectoriesAndFiles -bor [System.Security.AccessControl.FileSystemRights]::ChangePermissions -bor [System.Security.AccessControl.FileSystemRights]::TakeOwnership)",
33
+ " if (([int]$rule.FileSystemRights -band $writeMask) -eq 0) { continue }",
34
+ " }",
35
+ " $violations += ('untrusted_allow_ace:' + $target + ':' + $sid + ':' + $rule.FileSystemRights)",,,
36
+ " }",
37
+ "}",
38
+ "if ($violations.Count -gt 0) { [Console]::Error.WriteLine(($violations -join '|')); exit 23 }",
39
+ "[Console]::Out.Write('ok')",
40
+ ].join("\n");
41
+
42
+ /**
43
+ * 描述 POSIX manager/parent/file mode 和 owner UID 的权限快照。
44
+ */
45
+ export interface PosixCredentialPermissionSnapshot {
46
+ managerMode: number;
47
+ parentMode: number;
48
+ fileMode: number;
49
+ managerUid: number;
50
+ fileUid: number;
51
+ currentUid?: number;
52
+ }
53
+
54
+ /**
55
+ * 判断 POSIX 凭证路径是否没有 group/other 读取或写入权限。
56
+ *
57
+ * @param snapshot manager、父目录、凭证文件 mode 和 owner UID。
58
+ * @returns manager/file 私有且父目录不可被其他主体写入时返回 true。
59
+ */
60
+ export function isPosixCredentialPermissionSafe(
61
+ snapshot: PosixCredentialPermissionSnapshot,
62
+ ): boolean {
63
+ const ownerMatches = snapshot.currentUid === undefined || (
64
+ snapshot.managerUid === snapshot.currentUid && snapshot.fileUid === snapshot.currentUid
65
+ );
66
+ return (snapshot.managerMode & 0o077) === 0 &&
67
+ (snapshot.parentMode & 0o022) === 0 &&
68
+ (snapshot.fileMode & 0o077) === 0 &&
69
+ ownerMatches;
70
+ }
71
+
72
+ export interface IlinkCredentialRecord {
73
+ schemaVersion: 1;
74
+ authorizedUserId: string;
75
+ token: string;
76
+ baseUrl: string;
77
+ }
78
+
79
+ export interface CreatedIlinkCredential {
80
+ filePath: string;
81
+ device: number;
82
+ inode: number;
83
+ }
84
+
85
+ export type IlinkCredentialStoreOptions = {
86
+ platform?: NodeJS.Platform;
87
+ verifyWindowsAcl?: (managerDirectory: string, credentialFile: string) => Promise<void>;
88
+ };
89
+
90
+ /**
91
+ * 确认 manager 目录权限安全后, 才能开始扫码流程或写入新的 Hub 凭证。
92
+ *
93
+ * @param managerDirectory Hub 私有 manager 数据目录。
94
+ * @param options 平台覆盖和 Windows ACL 验证器。
95
+ * @returns 目录及其父目录满足平台权限策略时正常返回。
96
+ * @throws {IlinkCredentialStoreError} 路径、ACL 或 POSIX mode 不安全时抛出。
97
+ */
98
+ export async function verifyCredentialDirectoryPermissions(
99
+ managerDirectory: string,
100
+ options: IlinkCredentialStoreOptions = {},
101
+ ): Promise<void> {
102
+ const platform = options.platform ?? process.platform;
103
+ const directory = resolve(managerDirectory);
104
+ let directoryInfo: Stats;
105
+ let parentInfo: Stats;
106
+ try {
107
+ directoryInfo = await lstat(directory);
108
+ parentInfo = await lstat(dirname(directory));
109
+ if (
110
+ !directoryInfo.isDirectory() || directoryInfo.isSymbolicLink() ||
111
+ !parentInfo.isDirectory() || parentInfo.isSymbolicLink()
112
+ ) {
113
+ throw new Error("unsafe_directory");
114
+ }
115
+ } catch {
116
+ throw new IlinkCredentialStoreError(
117
+ "credential_path_unsafe",
118
+ "Hub manager 目录或父目录无法安全验证。",
119
+ );
120
+ }
121
+
122
+ if (platform === "win32") {
123
+ try {
124
+ await (options.verifyWindowsAcl ?? verifyWindowsAcl)(directory, join(directory, "credentials.json"));
125
+ return;
126
+ } catch {
127
+ throw new IlinkCredentialStoreError(
128
+ "credential_permissions_unsafe",
129
+ "Windows Hub 目录 ACL 不安全; 请只授权当前用户、SYSTEM 和 Administrators。",
130
+ );
131
+ }
132
+ }
133
+
134
+ const parentDirectoryInfo = await stat(dirname(directory)).catch(() => undefined);
135
+ const currentUid = process.getuid?.();
136
+ if (
137
+ !parentDirectoryInfo ||
138
+ (directoryInfo.mode & 0o077) !== 0 ||
139
+ (parentDirectoryInfo.mode & 0o022) !== 0 ||
140
+ (currentUid !== undefined && directoryInfo.uid !== currentUid)
141
+ ) {
142
+ throw new IlinkCredentialStoreError(
143
+ "credential_permissions_unsafe",
144
+ "POSIX Hub 目录必须归当前用户所有且无 group/other 权限, 父目录也不能被其他主体写入。",
145
+ );
146
+ }
147
+ }
148
+
149
+ /**
150
+ * 独占创建 Hub 专属 credentials.json, 绝不覆盖已存在文件。
151
+ *
152
+ * @param managerDirectory Hub 私有 manager 数据目录。
153
+ * @param record 已确认的 iLink 凭证记录。
154
+ * @param options 平台覆盖和 Windows ACL 验证器。
155
+ * @returns 新建文件身份, 供配置更新失败时安全回滚。
156
+ * @throws {IlinkCredentialStoreError} 文件已存在、权限不安全或内容不合法时抛出。
157
+ */
158
+ export async function createIlinkCredentialFile(
159
+ managerDirectory: string,
160
+ record: IlinkCredentialRecord,
161
+ options: IlinkCredentialStoreOptions = {},
162
+ ): Promise<CreatedIlinkCredential> {
163
+ const directory = resolve(managerDirectory);
164
+ const filePath = join(directory, "credentials.json");
165
+ const validated = parseCredentialRecord(JSON.stringify(record));
166
+ await verifyCredentialDirectoryPermissions(directory, options);
167
+
168
+ let handle: Awaited<ReturnType<typeof open>> | undefined;
169
+ let createdInfo: Stats | undefined;
170
+ try {
171
+ handle = await open(filePath, "wx", 0o600);
172
+ createdInfo = await handle.stat();
173
+ await handle.writeFile(`${JSON.stringify(validated)}\n`, "utf8");
174
+ await handle.sync();
175
+ } catch (error) {
176
+ await handle?.close().catch(() => undefined);
177
+ if (isNodeError(error) && error.code === "EEXIST") {
178
+ throw new IlinkCredentialStoreError(
179
+ "credential_exists",
180
+ "Pi Hub 已有 credentials.json, 为避免覆盖凭证, 登录已停止。",
181
+ );
182
+ }
183
+ if (createdInfo) {
184
+ await removeCreatedIlinkCredentialIfUnchanged({
185
+ filePath,
186
+ device: createdInfo.dev,
187
+ inode: createdInfo.ino,
188
+ });
189
+ }
190
+ throw new IlinkCredentialStoreError(
191
+ "credential_file_unsafe",
192
+ "无法安全创建 Pi Hub credentials.json。",
193
+ );
194
+ }
195
+ if (!createdInfo) {
196
+ throw new IlinkCredentialStoreError(
197
+ "credential_file_unsafe",
198
+ "无法确认新凭证文件身份, 登录已停止。",
199
+ );
200
+ }
201
+ try {
202
+ await handle?.close();
203
+ } catch {
204
+ await removeCreatedIlinkCredentialIfUnchanged({
205
+ filePath,
206
+ device: createdInfo.dev,
207
+ inode: createdInfo.ino,
208
+ });
209
+ throw new IlinkCredentialStoreError(
210
+ "credential_file_unsafe",
211
+ "无法安全关闭新建凭证文件。",
212
+ );
213
+ }
214
+
215
+ const created: CreatedIlinkCredential = {
216
+ filePath,
217
+ device: createdInfo.dev,
218
+ inode: createdInfo.ino,
219
+ };
220
+ try {
221
+ await new IlinkCredentialStore(directory, filePath, options).load(validated.authorizedUserId);
222
+ return created;
223
+ } catch (error) {
224
+ await removeCreatedIlinkCredentialIfUnchanged(created);
225
+ if (error instanceof IlinkCredentialStoreError) {
226
+ throw error;
227
+ }
228
+ throw new IlinkCredentialStoreError(
229
+ "credential_file_unsafe",
230
+ "新凭证未通过 Hub 安全校验, 已清理本次创建的文件。",
231
+ );
232
+ }
233
+ }
234
+
235
+ /**
236
+ * 只删除本次创建且 inode/dev 仍匹配的 Hub credentials.json。
237
+ *
238
+ * @param created 本次新建文件的路径和文件身份。
239
+ * @returns 文件已删除或已不存在时返回 true; 身份不匹配时返回 false。
240
+ */
241
+ export async function removeCreatedIlinkCredentialIfUnchanged(
242
+ created: CreatedIlinkCredential,
243
+ ): Promise<boolean> {
244
+ try {
245
+ const current = await lstat(created.filePath);
246
+ if (
247
+ current.isSymbolicLink() ||
248
+ current.dev !== created.device ||
249
+ current.ino !== created.inode
250
+ ) {
251
+ return false;
252
+ }
253
+ await unlink(created.filePath);
254
+ return true;
255
+ } catch (error) {
256
+ return isNodeError(error) && error.code === "ENOENT";
257
+ }
258
+ }
259
+
260
+ /**
261
+ * iLink 凭证读取和安全校验失败的稳定错误代码。
262
+ */
263
+ export type IlinkCredentialStoreErrorCode =
264
+ | "credential_missing"
265
+ | "credential_path_unsafe"
266
+ | "credential_file_unsafe"
267
+ | "credential_exists"
268
+ | "credential_permissions_unsafe"
269
+ | "credential_invalid"
270
+ | "authorized_user_mismatch";
271
+
272
+ /**
273
+ * 表示 iLink 凭证文件缺失、格式不合法或权限无法安全验证。
274
+ */
275
+ export class IlinkCredentialStoreError extends Error {
276
+ /**
277
+ * 创建不包含凭证内容的凭证存储错误。
278
+ *
279
+ * @param code 稳定错误代码。
280
+ * @param message 可安全显示给用户的中文说明。
281
+ */
282
+ constructor(
283
+ readonly code: IlinkCredentialStoreErrorCode,
284
+ message: string,
285
+ ) {
286
+ super(message);
287
+ this.name = "IlinkCredentialStoreError";
288
+ }
289
+ }
290
+
291
+ /**
292
+ * 只读加载枢纽专属 iLink 凭证, 不创建、更新或迁移任何账号数据。
293
+ */
294
+ export class IlinkCredentialStore {
295
+ private readonly managerDirectory: string;
296
+ private readonly credentialFile: string;
297
+ private readonly platform: NodeJS.Platform;
298
+ private readonly verifyWindowsAcl?: (managerDirectory: string, credentialFile: string) => Promise<void>;
299
+
300
+ /**
301
+ * 创建受限凭证文件 reader。
302
+ *
303
+ * @param managerDirectory 枢纽专属 manager 数据目录。
304
+ * @param credentialFile 配置中的凭证文件绝对路径。
305
+ * @param options 可选平台覆盖和 Windows ACL 验证器。
306
+ */
307
+ constructor(
308
+ managerDirectory: string,
309
+ credentialFile: string,
310
+ options: IlinkCredentialStoreOptions = {},
311
+ ) {
312
+ this.managerDirectory = resolve(managerDirectory);
313
+ this.credentialFile = resolve(credentialFile);
314
+ this.platform = options.platform ?? process.platform;
315
+ this.verifyWindowsAcl = options.verifyWindowsAcl;
316
+ }
317
+
318
+ /**
319
+ * 读取并验证凭证文件, 并校验其中声明的授权微信用户。
320
+ *
321
+ * @param expectedAuthorizedUserId 配置中的唯一授权用户 ID。
322
+ * @returns 仅供内存使用的 iLink API 凭证。
323
+ * @throws {IlinkCredentialStoreError} 文件路径、权限、内容或用户 ID 不安全时抛出。
324
+ */
325
+ async load(expectedAuthorizedUserId: string): Promise<IlinkCredentials> {
326
+ if (!expectedAuthorizedUserId.trim()) {
327
+ throw new IlinkCredentialStoreError(
328
+ "authorized_user_mismatch",
329
+ "启动 Gateway 前必须配置唯一授权微信 userId。",
330
+ );
331
+ }
332
+ this.assertConfiguredPathIsAppOwned();
333
+
334
+ let canonicalDirectory: string;
335
+ try {
336
+ canonicalDirectory = await realpath(this.managerDirectory);
337
+ } catch {
338
+ throw new IlinkCredentialStoreError(
339
+ "credential_path_unsafe",
340
+ "枢纽数据目录不存在或无法解析, 已拒绝读取凭证。",
341
+ );
342
+ }
343
+ let canonicalParent: string;
344
+ let fileStat;
345
+ try {
346
+ const directoryStat = await lstat(this.managerDirectory);
347
+ const parentStat = await lstat(dirname(this.managerDirectory));
348
+ if (
349
+ !directoryStat.isDirectory() || directoryStat.isSymbolicLink() ||
350
+ !parentStat.isDirectory() || parentStat.isSymbolicLink()
351
+ ) {
352
+ throw new Error("unsafe_manager_directory");
353
+ }
354
+ canonicalParent = await realpath(dirname(this.credentialFile));
355
+ fileStat = await lstat(this.credentialFile);
356
+ } catch (error) {
357
+ if (isNodeError(error) && error.code === "ENOENT") {
358
+ throw new IlinkCredentialStoreError(
359
+ "credential_missing",
360
+ "未找到枢纽专属 iLink 凭证文件; Gateway 不会自动扫码, 也不会读取其他应用凭证。",
361
+ );
362
+ }
363
+ if (error instanceof IlinkCredentialStoreError) {
364
+ throw error;
365
+ }
366
+ throw new IlinkCredentialStoreError(
367
+ "credential_file_unsafe",
368
+ "iLink 凭证文件无法安全检查。",
369
+ );
370
+ }
371
+ if (
372
+ !samePath(canonicalDirectory, canonicalParent, this.platform) ||
373
+ fileStat.isSymbolicLink() ||
374
+ !fileStat.isFile() ||
375
+ fileStat.size <= 0 ||
376
+ fileStat.size > MAX_CREDENTIAL_FILE_BYTES
377
+ ) {
378
+ throw new IlinkCredentialStoreError(
379
+ "credential_file_unsafe",
380
+ "凭证必须是枢纽数据目录中的普通 credentials.json 文件, 且大小不能超过 64 KB。",
381
+ );
382
+ }
383
+
384
+ await this.verifyPermissions(canonicalDirectory, this.credentialFile, fileStat);
385
+ const content = await this.readOpenedFile(fileStat);
386
+ const record = parseCredentialRecord(content);
387
+ if (record.authorizedUserId !== expectedAuthorizedUserId) {
388
+ throw new IlinkCredentialStoreError(
389
+ "authorized_user_mismatch",
390
+ "凭证文件声明的授权微信 userId 与配置不一致, 已拒绝启动。",
391
+ );
392
+ }
393
+ return { token: record.token, baseUrl: record.baseUrl };
394
+ }
395
+
396
+ /**
397
+ * 确保配置路径精确指向 manager 数据目录的固定凭证文件。
398
+ *
399
+ * @returns 无返回值。
400
+ * @throws {IlinkCredentialStoreError} 配置路径越界或使用其他文件名时抛出。
401
+ */
402
+ private assertConfiguredPathIsAppOwned(): void {
403
+ const expected = join(this.managerDirectory, "credentials.json");
404
+ if (
405
+ basename(this.credentialFile) !== "credentials.json" ||
406
+ !samePath(this.credentialFile, expected, this.platform)
407
+ ) {
408
+ throw new IlinkCredentialStoreError(
409
+ "credential_path_unsafe",
410
+ "wechat.credentialFile 必须指向枢纽数据目录中的 credentials.json, 不读取目录外凭证。",
411
+ );
412
+ }
413
+ }
414
+
415
+ /**
416
+ * 在当前平台验证凭证文件和父目录权限。
417
+ *
418
+ * @param managerDirectory 规范化后的 manager 数据目录。
419
+ * @param credentialFile 凭证文件路径。
420
+ * @param fileStat 初步取得的文件状态。
421
+ * @returns 无返回值。
422
+ * @throws {IlinkCredentialStoreError} 权限不满足当前平台策略时抛出。
423
+ */
424
+ private async verifyPermissions(
425
+ managerDirectory: string,
426
+ credentialFile: string,
427
+ fileStat: Stats,
428
+ ): Promise<void> {
429
+ if (this.platform === "win32") {
430
+ if (this.verifyWindowsAcl) {
431
+ try {
432
+ await this.verifyWindowsAcl(managerDirectory, credentialFile);
433
+ return;
434
+ } catch {
435
+ throw new IlinkCredentialStoreError(
436
+ "credential_permissions_unsafe",
437
+ "Windows 凭证目录 ACL 未通过验证; 请仅授权当前用户、SYSTEM 和 Administrators。",
438
+ );
439
+ }
440
+ }
441
+ await verifyWindowsAcl(managerDirectory, credentialFile);
442
+ return;
443
+ }
444
+
445
+ const directoryStat = await stat(managerDirectory);
446
+ const parentDirectoryStat = await stat(dirname(managerDirectory));
447
+ const getUid = process.getuid;
448
+ if (!isPosixCredentialPermissionSafe({
449
+ managerMode: directoryStat.mode,
450
+ parentMode: parentDirectoryStat.mode,
451
+ fileMode: fileStat.mode,
452
+ managerUid: directoryStat.uid,
453
+ fileUid: fileStat.uid,
454
+ ...(getUid ? { currentUid: getUid() } : {}),
455
+ })) {
456
+ throw new IlinkCredentialStoreError(
457
+ "credential_permissions_unsafe",
458
+ "POSIX 凭证目录和文件必须归当前用户所有, 且 group/other 权限为 0。",
459
+ );
460
+ }
461
+ }
462
+
463
+ /**
464
+ * 以已打开文件句柄读取凭证, 并检查打开对象与 lstat 对象一致。
465
+ *
466
+ * @param expectedStat 打开前取得的普通文件状态。
467
+ * @returns UTF-8 文件内容。
468
+ * @throws {IlinkCredentialStoreError} 文件被替换或无法安全打开时抛出。
469
+ */
470
+ private async readOpenedFile(expectedStat: Stats): Promise<string> {
471
+ let handle;
472
+ try {
473
+ const noFollow = "O_NOFOLLOW" in constants ? constants.O_NOFOLLOW : 0;
474
+ handle = await open(this.credentialFile, constants.O_RDONLY | noFollow);
475
+ const openedStat = await handle.stat();
476
+ if (
477
+ !openedStat.isFile() ||
478
+ openedStat.dev !== expectedStat.dev ||
479
+ openedStat.ino !== expectedStat.ino ||
480
+ openedStat.size > MAX_CREDENTIAL_FILE_BYTES
481
+ ) {
482
+ throw new IlinkCredentialStoreError(
483
+ "credential_file_unsafe",
484
+ "凭证文件在读取期间发生变化, 已拒绝使用。",
485
+ );
486
+ }
487
+ return await handle.readFile("utf8");
488
+ } catch (error) {
489
+ if (error instanceof IlinkCredentialStoreError) {
490
+ throw error;
491
+ }
492
+ throw new IlinkCredentialStoreError(
493
+ "credential_file_unsafe",
494
+ "凭证文件无法安全读取。",
495
+ );
496
+ } finally {
497
+ await handle?.close().catch(() => undefined);
498
+ }
499
+ }
500
+ }
501
+
502
+ /**
503
+ * 验证 iLink 凭证文件的 JSON schema 和字段边界。
504
+ *
505
+ * @param content UTF-8 凭证文件内容。
506
+ * @returns 已校验的枢纽专属凭证记录。
507
+ * @throws {IlinkCredentialStoreError} JSON/schema 不合法时抛出。
508
+ */
509
+ function parseCredentialRecord(content: string): IlinkCredentialRecord {
510
+ let parsed: unknown;
511
+ try {
512
+ parsed = JSON.parse(content) as unknown;
513
+ } catch {
514
+ throw new IlinkCredentialStoreError(
515
+ "credential_invalid",
516
+ "iLink 凭证文件不是有效 JSON。",
517
+ );
518
+ }
519
+ if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) {
520
+ throw new IlinkCredentialStoreError(
521
+ "credential_invalid",
522
+ "iLink 凭证文件根节点必须是 JSON 对象。",
523
+ );
524
+ }
525
+ const record = parsed as Record<string, unknown>;
526
+ const allowedKeys = new Set(["schemaVersion", "authorizedUserId", "token", "baseUrl"]);
527
+ if (
528
+ Object.keys(record).some((key) => !allowedKeys.has(key)) ||
529
+ record.schemaVersion !== 1 ||
530
+ typeof record.authorizedUserId !== "string" ||
531
+ !record.authorizedUserId.trim() ||
532
+ typeof record.token !== "string" ||
533
+ !record.token.trim() ||
534
+ record.token.length > 16384 ||
535
+ typeof record.baseUrl !== "string" ||
536
+ !record.baseUrl.trim() ||
537
+ record.baseUrl.length > 2048
538
+ ) {
539
+ throw new IlinkCredentialStoreError(
540
+ "credential_invalid",
541
+ "iLink 凭证文件必须仅包含 schemaVersion、authorizedUserId、token 和 baseUrl, 且字段有效。",
542
+ );
543
+ }
544
+ return {
545
+ schemaVersion: 1,
546
+ authorizedUserId: record.authorizedUserId,
547
+ token: record.token,
548
+ baseUrl: record.baseUrl,
549
+ };
550
+ }
551
+
552
+ /**
553
+ * 使用 PowerShell/.NET 检查 Windows manager 目录和凭证文件 ACL。
554
+ *
555
+ * @param managerDirectory manager 数据目录。
556
+ * @param credentialFile iLink 凭证文件。
557
+ * @returns ACL 仅授予当前用户、SYSTEM 和 Administrators 时正常返回。
558
+ * @throws {Error} PowerShell 不可用或 ACL 包含其他授权主体时抛出。
559
+ */
560
+ async function verifyWindowsAcl(managerDirectory: string, credentialFile: string): Promise<void> {
561
+ const execFileAsync = promisify(execFile);
562
+ const encodedScript = Buffer.from(WINDOWS_ACL_SCRIPT, "utf16le").toString("base64");
563
+ try {
564
+ await execFileAsync(
565
+ "pwsh.exe",
566
+ ["-NoLogo", "-NoProfile", "-NonInteractive", "-EncodedCommand", encodedScript],
567
+ {
568
+ windowsHide: true,
569
+ timeout: 5000,
570
+ maxBuffer: 64 * 1024,
571
+ env: {
572
+ ...process.env,
573
+ PI_WECHAT_MANAGER_DIRECTORY: managerDirectory,
574
+ PI_WECHAT_CREDENTIAL_FILE: credentialFile,
575
+ },
576
+ },
577
+ );
578
+ } catch (error) {
579
+ const failureCode = isNodeError(error) ? String(error.code) : error instanceof Error ? error.name : typeof error;
580
+ throw new IlinkCredentialStoreError(
581
+ "credential_permissions_unsafe",
582
+ `Windows 凭证目录 ACL 未通过验证 (${failureCode}); 请仅授权当前用户、SYSTEM 和 Administrators。`,
583
+ );
584
+ }
585
+ }
586
+
587
+ /**
588
+ * 比较路径, 在 Windows 上忽略大小写。
589
+ *
590
+ * @param left 左侧路径。
591
+ * @param right 右侧路径。
592
+ * @param platform 目标平台。
593
+ * @returns 两条路径指向同一规范路径时返回 true。
594
+ */
595
+ function samePath(left: string, right: string, platform: NodeJS.Platform): boolean {
596
+ const normalizedLeft = resolve(left);
597
+ const normalizedRight = resolve(right);
598
+ return platform === "win32"
599
+ ? normalizedLeft.toLowerCase() === normalizedRight.toLowerCase()
600
+ : normalizedLeft === normalizedRight;
601
+ }
602
+
603
+ /**
604
+ * 判断值是否为 Node.js 文件系统错误。
605
+ *
606
+ * @param error 待检查值。
607
+ * @returns 值包含 Node.js 错误代码时返回 true。
608
+ */
609
+ function isNodeError(error: unknown): error is NodeJS.ErrnoException {
610
+ return error instanceof Error && "code" in error;
611
+ }