pi-wechat-session-hub 0.1.2 → 0.1.5

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.
@@ -0,0 +1,186 @@
1
+ import { createHash } from "node:crypto";
2
+ import { lstat, open, readFile, rename, unlink } from "node:fs/promises";
3
+ import { mkdir } from "node:fs/promises";
4
+ import { dirname, join } from "node:path";
5
+ import type { IlinkReplyContext } from "../channel-types.ts";
6
+
7
+ /**
8
+ * 持久化的最新活跃 context token 记录。
9
+ */
10
+ export interface ContextTokenRecord {
11
+ recipientId: string;
12
+ contextToken: string;
13
+ /** token 对应入站消息的 ISO 时间戳, 用于新鲜度判断。 */
14
+ receivedAt: string;
15
+ }
16
+
17
+ /**
18
+ * 表示 context token 存储不可信或读写失败。
19
+ */
20
+ export class ContextTokenStoreError extends Error {
21
+ /**
22
+ * 创建存储错误, 不包含 token 内容。
23
+ *
24
+ * @param code 稳定错误代码。
25
+ * @param message 面向用户的中文说明。
26
+ */
27
+ constructor(
28
+ readonly code: "path_unsafe" | "format_invalid" | "write_failed",
29
+ message: string,
30
+ ) {
31
+ super(message);
32
+ this.name = "ContextTokenStoreError";
33
+ }
34
+ }
35
+
36
+ /**
37
+ * 保存单条通知的最大字符数。
38
+ */
39
+ const MAX_NOTIFICATION_TEXT_LENGTH = 8000;
40
+
41
+ /**
42
+ * 将授权微信用户的最新 context token 持久化到 ACL 保护目录。
43
+ *
44
+ * iLink 主动发送必须携带目标用户最近一条入站消息的 context_token,
45
+ * 该 token 约 24 小时过期。本存储只保存一个用户的单条活跃记录,
46
+ * daemon 重启后自动恢复, 补发与提醒功能都依赖它。
47
+ */
48
+ export class ContextTokenStore {
49
+ private readonly filePath: string;
50
+
51
+ /**
52
+ * 创建 context token 存储。
53
+ *
54
+ * @param managerDirectory Hub 私有数据目录。
55
+ */
56
+ constructor(managerDirectory: string) {
57
+ this.filePath = join(managerDirectory, "ilink-context-token.json");
58
+ }
59
+
60
+ /**
61
+ * 记录最新入站消息的回复上下文, 覆盖旧记录。
62
+ *
63
+ * @param replyContext 入站消息的回复上下文。
64
+ * @param receivedAt 入站消息时间, 缺省为当前时间。
65
+ * @returns 无返回值。
66
+ * @throws {ContextTokenStoreError} 写入失败时抛出。
67
+ */
68
+ async record(replyContext: IlinkReplyContext, receivedAt = new Date().toISOString()): Promise<void> {
69
+ if (!replyContext.recipientId.trim() || !replyContext.contextToken.trim()) {
70
+ return;
71
+ }
72
+ const record: ContextTokenRecord = {
73
+ recipientId: replyContext.recipientId,
74
+ contextToken: replyContext.contextToken,
75
+ receivedAt,
76
+ };
77
+ await this.writeFileAtomically(`${JSON.stringify(record, null, 2)}\n`);
78
+ }
79
+
80
+ /**
81
+ * 读取最新记录, 文件不存在时返回 undefined。
82
+ *
83
+ * @returns 最新 context token 记录。
84
+ * @throws {ContextTokenStoreError} 文件类型不可信或格式无效时抛出。
85
+ */
86
+ async load(): Promise<ContextTokenRecord | undefined> {
87
+ let fileInfo;
88
+ try {
89
+ fileInfo = await lstat(this.filePath);
90
+ } catch (error) {
91
+ if (isNodeError(error) && error.code === "ENOENT") {
92
+ return undefined;
93
+ }
94
+ throw error;
95
+ }
96
+ if (!fileInfo.isFile() || fileInfo.isSymbolicLink()) {
97
+ throw new ContextTokenStoreError("path_unsafe", "context token 文件类型不可信。");
98
+ }
99
+ let parsed: unknown;
100
+ try {
101
+ parsed = JSON.parse(await readFile(this.filePath, "utf8")) as unknown;
102
+ } catch (error) {
103
+ if (error instanceof SyntaxError) {
104
+ throw new ContextTokenStoreError("format_invalid", "context token 文件 JSON 无效。");
105
+ }
106
+ throw error;
107
+ }
108
+ if (
109
+ typeof parsed !== "object" ||
110
+ parsed === null ||
111
+ Array.isArray(parsed)
112
+ ) {
113
+ throw new ContextTokenStoreError("format_invalid", "context token 文件根节点无效。");
114
+ }
115
+ const record = parsed as Record<string, unknown>;
116
+ if (
117
+ typeof record.recipientId !== "string" ||
118
+ !record.recipientId.trim() ||
119
+ typeof record.contextToken !== "string" ||
120
+ !record.contextToken.trim() ||
121
+ typeof record.receivedAt !== "string" ||
122
+ Number.isNaN(new Date(record.receivedAt).getTime())
123
+ ) {
124
+ throw new ContextTokenStoreError("format_invalid", "context token 记录字段无效。");
125
+ }
126
+ return {
127
+ recipientId: record.recipientId,
128
+ contextToken: record.contextToken,
129
+ receivedAt: record.receivedAt,
130
+ };
131
+ }
132
+
133
+ /**
134
+ * 原子写入记录文件, 0600 权限, 同目录临时文件。
135
+ *
136
+ * @param contents 文件内容。
137
+ * @returns 无返回值。
138
+ */
139
+ private async writeFileAtomically(contents: string): Promise<void> {
140
+ await mkdir(dirname(this.filePath), { recursive: true });
141
+ const temporaryPath = `${this.filePath}.${process.pid}.tmp`;
142
+ let handle;
143
+ try {
144
+ handle = await open(temporaryPath, "wx", 0o600);
145
+ await handle.writeFile(contents, "utf8");
146
+ await handle.sync();
147
+ await handle.close();
148
+ handle = undefined;
149
+ await rename(temporaryPath, this.filePath);
150
+ } catch (error) {
151
+ await handle?.close().catch(() => undefined);
152
+ await unlink(temporaryPath).catch(() => undefined);
153
+ throw new ContextTokenStoreError("write_failed", "context token 文件写入失败。");
154
+ }
155
+ }
156
+ }
157
+
158
+ /**
159
+ * 计算通知正文的稳定哈希, 用于幂等发送 ID。
160
+ *
161
+ * @param value 通知正文。
162
+ * @returns SHA-256 十六进制摘要前 32 位。
163
+ */
164
+ export function hashNotificationContent(value: string): string {
165
+ return createHash("sha256").update(value, "utf8").digest("hex").slice(0, 32);
166
+ }
167
+
168
+ /**
169
+ * 校验通知正文长度。
170
+ *
171
+ * @param text 待校验正文。
172
+ * @returns 超限时返回 false。
173
+ */
174
+ export function isNotificationTextValid(text: string): boolean {
175
+ return text.trim().length > 0 && text.length <= MAX_NOTIFICATION_TEXT_LENGTH;
176
+ }
177
+
178
+ /**
179
+ * 判断未知值是否为 Node.js 文件系统错误。
180
+ *
181
+ * @param error 待检查值。
182
+ * @returns 值带有错误代码时返回 true。
183
+ */
184
+ function isNodeError(error: unknown): error is NodeJS.ErrnoException {
185
+ return error instanceof Error && "code" in error;
186
+ }
@@ -0,0 +1,494 @@
1
+ import { createHmac, randomUUID, timingSafeEqual } from "node:crypto";
2
+ import { lstat, open, readFile } from "node:fs/promises";
3
+ import { createServer, type Server, type Socket } from "node:net";
4
+ import { dirname, join, resolve } from "node:path";
5
+ import { tmpdir } from "node:os";
6
+ import { createHash } from "node:crypto";
7
+ import type { NotificationService } from "./notification-service.ts";
8
+
9
+ /**
10
+ * 通知入口鉴权 key 的字节长度 (hex 后 64 字符)。
11
+ */
12
+ const NOTIFY_KEY_LENGTH = 32;
13
+
14
+ /**
15
+ * 请求时间戳允许的偏差窗口, 防重放。
16
+ */
17
+ export const NOTIFY_TIMESTAMP_WINDOW_MS = 5 * 60 * 1000;
18
+
19
+ /**
20
+ * 单帧最大字节数。
21
+ */
22
+ const MAX_FRAME_BYTES = 64 * 1024;
23
+
24
+ /**
25
+ * 单连接处理超时。
26
+ */
27
+ const CONNECTION_TIMEOUT_MS = 10000;
28
+
29
+ /**
30
+ * 通知入口请求体。
31
+ */
32
+ export interface NotificationIngressRequest {
33
+ title?: string;
34
+ text: string;
35
+ source?: string;
36
+ urgent?: boolean;
37
+ requestId?: string;
38
+ }
39
+
40
+ /**
41
+ * 通知入口响应体。
42
+ */
43
+ export interface NotificationIngressResponse {
44
+ ok: boolean;
45
+ code:
46
+ | "sent"
47
+ | "queued"
48
+ | "dropped_stale"
49
+ | "dropped_no_context"
50
+ | "notify_text_invalid"
51
+ | "notify_deliver_failed"
52
+ | "rate_limited"
53
+ | "protocol_error"
54
+ | "auth_failed";
55
+ message?: string;
56
+ position?: number;
57
+ retryAfterMs?: number;
58
+ }
59
+
60
+ /**
61
+ * 表示通知入口鉴权或协议失败。
62
+ */
63
+ export class NotificationIngressError extends Error {
64
+ /**
65
+ * 创建入口错误, 不包含 key 或请求正文。
66
+ *
67
+ * @param code 稳定错误代码。
68
+ * @param message 面向用户的中文说明。
69
+ */
70
+ constructor(
71
+ readonly code: "key_unavailable" | "auth_failed" | "protocol_error",
72
+ message: string,
73
+ ) {
74
+ super(message);
75
+ this.name = "NotificationIngressError";
76
+ }
77
+ }
78
+
79
+ /**
80
+ * 通知入口的内存级滑动窗口限流器。
81
+ */
82
+ export class NotificationRateLimiter {
83
+ private readonly timestamps: number[] = [];
84
+
85
+ /**
86
+ * 创建限流器。
87
+ *
88
+ * @param maxPerMinute 每分钟最大通知数。
89
+ * @param maxPerHour 每小时最大通知数。
90
+ */
91
+ constructor(
92
+ private readonly maxPerMinute: number,
93
+ private readonly maxPerHour: number,
94
+ ) {}
95
+
96
+ /**
97
+ * 检查并记录一次发送; 超限时返回建议重试毫秒数。
98
+ *
99
+ * @returns 允许时返回 0, 超限时返回建议等待毫秒数。
100
+ */
101
+ tryAcquire(): number {
102
+ const now = Date.now();
103
+ while (this.timestamps.length > 0 && now - this.timestamps[0] >= 60 * 60 * 1000) {
104
+ this.timestamps.shift();
105
+ }
106
+ const minuteWindow = this.timestamps.filter((ts) => now - ts < 60 * 1000);
107
+ if (minuteWindow.length >= this.maxPerMinute) {
108
+ return 60 * 1000 - (now - minuteWindow[0]);
109
+ }
110
+ if (this.timestamps.length >= this.maxPerHour) {
111
+ return 60 * 60 * 1000 - (now - this.timestamps[0]);
112
+ }
113
+ this.timestamps.push(now);
114
+ return 0;
115
+ }
116
+ }
117
+
118
+ /**
119
+ * 计算 named pipe / unix socket endpoint, 与 control IPC 同样的目录哈希模式。
120
+ *
121
+ * @param managerDirectory Hub 私有数据目录。
122
+ * @param platform 目标平台。
123
+ * @returns 本机 IPC endpoint。
124
+ */
125
+ export function createNotificationIngressEndpoint(
126
+ managerDirectory: string,
127
+ platform: NodeJS.Platform = process.platform,
128
+ ): string {
129
+ const resolved = resolve(managerDirectory);
130
+ const normalized = platform === "win32" ? resolved.toLowerCase() : resolved;
131
+ const scope = createHash("sha256").update(normalized).digest("hex").slice(0, 24);
132
+ if (platform === "win32") {
133
+ return `\\\\.\\pipe\\pi-wechat-session-hub-${scope}-notify`;
134
+ }
135
+ return join(tmpdir(), `pi-wechat-session-hub-${scope}-notify.sock`);
136
+ }
137
+
138
+ /**
139
+ * 读取或 create-only 创建通知入口共享密钥, 存于 manager 目录 (ACL 保护)。
140
+ *
141
+ * @param managerDirectory Hub 私有数据目录。
142
+ * @returns hex 编码的 64 字符 key。
143
+ * @throws {NotificationIngressError} key 文件不可信或写入失败时抛出。
144
+ */
145
+ export async function readOrCreateNotifyIngressKey(managerDirectory: string): Promise<string> {
146
+ const keyPath = join(managerDirectory, "notify-shared.key");
147
+ const { randomBytes } = await import("node:crypto");
148
+ let handle;
149
+ try {
150
+ handle = await open(keyPath, "wx", 0o600);
151
+ const newToken = randomBytes(NOTIFY_KEY_LENGTH).toString("hex");
152
+ await handle.writeFile(`${newToken}\n`, "utf8");
153
+ await handle.sync();
154
+ await handle.close();
155
+ return newToken;
156
+ } catch (error) {
157
+ await handle?.close().catch(() => undefined);
158
+ if (isNodeError(error) && error.code === "EEXIST") {
159
+ const existing = await readNotifyIngressKey(managerDirectory);
160
+ if (existing) {
161
+ return existing;
162
+ }
163
+ throw new NotificationIngressError("key_unavailable", "通知入口 key 文件不可读取。");
164
+ }
165
+ throw new NotificationIngressError("key_unavailable", "无法创建通知入口 key。");
166
+ }
167
+ }
168
+
169
+ /**
170
+ * 读取通知入口共享密钥。
171
+ *
172
+ * @param managerDirectory Hub 私有数据目录。
173
+ * @returns hex key, 文件不存在时返回 undefined。
174
+ * @throws {NotificationIngressError} 文件类型不可信或内容无效时抛出。
175
+ */
176
+ export async function readNotifyIngressKey(managerDirectory: string): Promise<string | undefined> {
177
+ const keyPath = join(managerDirectory, "notify-shared.key");
178
+ let keyInfo;
179
+ try {
180
+ keyInfo = await lstat(keyPath);
181
+ } catch (error) {
182
+ if (isNodeError(error) && error.code === "ENOENT") {
183
+ return undefined;
184
+ }
185
+ throw error;
186
+ }
187
+ if (!keyInfo.isFile() || keyInfo.isSymbolicLink()) {
188
+ throw new NotificationIngressError("key_unavailable", "通知入口 key 文件类型不可信。");
189
+ }
190
+ const token = await readFile(keyPath, "utf8");
191
+ if (!/^[a-f0-9]{64}\r?\n?$/i.test(token)) {
192
+ throw new NotificationIngressError("key_unavailable", "通知入口 key 内容无效。");
193
+ }
194
+ return token.trim();
195
+ }
196
+
197
+ /**
198
+ * 计算通知请求的 HMAC-SHA256 proof。
199
+ *
200
+ * proof 绑定 key、requestId、时间戳与 payload 哈希; 客户端与服务端用同一算法。
201
+ *
202
+ * @param key hex 共享密钥。
203
+ * @param requestId 请求 ID。
204
+ * @param timestamp 毫秒时间戳。
205
+ * @param payload 规范化 JSON 请求体字符串。
206
+ * @returns base64url proof。
207
+ */
208
+ export function computeNotifyProof(
209
+ key: string,
210
+ requestId: string,
211
+ timestamp: number,
212
+ payload: string,
213
+ ): string {
214
+ return createHmac("sha256", Buffer.from(key, "hex"))
215
+ .update(`${requestId}\n${timestamp}\n`, "utf8")
216
+ .update(payload, "utf8")
217
+ .digest("base64url");
218
+ }
219
+
220
+ /**
221
+ * 服务端帧校验结果。
222
+ */
223
+ export type NotifyFrameValidation =
224
+ | { valid: true; request: NotificationIngressRequest }
225
+ | { valid: false; reason: string };
226
+
227
+ /**
228
+ * 校验客户端发来的鉴权帧。
229
+ *
230
+ * @param frame 解析后的 JSON 帧。
231
+ * @param key hex 共享密钥。
232
+ * @param now 当前毫秒时间戳, 测试可注入。
233
+ * @returns 校验结果。
234
+ */
235
+ export function validateNotifyFrame(
236
+ frame: unknown,
237
+ key: string,
238
+ now = Date.now(),
239
+ ): NotifyFrameValidation {
240
+ if (typeof frame !== "object" || frame === null || Array.isArray(frame)) {
241
+ return { valid: false, reason: "frame 根节点必须是对象。" };
242
+ }
243
+ const record = frame as Record<string, unknown>;
244
+ const requestId = typeof record.requestId === "string" ? record.requestId : "";
245
+ const timestamp = typeof record.timestamp === "number" ? record.timestamp : NaN;
246
+ const proof = typeof record.proof === "string" ? record.proof : "";
247
+ const payload = typeof record.payload === "string" ? record.payload : "";
248
+ if (!requestId || !payload || !proof || Number.isNaN(timestamp)) {
249
+ return { valid: false, reason: "缺少 requestId、timestamp、payload 或 proof。" };
250
+ }
251
+ if (Math.abs(now - timestamp) > NOTIFY_TIMESTAMP_WINDOW_MS) {
252
+ return { valid: false, reason: "时间戳超出允许偏差, 请检查系统时钟。" };
253
+ }
254
+ const expected = computeNotifyProof(key, requestId, timestamp, payload);
255
+ const expectedBuf = Buffer.from(expected, "base64url");
256
+ const actualBuf = Buffer.from(proof, "base64url");
257
+ if (expectedBuf.length !== actualBuf.length || !timingSafeEqual(expectedBuf, actualBuf)) {
258
+ return { valid: false, reason: "鉴权失败。" };
259
+ }
260
+ let parsedPayload: unknown;
261
+ try {
262
+ parsedPayload = JSON.parse(payload) as unknown;
263
+ } catch {
264
+ return { valid: false, reason: "payload JSON 无效。" };
265
+ }
266
+ if (typeof parsedPayload !== "object" || parsedPayload === null || Array.isArray(parsedPayload)) {
267
+ return { valid: false, reason: "payload 根节点必须是对象。" };
268
+ }
269
+ const request = parsedPayload as Record<string, unknown>;
270
+ if (typeof request.text !== "string" || !request.text.trim()) {
271
+ return { valid: false, reason: "payload.text 必须是非空字符串。" };
272
+ }
273
+ return {
274
+ valid: true,
275
+ request: {
276
+ text: request.text,
277
+ ...(typeof request.title === "string" && request.title.trim() ? { title: request.title } : {}),
278
+ ...(typeof request.source === "string" && request.source.trim() ? { source: request.source } : {}),
279
+ requestId,
280
+ },
281
+ };
282
+ }
283
+
284
+ /**
285
+ * 基于 named pipe 的本机通知入口服务。
286
+ *
287
+ * 其他程序/会话通过零依赖客户端连接本 endpoint, 用 notify-shared.key
288
+ * 的 HMAC proof 投递通知; 服务端调用 NotificationService 直发微信。
289
+ * 不监听 TCP, 不暴露网络面。
290
+ */
291
+ export class NotificationIngressServer {
292
+ private server?: Server;
293
+ private readonly sockets = new Set<Socket>();
294
+
295
+ /**
296
+ * 创建通知入口服务。
297
+ *
298
+ * @param managerDirectory Hub 私有数据目录。
299
+ * @param notificationService 通知发送服务。
300
+ * @param rateLimiter 限流器。
301
+ * @param options 平台与 endpoint 覆盖值, 测试用。
302
+ */
303
+ constructor(
304
+ private readonly managerDirectory: string,
305
+ private readonly notificationService: NotificationService,
306
+ private readonly rateLimiter: NotificationRateLimiter = new NotificationRateLimiter(10, 60),
307
+ private readonly options: { endpoint?: string; platform?: NodeJS.Platform } = {},
308
+ ) {}
309
+
310
+ /**
311
+ * 开始监听通知入口。
312
+ *
313
+ * @returns 监听就绪后正常结束。
314
+ * @throws {NotificationIngressError} key 不可用或 endpoint 占用时抛出。
315
+ */
316
+ async listen(): Promise<void> {
317
+ if (this.server) {
318
+ return;
319
+ }
320
+ const key = await readOrCreateNotifyIngressKey(this.managerDirectory);
321
+ const endpoint = this.options.endpoint
322
+ ?? createNotificationIngressEndpoint(this.managerDirectory, this.options.platform ?? process.platform);
323
+ const server = createServer((socket) => {
324
+ this.sockets.add(socket);
325
+ socket.once("close", () => this.sockets.delete(socket));
326
+ void this.handleConnection(socket, key).catch(() => socket.destroy());
327
+ });
328
+ this.server = server;
329
+ await new Promise<void>((resolveListen, rejectListen) => {
330
+ const onError = (): void => {
331
+ server.off("listening", onListening);
332
+ this.server = undefined;
333
+ rejectListen(new NotificationIngressError("protocol_error", "通知入口无法监听本机 endpoint。"));
334
+ };
335
+ const onListening = (): void => {
336
+ server.off("error", onError);
337
+ resolveListen();
338
+ };
339
+ server.once("error", onError);
340
+ server.once("listening", onListening);
341
+ server.listen(endpoint);
342
+ });
343
+ }
344
+
345
+ /**
346
+ * 关闭入口服务并断开所有连接。
347
+ *
348
+ * @returns 关闭完成后正常结束。
349
+ */
350
+ async close(): Promise<void> {
351
+ for (const socket of this.sockets) {
352
+ socket.destroy();
353
+ }
354
+ this.sockets.clear();
355
+ const server = this.server;
356
+ this.server = undefined;
357
+ if (server) {
358
+ await new Promise<void>((resolveClose) => server.close(() => resolveClose()));
359
+ }
360
+ }
361
+
362
+ /**
363
+ * 返回当前 endpoint, 未监听时为 undefined。
364
+ *
365
+ * @returns endpoint 文本。
366
+ */
367
+ get listeningEndpoint(): string | undefined {
368
+ return this.server ? (this.options.endpoint ?? createNotificationIngressEndpoint(this.managerDirectory)) : undefined;
369
+ }
370
+
371
+ /**
372
+ * 完成单连接的读帧、鉴权、限流与投递。
373
+ *
374
+ * @param socket 客户端连接。
375
+ * @param key hex 共享密钥。
376
+ * @returns 处理完成后正常结束。
377
+ */
378
+ private async handleConnection(socket: Socket, key: string): Promise<void> {
379
+ socket.setEncoding("utf8");
380
+ let buffer = "";
381
+ let settled = false;
382
+ const finish = (response: NotificationIngressResponse): void => {
383
+ if (settled) {
384
+ return;
385
+ }
386
+ settled = true;
387
+ socket.end(`${JSON.stringify(response)}\n`, "utf8");
388
+ };
389
+ const timeout = setTimeout(() => {
390
+ finish({ ok: false, code: "protocol_error", message: "请求超时。" });
391
+ socket.destroy();
392
+ }, CONNECTION_TIMEOUT_MS);
393
+ timeout.unref();
394
+
395
+ socket.on("data", (chunk: string) => {
396
+ buffer += chunk;
397
+ if (Buffer.byteLength(buffer, "utf8") > MAX_FRAME_BYTES) {
398
+ finish({ ok: false, code: "protocol_error", message: "请求超出大小限制。" });
399
+ socket.destroy();
400
+ return;
401
+ }
402
+ const newline = buffer.indexOf("\n");
403
+ if (newline < 0) {
404
+ return;
405
+ }
406
+ const line = buffer.slice(0, newline);
407
+ let frame: unknown;
408
+ try {
409
+ frame = JSON.parse(line) as unknown;
410
+ } catch {
411
+ finish({ ok: false, code: "protocol_error", message: "请求 JSON 无效。" });
412
+ return;
413
+ }
414
+ const validation = validateNotifyFrame(frame, key);
415
+ if (!validation.valid) {
416
+ finish({ ok: false, code: "auth_failed", message: validation.reason });
417
+ return;
418
+ }
419
+ const retryAfterMs = this.rateLimiter.tryAcquire();
420
+ if (retryAfterMs > 0) {
421
+ finish({
422
+ ok: false,
423
+ code: "rate_limited",
424
+ message: "通知发送频率超限, 请稍后重试。",
425
+ retryAfterMs,
426
+ });
427
+ return;
428
+ }
429
+ void this.notificationService.notify({
430
+ title: validation.request.title,
431
+ text: validation.request.text,
432
+ source: validation.request.source,
433
+ }).then((result) => {
434
+ if (result.kind === "sent") {
435
+ finish({ ok: true, code: "sent" });
436
+ return;
437
+ }
438
+ if (result.kind === "queued") {
439
+ finish({ ok: true, code: "queued", position: result.position });
440
+ return;
441
+ }
442
+ if (result.kind === "dropped") {
443
+ finish({
444
+ ok: false,
445
+ code: result.code === "notify_stale" ? "dropped_stale" : "dropped_no_context",
446
+ message: result.code === "notify_stale"
447
+ ? "通知通道已超过 24 小时未互动, 通知被丢弃 (当前策略为 drop)。请先在微信与 Bot 互发一条消息。"
448
+ : "从未收到过你的微信消息, 无法主动发送。请先在微信与 Bot 互发一条消息。",
449
+ });
450
+ return;
451
+ }
452
+ finish({
453
+ ok: false,
454
+ code: result.code === "notify_text_invalid" ? "notify_text_invalid" : "notify_deliver_failed",
455
+ message: result.code === "notify_text_invalid"
456
+ ? "通知正文为空或超过长度上限。"
457
+ : "微信投递失败, 通知未送达。",
458
+ });
459
+ }).catch(() => {
460
+ finish({ ok: false, code: "notify_deliver_failed", message: "通知投递出现意外错误。" });
461
+ });
462
+ });
463
+ socket.on("error", () => socket.destroy());
464
+ }
465
+ }
466
+
467
+ /**
468
+ * 判断未知值是否为 Node.js 文件系统错误。
469
+ *
470
+ * @param error 待检查值。
471
+ * @returns 值带有错误代码时返回 true。
472
+ */
473
+ function isNodeError(error: unknown): error is NodeJS.ErrnoException {
474
+ return error instanceof Error && "code" in error;
475
+ }
476
+
477
+ /**
478
+ * 生成请求 ID 的兜底实现, 供客户端脚本复用。
479
+ *
480
+ * @returns UUID 字符串。
481
+ */
482
+ export function newNotificationRequestId(): string {
483
+ return randomUUID();
484
+ }
485
+
486
+ /**
487
+ * 为客户端导出 dirname 的最小替代, 避免脚本额外 import。
488
+ *
489
+ * @param path 任意路径。
490
+ * @returns 目录部分。
491
+ */
492
+ export function notificationKeyPath(managerDirectory: string): string {
493
+ return dirname(join(managerDirectory, "notify-shared.key"));
494
+ }