agent-dag 3.14.0 → 3.16.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,577 @@
1
+ // The sockets. Every decision this makes lives in lan-sync.mjs; what is here is
2
+ // the plumbing that decision layer refuses to own — a UDP socket that shouts,
3
+ // a TCP listener that answers, and the deadlines around both.
4
+ //
5
+ // TWO SOCKETS, AND NEITHER IS THE DECK'S HTTP SERVER. That server binds
6
+ // 127.0.0.1 and stays there. It has a mutation guard that deliberately trusts a
7
+ // request carrying no Origin header, so that hook.js and curl keep working —
8
+ // correct on loopback, and total exposure the moment the same server answers
9
+ // the network. So this feature never asks anybody to run `--host`: it opens its
10
+ // own listener, that listener speaks one protocol and nothing else, and it
11
+ // refuses every frame from anybody who has not proved they hold the group
12
+ // passphrase.
13
+ //
14
+ // DISCOVERY IS BROADCAST ON A FIXED PORT; THE SYNC LISTENER IS EPHEMERAL and
15
+ // says its port in the beacon. One fixed port rather than two is one thing to
16
+ // collide with, one firewall dialog, and one number in a support answer.
17
+ //
18
+ // A DECK HEARS ITSELF. Measured, not assumed: a broadcast to 255.255.255.255
19
+ // comes back to every socket on the sending machine bound to that port, from
20
+ // the machine's own LAN address rather than from loopback. That is what makes
21
+ // two decks on one machine find each other — which is how this gets tested at
22
+ // all — and it is why self-recognition is by fingerprint rather than by
23
+ // address.
24
+ import dgram from "node:dgram";
25
+ import net from "node:net";
26
+ import { randomBytes } from "node:crypto";
27
+ import {
28
+ beaconPayload, beaconVerdict, handshakeTranscript, notePeer, proof, proofOk,
29
+ inviteProof, readBeacon, readPub, sessionKey, trustedPeer,
30
+ ANNOUNCE_MS, MAX_BEACON_BYTES, MAX_MANIFEST_BYTES,
31
+ } from "./lan-sync.mjs";
32
+
33
+ /** The one fixed port in the feature. Out of the deck's HTTP range (4317-4400)
34
+ * so a beacon can never be mistaken for a deck's own traffic, and unassigned:
35
+ * 45317 reads as "4317, elsewhere", which is what a person tracing this in a
36
+ * firewall log needs it to say. */
37
+ export const DISCOVERY_PORT = 45_317;
38
+
39
+ /** How long a connection has to finish the handshake before it is dropped. A
40
+ * handshake is two round trips on a local network — single-digit
41
+ * milliseconds — so five seconds is generous for a slow machine and short
42
+ * enough that holding sockets open costs an attacker something. */
43
+ export const HANDSHAKE_MS = 5_000;
44
+
45
+ /** The most one frame may be, and the most a peer may hold open.
46
+ *
47
+ * Frames are JSON lines. The largest legitimate one is a manifest; the cap is
48
+ * an order of magnitude over the biggest real store, and the buffer is
49
+ * ABANDONED rather than grown past it — a socket that keeps sending without a
50
+ * newline is trying to make this allocate, and the answer is to stop reading
51
+ * rather than to read faster. */
52
+ export const MAX_FRAME_BYTES = MAX_MANIFEST_BYTES;
53
+
54
+ /** Concurrent connections from all peers together. Small on purpose: the real
55
+ * number is one per peer per minute, and anything above this is either a bug
56
+ * in a peer or somebody holding sockets open to see what happens. */
57
+ export const MAX_SOCKETS = 16;
58
+
59
+ /** The shortest gap between two "I am here too" replies to a stranger. Long
60
+ * enough that a burst of decks starting together cannot make a storm, short
61
+ * enough that starting two decks by hand feels instant. */
62
+ export const REPLY_COOLDOWN_MS = 2_000;
63
+
64
+ /**
65
+ * The shouting half.
66
+ *
67
+ * `reuseAddr` is not a convenience: without it a second deck on the same
68
+ * machine cannot bind the discovery port at all, and two decks on one machine
69
+ * is both a real setup and the only way this gets tested here.
70
+ *
71
+ * Errors are reported, never thrown. A machine with no route, a firewall that
72
+ * refuses the bind, an interface that comes and goes with a VPN — none of them
73
+ * is a reason for the deck to fall over, and all of them are reasons for the
74
+ * panel to be able to say what happened.
75
+ */
76
+ export function createBeacon({
77
+ port, name, fp, onPeer, onStranger, onError, onIdClash, now = Date.now,
78
+ /** The decks somebody has accepted, read fresh each packet so an accept takes
79
+ * effect immediately rather than at the next restart. */
80
+ trusted = () => [],
81
+ // Injected so the suite can drive this with a socket it controls. CI runners
82
+ // are not a network: GitHub's have no broadcast domain worth the name, and a
83
+ // test that quietly skipped there would be a test that stopped testing
84
+ // without saying so. The REAL socket is exercised by hand, two decks on one
85
+ // machine, which works because a broadcast comes back to its own host.
86
+ createSocket = opts => dgram.createSocket(opts),
87
+ } = {}) {
88
+ // Randomised per process. Two beacons from one fingerprint with different
89
+ // instance ids mean the deck restarted between them, which is the signal to
90
+ // drop any session held for it rather than resume into a process that is gone.
91
+ const instance = randomBytes(8).toString("hex");
92
+ const peers = new Map();
93
+ let sock = null;
94
+ let timer = null;
95
+ /** When this deck last answered a deck it had not heard, so answering cannot
96
+ * become a storm, and which decks it has already answered — without the
97
+ * second, a deck that is never accepted is answered again on every packet
98
+ * for as long as both are running. */
99
+ let repliedAt = 0;
100
+ const answered = new Set();
101
+
102
+ const payload = () => Buffer.from(JSON.stringify(beaconPayload({ name, fp, port, instance })));
103
+
104
+ const announce = () => {
105
+ if (!sock) return;
106
+ // 255.255.255.255 rather than a multicast group, and rather than the
107
+ // subnet's own broadcast address. The subnet-directed form needs the
108
+ // netmask of whichever interface the packet leaves by, which changes when a
109
+ // VPN comes up; the limited broadcast needs nothing and is what Syncthing
110
+ // sends for the same reason.
111
+ sock.send(payload(), DISCOVERY_PORT, "255.255.255.255", err => {
112
+ // ENETUNREACH and EACCES are what a machine with no network, or a
113
+ // firewall, says. Both are states the panel reports rather than crashes.
114
+ if (err) onError?.("announce", err);
115
+ });
116
+ };
117
+
118
+ const start = () => new Promise(resolve => {
119
+ sock = createSocket({ type: "udp4", reuseAddr: true });
120
+ sock.on("error", err => { onError?.("socket", err); });
121
+ sock.on("message", (msg, rinfo) => {
122
+ // Everything about whether to care lives in lan-sync.mjs. This hands it
123
+ // the bytes and the address and does what it is told.
124
+ if (msg.length > MAX_BEACON_BYTES) return;
125
+ const beacon = readBeacon(msg);
126
+ const verdict = beaconVerdict(beacon, { selfFp: fp, selfInstance: instance, trusted: trusted() });
127
+ // ANSWER A DECK WE HAVE NEVER HEARD, once, WHOEVER IT IS — and that last
128
+ // part is the change. It used to answer only a deck already in the group,
129
+ // which was fine when a group existed. Now the first thing a new deck has
130
+ // to become is a row on somebody's screen, and it cannot become one if
131
+ // this deck never tells it that it exists.
132
+ //
133
+ // Measured on two real decks before any of this: deck 1 saw deck 2 the
134
+ // instant it started and deck 2 saw nobody, because deck 1's own
135
+ // immediate announce went out before deck 2 was listening. Thirty seconds
136
+ // of an empty list is how a working feature reads as broken.
137
+ //
138
+ // At most once every few seconds, because the obvious version is a shout
139
+ // storm: two decks answering each other's answers forever. A new pair
140
+ // converges in two extra packets.
141
+ const newToUs = beacon && verdict !== "self" && verdict !== "id-clash" && verdict !== "unreadable"
142
+ && !peers.has(beacon.fp) && !answered.has(beacon.fp);
143
+ if (newToUs && now() - repliedAt > REPLY_COOLDOWN_MS) {
144
+ repliedAt = now();
145
+ answered.add(beacon.fp);
146
+ announce();
147
+ }
148
+ if (verdict !== "peer") {
149
+ // Another deck is using this one's key — see beaconVerdict. Reported
150
+ // rather than fixed here: this file carries packets, and choosing a new
151
+ // identity for the deck belongs to whoever stores it.
152
+ if (verdict === "id-clash") onIdClash?.();
153
+ // A DECK NOBODY HAS ACCEPTED. It is not refused and not silently
154
+ // dropped: it is a name and an address on the same network, which is a
155
+ // row somebody can accept. Nothing is asked of it and nothing is
156
+ // offered to it until they do.
157
+ if (verdict === "stranger") {
158
+ onStranger?.({ fp: beacon.fp, name: beacon.name, addr: rinfo.address, port: beacon.port, at: now() });
159
+ }
160
+ return;
161
+ }
162
+ const noted = notePeer(peers, beacon, rinfo.address, now());
163
+ if (noted.changed || noted.restarted) onPeer?.(noted);
164
+ });
165
+ sock.bind(DISCOVERY_PORT, "0.0.0.0", () => {
166
+ try { sock.setBroadcast(true); } catch (err) { onError?.("broadcast", err); }
167
+ // Immediately, not on the next tick. Syncthing's rule: a deck that just
168
+ // came up should appear now rather than up to thirty seconds later, which
169
+ // is the difference between "it works" and "it seems broken" for anybody
170
+ // who starts two decks and watches.
171
+ announce();
172
+ timer = setInterval(announce, ANNOUNCE_MS);
173
+ timer.unref?.();
174
+ resolve();
175
+ });
176
+ });
177
+
178
+ return {
179
+ start,
180
+ announce,
181
+ peers,
182
+ stop() {
183
+ if (timer) clearInterval(timer);
184
+ timer = null;
185
+ try { sock?.close(); } catch { /* already closed */ }
186
+ sock = null;
187
+ },
188
+ };
189
+ }
190
+
191
+ /**
192
+ * Read newline-delimited JSON off a socket, refusing to be made to allocate.
193
+ *
194
+ * The cap is on the UNTERMINATED buffer rather than on a frame that arrived,
195
+ * which is the distinction that matters: a peer that sends a megabyte with no
196
+ * newline in it is not sending a large frame, it is sending nothing at all,
197
+ * expensively. Past the cap this stops reading and hands the caller a refusal
198
+ * — it does not keep buffering in the hope a newline turns up.
199
+ */
200
+ export function frameReader(onFrame, onRefuse, max = MAX_FRAME_BYTES) {
201
+ let buf = "";
202
+ let dead = false;
203
+ return chunk => {
204
+ if (dead) return;
205
+ buf += chunk;
206
+ if (buf.length > max) { dead = true; buf = ""; onRefuse("frame too large"); return; }
207
+ let i;
208
+ while ((i = buf.indexOf("\n")) !== -1) {
209
+ const line = buf.slice(0, i);
210
+ buf = buf.slice(i + 1);
211
+ if (!line.trim()) continue;
212
+ let msg;
213
+ try { msg = JSON.parse(line); }
214
+ catch { dead = true; buf = ""; onRefuse("not json"); return; }
215
+ // `typeof [] === "object"`, so an array walks straight past the obvious
216
+ // check and reaches a handler that reads `msg.t` off it — undefined, and
217
+ // then whatever that handler does with a frame that has no type. A frame
218
+ // is a record; anything else is refused.
219
+ if (!msg || typeof msg !== "object" || Array.isArray(msg)) {
220
+ dead = true; buf = ""; onRefuse("not an object"); return;
221
+ }
222
+ onFrame(msg);
223
+ if (dead) return;
224
+ }
225
+ };
226
+ }
227
+
228
+ /** One line out. Kept in one place so nothing forgets the newline the reader
229
+ * above is waiting for. */
230
+ export function sendFrame(sock, obj) {
231
+ try { sock.write(`${JSON.stringify(obj)}\n`); } catch { /* peer went away */ }
232
+ }
233
+
234
+ /**
235
+ * The answering half.
236
+ *
237
+ * WHAT IT DOES BEFORE IT KNOWS WHO IS CALLING, in order, and the order is the
238
+ * whole security argument: accept, arm a deadline, read at most one frame, and
239
+ * check a proof. No manifest, no account, no store read, nothing that touches
240
+ * claude-swap, until `authed` is true. KDE Connect's CVE-2020-26164 was several
241
+ * issues in a daemon whose protocol was fine, and this is the shape that
242
+ * lesson has.
243
+ *
244
+ * `handlers` is called only with authenticated frames, and it never sees the
245
+ * handshake at all.
246
+ */
247
+ export function createSyncServer({
248
+ fp, pub, name, secret, handlers, onError, host = "0.0.0.0", prefer = 0,
249
+ /** The peers somebody has accepted, read fresh on every connection so an
250
+ * accept takes effect on the next one rather than on the next restart. */
251
+ trusted = () => [],
252
+ /** A deck we have never been told to trust, which finished the handshake and
253
+ * is therefore a real deck rather than a port scan. The panel turns this
254
+ * into a row with an accept on it. */
255
+ onPending,
256
+ /** The invite this deck is currently offering, or null. A caller that proves
257
+ * it holds the code is somebody the owner handed a token to, so it is paired
258
+ * on arrival rather than queued behind a press. */
259
+ invite = () => null,
260
+ /** One was used. The caller stores the pairing and retires the invite: a
261
+ * token that pairs twice is a token worth stealing twice. */
262
+ onInviteUsed,
263
+ } = {}) {
264
+ let server = null;
265
+ const live = new Set();
266
+
267
+ const onConnection = sock => {
268
+ if (!secret || live.size >= MAX_SOCKETS) { sock.destroy(); return; }
269
+ live.add(sock);
270
+ sock.setEncoding("utf8");
271
+ sock.setNoDelay(true);
272
+
273
+ let authed = false;
274
+ let peerFp = null;
275
+ let peerPub = null;
276
+ let peerName = "";
277
+ let peerPort = null;
278
+ let key = null;
279
+ const myChallenge = randomBytes(16).toString("hex");
280
+ let theirChallenge = null;
281
+
282
+ // Armed before the first byte is read, and cleared only by a completed
283
+ // handshake. A socket that connects and says nothing is the cheapest
284
+ // possible way to hold a resource, so it is also the first one closed.
285
+ const deadline = setTimeout(() => { if (!authed) sock.destroy(); }, HANDSHAKE_MS);
286
+ deadline.unref?.();
287
+
288
+ const done = () => { clearTimeout(deadline); live.delete(sock); };
289
+ sock.on("close", done);
290
+ sock.on("error", err => { done(); onError?.("peer", err); });
291
+
292
+ /**
293
+ * Refuse, and SAY SO, which cost two people twenty minutes.
294
+ *
295
+ * This used to destroy the socket without a word, so the caller's only
296
+ * evidence was `peer closed the connection` — true, and useless. Every
297
+ * reason here is a different problem with a different fix, and the caller
298
+ * cannot tell them apart from the outside.
299
+ *
300
+ * It leaks nothing an attacker did not have. "I do not know you" is what
301
+ * the silent close already said, and the fingerprints involved are in every
302
+ * beacon this deck broadcasts.
303
+ *
304
+ * DESTROY, NOT END, and the difference is a caller that never reads. `end`
305
+ * is a FIN, and a peer whose socket is paused — connected, refusing to
306
+ * read, which is exactly the shape of a caller trying to cost something —
307
+ * never notices a FIN and holds the socket open. The callback orders the
308
+ * two: destroying before the write flushes would throw away the sentence
309
+ * that is the whole point. The timer is the backstop for a peer whose
310
+ * receive window is full and whose callback therefore never comes.
311
+ */
312
+ const refuse = why => {
313
+ onError?.("frame", new Error(why));
314
+ const bye = () => { try { sock.destroy(); } catch { /* already gone */ } };
315
+ try { sock.write(`${JSON.stringify({ t: "no", why })}\n`, bye); }
316
+ catch { bye(); return; }
317
+ setTimeout(bye, 250).unref?.();
318
+ };
319
+
320
+ sock.on("data", frameReader(msg => {
321
+ if (!authed) {
322
+ // FOUR MESSAGES, and the order is chosen so that a stranger who merely
323
+ // connects receives nothing derived from a key.
324
+ //
325
+ // 1. caller -> hello, its fingerprint, its public key, a challenge
326
+ // 2. us -> challenge, ours, and a random number
327
+ // 3. caller -> auth, a proof over the whole transcript
328
+ // 4. us -> ok, our name, and our proof over the same
329
+ //
330
+ // BOTH PUBLIC KEYS TRAVEL IN THE CLEAR and that is fine: a public key
331
+ // is public, and the fingerprint in the beacon is a hash of this exact
332
+ // value. What the exchange establishes is that whoever is on the other
333
+ // end holds the private half of the key they claimed — which is the
334
+ // only thing a pin can later be checked against.
335
+ if (msg.t === "hello") {
336
+ if (theirChallenge || typeof msg.challenge !== "string") return refuse("bad hello");
337
+ const them = readPub(msg.pub);
338
+ // The fingerprint is a hash of the key, so a hello whose two halves
339
+ // disagree is not a deck with a stale field, it is somebody trying to
340
+ // be announced as one deck and prove they are another.
341
+ if (!them || them.fp !== msg.fp) return refuse("bad hello");
342
+ theirChallenge = msg.challenge;
343
+ peerFp = them.fp;
344
+ peerPub = them.pub;
345
+ peerName = typeof msg.name === "string" ? msg.name : "";
346
+ peerPort = Number.isInteger(msg.port) && msg.port > 0 && msg.port < 65_536 ? msg.port : null;
347
+ key = sessionKey(secret, peerPub, handshakeTranscript(peerFp, fp, theirChallenge, myChallenge));
348
+ sendFrame(sock, { t: "challenge", fp, pub, name, challenge: myChallenge });
349
+ return;
350
+ }
351
+ if (msg.t !== "auth" || !theirChallenge) return refuse("expected auth");
352
+ const want = proof(key, {
353
+ challenge: theirChallenge, peerChallenge: myChallenge,
354
+ fromFp: peerFp, toFp: fp, direction: "hello",
355
+ });
356
+ // A recording of a previous exchange fails here, because `myChallenge`
357
+ // was made when this socket opened and has never been sent before.
358
+ if (!proofOk(want, msg.proof)) return refuse("bad proof");
359
+
360
+ // WHO IS THIS, and it is the only question left. The handshake proves
361
+ // they hold the key they claimed; the trusted list says whether anybody
362
+ // here ever agreed to talk to it.
363
+ const known = trustedPeer(trusted(), peerFp);
364
+ if (known && known.pub !== peerPub) {
365
+ // The fingerprint we pinned, presented with a different key. 48 bits
366
+ // is far past accident, so this is somebody wearing a paired deck's
367
+ // name — refused loudly rather than quietly re-pinned.
368
+ return refuse("impostor");
369
+ }
370
+ if (!known) {
371
+ // AN INVITE THIS DECK HANDED OUT, PRESENTED BACK. Whoever is calling
372
+ // holds a token the owner of this machine copied and sent, which is
373
+ // the same decision the accept button is — made earlier, and made
374
+ // once. So there is nothing to press: the deck is pinned here.
375
+ //
376
+ // The proof is over the transcript, so it is worth nothing to
377
+ // somebody who recorded an earlier exchange, and the code itself
378
+ // never travels.
379
+ const live = invite();
380
+ if (live && typeof msg.invite === "string") {
381
+ const want = inviteProof(live.code, handshakeTranscript(peerFp, fp, theirChallenge, myChallenge));
382
+ if (proofOk(want, msg.invite)) {
383
+ onInviteUsed?.({ fp: peerFp, pub: peerPub, name: peerName, port: peerPort,
384
+ addr: sock.remoteAddress?.replace(/^::ffff:/, "") ?? "" });
385
+ authed = true;
386
+ clearTimeout(deadline);
387
+ sendFrame(sock, {
388
+ t: "ok", fp, name,
389
+ proof: proof(key, {
390
+ challenge: myChallenge, peerChallenge: theirChallenge,
391
+ fromFp: fp, toFp: peerFp, direction: "reply",
392
+ }),
393
+ });
394
+ return;
395
+ }
396
+ }
397
+ // A REAL DECK WE HAVE NOT MET. It finished a handshake, so it is not
398
+ // a port scan, and it told us a name and an address a person can
399
+ // recognise. That is a row with an accept on it, and nothing else
400
+ // happens until somebody presses it.
401
+ onPending?.({
402
+ fp: peerFp, pub: peerPub, name: peerName,
403
+ addr: sock.remoteAddress?.replace(/^::ffff:/, "") ?? "",
404
+ // Where it LISTENS, from the hello — not this socket's remote port,
405
+ // which is ephemeral. This is what lets an accept dial back.
406
+ port: peerPort,
407
+ });
408
+ return refuse("pending");
409
+ }
410
+
411
+ authed = true;
412
+ clearTimeout(deadline);
413
+ // And ours, so the caller knows it reached the deck it pinned rather
414
+ // than something standing in the way of one.
415
+ sendFrame(sock, {
416
+ t: "ok", fp, name,
417
+ proof: proof(key, {
418
+ challenge: myChallenge, peerChallenge: theirChallenge,
419
+ fromFp: fp, toFp: peerFp, direction: "reply",
420
+ }),
421
+ });
422
+ return;
423
+ }
424
+ handlers?.(msg, { sock, peerFp, key, send: obj => sendFrame(sock, obj) });
425
+ }, refuse));
426
+ };
427
+
428
+ return {
429
+ /**
430
+ * Listen, on the same port as last time when that is still possible.
431
+ *
432
+ * IT ASKED FOR PORT 0 EVERY TIME, and the reasoning was sound in isolation:
433
+ * the beacon carries whichever port the OS picked, so nothing needs a fixed
434
+ * one and a fixed one is a thing to collide with. But the beacon is exactly
435
+ * what does not arrive when this feature is hardest to set up — a router
436
+ * or a firewall in the way is the whole reason the panel has an address
437
+ * field — and then the address somebody typed on the other machine stopped
438
+ * working the next time this deck restarted, with `handshake timed out` and
439
+ * nothing to say the port had simply moved.
440
+ *
441
+ * So the caller keeps one and hands it back, and a port already taken falls
442
+ * straight through to 0 rather than refusing to start. The pin is a
443
+ * preference, never a requirement.
444
+ */
445
+ start: () => new Promise((resolve, reject) => {
446
+ const wanted = Number.isInteger(prefer) && prefer > 0 && prefer < 65_536 ? prefer : 0;
447
+ let retried = wanted === 0;
448
+ server = net.createServer(onConnection);
449
+ server.on("error", err => {
450
+ if (!retried) {
451
+ // Somebody else has it — another deck on this machine, or something
452
+ // unrelated. The pin is not worth failing to start over.
453
+ retried = true;
454
+ onError?.("listen", err);
455
+ try { server.listen(0, host, () => resolve(server.address().port)); } catch { reject(err); }
456
+ return;
457
+ }
458
+ onError?.("listen", err);
459
+ reject(err);
460
+ });
461
+ server.listen(wanted, host, () => resolve(server.address().port));
462
+ }),
463
+ port: () => server?.address()?.port ?? null,
464
+ stop() {
465
+ for (const s of live) s.destroy();
466
+ live.clear();
467
+ try { server?.close(); } catch { /* not listening */ }
468
+ server = null;
469
+ },
470
+ };
471
+ }
472
+
473
+ /**
474
+ * The calling half: connect, prove, be proved to, then talk.
475
+ *
476
+ * BOTH SIDES PROVE, and the second half is the one that is easy to skip. A
477
+ * handshake where only the caller proves itself stops a stranger reading a
478
+ * manifest and stops nothing else — a stranger can still stand up a listener on
479
+ * the announced port, wait for a real deck to dial it, and be handed whatever
480
+ * that deck was going to say. So this checks the reply with the same care the
481
+ * server checks the hello, and gives up if it does not hold.
482
+ */
483
+ export function connectToPeer({
484
+ host, port, fp, pub, secret, name, myPort = null, code = null, timeoutMs = HANDSHAKE_MS,
485
+ /** The public key we pinned for this deck the first time, or null for a deck
486
+ * we are meeting — an address somebody typed. */
487
+ expectPub = null,
488
+ }) {
489
+ return new Promise((resolve, reject) => {
490
+ const myChallenge = randomBytes(16).toString("hex");
491
+ const sock = net.createConnection({ host, port });
492
+ sock.setEncoding("utf8");
493
+ let settled = false;
494
+ const fail = err => {
495
+ if (settled) return;
496
+ settled = true;
497
+ sock.destroy();
498
+ reject(err instanceof Error ? err : new Error(String(err)));
499
+ };
500
+ const timer = setTimeout(() => fail(new Error("handshake timed out")), timeoutMs);
501
+ timer.unref?.();
502
+
503
+ sock.on("error", fail);
504
+ sock.on("close", () => fail(new Error("peer closed the connection")));
505
+ sock.on("connect", () => {
506
+ // No proof in the hello: the caller cannot cover a challenge it has not
507
+ // been given, and a proof over an empty one would be a proof that means
508
+ // nothing. It goes in message three.
509
+ // `port` is where WE listen, which is not the port this socket came from
510
+ // — that one is ephemeral and useless to dial. Without it a deck can
511
+ // accept an incoming request and still have no way to reach back, so the
512
+ // pairing is mutual on paper and one-way in fact.
513
+ sendFrame(sock, { t: "hello", fp, pub, name, port: myPort, challenge: myChallenge });
514
+ });
515
+
516
+ let theirChallenge = null;
517
+ let theirFp = null;
518
+ let theirPub = null;
519
+ let key = null;
520
+ sock.on("data", frameReader(msg => {
521
+ if (settled) return;
522
+ // A deck that heard us and said no. Each reason is a different problem
523
+ // with a different fix, and until this frame existed they were all one
524
+ // silent close that read as a firewall.
525
+ if (msg.t === "no") {
526
+ return fail(new Error({
527
+ pending: "waiting for the other deck to accept this one",
528
+ impostor: "that deck has this one pinned under a different key",
529
+ "bad proof": "the other deck refused this one's proof",
530
+ }[msg.why] ?? "the other deck refused this handshake"));
531
+ }
532
+ if (msg.t === "challenge") {
533
+ if (theirFp || typeof msg.challenge !== "string") return fail(new Error("bad challenge"));
534
+ const them = readPub(msg.pub);
535
+ if (!them || them.fp !== msg.fp) return fail(new Error("bad challenge"));
536
+ // THE PIN, CHECKED BEFORE ANYTHING ELSE. A deck we have paired with is
537
+ // this key and no other; a key that does not match is not a peer whose
538
+ // details changed, it is a different machine at the same address.
539
+ if (expectPub && expectPub !== them.pub) {
540
+ return fail(new Error("a different deck is answering at that address"));
541
+ }
542
+ theirChallenge = msg.challenge;
543
+ theirFp = them.fp;
544
+ theirPub = them.pub;
545
+ key = sessionKey(secret, theirPub, handshakeTranscript(fp, theirFp, myChallenge, theirChallenge));
546
+ sendFrame(sock, {
547
+ t: "auth",
548
+ proof: proof(key, {
549
+ challenge: myChallenge, peerChallenge: theirChallenge,
550
+ fromFp: fp, toFp: theirFp, direction: "hello",
551
+ }),
552
+ // Only when joining on an invite. Sent in the same frame as the
553
+ // session proof so a deck that holds a token is paired in one round
554
+ // trip rather than being queued behind somebody else's press.
555
+ ...(code ? { invite: inviteProof(code, handshakeTranscript(fp, theirFp, myChallenge, theirChallenge)) } : {}),
556
+ });
557
+ return;
558
+ }
559
+ // The same deck that gave us the challenge, or nothing: a reply naming a
560
+ // different fingerprint is a second party in the middle of this.
561
+ if (msg.t !== "ok" || msg.fp !== theirFp) return fail(new Error("expected ok"));
562
+ const want = proof(key, {
563
+ challenge: theirChallenge, peerChallenge: myChallenge,
564
+ fromFp: theirFp, toFp: fp, direction: "reply",
565
+ });
566
+ if (!proofOk(want, msg.proof)) return fail(new Error("that deck could not prove its own key"));
567
+ settled = true;
568
+ clearTimeout(timer);
569
+ sock.removeAllListeners("close");
570
+ resolve({
571
+ sock, key,
572
+ peerFp: theirFp, peerPub: theirPub, peerName: msg.name,
573
+ send: obj => sendFrame(sock, obj),
574
+ });
575
+ }, fail));
576
+ });
577
+ }