@johnhenry/browsermesh-apps 0.0.0 → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@johnhenry/browsermesh-apps",
3
- "version": "0.0.0",
3
+ "version": "0.1.0",
4
4
  "description": "Application layer: marketplace, chat, payments, compute, orchestration, and agent tools for BrowserMesh",
5
5
  "type": "module",
6
6
  "main": "./src/index.mjs",
package/src/payments.mjs CHANGED
@@ -53,6 +53,67 @@ function generateEscrowId() {
53
53
  return `esc_${Date.now().toString(36)}_${(++_escrowSeq).toString(36)}`;
54
54
  }
55
55
 
56
+ // ---------------------------------------------------------------------------
57
+ // Signature helpers
58
+ // ---------------------------------------------------------------------------
59
+ //
60
+ // PaymentChannel accepts an injected signFn/verifyFn pair rather than
61
+ // hardcoding a crypto mechanism, so callers can wire a real
62
+ // MeshIdentityManager (see @johnhenry/browsermesh-core's identity.mjs)
63
+ // in without this published, general-purpose package taking a hard
64
+ // dependency on it. Shape matches peer-chat.mjs's convention:
65
+ // signFn: async (data: Uint8Array) => Uint8Array
66
+ // verifyFn: async (pubKey: Uint8Array, data: Uint8Array, sig: Uint8Array) => boolean
67
+
68
+ /**
69
+ * Encode a Uint8Array to a base64 string.
70
+ * Falls back to manual encoding when btoa is unavailable (Node tests).
71
+ *
72
+ * @param {Uint8Array} bytes
73
+ * @returns {string}
74
+ */
75
+ function bytesToBase64(bytes) {
76
+ if (typeof btoa === 'function') {
77
+ let binary = '';
78
+ for (let i = 0; i < bytes.length; i++) binary += String.fromCharCode(bytes[i]);
79
+ return btoa(binary);
80
+ }
81
+ if (typeof Buffer !== 'undefined') {
82
+ return Buffer.from(bytes).toString('base64');
83
+ }
84
+ throw new Error('No base64 encoder available');
85
+ }
86
+
87
+ /**
88
+ * Decode a base64 string to a Uint8Array.
89
+ *
90
+ * @param {string} b64
91
+ * @returns {Uint8Array}
92
+ */
93
+ function base64ToBytes(b64) {
94
+ if (typeof atob === 'function') {
95
+ const binary = atob(b64);
96
+ const bytes = new Uint8Array(binary.length);
97
+ for (let i = 0; i < binary.length; i++) bytes[i] = binary.charCodeAt(i);
98
+ return bytes;
99
+ }
100
+ if (typeof Buffer !== 'undefined') {
101
+ return new Uint8Array(Buffer.from(b64, 'base64'));
102
+ }
103
+ throw new Error('No base64 decoder available');
104
+ }
105
+
106
+ /**
107
+ * Canonical bytes for a plain fields object, used as the signing/verification
108
+ * payload for both PaymentUpdate and close claims/acks.
109
+ *
110
+ * @param {object} fields
111
+ * @returns {Uint8Array}
112
+ */
113
+ function canonicalBytes(fields) {
114
+ return new TextEncoder().encode(JSON.stringify(fields));
115
+ }
116
+
56
117
  // ---------------------------------------------------------------------------
57
118
  // LedgerEntry typedef
58
119
  // ---------------------------------------------------------------------------
@@ -258,6 +319,52 @@ export class CreditLedger {
258
319
  * @property {number} closedAt
259
320
  */
260
321
 
322
+ // ---------------------------------------------------------------------------
323
+ // CloseClaim / CloseAck typedefs (two-phase mutual close)
324
+ // ---------------------------------------------------------------------------
325
+
326
+ /**
327
+ * Signed claim produced by the initiator of a mutual close. Sent to the
328
+ * counterparty, which must verify it and cross-check its own ledger state
329
+ * before co-signing an ack (see PaymentChannel#handleCloseMessage).
330
+ *
331
+ * @typedef {object} CloseClaim
332
+ * @property {string} channelId
333
+ * @property {number} finalLocalBalance - Initiator's claimed final balance
334
+ * @property {number} finalRemoteBalance - Counterparty's claimed final balance
335
+ * @property {number} entryCount
336
+ * @property {number} closedAt
337
+ * @property {string} signature - base64-encoded signature over the fields above
338
+ */
339
+
340
+ /**
341
+ * Signed acknowledgement of a CloseClaim, produced by the counterparty once
342
+ * it has verified the claim and confirmed it matches its own local ledger.
343
+ * Echoes the claim's fields (co-signed) so the initiator can finalize.
344
+ *
345
+ * @typedef {object} CloseAck
346
+ * @property {string} channelId
347
+ * @property {number} finalLocalBalance
348
+ * @property {number} finalRemoteBalance
349
+ * @property {number} entryCount
350
+ * @property {number} closedAt
351
+ * @property {string} signature - base64-encoded signature, by the counterparty
352
+ */
353
+
354
+ /**
355
+ * Raised when a close claim or ack fails signature verification, or its
356
+ * balances don't match the receiving side's own local ledger state --
357
+ * i.e. the counterparty is claiming a settlement this side doesn't agree to.
358
+ *
359
+ * @typedef {object} PaymentDispute
360
+ * @property {string} channelId
361
+ * @property {'invalid-signature'|'balance-mismatch'|'invalid-ack-signature'|'ack-mismatch'} reason
362
+ * @property {object} evidence - The claim or ack that triggered the dispute
363
+ * @property {number} localBalance - This side's local balance at dispute time
364
+ * @property {number} remoteBalance - This side's remote balance at dispute time
365
+ * @property {number} raisedAt
366
+ */
367
+
261
368
  // ---------------------------------------------------------------------------
262
369
  // PaymentChannel
263
370
  // ---------------------------------------------------------------------------
@@ -305,12 +412,38 @@ export class PaymentChannel {
305
412
  /** @type {number} */
306
413
  #sequence = 0;
307
414
 
415
+ /** @type {((data: Uint8Array) => Promise<Uint8Array>)|null} */
416
+ #signFn;
417
+
418
+ /** @type {((pubKey: Uint8Array, data: Uint8Array, sig: Uint8Array) => Promise<boolean>)|null} */
419
+ #verifyFn;
420
+
421
+ /** @type {Uint8Array|null} */
422
+ #remotePublicKey;
423
+
424
+ /** @type {PaymentDispute[]} */
425
+ #disputes = [];
426
+
427
+ /** @type {Map<string, Set<Function>>} */
428
+ #listeners = new Map();
429
+
308
430
  /**
309
431
  * @param {string} localPodId
310
432
  * @param {string} remotePodId
311
433
  * @param {object} [opts]
312
434
  * @param {number} [opts.capacity]
313
435
  * @param {number} [opts.ttlMs]
436
+ * @param {Function} [opts.signFn] - async (data: Uint8Array) => Uint8Array.
437
+ * When omitted, PaymentUpdate/close signatures stay `null` and close()
438
+ * stays unilateral -- fully backward compatible.
439
+ * @param {Function} [opts.verifyFn] - async (pubKey, data, sig) => boolean
440
+ * @param {Uint8Array} [opts.remotePublicKey] - Remote pod's raw public key,
441
+ * required alongside verifyFn to verify incoming updates/claims.
442
+ * @param {string} [opts.channelId] - Use this exact channel ID instead of
443
+ * generating a new one. Lets both sides of a channel agree on the same
444
+ * ID (e.g. echoed back from a PAYMENT_OPEN handshake) so signed
445
+ * updates/close messages -- which are keyed by channelId -- validate
446
+ * against each other. Defaults to auto-generated, as before.
314
447
  */
315
448
  constructor(localPodId, remotePodId, opts = {}) {
316
449
  if (!localPodId || !remotePodId) {
@@ -318,10 +451,13 @@ export class PaymentChannel {
318
451
  }
319
452
  this.#localPodId = localPodId;
320
453
  this.#remotePodId = remotePodId;
321
- this.#channelId = generateChannelId(localPodId, remotePodId);
454
+ this.#channelId = opts.channelId || generateChannelId(localPodId, remotePodId);
322
455
  this.#capacity = opts.capacity || DEFAULT_CAPACITY;
323
456
  this.#ttlMs = opts.ttlMs || DEFAULT_TTL_MS;
324
457
  this.#createdAt = Date.now();
458
+ this.#signFn = opts.signFn || null;
459
+ this.#verifyFn = opts.verifyFn || null;
460
+ this.#remotePublicKey = opts.remotePublicKey || null;
325
461
  }
326
462
 
327
463
  /** Channel identifier. */
@@ -357,30 +493,61 @@ export class PaymentChannel {
357
493
  /**
358
494
  * Open the channel with an initial deposit.
359
495
  *
496
+ * `remoteDeposit` is what the *counterparty* funded the channel with, as
497
+ * reported by their PAYMENT_OPEN message. It exists because a channel has
498
+ * two sides and only one of them runs this method with first-hand
499
+ * knowledge: without it, the receiving side of an open handshake starts at
500
+ * `remoteBalance = 0` while the initiator sits at `localBalance = deposit`,
501
+ * and the two views can never converge -- every subsequent update is
502
+ * computed from a starting point they disagree about. See
503
+ * `PaymentRouter.broadcastOpen()` for the wire side of this.
504
+ *
505
+ * One-sided funding stays the default: `open(100)` behaves exactly as
506
+ * before, including throwing on a non-positive amount. A pure counterparty
507
+ * mirror is `open(0, 100)` -- zero of your own credits, 100 of theirs --
508
+ * which is why the positivity check is on the *total*, not on the local
509
+ * side alone.
510
+ *
360
511
  * @param {number} initialDeposit - Amount to deposit into local balance
512
+ * @param {number} [remoteDeposit=0] - Amount the counterparty deposited,
513
+ * credited to `remoteBalance`
361
514
  */
362
- open(initialDeposit) {
515
+ open(initialDeposit, remoteDeposit = 0) {
363
516
  if (this.#state !== 'idle') {
364
517
  throw new Error(`Cannot open channel in state: ${this.#state}`);
365
518
  }
366
- if (typeof initialDeposit !== 'number' || initialDeposit <= 0) {
519
+ if (typeof initialDeposit !== 'number' || Number.isNaN(initialDeposit) || initialDeposit < 0) {
520
+ throw new RangeError('Initial deposit must be positive');
521
+ }
522
+ if (typeof remoteDeposit !== 'number' || Number.isNaN(remoteDeposit) || remoteDeposit < 0) {
523
+ throw new RangeError('Remote deposit must not be negative');
524
+ }
525
+ if (initialDeposit + remoteDeposit <= 0) {
526
+ // Preserves the pre-existing message for the one-argument form, which
527
+ // is the only way this is reachable without an explicit remoteDeposit.
367
528
  throw new RangeError('Initial deposit must be positive');
368
529
  }
369
- if (initialDeposit > this.#capacity) {
530
+ if (initialDeposit + remoteDeposit > this.#capacity) {
370
531
  throw new RangeError(
371
- `Deposit ${initialDeposit} exceeds capacity ${this.#capacity}`
532
+ `Deposit ${initialDeposit + remoteDeposit} exceeds capacity ${this.#capacity}`
372
533
  );
373
534
  }
374
535
  this.#state = 'opening';
375
536
  this.#localBalance = initialDeposit;
537
+ this.#remoteBalance = remoteDeposit;
376
538
  this.#state = 'open';
377
539
  }
378
540
 
379
541
  /**
380
542
  * Send a payment to the remote pod.
381
543
  *
544
+ * When a signFn was injected at construction, the returned PaymentUpdate
545
+ * is signed and this method returns a Promise (awaited by the caller).
546
+ * Without a signFn, behavior is unchanged: synchronous return, signature
547
+ * stays `null`.
548
+ *
382
549
  * @param {number} amount
383
- * @returns {PaymentUpdate}
550
+ * @returns {PaymentUpdate|Promise<PaymentUpdate>}
384
551
  */
385
552
  pay(amount) {
386
553
  if (this.#state !== 'open') {
@@ -397,21 +564,45 @@ export class PaymentChannel {
397
564
  this.#localBalance -= amount;
398
565
  this.#remoteBalance += amount;
399
566
  this.#sequence += 1;
400
- return Object.freeze({
567
+ const base = {
401
568
  channelId: this.#channelId,
402
569
  sequence: this.#sequence,
403
570
  amount,
404
571
  localBalance: this.#localBalance,
405
572
  remoteBalance: this.#remoteBalance,
406
573
  timestamp: Date.now(),
407
- signature: null,
408
- });
574
+ };
575
+ if (!this.#signFn) {
576
+ return Object.freeze({ ...base, signature: null });
577
+ }
578
+ return this.#signUpdate(base);
579
+ }
580
+
581
+ /**
582
+ * Sign a PaymentUpdate's fields and return the frozen, signed update.
583
+ * @param {object} base - Unsigned update fields
584
+ * @returns {Promise<PaymentUpdate>}
585
+ */
586
+ async #signUpdate(base) {
587
+ const sigBytes = await this.#signFn(canonicalBytes(base));
588
+ return Object.freeze({ ...base, signature: bytesToBase64(sigBytes) });
409
589
  }
410
590
 
411
591
  /**
412
592
  * Receive a payment update from the remote pod.
413
593
  *
594
+ * When a verifyFn (+ remotePublicKey) was injected at construction, the
595
+ * update's signature is verified before it's applied; unsigned or invalid
596
+ * updates are rejected (this method returns a rejected Promise). Without
597
+ * a verifyFn, behavior is unchanged: synchronous, unconditional apply.
598
+ *
599
+ * `amount` is checked the same way `pay()` checks it — a finite number
600
+ * greater than zero. A signature proves the counterparty wrote the value,
601
+ * not that the value is sane, and this update arrives straight off the
602
+ * wire via `PaymentRouter`'s PAYMENT_UPDATE handler.
603
+ *
414
604
  * @param {PaymentUpdate} update
605
+ * @returns {void|Promise<void>}
415
606
  */
416
607
  receive(update) {
417
608
  if (this.#state !== 'open') {
@@ -425,31 +616,298 @@ export class PaymentChannel {
425
616
  `Stale sequence: got ${update.sequence}, expected > ${this.#sequence}`
426
617
  );
427
618
  }
619
+ // A negative amount runs #applyReceive backwards and moves credits from
620
+ // the receiver to the sender; a string turns `localBalance += amount`
621
+ // into concatenation; NaN or Infinity poisons both balances for the life
622
+ // of the channel. None of these are reachable through pay(), so they can
623
+ // only arrive from the counterparty.
624
+ if (typeof update.amount !== 'number' || !Number.isFinite(update.amount) || update.amount <= 0) {
625
+ throw new RangeError(
626
+ `Rejected payment update seq ${update.sequence}: ` +
627
+ `amount must be a finite number greater than zero, got ${
628
+ typeof update.amount === 'number' ? update.amount : typeof update.amount
629
+ }`
630
+ );
631
+ }
632
+ if (!this.#verifyFn) {
633
+ this.#applyReceive(update);
634
+ return;
635
+ }
636
+ return this.#verifyAndApplyReceive(update);
637
+ }
638
+
639
+ /**
640
+ * Verify an incoming update's signature and, if valid, apply it.
641
+ * Throws if the signature is missing or invalid.
642
+ * @param {PaymentUpdate} update
643
+ */
644
+ async #verifyAndApplyReceive(update) {
645
+ const fields = {
646
+ channelId: update.channelId,
647
+ sequence: update.sequence,
648
+ amount: update.amount,
649
+ localBalance: update.localBalance,
650
+ remoteBalance: update.remoteBalance,
651
+ timestamp: update.timestamp,
652
+ };
653
+ const valid = await this.#verifySigned(fields, update.signature);
654
+ if (!valid) {
655
+ throw new Error(
656
+ `Rejected payment update seq ${update.sequence}: missing or invalid signature`
657
+ );
658
+ }
659
+ this.#applyReceive(update);
660
+ }
661
+
662
+ /** Apply a verified (or verification-not-required) update's balance delta. */
663
+ #applyReceive(update) {
428
664
  // From our perspective: remote sent to us, so our local goes up
429
665
  this.#localBalance += update.amount;
430
666
  this.#remoteBalance -= update.amount;
431
667
  this.#sequence = update.sequence;
432
668
  }
433
669
 
670
+ /**
671
+ * Verify a signature over a canonical fields object using the injected
672
+ * verifyFn + remotePublicKey. Never throws -- returns false on any
673
+ * failure (missing config, missing signature, decode error, mismatch).
674
+ *
675
+ * @param {object} fields
676
+ * @param {string|null|undefined} signatureB64
677
+ * @returns {Promise<boolean>}
678
+ */
679
+ async #verifySigned(fields, signatureB64) {
680
+ if (!this.#verifyFn || !this.#remotePublicKey) return false;
681
+ if (!signatureB64) return false;
682
+ try {
683
+ const data = canonicalBytes(fields);
684
+ const sigBytes = base64ToBytes(signatureB64);
685
+ return await this.#verifyFn(this.#remotePublicKey, data, sigBytes);
686
+ } catch {
687
+ return false;
688
+ }
689
+ }
690
+
434
691
  /**
435
692
  * Close the channel and produce a settlement.
436
693
  *
437
- * @returns {ChannelSettlement}
694
+ * Without a signFn, this is unchanged: unilateral and synchronous -- the
695
+ * channel closes immediately with whatever local balances it holds.
696
+ *
697
+ * With a signFn, closing becomes a two-phase mutual protocol: this method
698
+ * signs a CloseClaim of the current local view and moves to the `closing`
699
+ * state, returning a Promise<CloseClaim> to send to the counterparty. The
700
+ * counterparty verifies it via handleCloseMessage(); once its ack comes
701
+ * back, call finalizeClose(ack) to actually reach `closed`.
702
+ *
703
+ * @returns {ChannelSettlement|Promise<CloseClaim>}
438
704
  */
439
705
  close() {
440
706
  if (this.#state !== 'open') {
441
707
  throw new Error(`Cannot close channel in state: ${this.#state}`);
442
708
  }
709
+ if (!this.#signFn) {
710
+ this.#state = 'closing';
711
+ const settlement = Object.freeze({
712
+ channelId: this.#channelId,
713
+ finalLocalBalance: this.#localBalance,
714
+ finalRemoteBalance: this.#remoteBalance,
715
+ entryCount: this.#sequence,
716
+ closedAt: Date.now(),
717
+ });
718
+ this.#state = 'closed';
719
+ return settlement;
720
+ }
721
+ return this.#initiateSignedClose();
722
+ }
723
+
724
+ /**
725
+ * Initiator side of a signed mutual close: sign a claim of the current
726
+ * local view and move to `closing` (not yet `closed`).
727
+ * @returns {Promise<CloseClaim>}
728
+ */
729
+ async #initiateSignedClose() {
443
730
  this.#state = 'closing';
444
- const settlement = Object.freeze({
731
+ const claimFields = {
445
732
  channelId: this.#channelId,
446
733
  finalLocalBalance: this.#localBalance,
447
734
  finalRemoteBalance: this.#remoteBalance,
448
735
  entryCount: this.#sequence,
449
736
  closedAt: Date.now(),
737
+ };
738
+ const sigBytes = await this.#signFn(canonicalBytes(claimFields));
739
+ return Object.freeze({ ...claimFields, signature: bytesToBase64(sigBytes) });
740
+ }
741
+
742
+ /**
743
+ * Counterparty side of a signed mutual close. Verifies the initiator's
744
+ * claim and cross-checks it against this side's own local ledger state
745
+ * before agreeing. Requires both verifyFn (to check the claim) and
746
+ * signFn (to co-sign the ack) to be configured.
747
+ *
748
+ * On agreement, this channel transitions straight to `closed` (the
749
+ * counterparty doesn't need a further round trip -- it already holds the
750
+ * balances it's attesting to). On mismatch or invalid signature, a
751
+ * PaymentDispute is raised and the channel is left as-is (`open`) so it
752
+ * can be inspected/retried rather than silently accepting the claim.
753
+ *
754
+ * @param {CloseClaim} claim
755
+ * @returns {Promise<{ ok: true, ack: CloseAck }|{ ok: false, dispute: PaymentDispute }>}
756
+ */
757
+ async handleCloseMessage(claim) {
758
+ if (this.#state !== 'open') {
759
+ throw new Error(`Cannot handle close message in state: ${this.#state}`);
760
+ }
761
+ if (!claim || claim.channelId !== this.#channelId) {
762
+ throw new Error('Channel ID mismatch');
763
+ }
764
+ const claimFields = {
765
+ channelId: claim.channelId,
766
+ finalLocalBalance: claim.finalLocalBalance,
767
+ finalRemoteBalance: claim.finalRemoteBalance,
768
+ entryCount: claim.entryCount,
769
+ closedAt: claim.closedAt,
770
+ };
771
+ const valid = await this.#verifySigned(claimFields, claim.signature);
772
+ // From the initiator's perspective, finalLocalBalance is *their*
773
+ // balance and finalRemoteBalance is *ours* -- so it must mirror what
774
+ // we independently hold.
775
+ const matches = valid
776
+ && claim.finalRemoteBalance === this.#localBalance
777
+ && claim.finalLocalBalance === this.#remoteBalance;
778
+
779
+ if (!matches) {
780
+ const dispute = this.#raiseDispute(
781
+ valid ? 'balance-mismatch' : 'invalid-signature',
782
+ claim
783
+ );
784
+ return { ok: false, dispute };
785
+ }
786
+
787
+ if (!this.#signFn) {
788
+ const dispute = this.#raiseDispute('invalid-signature', claim);
789
+ return { ok: false, dispute };
790
+ }
791
+
792
+ const sigBytes = await this.#signFn(canonicalBytes(claimFields));
793
+ const ack = Object.freeze({ ...claimFields, signature: bytesToBase64(sigBytes) });
794
+ this.#state = 'closed';
795
+ return { ok: true, ack };
796
+ }
797
+
798
+ /**
799
+ * Initiator side: finalize a close after receiving the counterparty's
800
+ * ack. Verifies the ack and cross-checks it against the claim this side
801
+ * already sent. On agreement, moves to `closed` and returns the
802
+ * settlement. On mismatch or invalid signature, raises a PaymentDispute
803
+ * instead of trusting the wire message.
804
+ *
805
+ * @param {CloseAck} ack
806
+ * @returns {Promise<{ ok: true, settlement: ChannelSettlement }|{ ok: false, dispute: PaymentDispute }>}
807
+ */
808
+ async finalizeClose(ack) {
809
+ if (this.#state !== 'closing') {
810
+ throw new Error(`Cannot finalize close in state: ${this.#state}`);
811
+ }
812
+ if (!ack || ack.channelId !== this.#channelId) {
813
+ throw new Error('Channel ID mismatch');
814
+ }
815
+ const ackFields = {
816
+ channelId: ack.channelId,
817
+ finalLocalBalance: ack.finalLocalBalance,
818
+ finalRemoteBalance: ack.finalRemoteBalance,
819
+ entryCount: ack.entryCount,
820
+ closedAt: ack.closedAt,
821
+ };
822
+ const valid = await this.#verifySigned(ackFields, ack.signature);
823
+ const matches = valid
824
+ && ack.finalLocalBalance === this.#localBalance
825
+ && ack.finalRemoteBalance === this.#remoteBalance;
826
+
827
+ if (!matches) {
828
+ const dispute = this.#raiseDispute(
829
+ valid ? 'ack-mismatch' : 'invalid-ack-signature',
830
+ ack
831
+ );
832
+ return { ok: false, dispute };
833
+ }
834
+
835
+ const settlement = Object.freeze({
836
+ channelId: this.#channelId,
837
+ finalLocalBalance: this.#localBalance,
838
+ finalRemoteBalance: this.#remoteBalance,
839
+ entryCount: this.#sequence,
840
+ closedAt: ack.closedAt,
450
841
  });
451
842
  this.#state = 'closed';
452
- return settlement;
843
+ return { ok: true, settlement };
844
+ }
845
+
846
+ /**
847
+ * Record a PaymentDispute, emit it to listeners, and return it.
848
+ * @param {PaymentDispute['reason']} reason
849
+ * @param {object} evidence - The claim/ack that triggered the dispute
850
+ * @returns {PaymentDispute}
851
+ */
852
+ #raiseDispute(reason, evidence) {
853
+ const dispute = Object.freeze({
854
+ channelId: this.#channelId,
855
+ reason,
856
+ evidence,
857
+ localBalance: this.#localBalance,
858
+ remoteBalance: this.#remoteBalance,
859
+ raisedAt: Date.now(),
860
+ });
861
+ this.#disputes.push(dispute);
862
+ this.#emit('dispute', dispute);
863
+ return dispute;
864
+ }
865
+
866
+ /**
867
+ * List all PaymentDisputes raised on this channel.
868
+ * @returns {PaymentDispute[]}
869
+ */
870
+ listDisputes() {
871
+ return [...this.#disputes];
872
+ }
873
+
874
+ /**
875
+ * Register a listener for 'dispute' events. Convenience wrapper over on().
876
+ * @param {(dispute: PaymentDispute) => void} cb
877
+ */
878
+ onPaymentDispute(cb) {
879
+ this.on('dispute', cb);
880
+ }
881
+
882
+ /**
883
+ * Register a listener for a channel event ('dispute' today).
884
+ * @param {string} event
885
+ * @param {Function} cb
886
+ */
887
+ on(event, cb) {
888
+ if (!this.#listeners.has(event)) {
889
+ this.#listeners.set(event, new Set());
890
+ }
891
+ this.#listeners.get(event).add(cb);
892
+ }
893
+
894
+ /**
895
+ * Remove a listener registered via on()/onPaymentDispute().
896
+ * @param {string} event
897
+ * @param {Function} cb
898
+ */
899
+ off(event, cb) {
900
+ const set = this.#listeners.get(event);
901
+ if (set) set.delete(cb);
902
+ }
903
+
904
+ /** @param {string} event @param {*} data */
905
+ #emit(event, data) {
906
+ const set = this.#listeners.get(event);
907
+ if (!set) return;
908
+ for (const cb of set) {
909
+ try { cb(data); } catch (e) { silentCatch('clawser-mesh-payments', 'channel-listener', e) }
910
+ }
453
911
  }
454
912
 
455
913
  /**
@@ -483,12 +941,17 @@ export class PaymentChannel {
483
941
  /**
484
942
  * Restore a PaymentChannel from serialized data.
485
943
  * @param {object} data
944
+ * @param {object} [extraOpts] - Additional constructor opts not covered by
945
+ * `data` (signFn/verifyFn/remotePublicKey aren't serializable, so they
946
+ * aren't part of toJSON()'s output -- pass them here to restore a
947
+ * signing-capable channel).
486
948
  * @returns {PaymentChannel}
487
949
  */
488
- static fromJSON(data) {
950
+ static fromJSON(data, extraOpts = {}) {
489
951
  const ch = new PaymentChannel(data.localPodId, data.remotePodId, {
490
952
  capacity: data.capacity,
491
953
  ttlMs: data.ttlMs,
954
+ ...extraOpts,
492
955
  });
493
956
  ch.#channelId = data.channelId;
494
957
  ch.#createdAt = data.createdAt;
@@ -696,6 +1159,12 @@ export class PaymentRouter {
696
1159
  /** @type {ReturnType<typeof setInterval>|null} */
697
1160
  #escrowSweeperTimer = null;
698
1161
 
1162
+ /** @type {PaymentDispute[]} */
1163
+ #disputes = [];
1164
+
1165
+ /** @type {Set<Function>} */
1166
+ #disputeListeners = new Set();
1167
+
699
1168
  /**
700
1169
  * @param {string} localPodId
701
1170
  */
@@ -721,13 +1190,22 @@ export class PaymentRouter {
721
1190
  *
722
1191
  * @param {string} remotePodId
723
1192
  * @param {number} [capacity]
1193
+ * @param {object} [signingOpts] - Forwarded to PaymentChannel. Enables
1194
+ * signed updates and mutual close, and carries `channelId` when both
1195
+ * sides must agree on one (see broadcastOpen()). Omit for unchanged,
1196
+ * unsigned behavior with a locally-generated id.
1197
+ * @param {Function} [signingOpts.signFn]
1198
+ * @param {Function} [signingOpts.verifyFn]
1199
+ * @param {Uint8Array} [signingOpts.remotePublicKey]
1200
+ * @param {string} [signingOpts.channelId]
724
1201
  * @returns {PaymentChannel}
725
1202
  */
726
- openChannel(remotePodId, capacity) {
1203
+ openChannel(remotePodId, capacity, signingOpts) {
727
1204
  if (this.#channels.has(remotePodId)) {
728
1205
  throw new Error(`Channel to ${remotePodId} already exists`);
729
1206
  }
730
- const opts = capacity != null ? { capacity } : {};
1207
+ const opts = { ...(signingOpts || {}) };
1208
+ if (capacity != null) opts.capacity = capacity;
731
1209
  const ch = new PaymentChannel(this.#localPodId, remotePodId, opts);
732
1210
  this.#channels.set(remotePodId, ch);
733
1211
  return ch;
@@ -746,15 +1224,60 @@ export class PaymentRouter {
746
1224
  /**
747
1225
  * Close a channel and return the settlement.
748
1226
  *
1227
+ * When the channel has signing configured, this only *initiates* the
1228
+ * two-phase close: it broadcasts a signed CloseClaim and returns a
1229
+ * Promise that resolves once the claim is sent (not once the
1230
+ * counterparty has acked). The channel itself stays in the router's
1231
+ * map until wireTransport's PAYMENT_CLOSE handler receives the ack and
1232
+ * removes it -- see wireTransport() below.
1233
+ *
749
1234
  * @param {string} remotePodId
750
- * @returns {ChannelSettlement|null}
1235
+ * @returns {ChannelSettlement|Promise<{ pending: true, claim: CloseClaim }>|null}
751
1236
  */
752
1237
  closeChannel(remotePodId) {
753
1238
  const ch = this.#channels.get(remotePodId);
754
1239
  if (!ch) return null;
755
- const settlement = ch.close();
1240
+ const result = ch.close();
1241
+ if (result && typeof result.then === 'function') {
1242
+ // Signed two-phase close: `result` resolves to a CloseClaim. Leave
1243
+ // the channel in the map (state 'closing') until the counterparty's
1244
+ // ack arrives over the wire and finalizes it.
1245
+ return result.then((claim) => {
1246
+ this.broadcastClose(remotePodId, { claim });
1247
+ return { pending: true, claim };
1248
+ });
1249
+ }
756
1250
  this.#channels.delete(remotePodId);
757
- return settlement;
1251
+ return result;
1252
+ }
1253
+
1254
+ /**
1255
+ * List all PaymentDisputes raised across every channel handled by this
1256
+ * router (signed close mismatches or invalid signatures).
1257
+ * @returns {PaymentDispute[]}
1258
+ */
1259
+ listDisputes() {
1260
+ return [...this.#disputes];
1261
+ }
1262
+
1263
+ /**
1264
+ * Register a listener called whenever a PaymentDispute is raised on any
1265
+ * channel wired through this router.
1266
+ * @param {(dispute: PaymentDispute) => void} cb
1267
+ */
1268
+ onPaymentDispute(cb) {
1269
+ this.#disputeListeners.add(cb);
1270
+ }
1271
+
1272
+ /**
1273
+ * Record a dispute and notify onPaymentDispute() listeners.
1274
+ * @param {PaymentDispute} dispute
1275
+ */
1276
+ #recordDispute(dispute) {
1277
+ this.#disputes.push(dispute);
1278
+ for (const cb of this.#disputeListeners) {
1279
+ try { cb(dispute); } catch (e) { silentCatch('clawser-mesh-payments', 'onPaymentDispute-callback', e) }
1280
+ }
758
1281
  }
759
1282
 
760
1283
  /**
@@ -829,10 +1352,26 @@ export class PaymentRouter {
829
1352
  // Inbound: channel open request
830
1353
  subscribeFn(PAYMENT_OPEN, (payload, fromPodId) => {
831
1354
  try {
832
- const { remotePodId, capacity } = payload;
833
- if (remotePodId === this.#localPodId) {
834
- // Remote peer wants to open a channel with us
835
- this.openChannel(fromPodId, capacity);
1355
+ const { remotePodId, capacity, channelId, deposit } = payload;
1356
+ if (remotePodId !== this.#localPodId) return;
1357
+
1358
+ // Adopt the initiator's channelId when they sent one. Signed updates
1359
+ // and close claims are keyed by channelId, so a locally-generated one
1360
+ // would make every message from the initiator fail the
1361
+ // 'Channel ID mismatch' check in receive().
1362
+ const ch = this.openChannel(
1363
+ fromPodId,
1364
+ capacity,
1365
+ typeof channelId === 'string' && channelId ? { channelId } : undefined,
1366
+ );
1367
+
1368
+ // Adopt the initiator's deposit as our view of *their* balance, so
1369
+ // both sides start from the same numbers. Senders that predate this
1370
+ // field send no deposit; the channel is then left idle exactly as
1371
+ // before, which is the old (non-converging) behaviour rather than a
1372
+ // new failure.
1373
+ if (typeof deposit === 'number' && Number.isFinite(deposit) && deposit > 0) {
1374
+ ch.open(0, deposit);
836
1375
  }
837
1376
  } catch (e) { silentCatch('clawser-mesh-payments', 'ignore-duplicate-or-invalid-opens', e) }
838
1377
  });
@@ -842,14 +1381,58 @@ export class PaymentRouter {
842
1381
  try {
843
1382
  const ch = this.#channels.get(fromPodId);
844
1383
  if (ch) {
845
- ch.receive(payload);
1384
+ // ch.receive() is synchronous when the channel has no verifyFn
1385
+ // (unchanged legacy behavior) or returns a Promise that rejects
1386
+ // on an unsigned/invalid update when verification is active.
1387
+ const result = ch.receive(payload);
1388
+ if (result && typeof result.then === 'function') {
1389
+ result.catch((e) => silentCatch('clawser-mesh-payments', 'ignore-invalid-signed-update', e));
1390
+ }
846
1391
  }
847
1392
  } catch (e) { silentCatch('clawser-mesh-payments', 'ignore-invalid-updates', e) }
848
1393
  });
849
1394
 
850
1395
  // Inbound: channel close
851
1396
  subscribeFn(PAYMENT_CLOSE, (payload, fromPodId) => {
852
- try { this.closeChannel(fromPodId); } catch (e) { silentCatch('clawser-mesh-payments', 'this.closeChannel', e) }
1397
+ try {
1398
+ const ch = this.#channels.get(fromPodId);
1399
+
1400
+ if (ch && payload && payload.claim) {
1401
+ // Two-phase signed close: this is the initiator's signed claim.
1402
+ // Verify + cross-check against our own ledger, then either
1403
+ // co-sign an ack or raise a dispute -- never accept the wire
1404
+ // message's numbers unconditionally.
1405
+ Promise.resolve(ch.handleCloseMessage(payload.claim))
1406
+ .then((result) => {
1407
+ if (result.ok) {
1408
+ this.#channels.delete(fromPodId);
1409
+ this.broadcastClose(fromPodId, { ack: result.ack });
1410
+ } else {
1411
+ this.#recordDispute(result.dispute);
1412
+ }
1413
+ })
1414
+ .catch((e) => silentCatch('clawser-mesh-payments', 'handleCloseMessage', e));
1415
+ return;
1416
+ }
1417
+
1418
+ if (ch && payload && payload.ack) {
1419
+ // Two-phase signed close: this is the counterparty's ack of our
1420
+ // claim. Verify + cross-check before finalizing.
1421
+ Promise.resolve(ch.finalizeClose(payload.ack))
1422
+ .then((result) => {
1423
+ if (result.ok) {
1424
+ this.#channels.delete(fromPodId);
1425
+ } else {
1426
+ this.#recordDispute(result.dispute);
1427
+ }
1428
+ })
1429
+ .catch((e) => silentCatch('clawser-mesh-payments', 'finalizeClose', e));
1430
+ return;
1431
+ }
1432
+
1433
+ // Legacy unilateral close (no signing configured on this channel).
1434
+ this.closeChannel(fromPodId);
1435
+ } catch (e) { silentCatch('clawser-mesh-payments', 'this.closeChannel', e) }
853
1436
  });
854
1437
 
855
1438
  // Inbound: escrow creation
@@ -864,13 +1447,42 @@ export class PaymentRouter {
864
1447
  /**
865
1448
  * Broadcast a channel open over the transport.
866
1449
  *
1450
+ * The message carries the channel's id and this side's deposit as well as
1451
+ * its capacity. Both are what let the counterparty build a mirror that
1452
+ * agrees with ours: the id because signed updates and close claims are
1453
+ * keyed by it, the deposit because otherwise the receiver's `remoteBalance`
1454
+ * starts at 0 while ours starts at the deposit, and no later message ever
1455
+ * reconciles the difference.
1456
+ *
1457
+ * Defaults are read from the local channel to `remotePodId` when one
1458
+ * exists, so the normal sequence -- `openChannel()`, `open(deposit)`,
1459
+ * `broadcastOpen()` -- needs no extra arguments. Call this *after*
1460
+ * `open()`, or the deposit on the wire is 0.
1461
+ *
1462
+ * Wire compatibility: `channelId` and `deposit` are additional fields. A
1463
+ * peer running the older code ignores them and behaves as it did before;
1464
+ * this side ignores their absence in an incoming message the same way. Only
1465
+ * when both ends send them do the two views actually converge.
1466
+ *
867
1467
  * @param {string} remotePodId
868
- * @param {number} [capacity]
1468
+ * @param {number} [capacity] - Defaults to the local channel's capacity
1469
+ * @param {object} [opts]
1470
+ * @param {string} [opts.channelId] - Defaults to the local channel's id
1471
+ * @param {number} [opts.deposit] - Defaults to the local channel's current
1472
+ * localBalance
869
1473
  */
870
- broadcastOpen(remotePodId, capacity) {
871
- if (this.#broadcastFn) {
872
- this.#broadcastFn(PAYMENT_OPEN, { remotePodId, capacity });
873
- }
1474
+ broadcastOpen(remotePodId, capacity, opts = {}) {
1475
+ if (!this.#broadcastFn) return;
1476
+ const ch = this.#channels.get(remotePodId);
1477
+ const payload = {
1478
+ remotePodId,
1479
+ capacity: capacity != null ? capacity : ch?.capacity,
1480
+ };
1481
+ const channelId = opts.channelId != null ? opts.channelId : ch?.channelId;
1482
+ if (channelId != null) payload.channelId = channelId;
1483
+ const deposit = opts.deposit != null ? opts.deposit : ch?.localBalance;
1484
+ if (deposit != null) payload.deposit = deposit;
1485
+ this.#broadcastFn(PAYMENT_OPEN, payload);
874
1486
  }
875
1487
 
876
1488
  /**
@@ -108,9 +108,16 @@ export class MigrationResult {
108
108
  /** @type {string} */
109
109
  toPod
110
110
 
111
- /** @type {string|null} */
111
+ /**
112
+ * What was actually redeployed to `toPod`, or null when nothing was.
113
+ * Never a summary word like 'all' -- see `deployed` for the itemised list.
114
+ * @type {string|null}
115
+ */
112
116
  workload
113
117
 
118
+ /** @type {string[]} names of the skills deployed to toPod (may be empty) */
119
+ deployed
120
+
114
121
  /** @type {number} */
115
122
  durationMs
116
123
 
@@ -123,6 +130,7 @@ export class MigrationResult {
123
130
  * @param {string} opts.fromPod
124
131
  * @param {string} opts.toPod
125
132
  * @param {string} [opts.workload=null]
133
+ * @param {string[]} [opts.deployed=[]]
126
134
  * @param {number} [opts.durationMs=0]
127
135
  * @param {string} [opts.error=null]
128
136
  */
@@ -131,6 +139,7 @@ export class MigrationResult {
131
139
  fromPod,
132
140
  toPod,
133
141
  workload = null,
142
+ deployed = [],
134
143
  durationMs = 0,
135
144
  error = null,
136
145
  }) {
@@ -138,6 +147,7 @@ export class MigrationResult {
138
147
  this.fromPod = fromPod
139
148
  this.toPod = toPod
140
149
  this.workload = workload
150
+ this.deployed = deployed
141
151
  this.durationMs = durationMs
142
152
  this.error = error
143
153
  }
@@ -152,6 +162,7 @@ export class MigrationResult {
152
162
  fromPod: this.fromPod,
153
163
  toPod: this.toPod,
154
164
  workload: this.workload,
165
+ deployed: [...this.deployed],
155
166
  durationMs: this.durationMs,
156
167
  error: this.error,
157
168
  }
@@ -518,21 +529,38 @@ export class AutoMigrator {
518
529
  /** @type {Map<string, Set<Function>>} event -> listeners */
519
530
  #listeners = new Map()
520
531
 
532
+ /** @type {Function|null} resolves the workload to redeploy on the target */
533
+ #resolveWorkload = null
534
+
521
535
  /**
522
536
  * @param {object} opts
523
537
  * @param {HealthMonitor} opts.healthMonitor - Health monitor to listen to
524
538
  * @param {object} opts.orchestrator - Object with drainPod(podId), listPods(), deploySkill(podId, skill)
539
+ * @param {Function} [opts.resolveWorkload] - `(fromPodId, { services }) => Promise<Array<{name, content}>>`
540
+ * Supplies the skills to deploy on the target. A failed peer cannot be asked
541
+ * what it was running, so the workload has to come from the caller -- a
542
+ * registry, a manifest, whatever the application uses as its source of
543
+ * truth. Without it the migrator can drain the dead pod but cannot start
544
+ * anything in its place, and says so in the result rather than reporting a
545
+ * migration that did not happen.
525
546
  * @param {Function} [opts.onLog] - Logging callback (level, msg)
526
547
  */
527
- constructor({ healthMonitor, orchestrator, onLog }) {
548
+ constructor({ healthMonitor, orchestrator, resolveWorkload, onLog }) {
528
549
  if (!healthMonitor) {
529
550
  throw new Error('healthMonitor is required')
530
551
  }
531
552
  if (!orchestrator || typeof orchestrator.drainPod !== 'function') {
532
553
  throw new Error('orchestrator with drainPod() method is required')
533
554
  }
555
+ if (resolveWorkload !== undefined && typeof resolveWorkload !== 'function') {
556
+ throw new Error('resolveWorkload must be a function')
557
+ }
558
+ if (resolveWorkload && typeof orchestrator.deploySkill !== 'function') {
559
+ throw new Error('orchestrator with deploySkill() method is required when resolveWorkload is given')
560
+ }
534
561
  this.#healthMonitor = healthMonitor
535
562
  this.#orchestrator = orchestrator
563
+ this.#resolveWorkload = resolveWorkload || null
536
564
  this.#onLog = onLog || (() => {})
537
565
  }
538
566
 
@@ -602,29 +630,64 @@ export class AutoMigrator {
602
630
  this.#onLog(2, `Migrating workload from ${fromPodId} to ${target}`)
603
631
 
604
632
  try {
605
- await this.#orchestrator.drainPod(fromPodId)
633
+ // drainPod reports failure for exactly the case this path exists to
634
+ // handle -- a pod that has already dropped out of the peer table -- so
635
+ // its verdict decides the migration. An orchestrator that returns
636
+ // nothing is giving no verdict, which is not the same as failing.
637
+ const drain = await this.#orchestrator.drainPod(fromPodId)
638
+ if (drain && drain.success === false) {
639
+ const reason = drain.error || `drainPod("${fromPodId}") reported failure`
640
+ return this.#fail(fromPodId, target, reason, startTime)
641
+ }
642
+
643
+ // Move the workload. Nothing below runs on a peer until deploySkill has
644
+ // said it succeeded, and `deployed` records what actually landed.
645
+ const workload = await this.#workloadFor(fromPodId)
646
+ const deployed = []
647
+
648
+ for (const item of workload) {
649
+ const name = item?.name || 'unnamed skill'
650
+ let outcome
651
+ try {
652
+ outcome = await this.#orchestrator.deploySkill(target, item?.content)
653
+ } catch (err) {
654
+ return this.#fail(
655
+ fromPodId, target,
656
+ `deploying "${name}" to ${target} threw: ${err.message}`,
657
+ startTime, deployed,
658
+ )
659
+ }
660
+ if (!outcome || outcome.success === false) {
661
+ const why = outcome?.error || 'deploySkill reported failure'
662
+ return this.#fail(
663
+ fromPodId, target,
664
+ `deploying "${name}" to ${target} failed: ${why}`,
665
+ startTime, deployed,
666
+ )
667
+ }
668
+ deployed.push(name)
669
+ }
606
670
 
607
671
  const result = new MigrationResult({
608
672
  success: true,
609
673
  fromPod: fromPodId,
610
674
  toPod: target,
611
- workload: 'all',
675
+ // Only ever names what was really deployed. This used to read 'all'
676
+ // unconditionally, while nothing at all was started on the target.
677
+ workload: deployed.length ? deployed.join(', ') : null,
678
+ deployed,
612
679
  durationMs: Date.now() - startTime,
613
680
  })
614
681
  this.#emit('migrated', result)
615
- this.#onLog(2, `Migration complete: ${fromPodId} -> ${target} (${result.durationMs}ms)`)
682
+ this.#onLog(
683
+ 2,
684
+ deployed.length
685
+ ? `Migration complete: ${fromPodId} -> ${target}, deployed ${deployed.length} (${result.durationMs}ms)`
686
+ : `Drained ${fromPodId}; NO workload was deployed to ${target} (${result.durationMs}ms)`,
687
+ )
616
688
  return result
617
689
  } catch (err) {
618
- const result = new MigrationResult({
619
- success: false,
620
- fromPod: fromPodId,
621
- toPod: target,
622
- error: err.message,
623
- durationMs: Date.now() - startTime,
624
- })
625
- this.#emit('migration-failed', result)
626
- this.#onLog(0, `Migration failed: ${fromPodId} -> ${target}: ${err.message}`)
627
- return result
690
+ return this.#fail(fromPodId, target, err.message, startTime)
628
691
  }
629
692
  }
630
693
 
@@ -657,6 +720,52 @@ export class AutoMigrator {
657
720
 
658
721
  // -- Internal -------------------------------------------------------------
659
722
 
723
+ /**
724
+ * Build a failed MigrationResult, emit it, and log it.
725
+ *
726
+ * @param {string} fromPodId
727
+ * @param {string} target
728
+ * @param {string} error - Why the migration failed
729
+ * @param {number} startTime
730
+ * @param {string[]} [deployed=[]] - Skills that did land before the failure
731
+ * @returns {MigrationResult}
732
+ */
733
+ #fail(fromPodId, target, error, startTime, deployed = []) {
734
+ const result = new MigrationResult({
735
+ success: false,
736
+ fromPod: fromPodId,
737
+ toPod: target,
738
+ workload: deployed.length ? deployed.join(', ') : null,
739
+ deployed,
740
+ error,
741
+ durationMs: Date.now() - startTime,
742
+ })
743
+ this.#emit('migration-failed', result)
744
+ this.#onLog(0, `Migration failed: ${fromPodId} -> ${target}: ${error}`)
745
+ return result
746
+ }
747
+
748
+ /**
749
+ * Resolve the workload to deploy on the target, normalised to a list.
750
+ *
751
+ * @param {string} fromPodId - Pod whose workload is being moved
752
+ * @returns {Promise<Array<{name: string, content: *}>>}
753
+ */
754
+ async #workloadFor(fromPodId) {
755
+ if (!this.#resolveWorkload) {
756
+ // Loud, because the alternative is a self-healing component that heals
757
+ // nothing while reporting success.
758
+ this.#onLog(
759
+ 1,
760
+ `No resolveWorkload configured: ${fromPodId}'s workload will NOT be redeployed`,
761
+ )
762
+ return []
763
+ }
764
+ const resolved = await this.#resolveWorkload(fromPodId, { services: this.#services })
765
+ if (!resolved) return []
766
+ return Array.isArray(resolved) ? resolved : [resolved]
767
+ }
768
+
660
769
  /**
661
770
  * Select the best target pod for migration.
662
771
  * Prefers failoverPriority list, then picks the healthiest peer.
@@ -443,14 +443,34 @@ export class PeerSession {
443
443
  return
444
444
  }
445
445
 
446
- // Set timeout for pong response
447
- if (this.#heartbeatTimer) clearTimeout(this.#heartbeatTimer)
448
- this.#heartbeatTimer = setTimeout(() => {
449
- if (this.#state === 'active') {
450
- this.#onLog(1, `Heartbeat timeout for session ${this.#sessionId}, suspending`)
451
- this.suspend()
452
- }
453
- }, this.#heartbeatTimeoutMs)
446
+ /*
447
+ * Arm a pong deadline, and DO NOT disturb one already outstanding.
448
+ *
449
+ * This used to `clearTimeout` unconditionally before re-arming, which
450
+ * made the detector incapable of firing under its own defaults: the
451
+ * interval is 15s and the timeout 60s, so each ping cancelled the
452
+ * deadline three times over before it could elapse. `#handlePong()`
453
+ * already clears it on a reply -- that is the only thing that should.
454
+ *
455
+ * Measured against a transport that accepts sends and never pongs, at
456
+ * the shipped 1:4 ratio scaled down: 21 pings, state still `active`.
457
+ * The only configuration in which it worked was the inverted one,
458
+ * interval longer than timeout.
459
+ *
460
+ * The surviving escape was `send()` throwing, which a buffering or
461
+ * half-open transport will not do -- so a peer whose tab closed kept a
462
+ * session `active` forever, `send()` kept succeeding into a dead pipe,
463
+ * and no 'session:suspend' ever fired.
464
+ */
465
+ if (this.#heartbeatTimer === null) {
466
+ this.#heartbeatTimer = setTimeout(() => {
467
+ this.#heartbeatTimer = null
468
+ if (this.#state === 'active') {
469
+ this.#onLog(1, `Heartbeat timeout for session ${this.#sessionId}, suspending`)
470
+ this.suspend()
471
+ }
472
+ }, this.#heartbeatTimeoutMs)
473
+ }
454
474
  }, intervalMs)
455
475
  }
456
476
 
@@ -82,24 +82,81 @@ export class TimestampProof {
82
82
  }
83
83
 
84
84
  /**
85
- * Verify internal consistency of this proof.
85
+ * Verify this proof.
86
86
  *
87
- * @param {Function} [verifyFn] - Optional async (signature, data, podId) => boolean
88
- * @returns {{ valid: boolean, confidence: number }}
87
+ * Without `verifyFn` this checks STRUCTURE ONLY -- that three fields have
88
+ * plausible types -- and says so in `checked`. A structurally valid proof is
89
+ * not an authentic one: `confidence` is a number the proof asserts about
90
+ * itself, and a forgery can assert it too.
91
+ *
92
+ * With `verifyFn` every signature in the proof is checked. Both the
93
+ * authority signature and the witness entries are signed by `issuedBy` --
94
+ * the authority attests to what each peer reported, peers do not sign for
95
+ * themselves -- so `issuedBy` is the pod whose key `verifyFn` must resolve,
96
+ * for witness entries as much as for the proof itself.
97
+ *
98
+ * @param {Function} [verifyFn] - async (signature: Uint8Array, data: string, signerPodId: string) => boolean
99
+ * @returns {Promise<{ valid: boolean, confidence: number, checked: 'structure'|'signatures', reason?: string }>}
89
100
  */
90
- verify(verifyFn) {
101
+ async verify(verifyFn) {
91
102
  // Basic structural checks
92
103
  if (!this.eventHash || typeof this.eventHash !== 'string') {
93
- return { valid: false, confidence: 0 }
104
+ return { valid: false, confidence: 0, checked: 'structure', reason: 'eventHash missing or not a string' }
94
105
  }
95
106
  if (typeof this.canonicalTimestamp !== 'number' || this.canonicalTimestamp <= 0) {
96
- return { valid: false, confidence: 0 }
107
+ return { valid: false, confidence: 0, checked: 'structure', reason: 'canonicalTimestamp missing or not a positive number' }
97
108
  }
98
109
  if (!Array.isArray(this.witnesses) || this.witnesses.length === 0) {
99
- return { valid: false, confidence: 0 }
110
+ return { valid: false, confidence: 0, checked: 'structure', reason: 'witnesses missing or empty' }
111
+ }
112
+
113
+ if (typeof verifyFn !== 'function') {
114
+ return { valid: true, confidence: this.confidence, checked: 'structure' }
115
+ }
116
+
117
+ if (!this.signature) {
118
+ return { valid: false, confidence: 0, checked: 'signatures', reason: 'proof carries no authority signature' }
119
+ }
120
+
121
+ const check = async (signature, data, what) => {
122
+ let ok
123
+ try {
124
+ ok = await verifyFn(fromBase64(signature), data, this.issuedBy)
125
+ } catch (err) {
126
+ return `verifying ${what} threw: ${err.message}`
127
+ }
128
+ return ok === true ? null : `${what} failed verification`
100
129
  }
101
130
 
102
- return { valid: true, confidence: this.confidence }
131
+ const authorityFailure = await check(
132
+ this.signature,
133
+ `${this.eventHash}:${this.canonicalTimestamp}`,
134
+ `authority signature from ${this.issuedBy}`,
135
+ )
136
+ if (authorityFailure) {
137
+ return { valid: false, confidence: 0, checked: 'signatures', reason: authorityFailure }
138
+ }
139
+
140
+ for (const witness of this.witnesses) {
141
+ if (!witness || !witness.signature) {
142
+ return {
143
+ valid: false,
144
+ confidence: 0,
145
+ checked: 'signatures',
146
+ reason: `witness ${witness?.podId ?? '(unnamed)'} carries no signature`,
147
+ }
148
+ }
149
+ const witnessFailure = await check(
150
+ witness.signature,
151
+ `${this.eventHash}:${witness.podId}:${witness.localTimestamp}`,
152
+ `witness entry for ${witness.podId}`,
153
+ )
154
+ if (witnessFailure) {
155
+ return { valid: false, confidence: 0, checked: 'signatures', reason: witnessFailure }
156
+ }
157
+ }
158
+
159
+ return { valid: true, confidence: this.confidence, checked: 'signatures' }
103
160
  }
104
161
 
105
162
  /**
@@ -154,6 +211,25 @@ function toBase64(bytes) {
154
211
  return btoa(String.fromCharCode(...bytes))
155
212
  }
156
213
 
214
+ /**
215
+ * Decode a base64 string back to a Uint8Array.
216
+ * Signatures travel through toJSON as base64; a verify callback expects the
217
+ * bytes it was given at signing time, so passing the string through would
218
+ * compare characters against byte values and never match.
219
+ *
220
+ * @param {string} b64
221
+ * @returns {Uint8Array}
222
+ */
223
+ function fromBase64(b64) {
224
+ if (typeof Buffer !== 'undefined') {
225
+ return new Uint8Array(Buffer.from(b64, 'base64'))
226
+ }
227
+ const binary = atob(b64)
228
+ const bytes = new Uint8Array(binary.length)
229
+ for (let i = 0; i < binary.length; i++) bytes[i] = binary.charCodeAt(i)
230
+ return bytes
231
+ }
232
+
157
233
  // ---------------------------------------------------------------------------
158
234
  // TimestampAuthority — distributed consensus coordinator
159
235
  // ---------------------------------------------------------------------------
@@ -271,45 +347,61 @@ export class TimestampAuthority {
271
347
  /**
272
348
  * Verify a TimestampProof.
273
349
  *
274
- * Checks that the authority signature matches the eventHash +
275
- * canonicalTimestamp, and validates witness signatures.
350
+ * Checks every signature in the proof against the key of the pod that
351
+ * issued it. This requires `identity.verify(signature, data, signerPodId)`.
352
+ * Without it the only check available is re-signing with THIS authority's
353
+ * own key, which answers a different question -- "did I issue this?" -- and
354
+ * is reported as such rather than as authenticity.
276
355
  *
277
356
  * @param {TimestampProof} proof
278
- * @returns {Promise<{ valid: boolean, reason?: string }>}
357
+ * @returns {Promise<{ valid: boolean, checked?: string, reason?: string }>}
279
358
  */
280
359
  async verify(proof) {
281
360
  if (!(proof instanceof TimestampProof)) {
282
361
  return { valid: false, reason: 'Not a TimestampProof instance' }
283
362
  }
284
363
 
285
- // Check basic structure
286
- const structural = proof.verify()
364
+ if (this.#identity.verify) {
365
+ const result = await proof.verify(
366
+ (signature, data, signerPodId) => this.#identity.verify(signature, data, signerPodId),
367
+ )
368
+ if (!result.valid) {
369
+ return { valid: false, checked: result.checked, reason: result.reason }
370
+ }
371
+ return { valid: true, checked: 'signatures' }
372
+ }
373
+
374
+ // No verify() on the identity: we can only re-sign and compare, which
375
+ // works solely for proofs this authority issued itself. Saying anything
376
+ // about a foreign proof here would be a guess.
377
+ if (proof.issuedBy !== this.#identity.podId) {
378
+ return {
379
+ valid: false,
380
+ checked: 'none',
381
+ reason: `Cannot verify a proof issued by ${proof.issuedBy}: identity has no verify() to check another pod's key`,
382
+ }
383
+ }
384
+
385
+ const structural = await proof.verify()
287
386
  if (!structural.valid) {
288
- return { valid: false, reason: 'Structural validation failed' }
387
+ return { valid: false, checked: 'structure', reason: structural.reason || 'Structural validation failed' }
289
388
  }
290
389
 
291
- // Verify authority signature matches eventHash + canonicalTimestamp
292
390
  const expectedData = `${proof.eventHash}:${proof.canonicalTimestamp}`
293
- const expectedSig = await this.#identity.sign(expectedData)
294
- const expectedB64 = toBase64(expectedSig)
295
-
391
+ const expectedB64 = toBase64(await this.#identity.sign(expectedData))
296
392
  if (proof.signature !== expectedB64) {
297
- return { valid: false, reason: 'Authority signature mismatch — eventHash or timestamp was tampered' }
393
+ return { valid: false, checked: 'self', reason: 'Authority signature mismatch — eventHash or timestamp was tampered' }
298
394
  }
299
395
 
300
- // Verify witness signatures
301
- if (this.#identity.verify) {
302
- for (const witness of proof.witnesses) {
303
- const witnessData = `${proof.eventHash}:${witness.podId}:${witness.localTimestamp}`
304
- const witnessSig = await this.#identity.sign(witnessData)
305
- const witnessSigB64 = toBase64(witnessSig)
306
- if (witness.signature !== witnessSigB64) {
307
- return { valid: false, reason: `Witness signature mismatch for ${witness.podId}` }
308
- }
396
+ for (const witness of proof.witnesses) {
397
+ const witnessData = `${proof.eventHash}:${witness.podId}:${witness.localTimestamp}`
398
+ const witnessSigB64 = toBase64(await this.#identity.sign(witnessData))
399
+ if (witness.signature !== witnessSigB64) {
400
+ return { valid: false, checked: 'self', reason: `Witness signature mismatch for ${witness.podId}` }
309
401
  }
310
402
  }
311
403
 
312
- return { valid: true }
404
+ return { valid: true, checked: 'self' }
313
405
  }
314
406
 
315
407
  /**