pi-wechat-session-hub 0.1.0 → 0.1.2
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/CHANGELOG.md +95 -0
- package/README.md +420 -365
- package/docs/handoff-next-session.md +4 -4
- package/docs/implementation-spec.md +150 -147
- package/extensions/daemon-entry.mjs +31 -0
- package/extensions/wechat-session-hub.ts +12 -12
- package/package.json +72 -67
- package/scripts/probe-wt-capability.mjs +26 -5
- package/scripts/release-preflight.mjs +229 -0
- package/src/gateway/command-parser.ts +25 -9
- package/src/gateway/command-router.ts +1790 -1449
- package/src/gateway/durable-message-queue.ts +1154 -1043
- package/src/gateway/gateway-control-ipc.ts +705 -687
- package/src/gateway/turn-health.ts +305 -0
- package/src/gateway/ui-worker-extension-bridge.ts +1092 -1070
- package/src/gateway/ui-worker-ipc.ts +1517 -1483
- package/src/gateway/wechat-ilink/api-client.ts +386 -390
- package/src/runtime/gateway-lifecycle-operation.ts +67 -2
- package/src/runtime/gateway-service-controller.ts +341 -339
- package/src/runtime/ui-worker-manager.ts +1216 -1186
- package/src/runtime/windows-logon-autostart-manager.ts +401 -0
- package/src/runtime/windows-logon-task-manager.ts +0 -212
|
@@ -1,687 +1,705 @@
|
|
|
1
|
-
import { createHash, createHmac, randomBytes, randomUUID, timingSafeEqual } from "node:crypto";
|
|
2
|
-
import { lstat, readFile, unlink } from "node:fs/promises";
|
|
3
|
-
import { createConnection, createServer, type Server, type Socket } from "node:net";
|
|
4
|
-
import { tmpdir } from "node:os";
|
|
5
|
-
import { join, resolve } from "node:path";
|
|
6
|
-
import type { GatewayLease } from "../registry/gateway-lease.ts";
|
|
7
|
-
|
|
8
|
-
export type GatewayControlAction = "status" | "stop" | "restart";
|
|
9
|
-
|
|
10
|
-
export interface GatewayControlHandlers {
|
|
11
|
-
/**
|
|
12
|
-
* 执行一个固定控制动作并返回其结果.
|
|
13
|
-
*
|
|
14
|
-
* @param action Gateway 控制动作.
|
|
15
|
-
* @returns 动作结果.
|
|
16
|
-
*/
|
|
17
|
-
handleAction(action: GatewayControlAction, operationId?: string): Promise<unknown>;
|
|
18
|
-
/**
|
|
19
|
-
* 在控制结果已发出并关闭当前请求连接后执行生命周期收尾.
|
|
20
|
-
*
|
|
21
|
-
* @param action 已完成的控制动作.
|
|
22
|
-
* @param operationId restart 动作的完成关联 ID.
|
|
23
|
-
* @returns 收尾完成后正常结束.
|
|
24
|
-
*/
|
|
25
|
-
afterActionResponse?(action: GatewayControlAction, operationId?: string): Promise<void>;
|
|
26
|
-
}
|
|
27
|
-
|
|
28
|
-
interface GatewayLeaseCredential {
|
|
29
|
-
ownerId: string;
|
|
30
|
-
pid: number;
|
|
31
|
-
processBirthId: string;
|
|
32
|
-
token: string;
|
|
33
|
-
}
|
|
34
|
-
|
|
35
|
-
/**
|
|
36
|
-
* 表示后台 Gateway 控制通道不可用或响应不可信。
|
|
37
|
-
*/
|
|
38
|
-
export class GatewayControlError extends Error {
|
|
39
|
-
/**
|
|
40
|
-
* 创建后台 Gateway 控制错误。
|
|
41
|
-
*
|
|
42
|
-
* @param code 稳定错误代码。
|
|
43
|
-
* @param message 可安全展示的中文说明。
|
|
44
|
-
*/
|
|
45
|
-
constructor(
|
|
46
|
-
readonly code: "not_running" | "protocol_error" | "authentication_failed" | "request_failed" | "timeout",
|
|
47
|
-
message: string,
|
|
48
|
-
) {
|
|
49
|
-
super(message);
|
|
50
|
-
this.name = "GatewayControlError";
|
|
51
|
-
}
|
|
52
|
-
}
|
|
53
|
-
|
|
54
|
-
/**
|
|
55
|
-
* 提供独立于 Pi TUI 生命周期的本机 Gateway 控制 named pipe 或 Unix socket。
|
|
56
|
-
*/
|
|
57
|
-
export class GatewayControlServer {
|
|
58
|
-
readonly endpoint: string;
|
|
59
|
-
private server?: Server;
|
|
60
|
-
private readonly sockets = new Set<Socket>();
|
|
61
|
-
private readonly platform: NodeJS.Platform;
|
|
62
|
-
|
|
63
|
-
/**
|
|
64
|
-
* 创建经过 Gateway lease 认证的本机控制服务。
|
|
65
|
-
*
|
|
66
|
-
* @param managerDirectory Hub 私有数据目录。
|
|
67
|
-
* @param lease 当前 Gateway lease。
|
|
68
|
-
* @param handlers 只接受枚举控制动作的处理器。
|
|
69
|
-
* @param options 平台和测试 endpoint 覆盖值。
|
|
70
|
-
*/
|
|
71
|
-
constructor(
|
|
72
|
-
private readonly managerDirectory: string,
|
|
73
|
-
private readonly lease: GatewayLease,
|
|
74
|
-
private readonly handlers: GatewayControlHandlers,
|
|
75
|
-
options: { endpoint?: string; platform?: NodeJS.Platform } = {},
|
|
76
|
-
) {
|
|
77
|
-
this.platform = options.platform ?? process.platform;
|
|
78
|
-
this.endpoint = options.endpoint ?? createGatewayControlEndpoint(managerDirectory, this.platform);
|
|
79
|
-
}
|
|
80
|
-
|
|
81
|
-
/**
|
|
82
|
-
* 开始监听控制请求。
|
|
83
|
-
*
|
|
84
|
-
* @returns IPC endpoint 开始监听时正常结束。
|
|
85
|
-
* @throws {GatewayControlError} endpoint 无法安全创建或已被占用时抛出。
|
|
86
|
-
*/
|
|
87
|
-
async listen(): Promise<void> {
|
|
88
|
-
if (this.platform !== "win32" && !this.endpoint.startsWith("/")) {
|
|
89
|
-
throw new GatewayControlError("protocol_error", "本机控制 socket 路径无效。");
|
|
90
|
-
}
|
|
91
|
-
if (this.server) {
|
|
92
|
-
return;
|
|
93
|
-
}
|
|
94
|
-
await this.removeStaleSocket();
|
|
95
|
-
const server = createServer((socket) => {
|
|
96
|
-
this.sockets.add(socket);
|
|
97
|
-
socket.once("close", () => this.sockets.delete(socket));
|
|
98
|
-
void this.handleConnection(socket).catch(() => socket.destroy());
|
|
99
|
-
});
|
|
100
|
-
this.server = server;
|
|
101
|
-
await new Promise<void>((resolveListen, rejectListen) => {
|
|
102
|
-
const onError = (): void => {
|
|
103
|
-
server.off("listening", onListening);
|
|
104
|
-
this.server = undefined;
|
|
105
|
-
rejectListen(new GatewayControlError("not_running", "后台控制通道无法监听本机 endpoint。"));
|
|
106
|
-
};
|
|
107
|
-
const onListening = (): void => {
|
|
108
|
-
server.off("error", onError);
|
|
109
|
-
resolveListen();
|
|
110
|
-
};
|
|
111
|
-
server.once("error", onError);
|
|
112
|
-
server.once("listening", onListening);
|
|
113
|
-
server.listen(this.endpoint);
|
|
114
|
-
});
|
|
115
|
-
}
|
|
116
|
-
|
|
117
|
-
/**
|
|
118
|
-
* 关闭控制 listener 并移除本地 Unix socket 文件。
|
|
119
|
-
*
|
|
120
|
-
* @returns 所有连接和 listener 关闭后正常结束。
|
|
121
|
-
*/
|
|
122
|
-
async close(): Promise<void> {
|
|
123
|
-
for (const socket of this.sockets) {
|
|
124
|
-
socket.destroy();
|
|
125
|
-
}
|
|
126
|
-
this.sockets.clear();
|
|
127
|
-
const server = this.server;
|
|
128
|
-
this.server = undefined;
|
|
129
|
-
if (server) {
|
|
130
|
-
await new Promise<void>((resolveClose) => server.close(() => resolveClose()));
|
|
131
|
-
}
|
|
132
|
-
if (this.platform !== "win32") {
|
|
133
|
-
try {
|
|
134
|
-
const endpointInfo = await lstat(this.endpoint);
|
|
135
|
-
if (!endpointInfo.isSocket() || endpointInfo.isSymbolicLink()) {
|
|
136
|
-
throw new GatewayControlError("protocol_error", "后台控制 endpoint 在关闭时已变为非 socket 文件, 未删除。 ");
|
|
137
|
-
}
|
|
138
|
-
await unlink(this.endpoint);
|
|
139
|
-
} catch (error) {
|
|
140
|
-
if (error instanceof GatewayControlError) {
|
|
141
|
-
throw error;
|
|
142
|
-
}
|
|
143
|
-
if (!isNodeError(error) || error.code !== "ENOENT") {
|
|
144
|
-
throw error;
|
|
145
|
-
}
|
|
146
|
-
}
|
|
147
|
-
}
|
|
148
|
-
}
|
|
149
|
-
|
|
150
|
-
/**
|
|
151
|
-
* 完成本机客户端挑战认证并执行固定控制动作。
|
|
152
|
-
*
|
|
153
|
-
* @param socket 新建的本机 IPC socket。
|
|
154
|
-
* @returns 单次 request 完成后关闭连接。
|
|
155
|
-
*/
|
|
156
|
-
private async handleConnection(socket: Socket): Promise<void> {
|
|
157
|
-
const peer = new GatewayControlPeer(socket);
|
|
158
|
-
let completedAction: GatewayControlAction | undefined;
|
|
159
|
-
let completedOperationId: string | undefined;
|
|
160
|
-
try {
|
|
161
|
-
const nonce = randomBytes(32).toString("base64url");
|
|
162
|
-
peer.send({ kind: "challenge", nonce });
|
|
163
|
-
const request = await peer.nextMessage(10000);
|
|
164
|
-
if (!isRecord(request) || request.kind !== "request") {
|
|
165
|
-
throw new GatewayControlError("protocol_error", "控制请求格式无效。");
|
|
166
|
-
}
|
|
167
|
-
const requestId = typeof request.requestId === "string" ? request.requestId : "";
|
|
168
|
-
const action = parseAction(request.action);
|
|
169
|
-
const operationId = typeof request.operationId === "string" ? request.operationId : undefined;
|
|
170
|
-
const operationProof = typeof request.operationProof === "string" ? request.operationProof : undefined;
|
|
171
|
-
if (
|
|
172
|
-
(operationId !== undefined && (!isOperationId(operationId) || action !== "restart" || !operationProof)) ||
|
|
173
|
-
(operationId === undefined && operationProof !== undefined)
|
|
174
|
-
) {
|
|
175
|
-
throw new GatewayControlError("protocol_error", "Gateway 控制请求 operationId 字段无效。");
|
|
176
|
-
}
|
|
177
|
-
const proof = typeof request.proof === "string" ? request.proof : "";
|
|
178
|
-
if (!/^[a-f0-9-]{36}$/i.test(requestId) || !proof) {
|
|
179
|
-
throw new GatewayControlError("protocol_error", "控制请求缺少有效身份字段。");
|
|
180
|
-
}
|
|
181
|
-
await this.lease.assertOwned();
|
|
182
|
-
const credential = await readGatewayLeaseCredential(this.managerDirectory);
|
|
183
|
-
await this.lease.assertOwned();
|
|
184
|
-
if (
|
|
185
|
-
!verifyProof(credential.token, nonce, requestId, action, proof) ||
|
|
186
|
-
(operationId !== undefined && !verifyOperationProof(
|
|
187
|
-
credential.token,
|
|
188
|
-
nonce,
|
|
189
|
-
requestId,
|
|
190
|
-
action,
|
|
191
|
-
operationId,
|
|
192
|
-
operationProof!,
|
|
193
|
-
))
|
|
194
|
-
) {
|
|
195
|
-
throw new GatewayControlError("authentication_failed", "后台控制客户端身份校验失败。");
|
|
196
|
-
}
|
|
197
|
-
const result = await this.handlers.handleAction(action, operationId);
|
|
198
|
-
completedAction = action;
|
|
199
|
-
completedOperationId = operationId;
|
|
200
|
-
peer.send({ kind: "response", requestId, ok: true, result });
|
|
201
|
-
} catch (error) {
|
|
202
|
-
const message = error instanceof GatewayControlError
|
|
203
|
-
? error.message
|
|
204
|
-
: "后台控制请求未能安全完成。";
|
|
205
|
-
peer.send({ kind: "response", requestId: "", ok: false, message });
|
|
206
|
-
} finally {
|
|
207
|
-
peer.close();
|
|
208
|
-
if (completedAction) {
|
|
209
|
-
await Promise.resolve(this.handlers.afterActionResponse?.(completedAction, completedOperationId)).catch(() => undefined);
|
|
210
|
-
}
|
|
211
|
-
}
|
|
212
|
-
}
|
|
213
|
-
|
|
214
|
-
/**
|
|
215
|
-
* 在确认 Gateway lease 已由当前进程持有后清理遗留 Unix socket 文件。
|
|
216
|
-
*
|
|
217
|
-
* @returns 文件不存在或为普通 socket 并清理后正常结束。
|
|
218
|
-
* @throws {GatewayControlError} endpoint 被非 socket 文件占用时抛出。
|
|
219
|
-
*/
|
|
220
|
-
private async removeStaleSocket(): Promise<void> {
|
|
221
|
-
if (this.platform === "win32") {
|
|
222
|
-
return;
|
|
223
|
-
}
|
|
224
|
-
try {
|
|
225
|
-
const socketInfo = await lstat(this.endpoint);
|
|
226
|
-
if (!socketInfo.isSocket() || socketInfo.isSymbolicLink()) {
|
|
227
|
-
throw new GatewayControlError("protocol_error", "控制 socket 路径被非 socket 文件占用。");
|
|
228
|
-
}
|
|
229
|
-
await unlink(this.endpoint);
|
|
230
|
-
} catch (error) {
|
|
231
|
-
if (error instanceof GatewayControlError) {
|
|
232
|
-
throw error;
|
|
233
|
-
}
|
|
234
|
-
if (!isNodeError(error) || error.code !== "ENOENT") {
|
|
235
|
-
throw new GatewayControlError("not_running", "无法安全清理遗留控制 socket。");
|
|
236
|
-
}
|
|
237
|
-
}
|
|
238
|
-
}
|
|
239
|
-
}
|
|
240
|
-
|
|
241
|
-
/**
|
|
242
|
-
* 连接后台 Gateway 并执行一个固定的控制动作。
|
|
243
|
-
*/
|
|
244
|
-
export class GatewayControlClient {
|
|
245
|
-
private readonly endpoint: string;
|
|
246
|
-
private readonly timeoutMs: number;
|
|
247
|
-
|
|
248
|
-
/**
|
|
249
|
-
* 创建 Gateway 控制客户端。
|
|
250
|
-
*
|
|
251
|
-
* @param managerDirectory Hub 私有数据目录。
|
|
252
|
-
* @param options endpoint 与请求超时时间。
|
|
253
|
-
*/
|
|
254
|
-
constructor(
|
|
255
|
-
private readonly managerDirectory: string,
|
|
256
|
-
options: { endpoint?: string; timeoutMs?: number; platform?: NodeJS.Platform } = {},
|
|
257
|
-
) {
|
|
258
|
-
const platform = options.platform ?? process.platform;
|
|
259
|
-
this.endpoint = options.endpoint ?? createGatewayControlEndpoint(managerDirectory, platform);
|
|
260
|
-
this.timeoutMs = options.timeoutMs ?? 10000;
|
|
261
|
-
}
|
|
262
|
-
|
|
263
|
-
/**
|
|
264
|
-
* 向已运行 Gateway 发送状态、停止或重启请求。
|
|
265
|
-
*
|
|
266
|
-
* @param action 固定控制动作。
|
|
267
|
-
* @param options 可选操作 ID 和响应等待时限。
|
|
268
|
-
* @returns Gateway 返回的数据。
|
|
269
|
-
* @throws {GatewayControlError} Gateway 离线、认证失败或响应无效时抛出。
|
|
270
|
-
*/
|
|
271
|
-
async request(
|
|
272
|
-
action: GatewayControlAction,
|
|
273
|
-
options: { operationId?: string; responseTimeoutMs?: number } = {},
|
|
274
|
-
): Promise<unknown> {
|
|
275
|
-
const operationId = options.operationId;
|
|
276
|
-
const responseTimeoutMs = options.responseTimeoutMs ?? this.timeoutMs;
|
|
277
|
-
if (operationId !== undefined && (!isOperationId(operationId) || action !== "restart")) {
|
|
278
|
-
throw new GatewayControlError("protocol_error", "Gateway 控制请求 operationId 字段无效。");
|
|
279
|
-
}
|
|
280
|
-
const credential = await readGatewayLeaseCredential(this.managerDirectory).catch((error: unknown) => {
|
|
281
|
-
throw error instanceof GatewayControlError
|
|
282
|
-
? error
|
|
283
|
-
: new GatewayControlError("not_running", "后台 Gateway 当前没有活动 lease。");
|
|
284
|
-
});
|
|
285
|
-
const peer = new GatewayControlPeer(createConnection(this.endpoint));
|
|
286
|
-
try {
|
|
287
|
-
await peer.waitUntilOpen(this.timeoutMs);
|
|
288
|
-
const challenge = await peer.nextMessage(this.timeoutMs);
|
|
289
|
-
if (!isRecord(challenge) || challenge.kind !== "challenge" || typeof challenge.nonce !== "string") {
|
|
290
|
-
throw new GatewayControlError("protocol_error", "后台 Gateway challenge 响应无效。");
|
|
291
|
-
}
|
|
292
|
-
const requestId = randomUUID();
|
|
293
|
-
peer.send({
|
|
294
|
-
kind: "request",
|
|
295
|
-
requestId,
|
|
296
|
-
action,
|
|
297
|
-
...(operationId
|
|
298
|
-
? {
|
|
299
|
-
operationId,
|
|
300
|
-
operationProof: createOperationProof(credential.token, challenge.nonce, requestId, action, operationId),
|
|
301
|
-
}
|
|
302
|
-
: {}),
|
|
303
|
-
proof: createProof(credential.token, challenge.nonce, requestId, action),
|
|
304
|
-
});
|
|
305
|
-
const response = await peer.nextMessage(responseTimeoutMs);
|
|
306
|
-
if (
|
|
307
|
-
!isRecord(response) ||
|
|
308
|
-
response.kind !== "response" ||
|
|
309
|
-
response.requestId !== requestId ||
|
|
310
|
-
response.ok !== true
|
|
311
|
-
) {
|
|
312
|
-
const message = isRecord(response) && typeof response.message === "string"
|
|
313
|
-
? response.message
|
|
314
|
-
: "后台 Gateway 未返回有效控制响应。";
|
|
315
|
-
throw new GatewayControlError("request_failed", message);
|
|
316
|
-
}
|
|
317
|
-
return response.result;
|
|
318
|
-
} catch (error) {
|
|
319
|
-
if (error instanceof GatewayControlError) {
|
|
320
|
-
throw error;
|
|
321
|
-
}
|
|
322
|
-
throw new GatewayControlError("not_running", "无法连接后台 Gateway 控制通道。");
|
|
323
|
-
} finally {
|
|
324
|
-
peer.close();
|
|
325
|
-
}
|
|
326
|
-
}
|
|
327
|
-
}
|
|
328
|
-
|
|
329
|
-
/**
|
|
330
|
-
* 创建与 manager 数据目录绑定且不包含用户路径的控制 endpoint。
|
|
331
|
-
*
|
|
332
|
-
* @param managerDirectory Hub 私有数据目录。
|
|
333
|
-
* @param platform 当前操作系统平台。
|
|
334
|
-
* @returns Windows named pipe 或 POSIX socket 路径。
|
|
335
|
-
*/
|
|
336
|
-
export function createGatewayControlEndpoint(
|
|
337
|
-
managerDirectory: string,
|
|
338
|
-
platform: NodeJS.Platform = process.platform,
|
|
339
|
-
): string {
|
|
340
|
-
const resolved = resolve(managerDirectory);
|
|
341
|
-
const normalized = platform === "win32" ? resolved.toLowerCase() : resolved;
|
|
342
|
-
const scope = createHash("sha256").update(normalized).digest("hex").slice(0, 24);
|
|
343
|
-
|
|
344
|
-
|
|
345
|
-
|
|
346
|
-
|
|
347
|
-
|
|
348
|
-
|
|
349
|
-
|
|
350
|
-
|
|
351
|
-
|
|
352
|
-
|
|
353
|
-
|
|
354
|
-
|
|
355
|
-
|
|
356
|
-
const
|
|
357
|
-
|
|
358
|
-
|
|
359
|
-
|
|
360
|
-
|
|
361
|
-
|
|
362
|
-
|
|
363
|
-
|
|
364
|
-
|
|
365
|
-
|
|
366
|
-
|
|
367
|
-
|
|
368
|
-
|
|
369
|
-
|
|
370
|
-
|
|
371
|
-
|
|
372
|
-
|
|
373
|
-
|
|
374
|
-
|
|
375
|
-
|
|
376
|
-
|
|
377
|
-
|
|
378
|
-
|
|
379
|
-
throw new GatewayControlError("
|
|
380
|
-
}
|
|
381
|
-
|
|
382
|
-
|
|
383
|
-
|
|
384
|
-
|
|
385
|
-
|
|
386
|
-
|
|
387
|
-
|
|
388
|
-
|
|
389
|
-
|
|
390
|
-
|
|
391
|
-
|
|
392
|
-
|
|
393
|
-
|
|
394
|
-
|
|
395
|
-
|
|
396
|
-
|
|
397
|
-
|
|
398
|
-
|
|
399
|
-
return
|
|
400
|
-
|
|
401
|
-
|
|
402
|
-
|
|
403
|
-
|
|
404
|
-
|
|
405
|
-
*
|
|
406
|
-
*
|
|
407
|
-
* @param
|
|
408
|
-
* @param
|
|
409
|
-
* @
|
|
410
|
-
|
|
411
|
-
|
|
412
|
-
|
|
413
|
-
|
|
414
|
-
|
|
415
|
-
|
|
416
|
-
|
|
417
|
-
|
|
418
|
-
|
|
419
|
-
|
|
420
|
-
|
|
421
|
-
|
|
422
|
-
|
|
423
|
-
|
|
424
|
-
|
|
425
|
-
|
|
426
|
-
|
|
427
|
-
*
|
|
428
|
-
*
|
|
429
|
-
* @param
|
|
430
|
-
* @
|
|
431
|
-
|
|
432
|
-
|
|
433
|
-
|
|
434
|
-
|
|
435
|
-
|
|
436
|
-
|
|
437
|
-
|
|
438
|
-
|
|
439
|
-
requestId
|
|
440
|
-
|
|
441
|
-
|
|
442
|
-
|
|
443
|
-
|
|
444
|
-
|
|
445
|
-
|
|
446
|
-
|
|
447
|
-
|
|
448
|
-
|
|
449
|
-
*
|
|
450
|
-
*
|
|
451
|
-
* @param
|
|
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
|
-
|
|
1
|
+
import { createHash, createHmac, randomBytes, randomUUID, timingSafeEqual } from "node:crypto";
|
|
2
|
+
import { lstat, readFile, unlink } from "node:fs/promises";
|
|
3
|
+
import { createConnection, createServer, type Server, type Socket } from "node:net";
|
|
4
|
+
import { tmpdir } from "node:os";
|
|
5
|
+
import { join, resolve } from "node:path";
|
|
6
|
+
import type { GatewayLease } from "../registry/gateway-lease.ts";
|
|
7
|
+
|
|
8
|
+
export type GatewayControlAction = "status" | "stop" | "restart";
|
|
9
|
+
|
|
10
|
+
export interface GatewayControlHandlers {
|
|
11
|
+
/**
|
|
12
|
+
* 执行一个固定控制动作并返回其结果.
|
|
13
|
+
*
|
|
14
|
+
* @param action Gateway 控制动作.
|
|
15
|
+
* @returns 动作结果.
|
|
16
|
+
*/
|
|
17
|
+
handleAction(action: GatewayControlAction, operationId?: string): Promise<unknown>;
|
|
18
|
+
/**
|
|
19
|
+
* 在控制结果已发出并关闭当前请求连接后执行生命周期收尾.
|
|
20
|
+
*
|
|
21
|
+
* @param action 已完成的控制动作.
|
|
22
|
+
* @param operationId restart 动作的完成关联 ID.
|
|
23
|
+
* @returns 收尾完成后正常结束.
|
|
24
|
+
*/
|
|
25
|
+
afterActionResponse?(action: GatewayControlAction, operationId?: string): Promise<void>;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
interface GatewayLeaseCredential {
|
|
29
|
+
ownerId: string;
|
|
30
|
+
pid: number;
|
|
31
|
+
processBirthId: string;
|
|
32
|
+
token: string;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
/**
|
|
36
|
+
* 表示后台 Gateway 控制通道不可用或响应不可信。
|
|
37
|
+
*/
|
|
38
|
+
export class GatewayControlError extends Error {
|
|
39
|
+
/**
|
|
40
|
+
* 创建后台 Gateway 控制错误。
|
|
41
|
+
*
|
|
42
|
+
* @param code 稳定错误代码。
|
|
43
|
+
* @param message 可安全展示的中文说明。
|
|
44
|
+
*/
|
|
45
|
+
constructor(
|
|
46
|
+
readonly code: "not_running" | "protocol_error" | "authentication_failed" | "request_failed" | "timeout",
|
|
47
|
+
message: string,
|
|
48
|
+
) {
|
|
49
|
+
super(message);
|
|
50
|
+
this.name = "GatewayControlError";
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
/**
|
|
55
|
+
* 提供独立于 Pi TUI 生命周期的本机 Gateway 控制 named pipe 或 Unix socket。
|
|
56
|
+
*/
|
|
57
|
+
export class GatewayControlServer {
|
|
58
|
+
readonly endpoint: string;
|
|
59
|
+
private server?: Server;
|
|
60
|
+
private readonly sockets = new Set<Socket>();
|
|
61
|
+
private readonly platform: NodeJS.Platform;
|
|
62
|
+
|
|
63
|
+
/**
|
|
64
|
+
* 创建经过 Gateway lease 认证的本机控制服务。
|
|
65
|
+
*
|
|
66
|
+
* @param managerDirectory Hub 私有数据目录。
|
|
67
|
+
* @param lease 当前 Gateway lease。
|
|
68
|
+
* @param handlers 只接受枚举控制动作的处理器。
|
|
69
|
+
* @param options 平台和测试 endpoint 覆盖值。
|
|
70
|
+
*/
|
|
71
|
+
constructor(
|
|
72
|
+
private readonly managerDirectory: string,
|
|
73
|
+
private readonly lease: GatewayLease,
|
|
74
|
+
private readonly handlers: GatewayControlHandlers,
|
|
75
|
+
options: { endpoint?: string; platform?: NodeJS.Platform } = {},
|
|
76
|
+
) {
|
|
77
|
+
this.platform = options.platform ?? process.platform;
|
|
78
|
+
this.endpoint = options.endpoint ?? createGatewayControlEndpoint(managerDirectory, this.platform);
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
/**
|
|
82
|
+
* 开始监听控制请求。
|
|
83
|
+
*
|
|
84
|
+
* @returns IPC endpoint 开始监听时正常结束。
|
|
85
|
+
* @throws {GatewayControlError} endpoint 无法安全创建或已被占用时抛出。
|
|
86
|
+
*/
|
|
87
|
+
async listen(): Promise<void> {
|
|
88
|
+
if (this.platform !== "win32" && !this.endpoint.startsWith("/")) {
|
|
89
|
+
throw new GatewayControlError("protocol_error", "本机控制 socket 路径无效。");
|
|
90
|
+
}
|
|
91
|
+
if (this.server) {
|
|
92
|
+
return;
|
|
93
|
+
}
|
|
94
|
+
await this.removeStaleSocket();
|
|
95
|
+
const server = createServer((socket) => {
|
|
96
|
+
this.sockets.add(socket);
|
|
97
|
+
socket.once("close", () => this.sockets.delete(socket));
|
|
98
|
+
void this.handleConnection(socket).catch(() => socket.destroy());
|
|
99
|
+
});
|
|
100
|
+
this.server = server;
|
|
101
|
+
await new Promise<void>((resolveListen, rejectListen) => {
|
|
102
|
+
const onError = (): void => {
|
|
103
|
+
server.off("listening", onListening);
|
|
104
|
+
this.server = undefined;
|
|
105
|
+
rejectListen(new GatewayControlError("not_running", "后台控制通道无法监听本机 endpoint。"));
|
|
106
|
+
};
|
|
107
|
+
const onListening = (): void => {
|
|
108
|
+
server.off("error", onError);
|
|
109
|
+
resolveListen();
|
|
110
|
+
};
|
|
111
|
+
server.once("error", onError);
|
|
112
|
+
server.once("listening", onListening);
|
|
113
|
+
server.listen(this.endpoint);
|
|
114
|
+
});
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
/**
|
|
118
|
+
* 关闭控制 listener 并移除本地 Unix socket 文件。
|
|
119
|
+
*
|
|
120
|
+
* @returns 所有连接和 listener 关闭后正常结束。
|
|
121
|
+
*/
|
|
122
|
+
async close(): Promise<void> {
|
|
123
|
+
for (const socket of this.sockets) {
|
|
124
|
+
socket.destroy();
|
|
125
|
+
}
|
|
126
|
+
this.sockets.clear();
|
|
127
|
+
const server = this.server;
|
|
128
|
+
this.server = undefined;
|
|
129
|
+
if (server) {
|
|
130
|
+
await new Promise<void>((resolveClose) => server.close(() => resolveClose()));
|
|
131
|
+
}
|
|
132
|
+
if (this.platform !== "win32") {
|
|
133
|
+
try {
|
|
134
|
+
const endpointInfo = await lstat(this.endpoint);
|
|
135
|
+
if (!endpointInfo.isSocket() || endpointInfo.isSymbolicLink()) {
|
|
136
|
+
throw new GatewayControlError("protocol_error", "后台控制 endpoint 在关闭时已变为非 socket 文件, 未删除。 ");
|
|
137
|
+
}
|
|
138
|
+
await unlink(this.endpoint);
|
|
139
|
+
} catch (error) {
|
|
140
|
+
if (error instanceof GatewayControlError) {
|
|
141
|
+
throw error;
|
|
142
|
+
}
|
|
143
|
+
if (!isNodeError(error) || error.code !== "ENOENT") {
|
|
144
|
+
throw error;
|
|
145
|
+
}
|
|
146
|
+
}
|
|
147
|
+
}
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
/**
|
|
151
|
+
* 完成本机客户端挑战认证并执行固定控制动作。
|
|
152
|
+
*
|
|
153
|
+
* @param socket 新建的本机 IPC socket。
|
|
154
|
+
* @returns 单次 request 完成后关闭连接。
|
|
155
|
+
*/
|
|
156
|
+
private async handleConnection(socket: Socket): Promise<void> {
|
|
157
|
+
const peer = new GatewayControlPeer(socket);
|
|
158
|
+
let completedAction: GatewayControlAction | undefined;
|
|
159
|
+
let completedOperationId: string | undefined;
|
|
160
|
+
try {
|
|
161
|
+
const nonce = randomBytes(32).toString("base64url");
|
|
162
|
+
peer.send({ kind: "challenge", nonce });
|
|
163
|
+
const request = await peer.nextMessage(10000);
|
|
164
|
+
if (!isRecord(request) || request.kind !== "request") {
|
|
165
|
+
throw new GatewayControlError("protocol_error", "控制请求格式无效。");
|
|
166
|
+
}
|
|
167
|
+
const requestId = typeof request.requestId === "string" ? request.requestId : "";
|
|
168
|
+
const action = parseAction(request.action);
|
|
169
|
+
const operationId = typeof request.operationId === "string" ? request.operationId : undefined;
|
|
170
|
+
const operationProof = typeof request.operationProof === "string" ? request.operationProof : undefined;
|
|
171
|
+
if (
|
|
172
|
+
(operationId !== undefined && (!isOperationId(operationId) || action !== "restart" || !operationProof)) ||
|
|
173
|
+
(operationId === undefined && operationProof !== undefined)
|
|
174
|
+
) {
|
|
175
|
+
throw new GatewayControlError("protocol_error", "Gateway 控制请求 operationId 字段无效。");
|
|
176
|
+
}
|
|
177
|
+
const proof = typeof request.proof === "string" ? request.proof : "";
|
|
178
|
+
if (!/^[a-f0-9-]{36}$/i.test(requestId) || !proof) {
|
|
179
|
+
throw new GatewayControlError("protocol_error", "控制请求缺少有效身份字段。");
|
|
180
|
+
}
|
|
181
|
+
await this.lease.assertOwned();
|
|
182
|
+
const credential = await readGatewayLeaseCredential(this.managerDirectory);
|
|
183
|
+
await this.lease.assertOwned();
|
|
184
|
+
if (
|
|
185
|
+
!verifyProof(credential.token, nonce, requestId, action, proof) ||
|
|
186
|
+
(operationId !== undefined && !verifyOperationProof(
|
|
187
|
+
credential.token,
|
|
188
|
+
nonce,
|
|
189
|
+
requestId,
|
|
190
|
+
action,
|
|
191
|
+
operationId,
|
|
192
|
+
operationProof!,
|
|
193
|
+
))
|
|
194
|
+
) {
|
|
195
|
+
throw new GatewayControlError("authentication_failed", "后台控制客户端身份校验失败。");
|
|
196
|
+
}
|
|
197
|
+
const result = await this.handlers.handleAction(action, operationId);
|
|
198
|
+
completedAction = action;
|
|
199
|
+
completedOperationId = operationId;
|
|
200
|
+
peer.send({ kind: "response", requestId, ok: true, result });
|
|
201
|
+
} catch (error) {
|
|
202
|
+
const message = error instanceof GatewayControlError
|
|
203
|
+
? error.message
|
|
204
|
+
: "后台控制请求未能安全完成。";
|
|
205
|
+
peer.send({ kind: "response", requestId: "", ok: false, message });
|
|
206
|
+
} finally {
|
|
207
|
+
peer.close();
|
|
208
|
+
if (completedAction) {
|
|
209
|
+
await Promise.resolve(this.handlers.afterActionResponse?.(completedAction, completedOperationId)).catch(() => undefined);
|
|
210
|
+
}
|
|
211
|
+
}
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
/**
|
|
215
|
+
* 在确认 Gateway lease 已由当前进程持有后清理遗留 Unix socket 文件。
|
|
216
|
+
*
|
|
217
|
+
* @returns 文件不存在或为普通 socket 并清理后正常结束。
|
|
218
|
+
* @throws {GatewayControlError} endpoint 被非 socket 文件占用时抛出。
|
|
219
|
+
*/
|
|
220
|
+
private async removeStaleSocket(): Promise<void> {
|
|
221
|
+
if (this.platform === "win32") {
|
|
222
|
+
return;
|
|
223
|
+
}
|
|
224
|
+
try {
|
|
225
|
+
const socketInfo = await lstat(this.endpoint);
|
|
226
|
+
if (!socketInfo.isSocket() || socketInfo.isSymbolicLink()) {
|
|
227
|
+
throw new GatewayControlError("protocol_error", "控制 socket 路径被非 socket 文件占用。");
|
|
228
|
+
}
|
|
229
|
+
await unlink(this.endpoint);
|
|
230
|
+
} catch (error) {
|
|
231
|
+
if (error instanceof GatewayControlError) {
|
|
232
|
+
throw error;
|
|
233
|
+
}
|
|
234
|
+
if (!isNodeError(error) || error.code !== "ENOENT") {
|
|
235
|
+
throw new GatewayControlError("not_running", "无法安全清理遗留控制 socket。");
|
|
236
|
+
}
|
|
237
|
+
}
|
|
238
|
+
}
|
|
239
|
+
}
|
|
240
|
+
|
|
241
|
+
/**
|
|
242
|
+
* 连接后台 Gateway 并执行一个固定的控制动作。
|
|
243
|
+
*/
|
|
244
|
+
export class GatewayControlClient {
|
|
245
|
+
private readonly endpoint: string;
|
|
246
|
+
private readonly timeoutMs: number;
|
|
247
|
+
|
|
248
|
+
/**
|
|
249
|
+
* 创建 Gateway 控制客户端。
|
|
250
|
+
*
|
|
251
|
+
* @param managerDirectory Hub 私有数据目录。
|
|
252
|
+
* @param options endpoint 与请求超时时间。
|
|
253
|
+
*/
|
|
254
|
+
constructor(
|
|
255
|
+
private readonly managerDirectory: string,
|
|
256
|
+
options: { endpoint?: string; timeoutMs?: number; platform?: NodeJS.Platform } = {},
|
|
257
|
+
) {
|
|
258
|
+
const platform = options.platform ?? process.platform;
|
|
259
|
+
this.endpoint = options.endpoint ?? createGatewayControlEndpoint(managerDirectory, platform);
|
|
260
|
+
this.timeoutMs = options.timeoutMs ?? 10000;
|
|
261
|
+
}
|
|
262
|
+
|
|
263
|
+
/**
|
|
264
|
+
* 向已运行 Gateway 发送状态、停止或重启请求。
|
|
265
|
+
*
|
|
266
|
+
* @param action 固定控制动作。
|
|
267
|
+
* @param options 可选操作 ID 和响应等待时限。
|
|
268
|
+
* @returns Gateway 返回的数据。
|
|
269
|
+
* @throws {GatewayControlError} Gateway 离线、认证失败或响应无效时抛出。
|
|
270
|
+
*/
|
|
271
|
+
async request(
|
|
272
|
+
action: GatewayControlAction,
|
|
273
|
+
options: { operationId?: string; responseTimeoutMs?: number } = {},
|
|
274
|
+
): Promise<unknown> {
|
|
275
|
+
const operationId = options.operationId;
|
|
276
|
+
const responseTimeoutMs = options.responseTimeoutMs ?? this.timeoutMs;
|
|
277
|
+
if (operationId !== undefined && (!isOperationId(operationId) || action !== "restart")) {
|
|
278
|
+
throw new GatewayControlError("protocol_error", "Gateway 控制请求 operationId 字段无效。");
|
|
279
|
+
}
|
|
280
|
+
const credential = await readGatewayLeaseCredential(this.managerDirectory).catch((error: unknown) => {
|
|
281
|
+
throw error instanceof GatewayControlError
|
|
282
|
+
? error
|
|
283
|
+
: new GatewayControlError("not_running", "后台 Gateway 当前没有活动 lease。");
|
|
284
|
+
});
|
|
285
|
+
const peer = new GatewayControlPeer(createConnection(this.endpoint));
|
|
286
|
+
try {
|
|
287
|
+
await peer.waitUntilOpen(this.timeoutMs);
|
|
288
|
+
const challenge = await peer.nextMessage(this.timeoutMs);
|
|
289
|
+
if (!isRecord(challenge) || challenge.kind !== "challenge" || typeof challenge.nonce !== "string") {
|
|
290
|
+
throw new GatewayControlError("protocol_error", "后台 Gateway challenge 响应无效。");
|
|
291
|
+
}
|
|
292
|
+
const requestId = randomUUID();
|
|
293
|
+
peer.send({
|
|
294
|
+
kind: "request",
|
|
295
|
+
requestId,
|
|
296
|
+
action,
|
|
297
|
+
...(operationId
|
|
298
|
+
? {
|
|
299
|
+
operationId,
|
|
300
|
+
operationProof: createOperationProof(credential.token, challenge.nonce, requestId, action, operationId),
|
|
301
|
+
}
|
|
302
|
+
: {}),
|
|
303
|
+
proof: createProof(credential.token, challenge.nonce, requestId, action),
|
|
304
|
+
});
|
|
305
|
+
const response = await peer.nextMessage(responseTimeoutMs);
|
|
306
|
+
if (
|
|
307
|
+
!isRecord(response) ||
|
|
308
|
+
response.kind !== "response" ||
|
|
309
|
+
response.requestId !== requestId ||
|
|
310
|
+
response.ok !== true
|
|
311
|
+
) {
|
|
312
|
+
const message = isRecord(response) && typeof response.message === "string"
|
|
313
|
+
? response.message
|
|
314
|
+
: "后台 Gateway 未返回有效控制响应。";
|
|
315
|
+
throw new GatewayControlError("request_failed", message);
|
|
316
|
+
}
|
|
317
|
+
return response.result;
|
|
318
|
+
} catch (error) {
|
|
319
|
+
if (error instanceof GatewayControlError) {
|
|
320
|
+
throw error;
|
|
321
|
+
}
|
|
322
|
+
throw new GatewayControlError("not_running", "无法连接后台 Gateway 控制通道。");
|
|
323
|
+
} finally {
|
|
324
|
+
peer.close();
|
|
325
|
+
}
|
|
326
|
+
}
|
|
327
|
+
}
|
|
328
|
+
|
|
329
|
+
/**
|
|
330
|
+
* 创建与 manager 数据目录绑定且不包含用户路径的控制 endpoint。
|
|
331
|
+
*
|
|
332
|
+
* @param managerDirectory Hub 私有数据目录。
|
|
333
|
+
* @param platform 当前操作系统平台。
|
|
334
|
+
* @returns Windows named pipe 或 POSIX socket 路径。
|
|
335
|
+
*/
|
|
336
|
+
export function createGatewayControlEndpoint(
|
|
337
|
+
managerDirectory: string,
|
|
338
|
+
platform: NodeJS.Platform = process.platform,
|
|
339
|
+
): string {
|
|
340
|
+
const resolved = resolve(managerDirectory);
|
|
341
|
+
const normalized = platform === "win32" ? resolved.toLowerCase() : resolved;
|
|
342
|
+
const scope = createHash("sha256").update(normalized).digest("hex").slice(0, 24);
|
|
343
|
+
if (platform === "win32") {
|
|
344
|
+
return `\\\\.\\pipe\\pi-wechat-session-hub-${scope}-control`;
|
|
345
|
+
}
|
|
346
|
+
// POSIX 的 sun_path 有固定上限(macOS 104 字节、Linux 108 字节)。
|
|
347
|
+
// macOS 的 tmpdir() 形如 /var/folders/xx/...(约 48 字节),
|
|
348
|
+
// 叠加 22 字节前缀 + 24 位 scope + 13 字节后缀会达到 108 字节,
|
|
349
|
+
// 超出上限后 listen 直接失败 EINVAL。
|
|
350
|
+
// 因此按实际可用字节数收缩 scope,必要时改用更短的 /tmp。
|
|
351
|
+
const endpointPrefix = "pi-wechat-session-hub-";
|
|
352
|
+
const endpointSuffix = "-control.sock";
|
|
353
|
+
const endpointBudget = 100; // 为 104 字节上限预留 4 字节余量
|
|
354
|
+
const endpointFixed = Buffer.byteLength(endpointPrefix, "utf8")
|
|
355
|
+
+ Buffer.byteLength(endpointSuffix, "utf8") + 1; // +1 为分隔符
|
|
356
|
+
for (const base of [tmpdir(), "/tmp"]) {
|
|
357
|
+
const available = endpointBudget - Buffer.byteLength(base, "utf8") - endpointFixed;
|
|
358
|
+
if (available >= 8) {
|
|
359
|
+
return join(base, `${endpointPrefix}${scope.slice(0, Math.min(24, available))}${endpointSuffix}`);
|
|
360
|
+
}
|
|
361
|
+
}
|
|
362
|
+
// 两个候选目录都放不下的极端情形:取最短组合,保证不产生超长路径。
|
|
363
|
+
return join("/tmp", `${endpointPrefix}${scope.slice(0, 8)}${endpointSuffix}`);
|
|
364
|
+
}
|
|
365
|
+
|
|
366
|
+
/**
|
|
367
|
+
* 从受保护的 manager.lock 读取 Gateway lease 客户端认证材料。
|
|
368
|
+
*
|
|
369
|
+
* @param managerDirectory Hub 私有数据目录。
|
|
370
|
+
* @returns 当前 lease 的本机认证材料。
|
|
371
|
+
* @throws {GatewayControlError} lock 缺失、权限路径不可信或格式无效时抛出。
|
|
372
|
+
*/
|
|
373
|
+
async function readGatewayLeaseCredential(managerDirectory: string): Promise<GatewayLeaseCredential> {
|
|
374
|
+
const lockPath = join(resolve(managerDirectory), "manager.lock");
|
|
375
|
+
let lockInfo;
|
|
376
|
+
try {
|
|
377
|
+
lockInfo = await lstat(lockPath);
|
|
378
|
+
} catch {
|
|
379
|
+
throw new GatewayControlError("not_running", "后台 Gateway 当前没有活动 lease。");
|
|
380
|
+
}
|
|
381
|
+
if (!lockInfo.isFile() || lockInfo.isSymbolicLink()) {
|
|
382
|
+
throw new GatewayControlError("authentication_failed", "Gateway lease 文件类型不可信。");
|
|
383
|
+
}
|
|
384
|
+
let metadata: unknown;
|
|
385
|
+
try {
|
|
386
|
+
metadata = JSON.parse(await readFile(lockPath, "utf8")) as unknown;
|
|
387
|
+
} catch {
|
|
388
|
+
throw new GatewayControlError("authentication_failed", "Gateway lease 文件格式无效。");
|
|
389
|
+
}
|
|
390
|
+
if (
|
|
391
|
+
!isRecord(metadata) ||
|
|
392
|
+
typeof metadata.ownerId !== "string" ||
|
|
393
|
+
typeof metadata.pid !== "number" || !Number.isSafeInteger(metadata.pid) || metadata.pid <= 0 ||
|
|
394
|
+
typeof metadata.processBirthId !== "string" ||
|
|
395
|
+
typeof metadata.token !== "string" || !/^[a-f0-9-]{36}$/i.test(metadata.token)
|
|
396
|
+
) {
|
|
397
|
+
throw new GatewayControlError("authentication_failed", "Gateway lease 身份字段无效。");
|
|
398
|
+
}
|
|
399
|
+
return metadata as unknown as GatewayLeaseCredential;
|
|
400
|
+
}
|
|
401
|
+
|
|
402
|
+
/**
|
|
403
|
+
* 计算 client 对固定 action 与 requestId 的 challenge proof。
|
|
404
|
+
*
|
|
405
|
+
* @param token Gateway lease 随机令牌。
|
|
406
|
+
* @param nonce 服务端随机 challenge。
|
|
407
|
+
* @param requestId 本次 request UUID。
|
|
408
|
+
* @param action 已验证控制动作。
|
|
409
|
+
* @returns base64url HMAC proof。
|
|
410
|
+
*/
|
|
411
|
+
function createProof(
|
|
412
|
+
token: string,
|
|
413
|
+
nonce: string,
|
|
414
|
+
requestId: string,
|
|
415
|
+
action: GatewayControlAction,
|
|
416
|
+
): string {
|
|
417
|
+
return createHmac("sha256", token)
|
|
418
|
+
.update(`${nonce}\n${JSON.stringify({ requestId, action })}`, "utf8")
|
|
419
|
+
.digest("base64url");
|
|
420
|
+
}
|
|
421
|
+
|
|
422
|
+
/**
|
|
423
|
+
* 使用恒定时间比较校验控制动作 HMAC。
|
|
424
|
+
*
|
|
425
|
+
* @param token Gateway lease 随机令牌。
|
|
426
|
+
* @param nonce 服务端随机 challenge。
|
|
427
|
+
* @param requestId 本次 request UUID。
|
|
428
|
+
* @param action 已验证控制动作。
|
|
429
|
+
* @param proof 客户端提供的 proof。
|
|
430
|
+
* @returns proof 有效时返回 true。
|
|
431
|
+
*/
|
|
432
|
+
function verifyProof(
|
|
433
|
+
token: string,
|
|
434
|
+
nonce: string,
|
|
435
|
+
requestId: string,
|
|
436
|
+
action: GatewayControlAction,
|
|
437
|
+
proof: string,
|
|
438
|
+
): boolean {
|
|
439
|
+
const expected = Buffer.from(createProof(token, nonce, requestId, action), "base64url");
|
|
440
|
+
const actual = Buffer.from(proof, "base64url");
|
|
441
|
+
return expected.length === actual.length && timingSafeEqual(expected, actual);
|
|
442
|
+
}
|
|
443
|
+
|
|
444
|
+
/**
|
|
445
|
+
* 为 restart 操作 ID 生成兼容旧 control client 的附加 HMAC.
|
|
446
|
+
*
|
|
447
|
+
* @param token Gateway lease 随机令牌.
|
|
448
|
+
* @param nonce 服务端随机 challenge.
|
|
449
|
+
* @param requestId 本次 request UUID.
|
|
450
|
+
* @param action Gateway 控制动作.
|
|
451
|
+
* @param operationId restart 操作 ID.
|
|
452
|
+
* @returns 绑定 operationId 的 base64url HMAC.
|
|
453
|
+
*/
|
|
454
|
+
function createOperationProof(
|
|
455
|
+
token: string,
|
|
456
|
+
nonce: string,
|
|
457
|
+
requestId: string,
|
|
458
|
+
action: GatewayControlAction,
|
|
459
|
+
operationId: string,
|
|
460
|
+
): string {
|
|
461
|
+
return createHmac("sha256", token)
|
|
462
|
+
.update(`${nonce}\n${JSON.stringify({ requestId, action, operationId })}`, "utf8")
|
|
463
|
+
.digest("base64url");
|
|
464
|
+
}
|
|
465
|
+
|
|
466
|
+
/**
|
|
467
|
+
* 校验 restart 操作 ID 的附加 HMAC.
|
|
468
|
+
*
|
|
469
|
+
* @param token Gateway lease 随机令牌.
|
|
470
|
+
* @param nonce 服务端随机 challenge.
|
|
471
|
+
* @param requestId 本次 request UUID.
|
|
472
|
+
* @param action Gateway 控制动作.
|
|
473
|
+
* @param operationId restart 操作 ID.
|
|
474
|
+
* @param proof 客户端提供的附加 proof.
|
|
475
|
+
* @returns proof 有效时返回 true.
|
|
476
|
+
*/
|
|
477
|
+
function verifyOperationProof(
|
|
478
|
+
token: string,
|
|
479
|
+
nonce: string,
|
|
480
|
+
requestId: string,
|
|
481
|
+
action: GatewayControlAction,
|
|
482
|
+
operationId: string,
|
|
483
|
+
proof: string,
|
|
484
|
+
): boolean {
|
|
485
|
+
const expected = Buffer.from(
|
|
486
|
+
createOperationProof(token, nonce, requestId, action, operationId),
|
|
487
|
+
"base64url",
|
|
488
|
+
);
|
|
489
|
+
const actual = Buffer.from(proof, "base64url");
|
|
490
|
+
return expected.length === actual.length && timingSafeEqual(expected, actual);
|
|
491
|
+
}
|
|
492
|
+
|
|
493
|
+
/**
|
|
494
|
+
* 判断值是否为本次 Gateway 生命周期操作的 UUID.
|
|
495
|
+
*
|
|
496
|
+
* @param value 待校验 ID.
|
|
497
|
+
* @returns UUID 格式有效时返回 true.
|
|
498
|
+
*/
|
|
499
|
+
function isOperationId(value: string): boolean {
|
|
500
|
+
return /^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(value);
|
|
501
|
+
}
|
|
502
|
+
|
|
503
|
+
/**
|
|
504
|
+
* 将控制 action 校验为严格枚举。
|
|
505
|
+
*
|
|
506
|
+
* @param value 未知请求字段。
|
|
507
|
+
* @returns 有效控制动作。
|
|
508
|
+
* @throws {GatewayControlError} 请求动作不受支持时抛出。
|
|
509
|
+
*/
|
|
510
|
+
function parseAction(value: unknown): GatewayControlAction {
|
|
511
|
+
if (value === "status" || value === "stop" || value === "restart") {
|
|
512
|
+
return value;
|
|
513
|
+
}
|
|
514
|
+
throw new GatewayControlError("protocol_error", "Gateway 控制动作不受支持。");
|
|
515
|
+
}
|
|
516
|
+
|
|
517
|
+
/**
|
|
518
|
+
* 判断值是否为普通对象。
|
|
519
|
+
*
|
|
520
|
+
* @param value 待检查值。
|
|
521
|
+
* @returns 普通对象时返回 true。
|
|
522
|
+
*/
|
|
523
|
+
function isRecord(value: unknown): value is Record<string, unknown> {
|
|
524
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
525
|
+
}
|
|
526
|
+
|
|
527
|
+
/**
|
|
528
|
+
* 判断值是否为 Node.js 文件系统或网络错误。
|
|
529
|
+
*
|
|
530
|
+
* @param error 待检查值。
|
|
531
|
+
* @returns 值带有错误代码时返回 true。
|
|
532
|
+
*/
|
|
533
|
+
function isNodeError(error: unknown): error is NodeJS.ErrnoException {
|
|
534
|
+
return error instanceof Error && "code" in error;
|
|
535
|
+
}
|
|
536
|
+
|
|
537
|
+
/**
|
|
538
|
+
* 处理本机控制 socket 上的换行 JSON frame 和有界请求超时。
|
|
539
|
+
*/
|
|
540
|
+
class GatewayControlPeer {
|
|
541
|
+
private input = "";
|
|
542
|
+
private closed = false;
|
|
543
|
+
private readonly queued: unknown[] = [];
|
|
544
|
+
private readonly waiters: Array<{
|
|
545
|
+
resolve: (value: unknown) => void;
|
|
546
|
+
reject: (error: Error) => void;
|
|
547
|
+
timer: NodeJS.Timeout;
|
|
548
|
+
}> = [];
|
|
549
|
+
|
|
550
|
+
/**
|
|
551
|
+
* 创建控制 peer 并挂接 socket 生命周期事件。
|
|
552
|
+
*
|
|
553
|
+
* @param socket 本机 IPC socket。
|
|
554
|
+
*/
|
|
555
|
+
constructor(private readonly socket: Socket) {
|
|
556
|
+
socket.setEncoding("utf8");
|
|
557
|
+
socket.on("data", (chunk: string) => this.handleData(chunk));
|
|
558
|
+
socket.on("error", (error) => this.fail(error));
|
|
559
|
+
socket.on("close", () => this.fail(new GatewayControlError("not_running", "Gateway 控制连接已关闭。")));
|
|
560
|
+
}
|
|
561
|
+
|
|
562
|
+
/**
|
|
563
|
+
* 等待 socket connect event。
|
|
564
|
+
*
|
|
565
|
+
* @param timeoutMs 建连超时。
|
|
566
|
+
* @returns 连接建立时正常结束。
|
|
567
|
+
*/
|
|
568
|
+
waitUntilOpen(timeoutMs: number): Promise<void> {
|
|
569
|
+
if (this.socket.readyState === "open") {
|
|
570
|
+
return Promise.resolve();
|
|
571
|
+
}
|
|
572
|
+
return new Promise<void>((resolveOpen, rejectOpen) => {
|
|
573
|
+
const cleanup = (): void => {
|
|
574
|
+
clearTimeout(timer);
|
|
575
|
+
this.socket.off("connect", onConnect);
|
|
576
|
+
this.socket.off("error", onError);
|
|
577
|
+
};
|
|
578
|
+
const onConnect = (): void => {
|
|
579
|
+
cleanup();
|
|
580
|
+
resolveOpen();
|
|
581
|
+
};
|
|
582
|
+
const onError = (): void => {
|
|
583
|
+
cleanup();
|
|
584
|
+
rejectOpen(new GatewayControlError("not_running", "Gateway 控制 socket 建连失败。"));
|
|
585
|
+
};
|
|
586
|
+
const timer = setTimeout(() => {
|
|
587
|
+
cleanup();
|
|
588
|
+
rejectOpen(new GatewayControlError("timeout", "Gateway 控制 socket 建连超时。"));
|
|
589
|
+
}, timeoutMs);
|
|
590
|
+
timer.unref();
|
|
591
|
+
this.socket.once("connect", onConnect);
|
|
592
|
+
this.socket.once("error", onError);
|
|
593
|
+
});
|
|
594
|
+
}
|
|
595
|
+
|
|
596
|
+
/**
|
|
597
|
+
* 发送一个 JSON line frame。
|
|
598
|
+
*
|
|
599
|
+
* @param frame 已校验结构化消息。
|
|
600
|
+
* @returns frame 写入 socket 后正常结束。
|
|
601
|
+
*/
|
|
602
|
+
send(frame: Record<string, unknown>): void {
|
|
603
|
+
if (this.closed || this.socket.destroyed) {
|
|
604
|
+
throw new GatewayControlError("not_running", "Gateway 控制 socket 已关闭。");
|
|
605
|
+
}
|
|
606
|
+
this.socket.write(`${JSON.stringify(frame)}\n`, "utf8");
|
|
607
|
+
}
|
|
608
|
+
|
|
609
|
+
/**
|
|
610
|
+
* 读取并解析下一个 JSON line frame。
|
|
611
|
+
*
|
|
612
|
+
* @param timeoutMs 等待超时。
|
|
613
|
+
* @returns 已解析 frame。
|
|
614
|
+
*/
|
|
615
|
+
nextMessage(timeoutMs: number): Promise<unknown> {
|
|
616
|
+
const queued = this.queued.shift();
|
|
617
|
+
if (queued !== undefined) {
|
|
618
|
+
return Promise.resolve(queued);
|
|
619
|
+
}
|
|
620
|
+
return new Promise<unknown>((resolveMessage, rejectMessage) => {
|
|
621
|
+
const timer = setTimeout(() => {
|
|
622
|
+
const index = this.waiters.findIndex((waiter) => waiter.resolve === resolveMessage);
|
|
623
|
+
if (index >= 0) {
|
|
624
|
+
this.waiters.splice(index, 1);
|
|
625
|
+
}
|
|
626
|
+
rejectMessage(new GatewayControlError("timeout", "等待 Gateway 控制响应超时。"));
|
|
627
|
+
}, timeoutMs);
|
|
628
|
+
timer.unref();
|
|
629
|
+
this.waiters.push({ resolve: resolveMessage, reject: rejectMessage, timer });
|
|
630
|
+
if (this.closed) {
|
|
631
|
+
this.fail(new GatewayControlError("not_running", "Gateway 控制连接已关闭。"));
|
|
632
|
+
}
|
|
633
|
+
});
|
|
634
|
+
}
|
|
635
|
+
|
|
636
|
+
/**
|
|
637
|
+
* 正常关闭 socket。
|
|
638
|
+
*
|
|
639
|
+
* @returns 无返回值。
|
|
640
|
+
*/
|
|
641
|
+
close(): void {
|
|
642
|
+
if (this.closed) {
|
|
643
|
+
return;
|
|
644
|
+
}
|
|
645
|
+
this.closed = true;
|
|
646
|
+
this.socket.end();
|
|
647
|
+
this.socket.destroy();
|
|
648
|
+
this.fail(new GatewayControlError("not_running", "Gateway 控制连接已关闭。"));
|
|
649
|
+
}
|
|
650
|
+
|
|
651
|
+
/**
|
|
652
|
+
* 收集并分发换行分隔的 JSON frame。
|
|
653
|
+
*
|
|
654
|
+
* @param chunk 新收到的 UTF-8 数据。
|
|
655
|
+
* @returns frame 被解析或连接被拒绝后结束。
|
|
656
|
+
*/
|
|
657
|
+
private handleData(chunk: string): void {
|
|
658
|
+
this.input += chunk;
|
|
659
|
+
if (Buffer.byteLength(this.input, "utf8") > 128 * 1024) {
|
|
660
|
+
this.fail(new GatewayControlError("protocol_error", "Gateway 控制 frame 超出大小限制。"));
|
|
661
|
+
this.socket.destroy();
|
|
662
|
+
return;
|
|
663
|
+
}
|
|
664
|
+
while (true) {
|
|
665
|
+
const newline = this.input.indexOf("\n");
|
|
666
|
+
if (newline < 0) {
|
|
667
|
+
return;
|
|
668
|
+
}
|
|
669
|
+
const line = this.input.slice(0, newline);
|
|
670
|
+
this.input = this.input.slice(newline + 1);
|
|
671
|
+
if (!line.trim()) {
|
|
672
|
+
continue;
|
|
673
|
+
}
|
|
674
|
+
let frame: unknown;
|
|
675
|
+
try {
|
|
676
|
+
frame = JSON.parse(line) as unknown;
|
|
677
|
+
} catch {
|
|
678
|
+
this.fail(new GatewayControlError("protocol_error", "Gateway 控制 frame JSON 无效。"));
|
|
679
|
+
this.socket.destroy();
|
|
680
|
+
return;
|
|
681
|
+
}
|
|
682
|
+
const waiter = this.waiters.shift();
|
|
683
|
+
if (waiter) {
|
|
684
|
+
clearTimeout(waiter.timer);
|
|
685
|
+
waiter.resolve(frame);
|
|
686
|
+
} else {
|
|
687
|
+
this.queued.push(frame);
|
|
688
|
+
}
|
|
689
|
+
}
|
|
690
|
+
}
|
|
691
|
+
|
|
692
|
+
/**
|
|
693
|
+
* 将 socket error/close 传递给全部未完成 reader。
|
|
694
|
+
*
|
|
695
|
+
* @param error 连接结束原因。
|
|
696
|
+
* @returns 无返回值。
|
|
697
|
+
*/
|
|
698
|
+
private fail(error: Error): void {
|
|
699
|
+
this.closed = true;
|
|
700
|
+
for (const waiter of this.waiters.splice(0)) {
|
|
701
|
+
clearTimeout(waiter.timer);
|
|
702
|
+
waiter.reject(error);
|
|
703
|
+
}
|
|
704
|
+
}
|
|
705
|
+
}
|