@serfab/cadre-core 0.9.0 → 0.11.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 (193) hide show
  1. package/README.md +255 -253
  2. package/dist/bootstrap-peer-store-file.d.ts +13 -0
  3. package/dist/bootstrap-peer-store-file.js +42 -0
  4. package/dist/bootstrap-peer-store-file.js.map +1 -0
  5. package/dist/bootstrap-peer-store.d.ts +73 -0
  6. package/dist/bootstrap-peer-store.js +128 -0
  7. package/dist/bootstrap-peer-store.js.map +1 -0
  8. package/dist/cadre-node.d.ts +1121 -81
  9. package/dist/cadre-node.js +2276 -262
  10. package/dist/cadre-node.js.map +1 -1
  11. package/dist/control-authorization.d.ts +93 -0
  12. package/dist/control-authorization.js +57 -0
  13. package/dist/control-authorization.js.map +1 -0
  14. package/dist/control-cohort.d.ts +26 -0
  15. package/dist/control-cohort.js +26 -0
  16. package/dist/control-cohort.js.map +1 -1
  17. package/dist/control-database.d.ts +959 -54
  18. package/dist/control-database.js +1421 -148
  19. package/dist/control-database.js.map +1 -1
  20. package/dist/control-formation-recorder.d.ts +90 -10
  21. package/dist/control-formation-recorder.js +130 -14
  22. package/dist/control-formation-recorder.js.map +1 -1
  23. package/dist/control-schema.d.ts +1 -1
  24. package/dist/control-schema.js +651 -72
  25. package/dist/control-schema.js.map +1 -1
  26. package/dist/control-stream.d.ts +38 -4
  27. package/dist/control-stream.js +70 -4
  28. package/dist/control-stream.js.map +1 -1
  29. package/dist/control-write-retry.d.ts +161 -0
  30. package/dist/control-write-retry.js +412 -0
  31. package/dist/control-write-retry.js.map +1 -0
  32. package/dist/delegate-admission.d.ts +134 -0
  33. package/dist/delegate-admission.js +244 -0
  34. package/dist/delegate-admission.js.map +1 -0
  35. package/dist/device-token.d.ts +11 -11
  36. package/dist/device-token.js +14 -13
  37. package/dist/device-token.js.map +1 -1
  38. package/dist/ed25519-key.d.ts +26 -0
  39. package/dist/ed25519-key.js +56 -1
  40. package/dist/ed25519-key.js.map +1 -1
  41. package/dist/file-durable-slot.d.ts +20 -0
  42. package/dist/file-durable-slot.js +53 -0
  43. package/dist/file-durable-slot.js.map +1 -0
  44. package/dist/formation-approval.d.ts +157 -0
  45. package/dist/formation-approval.js +375 -0
  46. package/dist/formation-approval.js.map +1 -0
  47. package/dist/fs-atomic.d.ts +38 -0
  48. package/dist/fs-atomic.js +97 -0
  49. package/dist/fs-atomic.js.map +1 -0
  50. package/dist/identity-key.d.ts +49 -0
  51. package/dist/identity-key.js +81 -0
  52. package/dist/identity-key.js.map +1 -0
  53. package/dist/index.d.ts +17 -7
  54. package/dist/index.js +40 -6
  55. package/dist/index.js.map +1 -1
  56. package/dist/key-store-file.d.ts +2 -24
  57. package/dist/key-store-file.js +10 -77
  58. package/dist/key-store-file.js.map +1 -1
  59. package/dist/membership-connection-gater.d.ts +146 -0
  60. package/dist/membership-connection-gater.js +180 -0
  61. package/dist/membership-connection-gater.js.map +1 -0
  62. package/dist/node-local-snapshot.d.ts +109 -0
  63. package/dist/node-local-snapshot.js +182 -0
  64. package/dist/node-local-snapshot.js.map +1 -0
  65. package/dist/peer-addr-book.d.ts +92 -0
  66. package/dist/peer-addr-book.js +220 -0
  67. package/dist/peer-addr-book.js.map +1 -0
  68. package/dist/peer-authorization.d.ts +135 -18
  69. package/dist/peer-authorization.js +152 -21
  70. package/dist/peer-authorization.js.map +1 -1
  71. package/dist/peer-record.d.ts +21 -8
  72. package/dist/peer-record.js +26 -10
  73. package/dist/peer-record.js.map +1 -1
  74. package/dist/relay-addrs.d.ts +45 -0
  75. package/dist/relay-addrs.js +103 -0
  76. package/dist/relay-addrs.js.map +1 -0
  77. package/dist/relay-reservation.d.ts +266 -0
  78. package/dist/relay-reservation.js +613 -0
  79. package/dist/relay-reservation.js.map +1 -0
  80. package/dist/seed-bootstrap.d.ts +228 -56
  81. package/dist/seed-bootstrap.js +340 -198
  82. package/dist/seed-bootstrap.js.map +1 -1
  83. package/dist/seed-trust-policy.d.ts +47 -21
  84. package/dist/seed-trust-policy.js +24 -15
  85. package/dist/seed-trust-policy.js.map +1 -1
  86. package/dist/strand-addr-protocol.d.ts +42 -13
  87. package/dist/strand-addr-protocol.js +58 -52
  88. package/dist/strand-addr-protocol.js.map +1 -1
  89. package/dist/strand-backfill.d.ts +109 -0
  90. package/dist/strand-backfill.js +279 -0
  91. package/dist/strand-backfill.js.map +1 -0
  92. package/dist/strand-cohort.d.ts +4 -37
  93. package/dist/strand-cohort.js +4 -15
  94. package/dist/strand-cohort.js.map +1 -1
  95. package/dist/strand-database.d.ts +11 -16
  96. package/dist/strand-database.js +19 -7
  97. package/dist/strand-database.js.map +1 -1
  98. package/dist/strand-formation-manager.d.ts +36 -7
  99. package/dist/strand-formation-manager.js +115 -15
  100. package/dist/strand-formation-manager.js.map +1 -1
  101. package/dist/strand-formation-protocol.d.ts +103 -4
  102. package/dist/strand-formation-protocol.js +232 -4
  103. package/dist/strand-formation-protocol.js.map +1 -1
  104. package/dist/strand-instance-manager.d.ts +88 -19
  105. package/dist/strand-instance-manager.js +178 -34
  106. package/dist/strand-instance-manager.js.map +1 -1
  107. package/dist/strand-member-registry.d.ts +5 -5
  108. package/dist/strand-member-registry.js +18 -10
  109. package/dist/strand-member-registry.js.map +1 -1
  110. package/dist/strand-membership-writer.d.ts +484 -88
  111. package/dist/strand-membership-writer.js +751 -128
  112. package/dist/strand-membership-writer.js.map +1 -1
  113. package/dist/strand-solicitation.d.ts +99 -33
  114. package/dist/strand-solicitation.js +100 -52
  115. package/dist/strand-solicitation.js.map +1 -1
  116. package/dist/strand-transport-key.d.ts +40 -0
  117. package/dist/strand-transport-key.js +56 -0
  118. package/dist/strand-transport-key.js.map +1 -0
  119. package/dist/strand-wake-protocol.d.ts +9 -7
  120. package/dist/strand-wake-protocol.js +22 -46
  121. package/dist/strand-wake-protocol.js.map +1 -1
  122. package/dist/strand-watcher.d.ts +17 -2
  123. package/dist/strand-watcher.js +47 -3
  124. package/dist/strand-watcher.js.map +1 -1
  125. package/dist/trusted-owner-store-file.d.ts +12 -0
  126. package/dist/trusted-owner-store-file.js +39 -0
  127. package/dist/trusted-owner-store-file.js.map +1 -0
  128. package/dist/trusted-owner-store.d.ts +64 -0
  129. package/dist/trusted-owner-store.js +126 -0
  130. package/dist/trusted-owner-store.js.map +1 -0
  131. package/dist/types.d.ts +307 -44
  132. package/dist/types.js +13 -0
  133. package/dist/types.js.map +1 -1
  134. package/package.json +20 -8
  135. package/src/arachnode-stub.ts +159 -159
  136. package/src/bootstrap-peer-store-file.ts +44 -0
  137. package/src/bootstrap-peer-store.ts +172 -0
  138. package/src/cadre-node.ts +5158 -2981
  139. package/src/canonical-json.ts +30 -30
  140. package/src/control-authorization.ts +114 -0
  141. package/src/control-cohort.ts +130 -103
  142. package/src/control-database.ts +2406 -948
  143. package/src/control-formation-recorder.ts +305 -151
  144. package/src/control-schema.ts +651 -72
  145. package/src/control-stream.ts +205 -128
  146. package/src/control-write-retry.ts +483 -0
  147. package/src/delegate-admission.ts +302 -0
  148. package/src/device-token.ts +94 -89
  149. package/src/diagnostics/connection-path.ts +277 -277
  150. package/src/diagnostics/webrtc-turn-tracker.ts +222 -222
  151. package/src/ed25519-key.ts +66 -1
  152. package/src/enrollment.ts +199 -199
  153. package/src/file-durable-slot.ts +61 -0
  154. package/src/formation-approval.ts +604 -0
  155. package/src/fs-atomic.ts +107 -0
  156. package/src/hibernation-manager.ts +437 -437
  157. package/src/identity-key.ts +109 -0
  158. package/src/index.ts +137 -5
  159. package/src/key-store-file.ts +132 -203
  160. package/src/key-store.ts +99 -99
  161. package/src/membership-connection-gater.ts +204 -0
  162. package/src/node-local-snapshot.ts +260 -0
  163. package/src/peer-addr-book.ts +250 -0
  164. package/src/peer-authorization.ts +259 -81
  165. package/src/peer-record.ts +164 -146
  166. package/src/push-credentials.ts +84 -84
  167. package/src/push-node.ts +64 -64
  168. package/src/push-notifier-apns.ts +247 -247
  169. package/src/push-notifier-fcm.ts +220 -220
  170. package/src/push-notifier-shared.ts +28 -28
  171. package/src/push-notifier.ts +52 -52
  172. package/src/relay-addrs.ts +111 -0
  173. package/src/relay-reservation.ts +823 -0
  174. package/src/seed-bootstrap.ts +409 -209
  175. package/src/seed-trust-policy.ts +140 -107
  176. package/src/strand-addr-protocol.ts +441 -410
  177. package/src/strand-backfill.ts +366 -0
  178. package/src/strand-cohort.ts +38 -77
  179. package/src/strand-database.ts +202 -204
  180. package/src/strand-formation-manager.ts +491 -368
  181. package/src/strand-formation-protocol.ts +692 -391
  182. package/src/strand-instance-manager.ts +201 -46
  183. package/src/strand-member-key.ts +39 -39
  184. package/src/strand-member-registry.ts +182 -177
  185. package/src/strand-membership-writer.ts +938 -146
  186. package/src/strand-solicitation.ts +472 -407
  187. package/src/strand-transport-key.ts +58 -0
  188. package/src/strand-wake-payload.ts +32 -32
  189. package/src/strand-wake-protocol.ts +314 -331
  190. package/src/strand-watcher.ts +314 -251
  191. package/src/trusted-owner-store-file.ts +41 -0
  192. package/src/trusted-owner-store.ts +171 -0
  193. package/src/types.ts +1309 -1032
@@ -1,159 +1,159 @@
1
- import debug from 'debug';
2
- import type { NodeProfile, ArachnodeConfig } from './types.js';
3
-
4
- const log = debug('sereus:cadre:arachnode');
5
-
6
- /**
7
- * Ring configuration for a storage node
8
- */
9
- export interface RingConfig {
10
- /** Ring number (0 = full keyspace, higher = more partitions) */
11
- ring: number;
12
- /** Partition within the ring (depends on ring level) */
13
- partition: number;
14
- /** Keyspace range this node is responsible for */
15
- keyspaceStart: Uint8Array;
16
- keyspaceEnd: Uint8Array;
17
- }
18
-
19
- /**
20
- * Stub implementation of Arachnode ring participation.
21
- *
22
- * Arachnode uses a concentric ring system where:
23
- * - Ring Zulu (transaction ring): All nodes participate for transaction verification
24
- * - Storage rings (0, 1, 2, 3...): Nodes join based on their storage capacity
25
- * - Ring 0: Full keyspace (requires most storage)
26
- * - Ring 1: 2 partitions
27
- * - Ring 2: 4 partitions
28
- * - Ring 3: 8 partitions
29
- * - etc.
30
- *
31
- * This is a stub that will be replaced when arachnode is fully implemented.
32
- */
33
- export class ArachnodeStub {
34
- private readonly profile: NodeProfile;
35
- private readonly config: ArachnodeConfig;
36
- private ringConfig?: RingConfig;
37
- private running = false;
38
-
39
- constructor(profile: NodeProfile, config: ArachnodeConfig) {
40
- this.profile = profile;
41
- this.config = config;
42
- log('ArachnodeStub created for profile=%s, config=%o', profile, config);
43
- }
44
-
45
- /**
46
- * Start participating in rings
47
- */
48
- async start(): Promise<void> {
49
- if (this.running) return;
50
- this.running = true;
51
-
52
- if (this.config.enableRingZulu) {
53
- log('Joining Ring Zulu (transaction ring)');
54
- // Stub: In real implementation, would register with transaction verification network
55
- }
56
-
57
- // Storage nodes join storage rings
58
- if (this.profile === 'storage' && this.config.storageRing) {
59
- const { ring, partition = 0 } = this.config.storageRing;
60
-
61
- log('Joining storage ring %d, partition %d', ring, partition);
62
-
63
- // Calculate keyspace range for this partition
64
- // Stub: Using placeholder keyspace calculation
65
- this.ringConfig = {
66
- ring,
67
- partition,
68
- keyspaceStart: this.calculateKeyspaceStart(ring, partition),
69
- keyspaceEnd: this.calculateKeyspaceEnd(ring, partition)
70
- };
71
-
72
- // Stub: In real implementation, would:
73
- // 1. Register with the storage ring
74
- // 2. Begin accepting block storage requests for our keyspace
75
- // 3. Participate in replication with other ring members
76
- }
77
-
78
- log('ArachnodeStub started');
79
- }
80
-
81
- /**
82
- * Stop participating in rings
83
- */
84
- async stop(): Promise<void> {
85
- if (!this.running) return;
86
- this.running = false;
87
-
88
- if (this.ringConfig) {
89
- log('Leaving storage ring %d, partition %d',
90
- this.ringConfig.ring, this.ringConfig.partition);
91
- // Stub: In real implementation, would gracefully leave the ring
92
- this.ringConfig = undefined;
93
- }
94
-
95
- if (this.config.enableRingZulu) {
96
- log('Leaving Ring Zulu');
97
- // Stub: In real implementation, would leave transaction ring
98
- }
99
-
100
- log('ArachnodeStub stopped');
101
- }
102
-
103
- /**
104
- * Get current ring configuration
105
- */
106
- getRingConfig(): RingConfig | undefined {
107
- return this.ringConfig;
108
- }
109
-
110
- /**
111
- * Check if participating in Ring Zulu
112
- */
113
- isInRingZulu(): boolean {
114
- return this.running && this.config.enableRingZulu;
115
- }
116
-
117
- /**
118
- * Check if participating in a storage ring
119
- */
120
- isInStorageRing(): boolean {
121
- return this.running && this.ringConfig !== undefined;
122
- }
123
-
124
- // Stub keyspace calculations
125
- private calculateKeyspaceStart(ring: number, partition: number): Uint8Array {
126
- // Stub: Real implementation would calculate based on ring partition scheme
127
- const numPartitions = Math.pow(2, ring);
128
- const partitionSize = 256 / numPartitions;
129
- const start = new Uint8Array(32);
130
- start[0] = Math.floor(partition * partitionSize);
131
- return start;
132
- }
133
-
134
- private calculateKeyspaceEnd(ring: number, partition: number): Uint8Array {
135
- // Stub: Real implementation would calculate based on ring partition scheme
136
- const numPartitions = Math.pow(2, ring);
137
- const partitionSize = 256 / numPartitions;
138
- const end = new Uint8Array(32);
139
- end[0] = Math.floor((partition + 1) * partitionSize) - 1;
140
- end.fill(0xFF, 1); // Fill rest with max values
141
- return end;
142
- }
143
- }
144
-
145
- /**
146
- * Create an arachnode instance for a strand
147
- */
148
- export function createArachnodeStub(
149
- profile: NodeProfile,
150
- config?: Partial<ArachnodeConfig>
151
- ): ArachnodeStub {
152
- const fullConfig: ArachnodeConfig = {
153
- enableRingZulu: config?.enableRingZulu ?? true,
154
- storageRing: profile === 'storage' ? (config?.storageRing ?? { ring: 0 }) : undefined
155
- };
156
-
157
- return new ArachnodeStub(profile, fullConfig);
158
- }
159
-
1
+ import debug from 'debug';
2
+ import type { NodeProfile, ArachnodeConfig } from './types.js';
3
+
4
+ const log = debug('sereus:cadre:arachnode');
5
+
6
+ /**
7
+ * Ring configuration for a storage node
8
+ */
9
+ export interface RingConfig {
10
+ /** Ring number (0 = full keyspace, higher = more partitions) */
11
+ ring: number;
12
+ /** Partition within the ring (depends on ring level) */
13
+ partition: number;
14
+ /** Keyspace range this node is responsible for */
15
+ keyspaceStart: Uint8Array;
16
+ keyspaceEnd: Uint8Array;
17
+ }
18
+
19
+ /**
20
+ * Stub implementation of Arachnode ring participation.
21
+ *
22
+ * Arachnode uses a concentric ring system where:
23
+ * - Ring Zulu (transaction ring): All nodes participate for transaction verification
24
+ * - Storage rings (0, 1, 2, 3...): Nodes join based on their storage capacity
25
+ * - Ring 0: Full keyspace (requires most storage)
26
+ * - Ring 1: 2 partitions
27
+ * - Ring 2: 4 partitions
28
+ * - Ring 3: 8 partitions
29
+ * - etc.
30
+ *
31
+ * This is a stub that will be replaced when arachnode is fully implemented.
32
+ */
33
+ export class ArachnodeStub {
34
+ private readonly profile: NodeProfile;
35
+ private readonly config: ArachnodeConfig;
36
+ private ringConfig?: RingConfig;
37
+ private running = false;
38
+
39
+ constructor(profile: NodeProfile, config: ArachnodeConfig) {
40
+ this.profile = profile;
41
+ this.config = config;
42
+ log('ArachnodeStub created for profile=%s, config=%o', profile, config);
43
+ }
44
+
45
+ /**
46
+ * Start participating in rings
47
+ */
48
+ async start(): Promise<void> {
49
+ if (this.running) return;
50
+ this.running = true;
51
+
52
+ if (this.config.enableRingZulu) {
53
+ log('Joining Ring Zulu (transaction ring)');
54
+ // Stub: In real implementation, would register with transaction verification network
55
+ }
56
+
57
+ // Storage nodes join storage rings
58
+ if (this.profile === 'storage' && this.config.storageRing) {
59
+ const { ring, partition = 0 } = this.config.storageRing;
60
+
61
+ log('Joining storage ring %d, partition %d', ring, partition);
62
+
63
+ // Calculate keyspace range for this partition
64
+ // Stub: Using placeholder keyspace calculation
65
+ this.ringConfig = {
66
+ ring,
67
+ partition,
68
+ keyspaceStart: this.calculateKeyspaceStart(ring, partition),
69
+ keyspaceEnd: this.calculateKeyspaceEnd(ring, partition)
70
+ };
71
+
72
+ // Stub: In real implementation, would:
73
+ // 1. Register with the storage ring
74
+ // 2. Begin accepting block storage requests for our keyspace
75
+ // 3. Participate in replication with other ring members
76
+ }
77
+
78
+ log('ArachnodeStub started');
79
+ }
80
+
81
+ /**
82
+ * Stop participating in rings
83
+ */
84
+ async stop(): Promise<void> {
85
+ if (!this.running) return;
86
+ this.running = false;
87
+
88
+ if (this.ringConfig) {
89
+ log('Leaving storage ring %d, partition %d',
90
+ this.ringConfig.ring, this.ringConfig.partition);
91
+ // Stub: In real implementation, would gracefully leave the ring
92
+ this.ringConfig = undefined;
93
+ }
94
+
95
+ if (this.config.enableRingZulu) {
96
+ log('Leaving Ring Zulu');
97
+ // Stub: In real implementation, would leave transaction ring
98
+ }
99
+
100
+ log('ArachnodeStub stopped');
101
+ }
102
+
103
+ /**
104
+ * Get current ring configuration
105
+ */
106
+ getRingConfig(): RingConfig | undefined {
107
+ return this.ringConfig;
108
+ }
109
+
110
+ /**
111
+ * Check if participating in Ring Zulu
112
+ */
113
+ isInRingZulu(): boolean {
114
+ return this.running && this.config.enableRingZulu;
115
+ }
116
+
117
+ /**
118
+ * Check if participating in a storage ring
119
+ */
120
+ isInStorageRing(): boolean {
121
+ return this.running && this.ringConfig !== undefined;
122
+ }
123
+
124
+ // Stub keyspace calculations
125
+ private calculateKeyspaceStart(ring: number, partition: number): Uint8Array {
126
+ // Stub: Real implementation would calculate based on ring partition scheme
127
+ const numPartitions = Math.pow(2, ring);
128
+ const partitionSize = 256 / numPartitions;
129
+ const start = new Uint8Array(32);
130
+ start[0] = Math.floor(partition * partitionSize);
131
+ return start;
132
+ }
133
+
134
+ private calculateKeyspaceEnd(ring: number, partition: number): Uint8Array {
135
+ // Stub: Real implementation would calculate based on ring partition scheme
136
+ const numPartitions = Math.pow(2, ring);
137
+ const partitionSize = 256 / numPartitions;
138
+ const end = new Uint8Array(32);
139
+ end[0] = Math.floor((partition + 1) * partitionSize) - 1;
140
+ end.fill(0xFF, 1); // Fill rest with max values
141
+ return end;
142
+ }
143
+ }
144
+
145
+ /**
146
+ * Create an arachnode instance for a strand
147
+ */
148
+ export function createArachnodeStub(
149
+ profile: NodeProfile,
150
+ config?: Partial<ArachnodeConfig>
151
+ ): ArachnodeStub {
152
+ const fullConfig: ArachnodeConfig = {
153
+ enableRingZulu: config?.enableRingZulu ?? true,
154
+ storageRing: profile === 'storage' ? (config?.storageRing ?? { ring: 0 }) : undefined
155
+ };
156
+
157
+ return new ArachnodeStub(profile, fullConfig);
158
+ }
159
+
@@ -0,0 +1,44 @@
1
+ /**
2
+ * Node-only file-backed {@link BootstrapPeerStore}: one JSON file per party under
3
+ * a configured directory (the node's state directory — `cadre-cli` passes
4
+ * `ResolvedConfig.nodeStateDir`), holding the node-local, non-replicated
5
+ * cold-start dial targets a seed nominated.
6
+ *
7
+ * Nothing but the file itself lives here: the envelope, load policy, per-entry
8
+ * validation (shape only — never signatures; see the `bootstrap-peer-store.ts`
9
+ * module comment for why nothing persisted here is trust-bearing) and the
10
+ * serialised snapshot writes are cross-platform in
11
+ * `PersistentBootstrapPeerStore` / `node-local-snapshot.ts`, and the file is a
12
+ * `FileDurableSlot`. This module exists only so the `node:fs` edge stays out of
13
+ * the package's cross-platform default entry (`./index.js`) — import it from the
14
+ * dedicated subpath instead:
15
+ *
16
+ * ```ts
17
+ * import { FileBootstrapPeerStore } from '@serfab/cadre-core/bootstrap-peer-store-file';
18
+ * ```
19
+ *
20
+ * A React Native / browser entry graph never resolves this path, so the
21
+ * `node:fs` edge never reaches a bundler that cannot satisfy it (same isolation
22
+ * pattern as `trusted-owner-store-file.ts` / `key-store-file.ts`).
23
+ */
24
+ import { FileDurableSlot } from './file-durable-slot.js';
25
+ import { PersistentBootstrapPeerStore } from './bootstrap-peer-store.js';
26
+ import type { BootstrapPeerStore } from './bootstrap-peer-store.js';
27
+
28
+ /** Base name of the store file: `<dir>/bootstrap-peers.<encoded partyId>.json`. */
29
+ const SLOT_NAME = 'bootstrap-peers';
30
+
31
+ /**
32
+ * File-backed {@link BootstrapPeerStore}. Open via {@link open}, which loads the
33
+ * existing file and returns the cross-platform store over it; an absent, corrupt, or wrong-party file is a cold
34
+ * start (empty store) and structurally junk entries are dropped, while a
35
+ * present-but-unreadable file throws. Those rules and their reasoning live on
36
+ * `NodeLocalSnapshot.open` — including the in-process-only write serialisation,
37
+ * which two nodes sharing one directory for one party would defeat.
38
+ */
39
+ export const FileBootstrapPeerStore = {
40
+ /** Load (or cold-start) the party's retained dial targets from a file in `dir`. */
41
+ async open(dir: string, partyId: string): Promise<BootstrapPeerStore> {
42
+ return PersistentBootstrapPeerStore.open(new FileDurableSlot(dir, SLOT_NAME, partyId), partyId);
43
+ }
44
+ };
@@ -0,0 +1,172 @@
1
+ /**
2
+ * Node-local, NON-replicated cold-start bootstrap-peer store: the dial targets a
3
+ * node keeps so it can retry its way back into a party it has been seeded into
4
+ * but never managed to connect to.
5
+ *
6
+ * A newcomer applies a signed seed nominating the party's owner machines and the
7
+ * addresses they answer on. `SeedBootstrapService.applySeed` dials those owners
8
+ * exactly once, best-effort; when that dial fails (owner briefly down, relay
9
+ * reservation not up, not yet vouched) the node has an empty `CadrePeer` table
10
+ * and no connection, and `CadreNode.reconcileControlCohort`'s cold-start branch
11
+ * is the only way back — it re-dials these retained addresses every pass. Held
12
+ * only in memory, they die with the process and the node is stranded for good,
13
+ * which is what this store exists to prevent.
14
+ *
15
+ * Three implementations, mirroring `trusted-owner-store.ts` (read that first —
16
+ * it solves the same "must outlive the process, storage differs per platform"
17
+ * problem, the two stores are deliberately symmetrical, and both persistent
18
+ * forms share `node-local-snapshot.ts`):
19
+ * - {@link MemoryBootstrapPeerStore} (this module, cross-platform) — ephemeral;
20
+ * the default when no store is injected via `CadreNodeConfig.bootstrapPeers`.
21
+ * - {@link PersistentBootstrapPeerStore} (this module, cross-platform) — durable
22
+ * over any `DurableSlot` the embedding app supplies (IndexedDB, a LevelDB KV,
23
+ * SQLite, …).
24
+ * - `FileBootstrapPeerStore` — the above over a Node file in the node's state
25
+ * directory; Node-only, behind the subpath
26
+ * `@serfab/cadre-core/bootstrap-peer-store-file` (same isolation pattern as
27
+ * `key-store-file`) so `node:fs` never lands in the RN/browser entry graph.
28
+ *
29
+ * **Nothing here is trust-bearing, and a loader must not try to re-verify it.**
30
+ * Only *dial targets* are retained — never a seed, a signature, or an authority
31
+ * claim. The seed was signature-checked against the node-local trusted-owner
32
+ * anchor before its addresses were retained, and a dial grants no authority:
33
+ * `CadreNode.bootstrapDialAddrs` binds every address to the peer id it was
34
+ * retained under, so a dial cannot be redirected to whoever answers. What a
35
+ * persistent backend's loader DOES owe is dropping structurally junk entries
36
+ * (unparseable peer id, empty address list, non-string address) rather than
37
+ * carrying them into the dial loop.
38
+ */
39
+ import debug from 'debug';
40
+ import { peerIdFromString } from '@libp2p/peer-id';
41
+ import { NodeLocalSnapshot, type DurableSlot, type NodeLocalSnapshotSpec } from './node-local-snapshot.js';
42
+
43
+ const log = debug('sereus:cadre:bootstrap-peer-store');
44
+
45
+ /** One retained cold-start dial target: an owner peer a seed nominated. */
46
+ export interface BootstrapPeerEntry {
47
+ /** Multiaddr strings exactly as the seed carried them (parsed at dial time). */
48
+ addrs: string[];
49
+ /** Wall-clock ms the entry was last recorded (diagnostics / future eviction). */
50
+ recordedAt: number;
51
+ }
52
+
53
+ export interface BootstrapPeerStore {
54
+ /** Party this store is scoped to. */
55
+ readonly partyId: string;
56
+
57
+ /**
58
+ * Every retained target, peerId -> entry. Every backend copies the map per call,
59
+ * so the result is a snapshot decoupled from later {@link record} calls and is
60
+ * safe to iterate while recording. The entry objects need no copy: `record`
61
+ * REPLACES an entry rather than mutating it in place.
62
+ */
63
+ all(): ReadonlyMap<string, BootstrapPeerEntry>;
64
+
65
+ /**
66
+ * Retain (or REPLACE) a peer's dial addresses. Replace, not merge, so a
67
+ * re-seed after an owner's address changed drops the stale address instead of
68
+ * accumulating dead ones.
69
+ *
70
+ * Implementations MUST reflect the entry in {@link all} SYNCHRONOUSLY; the
71
+ * returned promise tracks durability only. That is what lets the synchronous
72
+ * `CadreNode.recordSeedBootstrapPeers` keep its signature while a file
73
+ * backend persists in the background.
74
+ *
75
+ * NOTE: entries are never evicted, and a persistent backend's file therefore
76
+ * grows across the node's whole lifetime rather than one process. Fine while a
77
+ * seed nominates one or a few owners and entries are keyed by peer id; if a
78
+ * node ever applies seeds naming many distinct owners, add eviction (oldest
79
+ * {@link BootstrapPeerEntry.recordedAt} first, or a cap) rather than letting
80
+ * the file grow unbounded — `recordedAt` exists so eviction has something to
81
+ * sort by.
82
+ */
83
+ record(peerId: string, addrs: readonly string[]): Promise<void>;
84
+ }
85
+
86
+ /**
87
+ * Ephemeral in-memory store for nodes without durable storage (tests, browser
88
+ * demos, not-yet-persisted mobile). Same contract, no disk: a node using this
89
+ * loses its retry targets on restart and must be re-seeded to rejoin.
90
+ */
91
+ export class MemoryBootstrapPeerStore implements BootstrapPeerStore {
92
+ private readonly peers = new Map<string, BootstrapPeerEntry>();
93
+
94
+ constructor(readonly partyId: string) {}
95
+
96
+ all(): ReadonlyMap<string, BootstrapPeerEntry> {
97
+ return new Map(this.peers);
98
+ }
99
+
100
+ async record(peerId: string, addrs: readonly string[]): Promise<void> {
101
+ this.peers.set(peerId, { addrs: [...addrs], recordedAt: Date.now() });
102
+ log('bootstrap peer retained (party=%s, peer=%s, addrs=%d)', this.partyId, peerId, addrs.length);
103
+ }
104
+ }
105
+
106
+ /**
107
+ * What the store persists: `peers` maps peerId -> {@link BootstrapPeerEntry}.
108
+ *
109
+ * A structurally junk entry is DROPPED and its siblings retained — nothing here
110
+ * is trust-bearing (see the module comment) and the record is a stranded node's
111
+ * only way back into its party, so discarding the whole set over one bad entry
112
+ * would be strictly worse. What "junk" means: an unparseable peer id (the dial
113
+ * path binds every address to this id, so an id that cannot parse is not a dial
114
+ * target at all), an empty address list, or a non-string address — each would
115
+ * otherwise log a parse failure once per reconcile pass forever.
116
+ */
117
+ const BOOTSTRAP_PEER_SNAPSHOT: NodeLocalSnapshotSpec<BootstrapPeerEntry> = {
118
+ label: 'bootstrap-peer store',
119
+ payloadKey: 'peers',
120
+ unusableEntry: 'drop-entry',
121
+ acceptEntry: (peerId, entry) => {
122
+ if (typeof entry !== 'object' || entry === null) return undefined;
123
+ const { addrs, recordedAt } = entry as { addrs?: unknown; recordedAt?: unknown };
124
+ if (!Array.isArray(addrs) || addrs.length === 0) return undefined;
125
+ if (addrs.some((addr) => typeof addr !== 'string' || addr.length === 0)) return undefined;
126
+ if (typeof recordedAt !== 'number') return undefined;
127
+ try {
128
+ peerIdFromString(peerId);
129
+ } catch {
130
+ return undefined;
131
+ }
132
+ return { addrs: [...(addrs as string[])], recordedAt };
133
+ }
134
+ };
135
+
136
+ /**
137
+ * Durable {@link BootstrapPeerStore} over an app-supplied {@link DurableSlot} —
138
+ * the cross-platform half of every persistent backend (the Node
139
+ * `FileBootstrapPeerStore` is this class over a file slot).
140
+ *
141
+ * Construct via {@link open}. Load and persist policy — what an absent, corrupt,
142
+ * foreign-party or unreadable slot does, and what a failed persist does — is
143
+ * documented once on `NodeLocalSnapshot`; this class only supplies the payload
144
+ * shape and the drop-the-bad-entry policy above.
145
+ */
146
+ export class PersistentBootstrapPeerStore implements BootstrapPeerStore {
147
+ private constructor(private readonly snapshot: NodeLocalSnapshot<BootstrapPeerEntry>) {}
148
+
149
+ /** Load (or cold-start) the party's retained dial targets from `slot`. */
150
+ static async open(slot: DurableSlot, partyId: string): Promise<PersistentBootstrapPeerStore> {
151
+ return new PersistentBootstrapPeerStore(
152
+ await NodeLocalSnapshot.open(slot, partyId, BOOTSTRAP_PEER_SNAPSHOT)
153
+ );
154
+ }
155
+
156
+ get partyId(): string {
157
+ return this.snapshot.partyId;
158
+ }
159
+
160
+ all(): ReadonlyMap<string, BootstrapPeerEntry> {
161
+ return this.snapshot.entrySnapshot();
162
+ }
163
+
164
+ /**
165
+ * Retain a peer's dial addresses: visible via {@link all} synchronously, then
166
+ * the full snapshot is persisted (see `NodeLocalSnapshot.put`).
167
+ */
168
+ record(peerId: string, addrs: readonly string[]): Promise<void> {
169
+ log('bootstrap peer retained (party=%s, peer=%s, addrs=%d); persisting', this.partyId, peerId, addrs.length);
170
+ return this.snapshot.put(peerId, { addrs: [...addrs], recordedAt: Date.now() });
171
+ }
172
+ }