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