@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
@@ -3,7 +3,9 @@
3
3
 
4
4
  #include "Primitives.h"
5
5
 
6
+ #include <cmath>
6
7
  #include <cstring>
8
+ #include <limits>
7
9
  #include <string>
8
10
  #include <vector>
9
11
 
@@ -118,17 +120,79 @@ jsi::Value toUint8ArrayVal(jsi::Runtime& rt, const std::vector<uint8_t>& bytes)
118
120
  }
119
121
 
120
122
  uint64_t asU64(jsi::Runtime& rt, const jsi::Value& value) {
123
+ auto reject = [&]() -> uint64_t {
124
+ throw jsi::JSError(rt, "expected an integer in 0..=18446744073709551615");
125
+ };
121
126
  if (value.isBigInt()) {
122
- return value.asBigInt(rt).asUint64(rt);
127
+ jsi::BigInt big = value.getBigInt(rt);
128
+ return big.isUint64(rt) ? big.getUint64(rt) : reject();
123
129
  }
124
- return static_cast<uint64_t>(value.asNumber());
130
+ if (!value.isNumber()) {
131
+ return reject();
132
+ }
133
+ double number = value.getNumber();
134
+ // 18446744073709551616.0 is 2^64, the first double above `uint64_t`'s range.
135
+ if (!(number >= 0.0) || number >= 18446744073709551616.0 || std::trunc(number) != number) {
136
+ return reject();
137
+ }
138
+ return static_cast<uint64_t>(number);
125
139
  }
126
140
 
127
141
  namespace {
128
142
 
143
+ /// Read an integer losslessly: a `bigint` or `number` holding an integer in
144
+ /// `0..=max`. Anything else throws `<name> expects <expected>`, so a value is
145
+ /// never truncated, rounded, or wrapped on its way to the core.
146
+ uint64_t asBoundedInteger(jsi::Runtime& rt,
147
+ const char* name,
148
+ const jsi::Value& element,
149
+ uint64_t max,
150
+ const std::string& expected) {
151
+ auto reject = [&]() -> uint64_t {
152
+ throw jsi::JSError(rt, std::string(name) + " expects " + expected);
153
+ };
154
+ if (element.isBigInt()) {
155
+ jsi::BigInt big = element.getBigInt(rt);
156
+ if (!big.isUint64(rt)) {
157
+ return reject();
158
+ }
159
+ uint64_t number = big.getUint64(rt);
160
+ return number <= max ? number : reject();
161
+ }
162
+ if (!element.isNumber()) {
163
+ return reject();
164
+ }
165
+ double number = element.getNumber();
166
+ // 18446744073709551616.0 is 2^64, the first double above `uint64_t`'s range.
167
+ if (!(number >= 0.0) || number >= 18446744073709551616.0 || std::trunc(number) != number) {
168
+ return reject();
169
+ }
170
+ auto integer = static_cast<uint64_t>(number);
171
+ return integer <= max ? integer : reject();
172
+ }
173
+
174
+ /// Read one element of an integer array with `asBoundedInteger`.
175
+ uint64_t asArrayInteger(jsi::Runtime& rt,
176
+ const char* name,
177
+ const jsi::Value& element,
178
+ uint64_t max,
179
+ const char* range) {
180
+ return asBoundedInteger(rt, name, element, max, std::string("an array of integers in ") + range);
181
+ }
182
+
183
+ /// Read the scalar argument `argument` with `asBoundedInteger`.
184
+ uint64_t asScalarInteger(jsi::Runtime& rt,
185
+ const char* name,
186
+ const char* argument,
187
+ const jsi::Value& value,
188
+ uint64_t max) {
189
+ return asBoundedInteger(rt, name, value, max,
190
+ std::string(argument) + " to be an integer in 0..=" + std::to_string(max));
191
+ }
192
+
129
193
  /// Read a JS array of `bigint`/`number` elements as a `uint64_t` vector.
130
194
  /// Used for `protect_secret`'s `channels` argument.
131
- std::vector<uint64_t> asU64Array(jsi::Runtime& rt, const jsi::Value& value) {
195
+ std::vector<uint64_t> asU64Array(jsi::Runtime& rt, const char* name, const jsi::Value& value) {
132
196
  std::vector<uint64_t> out;
133
197
  if (value.isNull() || value.isUndefined()) {
134
198
  return out;
@@ -137,14 +201,16 @@ std::vector<uint64_t> asU64Array(jsi::Runtime& rt, const jsi::Value& value) {
137
201
  size_t length = array.size(rt);
138
202
  out.reserve(length);
139
203
  for (size_t i = 0; i < length; ++i) {
140
- out.push_back(asU64(rt, array.getValueAtIndex(rt, i)));
204
+ out.push_back(asArrayInteger(rt, name, array.getValueAtIndex(rt, i),
205
+ std::numeric_limits<uint64_t>::max(),
206
+ "0..=18446744073709551615"));
141
207
  }
142
208
  return out;
143
209
  }
144
210
 
145
211
  /// Read a JS array of `number` elements as a `uint32_t` vector. Used for
146
- /// `produce_store_share_request_message`'s `keep_list` argument.
147
- std::vector<uint32_t> asU32Array(jsi::Runtime& rt, const jsi::Value& value) {
212
+ /// `protect_secret`'s `weights` argument.
213
+ std::vector<uint32_t> asU32Array(jsi::Runtime& rt, const char* name, const jsi::Value& value) {
148
214
  std::vector<uint32_t> out;
149
215
  if (value.isNull() || value.isUndefined()) {
150
216
  return out;
@@ -153,7 +219,9 @@ std::vector<uint32_t> asU32Array(jsi::Runtime& rt, const jsi::Value& value) {
153
219
  size_t length = array.size(rt);
154
220
  out.reserve(length);
155
221
  for (size_t i = 0; i < length; ++i) {
156
- out.push_back(static_cast<uint32_t>(array.getValueAtIndex(rt, i).asNumber()));
222
+ out.push_back(static_cast<uint32_t>(
223
+ asArrayInteger(rt, name, array.getValueAtIndex(rt, i),
224
+ std::numeric_limits<uint32_t>::max(), "0..=4294967295")));
157
225
  }
158
226
  return out;
159
227
  }
@@ -336,9 +404,11 @@ jsi::Value createContactMessage(jsi::Runtime& rt,
336
404
  size_t count) {
337
405
  requireArgs(rt, "create_contact_message", count, 5);
338
406
  uint64_t channelId = asU64(rt, args[0]);
339
- auto contactMode = static_cast<int32_t>(args[1].asNumber());
407
+ auto contactMode = static_cast<int32_t>(asScalarInteger(
408
+ rt, "create_contact_message", "contact_mode", args[1], std::numeric_limits<int32_t>::max()));
340
409
  ByteView transportProtocols = asBytes(rt, args[2]);
341
- auto hasNonce = static_cast<uint32_t>(args[3].asNumber());
410
+ auto hasNonce = static_cast<uint32_t>(asScalarInteger(
411
+ rt, "create_contact_message", "has_nonce", args[3], std::numeric_limits<uint32_t>::max()));
342
412
  uint64_t nonce = asU64(rt, args[4]);
343
413
  CreateContactMessageResult result = create_contact_message(
344
414
  channelId, contactMode, transportProtocols.ptr, transportProtocols.len,
@@ -412,7 +482,8 @@ jsi::Value decodeMessageJson(jsi::Runtime& rt,
412
482
  const jsi::Value* args,
413
483
  size_t count) {
414
484
  requireArgs(rt, "decode_message_json", count, 2);
415
- auto kind = static_cast<int32_t>(args[0].asNumber());
485
+ auto kind = static_cast<int32_t>(asScalarInteger(
486
+ rt, "decode_message_json", "kind", args[0], std::numeric_limits<int32_t>::max()));
416
487
  ByteView proto = asBytes(rt, args[1]);
417
488
  DeRecMessageJsonResult result =
418
489
  derec_decode_message_json(kind, proto.ptr, proto.len);
@@ -432,7 +503,8 @@ jsi::Value encodeMessageJson(jsi::Runtime& rt,
432
503
  const jsi::Value* args,
433
504
  size_t count) {
434
505
  requireArgs(rt, "encode_message_json", count, 2);
435
- auto kind = static_cast<int32_t>(args[0].asNumber());
506
+ auto kind = static_cast<int32_t>(asScalarInteger(
507
+ rt, "encode_message_json", "kind", args[0], std::numeric_limits<int32_t>::max()));
436
508
  ByteView json = asBytes(rt, args[1]);
437
509
  DeRecMessageJsonResult result =
438
510
  derec_encode_message_json(kind, json.ptr, json.len);
@@ -453,7 +525,8 @@ jsi::Value producePairRequestMessage(jsi::Runtime& rt,
453
525
  const jsi::Value* args,
454
526
  size_t count) {
455
527
  requireArgs(rt, "produce_pair_request_message", count, 5);
456
- auto senderKind = static_cast<int32_t>(args[0].asNumber());
528
+ auto senderKind = static_cast<int32_t>(asScalarInteger(
529
+ rt, "produce_pair_request_message", "sender_kind", args[0], std::numeric_limits<int32_t>::max()));
457
530
  ByteView transportProtocols = asBytes(rt, args[1]);
458
531
  ByteView contactMessage = asBytes(rt, args[2]);
459
532
  ByteView communicationInfo = asBytes(rt, args[3]);
@@ -687,7 +760,7 @@ jsi::Value extractPrePairResponse(jsi::Runtime& rt,
687
760
 
688
761
  /// `process_pre_pair_response_message(contactMessage: ArrayBuffer,
689
762
  /// responseProto: ArrayBuffer) -> { mlkem_encapsulation_key,
690
- /// ecies_public_key, nonce }`
763
+ /// ecies_public_key, nonce, fingerprint_commitment }`
691
764
  jsi::Value processPrePairResponseMessage(jsi::Runtime& rt,
692
765
  const jsi::Value&,
693
766
  const jsi::Value* args,
@@ -703,6 +776,7 @@ jsi::Value processPrePairResponseMessage(jsi::Runtime& rt,
703
776
  }
704
777
  std::vector<uint8_t> mlkemKey = takeBuffer(result.mlkem_encapsulation_key);
705
778
  std::vector<uint8_t> eciesKey = takeBuffer(result.ecies_public_key);
779
+ std::vector<uint8_t> commitment = takeBuffer(result.fingerprint_commitment);
706
780
  auto payload = jsi::Object(rt);
707
781
  payload.setProperty(rt, "mlkem_encapsulation_key",
708
782
  toArrayBuffer(rt, mlkemKey.data(), mlkemKey.size()));
@@ -710,6 +784,8 @@ jsi::Value processPrePairResponseMessage(jsi::Runtime& rt,
710
784
  toArrayBuffer(rt, eciesKey.data(), eciesKey.size()));
711
785
  payload.setProperty(rt, "nonce",
712
786
  jsi::Value(rt, jsi::BigInt::fromUint64(rt, result.nonce)));
787
+ payload.setProperty(rt, "fingerprint_commitment",
788
+ toArrayBuffer(rt, commitment.data(), commitment.size()));
713
789
  return jsi::Value(rt, payload);
714
790
  }
715
791
 
@@ -742,7 +818,7 @@ jsi::Value producePrePairNoKeysResponseMessage(jsi::Runtime& rt,
742
818
 
743
819
  /// `process_pre_pair_no_keys_response_message(contactMessage: ArrayBuffer,
744
820
  /// responseProto: ArrayBuffer) -> { mlkem_encapsulation_key,
745
- /// ecies_public_key, nonce }`
821
+ /// ecies_public_key, nonce, fingerprint_commitment }`
746
822
  jsi::Value processPrePairNoKeysResponseMessage(jsi::Runtime& rt,
747
823
  const jsi::Value&,
748
824
  const jsi::Value* args,
@@ -760,6 +836,7 @@ jsi::Value processPrePairNoKeysResponseMessage(jsi::Runtime& rt,
760
836
  }
761
837
  std::vector<uint8_t> mlkemKey = takeBuffer(result.mlkem_encapsulation_key);
762
838
  std::vector<uint8_t> eciesKey = takeBuffer(result.ecies_public_key);
839
+ std::vector<uint8_t> commitment = takeBuffer(result.fingerprint_commitment);
763
840
  auto payload = jsi::Object(rt);
764
841
  payload.setProperty(rt, "mlkem_encapsulation_key",
765
842
  toArrayBuffer(rt, mlkemKey.data(), mlkemKey.size()));
@@ -767,6 +844,8 @@ jsi::Value processPrePairNoKeysResponseMessage(jsi::Runtime& rt,
767
844
  toArrayBuffer(rt, eciesKey.data(), eciesKey.size()));
768
845
  payload.setProperty(rt, "nonce",
769
846
  jsi::Value(rt, jsi::BigInt::fromUint64(rt, result.nonce)));
847
+ payload.setProperty(rt, "fingerprint_commitment",
848
+ toArrayBuffer(rt, commitment.data(), commitment.size()));
770
849
  return jsi::Value(rt, payload);
771
850
  }
772
851
 
@@ -796,7 +875,8 @@ jsi::Value produceGetShareRequestMessage(jsi::Runtime& rt,
796
875
  requireArgs(rt, "produce_get_share_request_message", count, 5);
797
876
  uint64_t channelId = asU64(rt, args[0]);
798
877
  uint64_t secretId = asU64(rt, args[1]);
799
- auto version = static_cast<uint32_t>(args[2].asNumber());
878
+ auto version = static_cast<uint32_t>(asScalarInteger(
879
+ rt, "produce_get_share_request_message", "version", args[2], std::numeric_limits<uint32_t>::max()));
800
880
  ByteView sharedKey = asBytes(rt, args[3]);
801
881
  ByteView replyTo = asBytes(rt, args[4]);
802
882
  ProduceGetShareRequestMessageResult result = produce_get_share_request_message(
@@ -886,7 +966,8 @@ jsi::Value recoverFromShareResponses(jsi::Runtime& rt,
886
966
  requireArgs(rt, "recover_from_share_responses", count, 3);
887
967
  ByteView responses = asBytes(rt, args[0]);
888
968
  uint64_t secretId = asU64(rt, args[1]);
889
- auto version = static_cast<uint32_t>(args[2].asNumber());
969
+ auto version = static_cast<uint32_t>(asScalarInteger(
970
+ rt, "recover_from_share_responses", "version", args[2], std::numeric_limits<uint32_t>::max()));
890
971
  RecoverFromShareResponsesResult result = recover_from_share_responses(
891
972
  responses.ptr, responses.len, secretId, version);
892
973
  if (result.error.code != 0) {
@@ -897,20 +978,29 @@ jsi::Value recoverFromShareResponses(jsi::Runtime& rt,
897
978
  }
898
979
 
899
980
  /// `protect_secret(secretId: bigint, secretData: ArrayBuffer, channels:
900
- /// (bigint|number)[], threshold: number, version: number) -> ArrayBuffer`
981
+ /// (bigint|number)[], weights: number[], threshold: number, version:
982
+ /// number) -> ArrayBuffer`
901
983
  jsi::Value protectSecret(jsi::Runtime& rt,
902
984
  const jsi::Value&,
903
985
  const jsi::Value* args,
904
986
  size_t count) {
905
- requireArgs(rt, "protect_secret", count, 5);
987
+ requireArgs(rt, "protect_secret", count, 6);
906
988
  uint64_t secretId = asU64(rt, args[0]);
907
989
  ByteView secretData = asBytes(rt, args[1]);
908
- std::vector<uint64_t> channels = asU64Array(rt, args[2]);
909
- auto threshold = static_cast<size_t>(args[3].asNumber());
910
- auto version = static_cast<uint32_t>(args[4].asNumber());
990
+ std::vector<uint64_t> channels = asU64Array(rt, "protect_secret", args[2]);
991
+ std::vector<uint32_t> weights = asU32Array(rt, "protect_secret", args[3]);
992
+ if (channels.size() != weights.size()) {
993
+ throw jsi::JSError(rt,
994
+ "protect_secret: channels and weights must have "
995
+ "the same length");
996
+ }
997
+ auto threshold = static_cast<size_t>(asScalarInteger(
998
+ rt, "protect_secret", "threshold", args[4], std::numeric_limits<size_t>::max()));
999
+ auto version = static_cast<uint32_t>(asScalarInteger(
1000
+ rt, "protect_secret", "version", args[5], std::numeric_limits<uint32_t>::max()));
911
1001
  ProtectSecretResult result = protect_secret(
912
1002
  secretId, secretData.ptr, secretData.len, channels.data(),
913
- channels.size(), threshold, version);
1003
+ weights.data(), channels.size(), threshold, version);
914
1004
  if (result.error.code != 0) {
915
1005
  throwDeRecError(rt, result.error);
916
1006
  }
@@ -919,7 +1009,7 @@ jsi::Value protectSecret(jsi::Runtime& rt,
919
1009
  }
920
1010
 
921
1011
  /// `produce_store_share_request_message(channelId: bigint, version: number,
922
- /// secretId: bigint, committedShare: ArrayBuffer, keepList: number[],
1012
+ /// secretId: bigint, committedShare: ArrayBuffer, keepVersion: number,
923
1013
  /// description: ArrayBuffer, sharedKey: ArrayBuffer, replyTo:
924
1014
  /// ArrayBuffer|null) -> ArrayBuffer`
925
1015
  jsi::Value produceStoreShareRequestMessage(jsi::Runtime& rt,
@@ -928,17 +1018,19 @@ jsi::Value produceStoreShareRequestMessage(jsi::Runtime& rt,
928
1018
  size_t count) {
929
1019
  requireArgs(rt, "produce_store_share_request_message", count, 8);
930
1020
  uint64_t channelId = asU64(rt, args[0]);
931
- auto version = static_cast<uint32_t>(args[1].asNumber());
1021
+ auto version = static_cast<uint32_t>(asScalarInteger(
1022
+ rt, "produce_store_share_request_message", "version", args[1], std::numeric_limits<uint32_t>::max()));
932
1023
  uint64_t secretId = asU64(rt, args[2]);
933
1024
  ByteView committedShare = asBytes(rt, args[3]);
934
- std::vector<uint32_t> keepList = asU32Array(rt, args[4]);
1025
+ auto keepVersion = static_cast<uint32_t>(asScalarInteger(
1026
+ rt, "produce_store_share_request_message", "keep_version", args[4], std::numeric_limits<uint32_t>::max()));
935
1027
  ByteView description = asBytes(rt, args[5]);
936
1028
  ByteView sharedKey = asBytes(rt, args[6]);
937
1029
  ByteView replyTo = asBytes(rt, args[7]);
938
1030
  ProduceStoreShareRequestMessageResult result =
939
1031
  produce_store_share_request_message(
940
1032
  channelId, version, secretId, committedShare.ptr,
941
- committedShare.len, keepList.data(), keepList.size(),
1033
+ committedShare.len, keepVersion,
942
1034
  description.ptr, description.len, sharedKey.ptr, sharedKey.len,
943
1035
  replyTo.ptr, replyTo.len);
944
1036
  if (result.error.code != 0) {
@@ -1035,7 +1127,8 @@ jsi::Value processStoreShareResponseMessage(jsi::Runtime& rt,
1035
1127
  const jsi::Value* args,
1036
1128
  size_t count) {
1037
1129
  requireArgs(rt, "process_store_share_response_message", count, 2);
1038
- auto version = static_cast<uint32_t>(args[0].asNumber());
1130
+ auto version = static_cast<uint32_t>(asScalarInteger(
1131
+ rt, "process_store_share_response_message", "version", args[0], std::numeric_limits<uint32_t>::max()));
1039
1132
  ByteView responseProto = asBytes(rt, args[1]);
1040
1133
  ProcessStoreShareResponseMessageResult result =
1041
1134
  process_store_share_response_message(version, responseProto.ptr,
@@ -1159,7 +1252,8 @@ jsi::Value produceVerifyShareRequestMessage(jsi::Runtime& rt,
1159
1252
  requireArgs(rt, "produce_verify_share_request_message", count, 5);
1160
1253
  uint64_t channelId = asU64(rt, args[0]);
1161
1254
  uint64_t secretId = asU64(rt, args[1]);
1162
- auto version = static_cast<uint32_t>(args[2].asNumber());
1255
+ auto version = static_cast<uint32_t>(asScalarInteger(
1256
+ rt, "produce_verify_share_request_message", "version", args[2], std::numeric_limits<uint32_t>::max()));
1163
1257
  ByteView sharedKey = asBytes(rt, args[3]);
1164
1258
  ByteView replyTo = asBytes(rt, args[4]);
1165
1259
  ProduceVerifyShareRequestMessageResult result =
@@ -1321,7 +1415,7 @@ void installPrimitives(jsi::Runtime& rt, jsi::Object& host) {
1321
1415
  produceGetShareResponseMessage);
1322
1416
  bind(rt, host, "extract_get_share_response", 2, extractGetShareResponse);
1323
1417
  bind(rt, host, "recover_from_share_responses", 3, recoverFromShareResponses);
1324
- bind(rt, host, "protect_secret", 5, protectSecret);
1418
+ bind(rt, host, "protect_secret", 6, protectSecret);
1325
1419
  bind(rt, host, "produce_store_share_request_message", 8,
1326
1420
  produceStoreShareRequestMessage);
1327
1421
  bind(rt, host, "extract_store_share_request", 2, extractStoreShareRequest);
@@ -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
  });
@@ -27,7 +27,7 @@ static_assert(sizeof(ChannelStoreCallbacks) == 9 * sizeof(void*),
27
27
  "ChannelStoreCallbacks layout changed; update the bindings");
28
28
  static_assert(sizeof(SecretStoreCallbacks) == 6 * sizeof(void*),
29
29
  "SecretStoreCallbacks layout changed; update the bindings");
30
- static_assert(sizeof(ShareStoreCallbacks) == 10 * sizeof(void*),
30
+ static_assert(sizeof(ShareStoreCallbacks) == 11 * sizeof(void*),
31
31
  "ShareStoreCallbacks layout changed; update the bindings");
32
32
  static_assert(sizeof(UserSecretStoreCallbacks) == 5 * sizeof(void*),
33
33
  "UserSecretStoreCallbacks layout changed; update the bindings");
@@ -245,6 +245,21 @@ CallResult toShareListResult(jsi::Runtime& rt, const jsi::Value& value) {
245
245
  text += "{\"secret_id\":\"" + secretIdStr + "\",\"version\":" + std::to_string(version) +
246
246
  ",\"bytes\":";
247
247
  appendByteArrayJson(text, bytes.ptr, bytes.len);
248
+ // `subshares` and `threshold`: `null`/`undefined` is none and is omitted,
249
+ // as Rust omits it; anything else must be a `u32` to cross as one.
250
+ for (const char* field : {"subshares", "threshold"}) {
251
+ jsi::Value value = entry.getProperty(rt, field);
252
+ if (value.isNull() || value.isUndefined()) continue;
253
+ if (!value.isNumber()) {
254
+ return CallResult{kBackendFailure, {}};
255
+ }
256
+ double number = value.asNumber();
257
+ if (!(number >= 0 && number <= 4294967295.0) ||
258
+ number != static_cast<double>(static_cast<uint32_t>(number))) {
259
+ return CallResult{kBackendFailure, {}};
260
+ }
261
+ text += std::string(",\"") + field + "\":" + std::to_string(static_cast<uint32_t>(number));
262
+ }
248
263
  text += '}';
249
264
  }
250
265
  text += ']';
@@ -320,38 +335,59 @@ CallResult toStateLoadAllResult(jsi::Runtime& rt, const jsi::Value& value) {
320
335
  return CallResult{0, std::vector<uint8_t>(text.begin(), text.end())};
321
336
  }
322
337
 
323
- /// `ShareStore.keepList(): Promise<number[] | null | undefined>`. Encodes the
324
- /// resolved value as the wire's `Option<Vec<u32>>` JSON: `null` for
325
- /// `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`.
326
341
  ///
327
- /// Anything else, or an entry that is not an integer in `0..=4294967295`, is
328
- /// a backend failure: reading it as `null` would silently send an empty
329
- /// keepList, so helpers would keep every version instead of the list the
330
- /// application meant to send.
331
- CallResult toKeepListResult(jsi::Runtime& rt, const jsi::Value& value) {
332
- if (value.isNull() || value.isUndefined()) {
333
- return CallResult{0, {'n', 'u', 'l', 'l'}};
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()) {
346
+ return CallResult{kBackendFailure, {}};
334
347
  }
335
- if (!value.isObject() || !value.asObject(rt).isArray(rt)) {
348
+ double raw = value.asNumber();
349
+ if (!(raw >= 0 && raw <= 4294967295.0) || raw != static_cast<double>(static_cast<uint32_t>(raw))) {
336
350
  return CallResult{kBackendFailure, {}};
337
351
  }
338
- jsi::Array arr = value.asObject(rt).asArray(rt);
339
- size_t n = arr.size(rt);
340
- std::string text = "[";
341
- for (size_t i = 0; i < n; ++i) {
342
- jsi::Value entry = arr.getValueAtIndex(rt, i);
343
- if (!entry.isNumber()) {
344
- return CallResult{kBackendFailure, {}};
345
- }
346
- double version = entry.asNumber();
347
- if (!(version >= 0 && version <= 4294967295.0) || version != static_cast<double>(static_cast<uint32_t>(version))) {
348
- return CallResult{kBackendFailure, {}};
349
- }
350
- if (i != 0) text += ',';
351
- text += std::to_string(static_cast<uint32_t>(version));
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};
359
+ }
360
+
361
+ /// Reads the `refusal` property a `ShareStore.save`/`recordVerification`
362
+ /// throws, or rejects its promise with, to refuse the call — see
363
+ /// `shareStoreRefusal` in `src/types.ts`. Maps the wire string to the FFI
364
+ /// return code `library/src/interop/ffi/error.rs` names
365
+ /// `DEREC_SHARE_STORE_REFUSED_*`; a missing or unknown property is an
366
+ /// ordinary backend failure, never any other interpretation.
367
+ int32_t shareRefusalCode(jsi::Runtime& rt, const jsi::Value& value) {
368
+ if (!value.isObject()) {
369
+ return kBackendFailure;
352
370
  }
353
- text += ']';
354
- return CallResult{0, std::vector<uint8_t>(text.begin(), text.end())};
371
+ jsi::Object obj = value.asObject(rt);
372
+ if (!obj.hasProperty(rt, "refusal")) {
373
+ return kBackendFailure;
374
+ }
375
+ jsi::Value refusal = obj.getProperty(rt, "refusal");
376
+ if (!refusal.isString()) {
377
+ return kBackendFailure;
378
+ }
379
+ std::string reason = refusal.asString(rt).utf8(rt);
380
+ if (reason == "too_frequent") return DEREC_SHARE_STORE_REFUSED_TOO_FREQUENT;
381
+ if (reason == "size_limit_exceeded") return DEREC_SHARE_STORE_REFUSED_SIZE_LIMIT_EXCEEDED;
382
+ if (reason == "rejected") return DEREC_SHARE_STORE_REFUSED_REJECTED;
383
+ return kBackendFailure;
384
+ }
385
+
386
+ /// `ResultConverter` form of `shareRefusalCode`, passed as `ShareStore.save`/
387
+ /// `recordVerification`'s `settleFromPromise` error converter and used
388
+ /// directly on a synchronous throw.
389
+ CallResult toShareRefusalResult(jsi::Runtime& rt, const jsi::Value& value) {
390
+ return CallResult{shareRefusalCode(rt, value), {}};
355
391
  }
356
392
 
357
393
  /// `UserSecretStore.loadLatest(): Promise<UserSecrets | null | undefined>`.
@@ -811,13 +847,59 @@ extern "C" int32_t shareStoreSave(void* userData, uint64_t secretId, uint64_t ch
811
847
  jsi::Value(rt, jsi::String::createFromUtf8(rt, decoded.secretId)));
812
848
  shareObj.setProperty(rt, "version", jsi::Value(static_cast<int>(decoded.version)));
813
849
  shareObj.setProperty(rt, "bytes", toUint8ArrayVal(rt, decoded.bytes));
814
- jsi::Value promise = method.callWithThis(rt, *store, idVal(rt, secretId), idVal(rt, channelId),
815
- jsi::Value(rt, shareObj));
816
- keepAlive->settleFromPromise(rt, std::move(promise), std::move(settle), toVoidResult);
850
+ if (decoded.subshares) {
851
+ shareObj.setProperty(rt, "subshares", jsi::Value(static_cast<double>(*decoded.subshares)));
852
+ }
853
+ if (decoded.threshold) {
854
+ shareObj.setProperty(rt, "threshold", jsi::Value(static_cast<double>(*decoded.threshold)));
855
+ }
856
+ // A refusal thrown synchronously (rather than via a rejected promise)
857
+ // never reaches `settleFromPromise`'s `onErr`, so it is read here,
858
+ // before it would otherwise fall into `JsCallbackBridge::callSync`'s
859
+ // generic backend-failure catch.
860
+ try {
861
+ jsi::Value promise = method.callWithThis(rt, *store, idVal(rt, secretId), idVal(rt, channelId),
862
+ jsi::Value(rt, shareObj));
863
+ keepAlive->settleFromPromise(rt, std::move(promise), settle, toVoidResult, toShareRefusalResult);
864
+ } catch (jsi::JSError& e) {
865
+ settle(toShareRefusalResult(rt, e.value()));
866
+ }
817
867
  });
818
868
  return result.code;
819
869
  }
820
870
 
871
+ /// `ShareStore.recordVerification(secretId, channelId, version) -> void`
872
+ ///
873
+ /// Called once per accepted verification challenge, after the challenged
874
+ /// share is found and before the helper answers — see
875
+ /// `DeRecShareStore::record_verification` on the Rust side. A refusal
876
+ /// (thrown, or a rejected promise, tagged with `shareStoreRefusal`'s
877
+ /// `refusal` property) maps to the matching FFI return code exactly as
878
+ /// `ShareStore.save` does; any other failure is an ordinary backend failure.
879
+ extern "C" int32_t shareStoreRecordVerification(void* userData, uint64_t secretId, uint64_t channelId,
880
+ uint32_t version) {
881
+ auto* self = static_cast<StoreBindings*>(userData);
882
+ // Kept alive past this call so the lambda handed to `callSync` — which the
883
+ // JavaScript CallInvoker's queue may still be holding after this object's
884
+ // owner has released its own reference — has somewhere safe to run.
885
+ auto keepAlive = self->shared_from_this();
886
+ CallResult result = keepAlive->bridge().callSync(
887
+ [keepAlive, secretId, channelId, version](std::function<void(CallResult)> settle) {
888
+ jsi::Runtime& rt = keepAlive->runtime();
889
+ auto store = keepAlive->shareStore();
890
+ auto method = store->getPropertyAsFunction(rt, "recordVerification");
891
+ try {
892
+ jsi::Value promise = method.callWithThis(rt, *store, idVal(rt, secretId), idVal(rt, channelId),
893
+ jsi::Value(static_cast<double>(version)));
894
+ keepAlive->settleFromPromise(rt, std::move(promise), settle, toVoidResult,
895
+ toShareRefusalResult);
896
+ } catch (jsi::JSError& e) {
897
+ settle(toShareRefusalResult(rt, e.value()));
898
+ }
899
+ });
900
+ return result.code;
901
+ }
902
+
821
903
  /// `ShareStore.removeChannel(secretId, channelId) -> void`
822
904
  extern "C" int32_t shareStoreRemoveChannel(void* userData, uint64_t secretId, uint64_t channelId) {
823
905
  auto* self = static_cast<StoreBindings*>(userData);
@@ -858,29 +940,28 @@ extern "C" int32_t shareStoreRemoveVersions(void* userData, uint64_t secretId, u
858
940
  return result.code;
859
941
  }
860
942
 
861
- /// `ShareStore.keepList(secretId, version) -> number[] | null`
862
- extern "C" int32_t shareStoreKeepList(void* userData, uint64_t secretId, uint32_t version, uint8_t** outPtr,
863
- 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) {
864
946
  auto* self = static_cast<StoreBindings*>(userData);
865
947
  auto keepAlive = self->shared_from_this();
866
948
  CallResult result =
867
949
  keepAlive->bridge().callSync([keepAlive, secretId, version](std::function<void(CallResult)> settle) {
868
950
  jsi::Runtime& rt = keepAlive->runtime();
869
951
  auto store = keepAlive->shareStore();
870
- auto method = store->getPropertyAsFunction(rt, "keepList");
952
+ auto method = store->getPropertyAsFunction(rt, "keepVersion");
871
953
  jsi::Value promise =
872
954
  method.callWithThis(rt, *store, idVal(rt, secretId), jsi::Value(static_cast<double>(version)));
873
- keepAlive->settleFromPromise(rt, std::move(promise), std::move(settle), toKeepListResult);
955
+ keepAlive->settleFromPromise(rt, std::move(promise), std::move(settle), toKeepVersionResult);
874
956
  });
875
- if (result.code == 0) {
876
- if (!writeOut(result.bytes, outPtr, outLen)) {
877
- return kBackendFailure;
878
- }
879
- } else {
880
- *outPtr = nullptr;
881
- *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;
882
962
  }
883
- return result.code;
963
+ *outVersion = 0;
964
+ return result.code == 0 ? kBackendFailure : result.code;
884
965
  }
885
966
 
886
967
  /// `UserSecretStore.loadLatest(secretId) -> UserSecrets | null`
@@ -1110,7 +1191,7 @@ StoreBindings::StoreBindings(jsi::Runtime& rt, JsCallbackBridge& bridge,
1110
1191
 
1111
1192
  void StoreBindings::settleFromPromise(jsi::Runtime& rt, jsi::Value value,
1112
1193
  std::function<void(CallResult)> settle,
1113
- ResultConverter convert) {
1194
+ ResultConverter convert, ResultConverter convertError) {
1114
1195
  // A store may legitimately return a plain value; only route through
1115
1196
  // `then` when the result actually is a thenable.
1116
1197
  if (!value.isObject()) {
@@ -1150,13 +1231,16 @@ void StoreBindings::settleFromPromise(jsi::Runtime& rt, jsi::Value value,
1150
1231
 
1151
1232
  auto onErr = jsi::Function::createFromHostFunction(
1152
1233
  rt, jsi::PropNameID::forAscii(rt, "onErr"), 1,
1153
- [shared](jsi::Runtime&, const jsi::Value&, const jsi::Value*, size_t) -> jsi::Value {
1234
+ [shared, convertError](jsi::Runtime& rt, const jsi::Value&, const jsi::Value* args,
1235
+ size_t count) -> jsi::Value {
1154
1236
  try {
1155
- (*shared)(CallResult{kBackendFailure, {}});
1237
+ CallResult result = convertError != nullptr
1238
+ ? (count > 0 ? convertError(rt, args[0])
1239
+ : convertError(rt, jsi::Value::undefined()))
1240
+ : CallResult{kBackendFailure, {}};
1241
+ (*shared)(std::move(result));
1156
1242
  } catch (...) {
1157
- // `settle` on an already-resolved slot is a documented no-op, but
1158
- // guard uniformly with `onOk` in case a future `settle`
1159
- // implementation grows a fallible step.
1243
+ (*shared)(CallResult{kBackendFailure, {}});
1160
1244
  }
1161
1245
  return jsi::Value::undefined();
1162
1246
  });
@@ -1198,16 +1282,17 @@ std::shared_ptr<StoreBindings> StoreBindings::create(jsi::Runtime& rt, jsi::Obje
1198
1282
  storeFreeBuffer, // free_buffer
1199
1283
  };
1200
1284
  bindings->shareCallbacks_ = ShareStoreCallbacks{
1201
- self, // user_data
1202
- shareStoreLoad, // load
1203
- shareStoreLoadMany, // load_many
1204
- shareStoreLoadAll, // load_all
1205
- shareStoreLatestVersion, // latest_version
1206
- shareStoreSave, // save
1207
- shareStoreRemoveChannel, // remove_channel
1208
- shareStoreRemoveVersions, // remove_versions
1209
- shareStoreKeepList, // keep_list
1210
- storeFreeBuffer, // free_buffer
1285
+ self, // user_data
1286
+ shareStoreLoad, // load
1287
+ shareStoreLoadMany, // load_many
1288
+ shareStoreLoadAll, // load_all
1289
+ shareStoreLatestVersion, // latest_version
1290
+ shareStoreSave, // save
1291
+ shareStoreRemoveChannel, // remove_channel
1292
+ shareStoreRemoveVersions, // remove_versions
1293
+ shareStoreKeepVersion, // keep_version
1294
+ shareStoreRecordVerification, // record_verification
1295
+ storeFreeBuffer, // free_buffer
1211
1296
  };
1212
1297
  bindings->userSecretCallbacks_ = UserSecretStoreCallbacks{
1213
1298
  self, // user_data
@@ -1254,7 +1339,9 @@ std::shared_ptr<StoreBindings> StoreBindings::create(jsi::Runtime& rt, jsi::Obje
1254
1339
  requireField(rt, bindings->shareCallbacks_.save, "ShareStoreCallbacks.save");
1255
1340
  requireField(rt, bindings->shareCallbacks_.remove_channel, "ShareStoreCallbacks.remove_channel");
1256
1341
  requireField(rt, bindings->shareCallbacks_.remove_versions, "ShareStoreCallbacks.remove_versions");
1257
- requireField(rt, bindings->shareCallbacks_.keep_list, "ShareStoreCallbacks.keep_list");
1342
+ requireField(rt, bindings->shareCallbacks_.keep_version, "ShareStoreCallbacks.keep_version");
1343
+ requireField(rt, bindings->shareCallbacks_.record_verification,
1344
+ "ShareStoreCallbacks.record_verification");
1258
1345
  requireField(rt, bindings->shareCallbacks_.free_buffer, "ShareStoreCallbacks.free_buffer");
1259
1346
 
1260
1347
  requireField(rt, bindings->userSecretCallbacks_.user_data, "UserSecretStoreCallbacks.user_data");