@derec-alliance/react-native 0.0.8 → 0.0.10

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 (50) hide show
  1. package/README.md +410 -9
  2. package/android/src/main/jniLibs/arm64-v8a/libderec_library.a +0 -0
  3. package/android/src/main/jniLibs/armeabi-v7a/libderec_library.a +0 -0
  4. package/android/src/main/jniLibs/x86_64/libderec_library.a +0 -0
  5. package/cpp/Convert.cpp +9 -0
  6. package/cpp/Convert.h +8 -2
  7. package/cpp/Primitives.cpp +123 -29
  8. package/cpp/ProtocolHost.cpp +4 -5
  9. package/cpp/StoreCallbacks.cpp +148 -61
  10. package/cpp/StoreCallbacks.h +8 -1
  11. package/cpp/derec_ffi.h +127 -48
  12. package/ios/DeRecFFI.xcframework/Info.plist +5 -5
  13. package/ios/DeRecFFI.xcframework/ios-arm64/Headers/derec_ffi.h +127 -48
  14. package/ios/DeRecFFI.xcframework/ios-arm64/libderec_library.a +0 -0
  15. package/ios/DeRecFFI.xcframework/ios-arm64_x86_64-simulator/Headers/derec_ffi.h +127 -48
  16. package/ios/DeRecFFI.xcframework/ios-arm64_x86_64-simulator/libderec_library.a +2 -2
  17. package/lib/errors.d.ts +11 -1
  18. package/lib/errors.js +66 -1
  19. package/lib/messages.js +5 -3
  20. package/lib/primitives.d.ts +3 -3
  21. package/lib/primitives.js +7 -3
  22. package/lib/protocol.d.ts +110 -10
  23. package/lib/protocol.js +166 -11
  24. package/lib/types.d.ts +474 -48
  25. package/lib/types.js +23 -1
  26. package/package.json +4 -17
  27. package/schema/derec_descriptor.bin +0 -0
  28. package/schema/proto/committedderecshare.proto +93 -0
  29. package/schema/proto/communicationinfo.proto +104 -0
  30. package/schema/proto/contact.proto +258 -0
  31. package/schema/proto/derecmessage.proto +232 -0
  32. package/schema/proto/derecsecret.proto +163 -0
  33. package/schema/proto/derectransport.proto +38 -0
  34. package/schema/proto/error.proto +68 -0
  35. package/schema/proto/getshare.proto +184 -0
  36. package/schema/proto/pair.proto +284 -0
  37. package/schema/proto/parameterrange.proto +36 -0
  38. package/schema/proto/prepair.proto +163 -0
  39. package/schema/proto/result.proto +194 -0
  40. package/schema/proto/secretidsversions.proto +199 -0
  41. package/schema/proto/storeshare.proto +242 -0
  42. package/schema/proto/transportprotocol.proto +112 -0
  43. package/schema/proto/unpair.proto +132 -0
  44. package/schema/proto/updatechannelinfo.proto +100 -0
  45. package/schema/proto/verify.proto +160 -0
  46. package/src/errors.ts +69 -1
  47. package/src/messages.ts +5 -3
  48. package/src/primitives.ts +19 -4
  49. package/src/protocol.ts +175 -13
  50. package/src/types.ts +481 -52
package/README.md CHANGED
@@ -91,12 +91,16 @@ import {
91
91
  SenderKind,
92
92
  } from '@derec-alliance/react-native';
93
93
 
94
+ // withStores sets all five stores in one call. Each with*Store setter is
95
+ // still available; the last call for a store wins.
94
96
  const protocol = new DeRecProtocolBuilder(secretId) // bigint | number
95
- .withChannelStore(myChannelStore)
96
- .withShareStore(myShareStore)
97
- .withSecretStore(mySecretStore)
98
- .withUserSecretStore(myUserSecretStore)
99
- .withStateStore(myStateStore)
97
+ .withStores({
98
+ channelStore: myChannelStore,
99
+ shareStore: myShareStore,
100
+ secretStore: mySecretStore,
101
+ userSecretStore: myUserSecretStore,
102
+ stateStore: myStateStore,
103
+ })
100
104
  .withTransport(myTransport)
101
105
  .withOwnTransports([{ uri: 'https://owner.example.com', protocol: 'https' }])
102
106
  .withThreshold(2)
@@ -125,6 +129,88 @@ longer needed (safe to call more than once).
125
129
 
126
130
  ---
127
131
 
132
+ ## Verification outcomes
133
+
134
+ `protocol.start(FlowKind.VerifyShares, …)` challenges each targeted helper,
135
+ and every challenged channel ends with exactly one event:
136
+
137
+ - `ShareVerified` — the helper proved it holds the exact share. `subshares`
138
+ is how many subshares that helper holds for `version`, read from this
139
+ device's stored share, so it is the weight of the round that published
140
+ `version`, not the helper's current weight; it is absent when that share was
141
+ stored before the count was recorded. `threshold` is the threshold that version was split with, from the
142
+ same stored share, not the current one; it is absent when that share was
143
+ stored before the threshold was recorded. To judge whether a version is
144
+ recoverable, sum `subshares` over its `ShareVerified` events and compare the
145
+ sum with their `threshold`. If either is absent on any of those events,
146
+ the result is unknown: a absent count is not `0` or `1`. The count lives on `Share.subshares`, which the
147
+ library sets on owner-side shares only (absent on a helper's share and never
148
+ backfilled): your `ShareStore` must persist it as given and return it
149
+ unchanged. `Share.threshold` follows the same rules, and must be
150
+ persisted the same way.
151
+ - `ShareVerifyInvalid { channel_id, version }` — the helper's proof does not
152
+ match the share this device stored. It is an event; `process()` does not
153
+ reject.
154
+ - `ShareVerifyRejected { status, memo }` — the helper refused the challenge
155
+ with a non-OK status.
156
+ - `VerifySharesFailed { reason, error }` — no verdict could be reached on
157
+ this device. `reason` is a `VerifyFailureReason`: `'NoSharedKey'`,
158
+ `'NoProof'` or `'DispatchFailed'`.
159
+
160
+ A stored proof is either confirmed by its helper or part of a sharing round
161
+ still open: when a round settles a channel as failed (a rejection or a
162
+ timeout), that channel's proof is deleted. A confirmation also deletes the
163
+ proofs of versions the helper dropped: a helper that stores a version
164
+ deletes every other version except that round's `keepVersion`, so when it
165
+ confirms, its proofs for those versions are deleted here too (the confirmed
166
+ version and `keepVersion` stay). A helper that rejects the round keeps its
167
+ older versions, and so do their proofs. A replica Destination never sees the helpers' answers, and it keeps every
168
+ proof it receives: it never deletes one on its own, and freeing that storage
169
+ is the app's concern. Verifying on a Destination a version that a helper
170
+ refused, or later dropped under a `keepVersion`, gets `ShareVerifyRejected`
171
+ (`UNKNOWN_SHARE_VERSION`) from that helper, where the Source reports
172
+ `NoProof`. The app may delete such rows from the Destination's share store;
173
+ verifying a version whose rows are gone then gives `VerifySharesFailed` with
174
+ `reason: 'NoProof'`. Verify only versions whose round
175
+ completed (`SharingComplete`). Starting verification on a channel with no
176
+ proof sends nothing and returns `VerifySharesFailed` with
177
+ `reason: 'NoProof'` at once. A late response to an earlier challenge is
178
+ ignored as `MessageIgnored` with `reason: 'StaleResponse'`, and the current
179
+ challenge stays open; a response missing its `result` is still an error.
180
+
181
+ Matching responses to requests is the app's concern. The library applies a
182
+ response that changes stored state only against the flow that asked for it,
183
+ and reports the rest as they arrive without matching them: `ShareConfirmed`
184
+ and `ShareRejected` (a sharing round counts only the helpers it is waiting
185
+ for), `SecretsDiscovered`, `ChannelInfoUpdated`, `ChannelInfoUpdateRejected`
186
+ and `ErrorResponseReceived`. An app that acts on these should record what it
187
+ started and match each event against it, and decide which versions committed
188
+ from `SharingComplete` with `threshold_met` rather than by counting
189
+ `ShareConfirmed`, since a helper can confirm twice or unasked. See [Matching
190
+ responses to requests is the application's
191
+ job](https://github.com/derecalliance/lib-derec/tree/main/library#matching-responses-to-requests-is-the-applications-job).
192
+
193
+ **After recovery: restore or join.** `SecretRecovered` writes nothing, so
194
+ decide before calling `restore`. When `secret.replicas?.members` names live
195
+ members other than the lost device, do not restore: tell the user and offer
196
+ to join that group as a new replica — pair with a live member, confirm the
197
+ fingerprint, then run `start(FlowKind.ReplicaDiscovery)`. With no live member, restore. Neither path gives this device the proofs of
198
+ earlier versions, so it cannot verify them: restore writes none, and a
199
+ joining device gets only the share map of the single version each push or
200
+ catch-up carries. The live members keep the proofs they hold. A restored
201
+ device also cannot publish, or answer a member's catch-up, until the app
202
+ configures a `replica_id` the roster names. Joining adds the device as a new
203
+ member, while restoring next to live replicas makes a second device claim
204
+ the lost device's role. See
205
+ [Restore or join](https://derec-alliance.gitbook.io/docs/concepts/replicas/restore-or-join).
206
+
207
+ Every channel message carries one timestamp, its send time, in both the
208
+ envelope and the inner message. A message whose two timestamps differ, or
209
+ where either or both are absent, is ignored as `MessageIgnored` with
210
+ `reason: 'TimestampMismatch'`; this includes replies from 0.0.8 peers.
211
+
212
+ ---
213
+
128
214
  ## When `process()` fails
129
215
 
130
216
  `process()` settles expired deadlines (sharing-round and unpair timeouts)
@@ -144,6 +230,80 @@ try {
144
230
  }
145
231
  ```
146
232
 
233
+ A request this device fails to handle does not reject the call; see
234
+ [Failed requests](#failed-requests).
235
+
236
+ ---
237
+
238
+ ## Failed requests
239
+
240
+ Every request that arrives on an authenticated channel gets exactly one
241
+ response, even when handling it fails. Such a failure does not make
242
+ `process()` or `accept()` reject: it is reported as a `RequestFailed` event,
243
+ and the call's other events are kept.
244
+
245
+ - `action_kind` is the type of the request that failed, a
246
+ `PendingActionKind` label (`"Failed"` when its body could not be decoded,
247
+ or was a request type the channel cannot carry).
248
+ - `responded` is `true` when the library already sent the response.
249
+ - `status` is the `StatusEnum` that was sent, or would have been. It is
250
+ always present. `memo` is the wire-safe memo sent with it, or that would
251
+ have been, so `reject(action, status, memo)` sends exactly the response
252
+ the library would have sent.
253
+ - `error_code` is the error's `DeRecErrorCode` and `message` a local
254
+ description; neither goes on the wire.
255
+ - `action`, when `responded` is `false`, is the token that answers the
256
+ request. Pass it to `reject`, which sends the one response; `accept`
257
+ refuses it. The library never expires it. It is absent only when `reject`
258
+ could never answer it: a request on a replica group channel that names no
259
+ member and carries no `replyTo`, which has no reply target, or, with
260
+ `withAutoRespondOnFailure` off, a replica copy that hands this device the
261
+ group key and fails before that key is stored.
262
+
263
+ Resolve each token once. The library is stateless, so rejecting the same
264
+ token twice, or rejecting an action already accepted, sends a second
265
+ response.
266
+
267
+ `withAutoRespondOnFailure` decides who answers. With it on, the library sends
268
+ the response itself (a known failure keeps its specific status; anything else
269
+ is `FAIL` with a generic memo). With it off (the default), nothing is sent and
270
+ the event carries the token:
271
+
272
+ ```ts
273
+ for (const event of events) {
274
+ if (event.type === "RequestFailed" && !event.responded && event.action) {
275
+ await protocol.reject(event.action, event.status, event.memo);
276
+ }
277
+ }
278
+ ```
279
+
280
+ A message that decrypts under the channel key but whose body cannot be
281
+ decoded is answered with an `ErrorResponseMessage` (`FORMAT_ERROR` when the
282
+ library answers it; the status passed to `reject` otherwise). A peer that
283
+ answers this device that way is reported as an `ErrorResponseReceived` event
284
+ with `status` and `memo`; it is never answered.
285
+
286
+ An inbound `PairRequest` refused under a protocol rule (a parameter range that
287
+ does not overlap this device's, `INCOMPATIBLE_PARAMETER_RANGE`, or a replica id
288
+ already in the group, `REPLICA_ID_CONFLICT`) is answered with that status in
289
+ every mode and reported as a `PairingRefused` event with `status` and `memo`,
290
+ the reason sent to the requester and written from its side. `error_code`
291
+ (`incompatible_parameter_range` or `replica_id_conflict`) and `message` carry
292
+ the local reason for logging or display, as on `RequestFailed`; they are never
293
+ sent. `process()` does not reject for it, and no channel is created. The
294
+ requester's `process()` rejects with code `non_ok_status`, whose `status` and
295
+ `memo` hold the refusal.
296
+
297
+ An inbound share the library refuses before any `ActionRequired` (undecodable,
298
+ failing its commitment, outside this device's share-size range, or conflicting
299
+ with the share stored at that version) is reported as a `ShareRefused` event
300
+ with the `status` and `memo` sent; the owner observes it as `ShareRejected`.
301
+
302
+ A replica group member's copy of the secret that does not decode or verify is
303
+ refused, nothing is written, and it is reported as a `ReplicaSecretRefused`
304
+ event with `status` and `memo`; on a push the publisher observes it as
305
+ `ReplicaSyncRejected`.
306
+
147
307
  ---
148
308
 
149
309
  ## Store interfaces
@@ -155,9 +315,10 @@ declared in `src/types.ts`:
155
315
  - **`ChannelStore`** — pairing state: helper channels and replica-group
156
316
  membership, keyed by `(channelId, replicaId)`.
157
317
  - **`ShareStore`** — versioned VSS shares this device holds as a helper.
158
- On an owner, `keepList` chooses which versions helpers keep; returning
159
- `null` sends no keepList, so helpers keep every version; see
160
- [the owner's keep list](https://github.com/derecalliance/lib-derec/tree/main/library#share-store-the-owners-keep-list).
318
+ On an owner, `keepVersion` chooses the one older version helpers keep
319
+ besides the one being shared (`0` keeps none); an answer equal to or
320
+ greater than that version fails the round with `invalid_keep_version`; see
321
+ [`DeRecShareStore::keep_version`](https://docs.rs/derec-library/latest/derec_library/protocol/traits/trait.DeRecShareStore.html#tymethod.keep_version).
161
322
  - **`SecretStore`** — small per-channel key material (shared keys, etc.),
162
323
  distinct from share bytes.
163
324
  - **`UserSecretStore`** — the most recent user-facing secret snapshot per
@@ -172,12 +333,72 @@ declared in `src/types.ts`:
172
333
  deliver once, to the first one that accepts it, and reject only when none
173
334
  did. `sequentialFailover` and `singleEndpointTransport` implement that
174
335
  choice for you. It is a mailbox, not a request/response call, since not
175
- every peer (e.g. a phone behind NAT) can be dialed back.
336
+ every peer (e.g. a phone behind NAT) can be dialed back. Recommended HTTP
337
+ conventions (`POST`, `application/octet-stream` body, `202 Accepted`) and
338
+ the same-connection pattern for unreachable peers are in
339
+ [Transports](https://derec-alliance.gitbook.io/docs/protocol-specification/transports);
340
+ they are recommendations, not protocol requirements.
176
341
 
177
342
  Every method is `async` and keyed by decimal-string ids — see the next
178
343
  section for why that differs from `DeRecProtocol`'s own methods. Full field-
179
344
  level contracts are documented as TSDoc on each interface in `src/types.ts`.
180
345
 
346
+ ### Helpers and shares
347
+
348
+ - Each share goes to a **different** helper. Threshold security depends on it:
349
+ compromising one helper must yield at most one share.
350
+ - The library hands out one share per channel per version, and every pairing
351
+ produces its own channel. It cannot tell whether two channels lead to the
352
+ same party; keeping helpers distinct is the application's job.
353
+ - **Discouraged:** a single guardian acting as several helpers for the same
354
+ owner. It is against the protocol's recommendation, since one compromise
355
+ yields several shares. The library does not prevent it, but channel linking
356
+ then needs the application's help (below).
357
+ - **Channel linking is expected to be one-to-one.** After an owner re-pairs in
358
+ recovery mode, the helper application links the new channel to the old one
359
+ with `ChannelStore.linkChannel`. Linking assumes a helper holds **at most one share per owner
360
+ for a given `secretId` and version**, so each recovery channel is linked to the
361
+ single old channel it replaces. On `GetShare` the helper answers with
362
+ **one** share from the linked set: the first whose `secretId` matches the
363
+ request, in the order `ShareStore.loadMany` returns. The library imposes no order. If
364
+ several channels holding shares for the same owner are linked to one
365
+ recovery channel and every recovery channel is answered from the same
366
+ share, the owner receives it more than once (it counts once) and can fall
367
+ below the threshold. An application that runs such a helper keeps each
368
+ recovery channel resolving to a distinct share: either links stay
369
+ one-to-one, or its share store returns, for each requesting channel, the
370
+ share intended for it first, in a deterministic order.
371
+
372
+ ### Refusing a share or a verification
373
+
374
+ A helper enforces share size itself: with a parameter range configured, a
375
+ share outside its own `minShareSize`/`maxShareSize` (inclusive; a max of `0` means
376
+ unbounded) is answered with `SIZE_LIMIT_EXCEEDED` before any
377
+ `ActionRequired` or auto-accept. Frequency limits on share updates and
378
+ verifications are the application's to enforce, from its share store.
379
+
380
+ On a helper channel, throw (or reject with) `shareStoreRefusal(reason)` from
381
+ `ShareStore.save` (a genuinely new share version) or
382
+ `ShareStore.recordVerification` (an accepted verification challenge) to
383
+ refuse it:
384
+
385
+ ```ts
386
+ import { shareStoreRefusal } from "@derec-alliance/react-native";
387
+
388
+ async recordVerification(secretId: string, channelId: string, version: number) {
389
+ if (limiter.tooSoon(channelId)) throw shareStoreRefusal("too_frequent");
390
+ }
391
+ ```
392
+
393
+ The library answers the owner with the mapped status (`"too_frequent"` →
394
+ `TOO_FREQUENT`, `"size_limit_exceeded"` → `SIZE_LIMIT_EXCEEDED`,
395
+ `"rejected"` → `REJECTED`), and the owner sees `ShareRejected` or
396
+ `ShareVerifyRejected` with that `status`. Any other rejection is an ordinary
397
+ store failure, reported as a `RequestFailed` event (see
398
+ [Failed requests](#failed-requests)). Every `ShareStore` implements
399
+ `recordVerification`; an app with no limit resolves it. See
400
+ [Helper-side admission control](https://github.com/derecalliance/lib-derec/tree/main/library#helper-side-admission-control).
401
+
181
402
  ### Filtered listings
182
403
 
183
404
  `listHelpers` and `listReplicas` receive a filter object — `ids`, `status`,
@@ -226,6 +447,102 @@ for its duration. Applications that need this work off the JS thread should
226
447
  drive it through `DeRecProtocol` (e.g. `start(FlowKind.ProtectSecret, ...)`)
227
448
  instead of calling the primitive directly.
228
449
 
450
+ `split`'s `channels` argument is a `WeightedChannel[]` — `[channelId,
451
+ weight]` tuples, one per channel, letting a chosen channel hold more than
452
+ one subshare (e.g. a device the owner trusts more than the others). A
453
+ weight of `1` is an ordinary helper holding a single subshare, so with every
454
+ weight at `1`, `threshold` counts helpers as before. `ProtectSecretParams`
455
+ accepts an equivalent `weights: Map<bigint, number>` when driving the flow
456
+ through `DeRecProtocol`; `ProtectSecretStarted` and `ProtectSecretFailed`
457
+ report the resulting `weight` for the channel they name.
458
+
459
+ That map is the **full assignment, not a patch**: a paired helper it does not
460
+ name holds one subshare. Weights are recorded: each round writes the weight it gave every paired helper
461
+ to that helper's channel record before anything is sent, and the publishes the
462
+ library starts on its own (after pairing, after a fingerprint is confirmed)
463
+ reuse those weights; a newly paired helper starts at 1. The weights also travel
464
+ in the recovered secret (`helpers[].weight`), so `restore` and replica
465
+ hydration write them back into the channel records they create.
466
+
467
+ The threshold is recorded too. A round splits at `ProtectSecretParams.threshold` when
468
+ given, otherwise at the stored threshold (`UserSecrets.threshold`), and only otherwise
469
+ at `withThreshold`, which is therefore the starting threshold for a secret with
470
+ nothing stored. Every publish stores the threshold it used, the recovered
471
+ secret carries it (`secret.threshold`), and `restore` and replica
472
+ hydration put it back, so the publishes the library starts on its own and
473
+ the follow-up after `restore` keep it: leave `threshold` unset there. To
474
+ change it, pass `threshold` on `start(FlowKind.ProtectSecret, …)`. It must be at least 2,
475
+ above every weight, and no greater than a subshare cap; a round that fails
476
+ a check writes and sends nothing. Your `UserSecretStore` must persist the
477
+ snapshot's threshold as given.
478
+
479
+ The intended flow. Weights are the user's choice: before `start`, show the
480
+ user each paired helper's current weight, pre-filled from your `ChannelStore`,
481
+ and pass the user's final choice as the whole `weights` map. Reading the
482
+ stored weights first is the normal flow. Every other `start(FlowKind.ProtectSecret, ...)`
483
+ the app makes, such as a republish after editing the secrets or the follow-up
484
+ after `restore`, must pass the stored weights unchanged: a helper left out
485
+ returns to 1, which silently undoes the user's choice. Only the publishes the
486
+ library starts on its own (after pairing, after a fingerprint is confirmed)
487
+ reuse the stored weights by themselves.
488
+
489
+ A helper record is opaque JSON bytes, `{"Helper": {...}}`. Parsing one to read
490
+ `weight` is safe: it is a small integer, and the channel id comes from the
491
+ `channelId` argument your store received, never from the parsed object's
492
+ `channel_id` (a `u64` that `JSON.parse` can round). What the `ChannelStore`
493
+ docs forbid is re-serialising a parsed record; keep persisting the original
494
+ bytes.
495
+
496
+ ```ts
497
+ const weight = JSON.parse(new TextDecoder().decode(helperRecordBytes)).Helper.weight || 1;
498
+ ```
499
+
500
+ When the builder's threshold applies (no threshold is stored), lowering it to
501
+ or below a stored weight makes the next publish fail
502
+ with code `invalid_weight` before anything is sent, until `ProtectSecret`
503
+ assigns valid weights.
504
+
505
+ That failure surfaces where the library started the publish, and in each
506
+ case nothing is sent:
507
+
508
+ - `process()` throws an error whose `events` keep the message's events,
509
+ `PairingCompleted` included.
510
+ - `accept()` throws. The pairing has completed and its response was sent,
511
+ but `PairingCompleted` is not returned.
512
+ - `verifyFingerprint()` throws. The promotion stands: calling it again
513
+ resolves `true` and publishes nothing.
514
+
515
+ Call `start` with `ProtectSecret` and valid weights to publish to every
516
+ helper.
517
+
518
+ **Below the threshold.** When the paired helpers' total weight is below the
519
+ threshold, `start` skips the split: no helper receives anything, so no
520
+ `ProtectSecretStarted` / `ProtectSecretFailed` comes back for one. A paired
521
+ replica still gets its usual secret-only copy and events; with none paired,
522
+ `start` resolves with no events at all — this is not an error. The version
523
+ still advances and the secrets/description are saved as the latest
524
+ snapshot, so the next publish that reaches threshold (including one the
525
+ library starts on its own) shares it. Sum the weights about to be assigned
526
+ against the threshold beforehand, or count the returned helper events
527
+ afterward, to tell the two cases apart. This is more reachable with
528
+ weighted helpers than with the default of 1: two helpers at weight 2 against
529
+ a threshold of 3 (total weight 4) drop below it when a publish leaves both
530
+ out of the weights map, resetting each to weight 1 for a total of 2 — a
531
+ risk for a restore follow-up publish that does not pass the stored weights
532
+ unchanged.
533
+
534
+ `withMaxSubshares(max)` on the builder caps the total subshares one round
535
+ splits the secret into — the sum of every helper's weight. Unset means no
536
+ cap. Recovery time grows quadratically with that total (about 0.2 s at 200,
537
+ 5.5 s at 1,000 and 87 s at 4,000 subshares per attempt) while splitting stays
538
+ cheap, so this is the place to bound it. A round over the cap fails
539
+ `start(FlowKind.ProtectSecret, ...)` with code `too_many_subshares` before
540
+ anything is sent; publishes the library starts itself count the stored weights
541
+ and respect it too. A cap
542
+ below the threshold makes `build()` throw `invalid_input`. The cap applies at
543
+ sharing only, never at recovery: a recovering device cannot know the cap the
544
+ shares were made under.
545
+
229
546
  **Do not call protocol methods from inside a store callback.** A store
230
547
  method (`load`, `save`, `remove`, ...) is invoked as a callback into
231
548
  JavaScript, with the protocol's worker blocked waiting for the promise that
@@ -249,6 +566,11 @@ omits `"wasm"`, which a C-ABI binding can never emit, and adds `"ok"`,
249
566
  `"ffi"` and `"state_store"`, which it can. A test pins the union to the crate's shared enum fixture so it stays in step
250
567
  with the Rust enum.
251
568
 
569
+ **`DeRecError.code` is typed `DeRecErrorCode`.** It lists exactly the codes
570
+ `derec_error_code_name` can return — no WASM-only marshalling codes, since
571
+ this SDK never goes through WASM. A test pins it to the same shared enum
572
+ fixture as `DeRecErrorCategory`.
573
+
252
574
  **Ids are decimal strings in stores, `bigint | number` on `DeRecProtocol`.**
253
575
  Store interfaces (`ChannelStore`, `ShareStore`, event fields such as
254
576
  `channel_id` / `replica_id`, etc.) use decimal strings for every `u64` id,
@@ -263,6 +585,85 @@ everywhere.
263
585
 
264
586
  ---
265
587
 
588
+ ## Configuration from a file or record
589
+
590
+ Applications usually load settings as a whole: general settings from the
591
+ environment or a config file, per-user settings from a user record.
592
+ `DeRecProtocolConfig` holds every data setting of the builder, each one
593
+ optional, and `withConfig` applies it in one call:
594
+
595
+ ```ts
596
+ import { DeRecProtocolBuilder } from "@derec-alliance/react-native";
597
+ import type { DeRecProtocolConfig } from "@derec-alliance/react-native";
598
+
599
+ const general: DeRecProtocolConfig = JSON.parse(generalJson);
600
+ const perUser: DeRecProtocolConfig = JSON.parse(userRecordJson);
601
+
602
+ const protocol = new DeRecProtocolBuilder(secretId)
603
+ .withChannelStore(channelStore)
604
+ .withShareStore(shareStore)
605
+ .withSecretStore(secretStore)
606
+ .withUserSecretStore(userSecretStore)
607
+ .withStateStore(stateStore)
608
+ .withTransport(myTransport)
609
+ .withConfig(general) // 1. general settings
610
+ .withConfig(perUser) // 2. per-user settings
611
+ .withThreshold(4) // 3. individual setters
612
+ .build();
613
+ ```
614
+
615
+ - **Only set (present and non-`null`) fields are applied.** An absent or
616
+ `null` field leaves whatever the builder already holds.
617
+ - **Last write wins, per field.** Nested objects replace the builder's value
618
+ as a whole, except `timeouts`: each of its fields is merged separately, so
619
+ a per-user config that sets only `inbound_message_secs` keeps the
620
+ `sharing_round_secs` the general config set.
621
+ - **This binding assigns; it validates nothing.** Every key is forwarded
622
+ verbatim, under its own spelling, into the same `snake_case` config JSON
623
+ `build()` sends over the FFI. Rust applies the same rules a matching
624
+ `with*` setter's value would and rejects an unknown key at any level — a
625
+ misspelled key, or a value that fails validation, throws from `build()`
626
+ rather than being silently ignored.
627
+ - **Stores, the transport and the constructor's `secretId` are not settings**
628
+ and are not carried in the config.
629
+ - **A `secret_id` key in a config is ignored, not rejected.** `build()`
630
+ assigns the constructor's `secretId` last, so a config carrying a
631
+ `secret_id` key (for example a per-user record that includes it by
632
+ mistake) never changes which secret this instance manages. Every other
633
+ SDK rejects that key outright, since `DeRecProtocolConfig` has no
634
+ `secret_id` field there and unknown keys fail.
635
+
636
+ The canonical JSON, shared by every SDK, is:
637
+
638
+ ```json
639
+ {
640
+ "threshold": 3,
641
+ "max_subshares": "12",
642
+ "timeouts": {
643
+ "inbound_message_secs": 300,
644
+ "sharing_round_secs": 60,
645
+ "unpair_ack_secs": 60,
646
+ "expired_channels": { "enabled": true, "timeout_in_secs": 300 }
647
+ },
648
+ "parameter_range": { "min_share_size": 1, "max_share_size": 4096 },
649
+ "auto_accept": { "pairing": true, "store_share": true },
650
+ "auto_respond_on_failure": false,
651
+ "auto_reply_to": false,
652
+ "unpair_ack": "required",
653
+ "unsafe_connection": false,
654
+ "communication_info": { "name": "alice" },
655
+ "own_transports": [{ "uri": "https://me.example.com/derec", "protocol": "https" }],
656
+ "replica_id": "9007199254740993"
657
+ }
658
+ ```
659
+
660
+ Keys are `snake_case` and every key is optional. `replica_id` and
661
+ `max_subshares` are `u64` values written as decimal strings. Timeouts are
662
+ whole seconds. See the `DeRecProtocolConfig` doc comment in `src/types.ts` for
663
+ every field's accepted forms.
664
+
665
+ ---
666
+
266
667
  ## Package contents
267
668
 
268
669
  ```text
package/cpp/Convert.cpp CHANGED
@@ -169,6 +169,15 @@ std::optional<DecodedShare> decodeShareRecord(const uint8_t* ptr, size_t len) {
169
169
  out.secretId = std::move(*secretId);
170
170
  out.version = static_cast<uint32_t>(parseUnsignedAt(json, versionPos));
171
171
  out.bytes = parseByteArrayAt(json, bytesPos);
172
+ auto optionalUnsigned = [&json](const char* field) -> std::optional<uint32_t> {
173
+ size_t pos = fieldValueOffset(json, field);
174
+ if (pos != std::string::npos && pos < json.size() && json[pos] >= '0' && json[pos] <= '9') {
175
+ return static_cast<uint32_t>(parseUnsignedAt(json, pos));
176
+ }
177
+ return std::nullopt;
178
+ };
179
+ out.subshares = optionalUnsigned("subshares");
180
+ out.threshold = optionalUnsigned("threshold");
172
181
  return out;
173
182
  }
174
183
 
package/cpp/Convert.h CHANGED
@@ -60,14 +60,20 @@ std::vector<uint8_t> decodeSecretValueBytes(const uint8_t* ptr, size_t len);
60
60
 
61
61
  /// A `ShareRecord` as `ShareStore.save` receives it. `secretId` is the
62
62
  /// record's own `secret_id`, kept as the decimal string Rust wrote.
63
+ /// `subshares` is the owner-side subshare count and `threshold` the
64
+ /// owner-side threshold the version was split with, each empty when Rust
65
+ /// wrote none.
63
66
  struct DecodedShare {
64
67
  std::string secretId;
65
68
  uint32_t version;
66
69
  std::vector<uint8_t> bytes;
70
+ std::optional<uint32_t> subshares;
71
+ std::optional<uint32_t> threshold;
67
72
  };
68
73
 
69
- /// Decode `{"secret_id":"...","version":<n>,"bytes":[<n>,...]}`. Empty when
70
- /// any of the three fields is absent.
74
+ /// Decode `{"secret_id":"...","version":<n>,"bytes":[<n>,...],"subshares":<n>,"threshold":<n>}`.
75
+ /// Empty when any of the first three fields is absent; `subshares` and
76
+ /// `threshold` are optional, and absent or `null` decodes as none.
71
77
  std::optional<DecodedShare> decodeShareRecord(const uint8_t* ptr, size_t len);
72
78
 
73
79
  } // namespace derec