@serfab/cadre-core 1.6.0 → 1.8.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.
Files changed (179) hide show
  1. package/README.md +8 -6
  2. package/dist/cadre-node.d.ts +548 -137
  3. package/dist/cadre-node.js +1208 -383
  4. package/dist/cadre-node.js.map +1 -1
  5. package/dist/control-authorization.d.ts +2 -2
  6. package/dist/control-authorization.js +1 -0
  7. package/dist/control-authorization.js.map +1 -1
  8. package/dist/control-cohort.d.ts +6 -0
  9. package/dist/control-cohort.js +6 -0
  10. package/dist/control-cohort.js.map +1 -1
  11. package/dist/control-database.d.ts +46 -8
  12. package/dist/control-database.js +97 -18
  13. package/dist/control-database.js.map +1 -1
  14. package/dist/control-formation-recorder.d.ts +37 -14
  15. package/dist/control-formation-recorder.js +60 -10
  16. package/dist/control-formation-recorder.js.map +1 -1
  17. package/dist/control-read-retry.d.ts +13 -12
  18. package/dist/control-read-retry.js +14 -12
  19. package/dist/control-read-retry.js.map +1 -1
  20. package/dist/control-schema.d.ts +1 -1
  21. package/dist/control-schema.js +67 -5
  22. package/dist/control-schema.js.map +1 -1
  23. package/dist/control-stream.d.ts +9 -1
  24. package/dist/control-stream.js +24 -1
  25. package/dist/control-stream.js.map +1 -1
  26. package/dist/control-write-retry.d.ts +12 -2
  27. package/dist/control-write-retry.js +13 -2
  28. package/dist/control-write-retry.js.map +1 -1
  29. package/dist/delegate-admission.d.ts +11 -8
  30. package/dist/delegate-admission.js +19 -11
  31. package/dist/delegate-admission.js.map +1 -1
  32. package/dist/diagnostics/connection-path.d.ts +0 -7
  33. package/dist/diagnostics/connection-path.js +0 -7
  34. package/dist/diagnostics/connection-path.js.map +1 -1
  35. package/dist/formation-approval.d.ts +7 -0
  36. package/dist/formation-approval.js +9 -3
  37. package/dist/formation-approval.js.map +1 -1
  38. package/dist/fs-atomic.d.ts +11 -2
  39. package/dist/fs-atomic.js +13 -3
  40. package/dist/fs-atomic.js.map +1 -1
  41. package/dist/hibernation-manager.d.ts +111 -8
  42. package/dist/hibernation-manager.js +234 -49
  43. package/dist/hibernation-manager.js.map +1 -1
  44. package/dist/index.d.ts +13 -6
  45. package/dist/index.js +27 -5
  46. package/dist/index.js.map +1 -1
  47. package/dist/joined-strand-store.d.ts +177 -0
  48. package/dist/joined-strand-store.js +431 -0
  49. package/dist/joined-strand-store.js.map +1 -0
  50. package/dist/key-store-file.js +14 -5
  51. package/dist/key-store-file.js.map +1 -1
  52. package/dist/key-store.d.ts +6 -0
  53. package/dist/key-store.js.map +1 -1
  54. package/dist/link-budget.d.ts +367 -69
  55. package/dist/link-budget.js +375 -72
  56. package/dist/link-budget.js.map +1 -1
  57. package/dist/membership-connection-gater.d.ts +30 -43
  58. package/dist/membership-connection-gater.js +31 -42
  59. package/dist/membership-connection-gater.js.map +1 -1
  60. package/dist/node-local-snapshot.d.ts +5 -4
  61. package/dist/node-local-snapshot.js +6 -3
  62. package/dist/node-local-snapshot.js.map +1 -1
  63. package/dist/peer-dial.d.ts +24 -4
  64. package/dist/peer-dial.js +74 -5
  65. package/dist/peer-dial.js.map +1 -1
  66. package/dist/peer-join-backfill.d.ts +35 -15
  67. package/dist/peer-join-backfill.js +115 -55
  68. package/dist/peer-join-backfill.js.map +1 -1
  69. package/dist/push-fanout.d.ts +6 -0
  70. package/dist/push-fanout.js +6 -0
  71. package/dist/push-fanout.js.map +1 -1
  72. package/dist/relay-reservation.d.ts +3 -1
  73. package/dist/relay-reservation.js +3 -1
  74. package/dist/relay-reservation.js.map +1 -1
  75. package/dist/relay-server.d.ts +79 -0
  76. package/dist/relay-server.js +74 -0
  77. package/dist/relay-server.js.map +1 -0
  78. package/dist/seed-bootstrap.d.ts +57 -4
  79. package/dist/seed-bootstrap.js +107 -83
  80. package/dist/seed-bootstrap.js.map +1 -1
  81. package/dist/storage-scope.d.ts +33 -17
  82. package/dist/storage-scope.js +44 -23
  83. package/dist/storage-scope.js.map +1 -1
  84. package/dist/strand-addr-protocol.d.ts +58 -21
  85. package/dist/strand-addr-protocol.js +133 -85
  86. package/dist/strand-addr-protocol.js.map +1 -1
  87. package/dist/strand-database.d.ts +20 -2
  88. package/dist/strand-database.js +42 -5
  89. package/dist/strand-database.js.map +1 -1
  90. package/dist/strand-first-sync-gate.d.ts +59 -21
  91. package/dist/strand-first-sync-gate.js +58 -19
  92. package/dist/strand-first-sync-gate.js.map +1 -1
  93. package/dist/strand-formation-deadlines.d.ts +151 -0
  94. package/dist/strand-formation-deadlines.js +171 -0
  95. package/dist/strand-formation-deadlines.js.map +1 -0
  96. package/dist/strand-formation-manager.d.ts +63 -30
  97. package/dist/strand-formation-manager.js +67 -41
  98. package/dist/strand-formation-manager.js.map +1 -1
  99. package/dist/strand-formation-protocol.d.ts +45 -35
  100. package/dist/strand-formation-protocol.js +59 -122
  101. package/dist/strand-formation-protocol.js.map +1 -1
  102. package/dist/strand-instance-manager.d.ts +152 -6
  103. package/dist/strand-instance-manager.js +331 -42
  104. package/dist/strand-instance-manager.js.map +1 -1
  105. package/dist/strand-membership-writer.d.ts +6 -0
  106. package/dist/strand-membership-writer.js +11 -0
  107. package/dist/strand-membership-writer.js.map +1 -1
  108. package/dist/strand-peer-book-file.d.ts +12 -0
  109. package/dist/strand-peer-book-file.js +37 -0
  110. package/dist/strand-peer-book-file.js.map +1 -0
  111. package/dist/strand-peer-book-protocol.d.ts +168 -0
  112. package/dist/strand-peer-book-protocol.js +356 -0
  113. package/dist/strand-peer-book-protocol.js.map +1 -0
  114. package/dist/strand-peer-book-swap.d.ts +104 -0
  115. package/dist/strand-peer-book-swap.js +284 -0
  116. package/dist/strand-peer-book-swap.js.map +1 -0
  117. package/dist/strand-peer-book.d.ts +159 -0
  118. package/dist/strand-peer-book.js +361 -0
  119. package/dist/strand-peer-book.js.map +1 -0
  120. package/dist/strand-peer-observer.d.ts +88 -0
  121. package/dist/strand-peer-observer.js +180 -0
  122. package/dist/strand-peer-observer.js.map +1 -0
  123. package/dist/strand-revocation-enforcer.js +2 -1
  124. package/dist/strand-revocation-enforcer.js.map +1 -1
  125. package/dist/strand-solicitation.d.ts +36 -20
  126. package/dist/strand-solicitation.js +4 -4
  127. package/dist/strand-solicitation.js.map +1 -1
  128. package/dist/strand-wake-protocol.d.ts +80 -23
  129. package/dist/strand-wake-protocol.js +89 -64
  130. package/dist/strand-wake-protocol.js.map +1 -1
  131. package/dist/types.d.ts +181 -33
  132. package/dist/types.js +4 -3
  133. package/dist/types.js.map +1 -1
  134. package/package.json +11 -7
  135. package/src/cadre-node.ts +1316 -398
  136. package/src/control-authorization.ts +2 -1
  137. package/src/control-cohort.ts +6 -0
  138. package/src/control-database.ts +122 -18
  139. package/src/control-formation-recorder.ts +354 -305
  140. package/src/control-read-retry.ts +14 -12
  141. package/src/control-schema.ts +67 -5
  142. package/src/control-stream.ts +25 -1
  143. package/src/control-write-retry.ts +13 -2
  144. package/src/delegate-admission.ts +23 -13
  145. package/src/diagnostics/connection-path.ts +0 -7
  146. package/src/formation-approval.ts +610 -604
  147. package/src/fs-atomic.ts +14 -4
  148. package/src/hibernation-manager.ts +638 -437
  149. package/src/index.ts +91 -6
  150. package/src/joined-strand-store.ts +498 -0
  151. package/src/key-store-file.ts +14 -5
  152. package/src/key-store.ts +6 -0
  153. package/src/link-budget.ts +393 -74
  154. package/src/membership-connection-gater.ts +31 -45
  155. package/src/node-local-snapshot.ts +293 -289
  156. package/src/peer-dial.ts +81 -7
  157. package/src/peer-join-backfill.ts +120 -57
  158. package/src/push-fanout.ts +6 -0
  159. package/src/relay-reservation.ts +3 -1
  160. package/src/relay-server.ts +98 -0
  161. package/src/seed-bootstrap.ts +133 -91
  162. package/src/storage-scope.ts +44 -23
  163. package/src/strand-addr-protocol.ts +547 -458
  164. package/src/strand-database.ts +287 -242
  165. package/src/strand-first-sync-gate.ts +58 -19
  166. package/src/strand-formation-deadlines.ts +227 -0
  167. package/src/strand-formation-manager.ts +700 -647
  168. package/src/strand-formation-protocol.ts +103 -150
  169. package/src/strand-instance-manager.ts +387 -45
  170. package/src/strand-membership-writer.ts +12 -0
  171. package/src/strand-peer-book-file.ts +39 -0
  172. package/src/strand-peer-book-protocol.ts +466 -0
  173. package/src/strand-peer-book-swap.ts +338 -0
  174. package/src/strand-peer-book.ts +475 -0
  175. package/src/strand-peer-observer.ts +235 -0
  176. package/src/strand-revocation-enforcer.ts +2 -1
  177. package/src/strand-solicitation.ts +519 -500
  178. package/src/strand-wake-protocol.ts +401 -355
  179. package/src/types.ts +185 -33
package/src/index.ts CHANGED
@@ -117,10 +117,78 @@ export {
117
117
  type EnrolledMachineStore
118
118
  } from './enrolled-machine-store.js';
119
119
 
120
+ // Node-local record of the strands this node joined from ANOTHER party and has not yet
121
+ // published party-wide, re-offered on every start as `strand:discovered`.
122
+ // Cross-platform: its durable form rides the KeyStore seam above (the record carries a
123
+ // closed strand's read secret), so there is no file-backed subpath.
124
+ export {
125
+ MemoryJoinedStrandStore,
126
+ KeyStoreJoinedStrandStore,
127
+ type JoinedStrandStore,
128
+ type JoinedStrandRecord
129
+ } from './joined-strand-store.js';
130
+
131
+ // Node-local strand peer book: per strand, the strand peers this node has met and
132
+ // their last-known addresses, dialed first on every launch so a restarted machine
133
+ // re-finds the other parties. Same cross-platform split as the bootstrap-peer store
134
+ // above — interface + in-memory + slot-backed stores here, Node-only file backend
135
+ // behind the subpath '@serfab/cadre-core/strand-peer-book-file'.
136
+ export {
137
+ MemoryStrandPeerBookStore,
138
+ PersistentStrandPeerBookStore,
139
+ mergeStrandPeerEntry,
140
+ sanitizeStrandPeerEntry,
141
+ strandPeerFreshness,
142
+ MAX_STRAND_PEERS,
143
+ STRAND_PEER_MAX_AGE_MS,
144
+ type StrandPeerBookStore,
145
+ type StrandPeerBookOptions,
146
+ type StrandPeerEntry
147
+ } from './strand-peer-book.js';
148
+ export {
149
+ StrandPeerObserver,
150
+ dialableAddrs,
151
+ connectedIdentifiedPeers,
152
+ STRAND_PEER_OBSERVE_THROTTLE_MS,
153
+ type StrandPeerObservation,
154
+ type StrandPeerObserverDeps,
155
+ type StrandPeerObserverOptions,
156
+ type ConnectedIdentifiedPeer
157
+ } from './strand-peer-observer.js';
158
+ // The signed book SWAP between strand peers (`/sereus/strand-peers/1.0.0`): the wire
159
+ // protocol, signing and verification, and the per-strand driver that arms it.
160
+ export {
161
+ STRAND_PEER_BOOK_PROTOCOL,
162
+ SIGNED_STRAND_PEER_ENTRY_VERSION,
163
+ STRAND_PEER_ISSUED_AT_SKEW_MS,
164
+ MAX_BOOK_FRAME_SIZE,
165
+ StrandPeerBookService,
166
+ exchangeStrandPeerBook,
167
+ signStrandPeerEntry,
168
+ signedStrandPeerEntryPayload,
169
+ verifySignedStrandPeerEntry,
170
+ verifyStrandPeerBookFrame,
171
+ trimBookFrameToFit,
172
+ assertBookFrameFits,
173
+ type SignedStrandPeerEntry,
174
+ type StrandPeerBookFrame,
175
+ type StrandPeerEntryVerdict,
176
+ type StrandPeerBookServiceDeps,
177
+ type ExchangeStrandPeerBookOptions
178
+ } from './strand-peer-book-protocol.js';
179
+ export {
180
+ StrandPeerBookSwap,
181
+ STRAND_PEER_BOOK_SWAP_THROTTLE_MS,
182
+ OWN_ENTRY_RESIGN_DEBOUNCE_MS,
183
+ type StrandPeerBookSwapDeps,
184
+ type StrandPeerBookSwapOptions
185
+ } from './strand-peer-book-swap.js';
186
+
120
187
  // Storage scope keys — what `CadreNodeConfig.storage.provider` is called with. A
121
188
  // strand's key is its strand id; the control database's key carries the party id,
122
189
  // so two parties on one device never share a control store. Every key stays within
123
- // `[A-Za-z0-9._-]`: the control key by base64url encoding, a strand's by
190
+ // `[a-z0-9._-]` — lowercase, so distinct keys stay distinct on a case-insensitive
191
+ // filesystem: the control key by lowercase hex encoding, a strand's by
124
192
  // `assertStrandScopeKey`, which every strand launch runs.
125
193
  export {
126
194
  controlStorageScope,
@@ -238,6 +306,8 @@ export {
238
306
  createDefaultFormationResponseValidator,
239
307
  type DisclosureValidator,
240
308
  type FormationUsageRecorder,
309
+ type FormationUsageParams,
310
+ type AuthorizedFormationUsage,
241
311
  type ResolvedHostStrand,
242
312
  type StrandProvisioner,
243
313
  type FormationResponseValidator,
@@ -363,14 +433,16 @@ export {
363
433
  } from './strand-wake-protocol.js';
364
434
 
365
435
  // Strand Address (control-network strand-address RPC) — wire types come via
366
- // `export * from './types.js'` (StrandAddrRequest / StrandAddrResponse).
436
+ // `export * from './types.js'` (StrandAddrRequest / StrandAddrResponse / StrandAddrStatus).
367
437
  export {
368
438
  StrandAddrService,
369
439
  collectStrandAddrs,
370
440
  STRAND_ADDR_PROTOCOL,
371
441
  type StrandAddrServiceOptions,
372
442
  type StrandAddrPeer,
373
- type CollectStrandAddrsOptions
443
+ type CollectStrandAddrsOptions,
444
+ type StrandAddrOutcome,
445
+ type StrandAddrCollection
374
446
  } from './strand-addr-protocol.js';
375
447
 
376
448
  // Peer-address record (self-published, signed, freshness-stamped CadrePeer row)
@@ -437,6 +509,7 @@ export {
437
509
  // limit, so an address that never answers cannot starve the rest.
438
510
  export {
439
511
  dialPeerAddrs,
512
+ SelfRelayOnlyError,
440
513
  tryAddrsInTurn,
441
514
  directBeforeRelayed,
442
515
  DEFAULT_CONTROL_COHORT_DIAL_TIMEOUT_MS,
@@ -454,12 +527,14 @@ export {
454
527
  RELAYED_DIAL_ROUND_TRIPS,
455
528
  RELAY_RESERVATION_ROUND_TRIPS,
456
529
  CIRCUIT_REQUEST_ROUND_TRIPS,
530
+ RELAYED_REQUEST_ROUND_TRIPS,
457
531
  PUSH_TRANSFER_ALLOWANCE_MS,
532
+ ADMISSION_DECISION_TIMEOUT_MS,
458
533
  resolveLinkRoundTripMs,
459
534
  relayedDialBudgetMs,
460
- connectionManagerTimeouts,
461
535
  relayReservationBudgetMs,
462
536
  circuitRequestBudgetMs,
537
+ relayedRequestBudgetMs,
463
538
  peerJoinPushBudget,
464
539
  type PeerJoinPushBudget
465
540
  } from './link-budget.js';
@@ -501,6 +576,7 @@ export {
501
576
  type FormationDialResult,
502
577
  type ResponderProvisionOutcome
503
578
  } from './strand-formation-protocol.js';
579
+ export { formationDeadlines, type FormationDeadlines } from './strand-formation-deadlines.js';
504
580
 
505
581
  // Strand Formation manager (drives the native transport)
506
582
  export {
@@ -509,6 +585,7 @@ export {
509
585
  MEMBERSHIP_INVITE_TTL_MS,
510
586
  MEMBERSHIP_INVITE_UNAVAILABLE_REASON,
511
587
  HOST_STRAND_MUST_BE_RECREATED_REASON,
588
+ type MembershipInviteIssuer,
512
589
  type StrandFormationManagerConfig,
513
590
  type StrandFormationManagerOptions
514
591
  } from './strand-formation-manager.js';
@@ -518,11 +595,9 @@ export {
518
595
  createMembershipConnectionGater,
519
596
  STRANGER_OPEN_PROTOCOLS,
520
597
  DEFAULT_ENROLLMENT_WINDOW_MS,
521
- ADMISSION_DECISION_TIMEOUT_MS,
522
598
  RELAY_ADMISSION_RESERVE_DEADLINE_MS,
523
599
  RELAY_ADMISSION_CLOSE_TIMEOUT_MS,
524
600
  MAX_UNAUTHORIZED_RELAY_RESERVATIONS,
525
- UNAUTHORIZED_RESERVATION_TTL_MS,
526
601
  UnauthorizedReservationBudget,
527
602
  type InboundAdmissionPolicy,
528
603
  type InboundConnectionVerdict
@@ -548,6 +623,16 @@ export {
548
623
  resolveListenAddrs
549
624
  } from './relay-addrs.js';
550
625
  export { strandNodeAddrs, type StrandNodeAddrs } from './strand-network-config.js';
626
+ // The circuit-relay SERVER a node runs, and with which init — one resolution shared by the
627
+ // control node and every strand node. Exported alongside the listen derivations above for the
628
+ // same reason: an embedder can assert on what its `network` block resolves to.
629
+ export {
630
+ resolveRelayServer,
631
+ PARTY_RELAY_MAX_RESERVATIONS,
632
+ PARTY_RELAY_RESERVATION_TTL_MS,
633
+ type ResolvedRelayServer,
634
+ type ResolvedRelayReservations
635
+ } from './relay-server.js';
551
636
 
552
637
  // Relay reservation via the bare `/p2p-circuit` search listener — the one route
553
638
  // every control node takes; `network.relayAddrs` is its fail-fast posture
@@ -0,0 +1,498 @@
1
+ /**
2
+ * The strands this party joined from ANOTHER party, held in two records.
3
+ *
4
+ * A party's own strands come back after a restart through its control database: the
5
+ * `Strand` table holds their rows, the strand watcher polls it, and each row no sApp
6
+ * config claims is offered as `strand:discovered`. A strand joined through formation with
7
+ * another party (`CadreNode.formStrand`) has its `Strand` row in the OTHER party's control
8
+ * database, so it needs a record of its own (gotchoices/sereus#18):
9
+ *
10
+ * - the PARTY-WIDE record, a `CadreControl.JoinedStrand` row ({@link PartyJoinedStrandLedger}).
11
+ * Once it exists it is the authority: every machine of the party offers it, a storage
12
+ * replica host launches it, and removing it is how the party leaves the strand;
13
+ * - the MACHINE-LOCAL record ({@link JoinedStrandStore}, below), a queue of joins this
14
+ * machine made that the party does not know about yet. A join is recorded here first,
15
+ * published by an owner machine's connected reconcile pass, and forgotten as soon as the
16
+ * party-wide row is visible, so a local record always means "joined here, not yet
17
+ * published". A machine that is not an owner never publishes; its joins stay here.
18
+ *
19
+ * {@link JoinedStrandSession} moves joins between the two and is what the strand watcher
20
+ * polls beside the control rows.
21
+ *
22
+ * Two store implementations:
23
+ * - {@link MemoryJoinedStrandStore} — joins die with the process. The default only for a
24
+ * node configured with no `keyStore`.
25
+ * - {@link KeyStoreJoinedStrandStore} — one {@link KeyStore} slot per join. A record holds
26
+ * the closed strand's shared read secret, and the KeyStore is the one seam every
27
+ * platform already routes secrets through (the platform enclave on React Native, the
28
+ * state directory for `FileKeyStore`), so the record goes there rather than into a
29
+ * `DurableSlot` like the bootstrap-peer store.
30
+ *
31
+ * Party-scoped like every other node-local store, because one KeyStore can serve several
32
+ * parties: the React Native app keeps one per device and lets the user switch party. A
33
+ * join made for one party must never be offered to a node started for another.
34
+ *
35
+ * Dependency-free beyond the KeyStore seam, so safe in every entry graph.
36
+ */
37
+ import debug from 'debug';
38
+ import { toString as uint8ArrayToString, fromString as uint8ArrayFromString } from 'uint8arrays';
39
+ import type { KeyId, KeyStore } from './key-store.js';
40
+ import { assertStrandScopeKey, isValidStrandScopeKey } from './storage-scope.js';
41
+ import type { StrandRow } from './types.js';
42
+
43
+ const log = debug('sereus:cadre:joined-strand-store');
44
+
45
+ /** One strand this node joined from ANOTHER party and has not yet published party-wide. */
46
+ export interface JoinedStrandRecord {
47
+ /** The strand id (a valid scope key, see storage-scope.ts). */
48
+ Id: string;
49
+ Type: 'o' | 'c';
50
+ /** The closed strand's shared read secret the formation delivered; null for an open strand. */
51
+ MemberPrivateKey: string | null;
52
+ /** Wall-clock ms this node first recorded the join. Diagnostics only. */
53
+ joinedAt: number;
54
+ }
55
+
56
+ export interface JoinedStrandStore {
57
+ /** Party this store is scoped to. */
58
+ readonly partyId: string;
59
+
60
+ /** Every remembered join. A call reflects every {@link record}/{@link forget} that resolved before it was made. */
61
+ list(): Promise<JoinedStrandRecord[]>;
62
+
63
+ /** Remember a join, REPLACING any record with the same `Id`. */
64
+ record(record: JoinedStrandRecord): Promise<void>;
65
+
66
+ /** Forget a join. A no-op when there is no record for `strandId`. */
67
+ forget(strandId: string): Promise<void>;
68
+ }
69
+
70
+ /**
71
+ * The {@link StrandRow} a record stands for — the shape `addStrand` and `strand:discovered`
72
+ * carry. `FounderOwnerKey` is null because a joiner never founds; `CadreNode.launchStrand`
73
+ * reads null as "not mine" and joins.
74
+ */
75
+ export function joinedStrandRow(record: JoinedStrandRecord): StrandRow {
76
+ return { Id: record.Id, Type: record.Type, MemberPrivateKey: record.MemberPrivateKey, FounderOwnerKey: null };
77
+ }
78
+
79
+ /**
80
+ * Ephemeral store for a node without a `keyStore`. Warns once, at the first join it is
81
+ * asked to remember, because a join held only here is not re-offered after a restart —
82
+ * exactly the gotchoices/sereus#18 shape, and it should show in a log rather than pass
83
+ * silently.
84
+ */
85
+ export class MemoryJoinedStrandStore implements JoinedStrandStore {
86
+ private readonly records = new Map<string, JoinedStrandRecord>();
87
+ private warned = false;
88
+
89
+ constructor(readonly partyId: string) {}
90
+
91
+ async list(): Promise<JoinedStrandRecord[]> {
92
+ return [...this.records.values()];
93
+ }
94
+
95
+ async record(record: JoinedStrandRecord): Promise<void> {
96
+ this.warnOnce();
97
+ this.records.set(record.Id, { ...record });
98
+ }
99
+
100
+ async forget(strandId: string): Promise<void> {
101
+ this.records.delete(strandId);
102
+ }
103
+
104
+ private warnOnce(): void {
105
+ if (this.warned) {
106
+ return;
107
+ }
108
+ this.warned = true;
109
+ console.warn(
110
+ 'CadreNode has no keyStore and no joinedStrands.store, so strands joined from another party ' +
111
+ 'are remembered in memory only and will NOT be re-offered after a restart. Configure a keyStore, ' +
112
+ 'or inject joinedStrands: { store: new KeyStoreJoinedStrandStore(<a durable KeyStore>, partyId) }.'
113
+ );
114
+ }
115
+ }
116
+
117
+ /** Slot id prefix for every joined-strand record; the party segment and the strand id follow. */
118
+ const SLOT_PREFIX = 'cadre/joined-strand/';
119
+
120
+ /**
121
+ * Durable store over a {@link KeyStore}: one slot per join, id
122
+ * `cadre/joined-strand/<base64url party id>/<strand id>`, holding the record's UTF-8 JSON.
123
+ * The party segment is base64url for the reason `controlStorageScope` gives: a party id is
124
+ * arbitrary text, and base64url never contains the `/` that ends the segment.
125
+ *
126
+ * Loads every slot once, at the first {@link list}, then answers from memory and writes
127
+ * through, so the strand watcher's five-second poll does not read the enclave on every
128
+ * pass. A load that fails — `KeyStoreAccessError` from a refused unlock prompt, say —
129
+ * is rethrown rather than read as "no joins" and retried at the next call, exactly as
130
+ * `loadOrCreateIdentityKey` treats the identity slot. A slot that does not parse as a
131
+ * record for its own id is dropped with a log and its siblings kept: refusing to start
132
+ * repairs nothing, and the other joins are still good.
133
+ */
134
+ export class KeyStoreJoinedStrandStore implements JoinedStrandStore {
135
+ private readonly slotPrefix: string;
136
+ /** The loaded records; null until a load succeeds. */
137
+ private records: Map<string, JoinedStrandRecord> | null = null;
138
+ /** Runs every KeyStore access in call order, so a load never interleaves with a write. */
139
+ private queue: Promise<unknown> = Promise.resolve();
140
+
141
+ constructor(private readonly keyStore: KeyStore, readonly partyId: string) {
142
+ this.slotPrefix = SLOT_PREFIX + uint8ArrayToString(uint8ArrayFromString(partyId, 'utf8'), 'base64url') + '/';
143
+ }
144
+
145
+ list(): Promise<JoinedStrandRecord[]> {
146
+ return this.inOrder(async () => [...(await this.loaded()).values()]);
147
+ }
148
+
149
+ /** Throws `InvalidStrandIdError` for an id that could never load back, before anything is written. */
150
+ record(record: JoinedStrandRecord): Promise<void> {
151
+ assertStrandScopeKey(record.Id);
152
+ const stored: JoinedStrandRecord = { ...record };
153
+ return this.inOrder(async () => {
154
+ await this.keyStore.set(this.slotId(record.Id), uint8ArrayFromString(JSON.stringify(stored), 'utf8'));
155
+ this.records?.set(record.Id, stored);
156
+ log('joined strand remembered (party=%s, strand=%s, type=%s)', this.partyId, record.Id, record.Type);
157
+ });
158
+ }
159
+
160
+ forget(strandId: string): Promise<void> {
161
+ return this.inOrder(async () => {
162
+ await this.keyStore.delete(this.slotId(strandId));
163
+ this.records?.delete(strandId);
164
+ log('joined strand forgotten (party=%s, strand=%s)', this.partyId, strandId);
165
+ });
166
+ }
167
+
168
+ private slotId(strandId: string): KeyId {
169
+ return this.slotPrefix + strandId;
170
+ }
171
+
172
+ private inOrder<T>(op: () => Promise<T>): Promise<T> {
173
+ const result = this.queue.then(op);
174
+ // The caller receives `result`, rejection included; the queue only needs to know it settled.
175
+ this.queue = result.catch(() => undefined);
176
+ return result;
177
+ }
178
+
179
+ // NOTE: a failed load is retried at the next list(), which is every strand-watcher poll;
180
+ // over a backend that gates reads behind an unlock prompt the user keeps declining, that
181
+ // is a prompt every five seconds. Every KeyStore shipped today is ungated for this reason
182
+ // (see `SecureStoreKeyStoreOptions.requireAuthentication`); if one is ever gated, back
183
+ // off the retry here.
184
+ private async loaded(): Promise<Map<string, JoinedStrandRecord>> {
185
+ if (this.records) {
186
+ return this.records;
187
+ }
188
+ const records = new Map<string, JoinedStrandRecord>();
189
+ for (const slot of await this.keyStore.list()) {
190
+ if (!slot.startsWith(this.slotPrefix)) {
191
+ continue;
192
+ }
193
+ const strandId = slot.slice(this.slotPrefix.length);
194
+ const bytes = await this.keyStore.get(slot);
195
+ if (!bytes) {
196
+ continue;
197
+ }
198
+ const record = parseRecord(strandId, bytes);
199
+ if (record) {
200
+ records.set(strandId, record);
201
+ }
202
+ }
203
+ this.records = records;
204
+ log('joined strands loaded (party=%s, count=%d)', this.partyId, records.size);
205
+ return records;
206
+ }
207
+ }
208
+
209
+ /** The record a slot holds, or undefined (logged) when it is not one for `strandId`. */
210
+ function parseRecord(strandId: string, bytes: Uint8Array): JoinedStrandRecord | undefined {
211
+ let parsed: unknown;
212
+ try {
213
+ parsed = JSON.parse(uint8ArrayToString(bytes, 'utf8'));
214
+ } catch (error) {
215
+ log('dropping joined-strand slot for %s: not JSON (%o)', strandId, error);
216
+ return undefined;
217
+ }
218
+ const { Id, Type, MemberPrivateKey, joinedAt } = (typeof parsed === 'object' && parsed !== null ? parsed : {}) as Record<string, unknown>;
219
+ const valid = Id === strandId
220
+ && isValidStrandScopeKey(strandId)
221
+ && (Type === 'o' || Type === 'c')
222
+ && (MemberPrivateKey === null || typeof MemberPrivateKey === 'string')
223
+ && typeof joinedAt === 'number';
224
+ if (!valid) {
225
+ log('dropping joined-strand slot for %s: not a joined-strand record for that id', strandId);
226
+ return undefined;
227
+ }
228
+ return { Id: strandId, Type: Type as 'o' | 'c', MemberPrivateKey: MemberPrivateKey as string | null, joinedAt: joinedAt as number };
229
+ }
230
+
231
+ /**
232
+ * The party-wide joined-strand table (`CadreControl.JoinedStrand`), as the node's control
233
+ * database exposes it. `CadreNode` builds it over `ControlDatabase` and the owner signing
234
+ * key; this module sees only the seam, so it stays free of the runtime.
235
+ */
236
+ export interface PartyJoinedStrandLedger {
237
+ /** Every party-wide join, as offerable rows (`FounderOwnerKey: null`). */
238
+ list(): Promise<StrandRow[]>;
239
+ /** Whether this party's control database names `strandId`, as its own strand or as a party-wide join. */
240
+ names(strandId: string): Promise<boolean>;
241
+ /** Whether this machine can sign {@link publish} and {@link remove}: it holds an owner key the party enrolls. */
242
+ canSign(): Promise<boolean>;
243
+ /** Owner-signed insert. Resolves when the row landed or a sibling's join already holds the id. */
244
+ publish(record: JoinedStrandRecord): Promise<void>;
245
+ /** Owner-signed delete + tombstone; false when there is no row. Throws when a row exists and this machine cannot sign. */
246
+ remove(strandId: string): Promise<boolean>;
247
+ }
248
+
249
+ /**
250
+ * One node session's joined strands: what the strand watcher sees of the two records, and
251
+ * the moves between them. Rebuilt at every start, which is what ends the per-session state
252
+ * below.
253
+ *
254
+ * The watcher reads a row missing from a poll as a removal and detaches the strand, so this
255
+ * holds the state a plain union would get wrong:
256
+ * - the last list each record answered, reused when a later read fails, so a failed read
257
+ * is not "every join was forgotten";
258
+ * - joins this party was removed from ({@link forgetAfterThisSession}): offered until this
259
+ * session ends, because `strand:revoked` promises that nothing is torn down for the app,
260
+ * and queued for party-wide removal so the next start does not re-attach them.
261
+ */
262
+ export class JoinedStrandSession {
263
+ private lastUnpublished: JoinedStrandRecord[] = [];
264
+ private lastPartyWide: StrandRow[] = [];
265
+ private readonly keptForSession = new Map<string, StrandRow>();
266
+ /** Strands whose party-wide row {@link syncWithParty} removes, queued by a self-revocation. */
267
+ private readonly pendingRemovals = new Set<string>();
268
+ /**
269
+ * Tail of the moves that must not interleave ({@link serialized}): a publish that found no
270
+ * party-wide row, then a {@link leave} that removed nothing, then the publish's insert
271
+ * would leave the party holding a strand the app just left.
272
+ */
273
+ private exclusive: Promise<unknown> = Promise.resolve();
274
+
275
+ constructor(private readonly store: JoinedStrandStore, private readonly ledger: PartyJoinedStrandLedger) {}
276
+
277
+ /**
278
+ * `control` plus every join, one row per id, in this precedence: the control rows (the
279
+ * party's own strands), then the party-wide joins, then this machine's unpublished joins
280
+ * and the joins kept for this session. A local record named by either of the first two in
281
+ * a read that succeeded this poll is stale — published, or the strand is the party's own
282
+ * now — so it is forgotten here; this also cleans up after a crash between a publish and
283
+ * its local forget. One named only by the last-good party-wide list is kept: that list may
284
+ * predate a leave the record re-joined after.
285
+ */
286
+ async withControlRows(control: readonly StrandRow[]): Promise<StrandRow[]> {
287
+ const controlIds = new Set(control.map((row) => row.Id));
288
+ const named = new Set(controlIds);
289
+ const offered = new Map<string, StrandRow>(control.map((row) => [row.Id, row]));
290
+ const partyWide = await this.partyWide();
291
+ // NOTE: a party-wide join whose id the party's own `Strand` table also holds (the party
292
+ // founded AND joined it — contrived) is shadowed here, not deleted: a watcher poll must
293
+ // not make owner-signed writes. If the party later unpublishes its own row the join row
294
+ // resurfaces; if that is ever seen, remove the join row inside `unpublishStrand`.
295
+ for (const row of partyWide.rows) {
296
+ if (!offered.has(row.Id)) {
297
+ offered.set(row.Id, row);
298
+ }
299
+ if (partyWide.fresh) {
300
+ named.add(row.Id);
301
+ }
302
+ }
303
+ for (const record of await this.unpublished()) {
304
+ if (named.has(record.Id)) {
305
+ await this.forgetSuperseded(record.Id);
306
+ } else if (!offered.has(record.Id)) {
307
+ offered.set(record.Id, joinedStrandRow(record));
308
+ }
309
+ }
310
+ for (const [strandId, row] of this.keptForSession) {
311
+ if (controlIds.has(strandId)) {
312
+ this.keptForSession.delete(strandId);
313
+ } else if (!offered.has(strandId)) {
314
+ offered.set(strandId, row);
315
+ }
316
+ }
317
+ return [...offered.values()];
318
+ }
319
+
320
+ /** Record a join `formStrand` just made. A re-join also cancels a removal a revocation queued. */
321
+ async remember(record: JoinedStrandRecord): Promise<void> {
322
+ this.pendingRemovals.delete(record.Id);
323
+ await this.store.record(record);
324
+ }
325
+
326
+ /**
327
+ * Record `row`, joined by `addStrand`, unless this party's control database already names
328
+ * it (its own strand, or a join already published) or an identical record is already here
329
+ * (an app re-claiming a remembered join on every start). Keeps the first `joinedAt`. Like
330
+ * {@link remember}, cancels a queued removal.
331
+ */
332
+ async rememberForeign(row: StrandRow): Promise<void> {
333
+ this.pendingRemovals.delete(row.Id);
334
+ if (await this.namedByParty(row.Id)) {
335
+ return;
336
+ }
337
+ const existing = (await this.store.list()).find((record) => record.Id === row.Id);
338
+ if (existing?.Type === row.Type && existing.MemberPrivateKey === row.MemberPrivateKey) {
339
+ return;
340
+ }
341
+ await this.store.record({
342
+ Id: row.Id,
343
+ Type: row.Type,
344
+ MemberPrivateKey: row.MemberPrivateKey,
345
+ joinedAt: existing?.joinedAt ?? Date.now()
346
+ });
347
+ }
348
+
349
+ /**
350
+ * Leave a join for the whole party: remove the party-wide row, then this machine's record.
351
+ * Throws, keeping both, when a party-wide row exists and this machine cannot sign.
352
+ */
353
+ leave(strandId: string): Promise<void> {
354
+ return this.serialized(async () => {
355
+ await this.ledger.remove(strandId);
356
+ this.pendingRemovals.delete(strandId);
357
+ this.keptForSession.delete(strandId);
358
+ this.lastPartyWide = this.lastPartyWide.filter((row) => row.Id !== strandId);
359
+ await this.store.forget(strandId);
360
+ });
361
+ }
362
+
363
+ /**
364
+ * For a strand this party was removed from: keep offering it until this session ends, and
365
+ * queue its party-wide row for removal by {@link syncWithParty}, so it does not re-attach
366
+ * on every start of every machine. A no-op for a strand with neither record (one of the
367
+ * party's own). The queue is in memory: if the process dies first, the next start
368
+ * relaunches the strand, the revoked-peer gate raises `strand:revoked` again, and this
369
+ * runs again.
370
+ */
371
+ forgetAfterThisSession(strandId: string): Promise<void> {
372
+ return this.serialized(async () => {
373
+ const local = (await this.unpublished()).find((record) => record.Id === strandId);
374
+ const row = local ? joinedStrandRow(local) : this.lastPartyWide.find((listed) => listed.Id === strandId);
375
+ if (!row) {
376
+ return;
377
+ }
378
+ // Kept BEFORE the store forgets, so no poll can union without it. Queued even for a
379
+ // local-only join, which a sibling may have published already.
380
+ this.keptForSession.set(strandId, row);
381
+ this.pendingRemovals.add(strandId);
382
+ if (local) {
383
+ await this.store.forget(strandId);
384
+ }
385
+ });
386
+ }
387
+
388
+ /**
389
+ * The owner machine's half, run by the node's connected reconcile pass: publish every
390
+ * unpublished join party-wide, then remove the party-wide rows queued by
391
+ * {@link forgetAfterThisSession}. Does nothing on a machine that cannot sign, whose joins
392
+ * stay machine-local. Per strand, a failure is logged and kept for the next pass; a
393
+ * failure to list the store or to check the signer throws.
394
+ */
395
+ syncWithParty(): Promise<void> {
396
+ return this.serialized(async () => {
397
+ // Straight from the store, never the last-good list: a stale list could republish a
398
+ // join that was left since.
399
+ const unpublished = await this.store.list();
400
+ if (unpublished.length === 0 && this.pendingRemovals.size === 0) {
401
+ return;
402
+ }
403
+ if (!(await this.ledger.canSign())) {
404
+ return;
405
+ }
406
+ for (const record of unpublished) {
407
+ await this.publish(record);
408
+ }
409
+ for (const strandId of [...this.pendingRemovals]) {
410
+ await this.removeQueued(strandId);
411
+ }
412
+ });
413
+ }
414
+
415
+ // NOTE: a sibling that joined the same strand and has not yet published publishes it after
416
+ // a leave, bringing the strand back party-wide. Needs two devices joining one strand within
417
+ // a reconcile interval of the leave; if it is ever seen, check the strand's `Revocation`
418
+ // tombstone before publishing.
419
+ private async publish(record: JoinedStrandRecord): Promise<void> {
420
+ try {
421
+ if (!(await this.ledger.names(record.Id))) {
422
+ await this.ledger.publish(record);
423
+ // Into the last-good list too: its local record goes next, so a party-wide read that
424
+ // fails before one succeeds would otherwise drop the strand from the poll and hide it
425
+ // from a self-revocation.
426
+ this.lastPartyWide = [...this.lastPartyWide.filter((row) => row.Id !== record.Id), joinedStrandRow(record)];
427
+ log('joined strand %s published party-wide (party=%s)', record.Id, this.store.partyId);
428
+ }
429
+ await this.store.forget(record.Id);
430
+ } catch (error) {
431
+ log('joined strand %s: publishing party-wide failed; kept for the next pass: %o', record.Id, error);
432
+ }
433
+ }
434
+
435
+ private async removeQueued(strandId: string): Promise<void> {
436
+ try {
437
+ const removed = await this.ledger.remove(strandId);
438
+ this.pendingRemovals.delete(strandId);
439
+ log('joined strand %s: party-wide row %s after this party was removed from it',
440
+ strandId, removed ? 'removed' : 'already absent');
441
+ } catch (error) {
442
+ log('joined strand %s: removing the party-wide row failed; queued for the next pass: %o', strandId, error);
443
+ }
444
+ }
445
+
446
+ /** The party-wide joins; `fresh` is false when this read failed and the last list it answered stands in. */
447
+ private async partyWide(): Promise<{ rows: StrandRow[]; fresh: boolean }> {
448
+ try {
449
+ this.lastPartyWide = await this.ledger.list();
450
+ return { rows: this.lastPartyWide, fresh: true };
451
+ } catch (error) {
452
+ log('party-wide joined-strand read failed; offering the last list it answered (%d join(s)): %o',
453
+ this.lastPartyWide.length, error);
454
+ return { rows: this.lastPartyWide, fresh: false };
455
+ }
456
+ }
457
+
458
+ /**
459
+ * {@link PartyJoinedStrandLedger.names}, answering false when the control database cannot
460
+ * be read (a machine cut off from its party before it received the `JoinedStrand` block).
461
+ * Recording is the safe side: a local record the party turns out to name is forgotten by
462
+ * the next poll that reads it, while a join with no record is not offered after a restart.
463
+ */
464
+ private async namedByParty(strandId: string): Promise<boolean> {
465
+ try {
466
+ return await this.ledger.names(strandId);
467
+ } catch (error) {
468
+ log('joined strand %s: could not read whether the control database names it; recording it locally: %o', strandId, error);
469
+ return false;
470
+ }
471
+ }
472
+
473
+ /** Run `work` after every earlier serialized move settles; see {@link exclusive}. */
474
+ private serialized<T>(work: () => Promise<T>): Promise<T> {
475
+ const result = this.exclusive.then(work);
476
+ this.exclusive = result.catch(() => undefined);
477
+ return result;
478
+ }
479
+
480
+ private async unpublished(): Promise<JoinedStrandRecord[]> {
481
+ try {
482
+ this.lastUnpublished = await this.store.list();
483
+ } catch (error) {
484
+ log('joined-strand store list failed; offering the last list it answered (%d join(s)): %o',
485
+ this.lastUnpublished.length, error);
486
+ }
487
+ return this.lastUnpublished;
488
+ }
489
+
490
+ private async forgetSuperseded(strandId: string): Promise<void> {
491
+ try {
492
+ await this.store.forget(strandId);
493
+ log('joined strand %s is named by this party\'s control database — local record forgotten', strandId);
494
+ } catch (error) {
495
+ log('forgetting superseded joined strand %s failed; the next poll retries: %o', strandId, error);
496
+ }
497
+ }
498
+ }