@serfab/cadre-core 1.23.0 → 1.24.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 (313) hide show
  1. package/README.md +216 -294
  2. package/dist/arachnode-stub.d.ts +12 -4
  3. package/dist/arachnode-stub.js +15 -8
  4. package/dist/arachnode-stub.js.map +1 -1
  5. package/dist/cadre-invite-protocol.js +5 -4
  6. package/dist/cadre-invite-protocol.js.map +1 -1
  7. package/dist/cadre-node.d.ts +145 -44
  8. package/dist/cadre-node.js +239 -79
  9. package/dist/cadre-node.js.map +1 -1
  10. package/dist/control-authorization.d.ts +14 -2
  11. package/dist/control-authorization.js +8 -3
  12. package/dist/control-authorization.js.map +1 -1
  13. package/dist/control-cohort.d.ts +27 -13
  14. package/dist/control-cohort.js +21 -14
  15. package/dist/control-cohort.js.map +1 -1
  16. package/dist/control-database.d.ts +18 -16
  17. package/dist/control-database.js +57 -22
  18. package/dist/control-database.js.map +1 -1
  19. package/dist/control-protocol-guard.d.ts +1 -1
  20. package/dist/control-protocol-guard.js +7 -3
  21. package/dist/control-protocol-guard.js.map +1 -1
  22. package/dist/control-read-retry.d.ts +49 -11
  23. package/dist/control-read-retry.js +56 -15
  24. package/dist/control-read-retry.js.map +1 -1
  25. package/dist/control-retry.d.ts +32 -3
  26. package/dist/control-retry.js +35 -4
  27. package/dist/control-retry.js.map +1 -1
  28. package/dist/control-schema-version.d.ts +5 -5
  29. package/dist/control-schema-version.js +5 -5
  30. package/dist/control-schema-version.js.map +1 -1
  31. package/dist/control-schema.d.ts +5 -5
  32. package/dist/control-schema.js +1032 -1011
  33. package/dist/control-schema.js.map +1 -1
  34. package/dist/control-write-retry.d.ts +54 -65
  35. package/dist/control-write-retry.js +134 -158
  36. package/dist/control-write-retry.js.map +1 -1
  37. package/dist/delegate-admission.d.ts +1 -1
  38. package/dist/delegate-admission.js +1 -1
  39. package/dist/edge-node/config.d.ts +4 -3
  40. package/dist/edge-node/config.js +11 -9
  41. package/dist/edge-node/config.js.map +1 -1
  42. package/dist/edge-node/dissolve.d.ts +4 -4
  43. package/dist/edge-node/dissolve.js +4 -4
  44. package/dist/edge-node/edge-join.d.ts +1 -1
  45. package/dist/edge-node/edge-join.js +1 -1
  46. package/dist/edge-node/edge-node.js +2 -2
  47. package/dist/edge-node/edge-node.js.map +1 -1
  48. package/dist/edge-node/index.d.ts +1 -0
  49. package/dist/edge-node/index.js +1 -0
  50. package/dist/edge-node/index.js.map +1 -1
  51. package/dist/edge-node/join-credential.d.ts +1 -1
  52. package/dist/edge-node/join-credential.js +1 -1
  53. package/dist/edge-node/lazy-raw-storage.js +12 -0
  54. package/dist/edge-node/lazy-raw-storage.js.map +1 -1
  55. package/dist/edge-node/listen-addrs.d.ts +21 -0
  56. package/dist/edge-node/listen-addrs.js +25 -0
  57. package/dist/edge-node/listen-addrs.js.map +1 -0
  58. package/dist/edge-node/owner-grant.d.ts +1 -1
  59. package/dist/edge-node/owner-grant.js +1 -1
  60. package/dist/edge-node/platform.d.ts +5 -4
  61. package/dist/edge-node/platform.js.map +1 -1
  62. package/dist/edge-node/strand-move.d.ts +1 -1
  63. package/dist/edge-node/strand-move.js +1 -1
  64. package/dist/edge-node/strands.js +27 -11
  65. package/dist/edge-node/strands.js.map +1 -1
  66. package/dist/index.d.ts +7 -5
  67. package/dist/index.js +18 -7
  68. package/dist/index.js.map +1 -1
  69. package/dist/invitation-bootstrap.d.ts +28 -5
  70. package/dist/invitation-bootstrap.js +41 -8
  71. package/dist/invitation-bootstrap.js.map +1 -1
  72. package/dist/link-budget.d.ts +53 -4
  73. package/dist/link-budget.js +58 -5
  74. package/dist/link-budget.js.map +1 -1
  75. package/dist/machine-removal.d.ts +2 -2
  76. package/dist/machine-removal.js +4 -3
  77. package/dist/machine-removal.js.map +1 -1
  78. package/dist/membership-connection-gater.d.ts +2 -2
  79. package/dist/membership-connection-gater.js +2 -2
  80. package/dist/membership-view.d.ts +2 -2
  81. package/dist/membership-view.js +2 -2
  82. package/dist/node-claim-payload.d.ts +15 -7
  83. package/dist/node-claim-payload.js +25 -9
  84. package/dist/node-claim-payload.js.map +1 -1
  85. package/dist/node-class.d.ts +36 -0
  86. package/dist/node-class.js +26 -0
  87. package/dist/node-class.js.map +1 -0
  88. package/dist/node-default-transports.d.ts +50 -3
  89. package/dist/node-default-transports.js +48 -3
  90. package/dist/node-default-transports.js.map +1 -1
  91. package/dist/node-roles.d.ts +118 -0
  92. package/dist/node-roles.js +142 -0
  93. package/dist/node-roles.js.map +1 -0
  94. package/dist/node-transports.d.ts +6 -2
  95. package/dist/node-transports.js +39 -7
  96. package/dist/node-transports.js.map +1 -1
  97. package/dist/owner-anchor-sync.js +1 -1
  98. package/dist/owner-key-export.js +1 -1
  99. package/dist/owner-key-flows.d.ts +1 -1
  100. package/dist/owner-key-store.js +1 -1
  101. package/dist/owner-signer.js +1 -1
  102. package/dist/peer-authorization.d.ts +3 -1
  103. package/dist/peer-authorization.js +3 -1
  104. package/dist/peer-authorization.js.map +1 -1
  105. package/dist/peer-dial.d.ts +74 -10
  106. package/dist/peer-dial.js +89 -17
  107. package/dist/peer-dial.js.map +1 -1
  108. package/dist/peer-join-backfill.js +4 -4
  109. package/dist/peer-join-backfill.js.map +1 -1
  110. package/dist/peer-record.d.ts +34 -9
  111. package/dist/peer-record.js +66 -13
  112. package/dist/peer-record.js.map +1 -1
  113. package/dist/pending-join-runner.d.ts +1 -1
  114. package/dist/pending-join-runner.js +1 -1
  115. package/dist/provider/client.d.ts +6 -5
  116. package/dist/provider/client.js +3 -3
  117. package/dist/provider/client.js.map +1 -1
  118. package/dist/provider/descriptor.d.ts +1 -1
  119. package/dist/provider/descriptor.js +1 -1
  120. package/dist/provider/oauth.d.ts +1 -1
  121. package/dist/provider/oauth.js +1 -1
  122. package/dist/provider/rent-node.d.ts +4 -3
  123. package/dist/provider/rent-node.js +3 -3
  124. package/dist/provider/rent-node.js.map +1 -1
  125. package/dist/relay-addrs.d.ts +62 -7
  126. package/dist/relay-addrs.js +74 -11
  127. package/dist/relay-addrs.js.map +1 -1
  128. package/dist/relay-reservation.d.ts +1 -1
  129. package/dist/relay-reservation.js +1 -1
  130. package/dist/relay-server.d.ts +6 -5
  131. package/dist/relay-server.js +5 -5
  132. package/dist/relay-server.js.map +1 -1
  133. package/dist/schema-verification.d.ts +13 -10
  134. package/dist/schema-verification.js +32 -24
  135. package/dist/schema-verification.js.map +1 -1
  136. package/dist/sealed-party-key.js +1 -1
  137. package/dist/seed-bootstrap.d.ts +4 -3
  138. package/dist/seed-bootstrap.js +6 -7
  139. package/dist/seed-bootstrap.js.map +1 -1
  140. package/dist/strand-addr-protocol.d.ts +8 -6
  141. package/dist/strand-addr-protocol.js +12 -10
  142. package/dist/strand-addr-protocol.js.map +1 -1
  143. package/dist/strand-app-schema-report.d.ts +16 -2
  144. package/dist/strand-app-schema-report.js +15 -0
  145. package/dist/strand-app-schema-report.js.map +1 -1
  146. package/dist/strand-cohort.d.ts +1 -4
  147. package/dist/strand-cohort.js.map +1 -1
  148. package/dist/strand-commit-durability.d.ts +1 -1
  149. package/dist/strand-database.d.ts +13 -6
  150. package/dist/strand-database.js +17 -9
  151. package/dist/strand-database.js.map +1 -1
  152. package/dist/strand-first-sync-gate.d.ts +3 -2
  153. package/dist/strand-first-sync-gate.js +3 -2
  154. package/dist/strand-first-sync-gate.js.map +1 -1
  155. package/dist/strand-formation-deadlines.d.ts +2 -2
  156. package/dist/strand-formation-deadlines.js +2 -2
  157. package/dist/strand-formation-protocol.d.ts +1 -1
  158. package/dist/strand-formation-protocol.js +51 -16
  159. package/dist/strand-formation-protocol.js.map +1 -1
  160. package/dist/strand-instance-manager.d.ts +67 -33
  161. package/dist/strand-instance-manager.js +164 -55
  162. package/dist/strand-instance-manager.js.map +1 -1
  163. package/dist/strand-membership-reconciler.d.ts +8 -3
  164. package/dist/strand-membership-reconciler.js +8 -3
  165. package/dist/strand-membership-reconciler.js.map +1 -1
  166. package/dist/strand-membership-writer.d.ts +2 -2
  167. package/dist/strand-membership-writer.js +41 -39
  168. package/dist/strand-membership-writer.js.map +1 -1
  169. package/dist/strand-move.js +1 -1
  170. package/dist/strand-network-config.d.ts +15 -5
  171. package/dist/strand-network-config.js +7 -6
  172. package/dist/strand-network-config.js.map +1 -1
  173. package/dist/strand-party-key-rotation.d.ts +7 -3
  174. package/dist/strand-party-key-rotation.js +7 -3
  175. package/dist/strand-party-key-rotation.js.map +1 -1
  176. package/dist/strand-party-machines.d.ts +19 -8
  177. package/dist/strand-party-machines.js +26 -11
  178. package/dist/strand-party-machines.js.map +1 -1
  179. package/dist/strand-party-peers.d.ts +36 -14
  180. package/dist/strand-party-peers.js +24 -15
  181. package/dist/strand-party-peers.js.map +1 -1
  182. package/dist/strand-peer-redial.d.ts +1 -1
  183. package/dist/strand-peer-redial.js +1 -1
  184. package/dist/strand-reactivity.d.ts +20 -17
  185. package/dist/strand-reactivity.js +31 -18
  186. package/dist/strand-reactivity.js.map +1 -1
  187. package/dist/strand-revocation-enforcer.d.ts +3 -3
  188. package/dist/strand-revocation-enforcer.js +3 -3
  189. package/dist/strand-wake-protocol.d.ts +19 -7
  190. package/dist/strand-wake-protocol.js +22 -10
  191. package/dist/strand-wake-protocol.js.map +1 -1
  192. package/dist/strand-watcher.d.ts +1 -1
  193. package/dist/strand-watcher.js +1 -1
  194. package/dist/table-change-watch.js +1 -1
  195. package/dist/types.d.ts +116 -55
  196. package/dist/types.js.map +1 -1
  197. package/dist/webrtc-upgrade.d.ts +254 -0
  198. package/dist/webrtc-upgrade.js +355 -0
  199. package/dist/webrtc-upgrade.js.map +1 -0
  200. package/package.json +9 -9
  201. package/src/announce-addrs.ts +93 -93
  202. package/src/arachnode-stub.ts +18 -10
  203. package/src/bootstrap-peer-store-file.ts +44 -44
  204. package/src/bootstrap-peer-store.ts +214 -214
  205. package/src/cadre-invite-protocol.ts +741 -740
  206. package/src/cadre-node.ts +12462 -12280
  207. package/src/claim-proof.ts +147 -147
  208. package/src/control-authorization.ts +290 -276
  209. package/src/control-cohort.ts +223 -204
  210. package/src/control-database.ts +72 -28
  211. package/src/control-formation-recorder.ts +359 -359
  212. package/src/control-protocol-guard.ts +370 -366
  213. package/src/control-read-retry.ts +222 -180
  214. package/src/control-retry.ts +36 -4
  215. package/src/control-schema-version.ts +301 -301
  216. package/src/control-schema.ts +1108 -1087
  217. package/src/control-write-retry.ts +639 -669
  218. package/src/delegate-admission.ts +351 -351
  219. package/src/describe-thrown.ts +60 -60
  220. package/src/ed25519-key.ts +185 -185
  221. package/src/edge-node/config.ts +13 -10
  222. package/src/edge-node/dissolve.ts +252 -252
  223. package/src/edge-node/edge-join.ts +320 -320
  224. package/src/edge-node/edge-node.ts +1095 -1095
  225. package/src/edge-node/index.ts +60 -59
  226. package/src/edge-node/join-credential.ts +16 -16
  227. package/src/edge-node/lazy-raw-storage.ts +194 -178
  228. package/src/edge-node/listen-addrs.ts +26 -0
  229. package/src/edge-node/node-local.ts +84 -84
  230. package/src/edge-node/options.ts +195 -195
  231. package/src/edge-node/owner-grant.ts +63 -63
  232. package/src/edge-node/platform.ts +5 -4
  233. package/src/edge-node/strand-move.ts +266 -266
  234. package/src/edge-node/strands.ts +27 -12
  235. package/src/enrolled-machine-store-file.ts +43 -43
  236. package/src/enrolled-machine-store.ts +280 -280
  237. package/src/fetch-impl.ts +23 -23
  238. package/src/file-durable-slot.ts +64 -64
  239. package/src/file-safe-name.ts +32 -32
  240. package/src/formation-approval.ts +604 -604
  241. package/src/formation-token.ts +63 -63
  242. package/src/fs-atomic.ts +92 -92
  243. package/src/index.ts +987 -957
  244. package/src/invitation-bootstrap.ts +152 -118
  245. package/src/joined-strand-store.ts +553 -553
  246. package/src/key-store-file.ts +142 -142
  247. package/src/link-budget.ts +61 -5
  248. package/src/machine-removal.ts +211 -210
  249. package/src/member-redemption.ts +643 -643
  250. package/src/membership-connection-gater.ts +650 -650
  251. package/src/membership-view.ts +147 -147
  252. package/src/node-claim-payload.ts +34 -12
  253. package/src/node-class.ts +47 -0
  254. package/src/node-default-transports.ts +65 -3
  255. package/src/node-roles.ts +220 -0
  256. package/src/node-transports.ts +86 -49
  257. package/src/owner-anchor-sync.ts +172 -172
  258. package/src/owner-grant-protocol.ts +547 -547
  259. package/src/owner-key-export.ts +348 -348
  260. package/src/owner-key-flows.ts +109 -109
  261. package/src/owner-key-store.ts +1 -1
  262. package/src/owner-keys.ts +179 -179
  263. package/src/owner-signer.ts +92 -92
  264. package/src/peer-addr-book.ts +252 -252
  265. package/src/peer-authorization.ts +584 -582
  266. package/src/peer-dial.ts +698 -605
  267. package/src/peer-join-backfill.ts +961 -961
  268. package/src/peer-record.ts +71 -16
  269. package/src/pending-join-runner.ts +798 -798
  270. package/src/primary-lan-address.ts +47 -47
  271. package/src/provider/client.ts +327 -326
  272. package/src/provider/descriptor.ts +129 -129
  273. package/src/provider/index.ts +59 -59
  274. package/src/provider/oauth.ts +285 -285
  275. package/src/provider/rent-node.ts +276 -275
  276. package/src/relay-addrs.ts +90 -12
  277. package/src/relay-reservation.ts +1 -1
  278. package/src/relay-server.ts +99 -98
  279. package/src/schema-verification.ts +38 -23
  280. package/src/sealed-party-key.ts +190 -190
  281. package/src/seed-bootstrap.ts +8 -11
  282. package/src/seed-trust-policy.ts +353 -353
  283. package/src/self-address-update.ts +19 -19
  284. package/src/strand-addr-protocol.ts +17 -14
  285. package/src/strand-app-schema-report.ts +147 -122
  286. package/src/strand-cohort.ts +1 -5
  287. package/src/strand-commit-durability.ts +165 -165
  288. package/src/strand-database.ts +522 -510
  289. package/src/strand-first-sync-gate.ts +3 -2
  290. package/src/strand-formation-deadlines.ts +227 -227
  291. package/src/strand-formation-manager.ts +731 -731
  292. package/src/strand-formation-protocol.ts +1174 -1138
  293. package/src/strand-fret-addrs.ts +179 -179
  294. package/src/strand-instance-manager.ts +188 -63
  295. package/src/strand-membership-reconciler.ts +1315 -1310
  296. package/src/strand-membership-writer.ts +2152 -2150
  297. package/src/strand-move.ts +1 -1
  298. package/src/strand-network-config.ts +16 -6
  299. package/src/strand-offline.ts +178 -178
  300. package/src/strand-party-key-rotation.ts +440 -436
  301. package/src/strand-party-machines.ts +308 -293
  302. package/src/strand-party-peers.ts +151 -129
  303. package/src/strand-peer-redial.ts +1 -1
  304. package/src/strand-reactivity.ts +36 -19
  305. package/src/strand-revocation-enforcer.ts +758 -758
  306. package/src/strand-wake-protocol.ts +406 -394
  307. package/src/strand-watcher.ts +1 -1
  308. package/src/table-change-watch.ts +285 -285
  309. package/src/timed-step.ts +28 -28
  310. package/src/timeout-scheduler.ts +29 -29
  311. package/src/trusted-owner-store.ts +242 -242
  312. package/src/types.ts +3182 -3121
  313. package/src/webrtc-upgrade.ts +439 -0
@@ -1,553 +1,553 @@
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 reads 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
- * reads 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. The founder columns are null because a joiner never founds; `CadreNode.launchStrand`
73
- * reads a null `FounderPeerId` 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, FounderPeerId: null };
77
- }
78
-
79
- function isSameJoin(record: JoinedStrandRecord, row: StrandRow): boolean {
80
- return record.Type === row.Type && record.MemberPrivateKey === row.MemberPrivateKey;
81
- }
82
-
83
- /**
84
- * Ephemeral store for a node without a `keyStore`. Warns once, at the first join it is
85
- * asked to remember, because a join held only here is not re-offered after a restart —
86
- * exactly the gotchoices/sereus#18 shape, and it should show in a log rather than pass
87
- * silently.
88
- */
89
- export class MemoryJoinedStrandStore implements JoinedStrandStore {
90
- private readonly records = new Map<string, JoinedStrandRecord>();
91
- private warned = false;
92
-
93
- constructor(readonly partyId: string) {}
94
-
95
- async list(): Promise<JoinedStrandRecord[]> {
96
- return [...this.records.values()];
97
- }
98
-
99
- async record(record: JoinedStrandRecord): Promise<void> {
100
- this.warnOnce();
101
- this.records.set(record.Id, { ...record });
102
- }
103
-
104
- async forget(strandId: string): Promise<void> {
105
- this.records.delete(strandId);
106
- }
107
-
108
- private warnOnce(): void {
109
- if (this.warned) {
110
- return;
111
- }
112
- this.warned = true;
113
- console.warn(
114
- 'CadreNode has no keyStore and no joinedStrands.store, so strands joined from another party ' +
115
- 'are remembered in memory only and will NOT be re-offered after a restart. Configure a keyStore, ' +
116
- 'or inject joinedStrands: { store: new KeyStoreJoinedStrandStore(<a durable KeyStore>, partyId) }.'
117
- );
118
- }
119
- }
120
-
121
- /** Slot id prefix for every joined-strand record; the party segment and the strand id follow. */
122
- const SLOT_PREFIX = 'cadre/joined-strand/';
123
-
124
- /**
125
- * Durable store over a {@link KeyStore}: one slot per join, id
126
- * `cadre/joined-strand/<base64url party id>/<strand id>`, holding the record's UTF-8 JSON.
127
- * The party segment is base64url for the reason `controlStorageScope` gives: a party id is
128
- * arbitrary text, and base64url never contains the `/` that ends the segment.
129
- *
130
- * Loads every slot once, at the first {@link list}, then answers from memory and writes
131
- * through, so a strand watcher run does not read the enclave each time. A load that
132
- * fails — `KeyStoreAccessError` from a refused unlock prompt, say — is rethrown rather
133
- * than read as "no joins" and retried at the next call, exactly as
134
- * `loadOrCreateIdentityKey` treats the identity slot. A slot that does not parse as a
135
- * record for its own id is dropped with a log and its siblings kept: refusing to start
136
- * repairs nothing, and the other joins are still good.
137
- */
138
- export class KeyStoreJoinedStrandStore implements JoinedStrandStore {
139
- private readonly slotPrefix: string;
140
- /** The loaded records; null until a load succeeds. */
141
- private records: Map<string, JoinedStrandRecord> | null = null;
142
- /** Runs every KeyStore access in call order, so a load never interleaves with a write. */
143
- private queue: Promise<unknown> = Promise.resolve();
144
-
145
- constructor(private readonly keyStore: KeyStore, readonly partyId: string) {
146
- this.slotPrefix = SLOT_PREFIX + uint8ArrayToString(uint8ArrayFromString(partyId, 'utf8'), 'base64url') + '/';
147
- }
148
-
149
- list(): Promise<JoinedStrandRecord[]> {
150
- return this.inOrder(async () => [...(await this.loaded()).values()]);
151
- }
152
-
153
- /** Throws `InvalidStrandIdError` for an id that could never load back, before anything is written. */
154
- record(record: JoinedStrandRecord): Promise<void> {
155
- assertStrandScopeKey(record.Id);
156
- const stored: JoinedStrandRecord = { ...record };
157
- return this.inOrder(async () => {
158
- await this.keyStore.set(this.slotId(record.Id), uint8ArrayFromString(JSON.stringify(stored), 'utf8'));
159
- this.records?.set(record.Id, stored);
160
- log('joined strand remembered (party=%s, strand=%s, type=%s)', this.partyId, record.Id, record.Type);
161
- });
162
- }
163
-
164
- forget(strandId: string): Promise<void> {
165
- return this.inOrder(async () => {
166
- await this.keyStore.delete(this.slotId(strandId));
167
- this.records?.delete(strandId);
168
- log('joined strand forgotten (party=%s, strand=%s)', this.partyId, strandId);
169
- });
170
- }
171
-
172
- private slotId(strandId: string): KeyId {
173
- return this.slotPrefix + strandId;
174
- }
175
-
176
- private inOrder<T>(op: () => Promise<T>): Promise<T> {
177
- const result = this.queue.then(op);
178
- // The caller receives `result`, rejection included; the queue only needs to know it settled.
179
- this.queue = result.catch(() => undefined);
180
- return result;
181
- }
182
-
183
- // NOTE: a failed load is retried at the next list(), which is every strand-watcher run (a
184
- // change to `Strand` or `JoinedStrand`, a local join, a retry, the backstop); over a backend
185
- // that gates reads behind an unlock prompt the user keeps declining, that is a prompt per
186
- // run. Every KeyStore shipped today is ungated for this reason
187
- // (see `SecureStoreKeyStoreOptions.requireAuthentication`); if one is ever gated, back
188
- // off the retry here.
189
- private async loaded(): Promise<Map<string, JoinedStrandRecord>> {
190
- if (this.records) {
191
- return this.records;
192
- }
193
- const records = new Map<string, JoinedStrandRecord>();
194
- for (const slot of await this.keyStore.list()) {
195
- if (!slot.startsWith(this.slotPrefix)) {
196
- continue;
197
- }
198
- const strandId = slot.slice(this.slotPrefix.length);
199
- const bytes = await this.keyStore.get(slot);
200
- if (!bytes) {
201
- continue;
202
- }
203
- const record = parseRecord(strandId, bytes);
204
- if (record) {
205
- records.set(strandId, record);
206
- }
207
- }
208
- this.records = records;
209
- log('joined strands loaded (party=%s, count=%d)', this.partyId, records.size);
210
- return records;
211
- }
212
- }
213
-
214
- /** The record a slot holds, or undefined (logged) when it is not one for `strandId`. */
215
- function parseRecord(strandId: string, bytes: Uint8Array): JoinedStrandRecord | undefined {
216
- let parsed: unknown;
217
- try {
218
- parsed = JSON.parse(uint8ArrayToString(bytes, 'utf8'));
219
- } catch (error) {
220
- log('dropping joined-strand slot for %s: not JSON (%o)', strandId, error);
221
- return undefined;
222
- }
223
- const { Id, Type, MemberPrivateKey, joinedAt } = (typeof parsed === 'object' && parsed !== null ? parsed : {}) as Record<string, unknown>;
224
- const valid = Id === strandId
225
- && isValidStrandScopeKey(strandId)
226
- && (Type === 'o' || Type === 'c')
227
- && (MemberPrivateKey === null || typeof MemberPrivateKey === 'string')
228
- && typeof joinedAt === 'number';
229
- if (!valid) {
230
- log('dropping joined-strand slot for %s: not a joined-strand record for that id', strandId);
231
- return undefined;
232
- }
233
- return { Id: strandId, Type: Type as 'o' | 'c', MemberPrivateKey: MemberPrivateKey as string | null, joinedAt: joinedAt as number };
234
- }
235
-
236
- /**
237
- * The party-wide joined-strand table (`CadreControl.JoinedStrand`), as the node's control
238
- * database exposes it. `CadreNode` builds it over `ControlDatabase` and the owner signing
239
- * key; this module sees only the seam, so it stays free of the runtime.
240
- */
241
- export interface PartyJoinedStrandLedger {
242
- /** Every party-wide join, as offerable rows (null founder columns). */
243
- list(): Promise<StrandRow[]>;
244
- /** Whether this party's control database names `strandId`, as its own strand or as a party-wide join. */
245
- names(strandId: string): Promise<boolean>;
246
- /** Whether this machine can sign {@link publish} and {@link remove}: it holds an owner key the party enrolls. */
247
- canSign(): Promise<boolean>;
248
- /** Owner-signed insert. Resolves when the row landed or a sibling's join already holds the id. */
249
- publish(record: JoinedStrandRecord): Promise<void>;
250
- /** Owner-signed delete + tombstone; false when there is no row. Throws when a row exists and this machine cannot sign. */
251
- remove(strandId: string): Promise<boolean>;
252
- }
253
-
254
- /**
255
- * One node session's joined strands: what the strand watcher sees of the two records, and
256
- * the moves between them. Rebuilt at every start, which is what ends the per-session state
257
- * below.
258
- *
259
- * The watcher reads a row missing from a run's read as a removal and detaches the strand, so this
260
- * holds the state a plain union would get wrong:
261
- * - the last list each record answered, reused when a later read fails, so a failed read
262
- * is not "every join was forgotten";
263
- * - joins this party was removed from ({@link forgetAfterThisSession}): offered until this
264
- * session ends, because `strand:revoked` promises that nothing is torn down for the app,
265
- * and queued for party-wide removal so the next start does not re-attach them.
266
- */
267
- export class JoinedStrandSession {
268
- private lastUnpublished: JoinedStrandRecord[] = [];
269
- private lastPartyWide: StrandRow[] = [];
270
- /** Whether the last party-wide read in {@link withControlRows} succeeded; see {@link lastReadPartial}. */
271
- private lastPartyWideFresh = true;
272
- private readonly keptForSession = new Map<string, StrandRow>();
273
- /** Strands whose party-wide row {@link syncWithParty} removes, queued by a self-revocation. */
274
- private readonly pendingRemovals = new Set<string>();
275
- /**
276
- * Tail of the moves that must not interleave ({@link serialized}): a publish that found no
277
- * party-wide row, then a {@link leave} that removed nothing, then the publish's insert
278
- * would leave the party holding a strand the app just left.
279
- */
280
- private exclusive: Promise<unknown> = Promise.resolve();
281
-
282
- /**
283
- * @param onLocalChange - Called after a move changes what {@link withControlRows} merges in
284
- * from outside the control database (this machine's unpublished joins, the joins kept for
285
- * this session), which no control-table change event reports. `CadreNode` wakes its strand
286
- * watcher with it.
287
- */
288
- constructor(
289
- private readonly store: JoinedStrandStore,
290
- private readonly ledger: PartyJoinedStrandLedger,
291
- private readonly onLocalChange: () => void = () => {}
292
- ) {}
293
-
294
- /**
295
- * `control` plus every join, one row per id, in this precedence: the control rows (the
296
- * party's own strands), then the party-wide joins, then this machine's unpublished joins
297
- * and the joins kept for this session. A local record named by either of the first two in
298
- * a read that succeeded this run is stale — published, or the strand is the party's own
299
- * now — so it is forgotten here; this also cleans up after a crash between a publish and
300
- * its local forget. One named only by the last-good party-wide list is kept: that list may
301
- * predate a leave the record re-joined after.
302
- */
303
- async withControlRows(control: readonly StrandRow[]): Promise<StrandRow[]> {
304
- const controlIds = new Set(control.map((row) => row.Id));
305
- const named = new Set(controlIds);
306
- const offered = new Map<string, StrandRow>(control.map((row) => [row.Id, row]));
307
- const partyWide = await this.partyWide();
308
- // NOTE: a party-wide join whose id the party's own `Strand` table also holds (the party
309
- // founded AND joined it — contrived) is shadowed here, not deleted: a watcher run must
310
- // not make owner-signed writes. If the party later unpublishes its own row the join row
311
- // resurfaces; if that is ever seen, remove the join row inside `unpublishStrand`.
312
- for (const row of partyWide.rows) {
313
- if (!offered.has(row.Id)) {
314
- offered.set(row.Id, row);
315
- }
316
- if (partyWide.fresh) {
317
- named.add(row.Id);
318
- }
319
- }
320
- for (const record of await this.unpublished()) {
321
- if (named.has(record.Id)) {
322
- await this.forgetSuperseded(record.Id);
323
- } else if (!offered.has(record.Id)) {
324
- offered.set(record.Id, joinedStrandRow(record));
325
- }
326
- }
327
- for (const [strandId, row] of this.keptForSession) {
328
- if (controlIds.has(strandId)) {
329
- this.keptForSession.delete(strandId);
330
- } else if (!offered.has(strandId)) {
331
- offered.set(strandId, row);
332
- }
333
- }
334
- return [...offered.values()];
335
- }
336
-
337
- /**
338
- * True when the last {@link withControlRows} offered the party-wide joins from the last
339
- * list that answered, because its read of `JoinedStrand` failed.
340
- */
341
- lastReadPartial(): boolean {
342
- return !this.lastPartyWideFresh;
343
- }
344
-
345
- /**
346
- * This machine's unpublished joins, straight from the store (never the last-good list a
347
- * failed read stands in with). What a strand move exports beside the `JoinedStrand`
348
- * table: a machine publishes only while a sibling is reachable, so until then its
349
- * joins live only here.
350
- */
351
- unpublishedRecords(): Promise<JoinedStrandRecord[]> {
352
- return this.store.list();
353
- }
354
-
355
- /** Record a join `formStrand` just made. A re-join also cancels a removal a revocation queued. */
356
- async remember(record: JoinedStrandRecord): Promise<void> {
357
- this.pendingRemovals.delete(record.Id);
358
- await this.store.record(record);
359
- this.onLocalChange();
360
- }
361
-
362
- /**
363
- * Record `row`, joined by `addStrand`, unless this party's control database already names
364
- * it (its own strand, or a join already published) or an identical record is already here
365
- * (an app re-claiming a remembered join on every start, or `addStrand` right after
366
- * `formStrand`). The store is asked first: it answers from memory once loaded, so the
367
- * common re-claim reads no control row. Keeps the first `joinedAt`. Like
368
- * {@link remember}, cancels a queued removal.
369
- */
370
- async rememberForeign(row: StrandRow): Promise<void> {
371
- this.pendingRemovals.delete(row.Id);
372
- const early = await this.storedRecord(row.Id).catch((error: unknown) => {
373
- // Asked again below only when the party does not name the strand; a second failure throws.
374
- log('joined strand %s: store lookup failed; asking the control database first: %o', row.Id, error);
375
- return null;
376
- });
377
- if (early && isSameJoin(early, row)) {
378
- return;
379
- }
380
- if (await this.namedByParty(row.Id)) {
381
- return;
382
- }
383
- const existing = early === null ? await this.storedRecord(row.Id) : early;
384
- if (existing && isSameJoin(existing, row)) {
385
- return;
386
- }
387
- await this.store.record({
388
- Id: row.Id,
389
- Type: row.Type,
390
- MemberPrivateKey: row.MemberPrivateKey,
391
- joinedAt: existing?.joinedAt ?? Date.now()
392
- });
393
- this.onLocalChange();
394
- }
395
-
396
- /**
397
- * Leave a join for the whole party: remove the party-wide row, then this machine's record.
398
- * Throws, keeping both, when a party-wide row exists and this machine cannot sign.
399
- */
400
- leave(strandId: string): Promise<void> {
401
- return this.serialized(async () => {
402
- await this.ledger.remove(strandId);
403
- this.pendingRemovals.delete(strandId);
404
- this.keptForSession.delete(strandId);
405
- this.lastPartyWide = this.lastPartyWide.filter((row) => row.Id !== strandId);
406
- await this.store.forget(strandId);
407
- this.onLocalChange();
408
- });
409
- }
410
-
411
- /**
412
- * For a strand this party was removed from: keep offering it until this session ends, and
413
- * queue its party-wide row for removal by {@link syncWithParty}, so it does not re-attach
414
- * on every start of every machine. A no-op for a strand with neither record (one of the
415
- * party's own). The queue is in memory: if the process dies first, the next start
416
- * relaunches the strand, the revoked-peer gate raises `strand:revoked` again, and this
417
- * runs again.
418
- */
419
- forgetAfterThisSession(strandId: string): Promise<void> {
420
- return this.serialized(async () => {
421
- const local = (await this.unpublished()).find((record) => record.Id === strandId);
422
- const row = local ? joinedStrandRow(local) : this.lastPartyWide.find((listed) => listed.Id === strandId);
423
- if (!row) {
424
- return;
425
- }
426
- // Kept BEFORE the store forgets, so no watcher run can union without it. Queued even for a
427
- // local-only join, which a sibling may have published already.
428
- this.keptForSession.set(strandId, row);
429
- this.pendingRemovals.add(strandId);
430
- if (local) {
431
- await this.store.forget(strandId);
432
- }
433
- this.onLocalChange();
434
- });
435
- }
436
-
437
- /**
438
- * The owner machine's half, run by the node's connected reconcile pass: publish every
439
- * unpublished join party-wide, then remove the party-wide rows queued by
440
- * {@link forgetAfterThisSession}. Does nothing on a machine that cannot sign, whose joins
441
- * stay machine-local. Per strand, a failure is logged and kept for the next pass; a
442
- * failure to list the store or to check the signer throws.
443
- */
444
- syncWithParty(): Promise<void> {
445
- return this.serialized(async () => {
446
- // Straight from the store, never the last-good list: a stale list could republish a
447
- // join that was left since.
448
- const unpublished = await this.store.list();
449
- if (unpublished.length === 0 && this.pendingRemovals.size === 0) {
450
- return;
451
- }
452
- if (!(await this.ledger.canSign())) {
453
- return;
454
- }
455
- for (const record of unpublished) {
456
- await this.publish(record);
457
- }
458
- for (const strandId of [...this.pendingRemovals]) {
459
- await this.removeQueued(strandId);
460
- }
461
- });
462
- }
463
-
464
- // NOTE: a sibling that joined the same strand and has not yet published publishes it after
465
- // a leave, bringing the strand back party-wide. Needs a second device to have joined the
466
- // strand and not yet run a connected reconcile pass when the leave lands (a join starts no
467
- // pass, so up to the 2-minute backstop); if it is ever seen, check the strand's `Revocation`
468
- // tombstone before publishing.
469
- private async publish(record: JoinedStrandRecord): Promise<void> {
470
- try {
471
- if (!(await this.ledger.names(record.Id))) {
472
- await this.ledger.publish(record);
473
- // Into the last-good list too: its local record goes next, so a party-wide read that
474
- // fails before one succeeds would otherwise drop the strand from the watcher's read and hide it
475
- // from a self-revocation.
476
- this.lastPartyWide = [...this.lastPartyWide.filter((row) => row.Id !== record.Id), joinedStrandRow(record)];
477
- log('joined strand %s published party-wide (party=%s)', record.Id, this.store.partyId);
478
- }
479
- await this.store.forget(record.Id);
480
- } catch (error) {
481
- log('joined strand %s: publishing party-wide failed; kept for the next pass: %o', record.Id, error);
482
- }
483
- }
484
-
485
- private async removeQueued(strandId: string): Promise<void> {
486
- try {
487
- const removed = await this.ledger.remove(strandId);
488
- this.pendingRemovals.delete(strandId);
489
- log('joined strand %s: party-wide row %s after this party was removed from it',
490
- strandId, removed ? 'removed' : 'already absent');
491
- } catch (error) {
492
- log('joined strand %s: removing the party-wide row failed; queued for the next pass: %o', strandId, error);
493
- }
494
- }
495
-
496
- /** The party-wide joins; `fresh` is false when this read failed and the last list it answered stands in. */
497
- private async partyWide(): Promise<{ rows: StrandRow[]; fresh: boolean }> {
498
- try {
499
- this.lastPartyWide = await this.ledger.list();
500
- this.lastPartyWideFresh = true;
501
- } catch (error) {
502
- log('party-wide joined-strand read failed; offering the last list it answered (%d join(s)): %o',
503
- this.lastPartyWide.length, error);
504
- this.lastPartyWideFresh = false;
505
- }
506
- return { rows: this.lastPartyWide, fresh: this.lastPartyWideFresh };
507
- }
508
-
509
- /**
510
- * {@link PartyJoinedStrandLedger.names}, answering false when the control database cannot
511
- * be read (a machine cut off from its party before it received the `JoinedStrand` block).
512
- * Recording is the safe side: a local record the party turns out to name is forgotten by
513
- * the next watcher run that reads it, while a join with no record is not offered after a restart.
514
- */
515
- private async namedByParty(strandId: string): Promise<boolean> {
516
- try {
517
- return await this.ledger.names(strandId);
518
- } catch (error) {
519
- log('joined strand %s: could not read whether the control database names it; recording it locally: %o', strandId, error);
520
- return false;
521
- }
522
- }
523
-
524
- private async storedRecord(strandId: string): Promise<JoinedStrandRecord | undefined> {
525
- return (await this.store.list()).find((record) => record.Id === strandId);
526
- }
527
-
528
- /** Run `work` after every earlier serialized move settles; see {@link exclusive}. */
529
- private serialized<T>(work: () => Promise<T>): Promise<T> {
530
- const result = this.exclusive.then(work);
531
- this.exclusive = result.catch(() => undefined);
532
- return result;
533
- }
534
-
535
- private async unpublished(): Promise<JoinedStrandRecord[]> {
536
- try {
537
- this.lastUnpublished = await this.store.list();
538
- } catch (error) {
539
- log('joined-strand store list failed; offering the last list it answered (%d join(s)): %o',
540
- this.lastUnpublished.length, error);
541
- }
542
- return this.lastUnpublished;
543
- }
544
-
545
- private async forgetSuperseded(strandId: string): Promise<void> {
546
- try {
547
- await this.store.forget(strandId);
548
- log('joined strand %s is named by this party\'s control database — local record forgotten', strandId);
549
- } catch (error) {
550
- log('forgetting superseded joined strand %s failed; the next watcher run retries: %o', strandId, error);
551
- }
552
- }
553
- }
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 reads 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
+ * reads 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. The founder columns are null because a joiner never founds; `CadreNode.launchStrand`
73
+ * reads a null `FounderPeerId` 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, FounderPeerId: null };
77
+ }
78
+
79
+ function isSameJoin(record: JoinedStrandRecord, row: StrandRow): boolean {
80
+ return record.Type === row.Type && record.MemberPrivateKey === row.MemberPrivateKey;
81
+ }
82
+
83
+ /**
84
+ * Ephemeral store for a node without a `keyStore`. Warns once, at the first join it is
85
+ * asked to remember, because a join held only here is not re-offered after a restart —
86
+ * exactly the gotchoices/sereus#18 shape, and it should show in a log rather than pass
87
+ * silently.
88
+ */
89
+ export class MemoryJoinedStrandStore implements JoinedStrandStore {
90
+ private readonly records = new Map<string, JoinedStrandRecord>();
91
+ private warned = false;
92
+
93
+ constructor(readonly partyId: string) {}
94
+
95
+ async list(): Promise<JoinedStrandRecord[]> {
96
+ return [...this.records.values()];
97
+ }
98
+
99
+ async record(record: JoinedStrandRecord): Promise<void> {
100
+ this.warnOnce();
101
+ this.records.set(record.Id, { ...record });
102
+ }
103
+
104
+ async forget(strandId: string): Promise<void> {
105
+ this.records.delete(strandId);
106
+ }
107
+
108
+ private warnOnce(): void {
109
+ if (this.warned) {
110
+ return;
111
+ }
112
+ this.warned = true;
113
+ console.warn(
114
+ 'CadreNode has no keyStore and no joinedStrands.store, so strands joined from another party ' +
115
+ 'are remembered in memory only and will NOT be re-offered after a restart. Configure a keyStore, ' +
116
+ 'or inject joinedStrands: { store: new KeyStoreJoinedStrandStore(<a durable KeyStore>, partyId) }.'
117
+ );
118
+ }
119
+ }
120
+
121
+ /** Slot id prefix for every joined-strand record; the party segment and the strand id follow. */
122
+ const SLOT_PREFIX = 'cadre/joined-strand/';
123
+
124
+ /**
125
+ * Durable store over a {@link KeyStore}: one slot per join, id
126
+ * `cadre/joined-strand/<base64url party id>/<strand id>`, holding the record's UTF-8 JSON.
127
+ * The party segment is base64url for the reason `controlStorageScope` gives: a party id is
128
+ * arbitrary text, and base64url never contains the `/` that ends the segment.
129
+ *
130
+ * Loads every slot once, at the first {@link list}, then answers from memory and writes
131
+ * through, so a strand watcher run does not read the enclave each time. A load that
132
+ * fails — `KeyStoreAccessError` from a refused unlock prompt, say — is rethrown rather
133
+ * than read as "no joins" and retried at the next call, exactly as
134
+ * `loadOrCreateIdentityKey` treats the identity slot. A slot that does not parse as a
135
+ * record for its own id is dropped with a log and its siblings kept: refusing to start
136
+ * repairs nothing, and the other joins are still good.
137
+ */
138
+ export class KeyStoreJoinedStrandStore implements JoinedStrandStore {
139
+ private readonly slotPrefix: string;
140
+ /** The loaded records; null until a load succeeds. */
141
+ private records: Map<string, JoinedStrandRecord> | null = null;
142
+ /** Runs every KeyStore access in call order, so a load never interleaves with a write. */
143
+ private queue: Promise<unknown> = Promise.resolve();
144
+
145
+ constructor(private readonly keyStore: KeyStore, readonly partyId: string) {
146
+ this.slotPrefix = SLOT_PREFIX + uint8ArrayToString(uint8ArrayFromString(partyId, 'utf8'), 'base64url') + '/';
147
+ }
148
+
149
+ list(): Promise<JoinedStrandRecord[]> {
150
+ return this.inOrder(async () => [...(await this.loaded()).values()]);
151
+ }
152
+
153
+ /** Throws `InvalidStrandIdError` for an id that could never load back, before anything is written. */
154
+ record(record: JoinedStrandRecord): Promise<void> {
155
+ assertStrandScopeKey(record.Id);
156
+ const stored: JoinedStrandRecord = { ...record };
157
+ return this.inOrder(async () => {
158
+ await this.keyStore.set(this.slotId(record.Id), uint8ArrayFromString(JSON.stringify(stored), 'utf8'));
159
+ this.records?.set(record.Id, stored);
160
+ log('joined strand remembered (party=%s, strand=%s, type=%s)', this.partyId, record.Id, record.Type);
161
+ });
162
+ }
163
+
164
+ forget(strandId: string): Promise<void> {
165
+ return this.inOrder(async () => {
166
+ await this.keyStore.delete(this.slotId(strandId));
167
+ this.records?.delete(strandId);
168
+ log('joined strand forgotten (party=%s, strand=%s)', this.partyId, strandId);
169
+ });
170
+ }
171
+
172
+ private slotId(strandId: string): KeyId {
173
+ return this.slotPrefix + strandId;
174
+ }
175
+
176
+ private inOrder<T>(op: () => Promise<T>): Promise<T> {
177
+ const result = this.queue.then(op);
178
+ // The caller receives `result`, rejection included; the queue only needs to know it settled.
179
+ this.queue = result.catch(() => undefined);
180
+ return result;
181
+ }
182
+
183
+ // NOTE: a failed load is retried at the next list(), which is every strand-watcher run (a
184
+ // change to `Strand` or `JoinedStrand`, a local join, a retry, the backstop); over a backend
185
+ // that gates reads behind an unlock prompt the user keeps declining, that is a prompt per
186
+ // run. Every KeyStore shipped today is ungated for this reason
187
+ // (see `SecureStoreKeyStoreOptions.requireAuthentication`); if one is ever gated, back
188
+ // off the retry here.
189
+ private async loaded(): Promise<Map<string, JoinedStrandRecord>> {
190
+ if (this.records) {
191
+ return this.records;
192
+ }
193
+ const records = new Map<string, JoinedStrandRecord>();
194
+ for (const slot of await this.keyStore.list()) {
195
+ if (!slot.startsWith(this.slotPrefix)) {
196
+ continue;
197
+ }
198
+ const strandId = slot.slice(this.slotPrefix.length);
199
+ const bytes = await this.keyStore.get(slot);
200
+ if (!bytes) {
201
+ continue;
202
+ }
203
+ const record = parseRecord(strandId, bytes);
204
+ if (record) {
205
+ records.set(strandId, record);
206
+ }
207
+ }
208
+ this.records = records;
209
+ log('joined strands loaded (party=%s, count=%d)', this.partyId, records.size);
210
+ return records;
211
+ }
212
+ }
213
+
214
+ /** The record a slot holds, or undefined (logged) when it is not one for `strandId`. */
215
+ function parseRecord(strandId: string, bytes: Uint8Array): JoinedStrandRecord | undefined {
216
+ let parsed: unknown;
217
+ try {
218
+ parsed = JSON.parse(uint8ArrayToString(bytes, 'utf8'));
219
+ } catch (error) {
220
+ log('dropping joined-strand slot for %s: not JSON (%o)', strandId, error);
221
+ return undefined;
222
+ }
223
+ const { Id, Type, MemberPrivateKey, joinedAt } = (typeof parsed === 'object' && parsed !== null ? parsed : {}) as Record<string, unknown>;
224
+ const valid = Id === strandId
225
+ && isValidStrandScopeKey(strandId)
226
+ && (Type === 'o' || Type === 'c')
227
+ && (MemberPrivateKey === null || typeof MemberPrivateKey === 'string')
228
+ && typeof joinedAt === 'number';
229
+ if (!valid) {
230
+ log('dropping joined-strand slot for %s: not a joined-strand record for that id', strandId);
231
+ return undefined;
232
+ }
233
+ return { Id: strandId, Type: Type as 'o' | 'c', MemberPrivateKey: MemberPrivateKey as string | null, joinedAt: joinedAt as number };
234
+ }
235
+
236
+ /**
237
+ * The party-wide joined-strand table (`CadreControl.JoinedStrand`), as the node's control
238
+ * database exposes it. `CadreNode` builds it over `ControlDatabase` and the owner signing
239
+ * key; this module sees only the seam, so it stays free of the runtime.
240
+ */
241
+ export interface PartyJoinedStrandLedger {
242
+ /** Every party-wide join, as offerable rows (null founder columns). */
243
+ list(): Promise<StrandRow[]>;
244
+ /** Whether this party's control database names `strandId`, as its own strand or as a party-wide join. */
245
+ names(strandId: string): Promise<boolean>;
246
+ /** Whether this machine can sign {@link publish} and {@link remove}: it holds an owner key the party enrolls. */
247
+ canSign(): Promise<boolean>;
248
+ /** Owner-signed insert. Resolves when the row landed or a sibling's join already holds the id. */
249
+ publish(record: JoinedStrandRecord): Promise<void>;
250
+ /** Owner-signed delete + tombstone; false when there is no row. Throws when a row exists and this machine cannot sign. */
251
+ remove(strandId: string): Promise<boolean>;
252
+ }
253
+
254
+ /**
255
+ * One node session's joined strands: what the strand watcher sees of the two records, and
256
+ * the moves between them. Rebuilt at every start, which is what ends the per-session state
257
+ * below.
258
+ *
259
+ * The watcher reads a row missing from a run's read as a removal and detaches the strand, so this
260
+ * holds the state a plain union would get wrong:
261
+ * - the last list each record answered, reused when a later read fails, so a failed read
262
+ * is not "every join was forgotten";
263
+ * - joins this party was removed from ({@link forgetAfterThisSession}): offered until this
264
+ * session ends, because `strand:revoked` promises that nothing is torn down for the app,
265
+ * and queued for party-wide removal so the next start does not re-attach them.
266
+ */
267
+ export class JoinedStrandSession {
268
+ private lastUnpublished: JoinedStrandRecord[] = [];
269
+ private lastPartyWide: StrandRow[] = [];
270
+ /** Whether the last party-wide read in {@link withControlRows} succeeded; see {@link lastReadPartial}. */
271
+ private lastPartyWideFresh = true;
272
+ private readonly keptForSession = new Map<string, StrandRow>();
273
+ /** Strands whose party-wide row {@link syncWithParty} removes, queued by a self-revocation. */
274
+ private readonly pendingRemovals = new Set<string>();
275
+ /**
276
+ * Tail of the moves that must not interleave ({@link serialized}): a publish that found no
277
+ * party-wide row, then a {@link leave} that removed nothing, then the publish's insert
278
+ * would leave the party holding a strand the app just left.
279
+ */
280
+ private exclusive: Promise<unknown> = Promise.resolve();
281
+
282
+ /**
283
+ * @param onLocalChange - Called after a move changes what {@link withControlRows} merges in
284
+ * from outside the control database (this machine's unpublished joins, the joins kept for
285
+ * this session), which no control-table change event reports. `CadreNode` wakes its strand
286
+ * watcher with it.
287
+ */
288
+ constructor(
289
+ private readonly store: JoinedStrandStore,
290
+ private readonly ledger: PartyJoinedStrandLedger,
291
+ private readonly onLocalChange: () => void = () => {}
292
+ ) {}
293
+
294
+ /**
295
+ * `control` plus every join, one row per id, in this precedence: the control rows (the
296
+ * party's own strands), then the party-wide joins, then this machine's unpublished joins
297
+ * and the joins kept for this session. A local record named by either of the first two in
298
+ * a read that succeeded this run is stale — published, or the strand is the party's own
299
+ * now — so it is forgotten here; this also cleans up after a crash between a publish and
300
+ * its local forget. One named only by the last-good party-wide list is kept: that list may
301
+ * predate a leave the record re-joined after.
302
+ */
303
+ async withControlRows(control: readonly StrandRow[]): Promise<StrandRow[]> {
304
+ const controlIds = new Set(control.map((row) => row.Id));
305
+ const named = new Set(controlIds);
306
+ const offered = new Map<string, StrandRow>(control.map((row) => [row.Id, row]));
307
+ const partyWide = await this.partyWide();
308
+ // NOTE: a party-wide join whose id the party's own `Strand` table also holds (the party
309
+ // founded AND joined it — contrived) is shadowed here, not deleted: a watcher run must
310
+ // not make owner-signed writes. If the party later unpublishes its own row the join row
311
+ // resurfaces; if that is ever seen, remove the join row inside `unpublishStrand`.
312
+ for (const row of partyWide.rows) {
313
+ if (!offered.has(row.Id)) {
314
+ offered.set(row.Id, row);
315
+ }
316
+ if (partyWide.fresh) {
317
+ named.add(row.Id);
318
+ }
319
+ }
320
+ for (const record of await this.unpublished()) {
321
+ if (named.has(record.Id)) {
322
+ await this.forgetSuperseded(record.Id);
323
+ } else if (!offered.has(record.Id)) {
324
+ offered.set(record.Id, joinedStrandRow(record));
325
+ }
326
+ }
327
+ for (const [strandId, row] of this.keptForSession) {
328
+ if (controlIds.has(strandId)) {
329
+ this.keptForSession.delete(strandId);
330
+ } else if (!offered.has(strandId)) {
331
+ offered.set(strandId, row);
332
+ }
333
+ }
334
+ return [...offered.values()];
335
+ }
336
+
337
+ /**
338
+ * True when the last {@link withControlRows} offered the party-wide joins from the last
339
+ * list that answered, because its read of `JoinedStrand` failed.
340
+ */
341
+ lastReadPartial(): boolean {
342
+ return !this.lastPartyWideFresh;
343
+ }
344
+
345
+ /**
346
+ * This machine's unpublished joins, straight from the store (never the last-good list a
347
+ * failed read stands in with). What a strand move exports beside the `JoinedStrand`
348
+ * table: a machine publishes only while a sibling is reachable, so until then its
349
+ * joins live only here.
350
+ */
351
+ unpublishedRecords(): Promise<JoinedStrandRecord[]> {
352
+ return this.store.list();
353
+ }
354
+
355
+ /** Record a join `formStrand` just made. A re-join also cancels a removal a revocation queued. */
356
+ async remember(record: JoinedStrandRecord): Promise<void> {
357
+ this.pendingRemovals.delete(record.Id);
358
+ await this.store.record(record);
359
+ this.onLocalChange();
360
+ }
361
+
362
+ /**
363
+ * Record `row`, joined by `addStrand`, unless this party's control database already names
364
+ * it (its own strand, or a join already published) or an identical record is already here
365
+ * (an app re-claiming a remembered join on every start, or `addStrand` right after
366
+ * `formStrand`). The store is asked first: it answers from memory once loaded, so the
367
+ * common re-claim reads no control row. Keeps the first `joinedAt`. Like
368
+ * {@link remember}, cancels a queued removal.
369
+ */
370
+ async rememberForeign(row: StrandRow): Promise<void> {
371
+ this.pendingRemovals.delete(row.Id);
372
+ const early = await this.storedRecord(row.Id).catch((error: unknown) => {
373
+ // Asked again below only when the party does not name the strand; a second failure throws.
374
+ log('joined strand %s: store lookup failed; asking the control database first: %o', row.Id, error);
375
+ return null;
376
+ });
377
+ if (early && isSameJoin(early, row)) {
378
+ return;
379
+ }
380
+ if (await this.namedByParty(row.Id)) {
381
+ return;
382
+ }
383
+ const existing = early === null ? await this.storedRecord(row.Id) : early;
384
+ if (existing && isSameJoin(existing, row)) {
385
+ return;
386
+ }
387
+ await this.store.record({
388
+ Id: row.Id,
389
+ Type: row.Type,
390
+ MemberPrivateKey: row.MemberPrivateKey,
391
+ joinedAt: existing?.joinedAt ?? Date.now()
392
+ });
393
+ this.onLocalChange();
394
+ }
395
+
396
+ /**
397
+ * Leave a join for the whole party: remove the party-wide row, then this machine's record.
398
+ * Throws, keeping both, when a party-wide row exists and this machine cannot sign.
399
+ */
400
+ leave(strandId: string): Promise<void> {
401
+ return this.serialized(async () => {
402
+ await this.ledger.remove(strandId);
403
+ this.pendingRemovals.delete(strandId);
404
+ this.keptForSession.delete(strandId);
405
+ this.lastPartyWide = this.lastPartyWide.filter((row) => row.Id !== strandId);
406
+ await this.store.forget(strandId);
407
+ this.onLocalChange();
408
+ });
409
+ }
410
+
411
+ /**
412
+ * For a strand this party was removed from: keep offering it until this session ends, and
413
+ * queue its party-wide row for removal by {@link syncWithParty}, so it does not re-attach
414
+ * on every start of every machine. A no-op for a strand with neither record (one of the
415
+ * party's own). The queue is in memory: if the process dies first, the next start
416
+ * relaunches the strand, the revoked-peer gate raises `strand:revoked` again, and this
417
+ * runs again.
418
+ */
419
+ forgetAfterThisSession(strandId: string): Promise<void> {
420
+ return this.serialized(async () => {
421
+ const local = (await this.unpublished()).find((record) => record.Id === strandId);
422
+ const row = local ? joinedStrandRow(local) : this.lastPartyWide.find((listed) => listed.Id === strandId);
423
+ if (!row) {
424
+ return;
425
+ }
426
+ // Kept BEFORE the store forgets, so no watcher run can union without it. Queued even for a
427
+ // local-only join, which a sibling may have published already.
428
+ this.keptForSession.set(strandId, row);
429
+ this.pendingRemovals.add(strandId);
430
+ if (local) {
431
+ await this.store.forget(strandId);
432
+ }
433
+ this.onLocalChange();
434
+ });
435
+ }
436
+
437
+ /**
438
+ * The owner machine's half, run by the node's connected reconcile pass: publish every
439
+ * unpublished join party-wide, then remove the party-wide rows queued by
440
+ * {@link forgetAfterThisSession}. Does nothing on a machine that cannot sign, whose joins
441
+ * stay machine-local. Per strand, a failure is logged and kept for the next pass; a
442
+ * failure to list the store or to check the signer throws.
443
+ */
444
+ syncWithParty(): Promise<void> {
445
+ return this.serialized(async () => {
446
+ // Straight from the store, never the last-good list: a stale list could republish a
447
+ // join that was left since.
448
+ const unpublished = await this.store.list();
449
+ if (unpublished.length === 0 && this.pendingRemovals.size === 0) {
450
+ return;
451
+ }
452
+ if (!(await this.ledger.canSign())) {
453
+ return;
454
+ }
455
+ for (const record of unpublished) {
456
+ await this.publish(record);
457
+ }
458
+ for (const strandId of [...this.pendingRemovals]) {
459
+ await this.removeQueued(strandId);
460
+ }
461
+ });
462
+ }
463
+
464
+ // NOTE: a sibling that joined the same strand and has not yet published publishes it after
465
+ // a leave, bringing the strand back party-wide. Needs a second device to have joined the
466
+ // strand and not yet run a connected reconcile pass when the leave lands (a join starts no
467
+ // pass, so up to the 2-minute backstop); if it is ever seen, check the strand's `Revocation`
468
+ // tombstone before publishing.
469
+ private async publish(record: JoinedStrandRecord): Promise<void> {
470
+ try {
471
+ if (!(await this.ledger.names(record.Id))) {
472
+ await this.ledger.publish(record);
473
+ // Into the last-good list too: its local record goes next, so a party-wide read that
474
+ // fails before one succeeds would otherwise drop the strand from the watcher's read and hide it
475
+ // from a self-revocation.
476
+ this.lastPartyWide = [...this.lastPartyWide.filter((row) => row.Id !== record.Id), joinedStrandRow(record)];
477
+ log('joined strand %s published party-wide (party=%s)', record.Id, this.store.partyId);
478
+ }
479
+ await this.store.forget(record.Id);
480
+ } catch (error) {
481
+ log('joined strand %s: publishing party-wide failed; kept for the next pass: %o', record.Id, error);
482
+ }
483
+ }
484
+
485
+ private async removeQueued(strandId: string): Promise<void> {
486
+ try {
487
+ const removed = await this.ledger.remove(strandId);
488
+ this.pendingRemovals.delete(strandId);
489
+ log('joined strand %s: party-wide row %s after this party was removed from it',
490
+ strandId, removed ? 'removed' : 'already absent');
491
+ } catch (error) {
492
+ log('joined strand %s: removing the party-wide row failed; queued for the next pass: %o', strandId, error);
493
+ }
494
+ }
495
+
496
+ /** The party-wide joins; `fresh` is false when this read failed and the last list it answered stands in. */
497
+ private async partyWide(): Promise<{ rows: StrandRow[]; fresh: boolean }> {
498
+ try {
499
+ this.lastPartyWide = await this.ledger.list();
500
+ this.lastPartyWideFresh = true;
501
+ } catch (error) {
502
+ log('party-wide joined-strand read failed; offering the last list it answered (%d join(s)): %o',
503
+ this.lastPartyWide.length, error);
504
+ this.lastPartyWideFresh = false;
505
+ }
506
+ return { rows: this.lastPartyWide, fresh: this.lastPartyWideFresh };
507
+ }
508
+
509
+ /**
510
+ * {@link PartyJoinedStrandLedger.names}, answering false when the control database cannot
511
+ * be read (a machine cut off from its party before it received the `JoinedStrand` block).
512
+ * Recording is the safe side: a local record the party turns out to name is forgotten by
513
+ * the next watcher run that reads it, while a join with no record is not offered after a restart.
514
+ */
515
+ private async namedByParty(strandId: string): Promise<boolean> {
516
+ try {
517
+ return await this.ledger.names(strandId);
518
+ } catch (error) {
519
+ log('joined strand %s: could not read whether the control database names it; recording it locally: %o', strandId, error);
520
+ return false;
521
+ }
522
+ }
523
+
524
+ private async storedRecord(strandId: string): Promise<JoinedStrandRecord | undefined> {
525
+ return (await this.store.list()).find((record) => record.Id === strandId);
526
+ }
527
+
528
+ /** Run `work` after every earlier serialized move settles; see {@link exclusive}. */
529
+ private serialized<T>(work: () => Promise<T>): Promise<T> {
530
+ const result = this.exclusive.then(work);
531
+ this.exclusive = result.catch(() => undefined);
532
+ return result;
533
+ }
534
+
535
+ private async unpublished(): Promise<JoinedStrandRecord[]> {
536
+ try {
537
+ this.lastUnpublished = await this.store.list();
538
+ } catch (error) {
539
+ log('joined-strand store list failed; offering the last list it answered (%d join(s)): %o',
540
+ this.lastUnpublished.length, error);
541
+ }
542
+ return this.lastUnpublished;
543
+ }
544
+
545
+ private async forgetSuperseded(strandId: string): Promise<void> {
546
+ try {
547
+ await this.store.forget(strandId);
548
+ log('joined strand %s is named by this party\'s control database — local record forgotten', strandId);
549
+ } catch (error) {
550
+ log('forgetting superseded joined strand %s failed; the next watcher run retries: %o', strandId, error);
551
+ }
552
+ }
553
+ }