@serfab/cadre-core 1.21.0 → 1.23.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 (109) hide show
  1. package/README.md +294 -294
  2. package/dist/cadre-node.d.ts +334 -53
  3. package/dist/cadre-node.js +794 -85
  4. package/dist/cadre-node.js.map +1 -1
  5. package/dist/control-authorization.d.ts +32 -2
  6. package/dist/control-authorization.js +19 -0
  7. package/dist/control-authorization.js.map +1 -1
  8. package/dist/control-database.d.ts +236 -23
  9. package/dist/control-database.js +587 -173
  10. package/dist/control-database.js.map +1 -1
  11. package/dist/control-schema.d.ts +3 -3
  12. package/dist/control-schema.js +71 -7
  13. package/dist/control-schema.js.map +1 -1
  14. package/dist/ed25519-key.d.ts +8 -0
  15. package/dist/ed25519-key.js +11 -1
  16. package/dist/ed25519-key.js.map +1 -1
  17. package/dist/index.d.ts +5 -1
  18. package/dist/index.js +13 -1
  19. package/dist/index.js.map +1 -1
  20. package/dist/machine-removal.d.ts +51 -1
  21. package/dist/machine-removal.js +42 -1
  22. package/dist/machine-removal.js.map +1 -1
  23. package/dist/membership-connection-gater.d.ts +8 -0
  24. package/dist/membership-connection-gater.js +13 -1
  25. package/dist/membership-connection-gater.js.map +1 -1
  26. package/dist/membership-view.js +4 -1
  27. package/dist/membership-view.js.map +1 -1
  28. package/dist/owner-keys.js +2 -1
  29. package/dist/owner-keys.js.map +1 -1
  30. package/dist/owner-signer.js +3 -4
  31. package/dist/owner-signer.js.map +1 -1
  32. package/dist/peer-authorization.d.ts +14 -2
  33. package/dist/peer-authorization.js +24 -1
  34. package/dist/peer-authorization.js.map +1 -1
  35. package/dist/sealed-party-key.d.ts +32 -0
  36. package/dist/sealed-party-key.js +162 -0
  37. package/dist/sealed-party-key.js.map +1 -0
  38. package/dist/seed-bootstrap.d.ts +10 -3
  39. package/dist/seed-bootstrap.js +12 -0
  40. package/dist/seed-bootstrap.js.map +1 -1
  41. package/dist/strand-addr-protocol.d.ts +56 -6
  42. package/dist/strand-addr-protocol.js +57 -5
  43. package/dist/strand-addr-protocol.js.map +1 -1
  44. package/dist/strand-commit-durability.d.ts +33 -2
  45. package/dist/strand-commit-durability.js +44 -4
  46. package/dist/strand-commit-durability.js.map +1 -1
  47. package/dist/strand-database.d.ts +35 -5
  48. package/dist/strand-database.js +34 -10
  49. package/dist/strand-database.js.map +1 -1
  50. package/dist/strand-instance-manager.d.ts +200 -18
  51. package/dist/strand-instance-manager.js +434 -64
  52. package/dist/strand-instance-manager.js.map +1 -1
  53. package/dist/strand-membership-reconciler.d.ts +250 -51
  54. package/dist/strand-membership-reconciler.js +410 -66
  55. package/dist/strand-membership-reconciler.js.map +1 -1
  56. package/dist/strand-membership-writer.d.ts +7 -0
  57. package/dist/strand-membership-writer.js +9 -0
  58. package/dist/strand-membership-writer.js.map +1 -1
  59. package/dist/strand-party-key-rotation.d.ts +177 -0
  60. package/dist/strand-party-key-rotation.js +340 -0
  61. package/dist/strand-party-key-rotation.js.map +1 -0
  62. package/dist/strand-party-machines.d.ts +111 -0
  63. package/dist/strand-party-machines.js +258 -0
  64. package/dist/strand-party-machines.js.map +1 -0
  65. package/dist/strand-party-peers.d.ts +101 -0
  66. package/dist/strand-party-peers.js +49 -0
  67. package/dist/strand-party-peers.js.map +1 -0
  68. package/dist/strand-peer-redial.d.ts +34 -7
  69. package/dist/strand-peer-redial.js +46 -13
  70. package/dist/strand-peer-redial.js.map +1 -1
  71. package/dist/strand-revocation-enforcer.d.ts +15 -1
  72. package/dist/strand-revocation-enforcer.js +16 -9
  73. package/dist/strand-revocation-enforcer.js.map +1 -1
  74. package/dist/strand-transport-key.js +3 -0
  75. package/dist/strand-transport-key.js.map +1 -1
  76. package/dist/strand-watcher.d.ts +7 -4
  77. package/dist/strand-watcher.js +12 -7
  78. package/dist/strand-watcher.js.map +1 -1
  79. package/dist/types.d.ts +169 -13
  80. package/dist/types.js.map +1 -1
  81. package/package.json +9 -8
  82. package/src/cadre-node.ts +12280 -11528
  83. package/src/control-authorization.ts +41 -1
  84. package/src/control-database.ts +6123 -5603
  85. package/src/control-schema.ts +71 -7
  86. package/src/ed25519-key.ts +12 -1
  87. package/src/index.ts +957 -924
  88. package/src/machine-removal.ts +80 -1
  89. package/src/membership-connection-gater.ts +13 -1
  90. package/src/membership-view.ts +4 -1
  91. package/src/owner-keys.ts +2 -1
  92. package/src/owner-signer.ts +92 -94
  93. package/src/peer-authorization.ts +27 -3
  94. package/src/sealed-party-key.ts +190 -0
  95. package/src/seed-bootstrap.ts +17 -3
  96. package/src/strand-addr-protocol.ts +67 -6
  97. package/src/strand-commit-durability.ts +54 -5
  98. package/src/strand-database.ts +47 -11
  99. package/src/strand-instance-manager.ts +524 -65
  100. package/src/strand-membership-reconciler.ts +1310 -942
  101. package/src/strand-membership-writer.ts +10 -0
  102. package/src/strand-party-key-rotation.ts +436 -0
  103. package/src/strand-party-machines.ts +293 -0
  104. package/src/strand-party-peers.ts +129 -0
  105. package/src/strand-peer-redial.ts +61 -14
  106. package/src/strand-revocation-enforcer.ts +27 -9
  107. package/src/strand-transport-key.ts +3 -0
  108. package/src/strand-watcher.ts +12 -7
  109. package/src/types.ts +3121 -2963
package/README.md CHANGED
@@ -1,294 +1,294 @@
1
- # @serfab/cadre-core
2
-
3
- Core library for Sereus cadre nodes—the infrastructure that enables parties to manage their personal cluster of nodes participating in distributed strand networks.
4
-
5
- ## Why Sereus Cadre Core?
6
-
7
- In traditional distributed systems, users depend on centralized services to manage their data and identities. **Sereus** inverts this model: each user (or "party") controls their own **cadre**—a personal cluster of nodes ranging from always-on cloud servers to intermittently-connected mobile devices.
8
-
9
- The cadre architecture provides:
10
-
11
- - **Sovereignty**: Your data lives on your nodes, under your control
12
- - **Resilience**: Multiple nodes means no single point of failure
13
- - **Flexibility**: Mix cloud servers, home NAS, laptops, and phones
14
- - **Privacy**: Cryptographic authorization without central servers
15
-
16
- A cadre doesn't exist in isolation. Cadres participate in **strands**—shared data spaces where multiple parties collaborate. When you join a messaging app, your cadre joins that strand. When you share a document, you're creating a strand between your cadre and theirs.
17
-
18
- ## Architecture Overview
19
-
20
- ```
21
- ┌─────────────────────────────────────────────────────────────────────────┐
22
- │ Your Cadre │
23
- │ │
24
- │ ┌────────────────────────────────────────────────────────────────────┐ │
25
- │ │ Control Network │ │
26
- │ │ (Private Optimystic DB for cadre management) │ │
27
- │ │ │ │
28
- │ │ ┌──────────┐ ┌──────────┐ ┌──────────┐ ┌──────────┐ │ │
29
- │ │ │ Phone │──│ Laptop │──│ Cloud │──│ NAS │ │ │
30
- │ │ │ (edge) │ │ (edge) │ │ (core) │ │ (core) │ │ │
31
- │ │ └──────────┘ └──────────┘ └──────────┘ └──────────┘ │ │
32
- │ └────────────────────────────────────────────────────────────────────┘ │
33
- │ │ │
34
- │ ┌─────────────────────┼─────────────────────┐ │
35
- │ ▼ ▼ ▼ │
36
- │ ┌──────────────────┐ ┌──────────────────┐ ┌──────────────────┐ │
37
- │ │ Strand A │ │ Strand B │ │ Strand C │ │
38
- │ │ (Chat App) │ │ (Shared Docs) │ │ (Photo Backup) │ │
39
- │ └──────────────────┘ └──────────────────┘ └──────────────────┘ │
40
- └─────────────────────────────────────────────────────────────────────────┘
41
- ```
42
-
43
- Each `CadreNode` instance:
44
- 1. **Connects to the control network** - A private Optimystic database shared only by your nodes
45
- 2. **Watches for strand changes** - Automatically detects when you join or leave strands
46
- 3. **Manages strand instances** - Spins up isolated libp2p networks for each strand
47
- 4. **Handles peer enrollment** - Cryptographically authorizes new devices to join your cadre
48
-
49
- ## Installation
50
-
51
- ```bash
52
- npm install @serfab/cadre-core
53
- ```
54
-
55
- ## Quick Start
56
-
57
- ```typescript
58
- import { CadreNode } from '@serfab/cadre-core';
59
- import { FileRawStorage } from '@optimystic/db-p2p-storage-fs';
60
-
61
- const node = new CadreNode({
62
- controlNetwork: {
63
- partyId: 'your-unique-party-id',
64
- bootstrapNodes: ['/ip4/192.168.1.100/tcp/4001/p2p/12D3KooW...']
65
- },
66
- profile: 'storage', // 'storage' for servers, 'transaction' for mobile
67
- storage: {
68
- // Storage provider factory - called once per scope (each strand id, plus this
69
- // party's control database) for per-scope isolation
70
- provider: (scope) => new FileRawStorage(`/data/sereus/${scope}`),
71
- quotaBytes: 10 * 1024 * 1024 * 1024 // 10 GB
72
- }
73
- });
74
-
75
- // Start the node
76
- await node.start();
77
- console.log('Node started with Peer ID:', node.peerId?.toString());
78
-
79
- // Listen for strand events
80
- node.on('strand:started', ({ strandId }) => {
81
- console.log('Joined strand:', strandId);
82
- });
83
-
84
- // Check active strands
85
- for (const [id, strand] of node.getStrands()) {
86
- console.log(`Strand ${id}: ${strand.status}, ${strand.connectedPeers} peers`);
87
- }
88
-
89
- // Graceful shutdown
90
- await node.stop();
91
- ```
92
-
93
- ## Node Profiles
94
-
95
- | Profile | Storage Role | Use Case | Ring Zulu |
96
- |---------|--------------|----------|-----------|
97
- | **transaction** | Arachnode disabled; transaction verification via FRET only | Mobile devices, intermittent connectivity | No |
98
- | **storage** | Ring Zulu + storage rings (storage rings not yet implemented — stub) | Servers, NAS, always-on nodes | Yes |
99
-
100
- Transaction-profile nodes verify transactions via FRET only, with Arachnode disabled. Storage-profile nodes additionally join Ring Zulu and (when implemented) the concentric storage rings.
101
-
102
- > **Note:** The storage-ring subsystem is currently a no-op stub (`arachnode-stub.ts`). See [Node Profiles in `docs/architecture.md`](../../docs/architecture.md#node-profiles) for the full design.
103
-
104
- ## Strand Filtering
105
-
106
- Mobile apps typically shouldn't participate in all strands. Use filters to control participation:
107
-
108
- ```typescript
109
- // Only participate in strands for a specific app
110
- strandFilter: { mode: 'sAppId', sAppId: 'com.example.chat' }
111
-
112
- // Only participate in one specific strand
113
- strandFilter: { mode: 'strandId', strandId: 'strand-abc123' }
114
-
115
- // Control network only, no strand participation
116
- strandFilter: { mode: 'none' }
117
-
118
- // Participate in all strands (default for servers)
119
- strandFilter: { mode: 'all' }
120
- ```
121
-
122
- ## Enrolling New Devices
123
-
124
- Adding a new device to your cadre uses the Seed Bootstrap API:
125
-
126
- ```typescript
127
- // On the new device: generate identity
128
- const enrollment = new EnrollmentService();
129
- const { peerId, privateKey } = await enrollment.createCadrePeer();
130
- // Store privateKey securely, send peerId + multiaddrs to owner
131
-
132
- // On owner device: authorize the new peer and create seed
133
- await node.authorizePeer(newDevicePeerId, newDeviceMultiaddrs);
134
- const seed = await node.createSeed();
135
-
136
- // Deliver seed to new device (via protocol, API, or out-of-band)
137
- await node.deliverSeed(newDeviceMultiaddr, seed);
138
- // Or encode for QR/link: const encoded = node.encodeSeed(seed);
139
-
140
- // On new device: apply seed to join cadre
141
- const result = await newNode.applySeed(seed);
142
- ```
143
-
144
- For a machine whose peer id and addresses you already have, use the helper (`cadre enroll add` runs it on the owner node):
145
-
146
- ```typescript
147
- // One call: authorize + create seed
148
- const { seed, encodedSeed } = await node.addDrone({ dronePeerId, droneMultiaddrs });
149
-
150
- // The new machine starts with it: `cadre start --seed <encodedSeed> --pin-owner-key <owner key>`
151
-
152
- // Await the dial of the drone from the addresses addDrone kept (a drone cannot
153
- // dial a phone); the row insert starts a pass that dials it anyway, about 50 ms
154
- // later, and retries a failed dial after 15 s, 30 s, 60 s, then every 2 minutes
155
- await node.reconcileControlCohort();
156
- ```
157
-
158
- A provider-hosted node is added with `rentNode` instead (below).
159
-
160
- ### Renting a provider node
161
-
162
- An app rents an always-on node from a hosting provider with `rentNode`, which adds the container to this node's cadre by invitation when a member is reachable from anywhere and by claim otherwise ([architecture.md → Renting a node from an app](../../docs/architecture.md#renting-a-node-from-an-app)). Everything it needs loads on React Native and in the browser:
163
-
164
- ```typescript
165
- import { createProviderClient, createTokenSource, fetchProviderDescriptor, rentNode } from '@serfab/cadre-core';
166
-
167
- const descriptor = await fetchProviderDescriptor('https://nodes.acme.example/api/v1/descriptor');
168
- // `stored` comes from the PKCE sign-in (createPkce, authorizationUrl, readAuthorizationRedirect,
169
- // exchangeAuthorizationCode) or from the app's own store; `save` writes each refreshed pair back
170
- const tokens = createTokenSource({ descriptor, clientId: 'my-app', tokens: stored, persist: save });
171
- const client = createProviderClient({ apiBaseUrl: descriptor.apiBaseUrl, tokens });
172
-
173
- const rental = await rentNode(node, client, { onProgress: (step) => console.log(step) });
174
- // rental.join: 'invitation' (the container joins by itself; watch client.getContainer(id).join)
175
- // or 'claim' (the node is in the cadre when rentNode returns, rental.peerId names it).
176
- // Keep rental.containerId: finishRental(node, client, containerId) resumes a rental the app
177
- // was killed in the middle of, and the container is what the provider bills.
178
- ```
179
-
180
- ## API Reference
181
-
182
- ### CadreNode
183
-
184
- The main entry point for cadre participation.
185
-
186
- | Method | Description |
187
- |--------|-------------|
188
- | `start()` | Connect to control network and begin strand participation |
189
- | `stop()` | Gracefully disconnect from all networks |
190
- | `getStrands()` | Get all active strand instances |
191
- | `getStrand(id)` | Get a specific strand instance |
192
- | `foundStrand(config)` | **Create a strand**: publish its `Strand` row and start it locally as founder, in one call that is safe to re-run after an interruption. Returns the instance plus the row it actually runs under — for a closed strand read the membership key from there, since a resumed founding keeps the stored key |
193
- | `addStrand(row)` | Attach only — start a local instance for a row that already exists (the join path; also testing/direct API). Does **not** publish |
194
- | `stopStrand(id)` | Stop a strand on this node only (the shared `Strand` row stays; rediscovered on restart) |
195
- | `publishStrand(id, type?, memberKey?)` | Owner-signed `Strand` row insert — makes the strand visible cadre-wide. Idempotent: a live row with the same `(Type, MemberPrivateKey)` is returned unwritten; different content on the same id throws. Prefer `foundStrand` when creating a strand |
196
- | `unpublishStrand(id)` | Owner-signed party-wide removal — deletes this party's `Strand` row; every node stops the strand. Destroys a closed strand's `MemberPrivateKey` |
197
- | `getEnrollmentService()` | Access peer enrollment API |
198
- | `isOwner()` | Whether this node can act as an owner of its cadre: an owner key is wired for signing (`useOwnerSigner`) and is a live `OwnerKey` row; never the node's identity key. The gate the owner-only flows (`createCadreInvitation`, `createOwnerGrant`, `claimNode`, `rentNode`) share with the apps |
199
- | `invitationReach()` | Where a device could redeem an invitation minted now from, judged on the other members' addresses (`anywhere`, `local-network`, `issuer-only`), without minting one; `rentNode` chooses its join path by it |
200
-
201
- ### Events
202
-
203
- | Event | Payload | Description |
204
- |-------|---------|-------------|
205
- | `control:connected` | - | Connected to control network |
206
- | `control:disconnected` | - | Disconnected from control network |
207
- | `strand:started` | `{ strandId }` | Strand instance started |
208
- | `strand:stopped` | `{ strandId }` | Strand instance stopped |
209
- | `strand:error` | `{ strandId, error }` | Error in strand instance. A failed launch re-emits this on every retry (backing off up to 5 min), so treat it as a repeating signal, not a one-shot |
210
- | `strand:commit-durability` | `StrandCommitDurability` | After every commit on a strand's database that wrote something: whether another member already holds it (`heldElsewhere`) and whether `strand:commit-held` will say when one does (`followed`). Also readable as `instance.database.commitDurability(tx)`; see [strands.md → A commit's durability](../../docs/strands.md#a-commits-durability) |
211
- | `strand:commit-held` | `{ strandId, transactionId }` | A followed commit held only below full replication is now held by every member of its cohort |
212
-
213
- ## Related Documentation
214
-
215
- - **[Cadre Architecture](../../docs/architecture.md)** - Deep dive into the cadre system design
216
- - **[Strand Management](../../docs/strands.md)** - How strands connect multiple cadres
217
- - **[Schema Guide](../../docs/schema-guide.md)** - Optimystic schema definitions
218
-
219
- ## React Native Support
220
-
221
- This package is compatible with React Native. For mobile apps, use the RN-specific storage provider:
222
-
223
- ```typescript
224
- import { CadreNode } from '@serfab/cadre-core';
225
- import { RNRawStorage } from '@optimystic/db-p2p-storage-rn';
226
- import { webSockets } from '@libp2p/websockets';
227
- import { circuitRelayTransport } from '@libp2p/circuit-relay-v2';
228
-
229
- const node = new CadreNode({
230
- controlNetwork: {
231
- partyId: 'your-unique-party-id',
232
- bootstrapNodes: ['/dns4/relay.example.com/tcp/443/wss/p2p/12D3KooW...']
233
- },
234
- profile: 'transaction', // Mobile devices typically use transaction profile
235
- strandFilter: { mode: 'sAppId', sAppId: 'com.example.myapp' },
236
- storage: {
237
- // RN storage provider creates per-scope AsyncStorage
238
- provider: (scope) => new RNRawStorage(scope)
239
- },
240
- network: {
241
- // TCP doesn't work in React Native — use WebSocket transport instead
242
- transports: [webSockets(), circuitRelayTransport()],
243
- listenAddrs: [] // RN nodes typically cannot listen
244
- }
245
- });
246
- ```
247
-
248
- ### Storage Provider Pattern
249
-
250
- The `storage.provider` option accepts either:
251
- - **An `IRawStorage` instance** - One store shared by every scope, so it can serve only a single party
252
- - **A factory function** `(scope: string) => IRawStorage` - Creates isolated storage per scope (recommended)
253
-
254
- A **scope key** is what the factory receives. It is the strand id for each strand, and
255
- `controlStorageScope(partyId)` — `control-<lowercase hex of the party id>` — for the control
256
- database, which holds one party's own records and must not be shared between parties. Every
257
- key is opaque and already safe as a file, directory or database name (always within
258
- `[a-z0-9._-]`), and two different keys are two different names even on a filesystem that
259
- ignores case (Windows, macOS): use it verbatim, do not parse it. `isControlStorageScope(scope)`
260
- tells the two kinds apart. The control key holds the charset by lowercase hex encoding; a strand
261
- id holds it by check — `assertStrandScopeKey` runs on every strand launch, so a strand
262
- whose row replicated in from another node with an unusable id (including one with an
263
- uppercase letter) is refused rather than
264
- handed to the factory, and on `publishStrand`, so this node never writes such an id into
265
- the party's control database to begin with.
266
-
267
- Available storage implementations:
268
- | Package | Environment | Description |
269
- |---------|-------------|-------------|
270
- | `@optimystic/db-p2p` | All | `MemoryRawStorage` - In-memory (testing only) |
271
- | `@optimystic/db-p2p-storage-fs` | Node.js | `FileRawStorage` - File system storage |
272
- | `@optimystic/db-p2p-storage-rn` | React Native | `RNRawStorage` - AsyncStorage-based |
273
-
274
- ### React Native Considerations
275
-
276
- 1. **Network Transport**: libp2p's TCP transport doesn't work in RN. Pass `transports: [webSockets(), circuitRelayTransport()]` in the `network` config (see example above).
277
-
278
- 2. **Schema Loading**: The control schema is embedded in the package. Do not set `schemaPath` in React Native.
279
-
280
- 3. **Profile**: Mobile devices should use `profile: 'transaction'` for battery/bandwidth efficiency.
281
-
282
- 4. **Strand Filtering**: Always filter strands on mobile to avoid participating in unnecessary networks.
283
-
284
- ## Related Packages
285
-
286
- - **[@optimystic/db-core](https://github.com/gotchoices/optimystic)** - Distributed database core
287
- - **[@optimystic/db-p2p](https://github.com/gotchoices/optimystic)** - libp2p integration for Optimystic
288
- - **[@optimystic/db-p2p-storage-fs](https://github.com/gotchoices/optimystic)** - File system storage (Node.js)
289
- - **[@optimystic/db-p2p-storage-rn](https://github.com/gotchoices/optimystic)** - AsyncStorage (React Native)
290
-
291
- ## License
292
-
293
- MIT
294
-
1
+ # @serfab/cadre-core
2
+
3
+ Core library for Sereus cadre nodes—the infrastructure that enables parties to manage their personal cluster of nodes participating in distributed strand networks.
4
+
5
+ ## Why Sereus Cadre Core?
6
+
7
+ In traditional distributed systems, users depend on centralized services to manage their data and identities. **Sereus** inverts this model: each user (or "party") controls their own **cadre**—a personal cluster of nodes ranging from always-on cloud servers to intermittently-connected mobile devices.
8
+
9
+ The cadre architecture provides:
10
+
11
+ - **Sovereignty**: Your data lives on your nodes, under your control
12
+ - **Resilience**: Multiple nodes means no single point of failure
13
+ - **Flexibility**: Mix cloud servers, home NAS, laptops, and phones
14
+ - **Privacy**: Cryptographic authorization without central servers
15
+
16
+ A cadre doesn't exist in isolation. Cadres participate in **strands**—shared data spaces where multiple parties collaborate. When you join a messaging app, your cadre joins that strand. When you share a document, you're creating a strand between your cadre and theirs.
17
+
18
+ ## Architecture Overview
19
+
20
+ ```
21
+ ┌─────────────────────────────────────────────────────────────────────────┐
22
+ │ Your Cadre │
23
+ │ │
24
+ │ ┌────────────────────────────────────────────────────────────────────┐ │
25
+ │ │ Control Network │ │
26
+ │ │ (Private Optimystic DB for cadre management) │ │
27
+ │ │ │ │
28
+ │ │ ┌──────────┐ ┌──────────┐ ┌──────────┐ ┌──────────┐ │ │
29
+ │ │ │ Phone │──│ Laptop │──│ Cloud │──│ NAS │ │ │
30
+ │ │ │ (edge) │ │ (edge) │ │ (core) │ │ (core) │ │ │
31
+ │ │ └──────────┘ └──────────┘ └──────────┘ └──────────┘ │ │
32
+ │ └────────────────────────────────────────────────────────────────────┘ │
33
+ │ │ │
34
+ │ ┌─────────────────────┼─────────────────────┐ │
35
+ │ ▼ ▼ ▼ │
36
+ │ ┌──────────────────┐ ┌──────────────────┐ ┌──────────────────┐ │
37
+ │ │ Strand A │ │ Strand B │ │ Strand C │ │
38
+ │ │ (Chat App) │ │ (Shared Docs) │ │ (Photo Backup) │ │
39
+ │ └──────────────────┘ └──────────────────┘ └──────────────────┘ │
40
+ └─────────────────────────────────────────────────────────────────────────┘
41
+ ```
42
+
43
+ Each `CadreNode` instance:
44
+ 1. **Connects to the control network** - A private Optimystic database shared only by your nodes
45
+ 2. **Watches for strand changes** - Automatically detects when you join or leave strands
46
+ 3. **Manages strand instances** - Spins up isolated libp2p networks for each strand
47
+ 4. **Handles peer enrollment** - Cryptographically authorizes new devices to join your cadre
48
+
49
+ ## Installation
50
+
51
+ ```bash
52
+ npm install @serfab/cadre-core
53
+ ```
54
+
55
+ ## Quick Start
56
+
57
+ ```typescript
58
+ import { CadreNode } from '@serfab/cadre-core';
59
+ import { FileRawStorage } from '@optimystic/db-p2p-storage-fs';
60
+
61
+ const node = new CadreNode({
62
+ controlNetwork: {
63
+ partyId: 'your-unique-party-id',
64
+ bootstrapNodes: ['/ip4/192.168.1.100/tcp/4001/p2p/12D3KooW...']
65
+ },
66
+ profile: 'storage', // 'storage' for servers, 'transaction' for mobile
67
+ storage: {
68
+ // Storage provider factory - called once per scope (each strand id, plus this
69
+ // party's control database) for per-scope isolation
70
+ provider: (scope) => new FileRawStorage(`/data/sereus/${scope}`),
71
+ quotaBytes: 10 * 1024 * 1024 * 1024 // 10 GB
72
+ }
73
+ });
74
+
75
+ // Start the node
76
+ await node.start();
77
+ console.log('Node started with Peer ID:', node.peerId?.toString());
78
+
79
+ // Listen for strand events
80
+ node.on('strand:started', ({ strandId }) => {
81
+ console.log('Joined strand:', strandId);
82
+ });
83
+
84
+ // Check active strands
85
+ for (const [id, strand] of node.getStrands()) {
86
+ console.log(`Strand ${id}: ${strand.status}, ${strand.connectedPeers} peers`);
87
+ }
88
+
89
+ // Graceful shutdown
90
+ await node.stop();
91
+ ```
92
+
93
+ ## Node Profiles
94
+
95
+ | Profile | Storage Role | Use Case | Ring Zulu |
96
+ |---------|--------------|----------|-----------|
97
+ | **transaction** | Arachnode disabled; transaction verification via FRET only | Mobile devices, intermittent connectivity | No |
98
+ | **storage** | Ring Zulu + storage rings (storage rings not yet implemented — stub) | Servers, NAS, always-on nodes | Yes |
99
+
100
+ Transaction-profile nodes verify transactions via FRET only, with Arachnode disabled. Storage-profile nodes additionally join Ring Zulu and (when implemented) the concentric storage rings.
101
+
102
+ > **Note:** The storage-ring subsystem is currently a no-op stub (`arachnode-stub.ts`). See [Node Profiles in `docs/architecture.md`](../../docs/architecture.md#node-profiles) for the full design.
103
+
104
+ ## Strand Filtering
105
+
106
+ Mobile apps typically shouldn't participate in all strands. Use filters to control participation:
107
+
108
+ ```typescript
109
+ // Only participate in strands for a specific app
110
+ strandFilter: { mode: 'sAppId', sAppId: 'com.example.chat' }
111
+
112
+ // Only participate in one specific strand
113
+ strandFilter: { mode: 'strandId', strandId: 'strand-abc123' }
114
+
115
+ // Control network only, no strand participation
116
+ strandFilter: { mode: 'none' }
117
+
118
+ // Participate in all strands (default for servers)
119
+ strandFilter: { mode: 'all' }
120
+ ```
121
+
122
+ ## Enrolling New Devices
123
+
124
+ Adding a new device to your cadre uses the Seed Bootstrap API:
125
+
126
+ ```typescript
127
+ // On the new device: generate identity
128
+ const enrollment = new EnrollmentService();
129
+ const { peerId, privateKey } = await enrollment.createCadrePeer();
130
+ // Store privateKey securely, send peerId + multiaddrs to owner
131
+
132
+ // On owner device: authorize the new peer and create seed
133
+ await node.authorizePeer(newDevicePeerId, newDeviceMultiaddrs);
134
+ const seed = await node.createSeed();
135
+
136
+ // Deliver seed to new device (via protocol, API, or out-of-band)
137
+ await node.deliverSeed(newDeviceMultiaddr, seed);
138
+ // Or encode for QR/link: const encoded = node.encodeSeed(seed);
139
+
140
+ // On new device: apply seed to join cadre
141
+ const result = await newNode.applySeed(seed);
142
+ ```
143
+
144
+ For a machine whose peer id and addresses you already have, use the helper (`cadre enroll add` runs it on the owner node):
145
+
146
+ ```typescript
147
+ // One call: authorize + create seed
148
+ const { seed, encodedSeed } = await node.addDrone({ dronePeerId, droneMultiaddrs });
149
+
150
+ // The new machine starts with it: `cadre start --seed <encodedSeed> --pin-owner-key <owner key>`
151
+
152
+ // Await the dial of the drone from the addresses addDrone kept (a drone cannot
153
+ // dial a phone); the row insert starts a pass that dials it anyway, about 50 ms
154
+ // later, and retries a failed dial after 15 s, 30 s, 60 s, then every 2 minutes
155
+ await node.reconcileControlCohort();
156
+ ```
157
+
158
+ A provider-hosted node is added with `rentNode` instead (below).
159
+
160
+ ### Renting a provider node
161
+
162
+ An app rents an always-on node from a hosting provider with `rentNode`, which adds the container to this node's cadre by invitation when a member is reachable from anywhere and by claim otherwise ([architecture.md → Renting a node from an app](../../docs/architecture.md#renting-a-node-from-an-app)). Everything it needs loads on React Native and in the browser:
163
+
164
+ ```typescript
165
+ import { createProviderClient, createTokenSource, fetchProviderDescriptor, rentNode } from '@serfab/cadre-core';
166
+
167
+ const descriptor = await fetchProviderDescriptor('https://nodes.acme.example/api/v1/descriptor');
168
+ // `stored` comes from the PKCE sign-in (createPkce, authorizationUrl, readAuthorizationRedirect,
169
+ // exchangeAuthorizationCode) or from the app's own store; `save` writes each refreshed pair back
170
+ const tokens = createTokenSource({ descriptor, clientId: 'my-app', tokens: stored, persist: save });
171
+ const client = createProviderClient({ apiBaseUrl: descriptor.apiBaseUrl, tokens });
172
+
173
+ const rental = await rentNode(node, client, { onProgress: (step) => console.log(step) });
174
+ // rental.join: 'invitation' (the container joins by itself; watch client.getContainer(id).join)
175
+ // or 'claim' (the node is in the cadre when rentNode returns, rental.peerId names it).
176
+ // Keep rental.containerId: finishRental(node, client, containerId) resumes a rental the app
177
+ // was killed in the middle of, and the container is what the provider bills.
178
+ ```
179
+
180
+ ## API Reference
181
+
182
+ ### CadreNode
183
+
184
+ The main entry point for cadre participation.
185
+
186
+ | Method | Description |
187
+ |--------|-------------|
188
+ | `start()` | Connect to control network and begin strand participation |
189
+ | `stop()` | Gracefully disconnect from all networks |
190
+ | `getStrands()` | Get all active strand instances |
191
+ | `getStrand(id)` | Get a specific strand instance |
192
+ | `foundStrand(config)` | **Create a strand**: publish its `Strand` row and start it locally as founder, in one call that is safe to re-run after an interruption. Returns the instance plus the row it actually runs under — for a closed strand read the membership key from there, since a resumed founding keeps the stored key |
193
+ | `addStrand(row)` | Attach only — start a local instance for a row that already exists (the join path; also testing/direct API). Does **not** publish |
194
+ | `stopStrand(id)` | Stop a strand on this node only (the shared `Strand` row stays; rediscovered on restart) |
195
+ | `publishStrand(id, type?, memberKey?)` | Owner-signed `Strand` row insert — makes the strand visible cadre-wide. Idempotent: a live row with the same `(Type, MemberPrivateKey)` is returned unwritten; different content on the same id throws. Prefer `foundStrand` when creating a strand |
196
+ | `unpublishStrand(id)` | Owner-signed party-wide removal — deletes this party's `Strand` row; every node stops the strand. Destroys a closed strand's `MemberPrivateKey` |
197
+ | `getEnrollmentService()` | Access peer enrollment API |
198
+ | `isOwner()` | Whether this node can act as an owner of its cadre: an owner key is wired for signing (`useOwnerSigner`) and is a live `OwnerKey` row; never the node's identity key. The gate the owner-only flows (`createCadreInvitation`, `createOwnerGrant`, `claimNode`, `rentNode`) share with the apps |
199
+ | `invitationReach()` | Where a device could redeem an invitation minted now from, judged on the other members' addresses (`anywhere`, `local-network`, `issuer-only`), without minting one; `rentNode` chooses its join path by it |
200
+
201
+ ### Events
202
+
203
+ | Event | Payload | Description |
204
+ |-------|---------|-------------|
205
+ | `control:connected` | - | Connected to control network |
206
+ | `control:disconnected` | - | Disconnected from control network |
207
+ | `strand:started` | `{ strandId }` | Strand instance started |
208
+ | `strand:stopped` | `{ strandId }` | Strand instance stopped |
209
+ | `strand:error` | `{ strandId, error }` | Error in strand instance. A failed launch re-emits this on every retry (backing off up to 5 min), so treat it as a repeating signal, not a one-shot. The exception is an `AppSchemaRefusedError` (the app's schema can never apply to the strand's tables): that strand is not retried until the next `addStrand` |
210
+ | `strand:commit-durability` | `StrandCommitDurability` | After every commit on a strand's database that wrote something: whether another member already holds it (`heldElsewhere`), whether `strand:commit-held` will say when one does (`followed`), and, on a node offering offline mode, which of the party's machines it did not reach (`awaitedMachines`). Also readable as `instance.database.commitDurability(tx)`; see [strands.md → A commit's durability](../../docs/strands.md#a-commits-durability) |
211
+ | `strand:commit-held` | `{ strandId, transactionId }` | A followed commit held only below full replication is now held by every member of its cohort |
212
+
213
+ ## Related Documentation
214
+
215
+ - **[Cadre Architecture](../../docs/architecture.md)** - Deep dive into the cadre system design
216
+ - **[Strand Management](../../docs/strands.md)** - How strands connect multiple cadres
217
+ - **[Schema Guide](../../docs/schema-guide.md)** - Optimystic schema definitions
218
+
219
+ ## React Native Support
220
+
221
+ This package is compatible with React Native. For mobile apps, use the RN-specific storage provider:
222
+
223
+ ```typescript
224
+ import { CadreNode } from '@serfab/cadre-core';
225
+ import { RNRawStorage } from '@optimystic/db-p2p-storage-rn';
226
+ import { webSockets } from '@libp2p/websockets';
227
+ import { circuitRelayTransport } from '@libp2p/circuit-relay-v2';
228
+
229
+ const node = new CadreNode({
230
+ controlNetwork: {
231
+ partyId: 'your-unique-party-id',
232
+ bootstrapNodes: ['/dns4/relay.example.com/tcp/443/wss/p2p/12D3KooW...']
233
+ },
234
+ profile: 'transaction', // Mobile devices typically use transaction profile
235
+ strandFilter: { mode: 'sAppId', sAppId: 'com.example.myapp' },
236
+ storage: {
237
+ // RN storage provider creates per-scope AsyncStorage
238
+ provider: (scope) => new RNRawStorage(scope)
239
+ },
240
+ network: {
241
+ // TCP doesn't work in React Native — use WebSocket transport instead
242
+ transports: [webSockets(), circuitRelayTransport()],
243
+ listenAddrs: [] // RN nodes typically cannot listen
244
+ }
245
+ });
246
+ ```
247
+
248
+ ### Storage Provider Pattern
249
+
250
+ The `storage.provider` option accepts either:
251
+ - **An `IRawStorage` instance** - One store shared by every scope, so it can serve only a single party
252
+ - **A factory function** `(scope: string) => IRawStorage` - Creates isolated storage per scope (recommended)
253
+
254
+ A **scope key** is what the factory receives. It is the strand id for each strand, and
255
+ `controlStorageScope(partyId)` — `control-<lowercase hex of the party id>` — for the control
256
+ database, which holds one party's own records and must not be shared between parties. Every
257
+ key is opaque and already safe as a file, directory or database name (always within
258
+ `[a-z0-9._-]`), and two different keys are two different names even on a filesystem that
259
+ ignores case (Windows, macOS): use it verbatim, do not parse it. `isControlStorageScope(scope)`
260
+ tells the two kinds apart. The control key holds the charset by lowercase hex encoding; a strand
261
+ id holds it by check — `assertStrandScopeKey` runs on every strand launch, so a strand
262
+ whose row replicated in from another node with an unusable id (including one with an
263
+ uppercase letter) is refused rather than
264
+ handed to the factory, and on `publishStrand`, so this node never writes such an id into
265
+ the party's control database to begin with.
266
+
267
+ Available storage implementations:
268
+ | Package | Environment | Description |
269
+ |---------|-------------|-------------|
270
+ | `@optimystic/db-p2p` | All | `MemoryRawStorage` - In-memory (testing only) |
271
+ | `@optimystic/db-p2p-storage-fs` | Node.js | `FileRawStorage` - File system storage |
272
+ | `@optimystic/db-p2p-storage-rn` | React Native | `RNRawStorage` - AsyncStorage-based |
273
+
274
+ ### React Native Considerations
275
+
276
+ 1. **Network Transport**: libp2p's TCP transport doesn't work in RN. Pass `transports: [webSockets(), circuitRelayTransport()]` in the `network` config (see example above).
277
+
278
+ 2. **Schema Loading**: The control schema is embedded in the package. Do not set `schemaPath` in React Native.
279
+
280
+ 3. **Profile**: Mobile devices should use `profile: 'transaction'` for battery/bandwidth efficiency.
281
+
282
+ 4. **Strand Filtering**: Always filter strands on mobile to avoid participating in unnecessary networks.
283
+
284
+ ## Related Packages
285
+
286
+ - **[@optimystic/db-core](https://github.com/gotchoices/optimystic)** - Distributed database core
287
+ - **[@optimystic/db-p2p](https://github.com/gotchoices/optimystic)** - libp2p integration for Optimystic
288
+ - **[@optimystic/db-p2p-storage-fs](https://github.com/gotchoices/optimystic)** - File system storage (Node.js)
289
+ - **[@optimystic/db-p2p-storage-rn](https://github.com/gotchoices/optimystic)** - AsyncStorage (React Native)
290
+
291
+ ## License
292
+
293
+ MIT
294
+