@oxyhq/core 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (277) hide show
  1. package/README.md +50 -0
  2. package/dist/cjs/AuthManager.js +361 -0
  3. package/dist/cjs/CrossDomainAuth.js +258 -0
  4. package/dist/cjs/HttpService.js +618 -0
  5. package/dist/cjs/OxyServices.base.js +263 -0
  6. package/dist/cjs/OxyServices.errors.js +22 -0
  7. package/dist/cjs/OxyServices.js +63 -0
  8. package/dist/cjs/constants/version.js +16 -0
  9. package/dist/cjs/crypto/index.js +20 -0
  10. package/dist/cjs/crypto/keyManager.js +887 -0
  11. package/dist/cjs/crypto/polyfill.js +64 -0
  12. package/dist/cjs/crypto/recoveryPhrase.js +169 -0
  13. package/dist/cjs/crypto/signatureService.js +296 -0
  14. package/dist/cjs/i18n/index.js +73 -0
  15. package/dist/cjs/i18n/locales/ar-SA.json +120 -0
  16. package/dist/cjs/i18n/locales/ca-ES.json +120 -0
  17. package/dist/cjs/i18n/locales/de-DE.json +120 -0
  18. package/dist/cjs/i18n/locales/en-US.json +956 -0
  19. package/dist/cjs/i18n/locales/es-ES.json +944 -0
  20. package/dist/cjs/i18n/locales/fr-FR.json +120 -0
  21. package/dist/cjs/i18n/locales/it-IT.json +120 -0
  22. package/dist/cjs/i18n/locales/ja-JP.json +119 -0
  23. package/dist/cjs/i18n/locales/ko-KR.json +120 -0
  24. package/dist/cjs/i18n/locales/locales/ar-SA.json +120 -0
  25. package/dist/cjs/i18n/locales/locales/ca-ES.json +120 -0
  26. package/dist/cjs/i18n/locales/locales/de-DE.json +120 -0
  27. package/dist/cjs/i18n/locales/locales/en-US.json +956 -0
  28. package/dist/cjs/i18n/locales/locales/es-ES.json +944 -0
  29. package/dist/cjs/i18n/locales/locales/fr-FR.json +120 -0
  30. package/dist/cjs/i18n/locales/locales/it-IT.json +120 -0
  31. package/dist/cjs/i18n/locales/locales/ja-JP.json +119 -0
  32. package/dist/cjs/i18n/locales/locales/ko-KR.json +120 -0
  33. package/dist/cjs/i18n/locales/locales/pt-PT.json +120 -0
  34. package/dist/cjs/i18n/locales/locales/zh-CN.json +120 -0
  35. package/dist/cjs/i18n/locales/pt-PT.json +120 -0
  36. package/dist/cjs/i18n/locales/zh-CN.json +120 -0
  37. package/dist/cjs/index.js +153 -0
  38. package/dist/cjs/mixins/OxyServices.analytics.js +49 -0
  39. package/dist/cjs/mixins/OxyServices.assets.js +380 -0
  40. package/dist/cjs/mixins/OxyServices.auth.js +259 -0
  41. package/dist/cjs/mixins/OxyServices.developer.js +97 -0
  42. package/dist/cjs/mixins/OxyServices.devices.js +116 -0
  43. package/dist/cjs/mixins/OxyServices.features.js +309 -0
  44. package/dist/cjs/mixins/OxyServices.fedcm.js +435 -0
  45. package/dist/cjs/mixins/OxyServices.karma.js +108 -0
  46. package/dist/cjs/mixins/OxyServices.language.js +154 -0
  47. package/dist/cjs/mixins/OxyServices.location.js +43 -0
  48. package/dist/cjs/mixins/OxyServices.payment.js +158 -0
  49. package/dist/cjs/mixins/OxyServices.popup.js +371 -0
  50. package/dist/cjs/mixins/OxyServices.privacy.js +162 -0
  51. package/dist/cjs/mixins/OxyServices.redirect.js +345 -0
  52. package/dist/cjs/mixins/OxyServices.security.js +81 -0
  53. package/dist/cjs/mixins/OxyServices.user.js +355 -0
  54. package/dist/cjs/mixins/OxyServices.utility.js +156 -0
  55. package/dist/cjs/mixins/index.js +79 -0
  56. package/dist/cjs/mixins/mixinHelpers.js +53 -0
  57. package/dist/cjs/models/interfaces.js +20 -0
  58. package/dist/cjs/models/session.js +2 -0
  59. package/dist/cjs/shared/index.js +70 -0
  60. package/dist/cjs/shared/utils/colorUtils.js +153 -0
  61. package/dist/cjs/shared/utils/debugUtils.js +73 -0
  62. package/dist/cjs/shared/utils/errorUtils.js +183 -0
  63. package/dist/cjs/shared/utils/index.js +49 -0
  64. package/dist/cjs/shared/utils/networkUtils.js +183 -0
  65. package/dist/cjs/shared/utils/themeUtils.js +106 -0
  66. package/dist/cjs/utils/apiUtils.js +61 -0
  67. package/dist/cjs/utils/asyncUtils.js +194 -0
  68. package/dist/cjs/utils/cache.js +226 -0
  69. package/dist/cjs/utils/deviceManager.js +205 -0
  70. package/dist/cjs/utils/errorUtils.js +154 -0
  71. package/dist/cjs/utils/index.js +26 -0
  72. package/dist/cjs/utils/languageUtils.js +165 -0
  73. package/dist/cjs/utils/loggerUtils.js +126 -0
  74. package/dist/cjs/utils/platform.js +144 -0
  75. package/dist/cjs/utils/requestUtils.js +209 -0
  76. package/dist/cjs/utils/sessionUtils.js +181 -0
  77. package/dist/cjs/utils/validationUtils.js +173 -0
  78. package/dist/esm/AuthManager.js +356 -0
  79. package/dist/esm/CrossDomainAuth.js +253 -0
  80. package/dist/esm/HttpService.js +614 -0
  81. package/dist/esm/OxyServices.base.js +259 -0
  82. package/dist/esm/OxyServices.errors.js +17 -0
  83. package/dist/esm/OxyServices.js +59 -0
  84. package/dist/esm/constants/version.js +13 -0
  85. package/dist/esm/crypto/index.js +13 -0
  86. package/dist/esm/crypto/keyManager.js +850 -0
  87. package/dist/esm/crypto/polyfill.js +61 -0
  88. package/dist/esm/crypto/recoveryPhrase.js +132 -0
  89. package/dist/esm/crypto/signatureService.js +259 -0
  90. package/dist/esm/i18n/index.js +69 -0
  91. package/dist/esm/i18n/locales/ar-SA.json +120 -0
  92. package/dist/esm/i18n/locales/ca-ES.json +120 -0
  93. package/dist/esm/i18n/locales/de-DE.json +120 -0
  94. package/dist/esm/i18n/locales/en-US.json +956 -0
  95. package/dist/esm/i18n/locales/es-ES.json +944 -0
  96. package/dist/esm/i18n/locales/fr-FR.json +120 -0
  97. package/dist/esm/i18n/locales/it-IT.json +120 -0
  98. package/dist/esm/i18n/locales/ja-JP.json +119 -0
  99. package/dist/esm/i18n/locales/ko-KR.json +120 -0
  100. package/dist/esm/i18n/locales/locales/ar-SA.json +120 -0
  101. package/dist/esm/i18n/locales/locales/ca-ES.json +120 -0
  102. package/dist/esm/i18n/locales/locales/de-DE.json +120 -0
  103. package/dist/esm/i18n/locales/locales/en-US.json +956 -0
  104. package/dist/esm/i18n/locales/locales/es-ES.json +944 -0
  105. package/dist/esm/i18n/locales/locales/fr-FR.json +120 -0
  106. package/dist/esm/i18n/locales/locales/it-IT.json +120 -0
  107. package/dist/esm/i18n/locales/locales/ja-JP.json +119 -0
  108. package/dist/esm/i18n/locales/locales/ko-KR.json +120 -0
  109. package/dist/esm/i18n/locales/locales/pt-PT.json +120 -0
  110. package/dist/esm/i18n/locales/locales/zh-CN.json +120 -0
  111. package/dist/esm/i18n/locales/pt-PT.json +120 -0
  112. package/dist/esm/i18n/locales/zh-CN.json +120 -0
  113. package/dist/esm/index.js +55 -0
  114. package/dist/esm/mixins/OxyServices.analytics.js +46 -0
  115. package/dist/esm/mixins/OxyServices.assets.js +377 -0
  116. package/dist/esm/mixins/OxyServices.auth.js +256 -0
  117. package/dist/esm/mixins/OxyServices.developer.js +94 -0
  118. package/dist/esm/mixins/OxyServices.devices.js +113 -0
  119. package/dist/esm/mixins/OxyServices.features.js +306 -0
  120. package/dist/esm/mixins/OxyServices.fedcm.js +433 -0
  121. package/dist/esm/mixins/OxyServices.karma.js +105 -0
  122. package/dist/esm/mixins/OxyServices.language.js +118 -0
  123. package/dist/esm/mixins/OxyServices.location.js +40 -0
  124. package/dist/esm/mixins/OxyServices.payment.js +155 -0
  125. package/dist/esm/mixins/OxyServices.popup.js +369 -0
  126. package/dist/esm/mixins/OxyServices.privacy.js +159 -0
  127. package/dist/esm/mixins/OxyServices.redirect.js +343 -0
  128. package/dist/esm/mixins/OxyServices.security.js +78 -0
  129. package/dist/esm/mixins/OxyServices.user.js +352 -0
  130. package/dist/esm/mixins/OxyServices.utility.js +153 -0
  131. package/dist/esm/mixins/index.js +76 -0
  132. package/dist/esm/mixins/mixinHelpers.js +48 -0
  133. package/dist/esm/models/interfaces.js +17 -0
  134. package/dist/esm/models/session.js +1 -0
  135. package/dist/esm/shared/index.js +31 -0
  136. package/dist/esm/shared/utils/colorUtils.js +143 -0
  137. package/dist/esm/shared/utils/debugUtils.js +65 -0
  138. package/dist/esm/shared/utils/errorUtils.js +170 -0
  139. package/dist/esm/shared/utils/index.js +15 -0
  140. package/dist/esm/shared/utils/networkUtils.js +173 -0
  141. package/dist/esm/shared/utils/themeUtils.js +98 -0
  142. package/dist/esm/utils/apiUtils.js +55 -0
  143. package/dist/esm/utils/asyncUtils.js +179 -0
  144. package/dist/esm/utils/cache.js +218 -0
  145. package/dist/esm/utils/deviceManager.js +168 -0
  146. package/dist/esm/utils/errorUtils.js +146 -0
  147. package/dist/esm/utils/index.js +7 -0
  148. package/dist/esm/utils/languageUtils.js +158 -0
  149. package/dist/esm/utils/loggerUtils.js +115 -0
  150. package/dist/esm/utils/platform.js +102 -0
  151. package/dist/esm/utils/requestUtils.js +203 -0
  152. package/dist/esm/utils/sessionUtils.js +171 -0
  153. package/dist/esm/utils/validationUtils.js +153 -0
  154. package/dist/types/AuthManager.d.ts +143 -0
  155. package/dist/types/CrossDomainAuth.d.ts +160 -0
  156. package/dist/types/HttpService.d.ts +163 -0
  157. package/dist/types/OxyServices.base.d.ts +126 -0
  158. package/dist/types/OxyServices.d.ts +81 -0
  159. package/dist/types/OxyServices.errors.d.ts +11 -0
  160. package/dist/types/constants/version.d.ts +13 -0
  161. package/dist/types/crypto/index.d.ts +11 -0
  162. package/dist/types/crypto/keyManager.d.ts +189 -0
  163. package/dist/types/crypto/polyfill.d.ts +11 -0
  164. package/dist/types/crypto/recoveryPhrase.d.ts +58 -0
  165. package/dist/types/crypto/signatureService.d.ts +86 -0
  166. package/dist/types/i18n/index.d.ts +3 -0
  167. package/dist/types/index.d.ts +50 -0
  168. package/dist/types/mixins/OxyServices.analytics.d.ts +66 -0
  169. package/dist/types/mixins/OxyServices.assets.d.ts +135 -0
  170. package/dist/types/mixins/OxyServices.auth.d.ts +186 -0
  171. package/dist/types/mixins/OxyServices.developer.d.ts +99 -0
  172. package/dist/types/mixins/OxyServices.devices.d.ts +96 -0
  173. package/dist/types/mixins/OxyServices.features.d.ts +228 -0
  174. package/dist/types/mixins/OxyServices.fedcm.d.ts +200 -0
  175. package/dist/types/mixins/OxyServices.karma.d.ts +85 -0
  176. package/dist/types/mixins/OxyServices.language.d.ts +81 -0
  177. package/dist/types/mixins/OxyServices.location.d.ts +64 -0
  178. package/dist/types/mixins/OxyServices.payment.d.ts +111 -0
  179. package/dist/types/mixins/OxyServices.popup.d.ts +205 -0
  180. package/dist/types/mixins/OxyServices.privacy.d.ts +122 -0
  181. package/dist/types/mixins/OxyServices.redirect.d.ts +245 -0
  182. package/dist/types/mixins/OxyServices.security.d.ts +78 -0
  183. package/dist/types/mixins/OxyServices.user.d.ts +182 -0
  184. package/dist/types/mixins/OxyServices.utility.d.ts +93 -0
  185. package/dist/types/mixins/index.d.ts +30 -0
  186. package/dist/types/mixins/mixinHelpers.d.ts +31 -0
  187. package/dist/types/models/interfaces.d.ts +415 -0
  188. package/dist/types/models/session.d.ts +27 -0
  189. package/dist/types/shared/index.d.ts +28 -0
  190. package/dist/types/shared/utils/colorUtils.d.ts +104 -0
  191. package/dist/types/shared/utils/debugUtils.d.ts +48 -0
  192. package/dist/types/shared/utils/errorUtils.d.ts +97 -0
  193. package/dist/types/shared/utils/index.d.ts +13 -0
  194. package/dist/types/shared/utils/networkUtils.d.ts +139 -0
  195. package/dist/types/shared/utils/themeUtils.d.ts +90 -0
  196. package/dist/types/utils/apiUtils.d.ts +53 -0
  197. package/dist/types/utils/asyncUtils.d.ts +58 -0
  198. package/dist/types/utils/cache.d.ts +127 -0
  199. package/dist/types/utils/deviceManager.d.ts +65 -0
  200. package/dist/types/utils/errorUtils.d.ts +46 -0
  201. package/dist/types/utils/index.d.ts +6 -0
  202. package/dist/types/utils/languageUtils.d.ts +37 -0
  203. package/dist/types/utils/loggerUtils.d.ts +48 -0
  204. package/dist/types/utils/platform.d.ts +40 -0
  205. package/dist/types/utils/requestUtils.d.ts +123 -0
  206. package/dist/types/utils/sessionUtils.d.ts +54 -0
  207. package/dist/types/utils/validationUtils.d.ts +85 -0
  208. package/package.json +84 -0
  209. package/src/AuthManager.ts +436 -0
  210. package/src/CrossDomainAuth.ts +307 -0
  211. package/src/HttpService.ts +752 -0
  212. package/src/OxyServices.base.ts +334 -0
  213. package/src/OxyServices.errors.ts +26 -0
  214. package/src/OxyServices.ts +129 -0
  215. package/src/constants/version.ts +15 -0
  216. package/src/crypto/index.ts +25 -0
  217. package/src/crypto/keyManager.ts +962 -0
  218. package/src/crypto/polyfill.ts +70 -0
  219. package/src/crypto/recoveryPhrase.ts +166 -0
  220. package/src/crypto/signatureService.ts +323 -0
  221. package/src/i18n/index.ts +75 -0
  222. package/src/i18n/locales/ar-SA.json +120 -0
  223. package/src/i18n/locales/ca-ES.json +120 -0
  224. package/src/i18n/locales/de-DE.json +120 -0
  225. package/src/i18n/locales/en-US.json +956 -0
  226. package/src/i18n/locales/es-ES.json +944 -0
  227. package/src/i18n/locales/fr-FR.json +120 -0
  228. package/src/i18n/locales/it-IT.json +120 -0
  229. package/src/i18n/locales/ja-JP.json +119 -0
  230. package/src/i18n/locales/ko-KR.json +120 -0
  231. package/src/i18n/locales/pt-PT.json +120 -0
  232. package/src/i18n/locales/zh-CN.json +120 -0
  233. package/src/index.ts +153 -0
  234. package/src/mixins/OxyServices.analytics.ts +53 -0
  235. package/src/mixins/OxyServices.assets.ts +412 -0
  236. package/src/mixins/OxyServices.auth.ts +358 -0
  237. package/src/mixins/OxyServices.developer.ts +114 -0
  238. package/src/mixins/OxyServices.devices.ts +119 -0
  239. package/src/mixins/OxyServices.features.ts +428 -0
  240. package/src/mixins/OxyServices.fedcm.ts +494 -0
  241. package/src/mixins/OxyServices.karma.ts +111 -0
  242. package/src/mixins/OxyServices.language.ts +127 -0
  243. package/src/mixins/OxyServices.location.ts +46 -0
  244. package/src/mixins/OxyServices.payment.ts +163 -0
  245. package/src/mixins/OxyServices.popup.ts +443 -0
  246. package/src/mixins/OxyServices.privacy.ts +182 -0
  247. package/src/mixins/OxyServices.redirect.ts +397 -0
  248. package/src/mixins/OxyServices.security.ts +103 -0
  249. package/src/mixins/OxyServices.user.ts +392 -0
  250. package/src/mixins/OxyServices.utility.ts +191 -0
  251. package/src/mixins/index.ts +91 -0
  252. package/src/mixins/mixinHelpers.ts +69 -0
  253. package/src/models/interfaces.ts +511 -0
  254. package/src/models/session.ts +30 -0
  255. package/src/shared/index.ts +82 -0
  256. package/src/shared/utils/colorUtils.ts +155 -0
  257. package/src/shared/utils/debugUtils.ts +73 -0
  258. package/src/shared/utils/errorUtils.ts +181 -0
  259. package/src/shared/utils/index.ts +59 -0
  260. package/src/shared/utils/networkUtils.ts +248 -0
  261. package/src/shared/utils/themeUtils.ts +115 -0
  262. package/src/types/bip39.d.ts +32 -0
  263. package/src/types/buffer.d.ts +97 -0
  264. package/src/types/color.d.ts +20 -0
  265. package/src/types/elliptic.d.ts +62 -0
  266. package/src/utils/apiUtils.ts +88 -0
  267. package/src/utils/asyncUtils.ts +252 -0
  268. package/src/utils/cache.ts +264 -0
  269. package/src/utils/deviceManager.ts +198 -0
  270. package/src/utils/errorUtils.ts +216 -0
  271. package/src/utils/index.ts +21 -0
  272. package/src/utils/languageUtils.ts +174 -0
  273. package/src/utils/loggerUtils.ts +153 -0
  274. package/src/utils/platform.ts +117 -0
  275. package/src/utils/requestUtils.ts +237 -0
  276. package/src/utils/sessionUtils.ts +206 -0
  277. package/src/utils/validationUtils.ts +174 -0
@@ -0,0 +1,850 @@
1
+ /**
2
+ * Key Manager - ECDSA secp256k1 Key Generation and Storage
3
+ *
4
+ * Handles secure generation, storage, and retrieval of cryptographic keys.
5
+ * Private keys are stored securely using expo-secure-store and never leave the device.
6
+ */
7
+ import { ec as EC } from 'elliptic';
8
+ import { isWeb, isIOS, isAndroid } from '../utils/platform';
9
+ import { logger } from '../utils/loggerUtils';
10
+ // Lazy imports for React Native specific modules
11
+ let SecureStore = null;
12
+ let ExpoCrypto = null;
13
+ const ec = new EC('secp256k1');
14
+ const STORAGE_KEYS = {
15
+ PRIVATE_KEY: 'oxy_identity_private_key',
16
+ PUBLIC_KEY: 'oxy_identity_public_key',
17
+ BACKUP_PRIVATE_KEY: 'oxy_identity_backup_private_key',
18
+ BACKUP_PUBLIC_KEY: 'oxy_identity_backup_public_key',
19
+ BACKUP_TIMESTAMP: 'oxy_identity_backup_timestamp',
20
+ // Shared keys accessible across all Oxy apps (iOS Keychain Group / Android Account Manager)
21
+ SHARED_PRIVATE_KEY: 'oxy_shared_identity_private_key',
22
+ SHARED_PUBLIC_KEY: 'oxy_shared_identity_public_key',
23
+ SHARED_SESSION_TOKEN: 'oxy_shared_session_token',
24
+ SHARED_SESSION_ID: 'oxy_shared_session_id',
25
+ };
26
+ /**
27
+ * iOS Keychain Access Group for sharing identities across Oxy apps
28
+ * All Oxy apps must have this access group enabled in their entitlements
29
+ * Format: [Team ID].com.oxy.shared or group.com.oxy.shared
30
+ */
31
+ const IOS_KEYCHAIN_GROUP = 'group.com.oxy.shared';
32
+ /**
33
+ * Android Account Manager type for shared authentication
34
+ * Used with sharedUserId to share sessions across apps
35
+ */
36
+ const ANDROID_ACCOUNT_TYPE = 'com.oxy.account';
37
+ /**
38
+ * Initialize React Native specific modules
39
+ * This allows the module to work in both Node.js and React Native environments
40
+ */
41
+ async function initSecureStore() {
42
+ if (!SecureStore) {
43
+ try {
44
+ SecureStore = await import('expo-secure-store');
45
+ }
46
+ catch (error) {
47
+ const errorMessage = error instanceof Error ? error.message : String(error);
48
+ throw new Error(`Failed to load expo-secure-store: ${errorMessage}. Make sure expo-secure-store is installed and properly configured.`);
49
+ }
50
+ }
51
+ if (!SecureStore) {
52
+ throw new Error('expo-secure-store module is not available');
53
+ }
54
+ return SecureStore;
55
+ }
56
+ /**
57
+ * Check if we're in a React Native environment
58
+ */
59
+ function isReactNative() {
60
+ return typeof navigator !== 'undefined' && navigator.product === 'ReactNative';
61
+ }
62
+ /**
63
+ * Check if we're in a Node.js environment
64
+ */
65
+ function isNodeJS() {
66
+ return typeof process !== 'undefined' && process.versions != null && process.versions.node != null;
67
+ }
68
+ /**
69
+ * Check if we're on web platform
70
+ * Identity storage is only available on native platforms (iOS/Android)
71
+ */
72
+ function isWebPlatform() {
73
+ return isWeb();
74
+ }
75
+ async function initExpoCrypto() {
76
+ if (!ExpoCrypto) {
77
+ ExpoCrypto = await import('expo-crypto');
78
+ }
79
+ return ExpoCrypto;
80
+ }
81
+ /**
82
+ * Convert Uint8Array to hexadecimal string
83
+ * Works in both Node.js and React Native
84
+ */
85
+ function uint8ArrayToHex(bytes) {
86
+ return Array.from(bytes)
87
+ .map(b => b.toString(16).padStart(2, '0'))
88
+ .join('');
89
+ }
90
+ /**
91
+ * Generate cryptographically secure random bytes
92
+ */
93
+ async function getSecureRandomBytes(length) {
94
+ // In React Native, always use expo-crypto
95
+ if (isReactNative() || !isNodeJS()) {
96
+ const Crypto = await initExpoCrypto();
97
+ return Crypto.getRandomBytes(length);
98
+ }
99
+ // In Node.js, use Node's crypto module
100
+ // Use Function constructor to prevent Metro bundler from statically analyzing this require
101
+ // This ensures the require is only evaluated in Node.js runtime, not during Metro bundling
102
+ try {
103
+ // eslint-disable-next-line @typescript-eslint/no-implied-eval
104
+ const getCrypto = new Function('return require("crypto")');
105
+ const crypto = getCrypto();
106
+ return new Uint8Array(crypto.randomBytes(length));
107
+ }
108
+ catch (error) {
109
+ // Fallback to expo-crypto if Node crypto fails
110
+ const Crypto = await initExpoCrypto();
111
+ return Crypto.getRandomBytes(length);
112
+ }
113
+ }
114
+ export class KeyManager {
115
+ /**
116
+ * Invalidate cached identity state
117
+ * Called internally when identity is created/deleted/imported
118
+ */
119
+ static invalidateCache() {
120
+ KeyManager.cachedPublicKey = null;
121
+ KeyManager.cachedHasIdentity = null;
122
+ }
123
+ /**
124
+ * Invalidate cached shared identity state
125
+ * Called internally when shared identity is created/deleted/imported
126
+ */
127
+ static invalidateSharedCache() {
128
+ KeyManager.cachedSharedPublicKey = null;
129
+ KeyManager.cachedHasSharedIdentity = null;
130
+ }
131
+ /**
132
+ * Generate a new ECDSA secp256k1 key pair
133
+ * Returns the keys in hexadecimal format
134
+ */
135
+ static generateKeyPairSync() {
136
+ const keyPair = ec.genKeyPair();
137
+ return {
138
+ privateKey: keyPair.getPrivate('hex'),
139
+ publicKey: keyPair.getPublic('hex'),
140
+ };
141
+ }
142
+ /**
143
+ * Generate a new key pair using secure random bytes
144
+ */
145
+ static async generateKeyPair() {
146
+ const randomBytes = await getSecureRandomBytes(32);
147
+ const privateKeyHex = uint8ArrayToHex(randomBytes);
148
+ const keyPair = ec.keyFromPrivate(privateKeyHex);
149
+ return {
150
+ privateKey: keyPair.getPrivate('hex'),
151
+ publicKey: keyPair.getPublic('hex'),
152
+ };
153
+ }
154
+ // ==================== SHARED IDENTITY METHODS ====================
155
+ // These methods enable cross-app session sharing (like Google)
156
+ // iOS: Uses Keychain Access Groups
157
+ // Android: Uses Account Manager with shared user ID
158
+ // =================================================================
159
+ /**
160
+ * Create a shared identity accessible across all Oxy apps
161
+ *
162
+ * iOS: Stores in shared keychain group (requires entitlement configuration)
163
+ * Android: Stores in Account Manager (requires sharedUserId in manifest)
164
+ *
165
+ * This enables true cross-app SSO - when user signs in to one Oxy app,
166
+ * they're automatically signed in to all other Oxy apps.
167
+ *
168
+ * @returns Public key of the shared identity
169
+ * @throws Error if not on native platform or if sharing is not configured
170
+ */
171
+ static async createSharedIdentity() {
172
+ if (isWebPlatform()) {
173
+ throw new Error('Shared identity is only available on native platforms (iOS/Android).');
174
+ }
175
+ const store = await initSecureStore();
176
+ const { privateKey, publicKey } = await KeyManager.generateKeyPair();
177
+ if (isIOS()) {
178
+ // iOS: Store in shared keychain group
179
+ // Note: keychainAccessGroup requires Keychain Sharing capability in Xcode
180
+ try {
181
+ await store.setItemAsync(STORAGE_KEYS.SHARED_PRIVATE_KEY, privateKey, {
182
+ keychainAccessible: store.WHEN_UNLOCKED_THIS_DEVICE_ONLY,
183
+ keychainAccessGroup: IOS_KEYCHAIN_GROUP, // This enables sharing across apps
184
+ }); // Type assertion: keychainAccessGroup may not be in older @types but is supported
185
+ await store.setItemAsync(STORAGE_KEYS.SHARED_PUBLIC_KEY, publicKey, {
186
+ keychainAccessGroup: IOS_KEYCHAIN_GROUP,
187
+ });
188
+ }
189
+ catch (error) {
190
+ throw new Error(`Failed to create shared identity on iOS. Ensure your app has the Keychain Sharing capability enabled with access group "${IOS_KEYCHAIN_GROUP}". Error: ${error}`);
191
+ }
192
+ }
193
+ else if (isAndroid()) {
194
+ // Android: Store in secure store (accessible via sharedUserId)
195
+ // Note: All Oxy apps must have the same sharedUserId in AndroidManifest.xml
196
+ await store.setItemAsync(STORAGE_KEYS.SHARED_PRIVATE_KEY, privateKey, {
197
+ keychainAccessible: store.WHEN_UNLOCKED_THIS_DEVICE_ONLY,
198
+ });
199
+ await store.setItemAsync(STORAGE_KEYS.SHARED_PUBLIC_KEY, publicKey);
200
+ }
201
+ // Update cache
202
+ KeyManager.cachedSharedPublicKey = publicKey;
203
+ KeyManager.cachedHasSharedIdentity = true;
204
+ if (__DEV__) {
205
+ logger.debug('Shared identity created successfully', { component: 'KeyManager' });
206
+ }
207
+ return publicKey;
208
+ }
209
+ /**
210
+ * Get the shared public key (accessible across all Oxy apps)
211
+ *
212
+ * @returns Shared public key or null if no shared identity exists
213
+ */
214
+ static async getSharedPublicKey() {
215
+ if (isWebPlatform()) {
216
+ return null;
217
+ }
218
+ // Return cached value if available
219
+ if (KeyManager.cachedSharedPublicKey !== null) {
220
+ return KeyManager.cachedSharedPublicKey;
221
+ }
222
+ try {
223
+ const store = await initSecureStore();
224
+ let publicKey = null;
225
+ if (isIOS()) {
226
+ publicKey = await store.getItemAsync(STORAGE_KEYS.SHARED_PUBLIC_KEY, {
227
+ keychainAccessGroup: IOS_KEYCHAIN_GROUP,
228
+ });
229
+ }
230
+ else if (isAndroid()) {
231
+ publicKey = await store.getItemAsync(STORAGE_KEYS.SHARED_PUBLIC_KEY);
232
+ }
233
+ // Cache result
234
+ KeyManager.cachedSharedPublicKey = publicKey;
235
+ return publicKey;
236
+ }
237
+ catch (error) {
238
+ if (__DEV__) {
239
+ logger.warn('Failed to get shared public key', { component: 'KeyManager' }, error);
240
+ }
241
+ KeyManager.cachedSharedPublicKey = null;
242
+ return null;
243
+ }
244
+ }
245
+ /**
246
+ * Get the shared private key (for signing operations)
247
+ *
248
+ * WARNING: Only use this for signing operations within the app.
249
+ * The private key should NEVER be transmitted or exposed.
250
+ *
251
+ * @returns Shared private key or null if no shared identity exists
252
+ */
253
+ static async getSharedPrivateKey() {
254
+ if (isWebPlatform()) {
255
+ return null;
256
+ }
257
+ try {
258
+ const store = await initSecureStore();
259
+ let privateKey = null;
260
+ if (isIOS()) {
261
+ privateKey = await store.getItemAsync(STORAGE_KEYS.SHARED_PRIVATE_KEY, {
262
+ keychainAccessGroup: IOS_KEYCHAIN_GROUP,
263
+ });
264
+ }
265
+ else if (isAndroid()) {
266
+ privateKey = await store.getItemAsync(STORAGE_KEYS.SHARED_PRIVATE_KEY);
267
+ }
268
+ return privateKey;
269
+ }
270
+ catch (error) {
271
+ if (__DEV__) {
272
+ logger.warn('Failed to get shared private key', { component: 'KeyManager' }, error);
273
+ }
274
+ return null;
275
+ }
276
+ }
277
+ /**
278
+ * Check if a shared identity exists (accessible across all Oxy apps)
279
+ *
280
+ * @returns True if shared identity exists, false otherwise
281
+ */
282
+ static async hasSharedIdentity() {
283
+ if (isWebPlatform()) {
284
+ return false;
285
+ }
286
+ // Return cached value if available
287
+ if (KeyManager.cachedHasSharedIdentity !== null) {
288
+ return KeyManager.cachedHasSharedIdentity;
289
+ }
290
+ try {
291
+ const privateKey = await KeyManager.getSharedPrivateKey();
292
+ const hasShared = privateKey !== null;
293
+ // Cache result
294
+ KeyManager.cachedHasSharedIdentity = hasShared;
295
+ return hasShared;
296
+ }
297
+ catch (error) {
298
+ if (__DEV__) {
299
+ logger.warn('Failed to check shared identity', { component: 'KeyManager' }, error);
300
+ }
301
+ KeyManager.cachedHasSharedIdentity = false;
302
+ return false;
303
+ }
304
+ }
305
+ /**
306
+ * Import an existing key pair as shared identity
307
+ *
308
+ * This is used when:
309
+ * 1. User signs in to a new Oxy app for the first time
310
+ * 2. User has existing identity on another Oxy app
311
+ * 3. We want to sync the identity across apps
312
+ *
313
+ * @param privateKey - Private key in hex format
314
+ * @returns Public key
315
+ */
316
+ static async importSharedIdentity(privateKey) {
317
+ if (isWebPlatform()) {
318
+ throw new Error('Shared identity import is only available on native platforms.');
319
+ }
320
+ const store = await initSecureStore();
321
+ const keyPair = ec.keyFromPrivate(privateKey);
322
+ const publicKey = keyPair.getPublic('hex');
323
+ if (isIOS()) {
324
+ await store.setItemAsync(STORAGE_KEYS.SHARED_PRIVATE_KEY, privateKey, {
325
+ keychainAccessible: store.WHEN_UNLOCKED_THIS_DEVICE_ONLY,
326
+ keychainAccessGroup: IOS_KEYCHAIN_GROUP,
327
+ });
328
+ await store.setItemAsync(STORAGE_KEYS.SHARED_PUBLIC_KEY, publicKey, {
329
+ keychainAccessGroup: IOS_KEYCHAIN_GROUP,
330
+ });
331
+ }
332
+ else if (isAndroid()) {
333
+ await store.setItemAsync(STORAGE_KEYS.SHARED_PRIVATE_KEY, privateKey, {
334
+ keychainAccessible: store.WHEN_UNLOCKED_THIS_DEVICE_ONLY,
335
+ });
336
+ await store.setItemAsync(STORAGE_KEYS.SHARED_PUBLIC_KEY, publicKey);
337
+ }
338
+ // Update cache
339
+ KeyManager.cachedSharedPublicKey = publicKey;
340
+ KeyManager.cachedHasSharedIdentity = true;
341
+ if (__DEV__) {
342
+ logger.debug('Shared identity imported successfully', { component: 'KeyManager' });
343
+ }
344
+ return publicKey;
345
+ }
346
+ /**
347
+ * Store session information in shared storage
348
+ *
349
+ * This allows all Oxy apps to access the same session without
350
+ * re-authenticating. When user signs in to one app, all apps
351
+ * get the session automatically.
352
+ *
353
+ * @param sessionId - Session ID from authentication
354
+ * @param accessToken - Access token for API calls
355
+ */
356
+ static async storeSharedSession(sessionId, accessToken) {
357
+ if (isWebPlatform()) {
358
+ return; // Not supported on web
359
+ }
360
+ try {
361
+ const store = await initSecureStore();
362
+ if (isIOS()) {
363
+ await store.setItemAsync(STORAGE_KEYS.SHARED_SESSION_ID, sessionId, {
364
+ keychainAccessGroup: IOS_KEYCHAIN_GROUP,
365
+ });
366
+ await store.setItemAsync(STORAGE_KEYS.SHARED_SESSION_TOKEN, accessToken, {
367
+ keychainAccessible: store.WHEN_UNLOCKED,
368
+ keychainAccessGroup: IOS_KEYCHAIN_GROUP,
369
+ });
370
+ }
371
+ else if (isAndroid()) {
372
+ await store.setItemAsync(STORAGE_KEYS.SHARED_SESSION_ID, sessionId);
373
+ await store.setItemAsync(STORAGE_KEYS.SHARED_SESSION_TOKEN, accessToken);
374
+ }
375
+ if (__DEV__) {
376
+ logger.debug('Shared session stored successfully', { component: 'KeyManager' });
377
+ }
378
+ }
379
+ catch (error) {
380
+ if (__DEV__) {
381
+ logger.error('Failed to store shared session', error, { component: 'KeyManager' });
382
+ }
383
+ throw error;
384
+ }
385
+ }
386
+ /**
387
+ * Get shared session information
388
+ *
389
+ * This allows any Oxy app to check if user is already signed in
390
+ * via another Oxy app. Enables instant cross-app SSO.
391
+ *
392
+ * @returns Session data or null if no shared session exists
393
+ */
394
+ static async getSharedSession() {
395
+ if (isWebPlatform()) {
396
+ return null;
397
+ }
398
+ try {
399
+ const store = await initSecureStore();
400
+ let sessionId = null;
401
+ let accessToken = null;
402
+ if (isIOS()) {
403
+ sessionId = await store.getItemAsync(STORAGE_KEYS.SHARED_SESSION_ID, {
404
+ keychainAccessGroup: IOS_KEYCHAIN_GROUP,
405
+ });
406
+ accessToken = await store.getItemAsync(STORAGE_KEYS.SHARED_SESSION_TOKEN, {
407
+ keychainAccessGroup: IOS_KEYCHAIN_GROUP,
408
+ });
409
+ }
410
+ else if (isAndroid()) {
411
+ sessionId = await store.getItemAsync(STORAGE_KEYS.SHARED_SESSION_ID);
412
+ accessToken = await store.getItemAsync(STORAGE_KEYS.SHARED_SESSION_TOKEN);
413
+ }
414
+ if (!sessionId || !accessToken) {
415
+ return null;
416
+ }
417
+ return { sessionId, accessToken };
418
+ }
419
+ catch (error) {
420
+ if (__DEV__) {
421
+ logger.warn('Failed to get shared session', { component: 'KeyManager' }, error);
422
+ }
423
+ return null;
424
+ }
425
+ }
426
+ /**
427
+ * Clear shared session (on logout)
428
+ *
429
+ * This signs out the user from ALL Oxy apps simultaneously.
430
+ * Call this when user explicitly logs out.
431
+ */
432
+ static async clearSharedSession() {
433
+ if (isWebPlatform()) {
434
+ return;
435
+ }
436
+ try {
437
+ const store = await initSecureStore();
438
+ if (isIOS()) {
439
+ await store.deleteItemAsync(STORAGE_KEYS.SHARED_SESSION_ID, {
440
+ keychainAccessGroup: IOS_KEYCHAIN_GROUP,
441
+ });
442
+ await store.deleteItemAsync(STORAGE_KEYS.SHARED_SESSION_TOKEN, {
443
+ keychainAccessGroup: IOS_KEYCHAIN_GROUP,
444
+ });
445
+ }
446
+ else if (isAndroid()) {
447
+ await store.deleteItemAsync(STORAGE_KEYS.SHARED_SESSION_ID);
448
+ await store.deleteItemAsync(STORAGE_KEYS.SHARED_SESSION_TOKEN);
449
+ }
450
+ if (__DEV__) {
451
+ logger.debug('Shared session cleared successfully', { component: 'KeyManager' });
452
+ }
453
+ }
454
+ catch (error) {
455
+ if (__DEV__) {
456
+ logger.error('Failed to clear shared session', error, { component: 'KeyManager' });
457
+ }
458
+ }
459
+ }
460
+ /**
461
+ * Migrate local identity to shared identity
462
+ *
463
+ * Call this when upgrading existing apps to use shared identities.
464
+ * Copies the device-specific identity to shared storage so it can
465
+ * be accessed by other Oxy apps.
466
+ *
467
+ * @returns True if migration was successful, false if no local identity exists
468
+ */
469
+ static async migrateToSharedIdentity() {
470
+ if (isWebPlatform()) {
471
+ return false;
472
+ }
473
+ try {
474
+ // Check if we already have a shared identity
475
+ const hasShared = await KeyManager.hasSharedIdentity();
476
+ if (hasShared) {
477
+ if (__DEV__) {
478
+ logger.debug('Shared identity already exists, skipping migration', { component: 'KeyManager' });
479
+ }
480
+ return true;
481
+ }
482
+ // Get local identity
483
+ const privateKey = await KeyManager.getPrivateKey();
484
+ if (!privateKey) {
485
+ if (__DEV__) {
486
+ logger.debug('No local identity to migrate', { component: 'KeyManager' });
487
+ }
488
+ return false;
489
+ }
490
+ // Import to shared storage
491
+ await KeyManager.importSharedIdentity(privateKey);
492
+ if (__DEV__) {
493
+ logger.debug('Successfully migrated local identity to shared identity', { component: 'KeyManager' });
494
+ }
495
+ return true;
496
+ }
497
+ catch (error) {
498
+ if (__DEV__) {
499
+ logger.error('Failed to migrate to shared identity', error, { component: 'KeyManager' });
500
+ }
501
+ return false;
502
+ }
503
+ }
504
+ // ==================== END SHARED IDENTITY METHODS ====================
505
+ /**
506
+ * Generate and securely store a new key pair on the device
507
+ * Returns only the public key (private key is stored securely)
508
+ */
509
+ static async createIdentity() {
510
+ if (isWebPlatform()) {
511
+ throw new Error('Identity creation is only available on native platforms (iOS/Android). Please use the native app to create your identity.');
512
+ }
513
+ const store = await initSecureStore();
514
+ const { privateKey, publicKey } = await KeyManager.generateKeyPair();
515
+ await store.setItemAsync(STORAGE_KEYS.PRIVATE_KEY, privateKey, {
516
+ keychainAccessible: store.WHEN_UNLOCKED_THIS_DEVICE_ONLY,
517
+ });
518
+ await store.setItemAsync(STORAGE_KEYS.PUBLIC_KEY, publicKey);
519
+ // Update cache
520
+ KeyManager.cachedPublicKey = publicKey;
521
+ KeyManager.cachedHasIdentity = true;
522
+ return publicKey;
523
+ }
524
+ /**
525
+ * Import an existing key pair (e.g., from recovery phrase)
526
+ */
527
+ static async importKeyPair(privateKey) {
528
+ if (isWebPlatform()) {
529
+ throw new Error('Identity import is only available on native platforms (iOS/Android). Please use the native app to import your identity.');
530
+ }
531
+ const store = await initSecureStore();
532
+ const keyPair = ec.keyFromPrivate(privateKey);
533
+ const publicKey = keyPair.getPublic('hex');
534
+ await store.setItemAsync(STORAGE_KEYS.PRIVATE_KEY, privateKey, {
535
+ keychainAccessible: store.WHEN_UNLOCKED_THIS_DEVICE_ONLY,
536
+ });
537
+ await store.setItemAsync(STORAGE_KEYS.PUBLIC_KEY, publicKey);
538
+ // Update cache
539
+ KeyManager.cachedPublicKey = publicKey;
540
+ KeyManager.cachedHasIdentity = true;
541
+ return publicKey;
542
+ }
543
+ /**
544
+ * Get the stored private key
545
+ * WARNING: Only use this for signing operations within the app
546
+ */
547
+ static async getPrivateKey() {
548
+ if (isWebPlatform()) {
549
+ return null; // Identity storage is only available on native platforms
550
+ }
551
+ try {
552
+ const store = await initSecureStore();
553
+ return await store.getItemAsync(STORAGE_KEYS.PRIVATE_KEY);
554
+ }
555
+ catch (error) {
556
+ // If secure store is not available, return null (no identity)
557
+ // This allows the app to continue functioning even if secure store fails to load
558
+ if (__DEV__) {
559
+ logger.warn('Failed to access secure store', { component: 'KeyManager' }, error);
560
+ }
561
+ return null;
562
+ }
563
+ }
564
+ /**
565
+ * Get the stored public key (cached for performance)
566
+ */
567
+ static async getPublicKey() {
568
+ if (isWebPlatform()) {
569
+ return null; // Identity storage is only available on native platforms
570
+ }
571
+ if (KeyManager.cachedPublicKey !== null) {
572
+ return KeyManager.cachedPublicKey;
573
+ }
574
+ try {
575
+ const store = await initSecureStore();
576
+ const publicKey = await store.getItemAsync(STORAGE_KEYS.PUBLIC_KEY);
577
+ // Cache result (null is a valid cache value meaning no identity)
578
+ KeyManager.cachedPublicKey = publicKey;
579
+ return publicKey;
580
+ }
581
+ catch (error) {
582
+ // If secure store is not available, return null (no identity)
583
+ // Cache null to avoid repeated failed attempts
584
+ KeyManager.cachedPublicKey = null;
585
+ if (__DEV__) {
586
+ logger.warn('Failed to access secure store', { component: 'KeyManager' }, error);
587
+ }
588
+ return null;
589
+ }
590
+ }
591
+ /**
592
+ * Check if an identity (key pair) exists on this device (cached for performance)
593
+ */
594
+ static async hasIdentity() {
595
+ if (isWebPlatform()) {
596
+ return false; // Identity storage is only available on native platforms
597
+ }
598
+ if (KeyManager.cachedHasIdentity !== null) {
599
+ return KeyManager.cachedHasIdentity;
600
+ }
601
+ try {
602
+ const privateKey = await KeyManager.getPrivateKey();
603
+ const hasIdentity = privateKey !== null;
604
+ // Cache result
605
+ KeyManager.cachedHasIdentity = hasIdentity;
606
+ return hasIdentity;
607
+ }
608
+ catch (error) {
609
+ // If we can't check, assume no identity (safer default)
610
+ // Cache false to avoid repeated failed attempts
611
+ KeyManager.cachedHasIdentity = false;
612
+ if (__DEV__) {
613
+ logger.warn('Failed to check identity', { component: 'KeyManager' }, error);
614
+ }
615
+ return false;
616
+ }
617
+ }
618
+ /**
619
+ * Delete the stored identity (both keys)
620
+ * Use with EXTREME caution - this is irreversible without a recovery phrase
621
+ * This should ONLY be called when explicitly requested by the user
622
+ * @param skipBackup - If true, skip backup before deletion (default: false)
623
+ * @param force - If true, skip confirmation checks (default: false)
624
+ * @param userConfirmed - If true, user has explicitly confirmed deletion (default: false)
625
+ */
626
+ static async deleteIdentity(skipBackup = false, force = false, userConfirmed = false) {
627
+ if (isWebPlatform()) {
628
+ return; // Identity storage is only available on native platforms, nothing to delete
629
+ }
630
+ // CRITICAL SAFEGUARD: Require explicit user confirmation unless force is true
631
+ if (!force && !userConfirmed) {
632
+ throw new Error('Identity deletion requires explicit user confirmation. This is a safety measure to prevent accidental data loss.');
633
+ }
634
+ if (!force) {
635
+ const hasIdentity = await KeyManager.hasIdentity();
636
+ if (!hasIdentity) {
637
+ return; // Nothing to delete
638
+ }
639
+ }
640
+ const store = await initSecureStore();
641
+ // ALWAYS create backup before deletion unless explicitly skipped
642
+ if (!skipBackup) {
643
+ try {
644
+ const backupSuccess = await KeyManager.backupIdentity();
645
+ if (!backupSuccess && typeof __DEV__ !== 'undefined' && __DEV__) {
646
+ logger.warn('Failed to backup identity before deletion - proceeding anyway', { component: 'KeyManager' });
647
+ }
648
+ }
649
+ catch (backupError) {
650
+ if (typeof __DEV__ !== 'undefined' && __DEV__) {
651
+ logger.warn('Failed to backup identity before deletion', { component: 'KeyManager' }, backupError);
652
+ }
653
+ }
654
+ }
655
+ await store.deleteItemAsync(STORAGE_KEYS.PRIVATE_KEY);
656
+ await store.deleteItemAsync(STORAGE_KEYS.PUBLIC_KEY);
657
+ // Invalidate cache
658
+ KeyManager.invalidateCache();
659
+ // Also clear backup if force deletion
660
+ if (force) {
661
+ try {
662
+ await store.deleteItemAsync(STORAGE_KEYS.BACKUP_PRIVATE_KEY);
663
+ await store.deleteItemAsync(STORAGE_KEYS.BACKUP_PUBLIC_KEY);
664
+ await store.deleteItemAsync(STORAGE_KEYS.BACKUP_TIMESTAMP);
665
+ }
666
+ catch (error) {
667
+ // Ignore backup deletion errors
668
+ }
669
+ }
670
+ }
671
+ /**
672
+ * Backup identity to SecureStore (separate backup storage)
673
+ * This provides a recovery mechanism if primary storage fails
674
+ */
675
+ static async backupIdentity() {
676
+ if (isWebPlatform()) {
677
+ return false; // Identity storage is only available on native platforms
678
+ }
679
+ try {
680
+ const store = await initSecureStore();
681
+ const privateKey = await KeyManager.getPrivateKey();
682
+ const publicKey = await KeyManager.getPublicKey();
683
+ if (!privateKey || !publicKey) {
684
+ return false; // Nothing to backup
685
+ }
686
+ // Store backup in SecureStore (still secure, but separate from primary storage)
687
+ await store.setItemAsync(STORAGE_KEYS.BACKUP_PRIVATE_KEY, privateKey, {
688
+ keychainAccessible: store.WHEN_UNLOCKED_THIS_DEVICE_ONLY,
689
+ });
690
+ await store.setItemAsync(STORAGE_KEYS.BACKUP_PUBLIC_KEY, publicKey);
691
+ await store.setItemAsync(STORAGE_KEYS.BACKUP_TIMESTAMP, Date.now().toString());
692
+ return true;
693
+ }
694
+ catch (error) {
695
+ if (typeof __DEV__ !== 'undefined' && __DEV__) {
696
+ logger.error('Failed to backup identity', error, { component: 'KeyManager' });
697
+ }
698
+ return false;
699
+ }
700
+ }
701
+ /**
702
+ * Verify identity integrity - checks if keys are valid and accessible
703
+ */
704
+ static async verifyIdentityIntegrity() {
705
+ if (isWebPlatform()) {
706
+ return false; // Identity storage is only available on native platforms
707
+ }
708
+ try {
709
+ const privateKey = await KeyManager.getPrivateKey();
710
+ const publicKey = await KeyManager.getPublicKey();
711
+ if (!privateKey || !publicKey) {
712
+ return false;
713
+ }
714
+ // Validate private key format
715
+ if (!KeyManager.isValidPrivateKey(privateKey)) {
716
+ return false;
717
+ }
718
+ // Validate public key format
719
+ if (!KeyManager.isValidPublicKey(publicKey)) {
720
+ return false;
721
+ }
722
+ // Verify public key can be derived from private key
723
+ const derivedPublicKey = KeyManager.derivePublicKey(privateKey);
724
+ if (derivedPublicKey !== publicKey) {
725
+ return false; // Keys don't match
726
+ }
727
+ // Verify we can create a key pair object (tests elliptic curve operations)
728
+ const keyPair = await KeyManager.getKeyPairObject();
729
+ if (!keyPair) {
730
+ return false;
731
+ }
732
+ return true;
733
+ }
734
+ catch (error) {
735
+ if (typeof __DEV__ !== 'undefined' && __DEV__) {
736
+ logger.error('Identity integrity check failed', error, { component: 'KeyManager' });
737
+ }
738
+ return false;
739
+ }
740
+ }
741
+ /**
742
+ * Restore identity from backup if primary storage is corrupted
743
+ */
744
+ static async restoreIdentityFromBackup() {
745
+ if (isWebPlatform()) {
746
+ return false; // Identity storage is only available on native platforms
747
+ }
748
+ try {
749
+ const store = await initSecureStore();
750
+ // Check if backup exists
751
+ const backupPrivateKey = await store.getItemAsync(STORAGE_KEYS.BACKUP_PRIVATE_KEY);
752
+ const backupPublicKey = await store.getItemAsync(STORAGE_KEYS.BACKUP_PUBLIC_KEY);
753
+ if (!backupPrivateKey || !backupPublicKey) {
754
+ return false; // No backup available
755
+ }
756
+ // Verify backup integrity
757
+ if (!KeyManager.isValidPrivateKey(backupPrivateKey)) {
758
+ return false;
759
+ }
760
+ if (!KeyManager.isValidPublicKey(backupPublicKey)) {
761
+ return false;
762
+ }
763
+ // Verify keys match
764
+ const derivedPublicKey = KeyManager.derivePublicKey(backupPrivateKey);
765
+ if (derivedPublicKey !== backupPublicKey) {
766
+ return false; // Backup keys don't match
767
+ }
768
+ await store.setItemAsync(STORAGE_KEYS.PRIVATE_KEY, backupPrivateKey, {
769
+ keychainAccessible: store.WHEN_UNLOCKED_THIS_DEVICE_ONLY,
770
+ });
771
+ await store.setItemAsync(STORAGE_KEYS.PUBLIC_KEY, backupPublicKey);
772
+ const restored = await KeyManager.verifyIdentityIntegrity();
773
+ if (restored) {
774
+ // Update cache
775
+ KeyManager.cachedPublicKey = backupPublicKey;
776
+ KeyManager.cachedHasIdentity = true;
777
+ await store.setItemAsync(STORAGE_KEYS.BACKUP_TIMESTAMP, Date.now().toString());
778
+ return true;
779
+ }
780
+ return false;
781
+ }
782
+ catch (error) {
783
+ if (typeof __DEV__ !== 'undefined' && __DEV__) {
784
+ logger.error('Failed to restore identity from backup', error, { component: 'KeyManager' });
785
+ }
786
+ return false;
787
+ }
788
+ }
789
+ /**
790
+ * Get the elliptic curve key object from the stored private key
791
+ * Used internally for signing operations
792
+ */
793
+ static async getKeyPairObject() {
794
+ if (isWebPlatform()) {
795
+ return null; // Identity storage is only available on native platforms
796
+ }
797
+ const privateKey = await KeyManager.getPrivateKey();
798
+ if (!privateKey)
799
+ return null;
800
+ return ec.keyFromPrivate(privateKey);
801
+ }
802
+ /**
803
+ * Derive public key from a private key (without storing)
804
+ */
805
+ static derivePublicKey(privateKey) {
806
+ const keyPair = ec.keyFromPrivate(privateKey);
807
+ return keyPair.getPublic('hex');
808
+ }
809
+ /**
810
+ * Validate that a string is a valid public key
811
+ */
812
+ static isValidPublicKey(publicKey) {
813
+ try {
814
+ ec.keyFromPublic(publicKey, 'hex');
815
+ return true;
816
+ }
817
+ catch {
818
+ return false;
819
+ }
820
+ }
821
+ /**
822
+ * Validate that a string is a valid private key
823
+ */
824
+ static isValidPrivateKey(privateKey) {
825
+ try {
826
+ const keyPair = ec.keyFromPrivate(privateKey);
827
+ // Verify it can derive a public key
828
+ keyPair.getPublic('hex');
829
+ return true;
830
+ }
831
+ catch {
832
+ return false;
833
+ }
834
+ }
835
+ /**
836
+ * Get a shortened version of the public key for display
837
+ * Format: first 8 chars...last 8 chars
838
+ */
839
+ static shortenPublicKey(publicKey) {
840
+ if (publicKey.length <= 20)
841
+ return publicKey;
842
+ return `${publicKey.slice(0, 8)}...${publicKey.slice(-8)}`;
843
+ }
844
+ }
845
+ // In-memory cache for identity state (invalidated on identity changes)
846
+ KeyManager.cachedPublicKey = null;
847
+ KeyManager.cachedHasIdentity = null;
848
+ KeyManager.cachedSharedPublicKey = null;
849
+ KeyManager.cachedHasSharedIdentity = null;
850
+ export default KeyManager;