@yourstandby/fabric 0.0.0-stage → 0.1.1
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/README.md +24 -2
- package/dist/daemon.js +3797 -0
- package/dist/index.js +3916 -0
- package/package.json +30 -4
- package/src/artifacts.test.ts +148 -0
- package/src/artifacts.ts +247 -0
- package/src/daemon-runner.ts +218 -0
- package/src/daemon.ts +524 -0
- package/src/discovery.ts +332 -0
- package/src/dispatch.test.ts +154 -0
- package/src/dispatch.ts +459 -0
- package/src/dispatcher.test.ts +321 -0
- package/src/dispatcher.ts +794 -0
- package/src/fabric-apply.test.ts +115 -0
- package/src/fabric-apply.ts +137 -0
- package/src/fabric-avatar.test.ts +51 -0
- package/src/fabric-discovery.test.ts +100 -0
- package/src/fabric-history.test.ts +68 -0
- package/src/fabric-keepalive.test.ts +112 -0
- package/src/fabric-notify.test.ts +269 -0
- package/src/fabric-pairing.test.ts +164 -0
- package/src/fabric-runner.test.ts +113 -0
- package/src/fabric-runner.ts +167 -0
- package/src/fabric-score.test.ts +74 -0
- package/src/fabric-server.ts +101 -0
- package/src/fabric-service.test.ts +279 -0
- package/src/fabric-service.ts +745 -0
- package/src/fabric-view.test.ts +118 -0
- package/src/fabric-view.ts +182 -0
- package/src/fabric-worktree.test.ts +139 -0
- package/src/fabric-worktree.ts +232 -0
- package/src/history.ts +127 -0
- package/src/host-load.ts +18 -0
- package/src/index.ts +27 -0
- package/src/pairing.test.ts +212 -0
- package/src/pairing.ts +342 -0
- package/src/peer-store.test.ts +212 -0
- package/src/peer-store.ts +243 -0
- package/src/transport.test.ts +247 -0
- package/src/transport.ts +709 -0
package/src/transport.ts
ADDED
|
@@ -0,0 +1,709 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 跨机字节流:把 Agent Host 的 NDJSON 帧搬到 net.Socket 上(0 新依赖)。
|
|
3
|
+
*
|
|
4
|
+
* 握手(1.5 RTT,X25519 ECDH + 双向 HMAC 挑战):
|
|
5
|
+
* C -> S hello{nodeId, publicKey, nonce, features}
|
|
6
|
+
* S -> C hello_ok{nodeId, publicKey, nonce, mac = HMAC(b2a, clientNonce|serverNodeId), features}
|
|
7
|
+
* C -> S auth{mac = HMAC(a2b, serverNonce|clientNodeId)}
|
|
8
|
+
* S -> C auth_ok{features} // 能力交集
|
|
9
|
+
* 两侧都必须证明自己握有私钥:单边认证等于给了中间人一张入场券。
|
|
10
|
+
*/
|
|
11
|
+
import { randomBytes } from "node:crypto";
|
|
12
|
+
import { connect as netConnect, type Socket } from "node:net";
|
|
13
|
+
import {
|
|
14
|
+
FABRIC_FEATURES,
|
|
15
|
+
FABRIC_PROTOCOL_VERSION,
|
|
16
|
+
checkProtocolVersion,
|
|
17
|
+
type FabricFeature,
|
|
18
|
+
} from "../../../contract/domains/fabric.ts";
|
|
19
|
+
import { negotiateCapabilities } from "../../../contract/protocol.ts";
|
|
20
|
+
import {
|
|
21
|
+
challengeMac,
|
|
22
|
+
deriveSessionKeys,
|
|
23
|
+
deriveSharedSecret,
|
|
24
|
+
nodeIdOf,
|
|
25
|
+
verifyChallengeMac,
|
|
26
|
+
type FabricIdentity,
|
|
27
|
+
} from "./pairing.ts";
|
|
28
|
+
|
|
29
|
+
export const FABRIC_HELLO_TIMEOUT_MS = 5_000;
|
|
30
|
+
export const FABRIC_MAX_FRAME_BYTES = 8 * 1024 * 1024;
|
|
31
|
+
export const FABRIC_CALL_TIMEOUT_MS = 30_000;
|
|
32
|
+
/** 重连退避:500ms 起,翻倍到 10s,永不放弃(只有 stop() 停)。 */
|
|
33
|
+
export const FABRIC_RECONNECT_BASE_MS = 500;
|
|
34
|
+
export const FABRIC_RECONNECT_MAX_MS = 10_000;
|
|
35
|
+
|
|
36
|
+
export class FabricTransportError extends Error {
|
|
37
|
+
code: string;
|
|
38
|
+
constructor(code: string, message: string) {
|
|
39
|
+
super(message);
|
|
40
|
+
this.name = "FabricTransportError";
|
|
41
|
+
this.code = code;
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
export interface FabricLink {
|
|
46
|
+
readonly nodeId: string;
|
|
47
|
+
readonly features: FabricFeature[];
|
|
48
|
+
readonly appVersion: string;
|
|
49
|
+
readonly connected: boolean;
|
|
50
|
+
call(method: string, params?: Record<string, unknown>): Promise<unknown>;
|
|
51
|
+
/** 主动推一个帧(服务端把任务完成事件推给发起方时用)。 */
|
|
52
|
+
send(frame: Record<string, unknown>): void;
|
|
53
|
+
/** 接收对端推来的事件帧(task_done / task_failed),返回取消订阅。 */
|
|
54
|
+
onEvent(handler: (frame: Record<string, unknown>) => void): () => void;
|
|
55
|
+
close(): void;
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
type Frame = Record<string, unknown>;
|
|
59
|
+
|
|
60
|
+
function isFrame(value: unknown): value is Frame {
|
|
61
|
+
return Boolean(value) && typeof value === "object" && !Array.isArray(value);
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
interface Channel {
|
|
65
|
+
write(frame: Frame): void;
|
|
66
|
+
close(): void;
|
|
67
|
+
onClose(callback: (reason: string) => void): void;
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
/** 一行一个 JSON;按字节缓冲,多字节字符跨包不会切坏。 */
|
|
71
|
+
export function createChannel(
|
|
72
|
+
socket: Socket,
|
|
73
|
+
onFrame: (frame: Frame) => void,
|
|
74
|
+
log?: (message: string) => void,
|
|
75
|
+
maxFrameBytes = FABRIC_MAX_FRAME_BYTES,
|
|
76
|
+
): Channel {
|
|
77
|
+
let buffer: Buffer = Buffer.alloc(0);
|
|
78
|
+
let closed = false;
|
|
79
|
+
const closeListeners: ((reason: string) => void)[] = [];
|
|
80
|
+
const die = (reason: string) => {
|
|
81
|
+
if (closed) return;
|
|
82
|
+
closed = true;
|
|
83
|
+
socket.destroy();
|
|
84
|
+
for (const listener of closeListeners) listener(reason);
|
|
85
|
+
};
|
|
86
|
+
socket.on("data", (chunk: Buffer) => {
|
|
87
|
+
if (closed) return;
|
|
88
|
+
buffer = buffer.length === 0 ? chunk : Buffer.concat([buffer, chunk]);
|
|
89
|
+
for (;;) {
|
|
90
|
+
const index = buffer.indexOf(0x0a);
|
|
91
|
+
if (index < 0) {
|
|
92
|
+
if (buffer.length > maxFrameBytes) {
|
|
93
|
+
log?.("fabric frame too large, closing");
|
|
94
|
+
die("frame too large");
|
|
95
|
+
}
|
|
96
|
+
return;
|
|
97
|
+
}
|
|
98
|
+
if (index > maxFrameBytes) {
|
|
99
|
+
die("frame too large");
|
|
100
|
+
return;
|
|
101
|
+
}
|
|
102
|
+
const line = buffer.subarray(0, index).toString("utf8");
|
|
103
|
+
buffer = buffer.subarray(index + 1);
|
|
104
|
+
if (!line.trim()) continue;
|
|
105
|
+
let parsed: unknown;
|
|
106
|
+
try {
|
|
107
|
+
parsed = JSON.parse(line) as unknown;
|
|
108
|
+
} catch {
|
|
109
|
+
continue;
|
|
110
|
+
}
|
|
111
|
+
if (isFrame(parsed)) onFrame(parsed);
|
|
112
|
+
}
|
|
113
|
+
});
|
|
114
|
+
socket.on("close", () => die("socket closed"));
|
|
115
|
+
socket.on("error", (error) => die(error.message));
|
|
116
|
+
return {
|
|
117
|
+
write(frame) {
|
|
118
|
+
if (closed) return;
|
|
119
|
+
socket.write(`${JSON.stringify(frame)}\n`);
|
|
120
|
+
},
|
|
121
|
+
close() {
|
|
122
|
+
die("closed locally");
|
|
123
|
+
},
|
|
124
|
+
onClose(callback) {
|
|
125
|
+
if (closed) {
|
|
126
|
+
callback("already closed");
|
|
127
|
+
return;
|
|
128
|
+
}
|
|
129
|
+
closeListeners.push(callback);
|
|
130
|
+
},
|
|
131
|
+
};
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
function nonceOf(frame: Frame): Buffer {
|
|
135
|
+
const nonce = typeof frame.nonce === "string" ? Buffer.from(frame.nonce, "base64") : Buffer.alloc(0);
|
|
136
|
+
if (nonce.length !== 32) throw new FabricTransportError("E_PROTOCOL", "bad nonce");
|
|
137
|
+
return nonce;
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
function featuresOf(frame: Frame): string[] {
|
|
141
|
+
return Array.isArray(frame.features)
|
|
142
|
+
? frame.features.filter((item): item is string => typeof item === "string")
|
|
143
|
+
: [];
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
/**
|
|
147
|
+
* 一条已连通的链路的全部运行时状态:握手等待队列、请求表、入站调用处理。
|
|
148
|
+
*
|
|
149
|
+
* 握手和正常请求共用同一个 onFrame 入口——否则握手期间到达的帧会丢,
|
|
150
|
+
* 表现就是「连上了但偶尔超时」这种最难查的毛病。
|
|
151
|
+
*/
|
|
152
|
+
class LinkCore {
|
|
153
|
+
readonly channel: Channel;
|
|
154
|
+
readonly pending = new Map<string, { resolve: (value: unknown) => void; reject: (error: Error) => void; timer: NodeJS.Timeout }>();
|
|
155
|
+
private inbox: Frame[] = [];
|
|
156
|
+
private waiters: ((frame: Frame) => void)[] = [];
|
|
157
|
+
private closeHandlers: ((reason: string) => void)[] = [];
|
|
158
|
+
private seq = 0;
|
|
159
|
+
private readonly eventHandlers = new Set<(frame: Record<string, unknown>) => void>();
|
|
160
|
+
closed = false;
|
|
161
|
+
nodeId = "";
|
|
162
|
+
features: FabricFeature[] = [];
|
|
163
|
+
appVersion = "";
|
|
164
|
+
|
|
165
|
+
private readonly onInboundCall: (method: string, params: Record<string, unknown>) => Promise<unknown>;
|
|
166
|
+
|
|
167
|
+
// 注意:不用参数属性(constructor(private x))——node 的类型擦除模式不支持。
|
|
168
|
+
constructor(
|
|
169
|
+
socket: Socket,
|
|
170
|
+
onInboundCall: (method: string, params: Record<string, unknown>) => Promise<unknown>,
|
|
171
|
+
log?: (message: string) => void,
|
|
172
|
+
) {
|
|
173
|
+
this.onInboundCall = onInboundCall;
|
|
174
|
+
this.channel = createChannel(socket, (frame) => void this.dispatch(frame), log);
|
|
175
|
+
this.channel.onClose((reason) => {
|
|
176
|
+
this.closed = true;
|
|
177
|
+
for (const [, waiter] of this.pending) {
|
|
178
|
+
clearTimeout(waiter.timer);
|
|
179
|
+
waiter.reject(new FabricTransportError("E_PEER_OFFLINE", `link lost: ${reason}`));
|
|
180
|
+
}
|
|
181
|
+
this.pending.clear();
|
|
182
|
+
for (const handler of this.closeHandlers) handler(reason);
|
|
183
|
+
});
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
onClose(callback: (reason: string) => void): void {
|
|
187
|
+
this.closeHandlers.push(callback);
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
private async dispatch(frame: Frame): Promise<void> {
|
|
191
|
+
if (frame.type === "call_result") {
|
|
192
|
+
const id = typeof frame.id === "string" ? frame.id : "";
|
|
193
|
+
const waiter = this.pending.get(id);
|
|
194
|
+
if (!waiter) return;
|
|
195
|
+
this.pending.delete(id);
|
|
196
|
+
clearTimeout(waiter.timer);
|
|
197
|
+
if (frame.ok === true) {
|
|
198
|
+
waiter.resolve(frame.result ?? null);
|
|
199
|
+
} else {
|
|
200
|
+
const error = isFrame(frame.error) ? frame.error : {};
|
|
201
|
+
waiter.reject(
|
|
202
|
+
new FabricTransportError(
|
|
203
|
+
typeof error.code === "string" ? error.code : "E_CALL_FAILED",
|
|
204
|
+
typeof error.message === "string" ? error.message : "call failed",
|
|
205
|
+
),
|
|
206
|
+
);
|
|
207
|
+
}
|
|
208
|
+
return;
|
|
209
|
+
}
|
|
210
|
+
if (frame.type === "call") {
|
|
211
|
+
const id = typeof frame.id === "string" ? frame.id : "";
|
|
212
|
+
const method = typeof frame.method === "string" ? frame.method : "";
|
|
213
|
+
const params = isFrame(frame.params) ? frame.params : {};
|
|
214
|
+
try {
|
|
215
|
+
const result = await this.onInboundCall(method, params);
|
|
216
|
+
this.channel.write({ type: "call_result", id, ok: true, result: result ?? null });
|
|
217
|
+
} catch (error) {
|
|
218
|
+
this.channel.write({
|
|
219
|
+
type: "call_result",
|
|
220
|
+
id,
|
|
221
|
+
ok: false,
|
|
222
|
+
error: {
|
|
223
|
+
code: error instanceof FabricTransportError ? error.code : "E_CALL_FAILED",
|
|
224
|
+
message: error instanceof Error ? error.message : String(error),
|
|
225
|
+
},
|
|
226
|
+
});
|
|
227
|
+
}
|
|
228
|
+
return;
|
|
229
|
+
}
|
|
230
|
+
if (frame.type === "ping") {
|
|
231
|
+
this.channel.write({ type: "pong", nonce: frame.nonce });
|
|
232
|
+
return;
|
|
233
|
+
}
|
|
234
|
+
if (frame.type === "event") {
|
|
235
|
+
// 事件帧不参与握手等待队列:它是任务级通知,跟握手无关。
|
|
236
|
+
const payload = isFrame(frame.event) ? frame.event : frame;
|
|
237
|
+
for (const handler of this.eventHandlers) handler(payload);
|
|
238
|
+
return;
|
|
239
|
+
}
|
|
240
|
+
const waiter = this.waiters.shift();
|
|
241
|
+
if (waiter) {
|
|
242
|
+
waiter(frame);
|
|
243
|
+
return;
|
|
244
|
+
}
|
|
245
|
+
this.inbox.push(frame);
|
|
246
|
+
}
|
|
247
|
+
|
|
248
|
+
next(predicate: (frame: Frame) => boolean, timeoutMs: number, label: string): Promise<Frame> {
|
|
249
|
+
for (let index = 0; index < this.inbox.length; index += 1) {
|
|
250
|
+
if (predicate(this.inbox[index])) return Promise.resolve(this.inbox.splice(index, 1)[0]);
|
|
251
|
+
}
|
|
252
|
+
return new Promise<Frame>((resolve, reject) => {
|
|
253
|
+
const timer = setTimeout(() => {
|
|
254
|
+
const position = this.waiters.indexOf(waiter);
|
|
255
|
+
if (position >= 0) this.waiters.splice(position, 1);
|
|
256
|
+
reject(new FabricTransportError("E_HELLO_TIMEOUT", `timed out waiting for ${label}`));
|
|
257
|
+
}, timeoutMs);
|
|
258
|
+
timer.unref?.();
|
|
259
|
+
const waiter = (frame: Frame) => {
|
|
260
|
+
if (!predicate(frame)) {
|
|
261
|
+
this.inbox.push(frame);
|
|
262
|
+
this.waiters.push(waiter);
|
|
263
|
+
return;
|
|
264
|
+
}
|
|
265
|
+
clearTimeout(timer);
|
|
266
|
+
resolve(frame);
|
|
267
|
+
};
|
|
268
|
+
this.waiters.push(waiter);
|
|
269
|
+
});
|
|
270
|
+
}
|
|
271
|
+
|
|
272
|
+
call(method: string, params: Record<string, unknown>, timeoutMs: number): Promise<unknown> {
|
|
273
|
+
if (this.closed) {
|
|
274
|
+
return Promise.reject(new FabricTransportError("E_PEER_OFFLINE", "link closed"));
|
|
275
|
+
}
|
|
276
|
+
this.seq += 1;
|
|
277
|
+
const id = String(this.seq);
|
|
278
|
+
return new Promise<unknown>((resolve, reject) => {
|
|
279
|
+
const timer = setTimeout(() => {
|
|
280
|
+
this.pending.delete(id);
|
|
281
|
+
reject(new FabricTransportError("E_CALL_TIMEOUT", `call ${method} timed out`));
|
|
282
|
+
}, timeoutMs);
|
|
283
|
+
timer.unref?.();
|
|
284
|
+
this.pending.set(id, { resolve, reject, timer });
|
|
285
|
+
this.channel.write({ type: "call", id, method, params });
|
|
286
|
+
});
|
|
287
|
+
}
|
|
288
|
+
|
|
289
|
+
link(): FabricLink {
|
|
290
|
+
// eslint 不允许 this 别名;getter 需要闭包内稳定引用,故局部常量 + 显式豁免。
|
|
291
|
+
// eslint-disable-next-line @typescript-eslint/no-this-alias
|
|
292
|
+
const self = this;
|
|
293
|
+
return {
|
|
294
|
+
get nodeId() {
|
|
295
|
+
return self.nodeId;
|
|
296
|
+
},
|
|
297
|
+
get features() {
|
|
298
|
+
return self.features;
|
|
299
|
+
},
|
|
300
|
+
get appVersion() {
|
|
301
|
+
return self.appVersion;
|
|
302
|
+
},
|
|
303
|
+
get connected() {
|
|
304
|
+
return !self.closed;
|
|
305
|
+
},
|
|
306
|
+
call: (method, params = {}) => self.call(method, params, FABRIC_CALL_TIMEOUT_MS),
|
|
307
|
+
send: (frame) => self.channel.write(frame),
|
|
308
|
+
onEvent: (handler) => {
|
|
309
|
+
self.eventHandlers.add(handler);
|
|
310
|
+
return () => self.eventHandlers.delete(handler);
|
|
311
|
+
},
|
|
312
|
+
close: () => self.channel.close(),
|
|
313
|
+
};
|
|
314
|
+
}
|
|
315
|
+
}
|
|
316
|
+
|
|
317
|
+
export interface FabricCaller {
|
|
318
|
+
/** 握手阶段认证出来的对端 nodeId——方法分发必须用它,不能信 params 里的自报身份。 */
|
|
319
|
+
nodeId: string;
|
|
320
|
+
/** 已配对的对端公钥(握手时拿到,可用于配对时落盘)。 */
|
|
321
|
+
publicKey: string;
|
|
322
|
+
/** 未配对的通知请求:这种连接只允许 pair.request 一个方法。 */
|
|
323
|
+
restricted: boolean;
|
|
324
|
+
/** 对端 TCP 地址与端口(配对时要记下来,之后主动连回去)。 */
|
|
325
|
+
address: string;
|
|
326
|
+
port: number;
|
|
327
|
+
}
|
|
328
|
+
|
|
329
|
+
/** 未配对连接上唯一被允许的方法:对方发起的配对请求。 */
|
|
330
|
+
export const FABRIC_PAIR_METHOD = "pair.request";
|
|
331
|
+
|
|
332
|
+
export interface PairRequestInfo {
|
|
333
|
+
nodeId: string;
|
|
334
|
+
publicKey: string;
|
|
335
|
+
name: string;
|
|
336
|
+
address: string;
|
|
337
|
+
/** 对端握手时的源端口(临时端口,通常不是监听端口)。 */
|
|
338
|
+
port: number;
|
|
339
|
+
/** 对端自报的监听端口:源端口不能用来回连。 */
|
|
340
|
+
claimedPort: number;
|
|
341
|
+
}
|
|
342
|
+
|
|
343
|
+
export interface AcceptLinkOptions {
|
|
344
|
+
socket: Socket;
|
|
345
|
+
identity: FabricIdentity;
|
|
346
|
+
/** 只有已配对的 nodeId 才应答;未知对端一律 hello_error 并断开。 */
|
|
347
|
+
isPaired: (nodeId: string) => boolean;
|
|
348
|
+
/**
|
|
349
|
+
* 未配对对端的配对请求入口。给了它就允许「受限会话」——只接受 pair.request,
|
|
350
|
+
* 其余方法一律 E_UNAUTHORIZED;不给就与以前一样在握手阶段直接拒绝。
|
|
351
|
+
*/
|
|
352
|
+
onPairRequest?: (info: PairRequestInfo) => Promise<unknown>;
|
|
353
|
+
/**
|
|
354
|
+
* 受限会话上额外放行的方法(目前只有 peer.status)。
|
|
355
|
+
* 发起方靠它区分「还挂着 / 被拒了 / 已成」,否则只能干等 TTL 过期。
|
|
356
|
+
*/
|
|
357
|
+
onRestrictedCall?: (
|
|
358
|
+
method: string,
|
|
359
|
+
params: Record<string, unknown>,
|
|
360
|
+
caller: FabricCaller,
|
|
361
|
+
) => Promise<unknown>;
|
|
362
|
+
onCall: (method: string, params: Record<string, unknown>, caller: FabricCaller) => Promise<unknown>;
|
|
363
|
+
appVersion?: string;
|
|
364
|
+
log?: (message: string) => void;
|
|
365
|
+
}
|
|
366
|
+
|
|
367
|
+
/** 服务端:接受入站连接并完成握手。 */
|
|
368
|
+
export async function acceptFabricLink(options: AcceptLinkOptions): Promise<FabricLink> {
|
|
369
|
+
const caller: FabricCaller = {
|
|
370
|
+
nodeId: "",
|
|
371
|
+
publicKey: "",
|
|
372
|
+
restricted: false,
|
|
373
|
+
address: options.socket.remoteAddress ?? "",
|
|
374
|
+
port: options.socket.remotePort ?? 0,
|
|
375
|
+
};
|
|
376
|
+
const core = new LinkCore(
|
|
377
|
+
options.socket,
|
|
378
|
+
(method, params) => {
|
|
379
|
+
if (caller.restricted) {
|
|
380
|
+
if (method === "peer.status" && options.onRestrictedCall) {
|
|
381
|
+
return options.onRestrictedCall(method, params, caller);
|
|
382
|
+
}
|
|
383
|
+
if (method !== FABRIC_PAIR_METHOD) {
|
|
384
|
+
throw new FabricTransportError("E_UNAUTHORIZED", "only pair.request is allowed before pairing");
|
|
385
|
+
}
|
|
386
|
+
if (!options.onPairRequest) {
|
|
387
|
+
throw new FabricTransportError("E_UNAUTHORIZED", "pairing requests are disabled");
|
|
388
|
+
}
|
|
389
|
+
return options.onPairRequest({
|
|
390
|
+
nodeId: caller.nodeId,
|
|
391
|
+
publicKey: caller.publicKey,
|
|
392
|
+
name: typeof params.name === "string" ? params.name.slice(0, 60) : "",
|
|
393
|
+
address: caller.address,
|
|
394
|
+
port: caller.port,
|
|
395
|
+
claimedPort:
|
|
396
|
+
typeof params.port === "number" && Number.isInteger(params.port) ? params.port : 0,
|
|
397
|
+
});
|
|
398
|
+
}
|
|
399
|
+
return options.onCall(method, params, caller);
|
|
400
|
+
},
|
|
401
|
+
options.log,
|
|
402
|
+
);
|
|
403
|
+
try {
|
|
404
|
+
const hello = await core.next((frame) => frame.type === "hello", FABRIC_HELLO_TIMEOUT_MS, "hello");
|
|
405
|
+
const remoteNodeId = typeof hello.nodeId === "string" ? hello.nodeId : "";
|
|
406
|
+
const remotePublicKey = typeof hello.publicKey === "string" ? hello.publicKey : "";
|
|
407
|
+
if (!/^[0-9a-f]{16}$/.test(remoteNodeId) || nodeIdOf(remotePublicKey) !== remoteNodeId) {
|
|
408
|
+
core.channel.write({ type: "hello_error", code: "E_PROTOCOL", message: "nodeId does not match public key" });
|
|
409
|
+
core.channel.close();
|
|
410
|
+
throw new FabricTransportError("E_PROTOCOL", "nodeId does not match public key");
|
|
411
|
+
}
|
|
412
|
+
// 先看协议版本,再看配对:版本不合时「没配对」是误导性的结论。
|
|
413
|
+
const protocol = checkProtocolVersion(hello.protocolVersion);
|
|
414
|
+
if (!protocol.ok) {
|
|
415
|
+
core.channel.write({ type: "hello_error", code: "E_PROTOCOL_VERSION", message: protocol.reason });
|
|
416
|
+
core.channel.close();
|
|
417
|
+
throw new FabricTransportError("E_PROTOCOL_VERSION", protocol.reason);
|
|
418
|
+
}
|
|
419
|
+
const paired = options.isPaired(remoteNodeId);
|
|
420
|
+
if (!paired && !options.onPairRequest) {
|
|
421
|
+
core.channel.write({ type: "hello_error", code: "E_PEER_UNKNOWN", message: "peer is not paired" });
|
|
422
|
+
core.channel.close();
|
|
423
|
+
throw new FabricTransportError("E_PEER_UNKNOWN", "peer is not paired");
|
|
424
|
+
}
|
|
425
|
+
const clientNonce = nonceOf(hello);
|
|
426
|
+
const secret = deriveSharedSecret(options.identity, remotePublicKey);
|
|
427
|
+
const keys = deriveSessionKeys(secret, remoteNodeId, options.identity.nodeId);
|
|
428
|
+
const serverNonce = randomBytes(32);
|
|
429
|
+
core.channel.write({
|
|
430
|
+
type: "hello_ok",
|
|
431
|
+
nodeId: options.identity.nodeId,
|
|
432
|
+
publicKey: options.identity.publicKey,
|
|
433
|
+
nonce: serverNonce.toString("base64"),
|
|
434
|
+
mac: challengeMac(keys.bToA, clientNonce, options.identity.nodeId),
|
|
435
|
+
protocolVersion: FABRIC_PROTOCOL_VERSION,
|
|
436
|
+
appVersion: options.appVersion ?? "",
|
|
437
|
+
features: FABRIC_FEATURES,
|
|
438
|
+
});
|
|
439
|
+
const auth = await core.next((frame) => frame.type === "auth", FABRIC_HELLO_TIMEOUT_MS, "auth");
|
|
440
|
+
const mac = typeof auth.mac === "string" ? auth.mac : "";
|
|
441
|
+
if (!verifyChallengeMac(keys.aToB, serverNonce, remoteNodeId, mac)) {
|
|
442
|
+
core.channel.write({ type: "hello_error", code: "E_UNAUTHORIZED", message: "bad challenge response" });
|
|
443
|
+
core.channel.close();
|
|
444
|
+
throw new FabricTransportError("E_UNAUTHORIZED", "bad challenge response");
|
|
445
|
+
}
|
|
446
|
+
caller.nodeId = remoteNodeId;
|
|
447
|
+
caller.publicKey = remotePublicKey;
|
|
448
|
+
caller.restricted = !paired;
|
|
449
|
+
core.nodeId = remoteNodeId;
|
|
450
|
+
core.features = negotiateCapabilities(featuresOf(hello), FABRIC_FEATURES) as FabricFeature[];
|
|
451
|
+
core.appVersion = typeof hello.appVersion === "string" ? hello.appVersion : "";
|
|
452
|
+
core.channel.write({ type: "auth_ok", features: core.features });
|
|
453
|
+
return core.link();
|
|
454
|
+
} catch (error) {
|
|
455
|
+
core.channel.close();
|
|
456
|
+
throw error;
|
|
457
|
+
}
|
|
458
|
+
}
|
|
459
|
+
|
|
460
|
+
export interface DialLinkOptions {
|
|
461
|
+
identity: FabricIdentity;
|
|
462
|
+
/** nodeId 可选:配对时还不知道对方是谁,拿到就信、拿到就记。 */
|
|
463
|
+
peer: { nodeId?: string; address: string; port: number };
|
|
464
|
+
appVersion?: string;
|
|
465
|
+
timeoutMs?: number;
|
|
466
|
+
log?: (message: string) => void;
|
|
467
|
+
}
|
|
468
|
+
|
|
469
|
+
/** 客户端:连上去并完成握手,双向证明身份。 */
|
|
470
|
+
export async function dialFabricLink(options: DialLinkOptions): Promise<FabricLink> {
|
|
471
|
+
const timeoutMs = options.timeoutMs ?? FABRIC_HELLO_TIMEOUT_MS;
|
|
472
|
+
const socket = netConnect({ host: options.peer.address, port: options.peer.port });
|
|
473
|
+
const core = new LinkCore(socket, async () => {
|
|
474
|
+
throw new FabricTransportError("E_UNSUPPORTED", "this side does not accept inbound calls");
|
|
475
|
+
}, options.log);
|
|
476
|
+
await new Promise<void>((resolve, reject) => {
|
|
477
|
+
const timer = setTimeout(() => {
|
|
478
|
+
socket.destroy();
|
|
479
|
+
reject(new FabricTransportError("E_PEER_OFFLINE", "connect timeout"));
|
|
480
|
+
}, timeoutMs);
|
|
481
|
+
timer.unref?.();
|
|
482
|
+
socket.once("connect", () => {
|
|
483
|
+
clearTimeout(timer);
|
|
484
|
+
resolve();
|
|
485
|
+
});
|
|
486
|
+
socket.once("error", (error) => {
|
|
487
|
+
clearTimeout(timer);
|
|
488
|
+
reject(new FabricTransportError("E_PEER_OFFLINE", error.message));
|
|
489
|
+
});
|
|
490
|
+
});
|
|
491
|
+
try {
|
|
492
|
+
const clientNonce = randomBytes(32);
|
|
493
|
+
core.channel.write({
|
|
494
|
+
type: "hello",
|
|
495
|
+
nodeId: options.identity.nodeId,
|
|
496
|
+
publicKey: options.identity.publicKey,
|
|
497
|
+
nonce: clientNonce.toString("base64"),
|
|
498
|
+
protocolVersion: FABRIC_PROTOCOL_VERSION,
|
|
499
|
+
appVersion: options.appVersion ?? "",
|
|
500
|
+
features: FABRIC_FEATURES,
|
|
501
|
+
});
|
|
502
|
+
const reply = await core.next(
|
|
503
|
+
(frame) => frame.type === "hello_ok" || frame.type === "hello_error",
|
|
504
|
+
timeoutMs,
|
|
505
|
+
"hello_ok",
|
|
506
|
+
);
|
|
507
|
+
if (reply.type === "hello_error") {
|
|
508
|
+
throw new FabricTransportError(
|
|
509
|
+
typeof reply.code === "string" ? reply.code : "E_PROTOCOL",
|
|
510
|
+
typeof reply.message === "string" ? reply.message : "handshake rejected",
|
|
511
|
+
);
|
|
512
|
+
}
|
|
513
|
+
const serverNodeId = typeof reply.nodeId === "string" ? reply.nodeId : "";
|
|
514
|
+
const serverPublicKey = typeof reply.publicKey === "string" ? reply.publicKey : "";
|
|
515
|
+
if (nodeIdOf(serverPublicKey) !== serverNodeId) {
|
|
516
|
+
throw new FabricTransportError("E_PEER_MISMATCH", "server public key does not match its nodeId");
|
|
517
|
+
}
|
|
518
|
+
if (options.peer.nodeId && serverNodeId !== options.peer.nodeId) {
|
|
519
|
+
throw new FabricTransportError("E_PEER_MISMATCH", "server identity does not match the paired peer");
|
|
520
|
+
}
|
|
521
|
+
const protocol = checkProtocolVersion(reply.protocolVersion);
|
|
522
|
+
if (!protocol.ok) {
|
|
523
|
+
throw new FabricTransportError("E_PROTOCOL_VERSION", protocol.reason);
|
|
524
|
+
}
|
|
525
|
+
const serverNonce = nonceOf(reply);
|
|
526
|
+
const secret = deriveSharedSecret(options.identity, serverPublicKey);
|
|
527
|
+
const keys = deriveSessionKeys(secret, options.identity.nodeId, serverNodeId);
|
|
528
|
+
const mac = typeof reply.mac === "string" ? reply.mac : "";
|
|
529
|
+
if (!verifyChallengeMac(keys.bToA, clientNonce, serverNodeId, mac)) {
|
|
530
|
+
throw new FabricTransportError("E_PEER_MISMATCH", "server failed the challenge");
|
|
531
|
+
}
|
|
532
|
+
core.channel.write({ type: "auth", mac: challengeMac(keys.aToB, serverNonce, options.identity.nodeId) });
|
|
533
|
+
const ok = await core.next((frame) => frame.type === "auth_ok", timeoutMs, "auth_ok");
|
|
534
|
+
core.nodeId = serverNodeId;
|
|
535
|
+
core.features = negotiateCapabilities(featuresOf(ok), FABRIC_FEATURES) as FabricFeature[];
|
|
536
|
+
core.appVersion = typeof reply.appVersion === "string" ? reply.appVersion : "";
|
|
537
|
+
return core.link();
|
|
538
|
+
} catch (error) {
|
|
539
|
+
core.channel.close();
|
|
540
|
+
throw error;
|
|
541
|
+
}
|
|
542
|
+
}
|
|
543
|
+
|
|
544
|
+
/**
|
|
545
|
+
* 配对请求(未配对连接):握手成功后只调 pair.request 一个方法,然后就断开。
|
|
546
|
+
* 返回握手时拿到的对端身份 + 是否已被接受(对端用户点了允许才会成立)。
|
|
547
|
+
*/
|
|
548
|
+
export async function requestPairing(options: {
|
|
549
|
+
identity: FabricIdentity;
|
|
550
|
+
address: string;
|
|
551
|
+
port: number;
|
|
552
|
+
name: string;
|
|
553
|
+
/** 本机监听端口:对端拿它回连(源端口是临时的,回连会失败)。 */
|
|
554
|
+
listenPort: number;
|
|
555
|
+
timeoutMs?: number;
|
|
556
|
+
log?: (message: string) => void;
|
|
557
|
+
}): Promise<{ nodeId: string; publicKey: string; accepted: boolean }> {
|
|
558
|
+
const link = await dialFabricLink({
|
|
559
|
+
identity: options.identity,
|
|
560
|
+
peer: { address: options.address, port: options.port },
|
|
561
|
+
timeoutMs: options.timeoutMs,
|
|
562
|
+
log: options.log,
|
|
563
|
+
});
|
|
564
|
+
try {
|
|
565
|
+
const reply = (await link.call(FABRIC_PAIR_METHOD, {
|
|
566
|
+
name: options.name,
|
|
567
|
+
port: options.listenPort,
|
|
568
|
+
})) as Record<string, unknown>;
|
|
569
|
+
return {
|
|
570
|
+
nodeId: link.nodeId,
|
|
571
|
+
publicKey: reply.publicKey && typeof reply.publicKey === "string" ? reply.publicKey : "",
|
|
572
|
+
accepted: reply.pending === true,
|
|
573
|
+
};
|
|
574
|
+
} finally {
|
|
575
|
+
link.close();
|
|
576
|
+
}
|
|
577
|
+
}
|
|
578
|
+
|
|
579
|
+
export type FabricConnState = "idle" | "online" | "reconnecting" | "manual-off";
|
|
580
|
+
|
|
581
|
+
export interface FabricPeerConnectionOptions {
|
|
582
|
+
identity: FabricIdentity;
|
|
583
|
+
peer: { nodeId: string; address: string; port: number };
|
|
584
|
+
appVersion?: string;
|
|
585
|
+
onCall?: (method: string, params: Record<string, unknown>) => Promise<unknown>;
|
|
586
|
+
log?: (message: string) => void;
|
|
587
|
+
baseMs?: number;
|
|
588
|
+
maxMs?: number;
|
|
589
|
+
}
|
|
590
|
+
|
|
591
|
+
/**
|
|
592
|
+
* 一台已配对机器的长连接:断线自动重连(指数退避,永不放弃),
|
|
593
|
+
* 只有 stop() 才停止——这就是「不手动取消就一直连着」的落点。
|
|
594
|
+
*/
|
|
595
|
+
export class FabricPeerConnection {
|
|
596
|
+
state: FabricConnState = "idle";
|
|
597
|
+
private link: FabricLink | null = null;
|
|
598
|
+
private stopped = true;
|
|
599
|
+
private timer: NodeJS.Timeout | null = null;
|
|
600
|
+
private attempts = 0;
|
|
601
|
+
private generation = 0;
|
|
602
|
+
private readonly listeners = new Set<(state: FabricConnState) => void>();
|
|
603
|
+
private readonly eventListeners = new Set<(frame: Record<string, unknown>) => void>();
|
|
604
|
+
private unsubscribeEvents: (() => void) | null = null;
|
|
605
|
+
|
|
606
|
+
private readonly options: FabricPeerConnectionOptions;
|
|
607
|
+
|
|
608
|
+
constructor(options: FabricPeerConnectionOptions) {
|
|
609
|
+
this.options = options;
|
|
610
|
+
}
|
|
611
|
+
|
|
612
|
+
onStateChange(listener: (state: FabricConnState) => void): () => void {
|
|
613
|
+
this.listeners.add(listener);
|
|
614
|
+
return () => this.listeners.delete(listener);
|
|
615
|
+
}
|
|
616
|
+
|
|
617
|
+
/** 订阅对端推来的事件:重连之后自动重新订阅(否则第一次断线就永久收不到通知)。 */
|
|
618
|
+
onEvent(listener: (frame: Record<string, unknown>) => void): () => void {
|
|
619
|
+
this.eventListeners.add(listener);
|
|
620
|
+
return () => this.eventListeners.delete(listener);
|
|
621
|
+
}
|
|
622
|
+
|
|
623
|
+
private setState(state: FabricConnState): void {
|
|
624
|
+
if (this.state === state) return;
|
|
625
|
+
this.state = state;
|
|
626
|
+
for (const listener of this.listeners) listener(state);
|
|
627
|
+
}
|
|
628
|
+
|
|
629
|
+
start(): void {
|
|
630
|
+
if (!this.stopped) return;
|
|
631
|
+
this.stopped = false;
|
|
632
|
+
this.attempts = 0;
|
|
633
|
+
void this.connect();
|
|
634
|
+
}
|
|
635
|
+
|
|
636
|
+
stop(): void {
|
|
637
|
+
this.stopped = true;
|
|
638
|
+
this.setState("manual-off");
|
|
639
|
+
if (this.timer) {
|
|
640
|
+
clearTimeout(this.timer);
|
|
641
|
+
this.timer = null;
|
|
642
|
+
}
|
|
643
|
+
this.link?.close();
|
|
644
|
+
this.link = null;
|
|
645
|
+
}
|
|
646
|
+
|
|
647
|
+
current(): FabricLink | null {
|
|
648
|
+
return this.link && this.link.connected ? this.link : null;
|
|
649
|
+
}
|
|
650
|
+
|
|
651
|
+
async call(method: string, params: Record<string, unknown> = {}): Promise<unknown> {
|
|
652
|
+
const link = this.current();
|
|
653
|
+
if (!link) throw new FabricTransportError("E_PEER_OFFLINE", "peer is not connected");
|
|
654
|
+
return link.call(method, params);
|
|
655
|
+
}
|
|
656
|
+
|
|
657
|
+
private async connect(): Promise<void> {
|
|
658
|
+
if (this.stopped) return;
|
|
659
|
+
const generation = ++this.generation;
|
|
660
|
+
try {
|
|
661
|
+
const link = await dialFabricLink({
|
|
662
|
+
identity: this.options.identity,
|
|
663
|
+
peer: this.options.peer,
|
|
664
|
+
appVersion: this.options.appVersion,
|
|
665
|
+
log: this.options.log,
|
|
666
|
+
});
|
|
667
|
+
if (this.stopped || generation !== this.generation) {
|
|
668
|
+
link.close();
|
|
669
|
+
return;
|
|
670
|
+
}
|
|
671
|
+
this.link = link;
|
|
672
|
+
this.attempts = 0;
|
|
673
|
+
this.setState("online");
|
|
674
|
+
this.unsubscribeEvents?.();
|
|
675
|
+
this.unsubscribeEvents = link.onEvent((frame) => {
|
|
676
|
+
for (const listener of this.eventListeners) listener(frame);
|
|
677
|
+
});
|
|
678
|
+
this.options.log?.(`fabric link up: ${this.options.peer.nodeId}`);
|
|
679
|
+
// 链路断开时不立刻抛弃,交给退避重连决定节奏。
|
|
680
|
+
const check = setInterval(() => {
|
|
681
|
+
if (!link.connected) {
|
|
682
|
+
clearInterval(check);
|
|
683
|
+
if (this.link === link) this.link = null;
|
|
684
|
+
if (!this.stopped) this.schedule();
|
|
685
|
+
}
|
|
686
|
+
}, 500);
|
|
687
|
+
check.unref?.();
|
|
688
|
+
} catch (error) {
|
|
689
|
+
this.options.log?.(
|
|
690
|
+
`fabric link failed: ${error instanceof Error ? error.message : String(error)}`,
|
|
691
|
+
);
|
|
692
|
+
if (!this.stopped && generation === this.generation) this.schedule();
|
|
693
|
+
}
|
|
694
|
+
}
|
|
695
|
+
|
|
696
|
+
private schedule(): void {
|
|
697
|
+
if (this.stopped || this.timer) return;
|
|
698
|
+
this.setState("reconnecting");
|
|
699
|
+
const base = this.options.baseMs ?? FABRIC_RECONNECT_BASE_MS;
|
|
700
|
+
const max = this.options.maxMs ?? FABRIC_RECONNECT_MAX_MS;
|
|
701
|
+
const delay = Math.min(max, base * 2 ** this.attempts);
|
|
702
|
+
this.attempts += 1;
|
|
703
|
+
this.timer = setTimeout(() => {
|
|
704
|
+
this.timer = null;
|
|
705
|
+
void this.connect();
|
|
706
|
+
}, delay);
|
|
707
|
+
this.timer.unref?.();
|
|
708
|
+
}
|
|
709
|
+
}
|