@derec-alliance/react-native 0.0.9 → 0.0.11

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 (47) hide show
  1. package/README.md +114 -7
  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/Primitives.cpp +38 -9
  6. package/cpp/Primitives.h +5 -3
  7. package/cpp/ProtocolHost.cpp +4 -5
  8. package/cpp/StoreCallbacks.cpp +31 -43
  9. package/cpp/derec_ffi.h +98 -33
  10. package/ios/DeRecFFI.xcframework/ios-arm64/Headers/derec_ffi.h +98 -33
  11. package/ios/DeRecFFI.xcframework/ios-arm64/libderec_library.a +0 -0
  12. package/ios/DeRecFFI.xcframework/ios-arm64_x86_64-simulator/Headers/derec_ffi.h +98 -33
  13. package/ios/DeRecFFI.xcframework/ios-arm64_x86_64-simulator/libderec_library.a +2 -2
  14. package/lib/errors.d.ts +8 -3
  15. package/lib/errors.js +6 -0
  16. package/lib/messages.js +5 -3
  17. package/lib/primitives.d.ts +12 -2
  18. package/lib/primitives.js +17 -2
  19. package/lib/protocol.d.ts +9 -5
  20. package/lib/protocol.js +9 -5
  21. package/lib/types.d.ts +194 -46
  22. package/lib/types.js +4 -1
  23. package/package.json +4 -17
  24. package/schema/derec_descriptor.bin +0 -0
  25. package/schema/proto/committedderecshare.proto +93 -0
  26. package/schema/proto/communicationinfo.proto +104 -0
  27. package/schema/proto/contact.proto +266 -0
  28. package/schema/proto/derecmessage.proto +248 -0
  29. package/schema/proto/derecsecret.proto +163 -0
  30. package/schema/proto/derectransport.proto +38 -0
  31. package/schema/proto/error.proto +68 -0
  32. package/schema/proto/getshare.proto +184 -0
  33. package/schema/proto/pair.proto +284 -0
  34. package/schema/proto/parameterrange.proto +36 -0
  35. package/schema/proto/prepair.proto +164 -0
  36. package/schema/proto/result.proto +194 -0
  37. package/schema/proto/secretidsversions.proto +199 -0
  38. package/schema/proto/storeshare.proto +242 -0
  39. package/schema/proto/transportprotocol.proto +112 -0
  40. package/schema/proto/unpair.proto +132 -0
  41. package/schema/proto/updatechannelinfo.proto +100 -0
  42. package/schema/proto/verify.proto +160 -0
  43. package/src/errors.ts +12 -1
  44. package/src/messages.ts +5 -3
  45. package/src/primitives.ts +23 -2
  46. package/src/protocol.ts +10 -6
  47. package/src/types.ts +185 -43
package/README.md CHANGED
@@ -161,13 +161,13 @@ A stored proof is either confirmed by its helper or part of a sharing round
161
161
  still open: when a round settles a channel as failed (a rejection or a
162
162
  timeout), that channel's proof is deleted. A confirmation also deletes the
163
163
  proofs of versions the helper dropped: a helper that stores a version
164
- deletes every other version that round's `keepList` leaves out, so when it
164
+ deletes every other version except that round's `keepVersion`, so when it
165
165
  confirms, its proofs for those versions are deleted here too (the confirmed
166
- version stays). A helper that rejects the round keeps its older versions, and
167
- so do their proofs; with no keep list nothing is deleted. A replica Destination never sees the helpers' answers, and it keeps every
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
168
  proof it receives: it never deletes one on its own, and freeing that storage
169
169
  is the app's concern. Verifying on a Destination a version that a helper
170
- refused, or later dropped under the `keepList`, gets `ShareVerifyRejected`
170
+ refused, or later dropped under a `keepVersion`, gets `ShareVerifyRejected`
171
171
  (`UNKNOWN_SHARE_VERSION`) from that helper, where the Source reports
172
172
  `NoProof`. The app may delete such rows from the Destination's share store;
173
173
  verifying a version whose rows are gone then gives `VerifySharesFailed` with
@@ -178,6 +178,46 @@ proof sends nothing and returns `VerifySharesFailed` with
178
178
  ignored as `MessageIgnored` with `reason: 'StaleResponse'`, and the current
179
179
  challenge stays open; a response missing its `result` is still an error.
180
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
+ A recovery reconstructs nothing until every helper it asked has answered (a
194
+ share, a refusal or a corrupted share all count) or
195
+ `timeouts.get_share_response_secs` has passed since the requests went out;
196
+ each silent helper is then reported as `RecoverSecretFailed` with
197
+ `error: "timeout"` from `tick()`. It then decides exactly once:
198
+
199
+ - `SecretRecovered` — one secret reconstructs and every collected share is
200
+ part of it;
201
+ - `RecoveryDisputed { version, secret, supported_by, disputed_by }` — one
202
+ secret reconstructs, but other helpers hold valid shares of a different
203
+ split that does not. Either side can be the owner's: colluding helpers can
204
+ forge a complete split, and the honest ones may be too few to reconstruct
205
+ theirs. Show the owner what `secret` holds and who stands on each side, and
206
+ pass it to `restore` only once they confirm it;
207
+ - `RecoveryConflict { version, candidates, disputed_by }` — two or more
208
+ different secrets reconstruct. Each candidate carries the `secret` and
209
+ `supported_by`. The library never picks: involve the owner, and pass the
210
+ candidate they confirm to `restore`;
211
+ - `RecoveryIncomplete { secret_id, version, shares_received }` — nothing reconstructs.
212
+ The recovery is closed; start it again to retry.
213
+
214
+ `supported_by` / `disputed_by` name helpers as `RecoveryHelper { channel_id,
215
+ communication_info }`, the `communication_info` being what the helper
216
+ advertised when it paired, so the app can tell the owner who is on each side.
217
+ That is the helper's own configured communication info, not the
218
+ `peer_communication_info` it passed to `start(Pairing)`: a helper that
219
+ configures none is named by its channel alone.
220
+
181
221
  **After recovery: restore or join.** `SecretRecovered` writes nothing, so
182
222
  decide before calling `restore`. When `secret.replicas?.members` names live
183
223
  members other than the lost device, do not restore: tell the user and offer
@@ -197,6 +237,32 @@ envelope and the inner message. A message whose two timestamps differ, or
197
237
  where either or both are absent, is ignored as `MessageIgnored` with
198
238
  `reason: 'TimestampMismatch'`; this includes replies from 0.0.8 peers.
199
239
 
240
+ Within the inbound window `process` handles every copy of a message it is
241
+ given, including one of this device's own messages delivered back to it.
242
+ Detecting both is the app's transport's job: `envelope.message_id(bytes)`
243
+ returns an `id` that is the same for every copy of one message, whatever its
244
+ unauthenticated fields (sequence, trace id, protocol version) say, and a
245
+ `timestamp`. Keep the `id` of every envelope you send and of every envelope
246
+ `process` accepted (no throw and no `MessageIgnored`) until
247
+ `max(received or sent at, timestamp) + inbound_message_secs`, drop an inbound
248
+ envelope whose `id` you kept, and keep the record across restarts. Never key
249
+ on a hash of the raw bytes. A helper ignores a `StoreShareRequest` for a
250
+ version older than the newest it stores on the channel, and not stored
251
+ itself, as `MessageIgnored` with `reason: 'Superseded'`, unanswered. Reject a
252
+ contact update older than the last one you accepted on the channel, using the
253
+ `timestamp` of the envelope that raised it; that needs auto-accept off for
254
+ `UpdateChannelInfo`.
255
+
256
+ A pairing has a lifetime, `timeouts.pairing_secs` (default 30). Both sides
257
+ enforce it and nothing is sent on expiry: `start(FlowKind.Pairing, …)` refuses
258
+ a contact older than it with code `pairing_expired`; the contact's creator
259
+ reports a request on such a contact, or a request older than the lifetime, as
260
+ `MessageIgnored` with reason `"Expired"` before any `ActionRequired`, and
261
+ `accept` refuses a request that outlived it with `pairing_expired`. Pairing
262
+ involves both parties, so treat an expiry as a retry and ask the user to scan
263
+ or share a fresh contact. Keep the scanner's `expired_channels` timeout at
264
+ least `pairing_secs` plus the time a response takes to arrive.
265
+
200
266
  ---
201
267
 
202
268
  ## When `process()` fails
@@ -303,9 +369,10 @@ declared in `src/types.ts`:
303
369
  - **`ChannelStore`** — pairing state: helper channels and replica-group
304
370
  membership, keyed by `(channelId, replicaId)`.
305
371
  - **`ShareStore`** — versioned VSS shares this device holds as a helper.
306
- On an owner, `keepList` chooses which versions helpers keep; returning
307
- `null` sends no keepList, so helpers keep every version; see
308
- [the owner's keep list](https://github.com/derecalliance/lib-derec/tree/main/library#share-store-the-owners-keep-list).
372
+ On an owner, `keepVersion` chooses the one older version helpers keep
373
+ besides the one being shared (`0` keeps none); an answer equal to or
374
+ greater than that version fails the round with `invalid_keep_version`; see
375
+ [`DeRecShareStore::keep_version`](https://docs.rs/derec-library/latest/derec_library/protocol/traits/trait.DeRecShareStore.html#tymethod.keep_version).
309
376
  - **`SecretStore`** — small per-channel key material (shared keys, etc.),
310
377
  distinct from share bytes.
311
378
  - **`UserSecretStore`** — the most recent user-facing secret snapshot per
@@ -630,6 +697,8 @@ The canonical JSON, shared by every SDK, is:
630
697
  "inbound_message_secs": 300,
631
698
  "sharing_round_secs": 60,
632
699
  "unpair_ack_secs": 60,
700
+ "get_share_response_secs": 300,
701
+ "pairing_secs": 30,
633
702
  "expired_channels": { "enabled": true, "timeout_in_secs": 300 }
634
703
  },
635
704
  "parameter_range": { "min_share_size": 1, "max_share_size": 4096 },
@@ -665,6 +734,44 @@ react-native.config.js
665
734
 
666
735
  ---
667
736
 
737
+ ## Security considerations
738
+
739
+ ### An unconfirmed replica member is not part of the group
740
+
741
+ Until a device confirms a member's fingerprint with `verifyFingerprint`, that
742
+ member is not part of the group as far as the device is concerned. It is left
743
+ out of every roster the device publishes (each new version, catch-up answers
744
+ and the vault itself), it is not asked in a replica version check, and it
745
+ cannot succeed a removed source. Every recipient installs a roster's members
746
+ as paired, so listing an unconfirmed one would admit it on their behalf.
747
+
748
+ ### Every helper sees the vault's compressed length
749
+
750
+ The vault (the user's secrets, every helper's channel key and
751
+ `communication_info`, and the replica group key) is compressed as one gzip stream
752
+ before it is encrypted and split. Encryption keeps the length, so every
753
+ helper learns the compressed length of every version. A helper also chooses
754
+ part of what is compressed: its own `communication_info`, which it changes with
755
+ `UpdateChannelInfo`. When that text repeats part of a secret elsewhere in
756
+ the vault, the vault compresses better, so over many versions a corrupted
757
+ helper could learn another helper's channel key, the group key or the
758
+ user's secrets a few characters at a time (the side channel behind CRIME
759
+ and BREACH). Each guess costs a new version, which only the owner creates,
760
+ after a contact change the owner's application has to accept. Keep the `updateChannelInfo` auto-accept flag
761
+ off, and treat a helper that keeps changing its contact details as suspect.
762
+
763
+ ### Decoding a recovered vault has no memory limit
764
+
765
+ In recovery the vault is decrypted from shares that nothing authenticates,
766
+ so a forged recovery group can deliver any payload, including one built to
767
+ exhaust memory. The decoder parses the vault while it inflates it: a
768
+ payload that is not JSON is refused after its first bytes, and padding is
769
+ not buffered. A payload that is valid JSON still receives the memory its
770
+ largest value claims, and gzip lets a payload claim up to about 1030 times
771
+ its own size. The library sets no limit. When memory runs out, the process is killed by the operating system or aborts inside the native library, with no error and no event. To bound it, configure
772
+ `parameter_range.max_share_size`: a recovery share larger than that is refused before anything is
773
+ decoded, so a vault can claim at most about 1030 times that size.
774
+
668
775
  ## License
669
776
 
670
777
  Apache License 2.0
@@ -38,6 +38,8 @@ void throwDeRecError(jsi::Runtime& rt,
38
38
  int32_t peerStatus = error.peer_status;
39
39
  uint32_t expected = error.expected;
40
40
  uint32_t got = error.got;
41
+ bool hasChannelId = process.hasChannelId || error.has_channel_id;
42
+ uint64_t channelId = process.hasChannelId ? process.channelId : error.channel_id;
41
43
 
42
44
  // Release both owned strings in one call, matching the ABI contract.
43
45
  DeRecError owned = error;
@@ -62,9 +64,9 @@ void throwDeRecError(jsi::Runtime& rt,
62
64
  jsi::Value::createFromJsonUtf8(rt, conflictingChannelIdsJson.data(),
63
65
  conflictingChannelIdsJson.size()));
64
66
  }
65
- if (process.hasChannelId) {
67
+ if (hasChannelId) {
66
68
  payload.setProperty(rt, "channel_id",
67
- jsi::String::createFromUtf8(rt, std::to_string(process.channelId)));
69
+ jsi::String::createFromUtf8(rt, std::to_string(channelId)));
68
70
  }
69
71
  if (!process.eventsJson.empty()) {
70
72
  payload.setProperty(rt, "events",
@@ -209,8 +211,7 @@ std::vector<uint64_t> asU64Array(jsi::Runtime& rt, const char* name, const jsi::
209
211
  }
210
212
 
211
213
  /// Read a JS array of `number` elements as a `uint32_t` vector. Used for
212
- /// `protect_secret`'s `weights` and
213
- /// `produce_store_share_request_message`'s `keep_list` arguments.
214
+ /// `protect_secret`'s `weights` argument.
214
215
  std::vector<uint32_t> asU32Array(jsi::Runtime& rt, const char* name, const jsi::Value& value) {
215
216
  std::vector<uint32_t> out;
216
217
  if (value.isNull() || value.isUndefined()) {
@@ -374,6 +375,26 @@ jsi::Value readTraceId(jsi::Runtime& rt,
374
375
  return jsi::Value(rt, jsi::BigInt::fromUint64(rt, result.trace_id));
375
376
  }
376
377
 
378
+ /// `message_id_from_envelope(envelope: ArrayBuffer)
379
+ /// -> { id: ArrayBuffer, timestamp: bigint }`
380
+ jsi::Value messageId(jsi::Runtime& rt,
381
+ const jsi::Value&,
382
+ const jsi::Value* args,
383
+ size_t count) {
384
+ requireArgs(rt, "message_id_from_envelope", count, 1);
385
+ ByteView envelope = asBytes(rt, args[0]);
386
+ MessageIdResult result = message_id_from_envelope(envelope.ptr, envelope.len);
387
+ if (result.error.code != 0) {
388
+ throwDeRecError(rt, result.error);
389
+ }
390
+ std::vector<uint8_t> id = takeBuffer(result.id);
391
+ auto payload = jsi::Object(rt);
392
+ payload.setProperty(rt, "id", toArrayBuffer(rt, id.data(), id.size()));
393
+ payload.setProperty(rt, "timestamp",
394
+ jsi::BigInt::fromUint64(rt, result.timestamp));
395
+ return payload;
396
+ }
397
+
377
398
  /// `version() -> { major: number, minor: number }` — the protocol version the
378
399
  /// core writes into every envelope it produces.
379
400
  jsi::Value protocolVersion(jsi::Runtime& rt,
@@ -761,7 +782,7 @@ jsi::Value extractPrePairResponse(jsi::Runtime& rt,
761
782
 
762
783
  /// `process_pre_pair_response_message(contactMessage: ArrayBuffer,
763
784
  /// responseProto: ArrayBuffer) -> { mlkem_encapsulation_key,
764
- /// ecies_public_key, nonce }`
785
+ /// ecies_public_key, nonce, fingerprint_commitment }`
765
786
  jsi::Value processPrePairResponseMessage(jsi::Runtime& rt,
766
787
  const jsi::Value&,
767
788
  const jsi::Value* args,
@@ -777,6 +798,7 @@ jsi::Value processPrePairResponseMessage(jsi::Runtime& rt,
777
798
  }
778
799
  std::vector<uint8_t> mlkemKey = takeBuffer(result.mlkem_encapsulation_key);
779
800
  std::vector<uint8_t> eciesKey = takeBuffer(result.ecies_public_key);
801
+ std::vector<uint8_t> commitment = takeBuffer(result.fingerprint_commitment);
780
802
  auto payload = jsi::Object(rt);
781
803
  payload.setProperty(rt, "mlkem_encapsulation_key",
782
804
  toArrayBuffer(rt, mlkemKey.data(), mlkemKey.size()));
@@ -784,6 +806,8 @@ jsi::Value processPrePairResponseMessage(jsi::Runtime& rt,
784
806
  toArrayBuffer(rt, eciesKey.data(), eciesKey.size()));
785
807
  payload.setProperty(rt, "nonce",
786
808
  jsi::Value(rt, jsi::BigInt::fromUint64(rt, result.nonce)));
809
+ payload.setProperty(rt, "fingerprint_commitment",
810
+ toArrayBuffer(rt, commitment.data(), commitment.size()));
787
811
  return jsi::Value(rt, payload);
788
812
  }
789
813
 
@@ -816,7 +840,7 @@ jsi::Value producePrePairNoKeysResponseMessage(jsi::Runtime& rt,
816
840
 
817
841
  /// `process_pre_pair_no_keys_response_message(contactMessage: ArrayBuffer,
818
842
  /// responseProto: ArrayBuffer) -> { mlkem_encapsulation_key,
819
- /// ecies_public_key, nonce }`
843
+ /// ecies_public_key, nonce, fingerprint_commitment }`
820
844
  jsi::Value processPrePairNoKeysResponseMessage(jsi::Runtime& rt,
821
845
  const jsi::Value&,
822
846
  const jsi::Value* args,
@@ -834,6 +858,7 @@ jsi::Value processPrePairNoKeysResponseMessage(jsi::Runtime& rt,
834
858
  }
835
859
  std::vector<uint8_t> mlkemKey = takeBuffer(result.mlkem_encapsulation_key);
836
860
  std::vector<uint8_t> eciesKey = takeBuffer(result.ecies_public_key);
861
+ std::vector<uint8_t> commitment = takeBuffer(result.fingerprint_commitment);
837
862
  auto payload = jsi::Object(rt);
838
863
  payload.setProperty(rt, "mlkem_encapsulation_key",
839
864
  toArrayBuffer(rt, mlkemKey.data(), mlkemKey.size()));
@@ -841,6 +866,8 @@ jsi::Value processPrePairNoKeysResponseMessage(jsi::Runtime& rt,
841
866
  toArrayBuffer(rt, eciesKey.data(), eciesKey.size()));
842
867
  payload.setProperty(rt, "nonce",
843
868
  jsi::Value(rt, jsi::BigInt::fromUint64(rt, result.nonce)));
869
+ payload.setProperty(rt, "fingerprint_commitment",
870
+ toArrayBuffer(rt, commitment.data(), commitment.size()));
844
871
  return jsi::Value(rt, payload);
845
872
  }
846
873
 
@@ -1004,7 +1031,7 @@ jsi::Value protectSecret(jsi::Runtime& rt,
1004
1031
  }
1005
1032
 
1006
1033
  /// `produce_store_share_request_message(channelId: bigint, version: number,
1007
- /// secretId: bigint, committedShare: ArrayBuffer, keepList: number[],
1034
+ /// secretId: bigint, committedShare: ArrayBuffer, keepVersion: number,
1008
1035
  /// description: ArrayBuffer, sharedKey: ArrayBuffer, replyTo:
1009
1036
  /// ArrayBuffer|null) -> ArrayBuffer`
1010
1037
  jsi::Value produceStoreShareRequestMessage(jsi::Runtime& rt,
@@ -1017,14 +1044,15 @@ jsi::Value produceStoreShareRequestMessage(jsi::Runtime& rt,
1017
1044
  rt, "produce_store_share_request_message", "version", args[1], std::numeric_limits<uint32_t>::max()));
1018
1045
  uint64_t secretId = asU64(rt, args[2]);
1019
1046
  ByteView committedShare = asBytes(rt, args[3]);
1020
- std::vector<uint32_t> keepList = asU32Array(rt, "produce_store_share_request_message", args[4]);
1047
+ auto keepVersion = static_cast<uint32_t>(asScalarInteger(
1048
+ rt, "produce_store_share_request_message", "keep_version", args[4], std::numeric_limits<uint32_t>::max()));
1021
1049
  ByteView description = asBytes(rt, args[5]);
1022
1050
  ByteView sharedKey = asBytes(rt, args[6]);
1023
1051
  ByteView replyTo = asBytes(rt, args[7]);
1024
1052
  ProduceStoreShareRequestMessageResult result =
1025
1053
  produce_store_share_request_message(
1026
1054
  channelId, version, secretId, committedShare.ptr,
1027
- committedShare.len, keepList.data(), keepList.size(),
1055
+ committedShare.len, keepVersion,
1028
1056
  description.ptr, description.len, sharedKey.ptr, sharedKey.len,
1029
1057
  replyTo.ptr, replyTo.len);
1030
1058
  if (result.error.code != 0) {
@@ -1377,6 +1405,7 @@ void installPrimitives(jsi::Runtime& rt, jsi::Object& host) {
1377
1405
  processGetSecretIdsVersionsResponseMessage);
1378
1406
  bind(rt, host, "apply_trace_id_to_envelope", 2, applyTraceId);
1379
1407
  bind(rt, host, "read_trace_id_from_envelope", 1, readTraceId);
1408
+ bind(rt, host, "message_id_from_envelope", 1, messageId);
1380
1409
  bind(rt, host, "create_contact_message", 5, createContactMessage);
1381
1410
  bind(rt, host, "encode_contact_message", 1, encodeContactMessage);
1382
1411
  bind(rt, host, "decode_contact_message", 1, decodeContactMessage);
package/cpp/Primitives.h CHANGED
@@ -34,9 +34,11 @@ struct ProcessFailureDetails {
34
34
  uint64_t channelId = 0;
35
35
  };
36
36
 
37
- /// As above, additionally attaching `channel_id` (a decimal string) when
38
- /// `process.hasChannelId` is set, and `events` (the JSON array verbatim)
39
- /// when `process.eventsJson` is non-empty. Only `process` produces these.
37
+ /// As above, additionally attaching `events` (the JSON array verbatim) when
38
+ /// `process.eventsJson` is non-empty, which only `process` produces.
39
+ /// `channel_id` (a decimal string) is `process.channelId` when
40
+ /// `process.hasChannelId` is set, else the error's own channel when it
41
+ /// names one.
40
42
  [[noreturn]] void throwDeRecError(facebook::jsi::Runtime& rt,
41
43
  const DeRecError& error,
42
44
  const std::vector<uint8_t>& conflictingChannelIdsJson,
@@ -538,16 +538,15 @@ jsi::Value ProtocolHost::get(jsi::Runtime& rt, const jsi::PropNameID& name) {
538
538
  DeRecProtocolHandle* handle = handle_;
539
539
 
540
540
  auto body = [handle, channelId, fingerprint]() -> std::vector<uint8_t> {
541
- uint32_t matched = 0;
542
541
  DeRecError error = derec_protocol_verify_fingerprint(
543
- handle, channelId, fingerprint.c_str(), &matched);
542
+ handle, channelId, fingerprint.c_str());
544
543
  if (error.code != DEREC_CODE_OK) {
545
544
  throw FfiFailure(error);
546
545
  }
547
- return std::vector<uint8_t>{static_cast<uint8_t>(matched != 0 ? 1 : 0)};
546
+ return {};
548
547
  };
549
- auto convert = [](jsi::Runtime&, std::vector<uint8_t>& bytes) {
550
- return jsi::Value(!bytes.empty() && bytes[0] != 0);
548
+ auto convert = [](jsi::Runtime&, std::vector<uint8_t>&) {
549
+ return jsi::Value::undefined();
551
550
  };
552
551
  return runAsync(rt2, std::move(body), std::move(convert));
553
552
  });
@@ -335,38 +335,27 @@ CallResult toStateLoadAllResult(jsi::Runtime& rt, const jsi::Value& value) {
335
335
  return CallResult{0, std::vector<uint8_t>(text.begin(), text.end())};
336
336
  }
337
337
 
338
- /// `ShareStore.keepList(): Promise<number[] | null | undefined>`. Encodes the
339
- /// resolved value as the wire's `Option<Vec<u32>>` JSON: `null` for
340
- /// `null`/`undefined`, otherwise the array of versions.
338
+ /// `ShareStore.keepVersion(): Promise<number>`. Encodes the resolved version
339
+ /// as 4 little-endian bytes so the calling function can rebuild
340
+ /// `out_version`.
341
341
  ///
342
- /// Anything else, or an entry that is not an integer in `0..=4294967295`, is
343
- /// a backend failure: reading it as `null` would silently send an empty
344
- /// keepList, so helpers would keep every version instead of the list the
345
- /// application meant to send.
346
- CallResult toKeepListResult(jsi::Runtime& rt, const jsi::Value& value) {
347
- if (value.isNull() || value.isUndefined()) {
348
- return CallResult{0, {'n', 'u', 'l', 'l'}};
349
- }
350
- if (!value.isObject() || !value.asObject(rt).isArray(rt)) {
342
+ /// Anything other than an integer in `0..=4294967295` is a backend failure:
343
+ /// reading it as `0` would silently tell helpers to keep no other version.
344
+ CallResult toKeepVersionResult(jsi::Runtime&, const jsi::Value& value) {
345
+ if (!value.isNumber()) {
351
346
  return CallResult{kBackendFailure, {}};
352
347
  }
353
- jsi::Array arr = value.asObject(rt).asArray(rt);
354
- size_t n = arr.size(rt);
355
- std::string text = "[";
356
- for (size_t i = 0; i < n; ++i) {
357
- jsi::Value entry = arr.getValueAtIndex(rt, i);
358
- if (!entry.isNumber()) {
359
- return CallResult{kBackendFailure, {}};
360
- }
361
- double version = entry.asNumber();
362
- if (!(version >= 0 && version <= 4294967295.0) || version != static_cast<double>(static_cast<uint32_t>(version))) {
363
- return CallResult{kBackendFailure, {}};
364
- }
365
- if (i != 0) text += ',';
366
- text += std::to_string(static_cast<uint32_t>(version));
348
+ double raw = value.asNumber();
349
+ if (!(raw >= 0 && raw <= 4294967295.0) || raw != static_cast<double>(static_cast<uint32_t>(raw))) {
350
+ return CallResult{kBackendFailure, {}};
367
351
  }
368
- text += ']';
369
- return CallResult{0, std::vector<uint8_t>(text.begin(), text.end())};
352
+ auto version = static_cast<uint32_t>(raw);
353
+ std::vector<uint8_t> bytes(4);
354
+ bytes[0] = static_cast<uint8_t>(version & 0xFF);
355
+ bytes[1] = static_cast<uint8_t>((version >> 8) & 0xFF);
356
+ bytes[2] = static_cast<uint8_t>((version >> 16) & 0xFF);
357
+ bytes[3] = static_cast<uint8_t>((version >> 24) & 0xFF);
358
+ return CallResult{0, bytes};
370
359
  }
371
360
 
372
361
  /// Reads the `refusal` property a `ShareStore.save`/`recordVerification`
@@ -951,29 +940,28 @@ extern "C" int32_t shareStoreRemoveVersions(void* userData, uint64_t secretId, u
951
940
  return result.code;
952
941
  }
953
942
 
954
- /// `ShareStore.keepList(secretId, version) -> number[] | null`
955
- extern "C" int32_t shareStoreKeepList(void* userData, uint64_t secretId, uint32_t version, uint8_t** outPtr,
956
- size_t* outLen) {
943
+ /// `ShareStore.keepVersion(secretId, version) -> number`
944
+ extern "C" int32_t shareStoreKeepVersion(void* userData, uint64_t secretId, uint32_t version,
945
+ uint32_t* outVersion) {
957
946
  auto* self = static_cast<StoreBindings*>(userData);
958
947
  auto keepAlive = self->shared_from_this();
959
948
  CallResult result =
960
949
  keepAlive->bridge().callSync([keepAlive, secretId, version](std::function<void(CallResult)> settle) {
961
950
  jsi::Runtime& rt = keepAlive->runtime();
962
951
  auto store = keepAlive->shareStore();
963
- auto method = store->getPropertyAsFunction(rt, "keepList");
952
+ auto method = store->getPropertyAsFunction(rt, "keepVersion");
964
953
  jsi::Value promise =
965
954
  method.callWithThis(rt, *store, idVal(rt, secretId), jsi::Value(static_cast<double>(version)));
966
- keepAlive->settleFromPromise(rt, std::move(promise), std::move(settle), toKeepListResult);
955
+ keepAlive->settleFromPromise(rt, std::move(promise), std::move(settle), toKeepVersionResult);
967
956
  });
968
- if (result.code == 0) {
969
- if (!writeOut(result.bytes, outPtr, outLen)) {
970
- return kBackendFailure;
971
- }
972
- } else {
973
- *outPtr = nullptr;
974
- *outLen = 0;
957
+ if (result.code == 0 && result.bytes.size() == 4) {
958
+ *outVersion = static_cast<uint32_t>(result.bytes[0]) | (static_cast<uint32_t>(result.bytes[1]) << 8) |
959
+ (static_cast<uint32_t>(result.bytes[2]) << 16) |
960
+ (static_cast<uint32_t>(result.bytes[3]) << 24);
961
+ return 0;
975
962
  }
976
- return result.code;
963
+ *outVersion = 0;
964
+ return result.code == 0 ? kBackendFailure : result.code;
977
965
  }
978
966
 
979
967
  /// `UserSecretStore.loadLatest(secretId) -> UserSecrets | null`
@@ -1302,7 +1290,7 @@ std::shared_ptr<StoreBindings> StoreBindings::create(jsi::Runtime& rt, jsi::Obje
1302
1290
  shareStoreSave, // save
1303
1291
  shareStoreRemoveChannel, // remove_channel
1304
1292
  shareStoreRemoveVersions, // remove_versions
1305
- shareStoreKeepList, // keep_list
1293
+ shareStoreKeepVersion, // keep_version
1306
1294
  shareStoreRecordVerification, // record_verification
1307
1295
  storeFreeBuffer, // free_buffer
1308
1296
  };
@@ -1351,7 +1339,7 @@ std::shared_ptr<StoreBindings> StoreBindings::create(jsi::Runtime& rt, jsi::Obje
1351
1339
  requireField(rt, bindings->shareCallbacks_.save, "ShareStoreCallbacks.save");
1352
1340
  requireField(rt, bindings->shareCallbacks_.remove_channel, "ShareStoreCallbacks.remove_channel");
1353
1341
  requireField(rt, bindings->shareCallbacks_.remove_versions, "ShareStoreCallbacks.remove_versions");
1354
- requireField(rt, bindings->shareCallbacks_.keep_list, "ShareStoreCallbacks.keep_list");
1342
+ requireField(rt, bindings->shareCallbacks_.keep_version, "ShareStoreCallbacks.keep_version");
1355
1343
  requireField(rt, bindings->shareCallbacks_.record_verification,
1356
1344
  "ShareStoreCallbacks.record_verification");
1357
1345
  requireField(rt, bindings->shareCallbacks_.free_buffer, "ShareStoreCallbacks.free_buffer");