@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/pairing.ts
ADDED
|
@@ -0,0 +1,342 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 配对与身份:X25519 身份密钥 + ECDH 派生会话密钥 + 6 位 SAS 人工比对。
|
|
3
|
+
*
|
|
4
|
+
* 为什么不是「共享密钥配对码」:
|
|
5
|
+
* ECDH 能保证密钥从不经过网络,配对码一旦被看到就等于永久身份泄露。
|
|
6
|
+
* 这里落盘的只有公钥/私钥(私钥单独 identity.json,0600),peer 记录里没有密钥。
|
|
7
|
+
*
|
|
8
|
+
* 配对流程(1 RTT + 用户看一眼):
|
|
9
|
+
* 双方交换 nodeId + 公钥 → 各自 ECDH 得到同一个 sharedSecret → 各自派生出同一个
|
|
10
|
+
* 6 位 SAS → 两端屏幕显示相同数字才点「允许」→ 落盘 peer。
|
|
11
|
+
* SAS 一致就证明没有中间人(中间人会让两边算出不同的 secret)。
|
|
12
|
+
*/
|
|
13
|
+
import {
|
|
14
|
+
createHash,
|
|
15
|
+
createHmac,
|
|
16
|
+
createPrivateKey,
|
|
17
|
+
createPublicKey,
|
|
18
|
+
diffieHellman,
|
|
19
|
+
generateKeyPairSync,
|
|
20
|
+
hkdfSync,
|
|
21
|
+
randomBytes,
|
|
22
|
+
timingSafeEqual,
|
|
23
|
+
} from "node:crypto";
|
|
24
|
+
import { chmodSync, existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from "node:fs";
|
|
25
|
+
import { dirname, join } from "node:path";
|
|
26
|
+
|
|
27
|
+
export const NODE_ID_LEN = 16;
|
|
28
|
+
/**
|
|
29
|
+
* 配对窗口:超时即作废,避免窗口一直开着等人误点。
|
|
30
|
+
* 10 分钟是因为「点一下就发请求」是异步投递——对端人可能正在开会,
|
|
31
|
+
* 60 秒的窗口意味着你得守在屏幕前反复点,那就退回了手抄流程。
|
|
32
|
+
*/
|
|
33
|
+
export const PAIRING_WINDOW_MS = 600_000;
|
|
34
|
+
/** 同一对端连续 3 次 SAS 不符就锁 5 分钟,防爆破 6 位码(100 万种,3 次/5 分钟足够)。 */
|
|
35
|
+
export const PAIRING_MAX_FAILURES = 3;
|
|
36
|
+
export const PAIRING_LOCKOUT_MS = 5 * 60_000;
|
|
37
|
+
/** 锁表的墓碑:过期的记录在这里留一会儿就清掉,避免 Map 无限长。 */
|
|
38
|
+
const PAIRING_STATE_TTL_MS = 30 * 60_000;
|
|
39
|
+
|
|
40
|
+
export class PairingError extends Error {
|
|
41
|
+
code: string;
|
|
42
|
+
constructor(code: string, message: string) {
|
|
43
|
+
super(message);
|
|
44
|
+
this.name = "PairingError";
|
|
45
|
+
this.code = code;
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
export interface FabricIdentity {
|
|
50
|
+
nodeId: string;
|
|
51
|
+
/** SPKI DER 的 base64,可公开。 */
|
|
52
|
+
publicKey: string;
|
|
53
|
+
/** PKCS8 DER 的 base64,绝不外发。 */
|
|
54
|
+
privateKey: string;
|
|
55
|
+
createdAt: number;
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
export function identityPath(agentDir: string): string {
|
|
59
|
+
return join(agentDir, "fabric", "identity.json");
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
let overridePath: string | null = null;
|
|
63
|
+
|
|
64
|
+
export function setIdentityPathForTest(path: string | null): void {
|
|
65
|
+
overridePath = path;
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
function resolvePath(agentDir: string): string {
|
|
69
|
+
return overridePath ?? identityPath(agentDir);
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
function isRecord(value: unknown): value is Record<string, unknown> {
|
|
73
|
+
return Boolean(value) && typeof value === "object" && !Array.isArray(value);
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
/** nodeId = sha256(SPKI) 前 16 位十六进制;公钥换了 nodeId 就换,天然绑定。 */
|
|
77
|
+
export function nodeIdOf(publicKeyBase64: string): string {
|
|
78
|
+
return createHash("sha256")
|
|
79
|
+
.update(Buffer.from(publicKeyBase64, "base64"))
|
|
80
|
+
.digest("hex")
|
|
81
|
+
.slice(0, NODE_ID_LEN);
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
function validateIdentity(raw: unknown): FabricIdentity {
|
|
85
|
+
if (!isRecord(raw)) throw new PairingError("E_INVALID_PARAMS", "identity must be an object");
|
|
86
|
+
const publicKey = typeof raw.publicKey === "string" ? raw.publicKey : "";
|
|
87
|
+
const privateKey = typeof raw.privateKey === "string" ? raw.privateKey : "";
|
|
88
|
+
if (!publicKey || !privateKey) {
|
|
89
|
+
throw new PairingError("E_INVALID_PARAMS", "identity is missing key material");
|
|
90
|
+
}
|
|
91
|
+
// 私钥与公钥必须成对:用私钥导出公钥再比,防止手改文件后静默用错身份。
|
|
92
|
+
const derived = createPublicKey(
|
|
93
|
+
createPrivateKey({ key: Buffer.from(privateKey, "base64"), format: "der", type: "pkcs8" }),
|
|
94
|
+
)
|
|
95
|
+
.export({ type: "spki", format: "der" })
|
|
96
|
+
.toString("base64");
|
|
97
|
+
if (derived !== publicKey) {
|
|
98
|
+
throw new PairingError("E_INVALID_PARAMS", "identity key pair mismatch");
|
|
99
|
+
}
|
|
100
|
+
const nodeId = nodeIdOf(publicKey);
|
|
101
|
+
if (typeof raw.nodeId === "string" && raw.nodeId !== nodeId) {
|
|
102
|
+
throw new PairingError("E_INVALID_PARAMS", "identity nodeId does not match its public key");
|
|
103
|
+
}
|
|
104
|
+
return {
|
|
105
|
+
nodeId,
|
|
106
|
+
publicKey,
|
|
107
|
+
privateKey,
|
|
108
|
+
createdAt: typeof raw.createdAt === "number" ? raw.createdAt : Date.now(),
|
|
109
|
+
};
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
export function createIdentity(now = Date.now()): FabricIdentity {
|
|
113
|
+
const { publicKey, privateKey } = generateKeyPairSync("x25519");
|
|
114
|
+
const publicDer = publicKey.export({ type: "spki", format: "der" }).toString("base64");
|
|
115
|
+
const privateDer = privateKey.export({ type: "pkcs8", format: "der" }).toString("base64");
|
|
116
|
+
return { nodeId: nodeIdOf(publicDer), publicKey: publicDer, privateKey: privateDer, createdAt: now };
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
/** 首次运行生成本机身份;之后原样读回(跨版本不重生成,否则已配对机器全部失联)。 */
|
|
120
|
+
export function loadOrCreateIdentity(agentDir: string, now = Date.now()): FabricIdentity {
|
|
121
|
+
const file = resolvePath(agentDir);
|
|
122
|
+
if (existsSync(file)) {
|
|
123
|
+
try {
|
|
124
|
+
return validateIdentity(JSON.parse(readFileSync(file, "utf8")) as unknown);
|
|
125
|
+
} catch {
|
|
126
|
+
// 文件损坏才重建;重建后 nodeId 会变,peers 需要重新配对,这是唯一可接受的代价。
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
const identity = createIdentity(now);
|
|
130
|
+
mkdirSync(dirname(file), { recursive: true });
|
|
131
|
+
const temp = `${file}.tmp`;
|
|
132
|
+
writeFileSync(temp, `${JSON.stringify(identity, null, 2)}\n`, { encoding: "utf8", mode: 0o600 });
|
|
133
|
+
renameSync(temp, file);
|
|
134
|
+
if (process.platform !== "win32") {
|
|
135
|
+
try {
|
|
136
|
+
chmodSync(file, 0o600);
|
|
137
|
+
} catch {
|
|
138
|
+
// 收紧失败不致命:目录本身在用户主目录下。
|
|
139
|
+
}
|
|
140
|
+
}
|
|
141
|
+
return identity;
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
/** X25519 ECDH:两端算出的 secret 相同,且任何一方都无法指定它(防弱密钥)。 */
|
|
145
|
+
export function deriveSharedSecret(identity: FabricIdentity, peerPublicKeyBase64: string): Buffer {
|
|
146
|
+
let secret: Buffer;
|
|
147
|
+
try {
|
|
148
|
+
secret = diffieHellman({
|
|
149
|
+
privateKey: createPrivateKey({
|
|
150
|
+
key: Buffer.from(identity.privateKey, "base64"),
|
|
151
|
+
format: "der",
|
|
152
|
+
type: "pkcs8",
|
|
153
|
+
}),
|
|
154
|
+
publicKey: createPublicKey({
|
|
155
|
+
key: Buffer.from(peerPublicKeyBase64, "base64"),
|
|
156
|
+
format: "der",
|
|
157
|
+
type: "spki",
|
|
158
|
+
}),
|
|
159
|
+
});
|
|
160
|
+
} catch {
|
|
161
|
+
throw new PairingError("E_INVALID_PARAMS", "peer public key is not a valid X25519 SPKI key");
|
|
162
|
+
}
|
|
163
|
+
if (secret.length !== 32 || secret.every((byte) => byte === 0)) {
|
|
164
|
+
throw new PairingError("E_INVALID_PARAMS", "peer public key produces a degenerate shared secret");
|
|
165
|
+
}
|
|
166
|
+
return secret;
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
function sortedPair(nodeIdA: string, nodeIdB: string): [string, string] {
|
|
170
|
+
return nodeIdA <= nodeIdB ? [nodeIdA, nodeIdB] : [nodeIdB, nodeIdA];
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
/**
|
|
174
|
+
* 6 位 SAS:两端算出同一个值。
|
|
175
|
+
* 绑定到双方的 nodeId,所以同一个 secret 在不同对端组合下 SAS 不同。
|
|
176
|
+
*/
|
|
177
|
+
export function deriveSas(sharedSecret: Buffer, nodeIdA: string, nodeIdB: string): string {
|
|
178
|
+
const [lo, hi] = sortedPair(nodeIdA, nodeIdB);
|
|
179
|
+
const digest = createHash("sha256")
|
|
180
|
+
.update(sharedSecret)
|
|
181
|
+
.update(lo)
|
|
182
|
+
.update(hi)
|
|
183
|
+
.digest();
|
|
184
|
+
const value = digest.readUInt32BE(0) % 1_000_000;
|
|
185
|
+
return String(value).padStart(6, "0");
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
export interface FabricSessionKeys {
|
|
189
|
+
/** 发起方 A → 接收方 B 的 HMAC 密钥。 */
|
|
190
|
+
aToB: Buffer;
|
|
191
|
+
/** 接收方 B → 发起方 A 的 HMAC 密钥(方向分开,防反射攻击)。 */
|
|
192
|
+
bToA: Buffer;
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
/** HKDF 派生两个方向的会话密钥:ECDH 原始 secret 不当密钥直接用。 */
|
|
196
|
+
export function deriveSessionKeys(
|
|
197
|
+
sharedSecret: Buffer,
|
|
198
|
+
nodeIdA: string,
|
|
199
|
+
nodeIdB: string,
|
|
200
|
+
): FabricSessionKeys {
|
|
201
|
+
const [lo, hi] = sortedPair(nodeIdA, nodeIdB);
|
|
202
|
+
const salt = Buffer.from(`${lo}:${hi}`, "utf8");
|
|
203
|
+
const aToB = Buffer.from(hkdfSync("sha256", sharedSecret, salt, Buffer.from("fabric/a2b", "utf8"), 32));
|
|
204
|
+
const bToA = Buffer.from(hkdfSync("sha256", sharedSecret, salt, Buffer.from("fabric/b2a", "utf8"), 32));
|
|
205
|
+
return { aToB, bToA };
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
/** 连接握手用的一次性挑战:nonce 由验证方随机出,响应方用自己方向的密钥算 MAC。 */
|
|
209
|
+
export function challengeMac(key: Buffer, nonce: Buffer, nodeId: string): string {
|
|
210
|
+
return createHmac("sha256", key).update(nonce).update(nodeId).digest("hex");
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
export function verifyChallengeMac(
|
|
214
|
+
key: Buffer,
|
|
215
|
+
nonce: Buffer,
|
|
216
|
+
nodeId: string,
|
|
217
|
+
mac: string,
|
|
218
|
+
): boolean {
|
|
219
|
+
const expected = Buffer.from(challengeMac(key, nonce, nodeId), "hex");
|
|
220
|
+
const actual = Buffer.from(typeof mac === "string" ? mac : "", "hex");
|
|
221
|
+
if (actual.length !== expected.length) return false;
|
|
222
|
+
return timingSafeEqual(expected, actual);
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
export function newNonce(): Buffer {
|
|
226
|
+
return randomBytes(32);
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
export type PairConfirmResult =
|
|
230
|
+
| { ok: true; sharedSecret: Buffer; keys: FabricSessionKeys }
|
|
231
|
+
| { ok: false; code: "E_PAIR_WINDOW_CLOSED" | "E_PAIR_SAS_MISMATCH" | "E_PAIR_LOCKED" };
|
|
232
|
+
|
|
233
|
+
export interface PairingSessionOptions {
|
|
234
|
+
windowMs?: number;
|
|
235
|
+
}
|
|
236
|
+
|
|
237
|
+
/**
|
|
238
|
+
* 一次配对会话。
|
|
239
|
+
*
|
|
240
|
+
* 注意时序:SAS 只在确认识别码时被用到,确认成功才应写 peer 记录;
|
|
241
|
+
* 失败不写任何持久化状态,因此「点了拒绝」等价于什么都没发生。
|
|
242
|
+
*/
|
|
243
|
+
export class PairingSession {
|
|
244
|
+
readonly remoteNodeId: string;
|
|
245
|
+
readonly remotePublicKey: string;
|
|
246
|
+
readonly sas: string;
|
|
247
|
+
readonly expiresAt: number;
|
|
248
|
+
readonly sharedSecret: Buffer;
|
|
249
|
+
private readonly keys: FabricSessionKeys;
|
|
250
|
+
private failures = 0;
|
|
251
|
+
private closed = false;
|
|
252
|
+
|
|
253
|
+
constructor(
|
|
254
|
+
identity: FabricIdentity,
|
|
255
|
+
remoteNodeId: string,
|
|
256
|
+
remotePublicKey: string,
|
|
257
|
+
now = Date.now(),
|
|
258
|
+
options: PairingSessionOptions = {},
|
|
259
|
+
) {
|
|
260
|
+
const window = options.windowMs ?? PAIRING_WINDOW_MS;
|
|
261
|
+
this.remoteNodeId = remoteNodeId;
|
|
262
|
+
this.remotePublicKey = remotePublicKey;
|
|
263
|
+
this.sharedSecret = deriveSharedSecret(identity, remotePublicKey);
|
|
264
|
+
this.sas = deriveSas(this.sharedSecret, identity.nodeId, remoteNodeId);
|
|
265
|
+
this.keys = deriveSessionKeys(this.sharedSecret, identity.nodeId, remoteNodeId);
|
|
266
|
+
this.expiresAt = now + window;
|
|
267
|
+
}
|
|
268
|
+
|
|
269
|
+
sessionKeys(): FabricSessionKeys {
|
|
270
|
+
return this.keys;
|
|
271
|
+
}
|
|
272
|
+
|
|
273
|
+
isExpired(now = Date.now()): boolean {
|
|
274
|
+
return now > this.expiresAt;
|
|
275
|
+
}
|
|
276
|
+
|
|
277
|
+
/** 会话已被烧掉:确认成功、被拒绝、或失败次数用尽。 */
|
|
278
|
+
isClosed(): boolean {
|
|
279
|
+
return this.closed;
|
|
280
|
+
}
|
|
281
|
+
|
|
282
|
+
/** 用户点了「允许」并(可选)比对过 SAS。 */
|
|
283
|
+
confirm(input: { sas?: string }, now = Date.now()): PairConfirmResult {
|
|
284
|
+
if (this.closed) return { ok: false, code: "E_PAIR_WINDOW_CLOSED" };
|
|
285
|
+
if (this.isExpired(now)) return { ok: false, code: "E_PAIR_WINDOW_CLOSED" };
|
|
286
|
+
const expected = input.sas == null ? null : String(input.sas).replace(/\s+/g, "");
|
|
287
|
+
if (expected !== null && expected !== this.sas) {
|
|
288
|
+
this.failures += 1;
|
|
289
|
+
if (this.failures >= PAIRING_MAX_FAILURES) {
|
|
290
|
+
// 会话级锁没有意义(窗口 60s < 锁 5min),锁交给 PairingGuard。
|
|
291
|
+
this.closed = true;
|
|
292
|
+
return { ok: false, code: "E_PAIR_LOCKED" };
|
|
293
|
+
}
|
|
294
|
+
return { ok: false, code: "E_PAIR_SAS_MISMATCH" };
|
|
295
|
+
}
|
|
296
|
+
this.closed = true;
|
|
297
|
+
return { ok: true, sharedSecret: this.sharedSecret, keys: this.keys };
|
|
298
|
+
}
|
|
299
|
+
|
|
300
|
+
reject(): void {
|
|
301
|
+
this.closed = true;
|
|
302
|
+
this.failures = 0;
|
|
303
|
+
}
|
|
304
|
+
}
|
|
305
|
+
|
|
306
|
+
interface LockState {
|
|
307
|
+
failures: number;
|
|
308
|
+
lockedUntil: number;
|
|
309
|
+
updatedAt: number;
|
|
310
|
+
}
|
|
311
|
+
|
|
312
|
+
/** 以 nodeId 为维度的失败计数:换一台机器配对不该被另一台的失败连累。 */
|
|
313
|
+
export class PairingGuard {
|
|
314
|
+
private readonly state = new Map<string, LockState>();
|
|
315
|
+
|
|
316
|
+
lockedUntil(nodeId: string): number {
|
|
317
|
+
return this.state.get(nodeId)?.lockedUntil ?? 0;
|
|
318
|
+
}
|
|
319
|
+
|
|
320
|
+
recordFailure(nodeId: string, now = Date.now()): void {
|
|
321
|
+
const current = this.state.get(nodeId) ?? { failures: 0, lockedUntil: 0, updatedAt: now };
|
|
322
|
+
const failures = current.failures + 1;
|
|
323
|
+
this.state.set(nodeId, {
|
|
324
|
+
failures,
|
|
325
|
+
lockedUntil: failures >= PAIRING_MAX_FAILURES ? now + PAIRING_LOCKOUT_MS : 0,
|
|
326
|
+
updatedAt: now,
|
|
327
|
+
});
|
|
328
|
+
this.prune(now);
|
|
329
|
+
}
|
|
330
|
+
|
|
331
|
+
reset(nodeId: string): void {
|
|
332
|
+
this.state.delete(nodeId);
|
|
333
|
+
}
|
|
334
|
+
|
|
335
|
+
private prune(now: number): void {
|
|
336
|
+
for (const [nodeId, value] of this.state) {
|
|
337
|
+
if (now - value.updatedAt > PAIRING_STATE_TTL_MS && value.lockedUntil < now) {
|
|
338
|
+
this.state.delete(nodeId);
|
|
339
|
+
}
|
|
340
|
+
}
|
|
341
|
+
}
|
|
342
|
+
}
|
|
@@ -0,0 +1,212 @@
|
|
|
1
|
+
import test from "node:test";
|
|
2
|
+
import assert from "node:assert/strict";
|
|
3
|
+
import { mkdtempSync, mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
|
|
4
|
+
import { tmpdir } from "node:os";
|
|
5
|
+
import { join } from "node:path";
|
|
6
|
+
import {
|
|
7
|
+
MAX_PEERS,
|
|
8
|
+
PeerStoreError,
|
|
9
|
+
deletePeer,
|
|
10
|
+
getPeer,
|
|
11
|
+
listPeers,
|
|
12
|
+
peersStorePath,
|
|
13
|
+
sanitizeFeatures,
|
|
14
|
+
sanitizeGrants,
|
|
15
|
+
savePeer,
|
|
16
|
+
setPeerStorePathForTest,
|
|
17
|
+
touchPeer,
|
|
18
|
+
} from "./peer-store.ts";
|
|
19
|
+
|
|
20
|
+
function setup() {
|
|
21
|
+
const dir = mkdtempSync(join(tmpdir(), "pi-fabric-peers-"));
|
|
22
|
+
const file = join(dir, "fabric", "peers.json");
|
|
23
|
+
setPeerStorePathForTest(file);
|
|
24
|
+
return {
|
|
25
|
+
dir,
|
|
26
|
+
file,
|
|
27
|
+
cleanup: () => {
|
|
28
|
+
setPeerStorePathForTest(null);
|
|
29
|
+
rmSync(dir, { recursive: true, force: true });
|
|
30
|
+
},
|
|
31
|
+
};
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
const NODE_A = "0123456789abcdef";
|
|
35
|
+
const NODE_B = "fedcba9876543210";
|
|
36
|
+
|
|
37
|
+
function peerInput(nodeId: string, overrides: Record<string, unknown> = {}) {
|
|
38
|
+
return {
|
|
39
|
+
nodeId,
|
|
40
|
+
name: `机-${nodeId.slice(0, 4)}`,
|
|
41
|
+
address: "192.168.1.20",
|
|
42
|
+
port: 7788,
|
|
43
|
+
grants: "workspace-rw" as const,
|
|
44
|
+
features: ["fabric.task.v1" as const],
|
|
45
|
+
appVersion: "0.12.5",
|
|
46
|
+
...overrides,
|
|
47
|
+
};
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
test("peer 记录落盘后原样读回", () => {
|
|
51
|
+
const env = setup();
|
|
52
|
+
try {
|
|
53
|
+
assert.equal(peersStorePath(env.dir), join(env.dir, "fabric", "peers.json"));
|
|
54
|
+
const saved = savePeer(env.dir, peerInput(NODE_A));
|
|
55
|
+
assert.equal(saved.nodeId, NODE_A);
|
|
56
|
+
assert.equal(saved.grants, "workspace-rw");
|
|
57
|
+
assert.deepEqual(saved.features, ["fabric.task.v1"]);
|
|
58
|
+
assert.ok(saved.pairedAt > 0);
|
|
59
|
+
|
|
60
|
+
const reloaded = listPeers(env.dir);
|
|
61
|
+
assert.equal(reloaded.length, 1);
|
|
62
|
+
assert.equal(reloaded[0].nodeId, NODE_A);
|
|
63
|
+
assert.equal(getPeer(env.dir, NODE_A)?.address, "192.168.1.20");
|
|
64
|
+
assert.equal(getPeer(env.dir, NODE_B), null);
|
|
65
|
+
} finally {
|
|
66
|
+
env.cleanup();
|
|
67
|
+
}
|
|
68
|
+
});
|
|
69
|
+
|
|
70
|
+
test("同一个 nodeId 重复配对是更新,不会长出第二条", () => {
|
|
71
|
+
const env = setup();
|
|
72
|
+
try {
|
|
73
|
+
savePeer(env.dir, peerInput(NODE_A, { name: "旧名字" }));
|
|
74
|
+
const updated = savePeer(env.dir, peerInput(NODE_A, { name: "新名字", grants: "read-only" }));
|
|
75
|
+
assert.equal(updated.name, "新名字");
|
|
76
|
+
assert.equal(updated.grants, "read-only");
|
|
77
|
+
const all = listPeers(env.dir);
|
|
78
|
+
assert.equal(all.length, 1);
|
|
79
|
+
assert.equal(all[0].name, "新名字");
|
|
80
|
+
} finally {
|
|
81
|
+
env.cleanup();
|
|
82
|
+
}
|
|
83
|
+
});
|
|
84
|
+
|
|
85
|
+
test("未知字段(未来版本 / 其他来源写的)不会被写丢", () => {
|
|
86
|
+
const env = setup();
|
|
87
|
+
try {
|
|
88
|
+
mkdirSync(join(env.dir, "fabric"), { recursive: true });
|
|
89
|
+
writeFileSync(
|
|
90
|
+
env.file,
|
|
91
|
+
JSON.stringify({
|
|
92
|
+
schemaVersion: 1,
|
|
93
|
+
futureTopLevel: { keep: true },
|
|
94
|
+
peers: [
|
|
95
|
+
{
|
|
96
|
+
...peerInput(NODE_A),
|
|
97
|
+
pairedAt: 1000,
|
|
98
|
+
createdAt: 1000,
|
|
99
|
+
updatedAt: 1000,
|
|
100
|
+
lastSeenAt: null,
|
|
101
|
+
futurePeerField: ["keep-me"],
|
|
102
|
+
},
|
|
103
|
+
],
|
|
104
|
+
}),
|
|
105
|
+
"utf8",
|
|
106
|
+
);
|
|
107
|
+
|
|
108
|
+
savePeer(env.dir, peerInput(NODE_A, { name: "改过名" }));
|
|
109
|
+
const written = JSON.parse(readFileSync(env.file, "utf8")) as Record<string, unknown>;
|
|
110
|
+
assert.deepEqual(written.futureTopLevel, { keep: true });
|
|
111
|
+
assert.equal(written.schemaVersion, 1);
|
|
112
|
+
const peers = written.peers as Record<string, unknown>[];
|
|
113
|
+
assert.deepEqual(peers[0].futurePeerField, ["keep-me"]);
|
|
114
|
+
assert.equal(peers[0].name, "改过名");
|
|
115
|
+
} finally {
|
|
116
|
+
env.cleanup();
|
|
117
|
+
}
|
|
118
|
+
});
|
|
119
|
+
|
|
120
|
+
test("规模上限拦截,并给出可识别的错误码", () => {
|
|
121
|
+
const env = setup();
|
|
122
|
+
try {
|
|
123
|
+
for (let index = 0; index < MAX_PEERS; index += 1) {
|
|
124
|
+
savePeer(env.dir, peerInput(index.toString(16).padStart(16, "0")));
|
|
125
|
+
}
|
|
126
|
+
assert.equal(listPeers(env.dir).length, MAX_PEERS);
|
|
127
|
+
assert.throws(
|
|
128
|
+
() => savePeer(env.dir, peerInput(NODE_B)),
|
|
129
|
+
(error: unknown) => error instanceof PeerStoreError && error.code === "E_PEER_LIMIT",
|
|
130
|
+
);
|
|
131
|
+
} finally {
|
|
132
|
+
env.cleanup();
|
|
133
|
+
}
|
|
134
|
+
});
|
|
135
|
+
|
|
136
|
+
test("坏记录与坏文件都不连累整份文件", () => {
|
|
137
|
+
const env = setup();
|
|
138
|
+
try {
|
|
139
|
+
mkdirSync(join(env.dir, "fabric"), { recursive: true });
|
|
140
|
+
writeFileSync(
|
|
141
|
+
env.file,
|
|
142
|
+
JSON.stringify({ peers: [{ ...peerInput(NODE_A) }, { nodeId: "not-hex" }, "垃圾"] }),
|
|
143
|
+
"utf8",
|
|
144
|
+
);
|
|
145
|
+
assert.equal(listPeers(env.dir).length, 1);
|
|
146
|
+
writeFileSync(env.file, "{ 这不是 JSON", "utf8");
|
|
147
|
+
assert.deepEqual(listPeers(env.dir), []);
|
|
148
|
+
savePeer(env.dir, peerInput(NODE_B));
|
|
149
|
+
assert.equal(listPeers(env.dir).length, 1);
|
|
150
|
+
} finally {
|
|
151
|
+
env.cleanup();
|
|
152
|
+
}
|
|
153
|
+
});
|
|
154
|
+
|
|
155
|
+
test("未登记的档位降到只读,未知 capability 直接忽略", () => {
|
|
156
|
+
assert.equal(sanitizeGrants("workspace-rw+bash"), "workspace-rw+bash");
|
|
157
|
+
assert.equal(sanitizeGrants("root"), "read-only");
|
|
158
|
+
assert.equal(sanitizeGrants(undefined), "read-only");
|
|
159
|
+
assert.deepEqual(sanitizeFeatures(["fabric.task.v1", "evil.feature", 42]), ["fabric.task.v1"]);
|
|
160
|
+
assert.deepEqual(sanitizeFeatures(undefined), []);
|
|
161
|
+
});
|
|
162
|
+
|
|
163
|
+
test("nodeId 必须是 16 位十六进制,地址不接受可疑字符", () => {
|
|
164
|
+
const env = setup();
|
|
165
|
+
try {
|
|
166
|
+
assert.throws(
|
|
167
|
+
() => savePeer(env.dir, peerInput("XYZ")),
|
|
168
|
+
(error: unknown) => error instanceof PeerStoreError,
|
|
169
|
+
);
|
|
170
|
+
assert.throws(
|
|
171
|
+
() => savePeer(env.dir, peerInput(NODE_A, { address: "1.2.3.4; rm -rf /" })),
|
|
172
|
+
(error: unknown) => error instanceof PeerStoreError,
|
|
173
|
+
);
|
|
174
|
+
assert.throws(
|
|
175
|
+
() => savePeer(env.dir, peerInput(NODE_A, { port: 70000 })),
|
|
176
|
+
(error: unknown) => error instanceof PeerStoreError,
|
|
177
|
+
);
|
|
178
|
+
} finally {
|
|
179
|
+
env.cleanup();
|
|
180
|
+
}
|
|
181
|
+
});
|
|
182
|
+
|
|
183
|
+
test("列表按最近配对排序,touch 只更新 lastSeenAt", () => {
|
|
184
|
+
const env = setup();
|
|
185
|
+
try {
|
|
186
|
+
savePeer(env.dir, peerInput(NODE_A, { pairedAt: 1_000 }));
|
|
187
|
+
savePeer(env.dir, peerInput(NODE_B, { pairedAt: 2_000 }));
|
|
188
|
+
const ordered = listPeers(env.dir);
|
|
189
|
+
assert.deepEqual(
|
|
190
|
+
ordered.map((peer) => peer.nodeId),
|
|
191
|
+
[NODE_B, NODE_A],
|
|
192
|
+
);
|
|
193
|
+
const touched = touchPeer(env.dir, NODE_A, 12_345);
|
|
194
|
+
assert.equal(touched?.lastSeenAt, 12_345);
|
|
195
|
+
assert.equal(touched?.pairedAt, 1_000);
|
|
196
|
+
assert.equal(getPeer(env.dir, NODE_B)?.lastSeenAt, null);
|
|
197
|
+
} finally {
|
|
198
|
+
env.cleanup();
|
|
199
|
+
}
|
|
200
|
+
});
|
|
201
|
+
|
|
202
|
+
test("取消配对后再也查不到", () => {
|
|
203
|
+
const env = setup();
|
|
204
|
+
try {
|
|
205
|
+
savePeer(env.dir, peerInput(NODE_A));
|
|
206
|
+
assert.equal(deletePeer(env.dir, NODE_A), true);
|
|
207
|
+
assert.equal(deletePeer(env.dir, NODE_A), false);
|
|
208
|
+
assert.equal(getPeer(env.dir, NODE_A), null);
|
|
209
|
+
} finally {
|
|
210
|
+
env.cleanup();
|
|
211
|
+
}
|
|
212
|
+
});
|