@dynamic-labs/legacy-react-native-extension 5.3.2 → 5.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -40,9 +40,11 @@ class KeyStoreKeyManager {
40
40
 
41
41
  fun generateKeyPair(alias: String): String {
42
42
 
43
- // Defensive: if alias somehow exists, clean it up before generating.
44
- // Matches iOS Secure Enclave's permissive overwrite semantics and keeps
45
- // the function single-call atomic so callers don't need to pre-delete.
43
+ // Replace any existing key so the alias holds exactly one key and
44
+ // callers never have to pre-delete. iOS does the same explicitly in
45
+ // `SecureEnclaveKeyManager.generateKeyPair` — there the keychain would
46
+ // otherwise keep several keys under one application tag and resolve
47
+ // lookups to an arbitrary one.
46
48
  if (hasKey(alias)) {
47
49
  deleteKey(alias)
48
50
  }
@@ -109,6 +111,30 @@ class KeyStoreKeyManager {
109
111
  keyStore.deleteEntry(alias)
110
112
  }
111
113
 
114
+ /**
115
+ * Reports whether the key under [alias] is the one whose public key is
116
+ * [expectedPublicKey]. Deletes nothing.
117
+ *
118
+ * The iOS counterpart genuinely prunes, because there an application tag can
119
+ * hold several Secure Enclave keys and a lookup resolves to an unspecified
120
+ * one of them. A KeyStore alias holds at most one key, so there is nothing
121
+ * ambiguous to resolve here — this only answers the question, letting the
122
+ * caller treat both platforms uniformly. A non-matching key is deliberately
123
+ * left in place: it may belong to a live session, and the caller has no way
124
+ * to know that from here.
125
+ *
126
+ * [expectedPublicKey] is accepted as base64url or hex, compressed (33 bytes)
127
+ * or uncompressed (65 bytes) SEC1; both sides are normalised to compressed
128
+ * form, which is the only representation in which two encodings of the same
129
+ * key compare equal.
130
+ */
131
+ fun matchesPublicKey(alias: String, expectedPublicKey: String): Boolean {
132
+ val expected = normalizedCompressedPublicKey(expectedPublicKey) ?: return false
133
+ val actual = getPublicKey(alias)?.let { normalizedCompressedPublicKey(it) } ?: return false
134
+
135
+ return expected.contentEquals(actual)
136
+ }
137
+
112
138
  // region Private helpers
113
139
 
114
140
  private fun loadKeyStore(): KeyStore {
@@ -139,6 +165,48 @@ class KeyStoreKeyManager {
139
165
  )
140
166
  }
141
167
 
168
+ /**
169
+ * Decodes a public key given as base64url or hex and returns it in
170
+ * compressed SEC1 form (33 bytes: 02/03 || x). Keep in sync with
171
+ * `SecureEnclaveKeyManager.normalizedCompressedPublicKey` on iOS.
172
+ */
173
+ private fun normalizedCompressedPublicKey(encoded: String): ByteArray? {
174
+ val candidates = listOf(
175
+ runCatching { base64urlDecode(encoded) }.getOrNull(),
176
+ hexDecode(encoded),
177
+ )
178
+
179
+ return candidates.firstNotNullOfOrNull { it?.let(::compressSec1PublicKey) }
180
+ }
181
+
182
+ /**
183
+ * Compresses an uncompressed SEC1 point (04 || x || y) to 02/03 || x, the
184
+ * prefix encoding the parity of y. Already-compressed input is returned
185
+ * unchanged.
186
+ */
187
+ private fun compressSec1PublicKey(data: ByteArray): ByteArray? {
188
+ if (data.size == 33 && (data[0] == 0x02.toByte() || data[0] == 0x03.toByte())) {
189
+ return data
190
+ }
191
+ if (data.size != 65 || data[0] != 0x04.toByte()) {
192
+ return null
193
+ }
194
+
195
+ val prefix = if (data[64].toInt() % 2 == 0) 0x02.toByte() else 0x03.toByte()
196
+
197
+ return byteArrayOf(prefix) + data.copyOfRange(1, 33)
198
+ }
199
+
200
+ private fun hexDecode(input: String): ByteArray? {
201
+ if (input.isEmpty() || input.length % 2 != 0) return null
202
+
203
+ return runCatching {
204
+ ByteArray(input.length / 2) { index ->
205
+ input.substring(index * 2, index * 2 + 2).toInt(16).toByte()
206
+ }
207
+ }.getOrNull()
208
+ }
209
+
142
210
  companion object {
143
211
  private const val ANDROID_KEYSTORE = "AndroidKeyStore"
144
212
 
@@ -67,5 +67,13 @@ class KeychainModule : Module() {
67
67
  promise.reject("ERR_KEYCHAIN", "Failed to delete key: ${e.message}", e)
68
68
  }
69
69
  }
70
+
71
+ AsyncFunction("pruneToPublicKey") { key: String, publicKey: String, promise: Promise ->
72
+ try {
73
+ promise.resolve(keyManager.matchesPublicKey(key, publicKey))
74
+ } catch (e: Exception) {
75
+ promise.reject("ERR_KEYCHAIN", "Failed to prune keys: ${e.message}", e)
76
+ }
77
+ }
70
78
  }
71
79
  }
package/index.cjs CHANGED
@@ -35,7 +35,7 @@ function _interopNamespace(e) {
35
35
  return Object.freeze(n);
36
36
  }
37
37
 
38
- var version = "5.3.2";
38
+ var version = "5.5.0";
39
39
 
40
40
  function _extends() {
41
41
  return _extends = Object.assign ? Object.assign.bind() : function (n) {
@@ -560,6 +560,7 @@ const getKeychain = () => {
560
560
  getPublicKey: () => Promise.reject(keychainUnavailableError),
561
561
  hasKey: () => Promise.reject(keychainUnavailableError),
562
562
  isAvailable: () => Promise.resolve(false),
563
+ pruneToPublicKey: () => Promise.reject(keychainUnavailableError),
563
564
  sign: () => Promise.reject(keychainUnavailableError)
564
565
  };
565
566
  return unavailableKeychain;
@@ -795,6 +796,184 @@ const setupPlatformHandler = core => {
795
796
  });
796
797
  };
797
798
 
799
+ /**
800
+ * expo-secure-store is an OPTIONAL peer dependency (see package.json) —
801
+ * most apps never had it and shouldn't have to install it. `require`
802
+ * inside a `try`/`catch` — not a static `import` — is Metro's own
803
+ * documented mechanism for this: `collectDependencies.js`'s
804
+ * `isOptionalDependency` recognizes a `require()` call sitting directly in
805
+ * a try block and marks that dependency `optional`, so an unresolvable
806
+ * module there does not fail the bundle — it only throws (here, caught) if
807
+ * actually reached at runtime. This needs `allowOptionalDependencies`
808
+ * enabled in the consumer's Metro transformer config; `@expo/metro-config`
809
+ * (what every consumer of this package uses, since expo-linking/
810
+ * expo-web-browser/expo-modules-core are already required peers) turns it
811
+ * on by default. Cached after the first call: a host app either has it
812
+ * installed or it doesn't, for the lifetime of the process.
813
+ */
814
+ let cachedLegacyStore;
815
+ const getLegacyExpoSecureStore = () => {
816
+ if (cachedLegacyStore === undefined) {
817
+ try {
818
+ // Deliberately not installed anywhere in this workspace, even for
819
+ // lint (see doc comment above): a root-only install still hoists into
820
+ // every app's node_modules, and expo-modules-autolinking picks it up
821
+ // from there regardless of whether that app declares it — forcing an
822
+ // unwanted native rebuild on every consumer.
823
+ // eslint-disable-next-line @typescript-eslint/no-var-requires, global-require, import/no-extraneous-dependencies
824
+ cachedLegacyStore = require('expo-secure-store');
825
+ } catch (_a) {
826
+ cachedLegacyStore = null;
827
+ }
828
+ }
829
+ return cachedLegacyStore;
830
+ };
831
+ /**
832
+ * Reads a value written by a previous SDK version into the legacy
833
+ * expo-secure-store backend. Both a missing module and a read failure
834
+ * (e.g. Android Keystore decryption error after a backup restore) are
835
+ * treated as "no legacy value" — the entry is unrecoverable either way, so
836
+ * the caller falls through to a clean miss instead of failing the whole
837
+ * request.
838
+ */
839
+ const readLegacyItem = key => __awaiter(void 0, void 0, void 0, function* () {
840
+ const legacyStore = getLegacyExpoSecureStore();
841
+ if (!legacyStore) return null;
842
+ try {
843
+ return yield legacyStore.getItemAsync(key);
844
+ } catch (_a) {
845
+ return null;
846
+ }
847
+ });
848
+ /**
849
+ * Best-effort delete of a legacy expo-secure-store entry. Logged, not
850
+ * thrown: the legacy backend is optional, so its absence or failure must
851
+ * not fail an otherwise-successful keychain operation. The tradeoff is
852
+ * that a persistently-failing legacy delete can leave a stale entry that
853
+ * resurrects through `getItem`'s migration path on a later boot — accepted
854
+ * because this only affects the narrow population still holding data from
855
+ * before the keychain switch.
856
+ */
857
+ const deleteLegacyItem = key => __awaiter(void 0, void 0, void 0, function* () {
858
+ const legacyStore = getLegacyExpoSecureStore();
859
+ if (!legacyStore) return;
860
+ try {
861
+ yield legacyStore.deleteItemAsync(key);
862
+ } catch (error) {
863
+ logger.warn('[legacy-expo-secure-store-recovery] failed to delete legacy entry', {
864
+ error,
865
+ key
866
+ });
867
+ }
868
+ });
869
+ /**
870
+ * Serializes storage operations per key so a lazy migration write-back
871
+ * (triggered by a read) can never interleave with a concurrent write or
872
+ * delete for the same key — e.g. a read that promotes a stale legacy value
873
+ * must not clobber a write that lands in between the read's keychain check
874
+ * and its migration write. Operations on different keys still run fully
875
+ * concurrently.
876
+ */
877
+ const createKeyedOperationQueue = () => {
878
+ const tailByKey = new Map();
879
+ const queueOperationForKey = (key, operation) => {
880
+ var _a;
881
+ const tail = (_a = tailByKey.get(key)) !== null && _a !== void 0 ? _a : Promise.resolve();
882
+ const result = tail.then(operation);
883
+ // Chain the next operation after this one, swallowing the outcome so
884
+ // a rejection doesn't break the chain for subsequent operations.
885
+ const settled = result.then(() => undefined, () => undefined);
886
+ tailByKey.set(key, settled);
887
+ // Drop the tail entry once it settles if no newer operation replaced
888
+ // it, so the map doesn't retain an entry per key forever.
889
+ settled.then(() => {
890
+ if (tailByKey.get(key) === settled) {
891
+ tailByKey.delete(key);
892
+ }
893
+ });
894
+ return result;
895
+ };
896
+ return {
897
+ queueOperationForKey
898
+ };
899
+ };
900
+ /**
901
+ * Decorates the react-native-keychain-backed storage bridge with recovery
902
+ * of sessions persisted by SDK versions that stored secure values in
903
+ * expo-secure-store, before the bridge switched to react-native-keychain.
904
+ *
905
+ * expo-secure-store and react-native-keychain are two separate,
906
+ * mutually-unreadable storage backends: even though both ultimately sit on
907
+ * top of the platform Keychain/Keystore, each library manages its own
908
+ * service/account naming (iOS) and its own encryption key (Android). An
909
+ * app that upgrades straight from an old SDK version has its session
910
+ * stranded in expo-secure-store, invisible to react-native-keychain,
911
+ * unless something explicitly reads the old backend's own API.
912
+ *
913
+ * expo-secure-store stays an OPTIONAL peer dependency — see
914
+ * `getLegacyExpoSecureStore`'s doc comment for how the lazy require stays
915
+ * Metro-bundle-safe without it. Recovery itself never rejects and never
916
+ * blocks: a missing/failed legacy read or delete is treated as a clean
917
+ * miss (see `readLegacyItem` and `deleteLegacyItem`).
918
+ *
919
+ * Every piece of state and behavior this migration needs is self-contained
920
+ * in this one factory: delete this file (and the rest of
921
+ * `legacyExpoSecureStoreRecovery/`), drop the `expo-secure-store` optional
922
+ * peer dependency from package.json, and replace the call to
923
+ * `withLegacyExpoSecureStoreRecovery` in `setupStorageHandler` with
924
+ * `{ getItem: getKeychainItem, setItem: setKeychainItem, deleteItem: deleteKeychainItem }`
925
+ * once this migration window has closed.
926
+ */
927
+ const withLegacyExpoSecureStoreRecovery = ({
928
+ deleteKeychainItem,
929
+ getKeychainItem,
930
+ setKeychainItem
931
+ }) => {
932
+ const {
933
+ queueOperationForKey
934
+ } = createKeyedOperationQueue();
935
+ return {
936
+ deleteItem: key => queueOperationForKey(key, () => __awaiter(void 0, void 0, void 0, function* () {
937
+ // Both backends must be attempted even if one fails, or a
938
+ // surviving copy would resurrect a value the SDK believes is gone
939
+ // (e.g. a stale session after logout) — either straight from the
940
+ // keychain, or via getItem's legacy-migration fallback. Only the
941
+ // keychain outcome is surfaced: deleteLegacyItem already logs its
942
+ // own failures instead of rejecting (see its doc comment).
943
+ const [keychainResult] = yield Promise.allSettled([deleteKeychainItem(key), deleteLegacyItem(key)]);
944
+ if (keychainResult.status === 'rejected') {
945
+ throw keychainResult.reason;
946
+ }
947
+ })),
948
+ getItem: key => queueOperationForKey(key, () => __awaiter(void 0, void 0, void 0, function* () {
949
+ const stored = yield getKeychainItem(key);
950
+ if (stored !== null) return stored;
951
+ const legacyValue = yield readLegacyItem(key);
952
+ if (legacyValue === null) return null;
953
+ // Lazy migration is best-effort: promote the legacy value into the
954
+ // keychain so the next read is a direct hit, then drop the legacy
955
+ // copy. A keychain write failure must not fail this read when a
956
+ // valid legacy value is already in hand — the next miss simply
957
+ // re-attempts the migration.
958
+ try {
959
+ yield setKeychainItem(key, legacyValue);
960
+ yield deleteLegacyItem(key);
961
+ } catch (_a) {
962
+ // ignore migration failures and still return the legacy value
963
+ }
964
+ return legacyValue;
965
+ })),
966
+ setItem: (key, data) => queueOperationForKey(key, () => __awaiter(void 0, void 0, void 0, function* () {
967
+ yield setKeychainItem(key, data);
968
+ // Drop any pre-migration legacy copy left over from a previous SDK
969
+ // version — best-effort, so a delete hiccup doesn't fail the
970
+ // write. Otherwise, if the fresh keychain entry were ever lost, a
971
+ // stale legacy value could resurrect through getItem's fallback.
972
+ yield deleteLegacyItem(key);
973
+ }))
974
+ };
975
+ };
976
+
798
977
  const REACT_NATIVE_KEYCHAIN_NOT_AVAILABLE_DOCS_URL = 'https://docs.dynamic.xyz/overview/migrations/react-native-expo-secure-store-to-keychain';
799
978
  const REACT_NATIVE_KEYCHAIN_NOT_AVAILABLE_MESSAGE = 'react-native-keychain native module is not available. ' + 'Install and link the peer dependency, then rebuild the native app. ' + `See ${REACT_NATIVE_KEYCHAIN_NOT_AVAILABLE_DOCS_URL}`;
800
979
  const assertValidSource = source => {
@@ -807,27 +986,51 @@ const assertReactNativeKeychainAvailable = () => {
807
986
  throw new Error(REACT_NATIVE_KEYCHAIN_NOT_AVAILABLE_MESSAGE);
808
987
  }
809
988
  };
989
+ /**
990
+ * Answers the webview-controller's secure-storage bridge requests with
991
+ * react-native-keychain (iOS Keychain / Android Keystore-backed storage),
992
+ * which has no practical value-size limit — values of any size are stored
993
+ * as one direct entry.
994
+ *
995
+ * A session persisted by an SDK version predating the keychain switch is
996
+ * recovered on a keychain miss via `withLegacyExpoSecureStoreRecovery`
997
+ * instead of signing the app out on upgrade. See that module's doc comment
998
+ * for how to retire the migration once it's no longer needed.
999
+ */
810
1000
  const setupStorageHandler = core => {
811
1001
  assertReactNativeKeychainAvailable();
812
1002
  const storageRequestChannel = messageTransport.createRequestChannel(core.messageTransport);
1003
+ const recoverable = withLegacyExpoSecureStoreRecovery({
1004
+ deleteKeychainItem: key => __awaiter(void 0, void 0, void 0, function* () {
1005
+ yield reactNativeKeychain.resetGenericPassword({
1006
+ service: key
1007
+ });
1008
+ }),
1009
+ getKeychainItem: key => __awaiter(void 0, void 0, void 0, function* () {
1010
+ const stored = yield reactNativeKeychain.getGenericPassword({
1011
+ service: key
1012
+ });
1013
+ return stored ? stored.password : null;
1014
+ }),
1015
+ setKeychainItem: (key, data) => __awaiter(void 0, void 0, void 0, function* () {
1016
+ yield reactNativeKeychain.setGenericPassword(key, data, {
1017
+ service: key
1018
+ });
1019
+ })
1020
+ });
813
1021
  storageRequestChannel.handle('getItem', _a => __awaiter(void 0, [_a], void 0, function* ({
814
1022
  key,
815
1023
  source
816
1024
  }) {
817
1025
  assertValidSource(source);
818
- const stored = yield reactNativeKeychain.getGenericPassword({
819
- service: key
820
- });
821
- return stored ? stored.password : null;
1026
+ return recoverable.getItem(key);
822
1027
  }));
823
1028
  storageRequestChannel.handle('deleteItem', _b => __awaiter(void 0, [_b], void 0, function* ({
824
1029
  key,
825
1030
  source
826
1031
  }) {
827
1032
  assertValidSource(source);
828
- yield reactNativeKeychain.resetGenericPassword({
829
- service: key
830
- });
1033
+ yield recoverable.deleteItem(key);
831
1034
  }));
832
1035
  storageRequestChannel.handle('setItem', _c => __awaiter(void 0, [_c], void 0, function* ({
833
1036
  key,
@@ -835,9 +1038,7 @@ const setupStorageHandler = core => {
835
1038
  source
836
1039
  }) {
837
1040
  assertValidSource(source);
838
- yield reactNativeKeychain.setGenericPassword(key, data, {
839
- service: key
840
- });
1041
+ yield recoverable.setItem(key, data);
841
1042
  }));
842
1043
  };
843
1044
 
@@ -904,6 +1105,19 @@ const setupKeychainHandler = core => {
904
1105
  }) {
905
1106
  return keychain.deleteKey(key);
906
1107
  }));
1108
+ keychainRequestChannel.handle('keychain_pruneToPublicKey', _f => __awaiter(void 0, [_f], void 0, function* ({
1109
+ key,
1110
+ publicKey
1111
+ }) {
1112
+ // Absent on a native binary that predates the operation (an OTA JS
1113
+ // update can run on one). Rejecting is the same answer the webview
1114
+ // already handles for any host without it: the session is served
1115
+ // unchanged, only the ambiguity is left unresolved.
1116
+ if (!keychain.pruneToPublicKey) {
1117
+ throw new Error('keychain_pruneToPublicKey is not available in this native build');
1118
+ }
1119
+ return keychain.pruneToPublicKey(key, publicKey);
1120
+ }));
907
1121
  };
908
1122
 
909
1123
  const defaultWebviewUrl = `https://webview.dynamicauth.com/${version}`;