pi-wechat-session-hub 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +661 -0
- package/README.md +365 -0
- package/docs/decisions/0001-ilink-context-token-queue.md +41 -0
- package/docs/handoff-next-session.md +134 -0
- package/docs/implementation-spec.md +147 -0
- package/extensions/wechat-session-hub.ts +589 -0
- package/package.json +67 -0
- package/scripts/pi-rpc-smoke.mjs +150 -0
- package/scripts/probe-wt-capability.mjs +27 -0
- package/scripts/start-ui-worker.ps1 +37 -0
- package/src/commands/ilink-qr-login-component.ts +148 -0
- package/src/commands/project-command-parser.ts +108 -0
- package/src/commands/tokenizer.ts +71 -0
- package/src/commands/wechat-manager-command-parser.ts +143 -0
- package/src/config/defaults.ts +30 -0
- package/src/config/paths.ts +56 -0
- package/src/config/store.ts +311 -0
- package/src/config/types.ts +33 -0
- package/src/config/validation.ts +221 -0
- package/src/gateway/channel-types.ts +47 -0
- package/src/gateway/command-parser.ts +291 -0
- package/src/gateway/command-router.ts +1449 -0
- package/src/gateway/credential-store.ts +611 -0
- package/src/gateway/durable-message-queue.ts +1043 -0
- package/src/gateway/gateway-control-ipc.ts +687 -0
- package/src/gateway/gateway-runtime.ts +726 -0
- package/src/gateway/ui-worker-extension-bridge.ts +1070 -0
- package/src/gateway/ui-worker-ipc.ts +1483 -0
- package/src/gateway/ui-worker-types.ts +50 -0
- package/src/gateway/wechat-ilink/api-client.ts +390 -0
- package/src/gateway/wechat-ilink/channel-adapter.ts +320 -0
- package/src/gateway/wechat-ilink/cursor-store.ts +134 -0
- package/src/gateway/wechat-ilink/qr-login.ts +612 -0
- package/src/gateway/wechat-ilink/typing-indicator.ts +133 -0
- package/src/gateway/windows-terminal-launcher.ts +247 -0
- package/src/projects/project-service.ts +483 -0
- package/src/registry/gateway-lease.ts +348 -0
- package/src/registry/manager-registry.ts +466 -0
- package/src/registry/types.ts +61 -0
- package/src/runtime/background-pi-worker.ts +309 -0
- package/src/runtime/background-worker-manager.ts +594 -0
- package/src/runtime/gateway-daemon.ts +281 -0
- package/src/runtime/gateway-lifecycle-operation.ts +308 -0
- package/src/runtime/gateway-service-controller.ts +339 -0
- package/src/runtime/gateway-worker-manager.ts +181 -0
- package/src/runtime/pi-cli.ts +56 -0
- package/src/runtime/pi-rpc-client.ts +427 -0
- package/src/runtime/ui-worker-manager.ts +1186 -0
- package/src/runtime/windows-logon-task-manager.ts +212 -0
- package/src/system/process-liveness.ts +88 -0
- package/tsconfig.json +19 -0
|
@@ -0,0 +1,1483 @@
|
|
|
1
|
+
import { createHash, createHmac, randomBytes, randomUUID, timingSafeEqual } from "node:crypto";
|
|
2
|
+
import { EventEmitter } from "node:events";
|
|
3
|
+
import { constants } from "node:fs";
|
|
4
|
+
import { mkdir, open, readdir, lstat, readFile, realpath, rename, unlink } from "node:fs/promises";
|
|
5
|
+
import { createConnection, createServer, type Server, type Socket } from "node:net";
|
|
6
|
+
import { dirname, isAbsolute, join, resolve } from "node:path";
|
|
7
|
+
import { isProcessAlive } from "../system/process-liveness.ts";
|
|
8
|
+
import { GatewayLease } from "../registry/gateway-lease.ts";
|
|
9
|
+
import { ManagerRegistry } from "../registry/manager-registry.ts";
|
|
10
|
+
import type { UiWorkerLaunchRecord, UiWorkerRegistration } from "./ui-worker-types.ts";
|
|
11
|
+
|
|
12
|
+
const MAX_FRAME_BYTES = 256 * 1024;
|
|
13
|
+
const MAX_LAUNCH_RECORD_BYTES = 64 * 1024;
|
|
14
|
+
|
|
15
|
+
/**
|
|
16
|
+
* 表示 UI worker 本机 IPC 的握手、协议或连接状态不安全。
|
|
17
|
+
*/
|
|
18
|
+
export class UiWorkerIpcError extends Error {
|
|
19
|
+
/**
|
|
20
|
+
* 创建不包含 launch ticket 或消息正文的 IPC 错误。
|
|
21
|
+
*
|
|
22
|
+
* @param code 稳定错误代码。
|
|
23
|
+
* @param message 可安全显示的中文说明。
|
|
24
|
+
*/
|
|
25
|
+
constructor(
|
|
26
|
+
readonly code:
|
|
27
|
+
| "pipe_unavailable"
|
|
28
|
+
| "invalid_frame"
|
|
29
|
+
| "handshake_rejected"
|
|
30
|
+
| "worker_disconnected"
|
|
31
|
+
| "request_timeout"
|
|
32
|
+
| "launch_record_invalid"
|
|
33
|
+
| "project_not_registered",
|
|
34
|
+
message: string,
|
|
35
|
+
) {
|
|
36
|
+
super(message);
|
|
37
|
+
this.name = "UiWorkerIpcError";
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/**
|
|
42
|
+
* UI worker 启动注册完成后的本机 IPC 连接。
|
|
43
|
+
*/
|
|
44
|
+
export class UiWorkerIpcConnection extends EventEmitter {
|
|
45
|
+
/**
|
|
46
|
+
* 创建已完成认证的 IPC connection。
|
|
47
|
+
*
|
|
48
|
+
* @param peer 已连接的 JSONL peer。
|
|
49
|
+
* @param registration 当前 owner 注册信息。
|
|
50
|
+
*/
|
|
51
|
+
constructor(
|
|
52
|
+
private readonly peer: JsonLinePeer,
|
|
53
|
+
readonly registration: UiWorkerRegistration,
|
|
54
|
+
) {
|
|
55
|
+
super();
|
|
56
|
+
this.peer.on("event", (name: string, data: Record<string, unknown>) => {
|
|
57
|
+
this.emit("worker_event", name, data);
|
|
58
|
+
});
|
|
59
|
+
this.peer.on("close", () => this.emit("close"));
|
|
60
|
+
this.peer.on("transport_error", (error: Error) => this.emit("transport_error", error));
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
/**
|
|
64
|
+
* 向 UI worker 发送控制请求并等待它的响应。
|
|
65
|
+
*
|
|
66
|
+
* @param method 受控 IPC 方法名。
|
|
67
|
+
* @param params 结构化参数对象。
|
|
68
|
+
* @param timeoutMs 等待超时。
|
|
69
|
+
* @returns UI worker 响应数据。
|
|
70
|
+
* @throws {UiWorkerIpcError} worker 断开或请求超时时抛出。
|
|
71
|
+
*/
|
|
72
|
+
request(method: string, params: Record<string, unknown>, timeoutMs = 15 * 60 * 1000): Promise<unknown> {
|
|
73
|
+
return this.peer.request(method, params, timeoutMs);
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
/**
|
|
77
|
+
* 关闭本机 IPC connection。
|
|
78
|
+
*
|
|
79
|
+
* @returns 无返回值。
|
|
80
|
+
*/
|
|
81
|
+
close(): void {
|
|
82
|
+
this.peer.close();
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
/**
|
|
87
|
+
* UI worker IPC 认证后调用的 registry、事件和断连处理器。
|
|
88
|
+
*/
|
|
89
|
+
export interface UiWorkerIpcServerHandlers {
|
|
90
|
+
onRegister: (
|
|
91
|
+
registration: UiWorkerRegistration,
|
|
92
|
+
authHash: string,
|
|
93
|
+
launchRecord: UiWorkerLaunchRecord | undefined,
|
|
94
|
+
connection: UiWorkerIpcConnection,
|
|
95
|
+
) => Promise<void>;
|
|
96
|
+
onWorkerEvent?: (
|
|
97
|
+
connection: UiWorkerIpcConnection,
|
|
98
|
+
name: string,
|
|
99
|
+
data: Record<string, unknown>,
|
|
100
|
+
) => Promise<void>;
|
|
101
|
+
onRequest?: (
|
|
102
|
+
connection: UiWorkerIpcConnection,
|
|
103
|
+
method: string,
|
|
104
|
+
params: Record<string, unknown>,
|
|
105
|
+
) => Promise<unknown>;
|
|
106
|
+
onDisconnect?: (connection: UiWorkerIpcConnection, serverStopping: boolean) => Promise<void>;
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
/**
|
|
110
|
+
* 通过 stable named pipe 管理 Hub session owner 注册、重连与受控 request。
|
|
111
|
+
*/
|
|
112
|
+
export class UiWorkerIpcServer extends EventEmitter {
|
|
113
|
+
readonly endpoint: string;
|
|
114
|
+
private server?: Server;
|
|
115
|
+
private managerAuthHash?: string;
|
|
116
|
+
private stopping = false;
|
|
117
|
+
private handlers?: UiWorkerIpcServerHandlers;
|
|
118
|
+
private readonly pendingLaunches = new Map<string, UiWorkerLaunchRecord>();
|
|
119
|
+
private readonly reservedLaunches = new Set<string>();
|
|
120
|
+
private readonly connections = new Map<string, UiWorkerIpcConnection>();
|
|
121
|
+
private readonly sockets = new Set<Socket>();
|
|
122
|
+
|
|
123
|
+
/**
|
|
124
|
+
* 创建 UI worker IPC server。
|
|
125
|
+
*
|
|
126
|
+
* @param managerDirectory manager 数据目录。
|
|
127
|
+
* @param registry 单写者 manager registry。
|
|
128
|
+
* @param options 可选 endpoint, 用于本机 IPC 测试。
|
|
129
|
+
*/
|
|
130
|
+
constructor(
|
|
131
|
+
private readonly managerDirectory: string,
|
|
132
|
+
private readonly registry: ManagerRegistry,
|
|
133
|
+
private readonly lease: GatewayLease,
|
|
134
|
+
options: { endpoint?: string } = {},
|
|
135
|
+
) {
|
|
136
|
+
super();
|
|
137
|
+
this.endpoint = options.endpoint ?? createStableNamedPipe(managerDirectory);
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
/**
|
|
141
|
+
* 设置注册、运行事件和连接关闭处理器。
|
|
142
|
+
*
|
|
143
|
+
* @param handlers worker 生命周期 handler。
|
|
144
|
+
* @returns 无返回值。
|
|
145
|
+
*/
|
|
146
|
+
setHandlers(handlers: UiWorkerIpcServerHandlers): void {
|
|
147
|
+
this.handlers = handlers;
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
/**
|
|
151
|
+
* 启动 UI worker IPC server。
|
|
152
|
+
*
|
|
153
|
+
* @returns server 开始监听时正常结束。
|
|
154
|
+
* @throws {UiWorkerIpcError} endpoint 不可用时抛出。
|
|
155
|
+
*/
|
|
156
|
+
async listen(): Promise<void> {
|
|
157
|
+
if (process.platform !== "win32" && !this.endpoint.startsWith("/")) {
|
|
158
|
+
throw new UiWorkerIpcError("pipe_unavailable", "可见 UI worker named pipe 仅支持 Windows。 ");
|
|
159
|
+
}
|
|
160
|
+
if (this.server) {
|
|
161
|
+
return;
|
|
162
|
+
}
|
|
163
|
+
await this.cleanupAbandonedLaunchRecords();
|
|
164
|
+
this.managerAuthHash = hashUiWorkerTicket(await readOrCreateUiWorkerAttachToken(this.managerDirectory));
|
|
165
|
+
const server = createServer((socket) => {
|
|
166
|
+
this.sockets.add(socket);
|
|
167
|
+
socket.once("close", () => this.sockets.delete(socket));
|
|
168
|
+
void this.acceptSocket(socket).catch(() => socket.destroy());
|
|
169
|
+
});
|
|
170
|
+
this.server = server;
|
|
171
|
+
await new Promise<void>((resolveListen, rejectListen) => {
|
|
172
|
+
const onError = (): void => {
|
|
173
|
+
server.off("listening", onListening);
|
|
174
|
+
this.server = undefined;
|
|
175
|
+
rejectListen(new UiWorkerIpcError("pipe_unavailable", "UI worker pipe endpoint 已占用或不可用。 "));
|
|
176
|
+
};
|
|
177
|
+
const onListening = (): void => {
|
|
178
|
+
server.off("error", onError);
|
|
179
|
+
resolveListen();
|
|
180
|
+
};
|
|
181
|
+
server.once("error", onError);
|
|
182
|
+
server.once("listening", onListening);
|
|
183
|
+
server.listen(this.endpoint);
|
|
184
|
+
});
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
/**
|
|
188
|
+
* 在取得 lease 后清理上一个 Gateway 遗留的未完成一次性 launch files。
|
|
189
|
+
*
|
|
190
|
+
* @returns 清理完成后正常结束。
|
|
191
|
+
*/
|
|
192
|
+
private async cleanupAbandonedLaunchRecords(): Promise<void> {
|
|
193
|
+
await this.lease.assertOwned();
|
|
194
|
+
const launchDirectory = join(this.managerDirectory, "launches");
|
|
195
|
+
let entries;
|
|
196
|
+
try {
|
|
197
|
+
const launchDirectoryStat = await lstat(launchDirectory);
|
|
198
|
+
if (!launchDirectoryStat.isDirectory() || launchDirectoryStat.isSymbolicLink()) {
|
|
199
|
+
throw new UiWorkerIpcError("launch_record_invalid", "launches 路径不是普通目录, Gateway fail-closed。 ");
|
|
200
|
+
}
|
|
201
|
+
entries = await readdir(launchDirectory);
|
|
202
|
+
} catch (error) {
|
|
203
|
+
if (isNodeError(error) && error.code === "ENOENT") {
|
|
204
|
+
return;
|
|
205
|
+
}
|
|
206
|
+
throw error;
|
|
207
|
+
}
|
|
208
|
+
const launchFiles = entries.filter((name) =>
|
|
209
|
+
/^[a-f0-9-]{36}\.json$/i.test(name) || /^.+\.tmp$/i.test(name),
|
|
210
|
+
);
|
|
211
|
+
await Promise.all(launchFiles.map((name) =>
|
|
212
|
+
unlink(join(launchDirectory, name)).catch((error: unknown) => {
|
|
213
|
+
if (!isNodeError(error) || error.code !== "ENOENT") {
|
|
214
|
+
throw error;
|
|
215
|
+
}
|
|
216
|
+
}),
|
|
217
|
+
));
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
/**
|
|
221
|
+
* 将一次性启动信息写到 manager 私有目录并保存待握手记录。
|
|
222
|
+
*
|
|
223
|
+
* @param record 已生成的 UI worker launch record。
|
|
224
|
+
* @returns launch record 文件绝对路径。
|
|
225
|
+
*/
|
|
226
|
+
async registerLaunch(record: UiWorkerLaunchRecord): Promise<string> {
|
|
227
|
+
assertLaunchRecord(record, this.managerDirectory);
|
|
228
|
+
await this.lease.assertOwned();
|
|
229
|
+
const launchDirectory = join(this.managerDirectory, "launches");
|
|
230
|
+
await mkdir(launchDirectory, { recursive: true, mode: 0o700 });
|
|
231
|
+
const launchDirectoryStat = await lstat(launchDirectory);
|
|
232
|
+
if (!launchDirectoryStat.isDirectory() || launchDirectoryStat.isSymbolicLink()) {
|
|
233
|
+
throw new UiWorkerIpcError("launch_record_invalid", "launches 路径不是 manager 下的普通目录。 ");
|
|
234
|
+
}
|
|
235
|
+
const filePath = join(launchDirectory, `${record.launchId}.json`);
|
|
236
|
+
const temporaryPath = `${filePath}.${process.pid}.${randomUUID()}.tmp`;
|
|
237
|
+
const handle = await open(temporaryPath, "wx", 0o600);
|
|
238
|
+
try {
|
|
239
|
+
await handle.writeFile(`${JSON.stringify(record)}\n`, "utf8");
|
|
240
|
+
await handle.sync();
|
|
241
|
+
} catch (error) {
|
|
242
|
+
await handle.close();
|
|
243
|
+
await unlink(temporaryPath).catch(() => undefined);
|
|
244
|
+
throw error;
|
|
245
|
+
}
|
|
246
|
+
await handle.close();
|
|
247
|
+
try {
|
|
248
|
+
await rename(temporaryPath, filePath);
|
|
249
|
+
} catch (error) {
|
|
250
|
+
await unlink(temporaryPath).catch(() => undefined);
|
|
251
|
+
throw error;
|
|
252
|
+
}
|
|
253
|
+
this.pendingLaunches.set(record.launchId, record);
|
|
254
|
+
return filePath;
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
/**
|
|
258
|
+
* 等待新启动的 UI worker 完成注册。
|
|
259
|
+
*
|
|
260
|
+
* @param launchId launch UUID。
|
|
261
|
+
* @param timeoutMs 握手时限。
|
|
262
|
+
* @returns 已注册连接。
|
|
263
|
+
*/
|
|
264
|
+
waitForLaunch(launchId: string, timeoutMs: number): Promise<UiWorkerIpcConnection> {
|
|
265
|
+
return this.waitForConnection((connection) => connection.registration.launchId === launchId, timeoutMs);
|
|
266
|
+
}
|
|
267
|
+
|
|
268
|
+
/**
|
|
269
|
+
* 等待先前已登记且仍存活的 UI worker 重新连接。
|
|
270
|
+
*
|
|
271
|
+
* @param instanceId registry instance ID。
|
|
272
|
+
* @param timeoutMs 最大等待时间。
|
|
273
|
+
* @returns 已认证的 UI worker connection。
|
|
274
|
+
*/
|
|
275
|
+
waitForReattach(instanceId: string, timeoutMs: number): Promise<UiWorkerIpcConnection> {
|
|
276
|
+
const connection = this.connections.get(instanceId);
|
|
277
|
+
if (connection) {
|
|
278
|
+
return Promise.resolve(connection);
|
|
279
|
+
}
|
|
280
|
+
return this.waitForConnection((candidate) => candidate.registration.instanceId === instanceId, timeoutMs);
|
|
281
|
+
}
|
|
282
|
+
|
|
283
|
+
/**
|
|
284
|
+
* 查询一个已认证 UI worker connection。
|
|
285
|
+
*
|
|
286
|
+
* @param instanceId worker instance ID。
|
|
287
|
+
* @returns 当前 connection 或 undefined。
|
|
288
|
+
*/
|
|
289
|
+
getConnection(instanceId: string): UiWorkerIpcConnection | undefined {
|
|
290
|
+
return this.connections.get(instanceId);
|
|
291
|
+
}
|
|
292
|
+
|
|
293
|
+
/**
|
|
294
|
+
* 删除已使用的 launch ticket 文件。
|
|
295
|
+
*
|
|
296
|
+
* @param launchId launch UUID。
|
|
297
|
+
* @returns 无返回值。
|
|
298
|
+
*/
|
|
299
|
+
async removeLaunch(launchId: string): Promise<void> {
|
|
300
|
+
this.pendingLaunches.delete(launchId);
|
|
301
|
+
this.reservedLaunches.delete(launchId);
|
|
302
|
+
await this.lease.assertOwned();
|
|
303
|
+
try {
|
|
304
|
+
await unlink(join(this.managerDirectory, "launches", `${launchId}.json`));
|
|
305
|
+
} catch (error) {
|
|
306
|
+
if (!isNodeError(error) || error.code !== "ENOENT") {
|
|
307
|
+
throw error;
|
|
308
|
+
}
|
|
309
|
+
}
|
|
310
|
+
}
|
|
311
|
+
|
|
312
|
+
/**
|
|
313
|
+
* 停止监听并断开 pipe sockets, 不关闭用户的 Pi TUI 进程。
|
|
314
|
+
*
|
|
315
|
+
* @returns server close 完成时正常结束。
|
|
316
|
+
*/
|
|
317
|
+
async close(): Promise<void> {
|
|
318
|
+
this.stopping = true;
|
|
319
|
+
await Promise.all([...this.pendingLaunches.keys()].map((launchId) =>
|
|
320
|
+
this.removeLaunch(launchId).catch(() => undefined),
|
|
321
|
+
));
|
|
322
|
+
for (const socket of this.sockets) {
|
|
323
|
+
socket.destroy();
|
|
324
|
+
}
|
|
325
|
+
this.sockets.clear();
|
|
326
|
+
for (const connection of this.connections.values()) {
|
|
327
|
+
connection.close();
|
|
328
|
+
}
|
|
329
|
+
this.connections.clear();
|
|
330
|
+
const server = this.server;
|
|
331
|
+
this.server = undefined;
|
|
332
|
+
if (!server) {
|
|
333
|
+
return;
|
|
334
|
+
}
|
|
335
|
+
await new Promise<void>((resolveClose) => server.close(() => resolveClose()));
|
|
336
|
+
}
|
|
337
|
+
|
|
338
|
+
/**
|
|
339
|
+
* 等待指定的 worker registration event。
|
|
340
|
+
*
|
|
341
|
+
* @param predicate 连接匹配函数。
|
|
342
|
+
* @param timeoutMs 最大等待时间。
|
|
343
|
+
* @returns 匹配连接。
|
|
344
|
+
*/
|
|
345
|
+
private waitForConnection(
|
|
346
|
+
predicate: (connection: UiWorkerIpcConnection) => boolean,
|
|
347
|
+
timeoutMs: number,
|
|
348
|
+
): Promise<UiWorkerIpcConnection> {
|
|
349
|
+
const found = [...this.connections.values()].find(predicate);
|
|
350
|
+
if (found) {
|
|
351
|
+
return Promise.resolve(found);
|
|
352
|
+
}
|
|
353
|
+
return new Promise<UiWorkerIpcConnection>((resolveConnection, rejectConnection) => {
|
|
354
|
+
const timer = setTimeout(() => {
|
|
355
|
+
this.off("worker_registered", onRegistered);
|
|
356
|
+
rejectConnection(new UiWorkerIpcError("request_timeout", "UI worker 未在期限内注册或重连。 "));
|
|
357
|
+
}, timeoutMs);
|
|
358
|
+
timer.unref();
|
|
359
|
+
const onRegistered = (connection: UiWorkerIpcConnection): void => {
|
|
360
|
+
if (!predicate(connection)) {
|
|
361
|
+
return;
|
|
362
|
+
}
|
|
363
|
+
clearTimeout(timer);
|
|
364
|
+
this.off("worker_registered", onRegistered);
|
|
365
|
+
resolveConnection(connection);
|
|
366
|
+
};
|
|
367
|
+
this.on("worker_registered", onRegistered);
|
|
368
|
+
});
|
|
369
|
+
}
|
|
370
|
+
|
|
371
|
+
/**
|
|
372
|
+
* 执行 UI worker challenge-response 握手。
|
|
373
|
+
*
|
|
374
|
+
* @param socket 新接入的 socket。
|
|
375
|
+
* @returns 注册、连接监听或安全拒绝结束。
|
|
376
|
+
*/
|
|
377
|
+
private async acceptSocket(socket: Socket): Promise<void> {
|
|
378
|
+
const peer = new JsonLinePeer(socket);
|
|
379
|
+
let reservedLaunchId: string | undefined;
|
|
380
|
+
try {
|
|
381
|
+
const hello = await peer.nextMessage(10000);
|
|
382
|
+
if (!isPlainRecord(hello)) {
|
|
383
|
+
throw new UiWorkerIpcError("handshake_rejected", "UI worker hello frame 无效。 ");
|
|
384
|
+
}
|
|
385
|
+
if (hello.kind === "control_hello") {
|
|
386
|
+
await this.acceptControlConnection(peer, hello);
|
|
387
|
+
return;
|
|
388
|
+
}
|
|
389
|
+
if (hello.kind !== "hello") {
|
|
390
|
+
throw new UiWorkerIpcError("handshake_rejected", "UI worker 首个 IPC frame 必须为 hello。 ");
|
|
391
|
+
}
|
|
392
|
+
const registration = parseUiWorkerRegistration(hello.registration);
|
|
393
|
+
const authKind = hello.authKind === undefined ? "ticket" : hello.authKind;
|
|
394
|
+
if (authKind !== "ticket" && authKind !== "manager") {
|
|
395
|
+
throw new UiWorkerIpcError("handshake_rejected", "UI worker authentication kind 无效。 ");
|
|
396
|
+
}
|
|
397
|
+
const auth = await this.resolveAuthContext(registration, authKind);
|
|
398
|
+
if (auth.launchRecord) {
|
|
399
|
+
reservedLaunchId = auth.launchRecord.launchId;
|
|
400
|
+
}
|
|
401
|
+
const nonce = randomBytes(32).toString("base64url");
|
|
402
|
+
peer.send({ kind: "challenge", nonce });
|
|
403
|
+
const proof = await peer.nextMessage(10000);
|
|
404
|
+
if (proof.kind !== "proof" || typeof proof.value !== "string") {
|
|
405
|
+
throw new UiWorkerIpcError("handshake_rejected", "UI worker challenge response 格式无效。 ");
|
|
406
|
+
}
|
|
407
|
+
const expectedProof = createUiWorkerProof(auth.authHash, nonce, registration);
|
|
408
|
+
if (!safeEqualBase64(proof.value, expectedProof)) {
|
|
409
|
+
throw new UiWorkerIpcError("handshake_rejected", "UI worker challenge response 校验失败。 ");
|
|
410
|
+
}
|
|
411
|
+
const connection = new UiWorkerIpcConnection(peer, registration);
|
|
412
|
+
if (!this.handlers) {
|
|
413
|
+
throw new UiWorkerIpcError("pipe_unavailable", "Gateway UI worker handler 尚未注册。 ");
|
|
414
|
+
}
|
|
415
|
+
await this.handlers.onRegister(registration, auth.authHash, auth.launchRecord, connection);
|
|
416
|
+
const oldConnection = this.connections.get(registration.instanceId);
|
|
417
|
+
if (oldConnection && oldConnection !== connection) {
|
|
418
|
+
oldConnection.close();
|
|
419
|
+
}
|
|
420
|
+
this.connections.set(registration.instanceId, connection);
|
|
421
|
+
connection.on("worker_event", (name: string, data: Record<string, unknown>) => {
|
|
422
|
+
void this.handlers?.onWorkerEvent?.(connection, name, data).catch(() => undefined);
|
|
423
|
+
});
|
|
424
|
+
peer.setRequestHandler(async (method, params) => {
|
|
425
|
+
if (method === "worker_shutdown") {
|
|
426
|
+
await this.handlers?.onWorkerEvent?.(connection!, "worker_shutdown", params);
|
|
427
|
+
return { accepted: true };
|
|
428
|
+
}
|
|
429
|
+
if (this.handlers?.onRequest) {
|
|
430
|
+
return this.handlers.onRequest(connection!, method, params);
|
|
431
|
+
}
|
|
432
|
+
throw new UiWorkerIpcError("invalid_frame", "Gateway 不支持该 UI worker IPC request。 ");
|
|
433
|
+
});
|
|
434
|
+
connection.once("close", () => {
|
|
435
|
+
if (this.connections.get(registration.instanceId) === connection) {
|
|
436
|
+
this.connections.delete(registration.instanceId);
|
|
437
|
+
}
|
|
438
|
+
void this.handlers?.onDisconnect?.(connection, this.stopping).catch(() => undefined);
|
|
439
|
+
});
|
|
440
|
+
peer.send({ kind: "registered", instanceId: registration.instanceId });
|
|
441
|
+
const ready = await peer.nextMessage(5000);
|
|
442
|
+
if (ready.kind !== "client_ready") {
|
|
443
|
+
throw new UiWorkerIpcError("handshake_rejected", "UI worker 未能初始化 IPC request handler。 ");
|
|
444
|
+
}
|
|
445
|
+
if (auth.launchRecord) {
|
|
446
|
+
await this.removeLaunch(auth.launchRecord.launchId);
|
|
447
|
+
}
|
|
448
|
+
this.emit("worker_registered", connection);
|
|
449
|
+
} catch (error) {
|
|
450
|
+
if (reservedLaunchId) {
|
|
451
|
+
this.reservedLaunches.delete(reservedLaunchId);
|
|
452
|
+
}
|
|
453
|
+
const message = error instanceof UiWorkerIpcError
|
|
454
|
+
? error.message
|
|
455
|
+
: "UI worker 注册未通过安全校验。";
|
|
456
|
+
peer.send({ kind: "registration_error", message });
|
|
457
|
+
peer.close();
|
|
458
|
+
}
|
|
459
|
+
}
|
|
460
|
+
|
|
461
|
+
/**
|
|
462
|
+
* 建立只允许发起 can_switch_session request 的临时本机控制连接。
|
|
463
|
+
*
|
|
464
|
+
* @param peer 已连接 JSONL peer。
|
|
465
|
+
* @param hello 已通过 JSON decode 的首个 control frame。
|
|
466
|
+
* @returns control client ready handshake 完成后正常结束。
|
|
467
|
+
* @throws {UiWorkerIpcError} attach token 或 control request 校验失败时抛出。
|
|
468
|
+
*/
|
|
469
|
+
private async acceptControlConnection(
|
|
470
|
+
peer: JsonLinePeer,
|
|
471
|
+
hello: Record<string, unknown>,
|
|
472
|
+
): Promise<void> {
|
|
473
|
+
const registration = parseUiWorkerRegistration(hello.registration);
|
|
474
|
+
await this.lease.assertOwned();
|
|
475
|
+
const authHash = this.managerAuthHash;
|
|
476
|
+
if (!authHash) {
|
|
477
|
+
throw new UiWorkerIpcError("handshake_rejected", "Gateway UI attach key 尚未初始化。 ");
|
|
478
|
+
}
|
|
479
|
+
const nonce = randomBytes(32).toString("base64url");
|
|
480
|
+
peer.send({ kind: "challenge", nonce });
|
|
481
|
+
const proof = await peer.nextMessage(10000);
|
|
482
|
+
if (proof.kind !== "proof" || typeof proof.value !== "string") {
|
|
483
|
+
throw new UiWorkerIpcError("handshake_rejected", "UI switch control proof 格式无效。 ");
|
|
484
|
+
}
|
|
485
|
+
const expectedProof = createUiWorkerProof(authHash, nonce, registration);
|
|
486
|
+
if (!safeEqualBase64(proof.value, expectedProof)) {
|
|
487
|
+
throw new UiWorkerIpcError("handshake_rejected", "UI switch control attach token 校验失败。 ");
|
|
488
|
+
}
|
|
489
|
+
const connection = new UiWorkerIpcConnection(peer, registration);
|
|
490
|
+
peer.setRequestHandler(async (method, params) => {
|
|
491
|
+
await this.lease.assertOwned();
|
|
492
|
+
if (method !== "can_switch_session" || !this.handlers?.onRequest) {
|
|
493
|
+
throw new UiWorkerIpcError("invalid_frame", "UI switch control connection 仅允许 can_switch_session。 ");
|
|
494
|
+
}
|
|
495
|
+
return this.handlers.onRequest(connection, method, params);
|
|
496
|
+
});
|
|
497
|
+
peer.send({ kind: "control_registered", instanceId: registration.instanceId });
|
|
498
|
+
const ready = await peer.nextMessage(5000);
|
|
499
|
+
if (ready.kind !== "client_ready") {
|
|
500
|
+
throw new UiWorkerIpcError("handshake_rejected", "UI switch control client 未能就绪。 ");
|
|
501
|
+
}
|
|
502
|
+
}
|
|
503
|
+
|
|
504
|
+
/**
|
|
505
|
+
* 解析初次 launch 或进程重连所需的共享秘密 hash。
|
|
506
|
+
*
|
|
507
|
+
* @param registration Pi extension registration。
|
|
508
|
+
* @returns HMAC key 和可选启动记录。
|
|
509
|
+
*/
|
|
510
|
+
private async resolveAuthContext(
|
|
511
|
+
registration: UiWorkerRegistration,
|
|
512
|
+
authKind: "ticket" | "manager",
|
|
513
|
+
): Promise<UiWorkerLaunchAuthContext> {
|
|
514
|
+
const launchRecord = this.pendingLaunches.get(registration.launchId);
|
|
515
|
+
if (launchRecord) {
|
|
516
|
+
if (authKind !== "ticket") {
|
|
517
|
+
throw new UiWorkerIpcError("handshake_rejected", "一次性 UI launch 只能使用对应 ticket 认证。 ");
|
|
518
|
+
}
|
|
519
|
+
if (this.reservedLaunches.has(registration.launchId)) {
|
|
520
|
+
throw new UiWorkerIpcError("handshake_rejected", "UI worker launch ticket 已被另一连接使用。 ");
|
|
521
|
+
}
|
|
522
|
+
this.reservedLaunches.add(registration.launchId);
|
|
523
|
+
if (
|
|
524
|
+
launchRecord.instanceId !== registration.instanceId ||
|
|
525
|
+
Date.parse(launchRecord.expiresAt) <= Date.now() ||
|
|
526
|
+
launchRecord.projectAlias !== registration.projectAlias ||
|
|
527
|
+
!samePath(launchRecord.projectPath, registration.cwd) ||
|
|
528
|
+
(launchRecord.mode === "resume" && (
|
|
529
|
+
launchRecord.sessionId !== registration.sessionId ||
|
|
530
|
+
!samePath(launchRecord.sessionFile ?? "", registration.sessionFile)
|
|
531
|
+
))
|
|
532
|
+
) {
|
|
533
|
+
throw new UiWorkerIpcError("handshake_rejected", "UI worker registration 与 launch record 不匹配。 ");
|
|
534
|
+
}
|
|
535
|
+
return { authHash: hashUiWorkerTicket(launchRecord.ticket), launchRecord };
|
|
536
|
+
}
|
|
537
|
+
|
|
538
|
+
if (authKind === "manager") {
|
|
539
|
+
await this.lease.assertOwned();
|
|
540
|
+
const authHash = this.managerAuthHash;
|
|
541
|
+
if (!authHash) {
|
|
542
|
+
throw new UiWorkerIpcError("handshake_rejected", "Gateway UI attach key 尚未初始化。 ");
|
|
543
|
+
}
|
|
544
|
+
await this.lease.assertOwned();
|
|
545
|
+
return { authHash };
|
|
546
|
+
}
|
|
547
|
+
|
|
548
|
+
const snapshot = await this.registry.readSnapshot();
|
|
549
|
+
const owner = snapshot.instances[registration.instanceId];
|
|
550
|
+
if (
|
|
551
|
+
!owner ||
|
|
552
|
+
owner.mode !== "ui" ||
|
|
553
|
+
owner.launchId !== registration.launchId ||
|
|
554
|
+
owner.pid !== registration.pid ||
|
|
555
|
+
owner.processBirthId !== registration.processBirthId ||
|
|
556
|
+
typeof owner.ipcAuthHash !== "string" ||
|
|
557
|
+
!/^[a-f0-9]{64}$/i.test(owner.ipcAuthHash) ||
|
|
558
|
+
!isProcessAlive(owner.pid)
|
|
559
|
+
) {
|
|
560
|
+
throw new UiWorkerIpcError("handshake_rejected", "UI worker 不是 registry 中有效的 active owner。 ");
|
|
561
|
+
}
|
|
562
|
+
return { authHash: owner.ipcAuthHash };
|
|
563
|
+
}
|
|
564
|
+
}
|
|
565
|
+
|
|
566
|
+
/**
|
|
567
|
+
* 通过 Gateway named pipe 接收可见 Pi TUI control request 并安全重连。
|
|
568
|
+
*/
|
|
569
|
+
export class UiWorkerIpcClient extends EventEmitter {
|
|
570
|
+
private requestHandler?: (method: string, params: Record<string, unknown>) => Promise<unknown>;
|
|
571
|
+
|
|
572
|
+
/**
|
|
573
|
+
* 创建已认证 UI worker client。
|
|
574
|
+
*
|
|
575
|
+
* @param peer JSONL peer。
|
|
576
|
+
* @param registration 当前 worker 注册信息。
|
|
577
|
+
*/
|
|
578
|
+
private constructor(private readonly peer: JsonLinePeer, readonly registration: UiWorkerRegistration) {
|
|
579
|
+
super();
|
|
580
|
+
peer.on("event", (name: string, data: Record<string, unknown>) => this.emit("gateway_event", name, data));
|
|
581
|
+
peer.on("request", (requestId: string, method: string, params: Record<string, unknown>) => {
|
|
582
|
+
void this.handleRequest(requestId, method, params);
|
|
583
|
+
});
|
|
584
|
+
peer.on("close", () => this.emit("close"));
|
|
585
|
+
peer.on("transport_error", (error: Error) => this.emit("transport_error", error));
|
|
586
|
+
}
|
|
587
|
+
|
|
588
|
+
/**
|
|
589
|
+
* 连接 pipe 并完成 HMAC challenge-response。
|
|
590
|
+
*
|
|
591
|
+
* @param endpoint stable pipe endpoint。
|
|
592
|
+
* @param ticket launch record ticket。
|
|
593
|
+
* @param registration 当前 worker registration。
|
|
594
|
+
* @param timeoutMs 握手超时。
|
|
595
|
+
* @returns 已认证 client。
|
|
596
|
+
*/
|
|
597
|
+
static async connect(
|
|
598
|
+
endpoint: string,
|
|
599
|
+
ticket: string,
|
|
600
|
+
registration: UiWorkerRegistration,
|
|
601
|
+
options: {
|
|
602
|
+
timeoutMs?: number;
|
|
603
|
+
managerToken?: string;
|
|
604
|
+
requestHandler?: (method: string, params: Record<string, unknown>) => Promise<unknown>;
|
|
605
|
+
} = {},
|
|
606
|
+
): Promise<UiWorkerIpcClient> {
|
|
607
|
+
const timeoutMs = options.timeoutMs ?? 10000;
|
|
608
|
+
const peer = new JsonLinePeer(createConnection(endpoint));
|
|
609
|
+
try {
|
|
610
|
+
await peer.waitUntilOpen(timeoutMs);
|
|
611
|
+
peer.send({
|
|
612
|
+
kind: "hello",
|
|
613
|
+
registration: publicRegistration(registration),
|
|
614
|
+
authKind: options.managerToken ? "manager" : "ticket",
|
|
615
|
+
});
|
|
616
|
+
const challenge = await peer.nextMessage(timeoutMs);
|
|
617
|
+
if (challenge.kind !== "challenge" || typeof challenge.nonce !== "string") {
|
|
618
|
+
throw new UiWorkerIpcError("handshake_rejected", "Gateway 未返回有效 IPC challenge。 ");
|
|
619
|
+
}
|
|
620
|
+
peer.send({
|
|
621
|
+
kind: "proof",
|
|
622
|
+
value: createUiWorkerProof(
|
|
623
|
+
hashUiWorkerTicket(options.managerToken ?? ticket),
|
|
624
|
+
challenge.nonce,
|
|
625
|
+
registration,
|
|
626
|
+
),
|
|
627
|
+
});
|
|
628
|
+
const accepted = await peer.nextMessage(timeoutMs);
|
|
629
|
+
if (accepted.kind !== "registered" || accepted.instanceId !== registration.instanceId) {
|
|
630
|
+
throw new UiWorkerIpcError(
|
|
631
|
+
"handshake_rejected",
|
|
632
|
+
typeof accepted.message === "string" ? accepted.message : "Gateway 未确认 UI worker 注册。",
|
|
633
|
+
);
|
|
634
|
+
}
|
|
635
|
+
const client = new UiWorkerIpcClient(peer, registration);
|
|
636
|
+
if (options.requestHandler) {
|
|
637
|
+
client.setRequestHandler(options.requestHandler);
|
|
638
|
+
}
|
|
639
|
+
peer.send({ kind: "client_ready" });
|
|
640
|
+
return client;
|
|
641
|
+
} catch (error) {
|
|
642
|
+
peer.close();
|
|
643
|
+
if (error instanceof UiWorkerIpcError) {
|
|
644
|
+
throw error;
|
|
645
|
+
}
|
|
646
|
+
throw new UiWorkerIpcError("pipe_unavailable", "无法连接 Gateway named pipe。 ");
|
|
647
|
+
}
|
|
648
|
+
}
|
|
649
|
+
|
|
650
|
+
/**
|
|
651
|
+
* 建立不占有 session 的本机 UI switch control connection。
|
|
652
|
+
*
|
|
653
|
+
* @param endpoint Gateway UI IPC endpoint。
|
|
654
|
+
* @param managerDirectory Hub 私有数据目录。
|
|
655
|
+
* @param managerToken 当前 manager 目录稳定 attach token。
|
|
656
|
+
* @param options 握手超时配置。
|
|
657
|
+
* @returns 仅用于 can_switch_session 等授权 control request 的 client。
|
|
658
|
+
* @throws {UiWorkerIpcError} server 身份验证或连接失败时抛出。
|
|
659
|
+
*/
|
|
660
|
+
static async connectControl(
|
|
661
|
+
endpoint: string,
|
|
662
|
+
managerDirectory: string,
|
|
663
|
+
managerToken: string,
|
|
664
|
+
options: { timeoutMs?: number } = {},
|
|
665
|
+
): Promise<UiWorkerIpcClient> {
|
|
666
|
+
const registration: UiWorkerRegistration = {
|
|
667
|
+
launchId: randomUUID(),
|
|
668
|
+
instanceId: randomUUID(),
|
|
669
|
+
pid: process.pid,
|
|
670
|
+
processBirthId: `${process.pid}:${Math.floor(Date.now() - process.uptime() * 1000)}`,
|
|
671
|
+
sessionId: "control-only",
|
|
672
|
+
sessionFile: join(resolve(managerDirectory), "control-only.jsonl"),
|
|
673
|
+
cwd: resolve(managerDirectory),
|
|
674
|
+
projectAlias: "control",
|
|
675
|
+
state: "idle",
|
|
676
|
+
};
|
|
677
|
+
const peer = new JsonLinePeer(createConnection(endpoint));
|
|
678
|
+
const timeoutMs = options.timeoutMs ?? 3000;
|
|
679
|
+
try {
|
|
680
|
+
await peer.waitUntilOpen(timeoutMs);
|
|
681
|
+
peer.send({ kind: "control_hello", registration: publicRegistration(registration) });
|
|
682
|
+
const challenge = await peer.nextMessage(timeoutMs);
|
|
683
|
+
if (challenge.kind !== "challenge" || typeof challenge.nonce !== "string") {
|
|
684
|
+
throw new UiWorkerIpcError("handshake_rejected", "Gateway 未返回有效 control challenge。 ");
|
|
685
|
+
}
|
|
686
|
+
peer.send({
|
|
687
|
+
kind: "proof",
|
|
688
|
+
value: createUiWorkerProof(hashUiWorkerTicket(managerToken), challenge.nonce, registration),
|
|
689
|
+
});
|
|
690
|
+
const accepted = await peer.nextMessage(timeoutMs);
|
|
691
|
+
if (accepted.kind !== "control_registered") {
|
|
692
|
+
throw new UiWorkerIpcError("handshake_rejected", "Gateway 未确认 UI switch control connection。 ");
|
|
693
|
+
}
|
|
694
|
+
const client = new UiWorkerIpcClient(peer, registration);
|
|
695
|
+
peer.send({ kind: "client_ready" });
|
|
696
|
+
return client;
|
|
697
|
+
} catch (error) {
|
|
698
|
+
peer.close();
|
|
699
|
+
if (error instanceof UiWorkerIpcError) {
|
|
700
|
+
throw error;
|
|
701
|
+
}
|
|
702
|
+
throw new UiWorkerIpcError("pipe_unavailable", "无法连接 Gateway UI switch control endpoint。 ");
|
|
703
|
+
}
|
|
704
|
+
}
|
|
705
|
+
|
|
706
|
+
/**
|
|
707
|
+
* 配置 Gateway request handler。
|
|
708
|
+
*
|
|
709
|
+
* @param handler 受控 request 分派函数。
|
|
710
|
+
* @returns 无返回值。
|
|
711
|
+
*/
|
|
712
|
+
setRequestHandler(handler: (method: string, params: Record<string, unknown>) => Promise<unknown>): void {
|
|
713
|
+
this.requestHandler = handler;
|
|
714
|
+
}
|
|
715
|
+
|
|
716
|
+
/**
|
|
717
|
+
* 向 Gateway 发起已认证 control request。
|
|
718
|
+
*
|
|
719
|
+
* @param method 受控 request 方法。
|
|
720
|
+
* @param params 结构化参数。
|
|
721
|
+
* @param timeoutMs 等待时限。
|
|
722
|
+
* @returns Gateway response。
|
|
723
|
+
*/
|
|
724
|
+
request(method: string, params: Record<string, unknown>, timeoutMs = 10000): Promise<unknown> {
|
|
725
|
+
return this.peer.request(method, params, timeoutMs);
|
|
726
|
+
}
|
|
727
|
+
|
|
728
|
+
/**
|
|
729
|
+
* 向 Gateway 发送 worker 生命周期事件。
|
|
730
|
+
*
|
|
731
|
+
* @param name 事件名。
|
|
732
|
+
* @param data 事件字段。
|
|
733
|
+
* @returns 无返回值。
|
|
734
|
+
*/
|
|
735
|
+
notify(name: string, data: Record<string, unknown> = {}): void {
|
|
736
|
+
this.peer.send({ kind: "event", name, data });
|
|
737
|
+
}
|
|
738
|
+
|
|
739
|
+
/**
|
|
740
|
+
* 关闭 client socket。
|
|
741
|
+
*
|
|
742
|
+
* @returns 无返回值。
|
|
743
|
+
*/
|
|
744
|
+
close(): void {
|
|
745
|
+
this.peer.close();
|
|
746
|
+
}
|
|
747
|
+
|
|
748
|
+
/**
|
|
749
|
+
* 执行 Gateway request 并返回 typed result。
|
|
750
|
+
*
|
|
751
|
+
* @param requestId request ID。
|
|
752
|
+
* @param method 方法名。
|
|
753
|
+
* @param params 参数对象。
|
|
754
|
+
* @returns 无返回值。
|
|
755
|
+
*/
|
|
756
|
+
private async handleRequest(
|
|
757
|
+
requestId: string,
|
|
758
|
+
method: string,
|
|
759
|
+
params: Record<string, unknown>,
|
|
760
|
+
): Promise<void> {
|
|
761
|
+
try {
|
|
762
|
+
if (!this.requestHandler) {
|
|
763
|
+
throw new UiWorkerIpcError("worker_disconnected", "UI worker 尚未准备好处理 Gateway 请求。 ");
|
|
764
|
+
}
|
|
765
|
+
this.peer.respond(requestId, true, await this.requestHandler(method, params));
|
|
766
|
+
} catch (error) {
|
|
767
|
+
this.peer.respond(
|
|
768
|
+
requestId,
|
|
769
|
+
false,
|
|
770
|
+
undefined,
|
|
771
|
+
error instanceof Error ? error.message : "UI worker request 失败。",
|
|
772
|
+
);
|
|
773
|
+
}
|
|
774
|
+
}
|
|
775
|
+
}
|
|
776
|
+
|
|
777
|
+
/**
|
|
778
|
+
* 通过 newline-delimited JSON 管理一个 socket 的握手消息和控制请求。
|
|
779
|
+
*/
|
|
780
|
+
class JsonLinePeer extends EventEmitter {
|
|
781
|
+
private input = "";
|
|
782
|
+
private closed = false;
|
|
783
|
+
private readonly queue: RawFrame[] = [];
|
|
784
|
+
private readonly waiters: Array<{
|
|
785
|
+
resolve: (frame: RawFrame) => void;
|
|
786
|
+
reject: (error: Error) => void;
|
|
787
|
+
timer: NodeJS.Timeout;
|
|
788
|
+
}> = [];
|
|
789
|
+
private readonly requests = new Map<string, {
|
|
790
|
+
resolve: (value: unknown) => void;
|
|
791
|
+
reject: (error: Error) => void;
|
|
792
|
+
timer: NodeJS.Timeout;
|
|
793
|
+
}>();
|
|
794
|
+
private requestHandler?: (method: string, params: Record<string, unknown>) => Promise<unknown>;
|
|
795
|
+
|
|
796
|
+
/**
|
|
797
|
+
* 创建底层 JSONL socket peer。
|
|
798
|
+
*
|
|
799
|
+
* @param socket 已连接或正在连接的 socket。
|
|
800
|
+
*/
|
|
801
|
+
constructor(private readonly socket: Socket) {
|
|
802
|
+
super();
|
|
803
|
+
socket.setEncoding("utf8");
|
|
804
|
+
socket.on("data", (chunk: string) => this.handleData(chunk));
|
|
805
|
+
socket.on("error", (error) => this.emit("transport_error", error));
|
|
806
|
+
socket.on("close", () => this.handleClose());
|
|
807
|
+
}
|
|
808
|
+
|
|
809
|
+
/**
|
|
810
|
+
* 配置对端发来的 request handler。
|
|
811
|
+
*
|
|
812
|
+
* @param handler request 分派函数。
|
|
813
|
+
* @returns 无返回值。
|
|
814
|
+
*/
|
|
815
|
+
setRequestHandler(handler: (method: string, params: Record<string, unknown>) => Promise<unknown>): void {
|
|
816
|
+
this.requestHandler = handler;
|
|
817
|
+
}
|
|
818
|
+
|
|
819
|
+
/**
|
|
820
|
+
* 等待 socket 建立连接。
|
|
821
|
+
*
|
|
822
|
+
* @param timeoutMs 建连时限。
|
|
823
|
+
* @returns socket connected event。
|
|
824
|
+
*/
|
|
825
|
+
waitUntilOpen(timeoutMs: number): Promise<void> {
|
|
826
|
+
if (this.socket.readyState === "open") {
|
|
827
|
+
return Promise.resolve();
|
|
828
|
+
}
|
|
829
|
+
return new Promise<void>((resolveOpen, rejectOpen) => {
|
|
830
|
+
const cleanup = (): void => {
|
|
831
|
+
clearTimeout(timer);
|
|
832
|
+
this.socket.off("connect", onConnect);
|
|
833
|
+
this.socket.off("error", onError);
|
|
834
|
+
};
|
|
835
|
+
const onConnect = (): void => {
|
|
836
|
+
cleanup();
|
|
837
|
+
resolveOpen();
|
|
838
|
+
};
|
|
839
|
+
const onError = (): void => {
|
|
840
|
+
cleanup();
|
|
841
|
+
rejectOpen(new UiWorkerIpcError("pipe_unavailable", "连接 UI worker pipe 失败。 "));
|
|
842
|
+
};
|
|
843
|
+
const timer = setTimeout(() => {
|
|
844
|
+
cleanup();
|
|
845
|
+
rejectOpen(new UiWorkerIpcError("pipe_unavailable", "连接 UI worker pipe 超时。 "));
|
|
846
|
+
}, timeoutMs);
|
|
847
|
+
timer.unref();
|
|
848
|
+
this.socket.once("connect", onConnect);
|
|
849
|
+
this.socket.once("error", onError);
|
|
850
|
+
});
|
|
851
|
+
}
|
|
852
|
+
|
|
853
|
+
/**
|
|
854
|
+
* 等待握手阶段下一条 frame。
|
|
855
|
+
*
|
|
856
|
+
* @param timeoutMs 等待时限。
|
|
857
|
+
* @returns 下一条 JSON frame。
|
|
858
|
+
*/
|
|
859
|
+
nextMessage(timeoutMs: number): Promise<RawFrame> {
|
|
860
|
+
const queued = this.queue.shift();
|
|
861
|
+
if (queued) {
|
|
862
|
+
return Promise.resolve(queued);
|
|
863
|
+
}
|
|
864
|
+
if (this.closed) {
|
|
865
|
+
return Promise.reject(new UiWorkerIpcError("worker_disconnected", "UI worker IPC socket 已关闭。 "));
|
|
866
|
+
}
|
|
867
|
+
return new Promise<RawFrame>((resolveFrame, rejectFrame) => {
|
|
868
|
+
const timer = setTimeout(() => {
|
|
869
|
+
const index = this.waiters.findIndex((waiter) => waiter.resolve === resolveFrame);
|
|
870
|
+
if (index >= 0) {
|
|
871
|
+
this.waiters.splice(index, 1);
|
|
872
|
+
}
|
|
873
|
+
rejectFrame(new UiWorkerIpcError("request_timeout", "UI worker IPC handshake 超时。 "));
|
|
874
|
+
}, timeoutMs);
|
|
875
|
+
timer.unref();
|
|
876
|
+
this.waiters.push({ resolve: resolveFrame, reject: rejectFrame, timer });
|
|
877
|
+
});
|
|
878
|
+
}
|
|
879
|
+
|
|
880
|
+
/**
|
|
881
|
+
* 发送一个 JSON frame。
|
|
882
|
+
*
|
|
883
|
+
* @param frame frame 对象。
|
|
884
|
+
* @returns 无返回值。
|
|
885
|
+
*/
|
|
886
|
+
send(frame: Record<string, unknown>): void {
|
|
887
|
+
if (this.closed || this.socket.destroyed) {
|
|
888
|
+
throw new UiWorkerIpcError("worker_disconnected", "UI worker IPC socket 已关闭。 ");
|
|
889
|
+
}
|
|
890
|
+
const body = `${JSON.stringify(frame)}\n`;
|
|
891
|
+
if (Buffer.byteLength(body, "utf8") > MAX_FRAME_BYTES) {
|
|
892
|
+
throw new UiWorkerIpcError("invalid_frame", "UI worker IPC frame 超过大小限制。 ");
|
|
893
|
+
}
|
|
894
|
+
this.socket.write(body);
|
|
895
|
+
}
|
|
896
|
+
|
|
897
|
+
/**
|
|
898
|
+
* 发起本机 request 并等待 response。
|
|
899
|
+
*
|
|
900
|
+
* @param method 方法名。
|
|
901
|
+
* @param params 参数对象。
|
|
902
|
+
* @param timeoutMs 等待时限。
|
|
903
|
+
* @returns response data。
|
|
904
|
+
*/
|
|
905
|
+
request(method: string, params: Record<string, unknown>, timeoutMs = 15000): Promise<unknown> {
|
|
906
|
+
const requestId = randomUUID();
|
|
907
|
+
return new Promise<unknown>((resolveRequest, rejectRequest) => {
|
|
908
|
+
const timer = setTimeout(() => {
|
|
909
|
+
this.requests.delete(requestId);
|
|
910
|
+
rejectRequest(new UiWorkerIpcError("request_timeout", `UI worker IPC ${method} 请求超时。`));
|
|
911
|
+
}, timeoutMs);
|
|
912
|
+
timer.unref();
|
|
913
|
+
this.requests.set(requestId, { resolve: resolveRequest, reject: rejectRequest, timer });
|
|
914
|
+
try {
|
|
915
|
+
this.send({ kind: "request", requestId, method, params });
|
|
916
|
+
} catch (error) {
|
|
917
|
+
clearTimeout(timer);
|
|
918
|
+
this.requests.delete(requestId);
|
|
919
|
+
rejectRequest(error instanceof Error ? error : new Error("IPC 发送失败。"));
|
|
920
|
+
}
|
|
921
|
+
});
|
|
922
|
+
}
|
|
923
|
+
|
|
924
|
+
/**
|
|
925
|
+
* 回复对端 request。
|
|
926
|
+
*
|
|
927
|
+
* @param requestId request ID。
|
|
928
|
+
* @param success 是否成功。
|
|
929
|
+
* @param data 成功结果。
|
|
930
|
+
* @param error 失败说明。
|
|
931
|
+
* @returns 无返回值。
|
|
932
|
+
*/
|
|
933
|
+
respond(requestId: string, success: boolean, data?: unknown, error?: string): void {
|
|
934
|
+
this.send({ kind: "response", requestId, success, ...(data === undefined ? {} : { data }), ...(error ? { error } : {}) });
|
|
935
|
+
}
|
|
936
|
+
|
|
937
|
+
/**
|
|
938
|
+
* 主动关闭 socket。
|
|
939
|
+
*
|
|
940
|
+
* @returns 无返回值。
|
|
941
|
+
*/
|
|
942
|
+
close(): void {
|
|
943
|
+
if (this.closed) {
|
|
944
|
+
return;
|
|
945
|
+
}
|
|
946
|
+
this.socket.destroy();
|
|
947
|
+
this.handleClose();
|
|
948
|
+
}
|
|
949
|
+
|
|
950
|
+
/**
|
|
951
|
+
* 解析 newline-delimited JSON frames。
|
|
952
|
+
*
|
|
953
|
+
* @param chunk socket 数据片段。
|
|
954
|
+
* @returns 无返回值。
|
|
955
|
+
*/
|
|
956
|
+
private handleData(chunk: string): void {
|
|
957
|
+
this.input += chunk;
|
|
958
|
+
if (Buffer.byteLength(this.input, "utf8") > MAX_FRAME_BYTES && !this.input.includes("\n")) {
|
|
959
|
+
this.emit("transport_error", new UiWorkerIpcError("invalid_frame", "UI worker IPC 缓冲区超过限制。 "));
|
|
960
|
+
this.close();
|
|
961
|
+
return;
|
|
962
|
+
}
|
|
963
|
+
let newlineIndex = this.input.indexOf("\n");
|
|
964
|
+
while (newlineIndex >= 0) {
|
|
965
|
+
const line = this.input.slice(0, newlineIndex).replace(/\r$/, "");
|
|
966
|
+
this.input = this.input.slice(newlineIndex + 1);
|
|
967
|
+
if (Buffer.byteLength(line, "utf8") > MAX_FRAME_BYTES) {
|
|
968
|
+
this.emit("transport_error", new UiWorkerIpcError("invalid_frame", "UI worker IPC frame 超过限制。 "));
|
|
969
|
+
this.close();
|
|
970
|
+
return;
|
|
971
|
+
}
|
|
972
|
+
if (line.trim()) {
|
|
973
|
+
let parsed: unknown;
|
|
974
|
+
try {
|
|
975
|
+
parsed = JSON.parse(line) as unknown;
|
|
976
|
+
} catch {
|
|
977
|
+
this.emit("transport_error", new UiWorkerIpcError("invalid_frame", "UI worker IPC JSON frame 无效。 "));
|
|
978
|
+
this.close();
|
|
979
|
+
return;
|
|
980
|
+
}
|
|
981
|
+
if (!isPlainRecord(parsed) || typeof parsed.kind !== "string") {
|
|
982
|
+
this.emit("transport_error", new UiWorkerIpcError("invalid_frame", "UI worker IPC frame 根节点无效。 "));
|
|
983
|
+
this.close();
|
|
984
|
+
return;
|
|
985
|
+
}
|
|
986
|
+
this.dispatch(parsed as RawFrame);
|
|
987
|
+
}
|
|
988
|
+
newlineIndex = this.input.indexOf("\n");
|
|
989
|
+
}
|
|
990
|
+
}
|
|
991
|
+
|
|
992
|
+
/**
|
|
993
|
+
* 分派 request response、events 和握手消息。
|
|
994
|
+
*
|
|
995
|
+
* @param frame JSON frame。
|
|
996
|
+
* @returns 无返回值。
|
|
997
|
+
*/
|
|
998
|
+
private dispatch(frame: RawFrame): void {
|
|
999
|
+
if (frame.kind === "response" && typeof frame.requestId === "string") {
|
|
1000
|
+
const pending = this.requests.get(frame.requestId);
|
|
1001
|
+
if (pending) {
|
|
1002
|
+
this.requests.delete(frame.requestId);
|
|
1003
|
+
clearTimeout(pending.timer);
|
|
1004
|
+
if (frame.success === true) {
|
|
1005
|
+
pending.resolve(frame.data);
|
|
1006
|
+
} else {
|
|
1007
|
+
pending.reject(new UiWorkerIpcError(
|
|
1008
|
+
"worker_disconnected",
|
|
1009
|
+
typeof frame.error === "string" ? frame.error : "UI worker IPC request 被拒绝。",
|
|
1010
|
+
));
|
|
1011
|
+
}
|
|
1012
|
+
}
|
|
1013
|
+
return;
|
|
1014
|
+
}
|
|
1015
|
+
if (frame.kind === "request") {
|
|
1016
|
+
if (
|
|
1017
|
+
typeof frame.requestId !== "string" ||
|
|
1018
|
+
typeof frame.method !== "string" ||
|
|
1019
|
+
!isPlainRecord(frame.params)
|
|
1020
|
+
) {
|
|
1021
|
+
this.emit("transport_error", new UiWorkerIpcError("invalid_frame", "UI worker IPC request 字段无效。 "));
|
|
1022
|
+
this.close();
|
|
1023
|
+
return;
|
|
1024
|
+
}
|
|
1025
|
+
if (this.requestHandler) {
|
|
1026
|
+
void this.handleRequest(frame.requestId, frame.method, frame.params);
|
|
1027
|
+
} else {
|
|
1028
|
+
this.emit("request", frame.requestId, frame.method, frame.params);
|
|
1029
|
+
}
|
|
1030
|
+
return;
|
|
1031
|
+
}
|
|
1032
|
+
if (frame.kind === "event" && typeof frame.name === "string" && isPlainRecord(frame.data)) {
|
|
1033
|
+
this.emit("event", frame.name, frame.data);
|
|
1034
|
+
return;
|
|
1035
|
+
}
|
|
1036
|
+
const waiter = this.waiters.shift();
|
|
1037
|
+
if (waiter) {
|
|
1038
|
+
clearTimeout(waiter.timer);
|
|
1039
|
+
waiter.resolve(frame);
|
|
1040
|
+
} else {
|
|
1041
|
+
this.queue.push(frame);
|
|
1042
|
+
}
|
|
1043
|
+
}
|
|
1044
|
+
|
|
1045
|
+
/**
|
|
1046
|
+
* 调用已配置的 request handler 并响应对端。
|
|
1047
|
+
*
|
|
1048
|
+
* @param requestId 对端 request ID。
|
|
1049
|
+
* @param method 控制方法。
|
|
1050
|
+
* @param params request 参数。
|
|
1051
|
+
* @returns 无返回值。
|
|
1052
|
+
*/
|
|
1053
|
+
private async handleRequest(
|
|
1054
|
+
requestId: string,
|
|
1055
|
+
method: string,
|
|
1056
|
+
params: Record<string, unknown>,
|
|
1057
|
+
): Promise<void> {
|
|
1058
|
+
try {
|
|
1059
|
+
const result = await this.requestHandler?.(method, params);
|
|
1060
|
+
this.respond(requestId, true, result);
|
|
1061
|
+
} catch (error) {
|
|
1062
|
+
this.respond(
|
|
1063
|
+
requestId,
|
|
1064
|
+
false,
|
|
1065
|
+
undefined,
|
|
1066
|
+
error instanceof Error ? error.message : "UI worker IPC request 失败。",
|
|
1067
|
+
);
|
|
1068
|
+
}
|
|
1069
|
+
}
|
|
1070
|
+
|
|
1071
|
+
/**
|
|
1072
|
+
* 清理等待操作并广播 socket 关闭。
|
|
1073
|
+
*
|
|
1074
|
+
* @returns 无返回值。
|
|
1075
|
+
*/
|
|
1076
|
+
private handleClose(): void {
|
|
1077
|
+
if (this.closed) {
|
|
1078
|
+
return;
|
|
1079
|
+
}
|
|
1080
|
+
this.closed = true;
|
|
1081
|
+
const error = new UiWorkerIpcError("worker_disconnected", "UI worker IPC connection 已断开。 ");
|
|
1082
|
+
for (const pending of this.requests.values()) {
|
|
1083
|
+
clearTimeout(pending.timer);
|
|
1084
|
+
pending.reject(error);
|
|
1085
|
+
}
|
|
1086
|
+
this.requests.clear();
|
|
1087
|
+
for (const waiter of this.waiters) {
|
|
1088
|
+
clearTimeout(waiter.timer);
|
|
1089
|
+
waiter.reject(error);
|
|
1090
|
+
}
|
|
1091
|
+
this.waiters.length = 0;
|
|
1092
|
+
this.emit("close");
|
|
1093
|
+
}
|
|
1094
|
+
}
|
|
1095
|
+
|
|
1096
|
+
interface RawFrame extends Record<string, unknown> {
|
|
1097
|
+
kind: string;
|
|
1098
|
+
}
|
|
1099
|
+
|
|
1100
|
+
interface UiWorkerLaunchAuthContext {
|
|
1101
|
+
authHash: string;
|
|
1102
|
+
launchRecord?: UiWorkerLaunchRecord;
|
|
1103
|
+
}
|
|
1104
|
+
|
|
1105
|
+
/**
|
|
1106
|
+
* 校验 iLink/Pi IPC 外部输入是否为普通 object。
|
|
1107
|
+
*
|
|
1108
|
+
* @param value 任意 JSON value。
|
|
1109
|
+
* @returns 非 null 非数组 object 时返回 true。
|
|
1110
|
+
*/
|
|
1111
|
+
function isPlainRecord(value: unknown): value is Record<string, unknown> {
|
|
1112
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
1113
|
+
}
|
|
1114
|
+
|
|
1115
|
+
/**
|
|
1116
|
+
* 从未经信任的 JSON frame 校验 UI worker registration。
|
|
1117
|
+
*
|
|
1118
|
+
* @param value frame registration。
|
|
1119
|
+
* @returns 字段经过限制的 registration。
|
|
1120
|
+
* @throws {UiWorkerIpcError} 字段无效时抛出。
|
|
1121
|
+
*/
|
|
1122
|
+
export function parseUiWorkerRegistration(value: unknown): UiWorkerRegistration {
|
|
1123
|
+
if (!isPlainRecord(value)) {
|
|
1124
|
+
throw new UiWorkerIpcError("handshake_rejected", "UI worker registration 必须是 object。 ");
|
|
1125
|
+
}
|
|
1126
|
+
const fields = value as Record<string, unknown>;
|
|
1127
|
+
const allowedFields = new Set([
|
|
1128
|
+
"launchId",
|
|
1129
|
+
"instanceId",
|
|
1130
|
+
"pid",
|
|
1131
|
+
"processBirthId",
|
|
1132
|
+
"sessionId",
|
|
1133
|
+
"sessionFile",
|
|
1134
|
+
"cwd",
|
|
1135
|
+
"projectAlias",
|
|
1136
|
+
"state",
|
|
1137
|
+
"name",
|
|
1138
|
+
]);
|
|
1139
|
+
if (
|
|
1140
|
+
Object.keys(fields).some((key) => !allowedFields.has(key)) ||
|
|
1141
|
+
!isUuid(fields.launchId) ||
|
|
1142
|
+
!isUuid(fields.instanceId) ||
|
|
1143
|
+
typeof fields.pid !== "number" || !Number.isInteger(fields.pid) || fields.pid <= 0 ||
|
|
1144
|
+
typeof fields.processBirthId !== "string" || !fields.processBirthId.trim() || fields.processBirthId.length > 128 ||
|
|
1145
|
+
typeof fields.sessionId !== "string" || !fields.sessionId.trim() || fields.sessionId.length > 256 ||
|
|
1146
|
+
typeof fields.sessionFile !== "string" || !isAbsolute(fields.sessionFile) || fields.sessionFile.length > 32768 ||
|
|
1147
|
+
typeof fields.cwd !== "string" || !isAbsolute(fields.cwd) || fields.cwd.length > 32768 ||
|
|
1148
|
+
typeof fields.projectAlias !== "string" || !/^[a-z0-9][a-z0-9_-]{0,31}$/.test(fields.projectAlias) ||
|
|
1149
|
+
(fields.state !== "starting" && fields.state !== "idle" && fields.state !== "running") ||
|
|
1150
|
+
(fields.name !== undefined && (typeof fields.name !== "string" || fields.name.length > 100))
|
|
1151
|
+
) {
|
|
1152
|
+
throw new UiWorkerIpcError("handshake_rejected", "UI worker registration 字段无效。 ");
|
|
1153
|
+
}
|
|
1154
|
+
return {
|
|
1155
|
+
launchId: fields.launchId,
|
|
1156
|
+
instanceId: fields.instanceId,
|
|
1157
|
+
pid: fields.pid,
|
|
1158
|
+
processBirthId: fields.processBirthId,
|
|
1159
|
+
sessionId: fields.sessionId,
|
|
1160
|
+
sessionFile: fields.sessionFile,
|
|
1161
|
+
cwd: fields.cwd,
|
|
1162
|
+
projectAlias: fields.projectAlias,
|
|
1163
|
+
state: fields.state,
|
|
1164
|
+
...(typeof fields.name === "string" ? { name: fields.name } : {}),
|
|
1165
|
+
};
|
|
1166
|
+
}
|
|
1167
|
+
|
|
1168
|
+
function publicRegistration(registration: UiWorkerRegistration): UiWorkerRegistration {
|
|
1169
|
+
return {
|
|
1170
|
+
launchId: registration.launchId,
|
|
1171
|
+
instanceId: registration.instanceId,
|
|
1172
|
+
pid: registration.pid,
|
|
1173
|
+
processBirthId: registration.processBirthId,
|
|
1174
|
+
sessionId: registration.sessionId,
|
|
1175
|
+
sessionFile: registration.sessionFile,
|
|
1176
|
+
cwd: registration.cwd,
|
|
1177
|
+
projectAlias: registration.projectAlias,
|
|
1178
|
+
state: registration.state,
|
|
1179
|
+
...(registration.name === undefined ? {} : { name: registration.name }),
|
|
1180
|
+
};
|
|
1181
|
+
}
|
|
1182
|
+
|
|
1183
|
+
/**
|
|
1184
|
+
* 从私有 manager/launches 目录读取并校验一次性 UI worker 启动记录。
|
|
1185
|
+
*
|
|
1186
|
+
* @param managerDirectory manager 数据目录。
|
|
1187
|
+
* @param launchId UI worker launch UUID。
|
|
1188
|
+
* @returns 已校验的一次性启动记录。
|
|
1189
|
+
* @throws {UiWorkerIpcError} 文件缺失、越界或内容无效时抛出。
|
|
1190
|
+
*/
|
|
1191
|
+
export async function readUiWorkerLaunchRecord(
|
|
1192
|
+
managerDirectory: string,
|
|
1193
|
+
launchId: string,
|
|
1194
|
+
): Promise<UiWorkerLaunchRecord> {
|
|
1195
|
+
if (!isUuid(launchId)) {
|
|
1196
|
+
throw new UiWorkerIpcError("launch_record_invalid", "UI worker launchId 格式无效。 ");
|
|
1197
|
+
}
|
|
1198
|
+
const canonicalManagerDirectory = await realpath(resolve(managerDirectory)).catch(() => {
|
|
1199
|
+
throw new UiWorkerIpcError("launch_record_invalid", "manager 数据目录无法解析。 ");
|
|
1200
|
+
});
|
|
1201
|
+
const launchDirectory = join(canonicalManagerDirectory, "launches");
|
|
1202
|
+
const filePath = join(launchDirectory, `${launchId}.json`);
|
|
1203
|
+
try {
|
|
1204
|
+
const [canonicalLaunchDirectory, fileStat] = await Promise.all([
|
|
1205
|
+
realpath(launchDirectory),
|
|
1206
|
+
lstat(filePath),
|
|
1207
|
+
]);
|
|
1208
|
+
if (
|
|
1209
|
+
!samePath(dirname(canonicalLaunchDirectory), canonicalManagerDirectory) ||
|
|
1210
|
+
fileStat.isSymbolicLink() ||
|
|
1211
|
+
!fileStat.isFile() ||
|
|
1212
|
+
fileStat.size <= 0 ||
|
|
1213
|
+
fileStat.size > MAX_LAUNCH_RECORD_BYTES
|
|
1214
|
+
) {
|
|
1215
|
+
throw new UiWorkerIpcError("launch_record_invalid", "launch record 路径或文件状态不安全。 ");
|
|
1216
|
+
}
|
|
1217
|
+
const noFollow = "O_NOFOLLOW" in constants ? Number(constants.O_NOFOLLOW) : 0;
|
|
1218
|
+
const handle = await open(filePath, constants.O_RDONLY | noFollow);
|
|
1219
|
+
let content: string;
|
|
1220
|
+
try {
|
|
1221
|
+
const openedStat = await handle.stat();
|
|
1222
|
+
if (
|
|
1223
|
+
!openedStat.isFile() ||
|
|
1224
|
+
openedStat.dev !== fileStat.dev ||
|
|
1225
|
+
openedStat.ino !== fileStat.ino ||
|
|
1226
|
+
openedStat.size > MAX_LAUNCH_RECORD_BYTES
|
|
1227
|
+
) {
|
|
1228
|
+
throw new UiWorkerIpcError("launch_record_invalid", "launch record 在读取期间发生变化。 ");
|
|
1229
|
+
}
|
|
1230
|
+
content = await handle.readFile("utf8");
|
|
1231
|
+
} finally {
|
|
1232
|
+
await handle.close();
|
|
1233
|
+
}
|
|
1234
|
+
const record = parseLaunchRecord(JSON.parse(content) as unknown, canonicalManagerDirectory);
|
|
1235
|
+
if (record.launchId !== launchId || Date.parse(record.expiresAt) <= Date.now()) {
|
|
1236
|
+
throw new UiWorkerIpcError("launch_record_invalid", "launch record 已过期或 ID 不匹配。 ");
|
|
1237
|
+
}
|
|
1238
|
+
return record;
|
|
1239
|
+
} catch (error) {
|
|
1240
|
+
if (error instanceof UiWorkerIpcError) {
|
|
1241
|
+
throw error;
|
|
1242
|
+
}
|
|
1243
|
+
throw new UiWorkerIpcError("launch_record_invalid", "无法安全读取 UI worker launch record。 ");
|
|
1244
|
+
}
|
|
1245
|
+
}
|
|
1246
|
+
|
|
1247
|
+
/**
|
|
1248
|
+
* 将启动 ticket 用 SHA-256 摘要作为 HMAC key identifier。
|
|
1249
|
+
*
|
|
1250
|
+
* @param ticket 随机 launch secret。
|
|
1251
|
+
* @returns 十六进制摘要。
|
|
1252
|
+
*/
|
|
1253
|
+
export function hashUiWorkerTicket(ticket: string): string {
|
|
1254
|
+
return createHash("sha256").update(ticket, "utf8").digest("hex");
|
|
1255
|
+
}
|
|
1256
|
+
|
|
1257
|
+
/**
|
|
1258
|
+
* 生成基于稳定字段序列的 UI worker HMAC proof。
|
|
1259
|
+
*
|
|
1260
|
+
* @param authHash ticket SHA-256。
|
|
1261
|
+
* @param nonce Gateway 随机挑战。
|
|
1262
|
+
* @param registration 当前 worker 注册字段。
|
|
1263
|
+
* @returns Base64URL proof。
|
|
1264
|
+
*/
|
|
1265
|
+
export function createUiWorkerProof(
|
|
1266
|
+
authHash: string,
|
|
1267
|
+
nonce: string,
|
|
1268
|
+
registration: UiWorkerRegistration,
|
|
1269
|
+
): string {
|
|
1270
|
+
const canonical = canonicalJson(publicRegistration(registration));
|
|
1271
|
+
return createHmac("sha256", Buffer.from(authHash, "hex"))
|
|
1272
|
+
.update(nonce, "utf8")
|
|
1273
|
+
.update("\n", "utf8")
|
|
1274
|
+
.update(canonical, "utf8")
|
|
1275
|
+
.digest("base64url");
|
|
1276
|
+
}
|
|
1277
|
+
|
|
1278
|
+
/**
|
|
1279
|
+
* 读取或 create-only 创建跨 Gateway 重启稳定的 UI attach 认证令牌。
|
|
1280
|
+
*
|
|
1281
|
+
* @param managerDirectory Hub 私有数据目录。
|
|
1282
|
+
* @returns 稳定的随机 IPC 令牌。
|
|
1283
|
+
* @throws {UiWorkerIpcError} key 文件权限路径、格式或写入无效时抛出。
|
|
1284
|
+
*/
|
|
1285
|
+
export async function readOrCreateUiWorkerAttachToken(managerDirectory: string): Promise<string> {
|
|
1286
|
+
const keyPath = join(managerDirectory, "ui-attachment.key");
|
|
1287
|
+
const newToken = randomBytes(32).toString("hex");
|
|
1288
|
+
let handle;
|
|
1289
|
+
try {
|
|
1290
|
+
handle = await open(keyPath, "wx", 0o600);
|
|
1291
|
+
await handle.writeFile(`${newToken}\n`, "utf8");
|
|
1292
|
+
await handle.sync();
|
|
1293
|
+
await handle.close();
|
|
1294
|
+
return newToken;
|
|
1295
|
+
} catch (error) {
|
|
1296
|
+
await handle?.close().catch(() => undefined);
|
|
1297
|
+
if (isNodeError(error) && error.code === "EEXIST") {
|
|
1298
|
+
const existingToken = await readUiWorkerAttachToken(managerDirectory);
|
|
1299
|
+
if (existingToken) {
|
|
1300
|
+
return existingToken;
|
|
1301
|
+
}
|
|
1302
|
+
throw new UiWorkerIpcError("handshake_rejected", "UI attach key 文件不可读取。 ");
|
|
1303
|
+
}
|
|
1304
|
+
if (handle) {
|
|
1305
|
+
await unlink(keyPath).catch(() => undefined);
|
|
1306
|
+
}
|
|
1307
|
+
throw new UiWorkerIpcError("handshake_rejected", "无法安全创建 UI attach key。 ");
|
|
1308
|
+
}
|
|
1309
|
+
}
|
|
1310
|
+
|
|
1311
|
+
export async function readUiWorkerAttachToken(managerDirectory: string): Promise<string | undefined> {
|
|
1312
|
+
const keyPath = join(managerDirectory, "ui-attachment.key");
|
|
1313
|
+
let keyInfo;
|
|
1314
|
+
try {
|
|
1315
|
+
keyInfo = await lstat(keyPath);
|
|
1316
|
+
} catch (error) {
|
|
1317
|
+
if (isNodeError(error) && error.code === "ENOENT") {
|
|
1318
|
+
return undefined;
|
|
1319
|
+
}
|
|
1320
|
+
throw new UiWorkerIpcError("handshake_rejected", "UI attach key 文件不可读取。 ");
|
|
1321
|
+
}
|
|
1322
|
+
if (!keyInfo.isFile() || keyInfo.isSymbolicLink()) {
|
|
1323
|
+
throw new UiWorkerIpcError("handshake_rejected", "UI attach key 文件类型不可信。 ");
|
|
1324
|
+
}
|
|
1325
|
+
const token = await readFile(keyPath, "utf8");
|
|
1326
|
+
if (!/^[a-f0-9]{64}\r?\n?$/i.test(token)) {
|
|
1327
|
+
throw new UiWorkerIpcError("handshake_rejected", "UI attach key 文件内容无效。 ");
|
|
1328
|
+
}
|
|
1329
|
+
return token.trim();
|
|
1330
|
+
}
|
|
1331
|
+
|
|
1332
|
+
/**
|
|
1333
|
+
* 计算 stable named pipe 名, 不嵌入用户名或项目路径。
|
|
1334
|
+
*
|
|
1335
|
+
* @param managerDirectory manager 数据目录。
|
|
1336
|
+
* @returns 当前用户配置唯一的 named pipe endpoint。
|
|
1337
|
+
*/
|
|
1338
|
+
export function createStableNamedPipe(managerDirectory: string): string {
|
|
1339
|
+
const normalized = resolve(managerDirectory).toLowerCase();
|
|
1340
|
+
const scope = createHash("sha256").update(normalized).digest("hex").slice(0, 24);
|
|
1341
|
+
return `\\\\.\\pipe\\pi-wechat-session-hub-${scope}`;
|
|
1342
|
+
}
|
|
1343
|
+
|
|
1344
|
+
/**
|
|
1345
|
+
* 解析 launch record 文件内容并检查字段边界。
|
|
1346
|
+
*
|
|
1347
|
+
* @param value JSON data。
|
|
1348
|
+
* @param managerDirectory 当前 manager 数据目录。
|
|
1349
|
+
* @returns 已校验 launch record。
|
|
1350
|
+
*/
|
|
1351
|
+
function parseLaunchRecord(value: unknown, managerDirectory: string): UiWorkerLaunchRecord {
|
|
1352
|
+
if (!isPlainRecord(value)) {
|
|
1353
|
+
throw new UiWorkerIpcError("launch_record_invalid", "UI worker launch record 根节点无效。 ");
|
|
1354
|
+
}
|
|
1355
|
+
const record = value as Record<string, unknown>;
|
|
1356
|
+
const allowedFields = new Set([
|
|
1357
|
+
"schemaVersion",
|
|
1358
|
+
"launchId",
|
|
1359
|
+
"instanceId",
|
|
1360
|
+
"ticket",
|
|
1361
|
+
"mode",
|
|
1362
|
+
"projectAlias",
|
|
1363
|
+
"projectPath",
|
|
1364
|
+
"sessionName",
|
|
1365
|
+
"sessionId",
|
|
1366
|
+
"sessionFile",
|
|
1367
|
+
"managerDirectory",
|
|
1368
|
+
"agentDirectory",
|
|
1369
|
+
"pipeEndpoint",
|
|
1370
|
+
"nodeExecutable",
|
|
1371
|
+
"piCliEntry",
|
|
1372
|
+
"extensionPath",
|
|
1373
|
+
"createdAt",
|
|
1374
|
+
"expiresAt",
|
|
1375
|
+
]);
|
|
1376
|
+
if (
|
|
1377
|
+
Object.keys(record).some((key) => !allowedFields.has(key)) ||
|
|
1378
|
+
record.schemaVersion !== 1 ||
|
|
1379
|
+
!isUuid(record.launchId) ||
|
|
1380
|
+
!isUuid(record.instanceId) ||
|
|
1381
|
+
typeof record.ticket !== "string" || !/^[a-f0-9]{64}$/i.test(record.ticket) ||
|
|
1382
|
+
(record.mode !== "new" && record.mode !== "resume") ||
|
|
1383
|
+
typeof record.projectAlias !== "string" || !/^[a-z0-9][a-z0-9_-]{0,31}$/.test(record.projectAlias) ||
|
|
1384
|
+
typeof record.projectPath !== "string" || !isAbsolute(record.projectPath) ||
|
|
1385
|
+
typeof record.managerDirectory !== "string" || !samePath(record.managerDirectory, managerDirectory) ||
|
|
1386
|
+
typeof record.agentDirectory !== "string" || !isAbsolute(record.agentDirectory) ||
|
|
1387
|
+
typeof record.pipeEndpoint !== "string" ||
|
|
1388
|
+
typeof record.nodeExecutable !== "string" || !isAbsolute(record.nodeExecutable) ||
|
|
1389
|
+
typeof record.piCliEntry !== "string" || !isAbsolute(record.piCliEntry) ||
|
|
1390
|
+
typeof record.extensionPath !== "string" || !isAbsolute(record.extensionPath) ||
|
|
1391
|
+
typeof record.createdAt !== "string" ||
|
|
1392
|
+
!Number.isFinite(Date.parse(record.createdAt)) ||
|
|
1393
|
+
typeof record.expiresAt !== "string" ||
|
|
1394
|
+
!Number.isFinite(Date.parse(record.expiresAt)) ||
|
|
1395
|
+
(record.sessionName !== undefined && (typeof record.sessionName !== "string" || record.sessionName.length > 100)) ||
|
|
1396
|
+
(record.mode === "resume" && (
|
|
1397
|
+
typeof record.sessionId !== "string" || !record.sessionId.trim() ||
|
|
1398
|
+
typeof record.sessionFile !== "string" || !isAbsolute(record.sessionFile)
|
|
1399
|
+
))
|
|
1400
|
+
) {
|
|
1401
|
+
throw new UiWorkerIpcError("launch_record_invalid", "UI worker launch record 字段无效。 ");
|
|
1402
|
+
}
|
|
1403
|
+
return record as unknown as UiWorkerLaunchRecord;
|
|
1404
|
+
}
|
|
1405
|
+
|
|
1406
|
+
/**
|
|
1407
|
+
* 校验内部 launch record 并确保时间窗口有效。
|
|
1408
|
+
*
|
|
1409
|
+
* @param record launch record。
|
|
1410
|
+
* @param managerDirectory 当前 Gateway 数据目录。
|
|
1411
|
+
* @returns 无返回值。
|
|
1412
|
+
* @throws {UiWorkerIpcError} launch record 无效时抛出。
|
|
1413
|
+
*/
|
|
1414
|
+
function assertLaunchRecord(record: UiWorkerLaunchRecord, managerDirectory: string): void {
|
|
1415
|
+
parseLaunchRecord(record, resolve(managerDirectory));
|
|
1416
|
+
if (Date.parse(record.expiresAt) <= Date.now()) {
|
|
1417
|
+
throw new UiWorkerIpcError("launch_record_invalid", "UI worker launch record 已过期。 ");
|
|
1418
|
+
}
|
|
1419
|
+
}
|
|
1420
|
+
|
|
1421
|
+
/**
|
|
1422
|
+
* 校验 UUID 字符串。
|
|
1423
|
+
*
|
|
1424
|
+
* @param value 候选字符串。
|
|
1425
|
+
* @returns UUID 格式有效时返回 true。
|
|
1426
|
+
*/
|
|
1427
|
+
function isUuid(value: unknown): value is string {
|
|
1428
|
+
return typeof value === "string" && /^[a-f0-9]{8}-[a-f0-9]{4}-[1-8][a-f0-9]{3}-[89ab][a-f0-9]{3}-[a-f0-9]{12}$/i.test(value);
|
|
1429
|
+
}
|
|
1430
|
+
|
|
1431
|
+
/**
|
|
1432
|
+
* 对 object key 排序后生成稳定 JSON 文本。
|
|
1433
|
+
*
|
|
1434
|
+
* @param value JSON-compatible value。
|
|
1435
|
+
* @returns 确定性序列化文本。
|
|
1436
|
+
*/
|
|
1437
|
+
function canonicalJson(value: unknown): string {
|
|
1438
|
+
if (Array.isArray(value)) {
|
|
1439
|
+
return `[${value.map((item) => canonicalJson(item)).join(",")}]`;
|
|
1440
|
+
}
|
|
1441
|
+
if (isPlainRecord(value)) {
|
|
1442
|
+
return `{${Object.keys(value).sort().map((key) => `${JSON.stringify(key)}:${canonicalJson(value[key])}`).join(",")}}`;
|
|
1443
|
+
}
|
|
1444
|
+
return JSON.stringify(value);
|
|
1445
|
+
}
|
|
1446
|
+
|
|
1447
|
+
/**
|
|
1448
|
+
* 以常量时间比较两个 Base64URL 字符串。
|
|
1449
|
+
*
|
|
1450
|
+
* @param provided client proof。
|
|
1451
|
+
* @param expected server proof。
|
|
1452
|
+
* @returns 两者相同时返回 true。
|
|
1453
|
+
*/
|
|
1454
|
+
function safeEqualBase64(provided: string, expected: string): boolean {
|
|
1455
|
+
const left = Buffer.from(provided, "base64url");
|
|
1456
|
+
const right = Buffer.from(expected, "base64url");
|
|
1457
|
+
return left.length === right.length && timingSafeEqual(left, right);
|
|
1458
|
+
}
|
|
1459
|
+
|
|
1460
|
+
/**
|
|
1461
|
+
* 比较绝对路径, Windows 平台忽略大小写。
|
|
1462
|
+
*
|
|
1463
|
+
* @param left 路径一。
|
|
1464
|
+
* @param right 路径二。
|
|
1465
|
+
* @returns 规范化路径一致时返回 true。
|
|
1466
|
+
*/
|
|
1467
|
+
function samePath(left: string, right: string): boolean {
|
|
1468
|
+
const leftPath = resolve(left);
|
|
1469
|
+
const rightPath = resolve(right);
|
|
1470
|
+
return process.platform === "win32"
|
|
1471
|
+
? leftPath.toLowerCase() === rightPath.toLowerCase()
|
|
1472
|
+
: leftPath === rightPath;
|
|
1473
|
+
}
|
|
1474
|
+
|
|
1475
|
+
/**
|
|
1476
|
+
* 判断值是否为 Node.js 文件系统错误。
|
|
1477
|
+
*
|
|
1478
|
+
* @param error 待检查值。
|
|
1479
|
+
* @returns 值带有 Node.js 错误代码时返回 true。
|
|
1480
|
+
*/
|
|
1481
|
+
function isNodeError(error: unknown): error is NodeJS.ErrnoException {
|
|
1482
|
+
return error instanceof Error && "code" in error;
|
|
1483
|
+
}
|