@oxy.so/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 (673) hide show
  1. package/LICENSE +202 -0
  2. package/NOTICE +16 -0
  3. package/README.md +221 -0
  4. package/dist/cjs/.tsbuildinfo +1 -0
  5. package/dist/cjs/HttpService.js +1270 -0
  6. package/dist/cjs/OxyServices.base.js +390 -0
  7. package/dist/cjs/OxyServices.errors.js +95 -0
  8. package/dist/cjs/OxyServices.js +72 -0
  9. package/dist/cjs/boot/sessionColdBoot.js +395 -0
  10. package/dist/cjs/constants/version.js +16 -0
  11. package/dist/cjs/crypto/aead.js +79 -0
  12. package/dist/cjs/crypto/ecdh.js +35 -0
  13. package/dist/cjs/crypto/identityMarker.js +255 -0
  14. package/dist/cjs/crypto/kdf.js +39 -0
  15. package/dist/cjs/crypto/keyManager.js +2234 -0
  16. package/dist/cjs/crypto/polyfill.js +131 -0
  17. package/dist/cjs/crypto/recoveryPhrase.js +242 -0
  18. package/dist/cjs/crypto/signatureService.js +273 -0
  19. package/dist/cjs/i18n/accountCategoryLabels.js +44 -0
  20. package/dist/cjs/i18n/accountRoleLabels.js +27 -0
  21. package/dist/cjs/i18n/index.js +90 -0
  22. package/dist/cjs/i18n/locales/ar-SA.json +282 -0
  23. package/dist/cjs/i18n/locales/ca-ES.json +282 -0
  24. package/dist/cjs/i18n/locales/de-DE.json +282 -0
  25. package/dist/cjs/i18n/locales/en-US.json +2161 -0
  26. package/dist/cjs/i18n/locales/es-ES.json +2161 -0
  27. package/dist/cjs/i18n/locales/fr-FR.json +282 -0
  28. package/dist/cjs/i18n/locales/it-IT.json +282 -0
  29. package/dist/cjs/i18n/locales/ja-JP.json +282 -0
  30. package/dist/cjs/i18n/locales/ko-KR.json +282 -0
  31. package/dist/cjs/i18n/locales/locales/ar-SA.json +282 -0
  32. package/dist/cjs/i18n/locales/locales/ca-ES.json +282 -0
  33. package/dist/cjs/i18n/locales/locales/de-DE.json +282 -0
  34. package/dist/cjs/i18n/locales/locales/en-US.json +2161 -0
  35. package/dist/cjs/i18n/locales/locales/es-ES.json +2161 -0
  36. package/dist/cjs/i18n/locales/locales/fr-FR.json +282 -0
  37. package/dist/cjs/i18n/locales/locales/it-IT.json +282 -0
  38. package/dist/cjs/i18n/locales/locales/ja-JP.json +282 -0
  39. package/dist/cjs/i18n/locales/locales/ko-KR.json +282 -0
  40. package/dist/cjs/i18n/locales/locales/pt-PT.json +282 -0
  41. package/dist/cjs/i18n/locales/locales/zh-CN.json +282 -0
  42. package/dist/cjs/i18n/locales/pt-PT.json +282 -0
  43. package/dist/cjs/i18n/locales/zh-CN.json +282 -0
  44. package/dist/cjs/i18n/reputationCategoryLabels.js +20 -0
  45. package/dist/cjs/i18n/trustTierLabels.js +19 -0
  46. package/dist/cjs/index.js +498 -0
  47. package/dist/cjs/inference/OxyInferenceClient.js +544 -0
  48. package/dist/cjs/logger/index.js +149 -0
  49. package/dist/cjs/mixins/OxyServices.accounts.js +555 -0
  50. package/dist/cjs/mixins/OxyServices.analytics.js +49 -0
  51. package/dist/cjs/mixins/OxyServices.appData.js +108 -0
  52. package/dist/cjs/mixins/OxyServices.assets.js +764 -0
  53. package/dist/cjs/mixins/OxyServices.auth.js +1254 -0
  54. package/dist/cjs/mixins/OxyServices.chains.js +73 -0
  55. package/dist/cjs/mixins/OxyServices.civic.js +611 -0
  56. package/dist/cjs/mixins/OxyServices.connectedApps.js +78 -0
  57. package/dist/cjs/mixins/OxyServices.contacts.js +50 -0
  58. package/dist/cjs/mixins/OxyServices.deviceBoot.js +191 -0
  59. package/dist/cjs/mixins/OxyServices.deviceTransfer.js +314 -0
  60. package/dist/cjs/mixins/OxyServices.devices.js +116 -0
  61. package/dist/cjs/mixins/OxyServices.features.js +335 -0
  62. package/dist/cjs/mixins/OxyServices.followGraph.js +221 -0
  63. package/dist/cjs/mixins/OxyServices.identity.js +461 -0
  64. package/dist/cjs/mixins/OxyServices.identityBackup.js +172 -0
  65. package/dist/cjs/mixins/OxyServices.inference.js +59 -0
  66. package/dist/cjs/mixins/OxyServices.language.js +125 -0
  67. package/dist/cjs/mixins/OxyServices.links.js +72 -0
  68. package/dist/cjs/mixins/OxyServices.location.js +43 -0
  69. package/dist/cjs/mixins/OxyServices.nodes.js +175 -0
  70. package/dist/cjs/mixins/OxyServices.notifications.js +63 -0
  71. package/dist/cjs/mixins/OxyServices.payment.js +158 -0
  72. package/dist/cjs/mixins/OxyServices.privacy.js +199 -0
  73. package/dist/cjs/mixins/OxyServices.reputation.js +289 -0
  74. package/dist/cjs/mixins/OxyServices.security.js +89 -0
  75. package/dist/cjs/mixins/OxyServices.store.js +266 -0
  76. package/dist/cjs/mixins/OxyServices.topics.js +137 -0
  77. package/dist/cjs/mixins/OxyServices.user.js +902 -0
  78. package/dist/cjs/mixins/OxyServices.utility.js +1098 -0
  79. package/dist/cjs/mixins/index.js +135 -0
  80. package/dist/cjs/mixins/mixinHelpers.js +53 -0
  81. package/dist/cjs/models/Topic.js +16 -0
  82. package/dist/cjs/models/interfaces.js +20 -0
  83. package/dist/cjs/models/session.js +2 -0
  84. package/dist/cjs/server/auth.js +167 -0
  85. package/dist/cjs/server/capabilityTicket.js +192 -0
  86. package/dist/cjs/server/cors.js +225 -0
  87. package/dist/cjs/server/index.js +97 -0
  88. package/dist/cjs/server/rateLimit.js +207 -0
  89. package/dist/cjs/server/safeFetch.js +458 -0
  90. package/dist/cjs/server/securityHeaders.js +377 -0
  91. package/dist/cjs/server/userInvalidation.js +156 -0
  92. package/dist/cjs/server/verifySecret.js +50 -0
  93. package/dist/cjs/session/SessionClient.js +865 -0
  94. package/dist/cjs/session/accountDelegationAccess.js +48 -0
  95. package/dist/cjs/session/accountDialogController.js +1131 -0
  96. package/dist/cjs/session/accountSwitchTargets.js +81 -0
  97. package/dist/cjs/session/authStateStore.js +404 -0
  98. package/dist/cjs/session/createSessionClient.js +32 -0
  99. package/dist/cjs/session/deviceDirectory.js +143 -0
  100. package/dist/cjs/session/deviceSwitcherRows.js +76 -0
  101. package/dist/cjs/session/identityPin.js +256 -0
  102. package/dist/cjs/session/identitySession.js +135 -0
  103. package/dist/cjs/session/projectSessionState.js +121 -0
  104. package/dist/cjs/session/refresh.js +398 -0
  105. package/dist/cjs/session/sessionClientHost.js +34 -0
  106. package/dist/cjs/session/sharedDeviceCredential.js +247 -0
  107. package/dist/cjs/session/socketLoader.js +55 -0
  108. package/dist/cjs/shared/utils/colorUtils.js +153 -0
  109. package/dist/cjs/shared/utils/errorUtils.js +183 -0
  110. package/dist/cjs/shared/utils/index.js +49 -0
  111. package/dist/cjs/shared/utils/networkUtils.js +183 -0
  112. package/dist/cjs/shared/utils/themeUtils.js +106 -0
  113. package/dist/cjs/utils/accountCacheSweep.js +80 -0
  114. package/dist/cjs/utils/accountUtils.js +140 -0
  115. package/dist/cjs/utils/activityId.js +6 -0
  116. package/dist/cjs/utils/apiUtils.js +91 -0
  117. package/dist/cjs/utils/asyncUtils.js +222 -0
  118. package/dist/cjs/utils/authHelpers.js +120 -0
  119. package/dist/cjs/utils/authWebUrl.js +19 -0
  120. package/dist/cjs/utils/avatarUtils.js +29 -0
  121. package/dist/cjs/utils/cache.js +235 -0
  122. package/dist/cjs/utils/cacheKey.js +85 -0
  123. package/dist/cjs/utils/coldBoot.js +122 -0
  124. package/dist/cjs/utils/commonsApproval.js +31 -0
  125. package/dist/cjs/utils/commonsDelivery.js +59 -0
  126. package/dist/cjs/utils/deviceManager.js +174 -0
  127. package/dist/cjs/utils/displayNamePolicyRanges.generated.js +60 -0
  128. package/dist/cjs/utils/edgeRegion.js +6 -0
  129. package/dist/cjs/utils/errorUtils.js +243 -0
  130. package/dist/cjs/utils/identityCacheSweep.js +97 -0
  131. package/dist/cjs/utils/languageUtils.js +224 -0
  132. package/dist/cjs/utils/oauthPkce.js +311 -0
  133. package/dist/cjs/utils/officialOrigins.js +64 -0
  134. package/dist/cjs/utils/oxyServiceEnvironment.js +19 -0
  135. package/dist/cjs/utils/platform.js +119 -0
  136. package/dist/cjs/utils/profileLinks.js +63 -0
  137. package/dist/cjs/utils/redactUrl.js +29 -0
  138. package/dist/cjs/utils/registrableApex.js +45 -0
  139. package/dist/cjs/utils/requestUtils.js +209 -0
  140. package/dist/cjs/utils/sessionUtils.js +181 -0
  141. package/dist/cjs/utils/textNormalization.js +158 -0
  142. package/dist/cjs/utils/userHandle.js +37 -0
  143. package/dist/cjs/utils/userIdentity.js +50 -0
  144. package/dist/cjs/utils/validationUtils.js +370 -0
  145. package/dist/cjs/utils/webauthnOrigin.js +51 -0
  146. package/dist/esm/.tsbuildinfo +1 -0
  147. package/dist/esm/HttpService.js +1266 -0
  148. package/dist/esm/OxyServices.base.js +386 -0
  149. package/dist/esm/OxyServices.errors.js +88 -0
  150. package/dist/esm/OxyServices.js +66 -0
  151. package/dist/esm/boot/sessionColdBoot.js +392 -0
  152. package/dist/esm/constants/version.js +13 -0
  153. package/dist/esm/crypto/aead.js +74 -0
  154. package/dist/esm/crypto/ecdh.js +32 -0
  155. package/dist/esm/crypto/identityMarker.js +248 -0
  156. package/dist/esm/crypto/kdf.js +36 -0
  157. package/dist/esm/crypto/keyManager.js +2227 -0
  158. package/dist/esm/crypto/polyfill.js +129 -0
  159. package/dist/esm/crypto/recoveryPhrase.js +238 -0
  160. package/dist/esm/crypto/signatureService.js +269 -0
  161. package/dist/esm/i18n/accountCategoryLabels.js +37 -0
  162. package/dist/esm/i18n/accountRoleLabels.js +20 -0
  163. package/dist/esm/i18n/index.js +83 -0
  164. package/dist/esm/i18n/locales/ar-SA.json +282 -0
  165. package/dist/esm/i18n/locales/ca-ES.json +282 -0
  166. package/dist/esm/i18n/locales/de-DE.json +282 -0
  167. package/dist/esm/i18n/locales/en-US.json +2161 -0
  168. package/dist/esm/i18n/locales/es-ES.json +2161 -0
  169. package/dist/esm/i18n/locales/fr-FR.json +282 -0
  170. package/dist/esm/i18n/locales/it-IT.json +282 -0
  171. package/dist/esm/i18n/locales/ja-JP.json +282 -0
  172. package/dist/esm/i18n/locales/ko-KR.json +282 -0
  173. package/dist/esm/i18n/locales/locales/ar-SA.json +282 -0
  174. package/dist/esm/i18n/locales/locales/ca-ES.json +282 -0
  175. package/dist/esm/i18n/locales/locales/de-DE.json +282 -0
  176. package/dist/esm/i18n/locales/locales/en-US.json +2161 -0
  177. package/dist/esm/i18n/locales/locales/es-ES.json +2161 -0
  178. package/dist/esm/i18n/locales/locales/fr-FR.json +282 -0
  179. package/dist/esm/i18n/locales/locales/it-IT.json +282 -0
  180. package/dist/esm/i18n/locales/locales/ja-JP.json +282 -0
  181. package/dist/esm/i18n/locales/locales/ko-KR.json +282 -0
  182. package/dist/esm/i18n/locales/locales/pt-PT.json +282 -0
  183. package/dist/esm/i18n/locales/locales/zh-CN.json +282 -0
  184. package/dist/esm/i18n/locales/pt-PT.json +282 -0
  185. package/dist/esm/i18n/locales/zh-CN.json +282 -0
  186. package/dist/esm/i18n/reputationCategoryLabels.js +13 -0
  187. package/dist/esm/i18n/trustTierLabels.js +12 -0
  188. package/dist/esm/index.js +254 -0
  189. package/dist/esm/inference/OxyInferenceClient.js +538 -0
  190. package/dist/esm/logger/index.js +140 -0
  191. package/dist/esm/mixins/OxyServices.accounts.js +543 -0
  192. package/dist/esm/mixins/OxyServices.analytics.js +46 -0
  193. package/dist/esm/mixins/OxyServices.appData.js +103 -0
  194. package/dist/esm/mixins/OxyServices.assets.js +761 -0
  195. package/dist/esm/mixins/OxyServices.auth.js +1247 -0
  196. package/dist/esm/mixins/OxyServices.chains.js +70 -0
  197. package/dist/esm/mixins/OxyServices.civic.js +605 -0
  198. package/dist/esm/mixins/OxyServices.connectedApps.js +75 -0
  199. package/dist/esm/mixins/OxyServices.contacts.js +47 -0
  200. package/dist/esm/mixins/OxyServices.deviceBoot.js +186 -0
  201. package/dist/esm/mixins/OxyServices.deviceTransfer.js +311 -0
  202. package/dist/esm/mixins/OxyServices.devices.js +113 -0
  203. package/dist/esm/mixins/OxyServices.features.js +332 -0
  204. package/dist/esm/mixins/OxyServices.followGraph.js +218 -0
  205. package/dist/esm/mixins/OxyServices.identity.js +457 -0
  206. package/dist/esm/mixins/OxyServices.identityBackup.js +169 -0
  207. package/dist/esm/mixins/OxyServices.inference.js +56 -0
  208. package/dist/esm/mixins/OxyServices.language.js +122 -0
  209. package/dist/esm/mixins/OxyServices.links.js +69 -0
  210. package/dist/esm/mixins/OxyServices.location.js +40 -0
  211. package/dist/esm/mixins/OxyServices.nodes.js +172 -0
  212. package/dist/esm/mixins/OxyServices.notifications.js +60 -0
  213. package/dist/esm/mixins/OxyServices.payment.js +155 -0
  214. package/dist/esm/mixins/OxyServices.privacy.js +196 -0
  215. package/dist/esm/mixins/OxyServices.reputation.js +286 -0
  216. package/dist/esm/mixins/OxyServices.security.js +86 -0
  217. package/dist/esm/mixins/OxyServices.store.js +263 -0
  218. package/dist/esm/mixins/OxyServices.topics.js +134 -0
  219. package/dist/esm/mixins/OxyServices.user.js +899 -0
  220. package/dist/esm/mixins/OxyServices.utility.js +1095 -0
  221. package/dist/esm/mixins/index.js +132 -0
  222. package/dist/esm/mixins/mixinHelpers.js +48 -0
  223. package/dist/esm/models/Topic.js +13 -0
  224. package/dist/esm/models/interfaces.js +17 -0
  225. package/dist/esm/models/session.js +1 -0
  226. package/dist/esm/server/auth.js +154 -0
  227. package/dist/esm/server/capabilityTicket.js +183 -0
  228. package/dist/esm/server/cors.js +220 -0
  229. package/dist/esm/server/index.js +47 -0
  230. package/dist/esm/server/rateLimit.js +201 -0
  231. package/dist/esm/server/safeFetch.js +447 -0
  232. package/dist/esm/server/securityHeaders.js +364 -0
  233. package/dist/esm/server/userInvalidation.js +152 -0
  234. package/dist/esm/server/verifySecret.js +47 -0
  235. package/dist/esm/session/SessionClient.js +861 -0
  236. package/dist/esm/session/accountDelegationAccess.js +45 -0
  237. package/dist/esm/session/accountDialogController.js +1126 -0
  238. package/dist/esm/session/accountSwitchTargets.js +77 -0
  239. package/dist/esm/session/authStateStore.js +398 -0
  240. package/dist/esm/session/createSessionClient.js +29 -0
  241. package/dist/esm/session/deviceDirectory.js +135 -0
  242. package/dist/esm/session/deviceSwitcherRows.js +72 -0
  243. package/dist/esm/session/identityPin.js +249 -0
  244. package/dist/esm/session/identitySession.js +131 -0
  245. package/dist/esm/session/projectSessionState.js +114 -0
  246. package/dist/esm/session/refresh.js +390 -0
  247. package/dist/esm/session/sessionClientHost.js +31 -0
  248. package/dist/esm/session/sharedDeviceCredential.js +239 -0
  249. package/dist/esm/session/socketLoader.js +19 -0
  250. package/dist/esm/shared/utils/colorUtils.js +143 -0
  251. package/dist/esm/shared/utils/errorUtils.js +170 -0
  252. package/dist/esm/shared/utils/index.js +15 -0
  253. package/dist/esm/shared/utils/networkUtils.js +173 -0
  254. package/dist/esm/shared/utils/themeUtils.js +98 -0
  255. package/dist/esm/utils/accountCacheSweep.js +75 -0
  256. package/dist/esm/utils/accountUtils.js +131 -0
  257. package/dist/esm/utils/activityId.js +2 -0
  258. package/dist/esm/utils/apiUtils.js +84 -0
  259. package/dist/esm/utils/asyncUtils.js +207 -0
  260. package/dist/esm/utils/authHelpers.js +111 -0
  261. package/dist/esm/utils/authWebUrl.js +16 -0
  262. package/dist/esm/utils/avatarUtils.js +26 -0
  263. package/dist/esm/utils/cache.js +227 -0
  264. package/dist/esm/utils/cacheKey.js +80 -0
  265. package/dist/esm/utils/coldBoot.js +119 -0
  266. package/dist/esm/utils/commonsApproval.js +27 -0
  267. package/dist/esm/utils/commonsDelivery.js +54 -0
  268. package/dist/esm/utils/deviceManager.js +170 -0
  269. package/dist/esm/utils/displayNamePolicyRanges.generated.js +57 -0
  270. package/dist/esm/utils/edgeRegion.js +2 -0
  271. package/dist/esm/utils/errorUtils.js +232 -0
  272. package/dist/esm/utils/identityCacheSweep.js +92 -0
  273. package/dist/esm/utils/languageUtils.js +212 -0
  274. package/dist/esm/utils/oauthPkce.js +297 -0
  275. package/dist/esm/utils/officialOrigins.js +59 -0
  276. package/dist/esm/utils/oxyServiceEnvironment.js +16 -0
  277. package/dist/esm/utils/platform.js +110 -0
  278. package/dist/esm/utils/profileLinks.js +60 -0
  279. package/dist/esm/utils/redactUrl.js +26 -0
  280. package/dist/esm/utils/registrableApex.js +42 -0
  281. package/dist/esm/utils/requestUtils.js +203 -0
  282. package/dist/esm/utils/sessionUtils.js +171 -0
  283. package/dist/esm/utils/textNormalization.js +154 -0
  284. package/dist/esm/utils/userHandle.js +33 -0
  285. package/dist/esm/utils/userIdentity.js +45 -0
  286. package/dist/esm/utils/validationUtils.js +350 -0
  287. package/dist/esm/utils/webauthnOrigin.js +48 -0
  288. package/dist/types/.tsbuildinfo +1 -0
  289. package/dist/types/HttpService.d.ts +413 -0
  290. package/dist/types/OxyServices.base.d.ts +187 -0
  291. package/dist/types/OxyServices.d.ts +139 -0
  292. package/dist/types/OxyServices.errors.d.ts +84 -0
  293. package/dist/types/boot/sessionColdBoot.d.ts +140 -0
  294. package/dist/types/constants/version.d.ts +13 -0
  295. package/dist/types/crypto/aead.d.ts +56 -0
  296. package/dist/types/crypto/ecdh.d.ts +29 -0
  297. package/dist/types/crypto/identityMarker.d.ts +94 -0
  298. package/dist/types/crypto/kdf.d.ts +25 -0
  299. package/dist/types/crypto/keyManager.d.ts +582 -0
  300. package/dist/types/crypto/polyfill.d.ts +25 -0
  301. package/dist/types/crypto/recoveryPhrase.d.ts +173 -0
  302. package/dist/types/crypto/signatureService.d.ts +136 -0
  303. package/dist/types/i18n/accountCategoryLabels.d.ts +34 -0
  304. package/dist/types/i18n/accountRoleLabels.d.ts +10 -0
  305. package/dist/types/i18n/index.d.ts +3 -0
  306. package/dist/types/i18n/reputationCategoryLabels.d.ts +10 -0
  307. package/dist/types/i18n/trustTierLabels.d.ts +9 -0
  308. package/dist/types/index.d.ts +145 -0
  309. package/dist/types/inference/OxyInferenceClient.d.ts +342 -0
  310. package/dist/types/logger/index.d.ts +104 -0
  311. package/dist/types/mixins/OxyServices.accounts.d.ts +868 -0
  312. package/dist/types/mixins/OxyServices.analytics.d.ts +72 -0
  313. package/dist/types/mixins/OxyServices.appData.d.ts +108 -0
  314. package/dist/types/mixins/OxyServices.assets.d.ts +329 -0
  315. package/dist/types/mixins/OxyServices.auth.d.ts +908 -0
  316. package/dist/types/mixins/OxyServices.chains.d.ts +156 -0
  317. package/dist/types/mixins/OxyServices.civic.d.ts +510 -0
  318. package/dist/types/mixins/OxyServices.connectedApps.d.ts +169 -0
  319. package/dist/types/mixins/OxyServices.contacts.d.ts +100 -0
  320. package/dist/types/mixins/OxyServices.deviceBoot.d.ts +185 -0
  321. package/dist/types/mixins/OxyServices.deviceTransfer.d.ts +149 -0
  322. package/dist/types/mixins/OxyServices.devices.d.ts +103 -0
  323. package/dist/types/mixins/OxyServices.features.d.ts +250 -0
  324. package/dist/types/mixins/OxyServices.followGraph.d.ts +223 -0
  325. package/dist/types/mixins/OxyServices.identity.d.ts +351 -0
  326. package/dist/types/mixins/OxyServices.identityBackup.d.ts +129 -0
  327. package/dist/types/mixins/OxyServices.inference.d.ts +95 -0
  328. package/dist/types/mixins/OxyServices.language.d.ts +87 -0
  329. package/dist/types/mixins/OxyServices.links.d.ts +104 -0
  330. package/dist/types/mixins/OxyServices.location.d.ts +70 -0
  331. package/dist/types/mixins/OxyServices.nodes.d.ts +198 -0
  332. package/dist/types/mixins/OxyServices.notifications.d.ts +143 -0
  333. package/dist/types/mixins/OxyServices.payment.d.ts +117 -0
  334. package/dist/types/mixins/OxyServices.privacy.d.ts +146 -0
  335. package/dist/types/mixins/OxyServices.reputation.d.ts +202 -0
  336. package/dist/types/mixins/OxyServices.security.d.ts +84 -0
  337. package/dist/types/mixins/OxyServices.store.d.ts +334 -0
  338. package/dist/types/mixins/OxyServices.topics.d.ts +110 -0
  339. package/dist/types/mixins/OxyServices.user.d.ts +558 -0
  340. package/dist/types/mixins/OxyServices.utility.d.ts +393 -0
  341. package/dist/types/mixins/index.d.ts +87 -0
  342. package/dist/types/mixins/mixinHelpers.d.ts +31 -0
  343. package/dist/types/models/Topic.d.ts +42 -0
  344. package/dist/types/models/interfaces.d.ts +675 -0
  345. package/dist/types/models/session.d.ts +51 -0
  346. package/dist/types/server/auth.d.ts +130 -0
  347. package/dist/types/server/capabilityTicket.d.ts +41 -0
  348. package/dist/types/server/cors.d.ts +98 -0
  349. package/dist/types/server/index.d.ts +35 -0
  350. package/dist/types/server/rateLimit.d.ts +40 -0
  351. package/dist/types/server/safeFetch.d.ts +137 -0
  352. package/dist/types/server/securityHeaders.d.ts +221 -0
  353. package/dist/types/server/userInvalidation.d.ts +114 -0
  354. package/dist/types/server/verifySecret.d.ts +29 -0
  355. package/dist/types/session/SessionClient.d.ts +418 -0
  356. package/dist/types/session/accountDelegationAccess.d.ts +40 -0
  357. package/dist/types/session/accountDialogController.d.ts +648 -0
  358. package/dist/types/session/accountSwitchTargets.d.ts +70 -0
  359. package/dist/types/session/authStateStore.d.ts +153 -0
  360. package/dist/types/session/createSessionClient.d.ts +30 -0
  361. package/dist/types/session/deviceDirectory.d.ts +182 -0
  362. package/dist/types/session/deviceSwitcherRows.d.ts +92 -0
  363. package/dist/types/session/identityPin.d.ts +87 -0
  364. package/dist/types/session/identitySession.d.ts +105 -0
  365. package/dist/types/session/projectSessionState.d.ts +74 -0
  366. package/dist/types/session/refresh.d.ts +179 -0
  367. package/dist/types/session/sessionClientHost.d.ts +18 -0
  368. package/dist/types/session/sharedDeviceCredential.d.ts +202 -0
  369. package/dist/types/session/socketLoader.d.ts +11 -0
  370. package/dist/types/shared/utils/colorUtils.d.ts +104 -0
  371. package/dist/types/shared/utils/errorUtils.d.ts +97 -0
  372. package/dist/types/shared/utils/index.d.ts +13 -0
  373. package/dist/types/shared/utils/networkUtils.d.ts +139 -0
  374. package/dist/types/shared/utils/themeUtils.d.ts +90 -0
  375. package/dist/types/utils/accountCacheSweep.d.ts +75 -0
  376. package/dist/types/utils/accountUtils.d.ts +100 -0
  377. package/dist/types/utils/activityId.d.ts +2 -0
  378. package/dist/types/utils/apiUtils.d.ts +95 -0
  379. package/dist/types/utils/asyncUtils.d.ts +62 -0
  380. package/dist/types/utils/authHelpers.d.ts +58 -0
  381. package/dist/types/utils/authWebUrl.d.ts +16 -0
  382. package/dist/types/utils/avatarUtils.d.ts +16 -0
  383. package/dist/types/utils/cache.d.ts +130 -0
  384. package/dist/types/utils/cacheKey.d.ts +66 -0
  385. package/dist/types/utils/coldBoot.d.ts +131 -0
  386. package/dist/types/utils/commonsApproval.d.ts +13 -0
  387. package/dist/types/utils/commonsDelivery.d.ts +105 -0
  388. package/dist/types/utils/deviceManager.d.ts +65 -0
  389. package/dist/types/utils/displayNamePolicyRanges.generated.d.ts +57 -0
  390. package/dist/types/utils/edgeRegion.d.ts +2 -0
  391. package/dist/types/utils/errorUtils.d.ts +125 -0
  392. package/dist/types/utils/identityCacheSweep.d.ts +80 -0
  393. package/dist/types/utils/languageUtils.d.ts +100 -0
  394. package/dist/types/utils/oauthPkce.d.ts +157 -0
  395. package/dist/types/utils/officialOrigins.d.ts +13 -0
  396. package/dist/types/utils/oxyServiceEnvironment.d.ts +17 -0
  397. package/dist/types/utils/platform.d.ts +49 -0
  398. package/dist/types/utils/profileLinks.d.ts +44 -0
  399. package/dist/types/utils/redactUrl.d.ts +17 -0
  400. package/dist/types/utils/registrableApex.d.ts +27 -0
  401. package/dist/types/utils/requestUtils.d.ts +123 -0
  402. package/dist/types/utils/sessionUtils.d.ts +54 -0
  403. package/dist/types/utils/textNormalization.d.ts +103 -0
  404. package/dist/types/utils/userHandle.d.ts +26 -0
  405. package/dist/types/utils/userIdentity.d.ts +21 -0
  406. package/dist/types/utils/validationUtils.d.ts +268 -0
  407. package/dist/types/utils/webauthnOrigin.d.ts +32 -0
  408. package/package.json +168 -0
  409. package/src/HttpService.ts +1553 -0
  410. package/src/OxyServices.base.ts +478 -0
  411. package/src/OxyServices.errors.ts +122 -0
  412. package/src/OxyServices.ts +172 -0
  413. package/src/__tests__/authSocket.test.ts +96 -0
  414. package/src/__tests__/httpServiceActivityId.test.ts +49 -0
  415. package/src/__tests__/httpServiceAuthSelfAwait.test.ts +108 -0
  416. package/src/__tests__/httpServiceCache.test.ts +318 -0
  417. package/src/__tests__/httpServiceCsrf.test.ts +235 -0
  418. package/src/__tests__/httpServiceFormEncoded.test.ts +142 -0
  419. package/src/__tests__/httpServiceQueueDeadlock.test.ts +128 -0
  420. package/src/__tests__/httpServiceUnwrapEnvelope.test.ts +115 -0
  421. package/src/__tests__/inSessionRefresh.test.ts +260 -0
  422. package/src/__tests__/linkedClient.test.ts +370 -0
  423. package/src/__tests__/parseHttpErrorBody.test.ts +116 -0
  424. package/src/__tests__/serverValueImportsDeclared.test.ts +120 -0
  425. package/src/__tests__/userIdentity.test.ts +143 -0
  426. package/src/boot/__tests__/sessionColdBoot.identity.test.ts +393 -0
  427. package/src/boot/__tests__/sessionColdBoot.sharedDevice.test.ts +325 -0
  428. package/src/boot/__tests__/sessionColdBoot.test.ts +570 -0
  429. package/src/boot/sessionColdBoot.ts +529 -0
  430. package/src/constants/version.ts +15 -0
  431. package/src/crypto/__tests__/backupMaterial.test.ts +86 -0
  432. package/src/crypto/__tests__/cryptoPrimitives.test.ts +226 -0
  433. package/src/crypto/__tests__/identityMocks.ts +125 -0
  434. package/src/crypto/__tests__/keyManager.atomicity.test.ts +272 -0
  435. package/src/crypto/__tests__/keyManager.cacheSafety.test.ts +175 -0
  436. package/src/crypto/__tests__/keyManager.identityStatus.test.ts +217 -0
  437. package/src/crypto/__tests__/keyManager.recoveryLadder.test.ts +179 -0
  438. package/src/crypto/__tests__/keyManager.recoveryMnemonic.test.ts +138 -0
  439. package/src/crypto/__tests__/keyManager.storageMigration.test.ts +227 -0
  440. package/src/crypto/__tests__/keyManager.test.ts +329 -0
  441. package/src/crypto/__tests__/polyfill.test.ts +109 -0
  442. package/src/crypto/__tests__/recoveryPhrase.test.ts +61 -0
  443. package/src/crypto/__tests__/scopedSeed.test.ts +126 -0
  444. package/src/crypto/__tests__/signChallengeShared.test.ts +63 -0
  445. package/src/crypto/__tests__/signedRecord.test.ts +230 -0
  446. package/src/crypto/aead.ts +97 -0
  447. package/src/crypto/ecdh.ts +37 -0
  448. package/src/crypto/identityMarker.ts +291 -0
  449. package/src/crypto/kdf.ts +43 -0
  450. package/src/crypto/keyManager.ts +2607 -0
  451. package/src/crypto/polyfill.ts +143 -0
  452. package/src/crypto/recoveryPhrase.ts +337 -0
  453. package/src/crypto/signatureService.ts +350 -0
  454. package/src/i18n/__tests__/accountCategoryLabels.test.ts +62 -0
  455. package/src/i18n/__tests__/accountRoleLabels.test.ts +54 -0
  456. package/src/i18n/__tests__/reputationCategoryLabels.test.ts +56 -0
  457. package/src/i18n/__tests__/trustTierLabels.test.ts +47 -0
  458. package/src/i18n/accountCategoryLabels.ts +44 -0
  459. package/src/i18n/accountRoleLabels.ts +26 -0
  460. package/src/i18n/index.ts +88 -0
  461. package/src/i18n/locales/ar-SA.json +282 -0
  462. package/src/i18n/locales/ca-ES.json +282 -0
  463. package/src/i18n/locales/de-DE.json +282 -0
  464. package/src/i18n/locales/en-US.json +2161 -0
  465. package/src/i18n/locales/es-ES.json +2161 -0
  466. package/src/i18n/locales/fr-FR.json +282 -0
  467. package/src/i18n/locales/it-IT.json +282 -0
  468. package/src/i18n/locales/ja-JP.json +282 -0
  469. package/src/i18n/locales/ko-KR.json +282 -0
  470. package/src/i18n/locales/pt-PT.json +282 -0
  471. package/src/i18n/locales/zh-CN.json +282 -0
  472. package/src/i18n/reputationCategoryLabels.ts +20 -0
  473. package/src/i18n/trustTierLabels.ts +18 -0
  474. package/src/index.ts +881 -0
  475. package/src/inference/OxyInferenceClient.ts +888 -0
  476. package/src/inference/__tests__/OxyInferenceClient.test.ts +834 -0
  477. package/src/logger/__tests__/logger.test.ts +207 -0
  478. package/src/logger/index.ts +217 -0
  479. package/src/mixins/OxyServices.accounts.ts +1330 -0
  480. package/src/mixins/OxyServices.analytics.ts +53 -0
  481. package/src/mixins/OxyServices.appData.ts +158 -0
  482. package/src/mixins/OxyServices.assets.ts +861 -0
  483. package/src/mixins/OxyServices.auth.ts +1858 -0
  484. package/src/mixins/OxyServices.chains.ts +134 -0
  485. package/src/mixins/OxyServices.civic.ts +945 -0
  486. package/src/mixins/OxyServices.connectedApps.ts +174 -0
  487. package/src/mixins/OxyServices.contacts.ts +73 -0
  488. package/src/mixins/OxyServices.deviceBoot.ts +210 -0
  489. package/src/mixins/OxyServices.deviceTransfer.ts +393 -0
  490. package/src/mixins/OxyServices.devices.ts +120 -0
  491. package/src/mixins/OxyServices.features.ts +454 -0
  492. package/src/mixins/OxyServices.followGraph.ts +293 -0
  493. package/src/mixins/OxyServices.identity.ts +705 -0
  494. package/src/mixins/OxyServices.identityBackup.ts +250 -0
  495. package/src/mixins/OxyServices.inference.ts +57 -0
  496. package/src/mixins/OxyServices.language.ts +144 -0
  497. package/src/mixins/OxyServices.links.ts +107 -0
  498. package/src/mixins/OxyServices.location.ts +46 -0
  499. package/src/mixins/OxyServices.nodes.ts +337 -0
  500. package/src/mixins/OxyServices.notifications.ts +142 -0
  501. package/src/mixins/OxyServices.payment.ts +163 -0
  502. package/src/mixins/OxyServices.privacy.ts +219 -0
  503. package/src/mixins/OxyServices.reputation.ts +436 -0
  504. package/src/mixins/OxyServices.security.ts +110 -0
  505. package/src/mixins/OxyServices.store.ts +585 -0
  506. package/src/mixins/OxyServices.topics.ts +169 -0
  507. package/src/mixins/OxyServices.user.ts +1137 -0
  508. package/src/mixins/OxyServices.utility.ts +1370 -0
  509. package/src/mixins/__tests__/OxyServices.civic.test.ts +1095 -0
  510. package/src/mixins/__tests__/OxyServices.deviceBoot.test.ts +124 -0
  511. package/src/mixins/__tests__/OxyServices.deviceTransfer.test.ts +271 -0
  512. package/src/mixins/__tests__/OxyServices.identity.test.ts +376 -0
  513. package/src/mixins/__tests__/OxyServices.links.test.ts +154 -0
  514. package/src/mixins/__tests__/OxyServices.nodes.test.ts +341 -0
  515. package/src/mixins/__tests__/OxyServices.rotateKey.test.ts +276 -0
  516. package/src/mixins/__tests__/OxyServices.serviceAssetMetadata.test.ts +192 -0
  517. package/src/mixins/__tests__/OxyServices.serviceAssetMetadataBySha.test.ts +135 -0
  518. package/src/mixins/__tests__/accounts.test.ts +727 -0
  519. package/src/mixins/__tests__/appData.test.ts +203 -0
  520. package/src/mixins/__tests__/assetCredentials.test.ts +47 -0
  521. package/src/mixins/__tests__/assetUpload.test.ts +191 -0
  522. package/src/mixins/__tests__/backgroundCredential.httpIntegration.test.ts +135 -0
  523. package/src/mixins/__tests__/chains.test.ts +113 -0
  524. package/src/mixins/__tests__/commonsSignIn.test.ts +1144 -0
  525. package/src/mixins/__tests__/connectedApps.test.ts +123 -0
  526. package/src/mixins/__tests__/deviceTokenMintPinned.test.ts +113 -0
  527. package/src/mixins/__tests__/discoveryErrorHandling.test.ts +266 -0
  528. package/src/mixins/__tests__/followCacheInvalidation.test.ts +173 -0
  529. package/src/mixins/__tests__/followGraph.test.ts +147 -0
  530. package/src/mixins/__tests__/followGraphPagination.test.ts +271 -0
  531. package/src/mixins/__tests__/getFileDownloadUrl.test.ts +346 -0
  532. package/src/mixins/__tests__/getFollowStatuses.test.ts +95 -0
  533. package/src/mixins/__tests__/getUsersByIds.test.ts +149 -0
  534. package/src/mixins/__tests__/identityBackup.test.ts +315 -0
  535. package/src/mixins/__tests__/identityWriteCacheInvalidation.test.ts +407 -0
  536. package/src/mixins/__tests__/inferenceFactory.test.ts +58 -0
  537. package/src/mixins/__tests__/onTokensChanged.test.ts +129 -0
  538. package/src/mixins/__tests__/preSessionSkipAuth.test.ts +284 -0
  539. package/src/mixins/__tests__/privacyCacheInvalidation.test.ts +155 -0
  540. package/src/mixins/__tests__/reputation.test.ts +522 -0
  541. package/src/mixins/__tests__/serviceAuth.test.ts +832 -0
  542. package/src/mixins/__tests__/serviceTokenJwks.test.ts +208 -0
  543. package/src/mixins/__tests__/store.test.ts +304 -0
  544. package/src/mixins/__tests__/topics.test.ts +156 -0
  545. package/src/mixins/__tests__/userReadCacheBypass.test.ts +129 -0
  546. package/src/mixins/__tests__/userTokenAuth.test.ts +746 -0
  547. package/src/mixins/__tests__/verifyChallenge.test.ts +130 -0
  548. package/src/mixins/__tests__/verifyServiceActingAs.test.ts +167 -0
  549. package/src/mixins/__tests__/webauthnAuth.test.ts +205 -0
  550. package/src/mixins/index.ts +201 -0
  551. package/src/mixins/mixinHelpers.ts +69 -0
  552. package/src/models/Topic.ts +46 -0
  553. package/src/models/interfaces.ts +786 -0
  554. package/src/models/session.ts +55 -0
  555. package/src/server/__tests__/auth.test.ts +78 -0
  556. package/src/server/__tests__/capabilityTicket.test.ts +111 -0
  557. package/src/server/__tests__/cors.socket.test.ts +225 -0
  558. package/src/server/__tests__/cors.test.ts +158 -0
  559. package/src/server/__tests__/rateLimit.test.ts +257 -0
  560. package/src/server/__tests__/safeFetch.test.ts +232 -0
  561. package/src/server/__tests__/securityHeaders.test.ts +348 -0
  562. package/src/server/__tests__/serviceTokenAttribution.test.ts +396 -0
  563. package/src/server/__tests__/userInvalidation.test.ts +203 -0
  564. package/src/server/__tests__/verifySecret.test.ts +40 -0
  565. package/src/server/auth.ts +271 -0
  566. package/src/server/capabilityTicket.ts +258 -0
  567. package/src/server/cors.ts +277 -0
  568. package/src/server/index.ts +136 -0
  569. package/src/server/rateLimit.ts +313 -0
  570. package/src/server/safeFetch.ts +586 -0
  571. package/src/server/securityHeaders.ts +467 -0
  572. package/src/server/userInvalidation.ts +199 -0
  573. package/src/server/verifySecret.ts +52 -0
  574. package/src/session/SessionClient.ts +1001 -0
  575. package/src/session/__tests__/SessionClient.additive.test.ts +153 -0
  576. package/src/session/__tests__/SessionClient.broadcastChannel.test.ts +114 -0
  577. package/src/session/__tests__/SessionClient.diagnostics.test.ts +91 -0
  578. package/src/session/__tests__/SessionClient.directory.test.ts +688 -0
  579. package/src/session/__tests__/SessionClient.httpIntegration.test.ts +65 -0
  580. package/src/session/__tests__/SessionClient.identityPin.test.ts +175 -0
  581. package/src/session/__tests__/SessionClient.rest.test.ts +119 -0
  582. package/src/session/__tests__/SessionClient.serverEvents.test.ts +72 -0
  583. package/src/session/__tests__/SessionClient.socket.test.ts +202 -0
  584. package/src/session/__tests__/SessionClient.socketFactory.test.ts +81 -0
  585. package/src/session/__tests__/SessionClient.state.test.ts +78 -0
  586. package/src/session/__tests__/SessionClient.switchTokenOrder.test.ts +170 -0
  587. package/src/session/__tests__/accountDelegationAccess.test.ts +104 -0
  588. package/src/session/__tests__/accountDialogController.test.ts +1969 -0
  589. package/src/session/__tests__/accountDialogShape.test.ts +118 -0
  590. package/src/session/__tests__/accountSwitchTargets.test.ts +137 -0
  591. package/src/session/__tests__/authStateStore.test.ts +451 -0
  592. package/src/session/__tests__/deviceDirectory.test.ts +422 -0
  593. package/src/session/__tests__/deviceSwitcherRows.test.ts +223 -0
  594. package/src/session/__tests__/identityPin.test.ts +131 -0
  595. package/src/session/__tests__/identitySession.test.ts +194 -0
  596. package/src/session/__tests__/projectSessionState.test.ts +105 -0
  597. package/src/session/__tests__/refresh.identityPin.test.ts +307 -0
  598. package/src/session/__tests__/refresh.test.ts +443 -0
  599. package/src/session/__tests__/sessionIntegration.test.ts +209 -0
  600. package/src/session/__tests__/sharedDeviceCredential.test.ts +300 -0
  601. package/src/session/accountDelegationAccess.ts +72 -0
  602. package/src/session/accountDialogController.ts +1494 -0
  603. package/src/session/accountSwitchTargets.ts +93 -0
  604. package/src/session/authStateStore.ts +502 -0
  605. package/src/session/createSessionClient.ts +39 -0
  606. package/src/session/deviceDirectory.ts +269 -0
  607. package/src/session/deviceSwitcherRows.ts +145 -0
  608. package/src/session/identityPin.ts +310 -0
  609. package/src/session/identitySession.ts +206 -0
  610. package/src/session/projectSessionState.ts +137 -0
  611. package/src/session/refresh.ts +517 -0
  612. package/src/session/sessionClientHost.ts +39 -0
  613. package/src/session/sharedDeviceCredential.ts +349 -0
  614. package/src/session/socketLoader.ts +30 -0
  615. package/src/shared/utils/colorUtils.ts +155 -0
  616. package/src/shared/utils/errorUtils.ts +181 -0
  617. package/src/shared/utils/index.ts +59 -0
  618. package/src/shared/utils/networkUtils.ts +248 -0
  619. package/src/shared/utils/themeUtils.ts +115 -0
  620. package/src/types/buffer.d.ts +97 -0
  621. package/src/types/expo-crypto.d.ts +16 -0
  622. package/src/types/expo-secure-store.d.ts +17 -0
  623. package/src/utils/__tests__/accountUtils.test.ts +151 -0
  624. package/src/utils/__tests__/activityId.test.ts +45 -0
  625. package/src/utils/__tests__/asyncUtils.test.ts +187 -0
  626. package/src/utils/__tests__/authWebUrl.test.ts +15 -0
  627. package/src/utils/__tests__/cacheKey.test.ts +0 -0
  628. package/src/utils/__tests__/coldBoot.test.ts +496 -0
  629. package/src/utils/__tests__/commonsApproval.test.ts +60 -0
  630. package/src/utils/__tests__/identityCacheSweep.test.ts +151 -0
  631. package/src/utils/__tests__/languageUtils.test.ts +219 -0
  632. package/src/utils/__tests__/oauthPkce.test.ts +272 -0
  633. package/src/utils/__tests__/officialOrigins.test.ts +31 -0
  634. package/src/utils/__tests__/oxyServiceEnvironment.test.ts +7 -0
  635. package/src/utils/__tests__/profileLinks.test.ts +180 -0
  636. package/src/utils/__tests__/redactUrl.test.ts +33 -0
  637. package/src/utils/__tests__/registrableApex.test.ts +62 -0
  638. package/src/utils/__tests__/textNormalization.test.ts +205 -0
  639. package/src/utils/__tests__/validationUtils.test.ts +703 -0
  640. package/src/utils/__tests__/webauthnOrigin.test.ts +83 -0
  641. package/src/utils/accountCacheSweep.ts +93 -0
  642. package/src/utils/accountUtils.ts +194 -0
  643. package/src/utils/activityId.ts +2 -0
  644. package/src/utils/apiUtils.ts +137 -0
  645. package/src/utils/asyncUtils.ts +280 -0
  646. package/src/utils/authHelpers.ts +148 -0
  647. package/src/utils/authWebUrl.ts +17 -0
  648. package/src/utils/avatarUtils.ts +39 -0
  649. package/src/utils/cache.ts +273 -0
  650. package/src/utils/cacheKey.ts +93 -0
  651. package/src/utils/coldBoot.ts +218 -0
  652. package/src/utils/commonsApproval.ts +39 -0
  653. package/src/utils/commonsDelivery.ts +132 -0
  654. package/src/utils/deviceManager.ts +203 -0
  655. package/src/utils/displayNamePolicyRanges.generated.ts +69 -0
  656. package/src/utils/edgeRegion.ts +2 -0
  657. package/src/utils/errorUtils.ts +352 -0
  658. package/src/utils/identityCacheSweep.ts +104 -0
  659. package/src/utils/languageUtils.ts +256 -0
  660. package/src/utils/oauthPkce.ts +392 -0
  661. package/src/utils/officialOrigins.ts +62 -0
  662. package/src/utils/oxyServiceEnvironment.ts +17 -0
  663. package/src/utils/platform.ts +139 -0
  664. package/src/utils/profileLinks.ts +91 -0
  665. package/src/utils/redactUrl.ts +28 -0
  666. package/src/utils/registrableApex.ts +41 -0
  667. package/src/utils/requestUtils.ts +237 -0
  668. package/src/utils/sessionUtils.ts +206 -0
  669. package/src/utils/textNormalization.ts +162 -0
  670. package/src/utils/userHandle.ts +49 -0
  671. package/src/utils/userIdentity.ts +60 -0
  672. package/src/utils/validationUtils.ts +390 -0
  673. package/src/utils/webauthnOrigin.ts +52 -0
@@ -0,0 +1,2234 @@
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
+ Object.defineProperty(exports, "__esModule", { value: true });
9
+ exports.KeyManager = exports.IdentityUnavailableError = exports.IdentityPersistError = exports.IdentityAlreadyExistsError = void 0;
10
+ const platform_1 = require("../utils/platform");
11
+ const protocol_1 = require("@oxy.so/protocol");
12
+ const secp256k1_1 = require("@oxy.so/protocol/secp256k1");
13
+ const logger_1 = require("../logger");
14
+ const kdf_1 = require("./kdf");
15
+ const identityMarker_1 = require("./identityMarker");
16
+ /**
17
+ * Thrown when an identity-mutating operation (createIdentity / importKeyPair)
18
+ * is invoked while a valid identity already exists on the device.
19
+ *
20
+ * The local private key IS the user's identity — overwriting it without
21
+ * explicit consent permanently loses access to their account (unless
22
+ * they previously saved their recovery phrase). This error forces callers
23
+ * to make an explicit, audited decision instead of silently clobbering.
24
+ */
25
+ class IdentityAlreadyExistsError extends Error {
26
+ constructor(existingPublicKey) {
27
+ super('An identity already exists on this device. Refusing to overwrite without explicit consent. ' +
28
+ 'If you really want to replace it, ensure the user has saved their recovery phrase, then call ' +
29
+ 'the operation with { overwrite: true }.');
30
+ this.name = 'IdentityAlreadyExistsError';
31
+ this.existingPublicKey = existingPublicKey;
32
+ }
33
+ }
34
+ exports.IdentityAlreadyExistsError = IdentityAlreadyExistsError;
35
+ /**
36
+ * Thrown when a freshly written identity cannot be read back, parsed, or
37
+ * round-tripped through sign/verify. Indicates a storage failure or
38
+ * corruption that would otherwise silently leave the user with an
39
+ * unusable account.
40
+ */
41
+ class IdentityPersistError extends Error {
42
+ constructor(message, cause) {
43
+ super(message);
44
+ this.cause = cause;
45
+ this.name = 'IdentityPersistError';
46
+ }
47
+ }
48
+ exports.IdentityPersistError = IdentityPersistError;
49
+ /**
50
+ * Thrown when identity storage cannot be read/written right now — the keychain
51
+ * is locked, the module failed to load, or a read threw — as opposed to the
52
+ * identity being genuinely absent.
53
+ *
54
+ * This is the crux of the corruption-vs-fresh-install fix: a storage THROW must
55
+ * NEVER be flattened into "no identity" (the old behavior, which let onboarding
56
+ * treat a momentarily-locked keystore as a blank device). Callers that used to
57
+ * tolerate a `false`/`null` from `hasIdentity()`/`getPublicKey()` on error must
58
+ * now treat this typed error as "cannot determine" — retry, surface a locked
59
+ * state, or abort a destructive path — never as "safe to create/overwrite".
60
+ */
61
+ class IdentityUnavailableError extends Error {
62
+ constructor(message, cause) {
63
+ super(message);
64
+ this.cause = cause;
65
+ this.name = 'IdentityUnavailableError';
66
+ }
67
+ }
68
+ exports.IdentityUnavailableError = IdentityUnavailableError;
69
+ /**
70
+ * HKDF salt that domain-separates every identity-scoped seed produced by
71
+ * {@link KeyManager.deriveScopedSeed}. Versioned so a future scheme change is a
72
+ * new, non-colliding tag. The per-app domain (e.g. Oxy Pay's FairCoin wallet)
73
+ * is carried by the caller's `info` string, not this salt.
74
+ */
75
+ const SCOPED_SEED_KDF_SALT = 'oxy-identity-scoped-seed-v1';
76
+ /** UTF-8 encode an ASCII label to bytes (HKDF salt/info). */
77
+ function utf8ToBytes(label) {
78
+ return new TextEncoder().encode(label);
79
+ }
80
+ /** Decode a hex string to bytes. Inverse of {@link uint8ArrayToHex}. */
81
+ function hexToBytes(hex) {
82
+ const out = new Uint8Array(hex.length / 2);
83
+ for (let i = 0; i < out.length; i++) {
84
+ out[i] = Number.parseInt(hex.slice(i * 2, i * 2 + 2), 16);
85
+ }
86
+ return out;
87
+ }
88
+ const STORAGE_KEYS = {
89
+ PRIVATE_KEY: 'oxy_identity_private_key',
90
+ PUBLIC_KEY: 'oxy_identity_public_key',
91
+ BACKUP_PRIVATE_KEY: 'oxy_identity_backup_private_key',
92
+ BACKUP_PUBLIC_KEY: 'oxy_identity_backup_public_key',
93
+ BACKUP_TIMESTAMP: 'oxy_identity_backup_timestamp',
94
+ // Shared keys accessible across all Oxy apps (iOS Keychain Group / Android Account Manager)
95
+ SHARED_PRIVATE_KEY: 'oxy_shared_identity_private_key',
96
+ SHARED_PUBLIC_KEY: 'oxy_shared_identity_public_key',
97
+ SHARED_SESSION_TOKEN: 'oxy_shared_session_token',
98
+ SHARED_SESSION_ID: 'oxy_shared_session_id',
99
+ };
100
+ /**
101
+ * v2 identity slot layout — blast-radius isolation.
102
+ *
103
+ * The legacy keys above were written WITHOUT a `keychainService`, so on Android
104
+ * they all shared expo-secure-store's single default `key_v1` AndroidKeyStore
105
+ * key — meaning ONE keystore invalidation deleted the primary AND the backup
106
+ * together (the exact loss this hardening closes). The v2 layout gives the
107
+ * primary and the backup DISTINCT keychain services (→ independent AndroidKeyStore
108
+ * keys, independent iOS keychain items), so they can no longer die together, and
109
+ * DISTINCT key names (`_v2`) so the post-copy migration verify can only observe
110
+ * what it actually wrote (old/new locations are non-aliasable).
111
+ *
112
+ * Migration from the legacy layout is lazy + verify-before-delete — see
113
+ * {@link KeyManager._runSlotMigration}.
114
+ */
115
+ const V2_PRIMARY_KEYCHAIN_SERVICE = 'oxy_identity';
116
+ const V2_BACKUP_KEYCHAIN_SERVICE = 'oxy_identity_backup';
117
+ const V2_STORAGE_KEYS = {
118
+ PRIVATE_KEY: 'oxy_identity_private_key_v2',
119
+ PUBLIC_KEY: 'oxy_identity_public_key_v2',
120
+ BACKUP_PRIVATE_KEY: 'oxy_identity_backup_private_key_v2',
121
+ BACKUP_PUBLIC_KEY: 'oxy_identity_backup_public_key_v2',
122
+ BACKUP_TIMESTAMP: 'oxy_identity_backup_timestamp_v2',
123
+ };
124
+ /**
125
+ * Dedicated keychain slot for the recovery mnemonic (the 12-word phrase).
126
+ *
127
+ * Stored under its OWN keychain service — distinct from the v2 primary, backup,
128
+ * and shared slots — so it shares an AndroidKeyStore key with none of them
129
+ * (blast-radius isolation, same rationale as the v2 primary/backup split).
130
+ * Written `WHEN_UNLOCKED_THIS_DEVICE_ONLY` and NEVER exported off-device: it
131
+ * exists solely so the user can RE-READ their phrase from Settings on the SAME
132
+ * device that generated/imported it.
133
+ *
134
+ * This is convenience persistence, NOT a recovery mechanism — a keystore death
135
+ * wipes it alongside the keys, exactly like the private key itself. The user's
136
+ * written-down phrase remains the sole out-of-band recovery path. The mnemonic
137
+ * lives ONLY in this slot: it is never mirrored into the identity marker,
138
+ * {@link KeyManager.getIdentityStatus}, logs, or any exported bundle.
139
+ */
140
+ const RECOVERY_MNEMONIC_KEYCHAIN_SERVICE = 'oxy_identity_mnemonic';
141
+ const RECOVERY_MNEMONIC_STORAGE_KEY = 'oxy_identity_mnemonic_v1';
142
+ /**
143
+ * Advisory AsyncStorage fast-path flag: set once the v2 slots own the identity.
144
+ * Re-derivable (its loss just re-runs the cheap slot check), so it lives in
145
+ * plain AsyncStorage rather than the keychain. It only SKIPS re-reading the
146
+ * legacy slots on an already-migrated device; it is never trusted over an actual
147
+ * v2 read (a set flag with an unhealthy v2 pair falls through to full migration).
148
+ */
149
+ const SLOTS_MIGRATED_FLAG_KEY = 'oxy_identity_slots_migrated_v2';
150
+ const V2_SLOT_LAYOUT = {
151
+ primaryService: V2_PRIMARY_KEYCHAIN_SERVICE,
152
+ primaryPrivateKeyName: V2_STORAGE_KEYS.PRIVATE_KEY,
153
+ primaryPublicKeyName: V2_STORAGE_KEYS.PUBLIC_KEY,
154
+ backupService: V2_BACKUP_KEYCHAIN_SERVICE,
155
+ backupPrivateKeyName: V2_STORAGE_KEYS.BACKUP_PRIVATE_KEY,
156
+ backupPublicKeyName: V2_STORAGE_KEYS.BACKUP_PUBLIC_KEY,
157
+ backupTimestampName: V2_STORAGE_KEYS.BACKUP_TIMESTAMP,
158
+ };
159
+ const LEGACY_SLOT_LAYOUT = {
160
+ primaryService: undefined,
161
+ primaryPrivateKeyName: STORAGE_KEYS.PRIVATE_KEY,
162
+ primaryPublicKeyName: STORAGE_KEYS.PUBLIC_KEY,
163
+ backupService: undefined,
164
+ backupPrivateKeyName: STORAGE_KEYS.BACKUP_PRIVATE_KEY,
165
+ backupPublicKeyName: STORAGE_KEYS.BACKUP_PUBLIC_KEY,
166
+ backupTimestampName: STORAGE_KEYS.BACKUP_TIMESTAMP,
167
+ };
168
+ /**
169
+ * iOS Keychain Access Group for sharing identities across Oxy apps
170
+ * All Oxy apps must have this access group enabled in their entitlements
171
+ * Format: [Team ID].so.oxy.shared or group.so.oxy.shared
172
+ */
173
+ const IOS_KEYCHAIN_GROUP = 'group.so.oxy.shared';
174
+ /**
175
+ * Android Account Manager type for shared authentication
176
+ * Used with sharedUserId to share sessions across apps
177
+ */
178
+ const ANDROID_ACCOUNT_TYPE = 'com.oxy.account';
179
+ /**
180
+ * Initialize React Native specific modules
181
+ *
182
+ * Delegates to `@oxy.so/protocol`'s `platform/crypto`, a per-platform module
183
+ * (`crypto.ts` vs `crypto.native.ts`) selected by the
184
+ * consumer's bundler. On RN it returns a statically-imported handle to
185
+ * `expo-secure-store`; off RN it throws (and is never called because every
186
+ * caller is gated by `isWebPlatform()` / native-only paths).
187
+ */
188
+ async function initSecureStore() {
189
+ try {
190
+ return await (0, protocol_1.loadSecureStore)();
191
+ }
192
+ catch (error) {
193
+ const errorMessage = error instanceof Error ? error.message : String(error);
194
+ throw new Error(`Failed to load expo-secure-store: ${errorMessage}. ` +
195
+ 'Make sure expo-secure-store is installed and properly configured.');
196
+ }
197
+ }
198
+ /**
199
+ * Check if we're on web platform
200
+ * Identity storage is only available on native platforms (iOS/Android)
201
+ */
202
+ function isWebPlatform() {
203
+ return (0, platform_1.isWeb)();
204
+ }
205
+ async function initExpoCrypto() {
206
+ // Same per-platform delegation as initSecureStore — see comment there.
207
+ return (0, protocol_1.loadExpoCrypto)();
208
+ }
209
+ /**
210
+ * Convert Uint8Array to hexadecimal string
211
+ * Works in both Node.js and React Native
212
+ */
213
+ function uint8ArrayToHex(bytes) {
214
+ return Array.from(bytes)
215
+ .map(b => b.toString(16).padStart(2, '0'))
216
+ .join('');
217
+ }
218
+ /**
219
+ * Generate cryptographically secure random bytes
220
+ */
221
+ async function getSecureRandomBytes(length) {
222
+ // In React Native, always use expo-crypto
223
+ if ((0, protocol_1.isReactNative)() || !(0, protocol_1.isNodeJS)()) {
224
+ const Crypto = await initExpoCrypto();
225
+ return Crypto.getRandomBytes(length);
226
+ }
227
+ // In Node.js, use Node's crypto module.
228
+ //
229
+ // `loadNodeCrypto` is per-platform: the default variant performs
230
+ // `await import('crypto')`, the RN variant throws (and we'd never reach
231
+ // here on RN because the early-return above caught it).
232
+ try {
233
+ const nodeCrypto = await (0, protocol_1.loadNodeCrypto)();
234
+ return new Uint8Array(nodeCrypto.randomBytes(length));
235
+ }
236
+ catch (error) {
237
+ // Fallback to expo-crypto if Node crypto fails (defensive — should not
238
+ // happen on real Node, but the platform-detection edge cases are
239
+ // surprisingly varied).
240
+ const Crypto = await initExpoCrypto();
241
+ return Crypto.getRandomBytes(length);
242
+ }
243
+ }
244
+ class KeyManager {
245
+ /**
246
+ * Invalidate cached identity state
247
+ * Called internally when identity is created/deleted/imported
248
+ */
249
+ static invalidateCache() {
250
+ KeyManager.cachedPublicKey = null;
251
+ KeyManager.cachedHasIdentity = null;
252
+ KeyManager.cachedPublicKeyResolved = false;
253
+ KeyManager.notifyIdentityChanged();
254
+ }
255
+ /**
256
+ * Subscribe to identity-verdict changes (create / import / delete / restore /
257
+ * cache invalidation). Fires synchronously; the returned function unsubscribes.
258
+ * Consumed via `useOxyEvent`-style hooks in commons to invalidate the routing
259
+ * queries the instant the identity state moves, without polling.
260
+ */
261
+ static subscribeIdentityChanged(listener) {
262
+ KeyManager.identityChangeListeners.add(listener);
263
+ return () => {
264
+ KeyManager.identityChangeListeners.delete(listener);
265
+ };
266
+ }
267
+ /** Synchronous fan-out with per-listener isolation (one throwing listener never blocks the rest). */
268
+ static notifyIdentityChanged() {
269
+ // Snapshot first — a listener may unsubscribe (mutate the Set) during fan-out.
270
+ for (const listener of Array.from(KeyManager.identityChangeListeners)) {
271
+ try {
272
+ listener();
273
+ }
274
+ catch (error) {
275
+ logger_1.logger.warn('Identity-change listener threw', { component: 'KeyManager' }, error);
276
+ }
277
+ }
278
+ }
279
+ /** Build `getItemAsync`/`deleteItemAsync` options for a given keychain service (read/delete). */
280
+ static _slotOpts(service) {
281
+ return service ? { keychainService: service } : {};
282
+ }
283
+ /** Build private-key write options (device-only accessibility) for a given keychain service. */
284
+ static _privateWriteOpts(store, service) {
285
+ const opts = { keychainAccessible: store.WHEN_UNLOCKED_THIS_DEVICE_ONLY };
286
+ if (service) {
287
+ opts.keychainService = service;
288
+ }
289
+ return opts;
290
+ }
291
+ /** True only when both keys are present, well-formed, AND the public derives from the private. */
292
+ static _isHealthyPair(privateKey, publicKey) {
293
+ if (!privateKey || !publicKey) {
294
+ return false;
295
+ }
296
+ if (!KeyManager.isValidPrivateKey(privateKey) || !KeyManager.isValidPublicKey(publicKey)) {
297
+ return false;
298
+ }
299
+ try {
300
+ return KeyManager.derivePublicKey(privateKey).toLowerCase() === publicKey.toLowerCase();
301
+ }
302
+ catch {
303
+ return false;
304
+ }
305
+ }
306
+ /**
307
+ * Resolve the AsyncStorage-backed KV store for the advisory migration flag, or
308
+ * `null` off-RN / when unavailable. Independent of the keychain, so the flag
309
+ * cannot be taken down by the keystore event this whole subsystem defends
310
+ * against.
311
+ */
312
+ static async _advisoryStorage() {
313
+ if (!(0, protocol_1.isReactNative)()) {
314
+ return null;
315
+ }
316
+ try {
317
+ const mod = await (0, protocol_1.loadAsyncStorage)();
318
+ return mod.default;
319
+ }
320
+ catch {
321
+ // Advisory only — absence just means the slot check runs in full.
322
+ return null;
323
+ }
324
+ }
325
+ static async _readSlotsMigratedFlag() {
326
+ const storage = await KeyManager._advisoryStorage();
327
+ if (!storage) {
328
+ return false;
329
+ }
330
+ try {
331
+ return (await storage.getItem(SLOTS_MIGRATED_FLAG_KEY)) === 'true';
332
+ }
333
+ catch {
334
+ // Advisory only — treat an unreadable flag as "not yet migrated".
335
+ return false;
336
+ }
337
+ }
338
+ static async _setSlotsMigratedFlag() {
339
+ const storage = await KeyManager._advisoryStorage();
340
+ if (!storage) {
341
+ return;
342
+ }
343
+ try {
344
+ await storage.setItem(SLOTS_MIGRATED_FLAG_KEY, 'true');
345
+ }
346
+ catch (error) {
347
+ // Advisory only — a failed write just re-runs the cheap slot check next launch.
348
+ if ((0, logger_1.isDev)()) {
349
+ logger_1.logger.debug('Failed to set slots-migrated flag (advisory)', { component: 'KeyManager' }, error);
350
+ }
351
+ }
352
+ }
353
+ /**
354
+ * Ensure the identity has been migrated onto the isolated v2 slots (or that we
355
+ * know we must read legacy this session). Memoized so concurrent callers share
356
+ * ONE run; a `deferred` (read-threw) outcome is not cached so a later call
357
+ * retries after the keychain unlocks. Every identity-slot accessor awaits this
358
+ * before touching storage.
359
+ */
360
+ static async _ensureIdentitySlotsMigrated() {
361
+ if (KeyManager.slotMigrationResult && KeyManager.slotMigrationResult.mode !== 'deferred') {
362
+ return KeyManager.slotMigrationResult;
363
+ }
364
+ if (!KeyManager.slotMigrationPromise) {
365
+ const run = (async () => {
366
+ const result = await KeyManager._runSlotMigration();
367
+ KeyManager.slotMigrationResult = result;
368
+ return result;
369
+ })();
370
+ KeyManager.slotMigrationPromise = run;
371
+ // Clear the in-flight handle once settled so a deferred outcome retries.
372
+ run
373
+ .then((result) => {
374
+ if (result.mode === 'deferred') {
375
+ KeyManager.slotMigrationPromise = null;
376
+ }
377
+ })
378
+ .catch(() => {
379
+ KeyManager.slotMigrationPromise = null;
380
+ });
381
+ }
382
+ return KeyManager.slotMigrationPromise;
383
+ }
384
+ /**
385
+ * One-shot slot migration state machine. All reads are DIRECT and a thrown
386
+ * read defers everything (zero writes/deletes) so a locked keychain is never
387
+ * mistaken for an empty one. INVARIANT: at every instant ≥1 readable copy of a
388
+ * previously-existing identity remains — legacy is deleted ONLY after the v2
389
+ * copy is verified re-readable in its new (non-aliasable) location.
390
+ */
391
+ static async _runSlotMigration() {
392
+ let store;
393
+ try {
394
+ store = await initSecureStore();
395
+ }
396
+ catch (error) {
397
+ return { mode: 'deferred', cause: error };
398
+ }
399
+ const migratedFlag = await KeyManager._readSlotsMigratedFlag();
400
+ // Read the v2 primary (dedicated keychain service).
401
+ let v2Private;
402
+ let v2Public;
403
+ try {
404
+ v2Private = await store.getItemAsync(V2_STORAGE_KEYS.PRIVATE_KEY, KeyManager._slotOpts(V2_PRIMARY_KEYCHAIN_SERVICE));
405
+ v2Public = await store.getItemAsync(V2_STORAGE_KEYS.PUBLIC_KEY, KeyManager._slotOpts(V2_PRIMARY_KEYCHAIN_SERVICE));
406
+ }
407
+ catch (error) {
408
+ return { mode: 'deferred', cause: error };
409
+ }
410
+ if (KeyManager._isHealthyPair(v2Private, v2Public)) {
411
+ // v2 already owns the identity. On the first observation, clean up any
412
+ // stale legacy copy and record the fast-path flag.
413
+ if (!migratedFlag) {
414
+ await KeyManager._bestEffortDeleteLegacyPrimaryAndBackup(store);
415
+ await KeyManager._setSlotsMigratedFlag();
416
+ }
417
+ return { mode: 'v2', layout: V2_SLOT_LAYOUT };
418
+ }
419
+ // v2 primary absent/partial but the flag says migration finished → v2 is
420
+ // simply empty (identity deleted / never created). No legacy to rescue.
421
+ if (migratedFlag) {
422
+ return { mode: 'v2', layout: V2_SLOT_LAYOUT };
423
+ }
424
+ // Read the legacy primary (default keychain service = the old `key_v1`).
425
+ let legacyPrivate;
426
+ let legacyPublic;
427
+ try {
428
+ legacyPrivate = await store.getItemAsync(STORAGE_KEYS.PRIVATE_KEY);
429
+ legacyPublic = await store.getItemAsync(STORAGE_KEYS.PUBLIC_KEY);
430
+ }
431
+ catch (error) {
432
+ return { mode: 'deferred', cause: error };
433
+ }
434
+ if (!KeyManager._isHealthyPair(legacyPrivate, legacyPublic)) {
435
+ // Nothing readable in either generation → v2 is the canonical (empty) home.
436
+ // The marker (not this migration) decides fresh-vs-lost.
437
+ return { mode: 'v2', layout: V2_SLOT_LAYOUT };
438
+ }
439
+ // legacy healthy, v2 absent → migrate: copy → read-back verify → only then delete legacy.
440
+ const canonicalPrivate = KeyManager.canonicalPrivateKey(legacyPrivate);
441
+ const canonicalPublic = legacyPublic.toLowerCase();
442
+ try {
443
+ await store.setItemAsync(V2_STORAGE_KEYS.PUBLIC_KEY, canonicalPublic, KeyManager._slotOpts(V2_PRIMARY_KEYCHAIN_SERVICE));
444
+ await store.setItemAsync(V2_STORAGE_KEYS.PRIVATE_KEY, canonicalPrivate, KeyManager._privateWriteOpts(store, V2_PRIMARY_KEYCHAIN_SERVICE));
445
+ const readBackPrivate = await store.getItemAsync(V2_STORAGE_KEYS.PRIVATE_KEY, KeyManager._slotOpts(V2_PRIMARY_KEYCHAIN_SERVICE));
446
+ const readBackPublic = await store.getItemAsync(V2_STORAGE_KEYS.PUBLIC_KEY, KeyManager._slotOpts(V2_PRIMARY_KEYCHAIN_SERVICE));
447
+ const verified = readBackPrivate?.toLowerCase() === canonicalPrivate &&
448
+ readBackPublic?.toLowerCase() === canonicalPublic &&
449
+ KeyManager._isHealthyPair(readBackPrivate, readBackPublic);
450
+ if (!verified) {
451
+ // v2 write did not durably land — remove the partial v2 and serve reads
452
+ // from legacy this session (legacy is UNTOUCHED). Retry next launch.
453
+ await KeyManager._bestEffortDeleteV2Primary(store);
454
+ logger_1.logger.warn('Identity slot migration verify failed; serving identity from legacy slots this session', { component: 'KeyManager' });
455
+ return { mode: 'legacy', layout: LEGACY_SLOT_LAYOUT };
456
+ }
457
+ }
458
+ catch (error) {
459
+ await KeyManager._bestEffortDeleteV2Primary(store);
460
+ logger_1.logger.warn('Identity slot migration write threw; serving identity from legacy slots this session', { component: 'KeyManager' }, error);
461
+ return { mode: 'legacy', layout: LEGACY_SLOT_LAYOUT };
462
+ }
463
+ // v2 primary is verified re-readable. Migrate the backup slot (best-effort),
464
+ // then it is finally safe to delete the legacy generation.
465
+ await KeyManager._migrateBackupSlotToV2(store, canonicalPrivate, canonicalPublic);
466
+ await KeyManager._bestEffortDeleteLegacyPrimaryAndBackup(store);
467
+ await KeyManager._setSlotsMigratedFlag();
468
+ return { mode: 'v2', layout: V2_SLOT_LAYOUT };
469
+ }
470
+ /**
471
+ * Seed the v2 backup slot during migration. Prefers a healthy legacy backup;
472
+ * otherwise mirrors the (already-verified) v2 primary material so a v2 backup
473
+ * always exists on an independent keychain key. Best-effort — a failure just
474
+ * defers backup population to the next {@link _persistIdentityAtomic}.
475
+ */
476
+ static async _migrateBackupSlotToV2(store, primaryPrivate, primaryPublic) {
477
+ try {
478
+ let backupPrivate = null;
479
+ let backupPublic = null;
480
+ try {
481
+ backupPrivate = await store.getItemAsync(STORAGE_KEYS.BACKUP_PRIVATE_KEY);
482
+ backupPublic = await store.getItemAsync(STORAGE_KEYS.BACKUP_PUBLIC_KEY);
483
+ }
484
+ catch (error) {
485
+ if ((0, logger_1.isDev)()) {
486
+ logger_1.logger.debug('Legacy backup unreadable during migration (non-fatal)', { component: 'KeyManager' }, error);
487
+ }
488
+ backupPrivate = null;
489
+ backupPublic = null;
490
+ }
491
+ let seedPrivate;
492
+ let seedPublic;
493
+ if (KeyManager._isHealthyPair(backupPrivate, backupPublic)) {
494
+ seedPrivate = KeyManager.canonicalPrivateKey(backupPrivate);
495
+ seedPublic = backupPublic.toLowerCase();
496
+ }
497
+ else {
498
+ seedPrivate = primaryPrivate;
499
+ seedPublic = primaryPublic;
500
+ }
501
+ await store.setItemAsync(V2_STORAGE_KEYS.BACKUP_PUBLIC_KEY, seedPublic, KeyManager._slotOpts(V2_BACKUP_KEYCHAIN_SERVICE));
502
+ await store.setItemAsync(V2_STORAGE_KEYS.BACKUP_PRIVATE_KEY, seedPrivate, KeyManager._privateWriteOpts(store, V2_BACKUP_KEYCHAIN_SERVICE));
503
+ await store.setItemAsync(V2_STORAGE_KEYS.BACKUP_TIMESTAMP, Date.now().toString(), KeyManager._slotOpts(V2_BACKUP_KEYCHAIN_SERVICE));
504
+ }
505
+ catch (error) {
506
+ logger_1.logger.warn('Failed to migrate identity backup slot to v2 (non-fatal)', { component: 'KeyManager' }, error);
507
+ }
508
+ }
509
+ /** Best-effort single delete under an optional keychain service. Cleanup only — never surfaces. */
510
+ static async _bestEffortDelete(store, key, service) {
511
+ try {
512
+ await store.deleteItemAsync(key, KeyManager._slotOpts(service));
513
+ }
514
+ catch (error) {
515
+ if ((0, logger_1.isDev)()) {
516
+ logger_1.logger.debug('Best-effort identity delete failed', { component: 'KeyManager' }, error);
517
+ }
518
+ }
519
+ }
520
+ static async _bestEffortDeleteV2Primary(store) {
521
+ await KeyManager._bestEffortDelete(store, V2_STORAGE_KEYS.PRIVATE_KEY, V2_PRIMARY_KEYCHAIN_SERVICE);
522
+ await KeyManager._bestEffortDelete(store, V2_STORAGE_KEYS.PUBLIC_KEY, V2_PRIMARY_KEYCHAIN_SERVICE);
523
+ }
524
+ static async _bestEffortDeleteLegacyPrimaryAndBackup(store) {
525
+ await KeyManager._bestEffortDelete(store, STORAGE_KEYS.PRIVATE_KEY);
526
+ await KeyManager._bestEffortDelete(store, STORAGE_KEYS.PUBLIC_KEY);
527
+ await KeyManager._bestEffortDelete(store, STORAGE_KEYS.BACKUP_PRIVATE_KEY);
528
+ await KeyManager._bestEffortDelete(store, STORAGE_KEYS.BACKUP_PUBLIC_KEY);
529
+ await KeyManager._bestEffortDelete(store, STORAGE_KEYS.BACKUP_TIMESTAMP);
530
+ }
531
+ static async _bestEffortDeleteBackupsAllGenerations(store) {
532
+ await KeyManager._bestEffortDelete(store, V2_STORAGE_KEYS.BACKUP_PRIVATE_KEY, V2_BACKUP_KEYCHAIN_SERVICE);
533
+ await KeyManager._bestEffortDelete(store, V2_STORAGE_KEYS.BACKUP_PUBLIC_KEY, V2_BACKUP_KEYCHAIN_SERVICE);
534
+ await KeyManager._bestEffortDelete(store, V2_STORAGE_KEYS.BACKUP_TIMESTAMP, V2_BACKUP_KEYCHAIN_SERVICE);
535
+ await KeyManager._bestEffortDelete(store, STORAGE_KEYS.BACKUP_PRIVATE_KEY);
536
+ await KeyManager._bestEffortDelete(store, STORAGE_KEYS.BACKUP_PUBLIC_KEY);
537
+ await KeyManager._bestEffortDelete(store, STORAGE_KEYS.BACKUP_TIMESTAMP);
538
+ }
539
+ /**
540
+ * Clear the cross-app shared identity slot (force-delete only) so a deleted
541
+ * identity cannot be resurrected via the recovery ladder's shared rung.
542
+ * Best-effort — the shared slot is a redundant convenience copy.
543
+ */
544
+ static async _clearSharedSlot(store) {
545
+ try {
546
+ if ((0, platform_1.isIOS)()) {
547
+ const opts = { keychainAccessGroup: IOS_KEYCHAIN_GROUP };
548
+ await store.deleteItemAsync(STORAGE_KEYS.SHARED_PRIVATE_KEY, opts);
549
+ await store.deleteItemAsync(STORAGE_KEYS.SHARED_PUBLIC_KEY, opts);
550
+ }
551
+ else if ((0, platform_1.isAndroid)()) {
552
+ const bridge = await (0, protocol_1.loadSharedIdentityBridge)();
553
+ if (bridge) {
554
+ await bridge.clearShared();
555
+ }
556
+ else {
557
+ await store.deleteItemAsync(STORAGE_KEYS.SHARED_PRIVATE_KEY);
558
+ await store.deleteItemAsync(STORAGE_KEYS.SHARED_PUBLIC_KEY);
559
+ }
560
+ }
561
+ KeyManager.invalidateSharedCache();
562
+ }
563
+ catch (error) {
564
+ logger_1.logger.warn('Failed to clear shared identity slot during force delete', { component: 'KeyManager' }, error);
565
+ }
566
+ }
567
+ /**
568
+ * Invalidate cached shared identity state
569
+ * Called internally when shared identity is created/deleted/imported
570
+ */
571
+ static invalidateSharedCache() {
572
+ KeyManager.cachedSharedPublicKey = null;
573
+ KeyManager.cachedHasSharedIdentity = null;
574
+ }
575
+ /**
576
+ * Lowercase and pad to canonical 64-hex-char form.
577
+ *
578
+ * Tolerates legacy leading-zero-stripped keys and externally imported
579
+ * uppercase hex. Every derivation path canonicalizes first so storage
580
+ * representation cannot change the resulting identity.
581
+ *
582
+ * Private (used only inside KeyManager) — public consumers should not need
583
+ * to think about hex representation.
584
+ */
585
+ static canonicalPrivateKey(key) {
586
+ return (0, secp256k1_1.normalizeSecp256k1PrivateKey)(key);
587
+ }
588
+ /**
589
+ * Generate a new ECDSA secp256k1 key pair
590
+ * Returns the keys in hexadecimal format
591
+ */
592
+ static generateKeyPairSync() {
593
+ return (0, secp256k1_1.generateSecp256k1KeyPair)();
594
+ }
595
+ /**
596
+ * Generate a new key pair using secure random bytes
597
+ */
598
+ static async generateKeyPair() {
599
+ for (let attempt = 0; attempt < 128; attempt += 1) {
600
+ const privateKey = uint8ArrayToHex(await getSecureRandomBytes(32));
601
+ if ((0, secp256k1_1.isValidSecp256k1PrivateKey)(privateKey)) {
602
+ return { privateKey, publicKey: (0, secp256k1_1.deriveSecp256k1PublicKey)(privateKey) };
603
+ }
604
+ }
605
+ throw new Error('Unable to generate a valid secp256k1 private key');
606
+ }
607
+ // ==================== SHARED IDENTITY METHODS ====================
608
+ // These methods enable cross-app session sharing (like Google)
609
+ // iOS: Uses Keychain Access Groups
610
+ // Android: Uses Account Manager with shared user ID
611
+ // =================================================================
612
+ /**
613
+ * Create a shared identity accessible across all Oxy apps
614
+ *
615
+ * iOS: Stores in shared keychain group (requires entitlement configuration)
616
+ * Android: Stores in Account Manager (requires sharedUserId in manifest)
617
+ *
618
+ * This enables true cross-app SSO - when user signs in to one Oxy app,
619
+ * they're automatically signed in to all other Oxy apps.
620
+ *
621
+ * @returns Public key of the shared identity
622
+ * @throws Error if not on native platform or if sharing is not configured
623
+ */
624
+ static async createSharedIdentity() {
625
+ if (isWebPlatform()) {
626
+ throw new Error('Shared identity is only available on native platforms (iOS/Android).');
627
+ }
628
+ const store = await initSecureStore();
629
+ const { privateKey, publicKey } = await KeyManager.generateKeyPair();
630
+ if ((0, platform_1.isIOS)()) {
631
+ // iOS: Store in shared keychain group
632
+ // Note: keychainAccessGroup requires Keychain Sharing capability in Xcode
633
+ try {
634
+ const privateOpts = {
635
+ keychainAccessible: store.WHEN_UNLOCKED_THIS_DEVICE_ONLY,
636
+ keychainAccessGroup: IOS_KEYCHAIN_GROUP, // Enables sharing across apps
637
+ };
638
+ await store.setItemAsync(STORAGE_KEYS.SHARED_PRIVATE_KEY, privateKey, privateOpts);
639
+ const publicOpts = {
640
+ keychainAccessGroup: IOS_KEYCHAIN_GROUP,
641
+ };
642
+ await store.setItemAsync(STORAGE_KEYS.SHARED_PUBLIC_KEY, publicKey, publicOpts);
643
+ }
644
+ catch (error) {
645
+ 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}`);
646
+ }
647
+ }
648
+ else if ((0, platform_1.isAndroid)()) {
649
+ // Android: write through the cross-app bridge (`@oxy.so/expo-oxy-identity`)
650
+ // when present — it persists into Commons's hardware-backed
651
+ // EncryptedSharedPreferences behind a signature-protected ContentProvider,
652
+ // so same-key Oxy apps can read it. When the bridge is not linked, fall
653
+ // back to the package-private secure store (no cross-app sharing).
654
+ const bridge = await (0, protocol_1.loadSharedIdentityBridge)();
655
+ if (bridge) {
656
+ await bridge.putShared(privateKey, publicKey);
657
+ }
658
+ else {
659
+ await store.setItemAsync(STORAGE_KEYS.SHARED_PRIVATE_KEY, privateKey, {
660
+ keychainAccessible: store.WHEN_UNLOCKED_THIS_DEVICE_ONLY,
661
+ });
662
+ await store.setItemAsync(STORAGE_KEYS.SHARED_PUBLIC_KEY, publicKey);
663
+ }
664
+ }
665
+ // Update cache
666
+ KeyManager.cachedSharedPublicKey = publicKey;
667
+ KeyManager.cachedHasSharedIdentity = true;
668
+ if ((0, logger_1.isDev)()) {
669
+ logger_1.logger.debug('Shared identity created successfully', { component: 'KeyManager' });
670
+ }
671
+ return publicKey;
672
+ }
673
+ /**
674
+ * Get the shared public key (accessible across all Oxy apps)
675
+ *
676
+ * @returns Shared public key or null if no shared identity exists
677
+ */
678
+ static async getSharedPublicKey() {
679
+ if (isWebPlatform()) {
680
+ return null;
681
+ }
682
+ // Return cached value if available
683
+ if (KeyManager.cachedSharedPublicKey !== null) {
684
+ return KeyManager.cachedSharedPublicKey;
685
+ }
686
+ try {
687
+ const store = await initSecureStore();
688
+ let publicKey = null;
689
+ if ((0, platform_1.isIOS)()) {
690
+ const opts = { keychainAccessGroup: IOS_KEYCHAIN_GROUP };
691
+ publicKey = await store.getItemAsync(STORAGE_KEYS.SHARED_PUBLIC_KEY, opts);
692
+ }
693
+ else if ((0, platform_1.isAndroid)()) {
694
+ // Android reads through the cross-app bridge; when it is not linked, fall
695
+ // back to the package-private store the fallback write path used.
696
+ const bridge = await (0, protocol_1.loadSharedIdentityBridge)();
697
+ if (bridge) {
698
+ publicKey = (await bridge.getShared())?.publicKey ?? null;
699
+ }
700
+ else {
701
+ publicKey = await store.getItemAsync(STORAGE_KEYS.SHARED_PUBLIC_KEY);
702
+ }
703
+ }
704
+ // Cache result
705
+ KeyManager.cachedSharedPublicKey = publicKey;
706
+ return publicKey;
707
+ }
708
+ catch (error) {
709
+ if ((0, logger_1.isDev)()) {
710
+ logger_1.logger.warn('Failed to get shared public key', { component: 'KeyManager' }, error);
711
+ }
712
+ KeyManager.cachedSharedPublicKey = null;
713
+ return null;
714
+ }
715
+ }
716
+ /**
717
+ * Get the shared private key (for signing operations)
718
+ *
719
+ * WARNING: Only use this for signing operations within the app.
720
+ * The private key should NEVER be transmitted or exposed.
721
+ *
722
+ * @returns Shared private key or null if no shared identity exists
723
+ */
724
+ static async getSharedPrivateKey() {
725
+ if (isWebPlatform()) {
726
+ return null;
727
+ }
728
+ try {
729
+ const store = await initSecureStore();
730
+ let privateKey = null;
731
+ if ((0, platform_1.isIOS)()) {
732
+ const opts = { keychainAccessGroup: IOS_KEYCHAIN_GROUP };
733
+ privateKey = await store.getItemAsync(STORAGE_KEYS.SHARED_PRIVATE_KEY, opts);
734
+ }
735
+ else if ((0, platform_1.isAndroid)()) {
736
+ // Android reads through the cross-app bridge; when it is not linked, fall
737
+ // back to the package-private store the fallback write path used.
738
+ const bridge = await (0, protocol_1.loadSharedIdentityBridge)();
739
+ if (bridge) {
740
+ privateKey = (await bridge.getShared())?.privateKey ?? null;
741
+ }
742
+ else {
743
+ privateKey = await store.getItemAsync(STORAGE_KEYS.SHARED_PRIVATE_KEY);
744
+ }
745
+ }
746
+ return privateKey;
747
+ }
748
+ catch (error) {
749
+ if ((0, logger_1.isDev)()) {
750
+ logger_1.logger.warn('Failed to get shared private key', { component: 'KeyManager' }, error);
751
+ }
752
+ return null;
753
+ }
754
+ }
755
+ /**
756
+ * Check if a shared identity exists (accessible across all Oxy apps)
757
+ *
758
+ * @returns True if shared identity exists, false otherwise
759
+ */
760
+ static async hasSharedIdentity() {
761
+ if (isWebPlatform()) {
762
+ return false;
763
+ }
764
+ // Return cached value if available
765
+ if (KeyManager.cachedHasSharedIdentity !== null) {
766
+ return KeyManager.cachedHasSharedIdentity;
767
+ }
768
+ try {
769
+ const privateKey = await KeyManager.getSharedPrivateKey();
770
+ const hasShared = privateKey !== null;
771
+ // Cache result
772
+ KeyManager.cachedHasSharedIdentity = hasShared;
773
+ return hasShared;
774
+ }
775
+ catch (error) {
776
+ if ((0, logger_1.isDev)()) {
777
+ logger_1.logger.warn('Failed to check shared identity', { component: 'KeyManager' }, error);
778
+ }
779
+ KeyManager.cachedHasSharedIdentity = false;
780
+ return false;
781
+ }
782
+ }
783
+ /**
784
+ * Import an existing key pair as shared identity
785
+ *
786
+ * This is used when:
787
+ * 1. User signs in to a new Oxy app for the first time
788
+ * 2. User has existing identity on another Oxy app
789
+ * 3. We want to sync the identity across apps
790
+ *
791
+ * @param privateKey - Private key in hex format
792
+ * @returns Public key
793
+ */
794
+ static async importSharedIdentity(privateKey) {
795
+ if (isWebPlatform()) {
796
+ throw new Error('Shared identity import is only available on native platforms.');
797
+ }
798
+ const store = await initSecureStore();
799
+ // Canonicalize incoming key BEFORE storage so the stored value is always
800
+ // in canonical 64-hex-char lowercase form going forward. Without this,
801
+ // legacy short keys would derive a different public key on the read path.
802
+ const canonicalPrivate = KeyManager.canonicalPrivateKey(privateKey);
803
+ const publicKey = (0, secp256k1_1.deriveSecp256k1PublicKey)(canonicalPrivate);
804
+ if ((0, platform_1.isIOS)()) {
805
+ const privateOpts = {
806
+ keychainAccessible: store.WHEN_UNLOCKED_THIS_DEVICE_ONLY,
807
+ keychainAccessGroup: IOS_KEYCHAIN_GROUP,
808
+ };
809
+ await store.setItemAsync(STORAGE_KEYS.SHARED_PRIVATE_KEY, canonicalPrivate, privateOpts);
810
+ const publicOpts = {
811
+ keychainAccessGroup: IOS_KEYCHAIN_GROUP,
812
+ };
813
+ await store.setItemAsync(STORAGE_KEYS.SHARED_PUBLIC_KEY, publicKey, publicOpts);
814
+ }
815
+ else if ((0, platform_1.isAndroid)()) {
816
+ // Android: write through the cross-app bridge when present; otherwise the
817
+ // package-private store (kept consistent with the read fallback).
818
+ const bridge = await (0, protocol_1.loadSharedIdentityBridge)();
819
+ if (bridge) {
820
+ await bridge.putShared(canonicalPrivate, publicKey);
821
+ }
822
+ else {
823
+ await store.setItemAsync(STORAGE_KEYS.SHARED_PRIVATE_KEY, canonicalPrivate, {
824
+ keychainAccessible: store.WHEN_UNLOCKED_THIS_DEVICE_ONLY,
825
+ });
826
+ await store.setItemAsync(STORAGE_KEYS.SHARED_PUBLIC_KEY, publicKey);
827
+ }
828
+ }
829
+ // Update cache
830
+ KeyManager.cachedSharedPublicKey = publicKey;
831
+ KeyManager.cachedHasSharedIdentity = true;
832
+ if ((0, logger_1.isDev)()) {
833
+ logger_1.logger.debug('Shared identity imported successfully', { component: 'KeyManager' });
834
+ }
835
+ return publicKey;
836
+ }
837
+ /**
838
+ * Store session information in shared storage
839
+ *
840
+ * This allows all Oxy apps to access the same session without
841
+ * re-authenticating. When user signs in to one app, all apps
842
+ * get the session automatically.
843
+ *
844
+ * @param sessionId - Session ID from authentication
845
+ * @param accessToken - Access token for API calls
846
+ */
847
+ static async storeSharedSession(sessionId, accessToken) {
848
+ if (isWebPlatform()) {
849
+ return; // Not supported on web
850
+ }
851
+ try {
852
+ const store = await initSecureStore();
853
+ if ((0, platform_1.isIOS)()) {
854
+ const sessionIdOpts = {
855
+ keychainAccessGroup: IOS_KEYCHAIN_GROUP,
856
+ };
857
+ await store.setItemAsync(STORAGE_KEYS.SHARED_SESSION_ID, sessionId, sessionIdOpts);
858
+ const tokenOpts = {
859
+ keychainAccessible: store.WHEN_UNLOCKED,
860
+ keychainAccessGroup: IOS_KEYCHAIN_GROUP,
861
+ };
862
+ await store.setItemAsync(STORAGE_KEYS.SHARED_SESSION_TOKEN, accessToken, tokenOpts);
863
+ }
864
+ else if ((0, platform_1.isAndroid)()) {
865
+ await store.setItemAsync(STORAGE_KEYS.SHARED_SESSION_ID, sessionId);
866
+ await store.setItemAsync(STORAGE_KEYS.SHARED_SESSION_TOKEN, accessToken);
867
+ }
868
+ if ((0, logger_1.isDev)()) {
869
+ logger_1.logger.debug('Shared session stored successfully', { component: 'KeyManager' });
870
+ }
871
+ }
872
+ catch (error) {
873
+ if ((0, logger_1.isDev)()) {
874
+ logger_1.logger.error('Failed to store shared session', error, { component: 'KeyManager' });
875
+ }
876
+ throw error;
877
+ }
878
+ }
879
+ /**
880
+ * Get shared session information
881
+ *
882
+ * This allows any Oxy app to check if user is already signed in
883
+ * via another Oxy app. Enables instant cross-app SSO.
884
+ *
885
+ * @returns Session data or null if no shared session exists
886
+ */
887
+ static async getSharedSession() {
888
+ if (isWebPlatform()) {
889
+ return null;
890
+ }
891
+ try {
892
+ const store = await initSecureStore();
893
+ let sessionId = null;
894
+ let accessToken = null;
895
+ if ((0, platform_1.isIOS)()) {
896
+ const opts = { keychainAccessGroup: IOS_KEYCHAIN_GROUP };
897
+ sessionId = await store.getItemAsync(STORAGE_KEYS.SHARED_SESSION_ID, opts);
898
+ accessToken = await store.getItemAsync(STORAGE_KEYS.SHARED_SESSION_TOKEN, opts);
899
+ }
900
+ else if ((0, platform_1.isAndroid)()) {
901
+ sessionId = await store.getItemAsync(STORAGE_KEYS.SHARED_SESSION_ID);
902
+ accessToken = await store.getItemAsync(STORAGE_KEYS.SHARED_SESSION_TOKEN);
903
+ }
904
+ if (!sessionId || !accessToken) {
905
+ return null;
906
+ }
907
+ return { sessionId, accessToken };
908
+ }
909
+ catch (error) {
910
+ if ((0, logger_1.isDev)()) {
911
+ logger_1.logger.warn('Failed to get shared session', { component: 'KeyManager' }, error);
912
+ }
913
+ return null;
914
+ }
915
+ }
916
+ /**
917
+ * Clear shared session (on logout)
918
+ *
919
+ * This signs out the user from ALL Oxy apps simultaneously.
920
+ * Call this when user explicitly logs out.
921
+ */
922
+ static async clearSharedSession() {
923
+ if (isWebPlatform()) {
924
+ return;
925
+ }
926
+ try {
927
+ const store = await initSecureStore();
928
+ if ((0, platform_1.isIOS)()) {
929
+ const opts = { keychainAccessGroup: IOS_KEYCHAIN_GROUP };
930
+ await store.deleteItemAsync(STORAGE_KEYS.SHARED_SESSION_ID, opts);
931
+ await store.deleteItemAsync(STORAGE_KEYS.SHARED_SESSION_TOKEN, opts);
932
+ }
933
+ else if ((0, platform_1.isAndroid)()) {
934
+ await store.deleteItemAsync(STORAGE_KEYS.SHARED_SESSION_ID);
935
+ await store.deleteItemAsync(STORAGE_KEYS.SHARED_SESSION_TOKEN);
936
+ }
937
+ if ((0, logger_1.isDev)()) {
938
+ logger_1.logger.debug('Shared session cleared successfully', { component: 'KeyManager' });
939
+ }
940
+ }
941
+ catch (error) {
942
+ if ((0, logger_1.isDev)()) {
943
+ logger_1.logger.error('Failed to clear shared session', error, { component: 'KeyManager' });
944
+ }
945
+ }
946
+ }
947
+ /**
948
+ * Migrate local identity to shared identity
949
+ *
950
+ * Call this when upgrading existing apps to use shared identities.
951
+ * Copies the device-specific identity to shared storage so it can
952
+ * be accessed by other Oxy apps.
953
+ *
954
+ * @returns True if migration was successful, false if no local identity exists
955
+ */
956
+ static async migrateToSharedIdentity() {
957
+ if (isWebPlatform()) {
958
+ return false;
959
+ }
960
+ try {
961
+ // Check if we already have a shared identity
962
+ const hasShared = await KeyManager.hasSharedIdentity();
963
+ if (hasShared) {
964
+ if ((0, logger_1.isDev)()) {
965
+ logger_1.logger.debug('Shared identity already exists, skipping migration', { component: 'KeyManager' });
966
+ }
967
+ return true;
968
+ }
969
+ // Get local identity
970
+ const privateKey = await KeyManager.getPrivateKey();
971
+ if (!privateKey) {
972
+ if ((0, logger_1.isDev)()) {
973
+ logger_1.logger.debug('No local identity to migrate', { component: 'KeyManager' });
974
+ }
975
+ return false;
976
+ }
977
+ // Import to shared storage
978
+ await KeyManager.importSharedIdentity(privateKey);
979
+ if ((0, logger_1.isDev)()) {
980
+ logger_1.logger.debug('Successfully migrated local identity to shared identity', { component: 'KeyManager' });
981
+ }
982
+ return true;
983
+ }
984
+ catch (error) {
985
+ if ((0, logger_1.isDev)()) {
986
+ logger_1.logger.error('Failed to migrate to shared identity', error, { component: 'KeyManager' });
987
+ }
988
+ return false;
989
+ }
990
+ }
991
+ // ==================== END SHARED IDENTITY METHODS ====================
992
+ /**
993
+ * Atomically persist a key pair to secure storage with verification + backup.
994
+ *
995
+ * INVARIANT (the reason this method exists): at no instant during the write
996
+ * may the device be left holding ZERO recoverable copies of a healthy
997
+ * identity. This matters most on the OVERWRITE / account-switch path: if we
998
+ * are replacing identity A with B and the write fails halfway, we MUST end
999
+ * up back on A — never on a half-written B, and never on nothing.
1000
+ *
1001
+ * Algorithm (recoverability-preserving):
1002
+ * 0. Snapshot the existing primary (privA, pubA) so we can roll back to
1003
+ * EXACTLY what was there.
1004
+ * 1. Write the new primary: public first, then private.
1005
+ * 2. Read back + sign/verify the new primary.
1006
+ * 3. ONLY after the new primary is proven durable, refresh the backup to
1007
+ * the new key. The backup is NEVER touched before this point, so any
1008
+ * prior identity's backup remains intact and `restoreIdentityFromBackup`
1009
+ * can always recover it.
1010
+ * 4. On ANY failure in steps 1–2, restore the snapshotted primary verbatim
1011
+ * (or delete it if there was none), then surface the error.
1012
+ *
1013
+ * Earlier versions wrote the *incoming* key to the backup FIRST, which
1014
+ * destroyed the previous identity's backup, and rolled back by blindly
1015
+ * deleting the primary — so a failed overwrite silently switched the user
1016
+ * to (or lost them into) the half-written new identity. That is fixed here.
1017
+ *
1018
+ * @internal
1019
+ */
1020
+ static async _persistIdentityAtomic(privateKey, publicKey, origin) {
1021
+ const store = await initSecureStore();
1022
+ // Resolve the active slot layout (normally v2; legacy only in the rare
1023
+ // migration-fallback session). Reading and writing the SAME layout keeps the
1024
+ // snapshot/rollback machinery below internally consistent. A deferred
1025
+ // migration (keychain locked) must never write blind.
1026
+ const migration = await KeyManager._ensureIdentitySlotsMigrated();
1027
+ if (migration.mode === 'deferred') {
1028
+ throw new IdentityUnavailableError('Identity storage is temporarily unavailable; refusing to persist an identity.', migration.cause);
1029
+ }
1030
+ const layout = migration.layout;
1031
+ const primaryReadOpts = KeyManager._slotOpts(layout.primaryService);
1032
+ const primaryPrivWriteOpts = KeyManager._privateWriteOpts(store, layout.primaryService);
1033
+ const primaryPubWriteOpts = KeyManager._slotOpts(layout.primaryService);
1034
+ const backupReadOpts = KeyManager._slotOpts(layout.backupService);
1035
+ const backupPrivWriteOpts = KeyManager._privateWriteOpts(store, layout.backupService);
1036
+ const backupPubWriteOpts = KeyManager._slotOpts(layout.backupService);
1037
+ // Canonicalize BEFORE persistence so the stored value is always in
1038
+ // canonical 64-hex-char lowercase form going forward. This is the single
1039
+ // place all primary writes flow through, so once a value lands here all
1040
+ // subsequent reads see a stable representation.
1041
+ const canonicalPrivate = KeyManager.canonicalPrivateKey(privateKey);
1042
+ const canonicalPublic = publicKey.toLowerCase();
1043
+ // Step 0: Snapshot the existing primary so a failed write can be rolled
1044
+ // back to EXACTLY the prior state. If the read itself fails we treat the
1045
+ // prior primary as unknown and refuse to proceed — overwriting blind
1046
+ // would risk clobbering an identity we just couldn't see (e.g. a
1047
+ // transient keychain lock).
1048
+ let priorPrivate;
1049
+ let priorPublic;
1050
+ try {
1051
+ priorPrivate = await store.getItemAsync(layout.primaryPrivateKeyName, primaryReadOpts);
1052
+ priorPublic = await store.getItemAsync(layout.primaryPublicKeyName, primaryReadOpts);
1053
+ }
1054
+ catch (error) {
1055
+ logger_1.logger.error('Failed to read existing primary before persist', error, { component: 'KeyManager' });
1056
+ throw new IdentityPersistError('Could not read existing identity before writing a new one; refusing to overwrite blind.', error);
1057
+ }
1058
+ // If we are replacing a DIFFERENT, currently-healthy identity, make sure
1059
+ // it is recoverable from the backup slot BEFORE we overwrite the primary.
1060
+ // We only do this when the existing backup does not already hold that
1061
+ // identity — otherwise we would needlessly churn the keychain. This keeps
1062
+ // the "always at least one recoverable copy" invariant intact across the
1063
+ // window where the primary briefly holds the new key but the new backup
1064
+ // has not been written yet.
1065
+ const priorIsHealthyDifferent = !!priorPrivate &&
1066
+ !!priorPublic &&
1067
+ priorPublic.toLowerCase() !== canonicalPublic &&
1068
+ KeyManager.isValidPrivateKey(priorPrivate) &&
1069
+ KeyManager.isValidPublicKey(priorPublic) &&
1070
+ KeyManager.derivePublicKey(priorPrivate).toLowerCase() === priorPublic.toLowerCase();
1071
+ if (priorIsHealthyDifferent && priorPrivate && priorPublic) {
1072
+ let existingBackupPublic = null;
1073
+ try {
1074
+ existingBackupPublic = await store.getItemAsync(layout.backupPublicKeyName, backupReadOpts);
1075
+ }
1076
+ catch {
1077
+ existingBackupPublic = null;
1078
+ }
1079
+ if (existingBackupPublic?.toLowerCase() !== priorPublic.toLowerCase()) {
1080
+ try {
1081
+ await store.setItemAsync(layout.backupPrivateKeyName, KeyManager.canonicalPrivateKey(priorPrivate), backupPrivWriteOpts);
1082
+ await store.setItemAsync(layout.backupPublicKeyName, priorPublic.toLowerCase(), backupPubWriteOpts);
1083
+ await store.setItemAsync(layout.backupTimestampName, Date.now().toString(), backupPubWriteOpts);
1084
+ }
1085
+ catch (error) {
1086
+ logger_1.logger.error('Failed to back up existing identity before overwrite', error, { component: 'KeyManager' });
1087
+ throw new IdentityPersistError('Failed to back up existing identity before overwrite', error);
1088
+ }
1089
+ }
1090
+ }
1091
+ // Step 1: Write the new primary. Public first so that if the private write
1092
+ // fails we are missing the most critical bit. The backup is intentionally
1093
+ // NOT touched here — it still holds the previous good identity until the
1094
+ // new primary is proven durable.
1095
+ try {
1096
+ await store.setItemAsync(layout.primaryPublicKeyName, canonicalPublic, primaryPubWriteOpts);
1097
+ await store.setItemAsync(layout.primaryPrivateKeyName, canonicalPrivate, primaryPrivWriteOpts);
1098
+ }
1099
+ catch (error) {
1100
+ logger_1.logger.error('Failed to write primary identity to secure store', error, { component: 'KeyManager' });
1101
+ await KeyManager._rollbackPrimary(store, layout, priorPrivate, priorPublic);
1102
+ throw new IdentityPersistError('Failed to write identity to secure store', error);
1103
+ }
1104
+ // Step 2: Verify round-trip. If the store silently drops our writes
1105
+ // (e.g., a misconfigured keychain access group), we MUST surface it
1106
+ // before declaring success — otherwise the caller will think the
1107
+ // identity was saved and discard the in-memory copy.
1108
+ let readBackPrivate;
1109
+ let readBackPublic;
1110
+ try {
1111
+ readBackPrivate = await store.getItemAsync(layout.primaryPrivateKeyName, primaryReadOpts);
1112
+ readBackPublic = await store.getItemAsync(layout.primaryPublicKeyName, primaryReadOpts);
1113
+ }
1114
+ catch (error) {
1115
+ logger_1.logger.error('Failed to read identity back after write', error, { component: 'KeyManager' });
1116
+ await KeyManager._rollbackPrimary(store, layout, priorPrivate, priorPublic);
1117
+ throw new IdentityPersistError('Failed to verify identity after write', error);
1118
+ }
1119
+ // Hex comparisons are case-insensitive — normalize on both sides so a
1120
+ // store that uppercases on round-trip (some keychain backends) doesn't
1121
+ // trigger a spurious mismatch.
1122
+ if (readBackPrivate?.toLowerCase() !== canonicalPrivate ||
1123
+ readBackPublic?.toLowerCase() !== canonicalPublic) {
1124
+ logger_1.logger.error('Identity round-trip mismatch after write', undefined, { component: 'KeyManager' });
1125
+ await KeyManager._rollbackPrimary(store, layout, priorPrivate, priorPublic);
1126
+ throw new IdentityPersistError('Identity write was not persisted correctly (round-trip mismatch).');
1127
+ }
1128
+ // Final sanity: derive public from the stored private and confirm the
1129
+ // pair signs/verifies cleanly. Catches crypto-state corruption immediately
1130
+ // rather than the next time the user tries to sign in.
1131
+ try {
1132
+ const privateKey = KeyManager.canonicalPrivateKey(readBackPrivate);
1133
+ const derived = (0, secp256k1_1.deriveSecp256k1PublicKey)(privateKey);
1134
+ if (derived.toLowerCase() !== readBackPublic.toLowerCase()) {
1135
+ throw new IdentityPersistError('Stored public key does not match derived public key.');
1136
+ }
1137
+ // Sign/verify roundtrip using a known test vector
1138
+ const probeHash = '0'.repeat(64);
1139
+ const signature = (0, secp256k1_1.signSecp256k1Digest)(privateKey, probeHash);
1140
+ if (!(0, secp256k1_1.verifySecp256k1Digest)(derived, probeHash, signature)) {
1141
+ throw new IdentityPersistError('Sign/verify roundtrip failed for newly stored identity.');
1142
+ }
1143
+ }
1144
+ catch (error) {
1145
+ await KeyManager._rollbackPrimary(store, layout, priorPrivate, priorPublic);
1146
+ if (error instanceof IdentityPersistError)
1147
+ throw error;
1148
+ logger_1.logger.error('Identity sign/verify probe failed', error, { component: 'KeyManager' });
1149
+ throw new IdentityPersistError('Stored identity failed crypto self-test', error);
1150
+ }
1151
+ // Step 3: The new primary is durable and functional. NOW it is safe to
1152
+ // refresh the backup to the new key. This is part of the successful write
1153
+ // contract: returning success while the backup still belongs to the
1154
+ // previous identity would allow a later restore with an absent primary to
1155
+ // silently switch the device back to the previous account. Snapshot the
1156
+ // backup first so a partial backup refresh can be rolled back along with
1157
+ // the primary before surfacing the failure.
1158
+ let priorBackupPrivate;
1159
+ let priorBackupPublic;
1160
+ let priorBackupTimestamp;
1161
+ try {
1162
+ priorBackupPrivate = await store.getItemAsync(layout.backupPrivateKeyName, backupReadOpts);
1163
+ priorBackupPublic = await store.getItemAsync(layout.backupPublicKeyName, backupReadOpts);
1164
+ priorBackupTimestamp = await store.getItemAsync(layout.backupTimestampName, backupReadOpts);
1165
+ }
1166
+ catch (error) {
1167
+ logger_1.logger.error('Failed to snapshot identity backup before refresh', error, { component: 'KeyManager' });
1168
+ await KeyManager._rollbackPrimary(store, layout, priorPrivate, priorPublic);
1169
+ throw new IdentityPersistError('Failed to snapshot identity backup before refresh', error);
1170
+ }
1171
+ try {
1172
+ await store.setItemAsync(layout.backupPrivateKeyName, canonicalPrivate, backupPrivWriteOpts);
1173
+ await store.setItemAsync(layout.backupPublicKeyName, canonicalPublic, backupPubWriteOpts);
1174
+ await store.setItemAsync(layout.backupTimestampName, Date.now().toString(), backupPubWriteOpts);
1175
+ }
1176
+ catch (error) {
1177
+ logger_1.logger.error('Failed to refresh identity backup after primary write', error, { component: 'KeyManager' });
1178
+ await KeyManager._rollbackBackup(store, layout, priorBackupPrivate, priorBackupPublic, priorBackupTimestamp);
1179
+ await KeyManager._rollbackPrimary(store, layout, priorPrivate, priorPublic);
1180
+ throw new IdentityPersistError('Failed to refresh identity backup after primary write', error);
1181
+ }
1182
+ // Update cache only after we are certain the identity is durable, then fan
1183
+ // out to identity-change subscribers.
1184
+ KeyManager.cachedPublicKey = canonicalPublic;
1185
+ KeyManager.cachedHasIdentity = true;
1186
+ KeyManager.cachedPublicKeyResolved = false;
1187
+ KeyManager.notifyIdentityChanged();
1188
+ // LAST step: mirror the identity into the AndroidKeyStore-independent marker
1189
+ // so a later keystore death can be told apart from a fresh install. This is
1190
+ // best-effort — a marker write failure must NEVER fail an otherwise-durable
1191
+ // persist (a subsequent healthy read re-backfills it). Rollback paths above
1192
+ // return before reaching here, so they never touch the marker.
1193
+ await KeyManager._syncMarkerAfterPersist(canonicalPublic, origin);
1194
+ }
1195
+ /**
1196
+ * Write/refresh the identity marker after a successful persist. A same-identity
1197
+ * re-persist (e.g. backup refresh, idempotent re-import) preserves `createdAt`
1198
+ * and the `onboardingComplete` milestone by only updating `origin`; a NEW or
1199
+ * switched identity writes a fresh marker. Best-effort — never throws.
1200
+ *
1201
+ * @internal
1202
+ */
1203
+ static async _syncMarkerAfterPersist(publicKey, origin) {
1204
+ try {
1205
+ const existing = await (0, identityMarker_1.readIdentityMarker)();
1206
+ if (existing && existing.publicKey.toLowerCase() === publicKey.toLowerCase()) {
1207
+ await (0, identityMarker_1.updateIdentityMarker)({ origin });
1208
+ }
1209
+ else {
1210
+ await (0, identityMarker_1.writeIdentityMarker)({ publicKey, origin });
1211
+ }
1212
+ }
1213
+ catch (error) {
1214
+ logger_1.logger.warn('Failed to sync identity marker after persist (non-fatal)', { component: 'KeyManager' }, error);
1215
+ }
1216
+ }
1217
+ /**
1218
+ * Restore the backup slot to a previously-snapshotted state. Best-effort so
1219
+ * the original persistence error remains the one surfaced to the caller.
1220
+ *
1221
+ * @internal
1222
+ */
1223
+ static async _rollbackBackup(store, layout, priorBackupPrivate, priorBackupPublic, priorBackupTimestamp) {
1224
+ const backupPrivWriteOpts = KeyManager._privateWriteOpts(store, layout.backupService);
1225
+ const backupPubWriteOpts = KeyManager._slotOpts(layout.backupService);
1226
+ const backupReadOpts = KeyManager._slotOpts(layout.backupService);
1227
+ try {
1228
+ if (priorBackupPrivate) {
1229
+ await store.setItemAsync(layout.backupPrivateKeyName, priorBackupPrivate, backupPrivWriteOpts);
1230
+ }
1231
+ else {
1232
+ try {
1233
+ await store.deleteItemAsync(layout.backupPrivateKeyName, backupReadOpts);
1234
+ }
1235
+ catch { /* best effort */ }
1236
+ }
1237
+ if (priorBackupPublic) {
1238
+ await store.setItemAsync(layout.backupPublicKeyName, priorBackupPublic, backupPubWriteOpts);
1239
+ }
1240
+ else {
1241
+ try {
1242
+ await store.deleteItemAsync(layout.backupPublicKeyName, backupReadOpts);
1243
+ }
1244
+ catch { /* best effort */ }
1245
+ }
1246
+ if (priorBackupTimestamp) {
1247
+ await store.setItemAsync(layout.backupTimestampName, priorBackupTimestamp, backupPubWriteOpts);
1248
+ }
1249
+ else {
1250
+ try {
1251
+ await store.deleteItemAsync(layout.backupTimestampName, backupReadOpts);
1252
+ }
1253
+ catch { /* best effort */ }
1254
+ }
1255
+ }
1256
+ catch (rollbackError) {
1257
+ logger_1.logger.error('Failed to roll back identity backup after a failed refresh', rollbackError, { component: 'KeyManager' });
1258
+ }
1259
+ }
1260
+ /**
1261
+ * Restore the primary slot to a previously-snapshotted (privA, pubA) pair,
1262
+ * or delete it entirely if there was no prior identity. Best-effort: every
1263
+ * step is wrapped so a rollback failure never masks the original error the
1264
+ * caller is about to throw. Invalidates the in-memory cache so the next read
1265
+ * reflects whatever actually landed on disk.
1266
+ *
1267
+ * @internal
1268
+ */
1269
+ static async _rollbackPrimary(store, layout, priorPrivate, priorPublic) {
1270
+ const primaryPrivWriteOpts = KeyManager._privateWriteOpts(store, layout.primaryService);
1271
+ const primaryPubWriteOpts = KeyManager._slotOpts(layout.primaryService);
1272
+ const primaryReadOpts = KeyManager._slotOpts(layout.primaryService);
1273
+ try {
1274
+ if (priorPrivate && priorPublic) {
1275
+ // Restore exactly what was there before the failed write.
1276
+ await store.setItemAsync(layout.primaryPublicKeyName, priorPublic, primaryPubWriteOpts);
1277
+ await store.setItemAsync(layout.primaryPrivateKeyName, priorPrivate, primaryPrivWriteOpts);
1278
+ }
1279
+ else {
1280
+ // There was no prior identity — leave the device empty rather than
1281
+ // half-written so hasIdentity() does not lie.
1282
+ try {
1283
+ await store.deleteItemAsync(layout.primaryPublicKeyName, primaryReadOpts);
1284
+ }
1285
+ catch { /* best effort */ }
1286
+ try {
1287
+ await store.deleteItemAsync(layout.primaryPrivateKeyName, primaryReadOpts);
1288
+ }
1289
+ catch { /* best effort */ }
1290
+ }
1291
+ }
1292
+ catch (rollbackError) {
1293
+ logger_1.logger.error('Failed to roll back primary identity after a failed write', rollbackError, { component: 'KeyManager' });
1294
+ }
1295
+ finally {
1296
+ // Whatever happened, the cached verdict is no longer trustworthy.
1297
+ KeyManager.invalidateCache();
1298
+ }
1299
+ }
1300
+ /**
1301
+ * Generate and securely store a new key pair on the device.
1302
+ *
1303
+ * Refuses to overwrite an existing identity unless `options.overwrite === true`.
1304
+ * Returns the public key. The private key never leaves secure storage.
1305
+ *
1306
+ * @throws IdentityAlreadyExistsError if an identity already exists and overwrite is not set
1307
+ * @throws IdentityPersistError if the key cannot be durably written
1308
+ */
1309
+ static async createIdentity(options) {
1310
+ if (isWebPlatform()) {
1311
+ throw new Error('Identity creation is only available on native platforms (iOS/Android). Please use the native app to create your identity.');
1312
+ }
1313
+ // CRITICAL SAFEGUARD: never silently overwrite an existing identity.
1314
+ // The local key IS the account — clobbering it without consent is
1315
+ // catastrophic. Callers must opt in explicitly when they have already
1316
+ // confirmed (via UI) that the user has saved their recovery phrase.
1317
+ //
1318
+ // The guard reads storage DIRECTLY (cache-bypassing) AND consults the
1319
+ // AndroidKeyStore-independent marker: either a stored key OR a marker means
1320
+ // an identity exists here → refuse. A storage THROW surfaces as
1321
+ // IdentityUnavailableError (never a blind write over a locked keystore).
1322
+ if (!options?.overwrite) {
1323
+ const marker = await (0, identityMarker_1.readIdentityMarker)();
1324
+ const direct = await KeyManager._readPrimaryDirect();
1325
+ if (direct.publicKey) {
1326
+ throw new IdentityAlreadyExistsError(direct.publicKey);
1327
+ }
1328
+ if (marker) {
1329
+ throw new IdentityAlreadyExistsError(marker.publicKey);
1330
+ }
1331
+ }
1332
+ const { privateKey, publicKey } = await KeyManager.generateKeyPair();
1333
+ await KeyManager._persistIdentityAtomic(privateKey, publicKey, 'create');
1334
+ return publicKey;
1335
+ }
1336
+ /**
1337
+ * Read the primary key pair DIRECTLY from storage, bypassing the in-memory
1338
+ * cache (which a prior transient failure could have poisoned). Awaits slot
1339
+ * migration first. Throws {@link IdentityUnavailableError} if storage is
1340
+ * deferred/locked or a read throws — so overwrite guards never write blind.
1341
+ *
1342
+ * @internal
1343
+ */
1344
+ static async _readPrimaryDirect() {
1345
+ const migration = await KeyManager._ensureIdentitySlotsMigrated();
1346
+ if (migration.mode === 'deferred') {
1347
+ throw new IdentityUnavailableError('Identity storage is temporarily unavailable; refusing to write blind.', migration.cause);
1348
+ }
1349
+ const layout = migration.layout;
1350
+ const readOpts = KeyManager._slotOpts(layout.primaryService);
1351
+ try {
1352
+ const store = await initSecureStore();
1353
+ const privateKey = await store.getItemAsync(layout.primaryPrivateKeyName, readOpts);
1354
+ const publicKey = await store.getItemAsync(layout.primaryPublicKeyName, readOpts);
1355
+ return { privateKey, publicKey };
1356
+ }
1357
+ catch (error) {
1358
+ throw new IdentityUnavailableError('Could not read existing identity; refusing to write blind.', error);
1359
+ }
1360
+ }
1361
+ /**
1362
+ * Import an existing key pair (e.g., from recovery phrase).
1363
+ *
1364
+ * Refuses to overwrite an existing identity unless `options.overwrite === true`.
1365
+ *
1366
+ * @throws IdentityAlreadyExistsError if an identity already exists and overwrite is not set
1367
+ * @throws IdentityPersistError if the key cannot be durably written
1368
+ */
1369
+ static async importKeyPair(privateKey, options) {
1370
+ if (isWebPlatform()) {
1371
+ throw new Error('Identity import is only available on native platforms (iOS/Android). Please use the native app to import your identity.');
1372
+ }
1373
+ if (!KeyManager.isValidPrivateKey(privateKey)) {
1374
+ throw new Error('Invalid private key supplied to importKeyPair.');
1375
+ }
1376
+ // Canonicalize the incoming private key so the stored value (and the
1377
+ // derived public key) are always in canonical form. Without this, an
1378
+ // externally-imported short or uppercase key would derive one public
1379
+ // key here and a different one when later read back unpadded.
1380
+ const canonicalPrivate = KeyManager.canonicalPrivateKey(privateKey);
1381
+ const publicKey = (0, secp256k1_1.deriveSecp256k1PublicKey)(canonicalPrivate);
1382
+ // Refuse silent overwrite — see createIdentity() for rationale. The guard
1383
+ // reads storage DIRECTLY (cache-bypassing) AND the marker, and treats
1384
+ // storage as authoritative:
1385
+ // - stored key === this import → safe idempotent refresh (fall through)
1386
+ // - stored key differs → a DIFFERENT identity is present → refuse
1387
+ // - storage empty + marker for a DIFFERENT identity (lost state) → refuse
1388
+ // - storage empty + marker matches this import (recovery) / no marker → allow
1389
+ // A storage throw surfaces as IdentityUnavailableError (never a blind write).
1390
+ if (!options?.overwrite) {
1391
+ const marker = await (0, identityMarker_1.readIdentityMarker)();
1392
+ const direct = await KeyManager._readPrimaryDirect();
1393
+ const importedPub = publicKey.toLowerCase();
1394
+ const existingPub = direct.publicKey?.toLowerCase() ?? null;
1395
+ const markerPub = marker?.publicKey.toLowerCase() ?? null;
1396
+ if (existingPub && existingPub !== importedPub) {
1397
+ throw new IdentityAlreadyExistsError(direct.publicKey);
1398
+ }
1399
+ if (!existingPub && markerPub && markerPub !== importedPub) {
1400
+ throw new IdentityAlreadyExistsError(marker?.publicKey);
1401
+ }
1402
+ // Otherwise: existing === import (idempotent refresh), or storage empty
1403
+ // with a matching/absent marker (fresh import or lost-identity recovery)
1404
+ // → fall through and (re-)persist to refresh the backup + marker.
1405
+ }
1406
+ await KeyManager._persistIdentityAtomic(canonicalPrivate, publicKey, 'import');
1407
+ return publicKey;
1408
+ }
1409
+ /**
1410
+ * Get the stored private key
1411
+ * WARNING: Only use this for signing operations within the app
1412
+ *
1413
+ * Preserves the "return null on any storage failure" contract signing paths
1414
+ * rely on (a locked keychain simply means "cannot sign now"); unlike
1415
+ * {@link getPublicKey}, it does NOT throw {@link IdentityUnavailableError}.
1416
+ */
1417
+ static async getPrivateKey() {
1418
+ if (isWebPlatform()) {
1419
+ return null; // Identity storage is only available on native platforms
1420
+ }
1421
+ try {
1422
+ const migration = await KeyManager._ensureIdentitySlotsMigrated();
1423
+ if (migration.mode === 'deferred') {
1424
+ // Storage unreadable right now — preserve the null contract.
1425
+ return null;
1426
+ }
1427
+ const store = await initSecureStore();
1428
+ return await store.getItemAsync(migration.layout.primaryPrivateKeyName, KeyManager._slotOpts(migration.layout.primaryService));
1429
+ }
1430
+ catch (error) {
1431
+ // If secure store is not available, return null (no identity)
1432
+ // This allows the app to continue functioning even if secure store fails to load
1433
+ if ((0, logger_1.isDev)()) {
1434
+ logger_1.logger.warn('Failed to access secure store', { component: 'KeyManager' }, error);
1435
+ }
1436
+ return null;
1437
+ }
1438
+ }
1439
+ /**
1440
+ * Get the stored public key (cached for performance).
1441
+ *
1442
+ * Returns the public key, or `null` when a read SUCCEEDS and finds none.
1443
+ * THROWS {@link IdentityUnavailableError} when storage is unreadable (keychain
1444
+ * locked / module load failure) — a thrown read is NEVER flattened to `null`
1445
+ * and NEVER cached, so a poisoned "no identity" verdict can no longer stick.
1446
+ */
1447
+ static async getPublicKey() {
1448
+ if (isWebPlatform()) {
1449
+ return null; // Identity storage is only available on native platforms
1450
+ }
1451
+ if (KeyManager.cachedPublicKey !== null) {
1452
+ return KeyManager.cachedPublicKey;
1453
+ }
1454
+ // A genuine-absent result (read succeeded, empty) is cacheable distinctly
1455
+ // from a thrown read — only the former sets this flag.
1456
+ if (KeyManager.cachedPublicKeyResolved) {
1457
+ return null;
1458
+ }
1459
+ const migration = await KeyManager._ensureIdentitySlotsMigrated();
1460
+ if (migration.mode === 'deferred') {
1461
+ throw new IdentityUnavailableError('Identity storage is temporarily unavailable (keychain locked or unreadable).', migration.cause);
1462
+ }
1463
+ try {
1464
+ const store = await initSecureStore();
1465
+ const publicKey = await store.getItemAsync(migration.layout.primaryPublicKeyName, KeyManager._slotOpts(migration.layout.primaryService));
1466
+ if (publicKey !== null) {
1467
+ KeyManager.cachedPublicKey = publicKey;
1468
+ }
1469
+ else {
1470
+ // Genuine-absent (successful empty read) IS safe to cache.
1471
+ KeyManager.cachedPublicKeyResolved = true;
1472
+ }
1473
+ return publicKey;
1474
+ }
1475
+ catch (error) {
1476
+ // Storage threw AFTER migration resolved — transient/unavailable. Do NOT
1477
+ // cache; surface a typed error so callers never misread it as "no identity".
1478
+ if ((0, logger_1.isDev)()) {
1479
+ logger_1.logger.warn('Failed to access secure store', { component: 'KeyManager' }, error);
1480
+ }
1481
+ throw new IdentityUnavailableError('Failed to read identity from secure storage.', error);
1482
+ }
1483
+ }
1484
+ /**
1485
+ * Persist the recovery mnemonic (the 12-word phrase) into its dedicated,
1486
+ * device-only keychain slot so the user can re-reveal it from Settings after
1487
+ * onboarding.
1488
+ *
1489
+ * Called best-effort at identity creation/import, where the phrase is already
1490
+ * in memory: a failure to persist it must NEVER fail the identity itself, so
1491
+ * callers deliberately swallow the thrown error (logging it). Storage errors
1492
+ * throw {@link IdentityUnavailableError} — same "cannot determine" semantics as
1493
+ * the other getters — so a caller MAY observe/log the failure.
1494
+ *
1495
+ * The mnemonic is stored ONLY here — never in the marker, `getIdentityStatus`,
1496
+ * logs, or any exported bundle.
1497
+ */
1498
+ static async storeRecoveryMnemonic(mnemonic) {
1499
+ if (isWebPlatform()) {
1500
+ return; // Identity storage is only available on native platforms
1501
+ }
1502
+ try {
1503
+ const store = await initSecureStore();
1504
+ await store.setItemAsync(RECOVERY_MNEMONIC_STORAGE_KEY, mnemonic, KeyManager._privateWriteOpts(store, RECOVERY_MNEMONIC_KEYCHAIN_SERVICE));
1505
+ }
1506
+ catch (error) {
1507
+ if ((0, logger_1.isDev)()) {
1508
+ logger_1.logger.warn('Failed to persist recovery mnemonic', { component: 'KeyManager' }, error);
1509
+ }
1510
+ throw new IdentityUnavailableError('Failed to persist recovery mnemonic.', error);
1511
+ }
1512
+ }
1513
+ /**
1514
+ * Read the stored recovery mnemonic for re-reveal in Settings.
1515
+ *
1516
+ * Returns the phrase, or `null` when a read SUCCEEDS and finds none — the
1517
+ * expected result for any identity created/imported before this feature
1518
+ * existed, since the phrase was never captured for those. THROWS
1519
+ * {@link IdentityUnavailableError} when storage is unreadable (keychain locked
1520
+ * / module load failure), matching {@link getPublicKey}'s contract — a thrown
1521
+ * read is never flattened to `null`, so a caller distinguishes "phrase was
1522
+ * never stored" from "keychain temporarily locked, retry".
1523
+ */
1524
+ static async getRecoveryMnemonic() {
1525
+ if (isWebPlatform()) {
1526
+ return null; // Identity storage is only available on native platforms
1527
+ }
1528
+ try {
1529
+ const store = await initSecureStore();
1530
+ return await store.getItemAsync(RECOVERY_MNEMONIC_STORAGE_KEY, KeyManager._slotOpts(RECOVERY_MNEMONIC_KEYCHAIN_SERVICE));
1531
+ }
1532
+ catch (error) {
1533
+ if ((0, logger_1.isDev)()) {
1534
+ logger_1.logger.warn('Failed to read recovery mnemonic', { component: 'KeyManager' }, error);
1535
+ }
1536
+ throw new IdentityUnavailableError('Failed to read recovery mnemonic from secure storage.', error);
1537
+ }
1538
+ }
1539
+ /**
1540
+ * Delete the stored recovery mnemonic. Best-effort: a delete failure is logged
1541
+ * and swallowed, never thrown — it runs inside the identity-deletion path where
1542
+ * an unreadable keychain must not abort the wider teardown.
1543
+ */
1544
+ static async deleteRecoveryMnemonic() {
1545
+ if (isWebPlatform()) {
1546
+ return; // Identity storage is only available on native platforms
1547
+ }
1548
+ const store = await initSecureStore();
1549
+ await KeyManager._bestEffortDelete(store, RECOVERY_MNEMONIC_STORAGE_KEY, RECOVERY_MNEMONIC_KEYCHAIN_SERVICE);
1550
+ }
1551
+ /**
1552
+ * Check if a complete, parseable identity exists on this device.
1553
+ *
1554
+ * Returns `true` only when BOTH the private and public keys are present,
1555
+ * both are well-formed, AND the public key derives from the private key.
1556
+ * A partially-written or corrupted identity (read succeeded, bytes empty/bad)
1557
+ * returns `false` so that downstream code can resume the create / restore flow.
1558
+ * THROWS {@link IdentityUnavailableError} when storage is unreadable — a locked
1559
+ * keychain must never be mistaken for "no identity" (the old behavior that let
1560
+ * onboarding treat a transient lock as a blank device).
1561
+ *
1562
+ * Note: this does NOT perform the full sign/verify roundtrip — call
1563
+ * `verifyIdentityIntegrity()` for that.
1564
+ */
1565
+ static async hasIdentity() {
1566
+ if (isWebPlatform()) {
1567
+ return false; // Identity storage is only available on native platforms
1568
+ }
1569
+ if (KeyManager.cachedHasIdentity !== null) {
1570
+ return KeyManager.cachedHasIdentity;
1571
+ }
1572
+ const migration = await KeyManager._ensureIdentitySlotsMigrated();
1573
+ if (migration.mode === 'deferred') {
1574
+ throw new IdentityUnavailableError('Identity storage is temporarily unavailable.', migration.cause);
1575
+ }
1576
+ let privateKey;
1577
+ let publicKey;
1578
+ try {
1579
+ const store = await initSecureStore();
1580
+ [privateKey, publicKey] = await Promise.all([
1581
+ store.getItemAsync(migration.layout.primaryPrivateKeyName, KeyManager._slotOpts(migration.layout.primaryService)),
1582
+ store.getItemAsync(migration.layout.primaryPublicKeyName, KeyManager._slotOpts(migration.layout.primaryService)),
1583
+ ]);
1584
+ }
1585
+ catch (error) {
1586
+ // Storage threw — could be a transient keychain lock (e.g., background
1587
+ // fetch before the device is unlocked). Do NOT cache; throw a TYPED error
1588
+ // so callers distinguish "temporarily unavailable" from "genuinely absent"
1589
+ // instead of silently treating a locked keystore as a blank device.
1590
+ logger_1.logger.error('Failed to read identity from secure storage', error, { component: 'KeyManager' });
1591
+ throw new IdentityUnavailableError('Failed to read identity from secure storage.', error);
1592
+ }
1593
+ // Storage succeeded. Now classify the result. From here onward, any
1594
+ // outcome is stable and safe to cache (the bytes won't change between
1595
+ // calls).
1596
+ let hasIdentity = false;
1597
+ if (privateKey && publicKey) {
1598
+ // Require BOTH bytes-present AND parseable AND matching. Any weaker
1599
+ // check would let a half-written identity (private without public)
1600
+ // pretend to be a real one, which then fails opaquely later in the
1601
+ // sign-in flow when SignatureService.sign() can't find the keypair.
1602
+ if (KeyManager.isValidPrivateKey(privateKey) && KeyManager.isValidPublicKey(publicKey)) {
1603
+ try {
1604
+ const derived = (0, secp256k1_1.deriveSecp256k1PublicKey)(KeyManager.canonicalPrivateKey(privateKey));
1605
+ // Hex equality is case-insensitive; normalize on both sides to
1606
+ // tolerate legacy uppercase-stored public keys.
1607
+ hasIdentity = derived.toLowerCase() === publicKey.toLowerCase();
1608
+ if (!hasIdentity) {
1609
+ logger_1.logger.warn('KeyManager.hasIdentity: stored public key does not match derived public key', { component: 'KeyManager' });
1610
+ }
1611
+ }
1612
+ catch (error) {
1613
+ logger_1.logger.warn('KeyManager.hasIdentity: failed to derive public key from stored private key', { component: 'KeyManager' }, error);
1614
+ }
1615
+ }
1616
+ else {
1617
+ logger_1.logger.warn('KeyManager.hasIdentity: stored key material is malformed', { component: 'KeyManager' });
1618
+ }
1619
+ }
1620
+ // Cache result. Storage succeeded, so this verdict is stable:
1621
+ // - true → identity exists and round-trips cleanly
1622
+ // - false → storage is empty / partial / malformed (a stable result;
1623
+ // callers should run integrity-recovery / restore from
1624
+ // backup explicitly)
1625
+ KeyManager.cachedHasIdentity = hasIdentity;
1626
+ if (hasIdentity && publicKey) {
1627
+ KeyManager.cachedPublicKey = publicKey;
1628
+ }
1629
+ // Diagnostic breadcrumb (dev only). Logs lengths + validity flags so we
1630
+ // can tell from `adb logcat` exactly WHY hasIdentity returned what it
1631
+ // did. Never log the key material itself.
1632
+ if ((0, logger_1.isDev)()) {
1633
+ logger_1.logger.debug('KeyManager.hasIdentity result', { component: 'KeyManager' }, {
1634
+ privateLen: privateKey?.length ?? 0,
1635
+ publicLen: publicKey?.length ?? 0,
1636
+ privateValid: privateKey ? KeyManager.isValidPrivateKey(privateKey) : null,
1637
+ publicValid: publicKey ? KeyManager.isValidPublicKey(publicKey) : null,
1638
+ derived: hasIdentity,
1639
+ });
1640
+ }
1641
+ return hasIdentity;
1642
+ }
1643
+ /**
1644
+ * Authoritative identity verdict — the corruption-vs-fresh-install
1645
+ * disambiguator that routing (commons) keys off of.
1646
+ *
1647
+ * - Healthy pair → `present` (and the marker is backfilled if missing or
1648
+ * pointing at a different key, `origin: 'backfill'`).
1649
+ * - Read succeeded but no healthy pair, WITH a marker → `lost` (keystore death
1650
+ * / corruption; route to recovery, NEVER to create).
1651
+ * - Read succeeded, no pair, NO marker → `absent` (a genuine fresh device; the
1652
+ * only state that may route to onboarding/create).
1653
+ * - A read THREW → `unavailable` (keychain locked); this verdict is NEVER
1654
+ * cached, so a later call re-reads.
1655
+ *
1656
+ * @param opts.bypassCache When true, never reads OR writes the in-memory cache
1657
+ * — a pure, fresh storage verdict for the auto-create interlock preflight.
1658
+ */
1659
+ static async getIdentityStatus(opts) {
1660
+ if (isWebPlatform()) {
1661
+ return { state: 'absent' }; // Identity storage is only available on native platforms
1662
+ }
1663
+ const bypassCache = opts?.bypassCache === true;
1664
+ // Read the marker FIRST (fail-open null) — it is the AndroidKeyStore-independent
1665
+ // signal that survives a keystore death.
1666
+ const marker = await (0, identityMarker_1.readIdentityMarker)();
1667
+ const migration = await KeyManager._ensureIdentitySlotsMigrated();
1668
+ if (migration.mode === 'deferred') {
1669
+ return { state: 'unavailable', cause: migration.cause };
1670
+ }
1671
+ let privateKey;
1672
+ let publicKey;
1673
+ try {
1674
+ const store = await initSecureStore();
1675
+ const readOpts = KeyManager._slotOpts(migration.layout.primaryService);
1676
+ privateKey = await store.getItemAsync(migration.layout.primaryPrivateKeyName, readOpts);
1677
+ publicKey = await store.getItemAsync(migration.layout.primaryPublicKeyName, readOpts);
1678
+ }
1679
+ catch (error) {
1680
+ // Storage threw — NEVER cache this verdict; callers retry.
1681
+ return { state: 'unavailable', cause: error };
1682
+ }
1683
+ if (KeyManager._isHealthyPair(privateKey, publicKey) && publicKey) {
1684
+ const canonicalPublic = publicKey.toLowerCase();
1685
+ // Backfill the marker when missing or pointing at a DIFFERENT identity —
1686
+ // e.g. a loss that predates markers, healed on first healthy read.
1687
+ if (!marker || marker.publicKey.toLowerCase() !== canonicalPublic) {
1688
+ try {
1689
+ await (0, identityMarker_1.writeIdentityMarker)({ publicKey: canonicalPublic, origin: 'backfill' });
1690
+ }
1691
+ catch (error) {
1692
+ logger_1.logger.warn('Failed to backfill identity marker', { component: 'KeyManager' }, error);
1693
+ }
1694
+ }
1695
+ if (!bypassCache) {
1696
+ KeyManager.cachedPublicKey = canonicalPublic;
1697
+ KeyManager.cachedHasIdentity = true;
1698
+ KeyManager.cachedPublicKeyResolved = false;
1699
+ }
1700
+ return { state: 'present', publicKey: canonicalPublic };
1701
+ }
1702
+ // Read succeeded but no healthy pair present.
1703
+ if (!bypassCache) {
1704
+ KeyManager.cachedHasIdentity = false;
1705
+ KeyManager.cachedPublicKeyResolved = true;
1706
+ }
1707
+ if (marker) {
1708
+ return { state: 'lost', marker };
1709
+ }
1710
+ return { state: 'absent' };
1711
+ }
1712
+ /**
1713
+ * Delete the stored identity (both keys)
1714
+ * Use with EXTREME caution - this is irreversible without a recovery phrase
1715
+ * This should ONLY be called when explicitly requested by the user
1716
+ * @param skipBackup - If true, skip backup before deletion (default: false)
1717
+ * @param force - If true, skip confirmation checks (default: false)
1718
+ * @param userConfirmed - If true, user has explicitly confirmed deletion (default: false)
1719
+ */
1720
+ static async deleteIdentity(skipBackup = false, force = false, userConfirmed = false) {
1721
+ if (isWebPlatform()) {
1722
+ return; // Identity storage is only available on native platforms, nothing to delete
1723
+ }
1724
+ // CRITICAL SAFEGUARD: Require explicit user confirmation unless force is true
1725
+ if (!force && !userConfirmed) {
1726
+ throw new Error('Identity deletion requires explicit user confirmation. This is a safety measure to prevent accidental data loss.');
1727
+ }
1728
+ if (!force) {
1729
+ // May throw IdentityUnavailableError if storage is locked — correct: a
1730
+ // non-force delete must abort rather than run against an unreadable store.
1731
+ const hasIdentity = await KeyManager.hasIdentity();
1732
+ if (!hasIdentity) {
1733
+ return; // Nothing to delete
1734
+ }
1735
+ }
1736
+ const store = await initSecureStore();
1737
+ // ALWAYS create backup before deletion unless explicitly skipped
1738
+ if (!skipBackup) {
1739
+ try {
1740
+ const backupSuccess = await KeyManager.backupIdentity();
1741
+ if (!backupSuccess && (0, logger_1.isDev)()) {
1742
+ logger_1.logger.warn('Failed to backup identity before deletion - proceeding anyway', { component: 'KeyManager' });
1743
+ }
1744
+ }
1745
+ catch (backupError) {
1746
+ if ((0, logger_1.isDev)()) {
1747
+ logger_1.logger.warn('Failed to backup identity before deletion', { component: 'KeyManager' }, backupError);
1748
+ }
1749
+ }
1750
+ }
1751
+ // Delete the primary from the active layout (authoritative), then best-effort
1752
+ // delete BOTH generations so a stale legacy copy can never resurrect the
1753
+ // identity after deletion.
1754
+ const migration = await KeyManager._ensureIdentitySlotsMigrated();
1755
+ if (migration.mode !== 'deferred') {
1756
+ const layout = migration.layout;
1757
+ const readOpts = KeyManager._slotOpts(layout.primaryService);
1758
+ await store.deleteItemAsync(layout.primaryPrivateKeyName, readOpts);
1759
+ await store.deleteItemAsync(layout.primaryPublicKeyName, readOpts);
1760
+ }
1761
+ await KeyManager._bestEffortDeleteV2Primary(store);
1762
+ await KeyManager._bestEffortDelete(store, STORAGE_KEYS.PRIVATE_KEY);
1763
+ await KeyManager._bestEffortDelete(store, STORAGE_KEYS.PUBLIC_KEY);
1764
+ // Always drop the stored recovery mnemonic — it is scoped to the identity
1765
+ // being deleted, so a leftover would let Settings reveal a stale phrase for
1766
+ // an identity that no longer exists (or a DIFFERENT one after re-onboarding).
1767
+ await KeyManager.deleteRecoveryMnemonic();
1768
+ // Also clear backups + the shared slot on force deletion, so a deleted
1769
+ // identity cannot be resurrected from any recovery source.
1770
+ if (force) {
1771
+ await KeyManager._bestEffortDeleteBackupsAllGenerations(store);
1772
+ await KeyManager._clearSharedSlot(store);
1773
+ }
1774
+ // Clear the marker AFTER key deletion succeeds — a marker must never outlive
1775
+ // its identity (a leftover marker would route a truly-absent device to
1776
+ // `recovery` instead of `welcome`).
1777
+ try {
1778
+ await (0, identityMarker_1.clearIdentityMarker)();
1779
+ }
1780
+ catch (error) {
1781
+ logger_1.logger.warn('Failed to clear identity marker during delete', { component: 'KeyManager' }, error);
1782
+ }
1783
+ // Invalidate cache LAST — its subscriber fan-out fires only after both the
1784
+ // keys AND the marker are gone, so a routing subscriber that re-reads on the
1785
+ // notification observes `absent`, never a transient `lost`.
1786
+ KeyManager.invalidateCache();
1787
+ }
1788
+ /**
1789
+ * Backup identity to SecureStore (separate backup storage)
1790
+ * This provides a recovery mechanism if primary storage fails
1791
+ */
1792
+ static async backupIdentity() {
1793
+ if (isWebPlatform()) {
1794
+ return false; // Identity storage is only available on native platforms
1795
+ }
1796
+ try {
1797
+ const store = await initSecureStore();
1798
+ const migration = await KeyManager._ensureIdentitySlotsMigrated();
1799
+ if (migration.mode === 'deferred') {
1800
+ return false; // Cannot read the primary safely → nothing to back up
1801
+ }
1802
+ const layout = migration.layout;
1803
+ // Read the primary DIRECTLY (raw) rather than via getPublicKey (which now
1804
+ // throws) — a locked keychain here should simply mean "nothing to back up".
1805
+ const primaryReadOpts = KeyManager._slotOpts(layout.primaryService);
1806
+ const privateKey = await store.getItemAsync(layout.primaryPrivateKeyName, primaryReadOpts);
1807
+ const publicKey = await store.getItemAsync(layout.primaryPublicKeyName, primaryReadOpts);
1808
+ if (!privateKey || !publicKey) {
1809
+ return false; // Nothing to backup
1810
+ }
1811
+ // Store backup in SecureStore (still secure, but separate from primary storage)
1812
+ await store.setItemAsync(layout.backupPrivateKeyName, privateKey, KeyManager._privateWriteOpts(store, layout.backupService));
1813
+ await store.setItemAsync(layout.backupPublicKeyName, publicKey, KeyManager._slotOpts(layout.backupService));
1814
+ await store.setItemAsync(layout.backupTimestampName, Date.now().toString(), KeyManager._slotOpts(layout.backupService));
1815
+ return true;
1816
+ }
1817
+ catch (error) {
1818
+ if ((0, logger_1.isDev)()) {
1819
+ logger_1.logger.error('Failed to backup identity', error, { component: 'KeyManager' });
1820
+ }
1821
+ return false;
1822
+ }
1823
+ }
1824
+ /**
1825
+ * Verify identity integrity — checks keys are valid, accessible, derive
1826
+ * consistently, AND can sign + verify a probe message.
1827
+ *
1828
+ * Returns true only when the full sign/verify roundtrip succeeds. Use
1829
+ * this on app start to detect silent corruption before the user finds
1830
+ * out by failing to sign in.
1831
+ */
1832
+ static async verifyIdentityIntegrity() {
1833
+ if (isWebPlatform()) {
1834
+ return false; // Identity storage is only available on native platforms
1835
+ }
1836
+ try {
1837
+ const privateKey = await KeyManager.getPrivateKey();
1838
+ const publicKey = await KeyManager.getPublicKey();
1839
+ if (!privateKey || !publicKey) {
1840
+ return false;
1841
+ }
1842
+ // Validate formats
1843
+ if (!KeyManager.isValidPrivateKey(privateKey)) {
1844
+ return false;
1845
+ }
1846
+ if (!KeyManager.isValidPublicKey(publicKey)) {
1847
+ return false;
1848
+ }
1849
+ // Verify public key derives from private key (case-insensitive
1850
+ // because hex is case-insensitive — legacy uppercase stored values
1851
+ // must still validate).
1852
+ const derivedPublicKey = KeyManager.derivePublicKey(privateKey);
1853
+ if (derivedPublicKey.toLowerCase() !== publicKey.toLowerCase()) {
1854
+ return false; // Keys don't match
1855
+ }
1856
+ // Full sign/verify probe — proves the keypair is functional, not just
1857
+ // bytewise parseable. A previous version of this method would return true
1858
+ // without proving the signing primitive could operate on the key.
1859
+ const canonicalPrivateKey = KeyManager.canonicalPrivateKey(privateKey);
1860
+ const probeHash = '0'.repeat(64);
1861
+ const signature = (0, secp256k1_1.signSecp256k1Digest)(canonicalPrivateKey, probeHash);
1862
+ if (!(0, secp256k1_1.verifySecp256k1Digest)(publicKey, probeHash, signature)) {
1863
+ logger_1.logger.error('Identity sign/verify probe failed during integrity check', undefined, { component: 'KeyManager' });
1864
+ return false;
1865
+ }
1866
+ return true;
1867
+ }
1868
+ catch (error) {
1869
+ logger_1.logger.error('Identity integrity check failed', error, { component: 'KeyManager' });
1870
+ return false;
1871
+ }
1872
+ }
1873
+ /**
1874
+ * Restore identity from backup if primary storage is genuinely missing or
1875
+ * corrupt.
1876
+ *
1877
+ * SAFETY (three independent guards against silently switching accounts):
1878
+ * 1. If the primary passes a full sign/verify probe, do nothing.
1879
+ * 2. If the primary keys CANNOT BE READ (storage threw — e.g. a transient
1880
+ * keychain lock during a background launch), do nothing. We must NOT
1881
+ * treat "couldn't read" as "corrupted" and restore a possibly-stale
1882
+ * backup over an identity that is actually fine but momentarily
1883
+ * inaccessible.
1884
+ * 3. If a primary private/public key IS present but does not match the
1885
+ * backup, the backup may belong to a different identity — refuse, so we
1886
+ * never silently switch the user to another account.
1887
+ *
1888
+ * Only when the primary is provably absent (read succeeded, returned
1889
+ * null/empty) or provably corrupt (read succeeded, bytes malformed AND no
1890
+ * conflicting key material is present) do we rebuild it from the backup.
1891
+ */
1892
+ static async restoreIdentityFromBackup() {
1893
+ if (isWebPlatform()) {
1894
+ return false; // Identity storage is only available on native platforms
1895
+ }
1896
+ try {
1897
+ const store = await initSecureStore();
1898
+ const migration = await KeyManager._ensureIdentitySlotsMigrated();
1899
+ if (migration.mode === 'deferred') {
1900
+ // Storage locked — refuse to restore (guard 2). Retry a later call.
1901
+ logger_1.logger.warn('restoreIdentityFromBackup: identity storage unavailable. Refusing to restore.', { component: 'KeyManager' });
1902
+ return false;
1903
+ }
1904
+ const layout = migration.layout;
1905
+ const primaryReadOpts = KeyManager._slotOpts(layout.primaryService);
1906
+ const backupReadOpts = KeyManager._slotOpts(layout.backupService);
1907
+ // Read the primary DIRECTLY (not via the error-swallowing getters) so
1908
+ // we can distinguish a transient read failure from a genuinely absent
1909
+ // key. A thrown read here means the keychain is locked/unavailable —
1910
+ // bail out and let a later call retry rather than risk restoring over a
1911
+ // healthy-but-locked identity.
1912
+ let primaryPrivate;
1913
+ let primaryPublic;
1914
+ try {
1915
+ primaryPrivate = await store.getItemAsync(layout.primaryPrivateKeyName, primaryReadOpts);
1916
+ primaryPublic = await store.getItemAsync(layout.primaryPublicKeyName, primaryReadOpts);
1917
+ }
1918
+ catch (error) {
1919
+ logger_1.logger.warn('restoreIdentityFromBackup: could not read primary (transient?). Refusing to restore.', { component: 'KeyManager' }, error);
1920
+ return false;
1921
+ }
1922
+ // If the primary reads back as a complete, self-consistent identity, it
1923
+ // is healthy — nothing to restore. (Guard 1.)
1924
+ if (primaryPrivate && primaryPublic) {
1925
+ if (KeyManager.isValidPrivateKey(primaryPrivate) &&
1926
+ KeyManager.isValidPublicKey(primaryPublic) &&
1927
+ KeyManager.derivePublicKey(primaryPrivate).toLowerCase() === primaryPublic.toLowerCase()) {
1928
+ return false;
1929
+ }
1930
+ }
1931
+ // Load + validate the backup.
1932
+ const backupPrivateKey = await store.getItemAsync(layout.backupPrivateKeyName, backupReadOpts);
1933
+ const backupPublicKey = await store.getItemAsync(layout.backupPublicKeyName, backupReadOpts);
1934
+ if (!backupPrivateKey || !backupPublicKey) {
1935
+ return false; // No backup available
1936
+ }
1937
+ if (!KeyManager.isValidPrivateKey(backupPrivateKey) || !KeyManager.isValidPublicKey(backupPublicKey)) {
1938
+ logger_1.logger.warn('Backup identity is malformed; refusing to restore', { component: 'KeyManager' });
1939
+ return false;
1940
+ }
1941
+ // Verify backup keys derive consistently. Hex is case-insensitive so
1942
+ // normalize both sides — a legacy uppercase-stored backup must still
1943
+ // be considered valid.
1944
+ const derivedPublicKey = KeyManager.derivePublicKey(backupPrivateKey);
1945
+ if (derivedPublicKey.toLowerCase() !== backupPublicKey.toLowerCase()) {
1946
+ logger_1.logger.warn('Backup public key does not match derived; refusing to restore', { component: 'KeyManager' });
1947
+ return false;
1948
+ }
1949
+ // Guard 3: if ANY primary key material is still present and identifies a
1950
+ // DIFFERENT identity than the backup, refuse — the backup may be from a
1951
+ // completely different account and restoring it would silently switch
1952
+ // the user. We check the private key too (not just the public): a
1953
+ // present private key that derives to a non-backup public means a real,
1954
+ // different identity is sitting in the primary slot.
1955
+ if (primaryPublic &&
1956
+ primaryPublic.toLowerCase() !== backupPublicKey.toLowerCase()) {
1957
+ logger_1.logger.error('Primary public key is present, corrupt-or-mismatched, AND differs from the backup. Refusing to restore to avoid switching accounts.', undefined, { component: 'KeyManager' });
1958
+ return false;
1959
+ }
1960
+ if (primaryPrivate &&
1961
+ KeyManager.isValidPrivateKey(primaryPrivate) &&
1962
+ KeyManager.derivePublicKey(primaryPrivate).toLowerCase() !== backupPublicKey.toLowerCase()) {
1963
+ logger_1.logger.error('Primary private key identifies a DIFFERENT identity than the backup. Refusing to restore to avoid switching accounts.', undefined, { component: 'KeyManager' });
1964
+ return false;
1965
+ }
1966
+ // Safe to restore: rebuild the primary using the same atomic write
1967
+ // path createIdentity uses, including verification.
1968
+ try {
1969
+ await KeyManager._persistIdentityAtomic(backupPrivateKey, backupPublicKey, 'restore');
1970
+ }
1971
+ catch (error) {
1972
+ logger_1.logger.error('Failed to persist identity restored from backup', error, { component: 'KeyManager' });
1973
+ return false;
1974
+ }
1975
+ await store.setItemAsync(layout.backupTimestampName, Date.now().toString(), backupReadOpts);
1976
+ return true;
1977
+ }
1978
+ catch (error) {
1979
+ logger_1.logger.error('Failed to restore identity from backup', error, { component: 'KeyManager' });
1980
+ return false;
1981
+ }
1982
+ }
1983
+ /**
1984
+ * Recovery ladder — restore a `lost` identity from an independent,
1985
+ * `key_v1`-surviving source WITHOUT the user re-entering their recovery phrase.
1986
+ *
1987
+ * Gated on {@link getIdentityStatus} being `lost` (marker present, keys empty):
1988
+ * - `present` / `absent` → `not-lost` (nothing to recover / nothing lost)
1989
+ * - `unavailable` → `unavailable` (keychain locked; retry later)
1990
+ *
1991
+ * Rungs, tried in order, each fully validated (well-formed + derive-match +
1992
+ * `publicKey === marker.publicKey`, so a source holding a DIFFERENT account is
1993
+ * SKIPPED, never restored):
1994
+ * 1. the v2 backup slot (independent keychain key from the primary), then
1995
+ * 2. the cross-app shared slot (Android bridge `getShared` / iOS keychain
1996
+ * group) — the copy that survives a primary+backup `key_v1` death.
1997
+ *
1998
+ * On success it re-persists via {@link _persistIdentityAtomic} (origin
1999
+ * `'restore'`) and invalidates the cache so routing re-reads `present`. When no
2000
+ * rung matches, the UI proceeds to recovery-phrase entry.
2001
+ */
2002
+ static async attemptIdentityRecovery() {
2003
+ if (isWebPlatform()) {
2004
+ return { recovered: false, reason: 'not-lost' };
2005
+ }
2006
+ const status = await KeyManager.getIdentityStatus({ bypassCache: true });
2007
+ if (status.state === 'present' || status.state === 'absent') {
2008
+ return { recovered: false, reason: 'not-lost' };
2009
+ }
2010
+ if (status.state === 'unavailable') {
2011
+ return { recovered: false, reason: 'unavailable' };
2012
+ }
2013
+ // status.state === 'lost'
2014
+ const expectedPublic = status.marker.publicKey.toLowerCase();
2015
+ let sawMismatch = false;
2016
+ // Rung 1: backup slot.
2017
+ const backupCandidate = await KeyManager._readBackupCandidate();
2018
+ if (backupCandidate) {
2019
+ if (backupCandidate.publicKey.toLowerCase() === expectedPublic) {
2020
+ if (await KeyManager._commitRecovery(backupCandidate.privateKey, backupCandidate.publicKey)) {
2021
+ return { recovered: true, source: 'backup', publicKey: backupCandidate.publicKey };
2022
+ }
2023
+ }
2024
+ else {
2025
+ sawMismatch = true;
2026
+ }
2027
+ }
2028
+ // Rung 2: cross-app shared slot.
2029
+ const sharedCandidate = await KeyManager._readSharedCandidate();
2030
+ if (sharedCandidate) {
2031
+ if (sharedCandidate.publicKey.toLowerCase() === expectedPublic) {
2032
+ if (await KeyManager._commitRecovery(sharedCandidate.privateKey, sharedCandidate.publicKey)) {
2033
+ return { recovered: true, source: 'shared', publicKey: sharedCandidate.publicKey };
2034
+ }
2035
+ }
2036
+ else {
2037
+ sawMismatch = true;
2038
+ }
2039
+ }
2040
+ // A source existed but identified a DIFFERENT account — never silently
2041
+ // switched. Report `mismatch` so the UI can require explicit confirmation.
2042
+ return { recovered: false, reason: sawMismatch ? 'mismatch' : 'no-sources' };
2043
+ }
2044
+ /** Read the active-layout backup slot as a healthy candidate, or null. @internal */
2045
+ static async _readBackupCandidate() {
2046
+ try {
2047
+ const migration = await KeyManager._ensureIdentitySlotsMigrated();
2048
+ if (migration.mode === 'deferred') {
2049
+ return null;
2050
+ }
2051
+ const layout = migration.layout;
2052
+ const backupReadOpts = KeyManager._slotOpts(layout.backupService);
2053
+ const store = await initSecureStore();
2054
+ const privateKey = await store.getItemAsync(layout.backupPrivateKeyName, backupReadOpts);
2055
+ const publicKey = await store.getItemAsync(layout.backupPublicKeyName, backupReadOpts);
2056
+ if (KeyManager._isHealthyPair(privateKey, publicKey) && privateKey && publicKey) {
2057
+ return { privateKey, publicKey };
2058
+ }
2059
+ return null;
2060
+ }
2061
+ catch (error) {
2062
+ logger_1.logger.warn('Recovery: failed to read backup slot', { component: 'KeyManager' }, error);
2063
+ return null;
2064
+ }
2065
+ }
2066
+ /** Read the cross-app shared slot as a healthy candidate, or null. @internal */
2067
+ static async _readSharedCandidate() {
2068
+ try {
2069
+ const privateKey = await KeyManager.getSharedPrivateKey();
2070
+ const publicKey = await KeyManager.getSharedPublicKey();
2071
+ if (KeyManager._isHealthyPair(privateKey, publicKey) && privateKey && publicKey) {
2072
+ return { privateKey, publicKey };
2073
+ }
2074
+ return null;
2075
+ }
2076
+ catch (error) {
2077
+ logger_1.logger.warn('Recovery: failed to read shared slot', { component: 'KeyManager' }, error);
2078
+ return null;
2079
+ }
2080
+ }
2081
+ /** Persist a validated recovery candidate + refresh caches/subscribers. @internal */
2082
+ static async _commitRecovery(privateKey, publicKey) {
2083
+ try {
2084
+ await KeyManager._persistIdentityAtomic(privateKey, publicKey, 'restore');
2085
+ KeyManager.invalidateCache();
2086
+ return true;
2087
+ }
2088
+ catch (error) {
2089
+ logger_1.logger.error('Recovery: failed to persist recovered identity', error, { component: 'KeyManager' });
2090
+ return false;
2091
+ }
2092
+ }
2093
+ /**
2094
+ * Derive public key from a private key (without storing)
2095
+ */
2096
+ static derivePublicKey(privateKey) {
2097
+ return (0, secp256k1_1.deriveSecp256k1PublicKey)(KeyManager.canonicalPrivateKey(privateKey));
2098
+ }
2099
+ /**
2100
+ * Normalize a public key to uncompressed, lowercased hex. Used when building
2101
+ * signed rotation payloads so legacy compressed/cased encodings still verify.
2102
+ */
2103
+ static canonicalPublicKey(publicKey) {
2104
+ return (0, secp256k1_1.normalizeSecp256k1PublicKey)(publicKey);
2105
+ }
2106
+ /**
2107
+ * Validate that a string is a valid public key
2108
+ *
2109
+ * Returns false on parse errors (invalid input is the expected fail mode here).
2110
+ * Errors are logged at debug level so they're available when troubleshooting
2111
+ * but don't pollute production logs.
2112
+ */
2113
+ static isValidPublicKey(publicKey) {
2114
+ if (typeof publicKey !== 'string' || publicKey.length === 0) {
2115
+ return false;
2116
+ }
2117
+ // secp256k1 public keys are either uncompressed (130 hex chars, starts with 04)
2118
+ // or compressed (66 hex chars, starts with 02 or 03). Anything else is
2119
+ // clearly bogus; reject up front so we never silently widen the trust
2120
+ // boundary by accepting whatever BN(...) parses out of junk input.
2121
+ if (!/^[0-9a-fA-F]+$/.test(publicKey)) {
2122
+ return false;
2123
+ }
2124
+ if (publicKey.length !== 130 && publicKey.length !== 66) {
2125
+ return false;
2126
+ }
2127
+ if ((0, secp256k1_1.isValidSecp256k1PublicKey)(publicKey)) {
2128
+ return true;
2129
+ }
2130
+ if ((0, logger_1.isDev)()) {
2131
+ logger_1.logger.debug('[oxy.crypto] isValidPublicKey rejected input', { component: 'KeyManager' });
2132
+ }
2133
+ return false;
2134
+ }
2135
+ /**
2136
+ * Validate that a string is a valid private key.
2137
+ *
2138
+ * secp256k1 private keys are 256-bit, so 64 hex chars. We require strict
2139
+ * hex-only input so malformed text can never be coerced into a scalar.
2140
+ */
2141
+ static isValidPrivateKey(privateKey) {
2142
+ if (typeof privateKey !== 'string' || privateKey.length === 0) {
2143
+ return false;
2144
+ }
2145
+ if (!/^[0-9a-fA-F]+$/.test(privateKey)) {
2146
+ return false;
2147
+ }
2148
+ // Legacy storage may have stripped leading zero bytes. Accept 1..64 chars
2149
+ // here and normalize before curve validation.
2150
+ if (privateKey.length > 64) {
2151
+ return false;
2152
+ }
2153
+ const padded = privateKey.padStart(64, '0').toLowerCase();
2154
+ // After padding, require minimum entropy: reject obvious low-scalar
2155
+ // keys. A scalar that fits in 8 hex chars (~32 bits of entropy) is a
2156
+ // degenerate / accidental key, not a real one. The existing isZero()
2157
+ // check below covers literal 0; this also rejects trivially small
2158
+ // scalars like '1', '2', etc. that would otherwise pad to a valid but
2159
+ // weak key whose public point is trivially derivable.
2160
+ if (/^0{56}/.test(padded)) {
2161
+ return false;
2162
+ }
2163
+ if ((0, secp256k1_1.isValidSecp256k1PrivateKey)(padded)) {
2164
+ return true;
2165
+ }
2166
+ if ((0, logger_1.isDev)()) {
2167
+ logger_1.logger.debug('[oxy.crypto] isValidPrivateKey rejected input', { component: 'KeyManager' });
2168
+ }
2169
+ return false;
2170
+ }
2171
+ /**
2172
+ * Derive a 32-byte, domain-separated seed from the on-device Oxy identity
2173
+ * private key via HKDF-SHA256, WITHOUT ever exposing the raw private key.
2174
+ *
2175
+ * The domain separation is carried by `info` (e.g. `"oxypay/faircoin/v1"`),
2176
+ * so distinct apps/purposes get independent seeds from the same identity.
2177
+ * The output is HKDF keying material, never the private key itself — a
2178
+ * consumer (e.g. Oxy Pay's FairCoin HD wallet) can feed it straight into
2179
+ * `HDKey.fromMasterSeed` and never touches the identity key.
2180
+ *
2181
+ * Key source (native only): prefers the shared ecosystem identity written to
2182
+ * `group.so.oxy.shared` (what a Relying Party like Oxy Pay reads), then falls
2183
+ * back to this device's primary identity (Commons/Accounts). Both reproduce
2184
+ * from the user's Oxy recovery phrase, so the derived seed is recoverable.
2185
+ *
2186
+ * @param info Context/domain-binding label (distinct labels → independent seeds).
2187
+ * @returns 32 bytes of derived keying material, or `null` on web / when no
2188
+ * identity key is available on this device.
2189
+ */
2190
+ static async deriveScopedSeed(info) {
2191
+ if (isWebPlatform()) {
2192
+ return null;
2193
+ }
2194
+ const privateKey = (await KeyManager.getSharedPrivateKey()) ?? (await KeyManager.getPrivateKey());
2195
+ if (!privateKey) {
2196
+ return null;
2197
+ }
2198
+ const ikm = hexToBytes(KeyManager.canonicalPrivateKey(privateKey));
2199
+ return (0, kdf_1.hkdfSha256)(ikm, utf8ToBytes(SCOPED_SEED_KDF_SALT), utf8ToBytes(info), 32);
2200
+ }
2201
+ /**
2202
+ * Get a shortened version of the public key for display
2203
+ * Format: first 8 chars...last 8 chars
2204
+ */
2205
+ static shortenPublicKey(publicKey) {
2206
+ if (publicKey.length <= 20)
2207
+ return publicKey;
2208
+ return `${publicKey.slice(0, 8)}...${publicKey.slice(-8)}`;
2209
+ }
2210
+ }
2211
+ exports.KeyManager = KeyManager;
2212
+ // In-memory cache for identity state (invalidated on identity changes)
2213
+ KeyManager.cachedPublicKey = null;
2214
+ KeyManager.cachedHasIdentity = null;
2215
+ KeyManager.cachedSharedPublicKey = null;
2216
+ KeyManager.cachedHasSharedIdentity = null;
2217
+ /**
2218
+ * Distinguishes "public key genuinely absent (a successful empty read, safe to
2219
+ * cache)" from "never resolved / storage threw (must NOT be cached)". A `null`
2220
+ * {@link cachedPublicKey} alone is ambiguous — this flag makes the genuine
2221
+ * absence cacheable WITHOUT ever caching a null produced by a thrown read.
2222
+ */
2223
+ KeyManager.cachedPublicKeyResolved = false;
2224
+ /** Listeners notified synchronously whenever the identity verdict may have changed. */
2225
+ KeyManager.identityChangeListeners = new Set();
2226
+ /**
2227
+ * Memoized one-run-per-process slot migration. `slotMigrationResult` caches a
2228
+ * STABLE outcome (`v2`/`legacy`); a `deferred` outcome is intentionally not
2229
+ * cached (the in-flight promise is cleared) so a later call retries once the
2230
+ * keychain unlocks.
2231
+ */
2232
+ KeyManager.slotMigrationPromise = null;
2233
+ KeyManager.slotMigrationResult = null;
2234
+ exports.default = KeyManager;