architecture-harness 0.28.0 → 0.29.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.
@@ -0,0 +1,355 @@
1
+ import { strict as assert } from "node:assert";
2
+ import { createHash, createPublicKey, createPrivateKey, diffieHellman, hkdfSync, createDecipheriv } from "node:crypto";
3
+ import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
4
+ import os from "node:os";
5
+ import path from "node:path";
6
+ import { test } from "node:test";
7
+ import { stateDir } from "./fleet-state.mjs";
8
+ import { createKey, pairCode, pairDigest, pairCommit, createPairing, pairingDecision, readPairing } from "./fleet-pair.mjs";
9
+
10
+ const now = 1_800_000_000_000;
11
+ const secret = "ab".repeat(32);
12
+ function fixture(t) {
13
+ const root = mkdtempSync(path.join(os.tmpdir(), "qc-pair-"));
14
+ mkdirSync(path.join(root, ".git"));
15
+ t.after(() => rmSync(root, { recursive: true, force: true, maxRetries: 10, retryDelay: 100 }));
16
+ return root;
17
+ }
18
+ function peers(t) {
19
+ let time = now, saved;
20
+ const a = { self: "leader", key: createKey(), secret, nodes: [{ id: "leader", port: 8080 }] };
21
+ const b = { self: "joiner", key: createKey(), nodes: [{ id: "joiner", port: 8081 }] };
22
+ const root = fixture(t), other = fixture(t), sent = [], reveals = [];
23
+ const lead = createPairing({ root, fleet: a, leader: () => true, address: "192.168.1.10", clock: () => time,
24
+ fetch: async (url, options) => { sent.push(JSON.parse(options.body)); return { status: 202 }; } });
25
+ const join = createPairing({ root: other, fleet: b, address: "192.168.1.20", clock: () => time,
26
+ fetch: async (_url, options) => { const body = JSON.parse(options.body); reveals.push(body); return { status: lead.receivePair(body, "192.168.1.20") ? 202 : 400 }; },
27
+ saveSecret: value => { saved = value; } });
28
+ return { a, b, root, other, lead, join, sent, reveals, get saved() { return saved; }, advance: ms => { time += ms; } };
29
+ }
30
+ async function offer(p) {
31
+ assert.equal(p.lead.receiveJoin(p.join.beacon(), "192.168.1.20"), true);
32
+ await p.lead.tick();
33
+ assert.equal(p.sent.at(-1).kind, "offer");
34
+ p.offerNonce = p.sent.at(-1).nonce;
35
+ assert.equal(p.join.receivePair(p.sent.at(-1), "192.168.1.10"), true);
36
+ return readPairing(p.root).requests.joiner.code;
37
+ }
38
+
39
+ test("digest binds ordered raw keys and ordered 16-byte random values; code uses its first six bytes", () => {
40
+ const a = createKey(), b = createKey(), lr = "11".repeat(16), r = "22".repeat(16);
41
+ const raw = key => Buffer.from(createPublicKey({ key: Buffer.from(key, "base64"), format: "der", type: "spki" }).export({ format: "jwk" }).x, "base64url");
42
+ const expected = createHash("sha256").update(Buffer.concat([Buffer.from("qc-fleet-pair\n"), raw(a.public), raw(b.public), Buffer.from(lr, "hex"), Buffer.from(r, "hex")])).digest();
43
+ assert.deepEqual(pairDigest(a.public, b.public, lr, r), expected);
44
+ assert.equal(pairCode(a.public, b.public, lr, r), String(expected.readUIntBE(0, 6) % 1_000_000).padStart(6, "0"));
45
+ assert.notDeepEqual(pairDigest(b.public, a.public, lr, r), expected);
46
+ assert.notDeepEqual(pairDigest(a.public, b.public, r, lr), expected);
47
+ assert.throws(() => pairCode(a.public, "bad", lr, r));
48
+ assert.throws(() => pairDigest(a.public, b.public, lr, "00"));
49
+ assert.equal(pairCommit(b.public, r), createHash("sha256").update(Buffer.concat([Buffer.from("qc-fleet-commit\n"), raw(b.public), Buffer.from(r, "hex")])).digest("hex"));
50
+ });
51
+
52
+ test("beacon commits once per attempt and reveals only after an offer; wrong reveals are refused", async t => {
53
+ const p = peers(t), beacon = p.join.beacon();
54
+ assert.match(beacon.commit, /^[0-9a-f]{64}$/);
55
+ assert.equal(beacon.pub, undefined);
56
+ assert.equal(beacon.nonce, undefined);
57
+ p.advance(1000);
58
+ assert.equal(p.join.beacon().commit, beacon.commit);
59
+ const restarted = createPairing({ fleet: p.b, address: "192.168.1.20" });
60
+ assert.notEqual(restarted.beacon().commit, beacon.commit);
61
+ assert.equal(p.reveals.length, 0);
62
+ assert.equal(p.lead.receiveJoin(beacon, "192.168.1.20"), true);
63
+ assert.equal(readPairing(p.root).requests.joiner.code, undefined);
64
+ assert.equal(p.lead.receivePair({ kind: "reveal", id: "joiner", pub: p.b.key.public, nonce: "00".repeat(16) }, "192.168.1.20"), false);
65
+ assert.equal(readPairing(p.root).requests.joiner.code, undefined);
66
+ await p.lead.tick();
67
+ assert.equal(p.sent[0].commit, beacon.commit);
68
+ assert.match(p.sent[0].nonce, /^[0-9a-f]{32}$/);
69
+ assert.equal(p.join.receivePair(p.sent[0], "192.168.1.10"), true);
70
+ assert.equal(p.reveals.length, 1);
71
+ const reveal = p.reveals[0];
72
+ assert.deepEqual(Object.keys(reveal).sort(), ["id", "kind", "nonce", "pub"]);
73
+ assert.equal(pairCommit(reveal.pub, reveal.nonce), beacon.commit);
74
+ assert.equal(p.lead.receivePair({ ...reveal, nonce: "ff".repeat(16) }, "192.168.1.20"), false);
75
+ assert.equal(p.lead.receivePair(reveal, "192.168.1.30"), false);
76
+ assert.equal(p.lead.receivePair({ ...reveal, extra: true }, "192.168.1.20"), false);
77
+ assert.equal(readPairing(p.root).requests.joiner.code, readPairing(p.other).offers.leader.code);
78
+ });
79
+
80
+ test("after revealing, the joiner ignores offers from every other Leader id", async t => {
81
+ const p = peers(t);
82
+ await offer(p);
83
+ const first = readPairing(p.other).offers.leader, reveal = p.reveals[0];
84
+ const second = { ...p.sent[0], leader: "fake-leader", pub: createKey().public };
85
+ assert.equal(p.join.receivePair(second, "192.168.1.30"), false);
86
+ assert.equal(p.reveals.length, 1);
87
+ p.advance(15_000);
88
+ await p.join.tick();
89
+ assert.deepEqual(p.reveals, [reveal, reveal]);
90
+ assert.deepEqual(readPairing(p.other).offers, { leader: first });
91
+ });
92
+
93
+ test("expiry rotates the attempt's random value and commitment before any new reveal", async t => {
94
+ const p = peers(t), beacon = p.join.beacon();
95
+ await offer(p);
96
+ const oldReveal = p.reveals[0], oldOffer = p.sent[0];
97
+ p.advance(600_001);
98
+ await p.join.tick();
99
+ assert.equal(p.reveals.length, 1);
100
+ const next = p.join.beacon();
101
+ assert.notEqual(next.commit, beacon.commit);
102
+ assert.equal(p.join.beacon().commit, next.commit);
103
+ assert.deepEqual(readPairing(p.other).offers, {});
104
+ assert.equal(p.join.receivePair({ ...oldOffer, time: now + 600_001 }, "192.168.1.10"), false);
105
+ assert.deepEqual(readPairing(p.other).offers, {});
106
+ assert.equal(p.reveals.length, 1);
107
+ assert.equal(p.lead.receiveJoin(next, "192.168.1.20"), true);
108
+ await p.lead.tick();
109
+ assert.equal(p.join.receivePair(p.sent.at(-1), "192.168.1.10"), true);
110
+ assert.equal(p.reveals.length, 2);
111
+ assert.notEqual(p.reveals[1].nonce, oldReveal.nonce);
112
+ assert.equal(pairCommit(p.reveals[1].pub, p.reveals[1].nonce), next.commit);
113
+ });
114
+
115
+ test("joiner deny drops its offer and rotates the attempt without revealing old randomness", async t => {
116
+ const p = peers(t), beacon = p.join.beacon(), code = await offer(p);
117
+ const oldReveal = p.reveals[0];
118
+ pairingDecision(p.root, "allow", code, now);
119
+ await p.lead.tick();
120
+ const grant = p.sent.find(body => body.kind === "grant");
121
+ assert.equal(p.join.receivePair(grant, "192.168.1.10"), true);
122
+ pairingDecision(p.other, "accept", code, now);
123
+ pairingDecision(p.other, "deny", code, now, { joiner: true });
124
+ assert.deepEqual(readPairing(p.other).offers, {});
125
+ assert.throws(() => pairingDecision(p.other, "accept", code, now));
126
+ await p.join.tick();
127
+ assert.equal(p.saved, undefined);
128
+ assert.equal(p.join.receivePair(grant, "192.168.1.10"), false);
129
+ assert.equal(p.reveals.length, 1);
130
+ const next = p.join.beacon();
131
+ assert.notEqual(next.commit, beacon.commit);
132
+ assert.equal(p.join.receivePair({ ...p.sent[0], leader: "other-leader", commit: next.commit }, "192.168.1.30"), true);
133
+ assert.notEqual(p.reveals[1].nonce, oldReveal.nonce);
134
+ assert.equal(pairCommit(p.reveals[1].pub, p.reveals[1].nonce), next.commit);
135
+ assert.equal(readPairing(p.other).offers["other-leader"].accepted, false);
136
+ });
137
+
138
+ test("retry with the same Leader after joiner deny waits for the old request to expire and pairs with matching codes", async t => {
139
+ const p = peers(t), code = await offer(p), oldOffer = p.sent[0];
140
+ p.advance(15_000);
141
+ pairingDecision(p.other, "deny", code, now + 15_000, { joiner: true });
142
+ const next = p.join.beacon();
143
+ assert.notEqual(next.commit, oldOffer.commit);
144
+ assert.equal(p.lead.receiveJoin(next, "192.168.1.20"), false);
145
+ await p.lead.tick();
146
+ const retry = p.sent.at(-1);
147
+ assert.equal(retry.commit, oldOffer.commit);
148
+ assert.equal(p.join.receivePair(retry, "192.168.1.10"), false);
149
+ assert.deepEqual(readPairing(p.other).offers, {});
150
+ assert.equal(p.reveals.length, 1);
151
+ assert.equal(readPairing(p.root).requests.joiner.code, code);
152
+ p.advance(585_001);
153
+ assert.equal(p.join.beacon().commit, next.commit);
154
+ const nextCode = await offer(p);
155
+ assert.equal(p.sent.at(-1).commit, next.commit);
156
+ assert.equal(readPairing(p.other).offers.leader.code, nextCode);
157
+ pairingDecision(p.root, "allow", nextCode, now + 600_001);
158
+ pairingDecision(p.other, "accept", nextCode, now + 600_001);
159
+ await p.lead.tick();
160
+ const grant = p.sent.find(body => body.kind === "grant");
161
+ assert.ok(grant);
162
+ assert.equal(p.join.receivePair(grant, "192.168.1.10"), true);
163
+ await p.join.tick();
164
+ assert.equal(p.saved, secret);
165
+ });
166
+
167
+ test("restart retains the active Leader binding and observes another process denying it", async t => {
168
+ const p = peers(t), beacon = p.join.beacon(), code = await offer(p), reveals = [];
169
+ const restarted = createPairing({ root: p.other, fleet: p.b, address: "192.168.1.20", clock: () => now,
170
+ fetch: async (_url, options) => { reveals.push(JSON.parse(options.body)); } });
171
+ assert.equal(restarted.beacon().commit, beacon.commit);
172
+ assert.equal(restarted.receivePair({ ...p.sent[0], leader: "other-leader" }, "192.168.1.30"), false);
173
+ await restarted.tick();
174
+ assert.deepEqual(reveals, [p.reveals[0]]);
175
+ pairingDecision(p.other, "deny", code, now, { joiner: true });
176
+ await restarted.tick();
177
+ assert.equal(reveals.length, 1);
178
+ const next = restarted.beacon();
179
+ assert.notEqual(next.commit, beacon.commit);
180
+ assert.equal(p.join.beacon().commit, next.commit);
181
+ assert.equal(restarted.receivePair(p.sent[0], "192.168.1.10"), false);
182
+ assert.equal(reveals.length, 1);
183
+ assert.equal(restarted.receivePair({ ...p.sent[0], commit: next.commit }, "192.168.1.10"), true);
184
+ assert.notEqual(reveals[1].nonce, p.reveals[0].nonce);
185
+ assert.equal(pairCommit(reveals[1].pub, reveals[1].nonce), next.commit);
186
+ });
187
+
188
+ test("bad public keys reach parsing before an offer is bound", t => {
189
+ const p = peers(t);
190
+ const body = { kind: "offer", leader: "unused-leader", commit: p.join.beacon().commit, pub: "bad", nonce: "11".repeat(16), port: 8080, time: now };
191
+ assert.equal(p.join.receivePair(body, "192.168.1.10"), false);
192
+ assert.deepEqual(readPairing(p.other).offers, {});
193
+ assert.equal(p.reveals.length, 0);
194
+ assert.equal(p.join.receivePair({ ...body, pub: p.a.key.public }, "192.168.1.10"), true);
195
+ assert.equal(p.reveals.length, 1);
196
+ });
197
+
198
+ test("offers without the active commitment cannot bind any Leader", t => {
199
+ const p = peers(t), beacon = p.join.beacon();
200
+ const body = { kind: "offer", leader: "leader", pub: p.a.key.public, nonce: "11".repeat(16), port: 8080, time: now };
201
+ for (const commit of [undefined, null, "bad", "00".repeat(32)]) {
202
+ assert.equal(p.join.receivePair({ ...body, commit }, "192.168.1.10"), false);
203
+ assert.deepEqual(readPairing(p.other).offers, {});
204
+ assert.equal(p.reveals.length, 0);
205
+ }
206
+ assert.equal(p.join.receivePair({ ...body, commit: beacon.commit }, "192.168.1.10"), true);
207
+ assert.equal(p.reveals.length, 1);
208
+ });
209
+
210
+ test("first commitment and offer stay fixed through retries until expiry", async t => {
211
+ const p = peers(t), beacon = p.join.beacon();
212
+ p.lead.receiveJoin(beacon, "192.168.1.20");
213
+ const first = readPairing(p.root).requests.joiner;
214
+ p.advance(15_000);
215
+ assert.equal(p.lead.receiveJoin({ ...beacon, commit: "11".repeat(32), port: 9090, time: now + 15_000 }, "192.168.1.20"), false);
216
+ assert.deepEqual(readPairing(p.root).requests.joiner, first);
217
+ await p.lead.tick();
218
+ const body = p.sent[0];
219
+ assert.equal(p.join.receivePair(body, "192.168.1.10"), true);
220
+ const original = readPairing(p.other).offers.leader;
221
+ pairingDecision(p.other, "accept", original.code, now + 15_000);
222
+ p.advance(15_000);
223
+ for (const change of [{ pub: createKey().public }, { nonce: "33".repeat(16) }, { port: 9090 }, {}])
224
+ assert.equal(p.join.receivePair({ ...body, ...change, time: now + 30_000 }, "192.168.1.10"), false);
225
+ assert.deepEqual(readPairing(p.other).offers.leader, { ...original, accepted: true });
226
+ assert.equal(p.lead.receiveJoin({ ...beacon, time: now + 30_000 }, "192.168.1.20"), false);
227
+ p.advance(600_001);
228
+ assert.equal(p.lead.receiveJoin(p.join.beacon(), "192.168.1.20"), true);
229
+ await p.lead.tick();
230
+ assert.notEqual(p.sent.at(-1).nonce, body.nonce);
231
+ assert.equal(p.join.receivePair(p.sent.at(-1), "192.168.1.10"), true);
232
+ assert.equal(readPairing(p.other).offers.leader.accepted, false);
233
+ });
234
+
235
+ test("grant waits for accept, authenticates its tag, then saves the shared secret", async t => {
236
+ const p = peers(t), code = await offer(p);
237
+ assert.deepEqual(readPairing(p.root).requests.joiner, { code, address: "192.168.1.20", port: 8081,
238
+ hostname: os.hostname(), os: process.platform, seen: now, allowed: false });
239
+ assert.equal(readPairing(p.other).offers.leader.code, code);
240
+ pairingDecision(p.root, "allow", code, now);
241
+ p.sent.length = 0;
242
+ await p.lead.tick();
243
+ const grant = p.sent.find(body => body.kind === "grant");
244
+ assert.ok(grant);
245
+ const reveal = p.reveals[0], digest = pairDigest(p.a.key.public, p.b.key.public, p.offerNonce, reveal.nonce);
246
+ const shared = diffieHellman({ privateKey: createPrivateKey({ key: Buffer.from(p.b.key.private, "base64"), format: "der", type: "pkcs8" }), publicKey: createPublicKey({ key: Buffer.from(p.a.key.public, "base64"), format: "der", type: "spki" }) });
247
+ const decipher = createDecipheriv("aes-256-gcm", hkdfSync("sha256", shared, digest, Buffer.from("qc-fleet-pair"), 32), Buffer.from(grant.nonce, "base64"));
248
+ const data = Buffer.from(grant.data, "base64");
249
+ decipher.setAuthTag(data.subarray(-16));
250
+ assert.deepEqual(JSON.parse(Buffer.concat([decipher.update(data.subarray(0, -16)), decipher.final()]).toString()), { secret });
251
+ assert.equal(JSON.stringify(grant).includes(secret), false);
252
+ const damaged = { ...grant, data: Buffer.alloc(Buffer.from(grant.data, "base64").length).toString("base64") };
253
+ assert.equal(p.join.receivePair(damaged, "192.168.1.10"), false);
254
+ assert.equal(p.join.receivePair(grant, "192.168.1.10"), true);
255
+ await p.join.tick();
256
+ assert.equal(p.saved, undefined);
257
+ pairingDecision(p.other, "accept", code, now);
258
+ await p.join.tick();
259
+ assert.equal(p.saved, secret);
260
+ });
261
+
262
+ test("deny blocks the same id and key for one hour and rejects ambiguous or expired codes", async t => {
263
+ const p = peers(t), code = await offer(p);
264
+ pairingDecision(p.root, "deny", code, now);
265
+ assert.equal(p.lead.receiveJoin(p.join.beacon(), "192.168.1.20"), false);
266
+ const changedId = { ...p.join.beacon(), id: "renamed" };
267
+ assert.equal(p.lead.receiveJoin(changedId, "192.168.1.20"), false);
268
+ p.b.key = createKey();
269
+ assert.equal(p.lead.receiveJoin(p.join.beacon(), "192.168.1.20"), false);
270
+ assert.throws(() => pairingDecision(p.root, "allow", code, now));
271
+ p.advance(3_600_001);
272
+ assert.equal(p.lead.receiveJoin(p.join.beacon(), "192.168.1.20"), true);
273
+ p.advance(600_001);
274
+ assert.throws(() => pairingDecision(p.root, "allow", code, now + 4_200_002));
275
+ });
276
+
277
+ test("join validation rejects bad fields, stale clocks, spoofed senders and oversized datagrams; requests cap at 20", async t => {
278
+ const p = peers(t), beacon = p.join.beacon();
279
+ for (const change of [{ v: 2 }, { id: "../bad" }, { commit: "bad" }, { port: 0 }, { hostname: "x\n" },
280
+ { os: {} }, { time: now - 60_001 }, { address: "192.168.1.30" }, { commit: "00".repeat(31) }, { extra: "x".repeat(2048) }]) {
281
+ assert.equal(p.lead.receiveJoin({ ...beacon, ...change }, "192.168.1.20"), false);
282
+ }
283
+ for (let i = 0; i < 21; i++) p.lead.receiveJoin({ ...beacon, id: `pc-${i}` }, "192.168.1.20");
284
+ assert.equal(Object.keys(readPairing(p.root).requests).length, 20);
285
+ assert.ok(readPairing(p.root).requests["pc-0"]);
286
+ assert.equal(readPairing(p.root).requests["pc-20"], undefined);
287
+ p.advance(600_001);
288
+ assert.equal(p.lead.receiveJoin(p.join.beacon(), "192.168.1.20"), true);
289
+ assert.equal(Object.keys(readPairing(p.root).requests).length, 1);
290
+ });
291
+
292
+ test("offers and grants bind sender, key and live offer; retries expire and stop on a signed beacon", async t => {
293
+ const p = peers(t), code = await offer(p), body = p.sent[0];
294
+ for (const change of [{ time: now - 60_001 }, { port: 0 }, { pub: "bad", leader: "unused-leader" }, { leader: "../bad" }, { extra: "x".repeat(2048) }])
295
+ assert.equal(p.join.receivePair({ ...body, ...change }, "192.168.1.10"), false);
296
+ pairingDecision(p.root, "allow", code, now);
297
+ p.sent.length = 0;
298
+ await p.lead.tick();
299
+ const grant = p.sent.find(body => body.kind === "grant");
300
+ assert.equal(p.join.receivePair(grant, "192.168.1.30"), false);
301
+ assert.equal(p.join.receivePair({ ...grant, pub: createKey().public }, "192.168.1.10"), false);
302
+ p.advance(15_000);
303
+ await p.lead.tick();
304
+ assert.equal(p.sent.filter(body => body.kind === "grant").length, 2);
305
+ p.lead.signed("joiner");
306
+ p.advance(15_000);
307
+ await p.lead.tick();
308
+ assert.equal(p.sent.filter(body => body.kind === "grant").length, 2);
309
+ const q = peers(t), qcode = await offer(q);
310
+ pairingDecision(q.root, "allow", qcode, now);
311
+ await q.lead.tick();
312
+ const old = q.sent.find(body => body.kind === "grant");
313
+ assert.equal(q.join.receivePair(old, "192.168.1.10"), true);
314
+ q.advance(600_001);
315
+ q.sent.length = 0;
316
+ await q.lead.tick();
317
+ assert.equal(q.sent.length, 0);
318
+ assert.equal(q.join.receivePair(old, "192.168.1.10"), false);
319
+ assert.throws(() => pairingDecision(q.other, "accept", qcode, now + 600_001));
320
+ });
321
+
322
+
323
+ test("shared contract flags drive grant and accept across a restart; retries cannot extend request lifetime", async t => {
324
+ const p = peers(t), code = await offer(p);
325
+ const file = path.join(stateDir(p.root), "pairing.json"), state = readPairing(p.root);
326
+ state.requests.joiner.allowed = "true";
327
+ writeFileSync(file, JSON.stringify(state));
328
+ await p.lead.tick();
329
+ assert.equal(p.sent.some(body => body.kind === "grant"), false);
330
+ state.requests.joiner.allowed = true;
331
+ writeFileSync(file, JSON.stringify(state));
332
+ await p.lead.tick();
333
+ let grant = p.sent.find(body => body.kind === "grant");
334
+ assert.ok(grant);
335
+ assert.equal(p.join.receivePair(grant, "192.168.1.10"), true);
336
+ const offers = readPairing(p.other);
337
+ offers.offers.leader.accepted = "true";
338
+ writeFileSync(path.join(stateDir(p.other), "pairing.json"), JSON.stringify(offers));
339
+ let saved;
340
+ const restarted = createPairing({ root: p.other, fleet: p.b, clock: () => now, saveSecret: value => { saved = value; } });
341
+ await restarted.tick();
342
+ assert.equal(saved, undefined);
343
+ offers.offers.leader.accepted = true;
344
+ writeFileSync(path.join(stateDir(p.other), "pairing.json"), JSON.stringify(offers));
345
+ await createPairing({ root: p.other, fleet: p.b, clock: () => now, saveSecret: value => { saved = value; } }).tick();
346
+ assert.equal(saved, secret);
347
+ assert.equal(readFileSync(path.join(stateDir(p.other), "pairing-private.json"), "utf8").includes(secret), false);
348
+ // Repeated beacons cannot extend the fixed request or its grant window.
349
+ delete p.b.secret;
350
+ p.advance(600_001);
351
+ p.sent.length = 0;
352
+ await p.lead.tick();
353
+ assert.equal(p.sent.length, 0);
354
+ assert.throws(() => pairingDecision(p.root, "allow", code, now + 600_001));
355
+ });
package/src/cli/fleet.mjs CHANGED
@@ -13,10 +13,11 @@ import { sendPushed, validPlatformBranch } from "./fleet-platform.mjs";
13
13
  import { TALK_VERBS, parseTalkArgs, runTalk } from "./fleet-talk.mjs";
14
14
  import { highestTerm, latestLeader, readState, writeState } from "./fleet-state.mjs";
15
15
  import { confirmLeader, nodeStatus, serveNode, startNode, stopNode } from "./fleet-node.mjs";
16
+ import { createKey, validateKey, pairingDecision, readPairing } from "./fleet-pair.mjs";
16
17
  import { effectiveFleet, readDiscovered } from "./fleet-discover.mjs";
17
18
 
18
19
  const SIZES = ["S", "M", "L"];
19
- const USAGE = "usage: qc fleet init [--self <id>] [--nodes <id:weight:size,...>] [--port <port>] [--secret <hex>] [--addresses <id@host:port,...>] [--force] | next [--repo <o/r>] [--all] | status [--repo <o/r>] | plan <issue> --file <path> | ask <issue> --file <path> | approve <message-id> [--changes] [--file <path>] | answer <message-id> --file <path> | show <message-id> | start [--leader] | serve [--leader] | stop | confirm-leader | progress <issue> --step plan|code|review|merge [--branch <b>] [--head <sha40>] | owns <issue> | pushed <issue> --branch <b> --head <sha40>";
20
+ const USAGE = "usage: qc fleet init [--self <id>] [--nodes <id:weight:size,...>] [--port <port>] [--secret <hex>] [--addresses <id@host:port,...>] [--force] | next [--repo <o/r>] [--all] | status [--repo <o/r>] | plan <issue> --file <path> | ask <issue> --file <path> | approve <message-id> [--changes] [--file <path>] | answer <message-id> --file <path> | show <message-id> | start [--leader] | serve [--leader] | stop | allow <code> | deny <code> | accept <code> | confirm-leader | progress <issue> --step plan|code|review|merge [--branch <b>] [--head <sha40>] | owns <issue> | pushed <issue> --branch <b> --head <sha40>";
20
21
 
21
22
  function validAddress(address) {
22
23
  if (typeof address !== "string" || !address || address.trim() !== address || address === "0.0.0.0") return false;
@@ -59,7 +60,8 @@ export function validateFleet(value) {
59
60
  if (!Array.isArray(leaders) || !leaders.length || leaders.some(id => !seen.has(id)) || new Set(leaders).size !== leaders.length) throw new Error("leaders must be a nonempty list of unique node IDs");
60
61
  if (value.discover !== undefined && typeof value.discover !== "boolean") throw new Error("discover must be a boolean");
61
62
  if (value.discoveryPort !== undefined && (!Number.isInteger(value.discoveryPort) || value.discoveryPort < 1024 || value.discoveryPort > 65535)) throw new Error("discoveryPort must be an integer from 1024 to 65535");
62
- return { self: value.self, nodes, leaders: [...leaders], ...(value.secret === undefined ? {} : { secret: value.secret }),
63
+ const key = value.key === undefined ? undefined : validateKey(value.key);
64
+ return { ...(key === undefined ? {} : { key }), self: value.self, nodes, leaders: [...leaders], ...(value.secret === undefined ? {} : { secret: value.secret }),
63
65
  ...(value.discover === undefined ? {} : { discover: value.discover }),
64
66
  ...(value.discoveryPort === undefined && value.discover === undefined ? {} : { discoveryPort: value.discoveryPort ?? 47913 }) };
65
67
  }
@@ -138,6 +140,10 @@ export function freeIssues(repo, cwd, { gh = runGh, git = gitOut, holdLabel = "h
138
140
 
139
141
  function parseArgs(argv) {
140
142
  const [verb, ...args] = argv;
143
+ if (["allow", "deny", "accept"].includes(verb)) {
144
+ if (args.length !== 1 || !/^\d{6}$/.test(args[0])) throw new Error(`${verb} needs a 6-digit code`);
145
+ return { verb, code: args[0] };
146
+ }
141
147
  if (TALK_VERBS.includes(verb)) return parseTalkArgs(verb, args);
142
148
  const hasIssue = ["progress", "owns", "pushed"].includes(verb);
143
149
  const rest = hasIssue ? args.slice(1) : args;
@@ -195,8 +201,8 @@ function initialize(options, file, say) {
195
201
  Object.assign(node, { address: ipv6 ?? host, port: Number(port) });
196
202
  }
197
203
  }
198
- const secret = options["--secret"] ?? randomBytes(32).toString("hex");
199
- const fleet = validateFleet({ self, nodes, secret, ...(options["--nodes"] === undefined ? { discover: true } : {}) });
204
+ const secret = options["--secret"] ?? (options["--nodes"] === undefined ? undefined : randomBytes(32).toString("hex"));
205
+ const fleet = validateFleet({ self, nodes, secret, key: createKey(), ...(options["--nodes"] === undefined ? { discover: true } : {}) });
200
206
  mkdirSync(path.dirname(file), { recursive: true });
201
207
  let fd;
202
208
  try {
@@ -209,12 +215,21 @@ function initialize(options, file, say) {
209
215
  } finally {
210
216
  if (fd !== undefined) closeSync(fd);
211
217
  }
212
- say(`fleet initialized: ${file}`);
218
+ if (options["--nodes"] !== undefined) say(`fleet initialized: ${file}`);
213
219
  say(`fleet name: ${self}`);
214
- if (!options["--secret"]) say(`run on the other PCs: npx architecture-harness fleet init --secret ${secret}`);
220
+ if (options["--nodes"] !== undefined && !options["--secret"]) say(`run on the other PCs: npx architecture-harness fleet init --secret ${secret}`);
215
221
  return 0;
216
222
  }
217
223
 
224
+ export function saveFleet(file, value) {
225
+ let fd;
226
+ try {
227
+ fd = openSync(file, "w", 0o600);
228
+ if (process.platform !== "win32") fchmodSync(fd, 0o600);
229
+ writeFileSync(fd, `${JSON.stringify(value, null, 2)}\n`);
230
+ } finally { if (fd !== undefined) closeSync(fd); }
231
+ }
232
+
218
233
  /** Fleet verbs return exit codes; injected readers and node operations keep tests local. */
219
234
  export function runFleet(argv, { cwd = process.cwd(), env = process.env, gh = runGh, git, origin = originOf, say = console.log, warn = console.error, node = {} } = {}) {
220
235
  try {
@@ -229,8 +244,34 @@ export function runFleet(argv, { cwd = process.cwd(), env = process.env, gh = ru
229
244
  let value;
230
245
  try { value = JSON.parse(text); } catch { throw new Error(`fleet file has invalid JSON: ${file}`); }
231
246
  const configuredFleet = validateFleet(value);
247
+ if (["start", "serve"].includes(options.verb)) {
248
+ let changed = false;
249
+ if (!configuredFleet.key) { configuredFleet.key = createKey(); changed = true; }
250
+ if (configuredFleet.discover && !configuredFleet.secret && options["--leader"]) {
251
+ configuredFleet.secret = randomBytes(32).toString("hex");
252
+ changed = true;
253
+ }
254
+ if (changed) saveFleet(file, { ...value, ...configuredFleet });
255
+ }
232
256
  const fleet = effectiveFleet(configuredFleet, configuredFleet.discover ? readDiscovered(cwd, configuredFleet.secret) : {}, node.clock?.() ?? Date.now(), node.interfaces);
233
- if (options.verb === "status") say(`name=${fleet.self} discover=${fleet.discover ? "on" : "off"}`);
257
+ if (["allow", "deny", "accept"].includes(options.verb)) {
258
+ const joiner = !fleet.secret, leader = Boolean(fleet.secret && readState(cwd, "node").leader);
259
+ if (options.verb === "accept" ? !joiner : options.verb === "allow" ? !leader : !joiner && !leader) throw new Error("pairing command is not available for this role");
260
+ pairingDecision(cwd, options.verb, options.code, node.clock?.() ?? Date.now(), { joiner });
261
+ say(`${options.verb} ${options.code}`);
262
+ return 0;
263
+ }
264
+ if (options.verb === "status") {
265
+ say(`name=${fleet.self} discover=${fleet.discover ? "on" : "off"}`);
266
+ const now = node.clock?.() ?? Date.now(), pairing = readPairing(cwd);
267
+ const live = row => Number.isFinite(row.seen) && now >= row.seen && now - row.seen <= 600_000;
268
+ if (fleet.secret && readState(cwd, "node").leader) {
269
+ for (const [id, row] of Object.entries(pairing.requests)) if (live(row) && /^\d{6}$/.test(row.code ?? "")) say(`join? ${id} code=${row.code} host=${row.hostname} address=${row.address}`);
270
+ } else if (!fleet.secret) {
271
+ for (const [id, row] of Object.entries(pairing.offers)) if (live(row)) say(`joining ${id} code=${row.code}`);
272
+ }
273
+ if ((fleet.discover && !fleet.secret) || (!origin(cwd) && !options["--repo"])) return 0;
274
+ }
234
275
  if (["start", "stop", "serve"].includes(options.verb)) {
235
276
  return runNodeVerb(options, { root: cwd, fleet, configuredFleet, env, gh, git, origin, say, warn, node }).catch(error => { warn(error.message); return 1; });
236
277
  }
@@ -305,7 +346,7 @@ export function runFleet(argv, { cwd = process.cwd(), env = process.env, gh = ru
305
346
  }
306
347
 
307
348
  async function runNodeVerb(options, { root, fleet, configuredFleet, env, gh, git, origin, say, warn, node }) {
308
- const deps = { gh, git, ...node, root, fleet, configuredFleet, env, leader: options["--leader"] === true };
349
+ const deps = { gh, git, ...node, root, fleet, configuredFleet, env, fleetFile: fleetPath(env), leader: options["--leader"] === true };
309
350
  if (options.verb === "serve") {
310
351
  const kitRoot = fileURLToPath(new URL("../../../../", import.meta.url));
311
352
  const kit = gitOut(kitRoot, "rev-parse", "HEAD")?.trim() || null;
@@ -99,7 +99,7 @@ test("fleet settings accept optional secrets, ordered leaders and node endpoints
99
99
  ]) assert.throws(() => validateFleet({ ...old, ...changes }), new RegExp(field));
100
100
  });
101
101
 
102
- test("init accepts explicit secrets and addresses and generates a reusable secret by default", t => {
102
+ test("init accepts explicit secrets and addresses and generates a secret for static nodes", t => {
103
103
  const f = fixture(t);
104
104
  const args = ["init", "--self", "a1", "--nodes", "a1:1:L,b2:1:S"];
105
105
  const secret = "ab".repeat(32);
@@ -120,15 +120,19 @@ test("init accepts explicit secrets and addresses and generates a reusable secre
120
120
  const generated = f.run([...args, "--force"]);
121
121
  assert.equal(generated.code, 0);
122
122
  saved = JSON.parse(readFileSync(f.env.QC_FLEET_FILE, "utf8"));
123
- assert.match(saved.secret, /^[0-9a-f]{64}$/);
123
+ assert.match(saved.secret, /^[a-f0-9]{64}$/);
124
+ assert.ok(saved.key.public && saved.key.private);
125
+ assert.ok(generated.lines.includes(`fleet initialized: ${f.env.QC_FLEET_FILE}`));
126
+ assert.ok(generated.lines.includes("fleet name: a1"));
124
127
  const instruction = generated.lines.filter(line => line.includes(saved.secret));
125
128
  assert.equal(instruction.length, 1);
126
129
  assert.equal(instruction[0], `run on the other PCs: npx architecture-harness fleet init --secret ${saved.secret}`);
127
130
  assert.equal(f.run([...args, "--force"]).code, 0);
128
131
  assert.notEqual(JSON.parse(readFileSync(f.env.QC_FLEET_FILE, "utf8")).secret, saved.secret);
132
+ assert.notEqual(JSON.parse(readFileSync(f.env.QC_FLEET_FILE, "utf8")).key.public, saved.key.public);
129
133
  });
130
134
 
131
- test("init without flags chooses a random hex name, enables discovery and prints the shared secret command", t => {
135
+ test("init without flags chooses a random hex name, enables discovery and prints only its name", t => {
132
136
  const f = fixture(t);
133
137
  const result = f.run(["init"]);
134
138
  assert.equal(result.code, 0, result.errors.join("\n"));
@@ -137,16 +141,18 @@ test("init without flags chooses a random hex name, enables discovery and prints
137
141
  assert.equal(saved.discover, true);
138
142
  assert.deepEqual(saved.nodes.map(({ id, port, weight, maxSize }) => ({ id, port, weight, maxSize })),
139
143
  [{ id: saved.self, port: 8080, weight: 1, maxSize: "L" }]);
140
- assert.ok(result.lines.includes(`fleet name: ${saved.self}`));
141
- assert.ok(result.lines.includes(`run on the other PCs: npx architecture-harness fleet init --secret ${saved.secret}`));
144
+ assert.deepEqual(result.lines, [`fleet name: ${saved.self}`]);
145
+ assert.equal(saved.secret, undefined);
146
+ assert.ok(saved.key.public && saved.key.private);
147
+ const shared = "ab".repeat(32);
142
148
  const other = fixture(t);
143
- const joined = other.run(["init", "--secret", saved.secret, "--port", "9090", "--self", "custom"]);
149
+ const joined = other.run(["init", "--secret", shared, "--port", "9090", "--self", "custom"]);
144
150
  assert.equal(joined.code, 0, joined.errors.join("\n"));
145
151
  const second = JSON.parse(readFileSync(other.env.QC_FLEET_FILE, "utf8"));
146
152
  assert.equal(second.self, "custom");
147
- assert.equal(second.secret, saved.secret);
153
+ assert.equal(second.secret, shared);
148
154
  assert.equal(second.nodes[0].port, 9090);
149
- assert.ok(!joined.lines.join("\n").includes(saved.secret));
155
+ assert.ok(!joined.lines.join("\n").includes(shared));
150
156
  for (const port of ["1023", "65536", "1.5", "no"]) assert.equal(other.run(["init", "--force", "--port", port]).code, 1);
151
157
  const staticPeers = fixture(t);
152
158
  const rejected = staticPeers.run(["init", "--nodes", "peer:2:M"]);
@@ -166,7 +172,7 @@ test("validateFleet accepts optional discovery settings and rejects invalid type
166
172
 
167
173
  test("status and assignment use the discoveries saved on disk", async t => {
168
174
  const f = fixture(t);
169
- assert.equal(f.run(["init", "--self", "a1"]).code, 0);
175
+ assert.equal(f.run(["init", "--self", "a1", "--secret", "ab".repeat(32)]).code, 0);
170
176
  mkdirSync(stateDir(f.cwd), { recursive: true });
171
177
  const configured = JSON.parse(readFileSync(f.env.QC_FLEET_FILE, "utf8"));
172
178
  writeFileSync(path.join(stateDir(f.cwd), "discovered.json"), JSON.stringify({
@@ -332,7 +338,7 @@ test("init routes through qc from an empty folder, creates mode 0600 and refuses
332
338
 
333
339
  test("CLI starts, starts twice, reports running and stops without reading GitHub", async t => {
334
340
  const f = fixture(t), lines = [], errors = [];
335
- assert.equal(f.run(["init", "--self", "a1", "--nodes", "a1:1:L,b2:1:L", "--addresses", "a1@127.0.0.1:8080"]).code, 0);
341
+ assert.equal(f.run(["init", "--self", "a1", "--nodes", "a1:1:L,b2:1:L", "--addresses", "a1@127.0.0.1:8080", "--secret", "ab".repeat(32)]).code, 0);
336
342
  let live = false, spawns = 0, instance;
337
343
  const node = { spawn: (_command, _args, options) => { instance = options.env.QC_FLEET_INSTANCE; live = true; spawns++; return { pid: 45678, unref() {}, once() {} }; },
338
344
  kill: (_pid, signal) => { if (!live) throw Object.assign(new Error("gone"), { code: "ESRCH" }); if (signal !== 0) live = false; },
@@ -367,7 +373,7 @@ test("CLI starts, starts twice, reports running and stops without reading GitHub
367
373
 
368
374
  test("CLI serve runs the node loop and exits after an injected stop signal", async t => {
369
375
  const f = fixture(t);
370
- assert.equal(f.run(["init", "--self", "a1", "--nodes", "a1:1:L", "--addresses", "a1@127.0.0.1:8080"]).code, 0);
376
+ assert.equal(f.run(["init", "--self", "a1", "--nodes", "a1:1:L", "--addresses", "a1@127.0.0.1:8080", "--secret", "ab".repeat(32)]).code, 0);
371
377
  const signals = new Map();
372
378
  let started;
373
379
  const ready = new Promise(resolve => { started = resolve; });
@@ -558,7 +564,7 @@ test("status prints the pending Leader proposal", async t => {
558
564
 
559
565
  test("pushed requires owns and strict branch/head and sends the held epoch to the Leader", async t => {
560
566
  const f = fixture(t);
561
- f.run(["init", "--self", "a1", "--nodes", "a1:1:L,b2:1:L", "--addresses", "a1@localhost:8080,b2@localhost:8081"]);
567
+ f.run(["init", "--self", "a1", "--nodes", "a1:1:L,b2:1:L", "--addresses", "a1@localhost:8080,b2@localhost:8081", "--secret", "ab".repeat(32)]);
562
568
  const head = "b".repeat(40), sent = [];
563
569
  const deps = { origin: () => "o/r", gh: () => { throw new Error("pushed needs no gh"); }, node: {
564
570
  fetch: async (url, options) => { sent.push({ url, message: JSON.parse(options.body) }); return { status: 202 }; }
@@ -580,3 +586,62 @@ test("pushed requires owns and strict branch/head and sends the held epoch to th
580
586
  assert.equal(sent[0].message.kind, "pushed");
581
587
  assert.deepEqual(sent[0].message.body, { issue: 7, epoch: 2, branch: "feat/7", head });
582
588
  });
589
+
590
+ test("joiner deny ends its attempt while allow and a joined follower's deny stay unavailable", async t => {
591
+ const { createKey, createPairing, readPairing } = await import("./fleet-pair.mjs");
592
+ const f = fixture(t), now = 1_800_000_000_000, address = "127.0.0.1";
593
+ assert.equal(f.run(["init", "--self", "joiner"]).code, 0);
594
+ const fleet = JSON.parse(readFileSync(f.env.QC_FLEET_FILE, "utf8"));
595
+ const joining = createPairing({ root: f.cwd, fleet, address, clock: () => now });
596
+ const beacon = joining.beacon();
597
+ assert.equal(joining.receivePair({ kind: "offer", leader: "leader", commit: beacon.commit, pub: createKey().public,
598
+ nonce: "11".repeat(16), port: 8080, time: now }, address), true);
599
+ const code = readPairing(f.cwd).offers.leader.code;
600
+ assert.equal(f.run(["allow", code], { node: { clock: () => now } }).code, 1);
601
+ const denied = f.run(["deny", code], { node: { clock: () => now } });
602
+ assert.equal(denied.code, 0, denied.errors.join("\n"));
603
+ assert.deepEqual(denied.lines, [`deny ${code}`]);
604
+ assert.deepEqual(readPairing(f.cwd).offers, {});
605
+ assert.notEqual(joining.beacon().commit, beacon.commit);
606
+ writeFileSync(f.env.QC_FLEET_FILE, JSON.stringify({ ...fleet, secret: "ab".repeat(32) }));
607
+ assert.equal(f.run(["deny", code], { node: { clock: () => now } }).code, 1);
608
+ });
609
+
610
+ test("start migrates keys, leader creates secret, and pairing CLI and status share the state contract", async t => {
611
+ const { createKey, createPairing, readPairing } = await import("./fleet-pair.mjs");
612
+ const f = fixture(t), now = 1_800_000_000_000, address = "127.0.0.1";
613
+ assert.equal(f.run(["init", "--self", "leader"]).code, 0);
614
+ const old = JSON.parse(readFileSync(f.env.QC_FLEET_FILE, "utf8"));
615
+ delete old.key;
616
+ writeFileSync(f.env.QC_FLEET_FILE, JSON.stringify(old));
617
+ const child = { pid: 12345, once() {}, unref() {} };
618
+ let instance;
619
+ const result = await f.run(["start", "--leader"], { node: { clock: () => now,
620
+ interfaces: () => ({ lo: [{ family: "IPv4", internal: false, address }] }),
621
+ spawn: (_cmd, _args, options) => { instance = options.env.QC_FLEET_INSTANCE; return child; },
622
+ kill: () => {}, fetch: async () => ({ status: 200, json: async () => ({ ok: true, instance }) }) } });
623
+ assert.equal(result.code, 0, result.errors.join("\n"));
624
+ const saved = JSON.parse(readFileSync(f.env.QC_FLEET_FILE, "utf8"));
625
+ assert.ok(saved.key.public && saved.key.private);
626
+ assert.match(saved.secret, /^[a-f0-9]{64}$/);
627
+ const joinFleet = { self: "new-pc", key: createKey(), nodes: [{ id: "new-pc", port: 8081 }] };
628
+ const joining = createPairing({ root: f.cwd, fleet: joinFleet, address, clock: () => now,
629
+ fetch: async (_url, options) => { pairing.receivePair(JSON.parse(options.body), address); } });
630
+ const sent = [];
631
+ const pairing = createPairing({ root: f.cwd, fleet: saved, address, leader: () => true, clock: () => now,
632
+ fetch: async (_url, options) => { sent.push(JSON.parse(options.body)); } });
633
+ assert.equal(pairing.receiveJoin(joining.beacon(), address), true);
634
+ const pending = f.run(["status"], { origin: () => null, node: { clock: () => now } });
635
+ assert.equal(pending.lines.some(line => line.startsWith("join?")), false);
636
+ await pairing.tick();
637
+ assert.equal(joining.receivePair(sent[0], address), true);
638
+ const code = readPairing(f.cwd).requests["new-pc"].code;
639
+ const status = f.run(["status"], { origin: () => null, node: { clock: () => now } });
640
+ assert.equal(status.code, 0, status.errors.join("\n"));
641
+ assert.ok(status.lines.includes(`join? new-pc code=${code} host=${os.hostname()} address=${address}`));
642
+ assert.equal(f.run(["allow", code], { node: { clock: () => now } }).code, 0);
643
+ assert.equal(readPairing(f.cwd).requests["new-pc"].allowed, true);
644
+ assert.equal(f.run(["deny", code], { node: { clock: () => now } }).code, 0);
645
+ assert.equal(f.run(["allow", "123"], { node: { clock: () => now } }).code, 1);
646
+ assert.equal(f.run(["accept", code], { node: { clock: () => now } }).code, 1);
647
+ });