@oxyhq/services 5.16.39 → 5.16.41

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 (267) hide show
  1. package/lib/commonjs/adapters/expo/crypto.js +56 -0
  2. package/lib/commonjs/adapters/expo/crypto.js.map +1 -0
  3. package/lib/commonjs/adapters/expo/fetch.js +30 -0
  4. package/lib/commonjs/adapters/expo/fetch.js.map +1 -0
  5. package/lib/commonjs/adapters/expo/index.js +48 -0
  6. package/lib/commonjs/adapters/expo/index.js.map +1 -0
  7. package/lib/commonjs/adapters/expo/storage.js +201 -0
  8. package/lib/commonjs/adapters/expo/storage.js.map +1 -0
  9. package/lib/commonjs/adapters/index.js +41 -0
  10. package/lib/commonjs/adapters/index.js.map +1 -0
  11. package/lib/commonjs/adapters/node/crypto.js +40 -0
  12. package/lib/commonjs/adapters/node/crypto.js.map +1 -0
  13. package/lib/commonjs/adapters/node/fetch.js +62 -0
  14. package/lib/commonjs/adapters/node/fetch.js.map +1 -0
  15. package/lib/commonjs/adapters/node/index.js +34 -0
  16. package/lib/commonjs/adapters/node/index.js.map +1 -0
  17. package/lib/commonjs/adapters/node/storage.js +163 -0
  18. package/lib/commonjs/adapters/node/storage.js.map +1 -0
  19. package/lib/commonjs/core/identity-session/DeviceManager.js +237 -0
  20. package/lib/commonjs/core/identity-session/DeviceManager.js.map +1 -0
  21. package/lib/commonjs/core/identity-session/INTEGRATION_GUIDE.md +287 -0
  22. package/lib/commonjs/core/identity-session/IdentityManager.js +400 -0
  23. package/lib/commonjs/core/identity-session/IdentityManager.js.map +1 -0
  24. package/lib/commonjs/core/identity-session/IdentitySessionCore.js +394 -0
  25. package/lib/commonjs/core/identity-session/IdentitySessionCore.js.map +1 -0
  26. package/lib/commonjs/core/identity-session/RefreshManager.js +137 -0
  27. package/lib/commonjs/core/identity-session/RefreshManager.js.map +1 -0
  28. package/lib/commonjs/core/identity-session/SessionManager.js +427 -0
  29. package/lib/commonjs/core/identity-session/SessionManager.js.map +1 -0
  30. package/lib/commonjs/core/identity-session/createIdentitySessionCore.js +24 -0
  31. package/lib/commonjs/core/identity-session/createIdentitySessionCore.js.map +1 -0
  32. package/lib/commonjs/core/identity-session/errors.js +176 -0
  33. package/lib/commonjs/core/identity-session/errors.js.map +1 -0
  34. package/lib/commonjs/core/identity-session/index.js +80 -0
  35. package/lib/commonjs/core/identity-session/index.js.map +1 -0
  36. package/lib/commonjs/core/identity-session/types.js +2 -0
  37. package/lib/commonjs/core/identity-session/types.js.map +1 -0
  38. package/lib/commonjs/core/index.js +2 -21
  39. package/lib/commonjs/core/index.js.map +1 -1
  40. package/lib/commonjs/index.js +58 -8
  41. package/lib/commonjs/index.js.map +1 -1
  42. package/lib/commonjs/models/interfaces.js +7 -0
  43. package/lib/commonjs/models/interfaces.js.map +1 -1
  44. package/lib/commonjs/ui/context/OxyContext.js +434 -820
  45. package/lib/commonjs/ui/context/OxyContext.js.map +1 -1
  46. package/lib/commonjs/ui/hooks/useAvatarPicker.js +52 -0
  47. package/lib/commonjs/ui/hooks/useAvatarPicker.js.map +1 -0
  48. package/lib/commonjs/ui/hooks/useIdentityTransfer.js +125 -0
  49. package/lib/commonjs/ui/hooks/useIdentityTransfer.js.map +1 -0
  50. package/lib/commonjs/ui/hooks/useTransferCodesPersistence.js +81 -0
  51. package/lib/commonjs/ui/hooks/useTransferCodesPersistence.js.map +1 -0
  52. package/lib/commonjs/ui/screens/AccountCenterScreen.js +7 -2
  53. package/lib/commonjs/ui/screens/AccountCenterScreen.js.map +1 -1
  54. package/lib/commonjs/ui/screens/AccountSettingsScreen.js +12 -5
  55. package/lib/commonjs/ui/screens/AccountSettingsScreen.js.map +1 -1
  56. package/lib/commonjs/ui/screens/AccountSwitcherScreen.js +2 -2
  57. package/lib/commonjs/ui/screens/AccountSwitcherScreen.js.map +1 -1
  58. package/lib/commonjs/ui/screens/ProfileScreen.js +6 -6
  59. package/lib/commonjs/ui/screens/ProfileScreen.js.map +1 -1
  60. package/lib/commonjs/ui/utils/sessionHelpers.js +7 -1
  61. package/lib/commonjs/ui/utils/sessionHelpers.js.map +1 -1
  62. package/lib/commonjs/utils/index.js +0 -7
  63. package/lib/commonjs/utils/index.js.map +1 -1
  64. package/lib/commonjs/utils/sessionUtils.js +8 -1
  65. package/lib/commonjs/utils/sessionUtils.js.map +1 -1
  66. package/lib/module/adapters/expo/crypto.js +51 -0
  67. package/lib/module/adapters/expo/crypto.js.map +1 -0
  68. package/lib/module/adapters/expo/fetch.js +26 -0
  69. package/lib/module/adapters/expo/fetch.js.map +1 -0
  70. package/lib/module/adapters/expo/index.js +45 -0
  71. package/lib/module/adapters/expo/index.js.map +1 -0
  72. package/lib/module/adapters/expo/storage.js +198 -0
  73. package/lib/module/adapters/expo/storage.js.map +1 -0
  74. package/lib/module/adapters/index.js +38 -0
  75. package/lib/module/adapters/index.js.map +1 -0
  76. package/lib/module/adapters/node/crypto.js +36 -0
  77. package/lib/module/adapters/node/crypto.js.map +1 -0
  78. package/lib/module/adapters/node/fetch.js +57 -0
  79. package/lib/module/adapters/node/fetch.js.map +1 -0
  80. package/lib/module/adapters/node/index.js +31 -0
  81. package/lib/module/adapters/node/index.js.map +1 -0
  82. package/lib/module/adapters/node/storage.js +159 -0
  83. package/lib/module/adapters/node/storage.js.map +1 -0
  84. package/lib/module/core/identity-session/DeviceManager.js +232 -0
  85. package/lib/module/core/identity-session/DeviceManager.js.map +1 -0
  86. package/lib/module/core/identity-session/INTEGRATION_GUIDE.md +287 -0
  87. package/lib/module/core/identity-session/IdentityManager.js +395 -0
  88. package/lib/module/core/identity-session/IdentityManager.js.map +1 -0
  89. package/lib/module/core/identity-session/IdentitySessionCore.js +390 -0
  90. package/lib/module/core/identity-session/IdentitySessionCore.js.map +1 -0
  91. package/lib/module/core/identity-session/RefreshManager.js +132 -0
  92. package/lib/module/core/identity-session/RefreshManager.js.map +1 -0
  93. package/lib/module/core/identity-session/SessionManager.js +422 -0
  94. package/lib/module/core/identity-session/SessionManager.js.map +1 -0
  95. package/lib/module/core/identity-session/createIdentitySessionCore.js +21 -0
  96. package/lib/module/core/identity-session/createIdentitySessionCore.js.map +1 -0
  97. package/lib/module/core/identity-session/errors.js +170 -0
  98. package/lib/module/core/identity-session/errors.js.map +1 -0
  99. package/lib/module/core/identity-session/index.js +17 -0
  100. package/lib/module/core/identity-session/index.js.map +1 -0
  101. package/lib/module/core/identity-session/types.js +2 -0
  102. package/lib/module/core/identity-session/types.js.map +1 -0
  103. package/lib/module/core/index.js +2 -3
  104. package/lib/module/core/index.js.map +1 -1
  105. package/lib/module/index.js +12 -2
  106. package/lib/module/index.js.map +1 -1
  107. package/lib/module/models/interfaces.js +7 -0
  108. package/lib/module/models/interfaces.js.map +1 -1
  109. package/lib/module/ui/context/OxyContext.js +436 -822
  110. package/lib/module/ui/context/OxyContext.js.map +1 -1
  111. package/lib/module/ui/hooks/useAvatarPicker.js +48 -0
  112. package/lib/module/ui/hooks/useAvatarPicker.js.map +1 -0
  113. package/lib/module/ui/hooks/useIdentityTransfer.js +121 -0
  114. package/lib/module/ui/hooks/useIdentityTransfer.js.map +1 -0
  115. package/lib/module/ui/hooks/useTransferCodesPersistence.js +77 -0
  116. package/lib/module/ui/hooks/useTransferCodesPersistence.js.map +1 -0
  117. package/lib/module/ui/screens/AccountCenterScreen.js +7 -2
  118. package/lib/module/ui/screens/AccountCenterScreen.js.map +1 -1
  119. package/lib/module/ui/screens/AccountSettingsScreen.js +12 -5
  120. package/lib/module/ui/screens/AccountSettingsScreen.js.map +1 -1
  121. package/lib/module/ui/screens/AccountSwitcherScreen.js +2 -2
  122. package/lib/module/ui/screens/AccountSwitcherScreen.js.map +1 -1
  123. package/lib/module/ui/screens/ProfileScreen.js +6 -6
  124. package/lib/module/ui/screens/ProfileScreen.js.map +1 -1
  125. package/lib/module/ui/utils/sessionHelpers.js +7 -1
  126. package/lib/module/ui/utils/sessionHelpers.js.map +1 -1
  127. package/lib/module/utils/index.js +2 -1
  128. package/lib/module/utils/index.js.map +1 -1
  129. package/lib/module/utils/sessionUtils.js +8 -1
  130. package/lib/module/utils/sessionUtils.js.map +1 -1
  131. package/lib/typescript/adapters/expo/crypto.d.ts +17 -0
  132. package/lib/typescript/adapters/expo/crypto.d.ts.map +1 -0
  133. package/lib/typescript/adapters/expo/fetch.d.ts +16 -0
  134. package/lib/typescript/adapters/expo/fetch.d.ts.map +1 -0
  135. package/lib/typescript/adapters/expo/index.d.ts +23 -0
  136. package/lib/typescript/adapters/expo/index.d.ts.map +1 -0
  137. package/lib/typescript/adapters/expo/storage.d.ts +23 -0
  138. package/lib/typescript/adapters/expo/storage.d.ts.map +1 -0
  139. package/lib/typescript/adapters/index.d.ts +13 -0
  140. package/lib/typescript/adapters/index.d.ts.map +1 -0
  141. package/lib/typescript/adapters/node/crypto.d.ts +17 -0
  142. package/lib/typescript/adapters/node/crypto.d.ts.map +1 -0
  143. package/lib/typescript/adapters/node/fetch.d.ts +16 -0
  144. package/lib/typescript/adapters/node/fetch.d.ts.map +1 -0
  145. package/lib/typescript/adapters/node/index.d.ts +23 -0
  146. package/lib/typescript/adapters/node/index.d.ts.map +1 -0
  147. package/lib/typescript/adapters/node/storage.d.ts +23 -0
  148. package/lib/typescript/adapters/node/storage.d.ts.map +1 -0
  149. package/lib/typescript/core/identity-session/DeviceManager.d.ts +64 -0
  150. package/lib/typescript/core/identity-session/DeviceManager.d.ts.map +1 -0
  151. package/lib/typescript/core/identity-session/IdentityManager.d.ts +88 -0
  152. package/lib/typescript/core/identity-session/IdentityManager.d.ts.map +1 -0
  153. package/lib/typescript/core/identity-session/IdentitySessionCore.d.ts +141 -0
  154. package/lib/typescript/core/identity-session/IdentitySessionCore.d.ts.map +1 -0
  155. package/lib/typescript/core/identity-session/RefreshManager.d.ts +36 -0
  156. package/lib/typescript/core/identity-session/RefreshManager.d.ts.map +1 -0
  157. package/lib/typescript/core/identity-session/SessionManager.d.ts +104 -0
  158. package/lib/typescript/core/identity-session/SessionManager.d.ts.map +1 -0
  159. package/lib/typescript/core/identity-session/createIdentitySessionCore.d.ts +11 -0
  160. package/lib/typescript/core/identity-session/createIdentitySessionCore.d.ts.map +1 -0
  161. package/lib/typescript/core/identity-session/errors.d.ts +63 -0
  162. package/lib/typescript/core/identity-session/errors.d.ts.map +1 -0
  163. package/lib/typescript/core/identity-session/index.d.ts +14 -0
  164. package/lib/typescript/core/identity-session/index.d.ts.map +1 -0
  165. package/lib/typescript/core/identity-session/types.d.ts +196 -0
  166. package/lib/typescript/core/identity-session/types.d.ts.map +1 -0
  167. package/lib/typescript/core/index.d.ts +1 -3
  168. package/lib/typescript/core/index.d.ts.map +1 -1
  169. package/lib/typescript/core/mixins/index.d.ts +2 -2
  170. package/lib/typescript/index.d.ts +3 -2
  171. package/lib/typescript/index.d.ts.map +1 -1
  172. package/lib/typescript/models/interfaces.d.ts +5 -36
  173. package/lib/typescript/models/interfaces.d.ts.map +1 -1
  174. package/lib/typescript/models/session.d.ts +3 -16
  175. package/lib/typescript/models/session.d.ts.map +1 -1
  176. package/lib/typescript/ui/context/OxyContext.d.ts +2 -25
  177. package/lib/typescript/ui/context/OxyContext.d.ts.map +1 -1
  178. package/lib/typescript/ui/hooks/mutations/useAccountMutations.d.ts +7 -8
  179. package/lib/typescript/ui/hooks/mutations/useAccountMutations.d.ts.map +1 -1
  180. package/lib/typescript/ui/hooks/mutations/useServicesMutations.d.ts +1 -1
  181. package/lib/typescript/ui/hooks/mutations/useServicesMutations.d.ts.map +1 -1
  182. package/lib/typescript/ui/hooks/queries/useAccountQueries.d.ts +5 -5
  183. package/lib/typescript/ui/hooks/queries/useAccountQueries.d.ts.map +1 -1
  184. package/lib/typescript/ui/hooks/useAvatarPicker.d.ts +18 -0
  185. package/lib/typescript/ui/hooks/useAvatarPicker.d.ts.map +1 -0
  186. package/lib/typescript/ui/hooks/useIdentityTransfer.d.ts +24 -0
  187. package/lib/typescript/ui/hooks/useIdentityTransfer.d.ts.map +1 -0
  188. package/lib/typescript/ui/hooks/useTransferCodesPersistence.d.ts +6 -0
  189. package/lib/typescript/ui/hooks/useTransferCodesPersistence.d.ts.map +1 -0
  190. package/lib/typescript/ui/screens/AccountCenterScreen.d.ts.map +1 -1
  191. package/lib/typescript/ui/screens/AccountSettingsScreen.d.ts.map +1 -1
  192. package/lib/typescript/ui/utils/sessionHelpers.d.ts +1 -0
  193. package/lib/typescript/ui/utils/sessionHelpers.d.ts.map +1 -1
  194. package/lib/typescript/utils/index.d.ts +0 -2
  195. package/lib/typescript/utils/index.d.ts.map +1 -1
  196. package/lib/typescript/utils/sessionUtils.d.ts.map +1 -1
  197. package/package.json +1 -1
  198. package/src/adapters/expo/crypto.ts +55 -0
  199. package/src/adapters/expo/fetch.ts +28 -0
  200. package/src/adapters/expo/index.ts +51 -0
  201. package/src/adapters/expo/storage.ts +228 -0
  202. package/src/adapters/index.ts +40 -0
  203. package/src/adapters/node/crypto.ts +39 -0
  204. package/src/adapters/node/fetch.ts +59 -0
  205. package/src/adapters/node/index.ts +37 -0
  206. package/src/adapters/node/storage.ts +170 -0
  207. package/src/core/identity-session/DeviceManager.ts +273 -0
  208. package/src/core/identity-session/INTEGRATION_GUIDE.md +287 -0
  209. package/src/core/identity-session/IdentityManager.ts +474 -0
  210. package/src/core/identity-session/IdentitySessionCore.ts +464 -0
  211. package/src/core/identity-session/RefreshManager.ts +189 -0
  212. package/src/core/identity-session/SessionManager.ts +500 -0
  213. package/src/core/identity-session/createIdentitySessionCore.ts +19 -0
  214. package/src/core/identity-session/errors.ts +197 -0
  215. package/src/core/identity-session/index.ts +15 -0
  216. package/src/core/identity-session/types.ts +188 -0
  217. package/src/core/index.ts +3 -4
  218. package/src/index.ts +28 -3
  219. package/src/models/interfaces.ts +12 -39
  220. package/src/models/session.ts +6 -16
  221. package/src/ui/context/OxyContext.tsx +442 -871
  222. package/src/ui/hooks/auth/index.ts +1 -0
  223. package/src/ui/hooks/useAvatarPicker.ts +62 -0
  224. package/src/ui/hooks/useIdentityTransfer.ts +135 -0
  225. package/src/ui/hooks/useTransferCodesPersistence.ts +80 -0
  226. package/src/ui/screens/AccountCenterScreen.tsx +7 -2
  227. package/src/ui/screens/AccountSettingsScreen.tsx +15 -8
  228. package/src/ui/screens/AccountSwitcherScreen.tsx +2 -2
  229. package/src/ui/screens/ProfileScreen.tsx +10 -10
  230. package/src/ui/utils/sessionHelpers.ts +7 -0
  231. package/src/utils/index.ts +1 -2
  232. package/src/utils/sessionUtils.ts +8 -0
  233. package/lib/commonjs/ui/context/hooks/useAuthOperations.js +0 -704
  234. package/lib/commonjs/ui/context/hooks/useAuthOperations.js.map +0 -1
  235. package/lib/commonjs/ui/context/hooks/useDeviceManagement.js +0 -73
  236. package/lib/commonjs/ui/context/hooks/useDeviceManagement.js.map +0 -1
  237. package/lib/commonjs/ui/hooks/useDeviceManagement.js +0 -73
  238. package/lib/commonjs/ui/hooks/useDeviceManagement.js.map +0 -1
  239. package/lib/commonjs/ui/hooks/useSessionManagement.js +0 -281
  240. package/lib/commonjs/ui/hooks/useSessionManagement.js.map +0 -1
  241. package/lib/commonjs/utils/deviceManager.js +0 -177
  242. package/lib/commonjs/utils/deviceManager.js.map +0 -1
  243. package/lib/module/ui/context/hooks/useAuthOperations.js +0 -698
  244. package/lib/module/ui/context/hooks/useAuthOperations.js.map +0 -1
  245. package/lib/module/ui/context/hooks/useDeviceManagement.js +0 -68
  246. package/lib/module/ui/context/hooks/useDeviceManagement.js.map +0 -1
  247. package/lib/module/ui/hooks/useDeviceManagement.js +0 -68
  248. package/lib/module/ui/hooks/useDeviceManagement.js.map +0 -1
  249. package/lib/module/ui/hooks/useSessionManagement.js +0 -276
  250. package/lib/module/ui/hooks/useSessionManagement.js.map +0 -1
  251. package/lib/module/utils/deviceManager.js +0 -171
  252. package/lib/module/utils/deviceManager.js.map +0 -1
  253. package/lib/typescript/ui/context/hooks/useAuthOperations.d.ts +0 -59
  254. package/lib/typescript/ui/context/hooks/useAuthOperations.d.ts.map +0 -1
  255. package/lib/typescript/ui/context/hooks/useDeviceManagement.d.ts +0 -27
  256. package/lib/typescript/ui/context/hooks/useDeviceManagement.d.ts.map +0 -1
  257. package/lib/typescript/ui/hooks/useDeviceManagement.d.ts +0 -27
  258. package/lib/typescript/ui/hooks/useDeviceManagement.d.ts.map +0 -1
  259. package/lib/typescript/ui/hooks/useSessionManagement.d.ts +0 -41
  260. package/lib/typescript/ui/hooks/useSessionManagement.d.ts.map +0 -1
  261. package/lib/typescript/utils/deviceManager.d.ts +0 -66
  262. package/lib/typescript/utils/deviceManager.d.ts.map +0 -1
  263. package/src/ui/context/hooks/useAuthOperations.ts +0 -773
  264. package/src/ui/context/hooks/useDeviceManagement.ts +0 -108
  265. package/src/ui/hooks/useDeviceManagement.ts +0 -108
  266. package/src/ui/hooks/useSessionManagement.ts +0 -401
  267. package/src/utils/deviceManager.ts +0 -198
@@ -1,698 +0,0 @@
1
- "use strict";
2
-
3
- import { useCallback } from 'react';
4
- import { DeviceManager } from '../../../utils/deviceManager';
5
- import { fetchSessionsWithFallback } from '../../utils/sessionHelpers';
6
- import { handleAuthError, isInvalidSessionError } from '../../utils/errorHandlers';
7
- import { KeyManager, SignatureService } from '../../../crypto';
8
- const LOGIN_ERROR_CODE = 'LOGIN_ERROR';
9
- const REGISTER_ERROR_CODE = 'REGISTER_ERROR';
10
- const LOGOUT_ERROR_CODE = 'LOGOUT_ERROR';
11
- const LOGOUT_ALL_ERROR_CODE = 'LOGOUT_ALL_ERROR';
12
-
13
- /**
14
- * Authentication operations using public key cryptography.
15
- * No passwords required - identity is based on ECDSA key pairs.
16
- */
17
- export const useAuthOperations = ({
18
- oxyServices,
19
- storage,
20
- sessions,
21
- activeSessionId,
22
- setActiveSessionId,
23
- updateSessions,
24
- saveActiveSessionId,
25
- clearSessionState,
26
- switchSession,
27
- applyLanguagePreference,
28
- onAuthStateChange,
29
- onError,
30
- loginSuccess,
31
- loginFailure,
32
- logoutStore,
33
- setAuthState,
34
- setIdentitySynced,
35
- setSyncing,
36
- logger
37
- }) => {
38
- /**
39
- * Clear session data if identity has changed
40
- * Internal helper to avoid code duplication
41
- */
42
- const clearSessionsIfIdentityChanged = useCallback(async (oldPublicKey, newPublicKey) => {
43
- if (oldPublicKey && oldPublicKey !== newPublicKey) {
44
- if (__DEV__ && logger) {
45
- logger('CRITICAL: Identity changed - clearing all session data', {
46
- oldPublicKey: oldPublicKey.substring(0, 16) + '...',
47
- newPublicKey: newPublicKey.substring(0, 16) + '...'
48
- });
49
- }
50
-
51
- // Clear all session state to prevent old identity's data from showing up
52
- await clearSessionState();
53
-
54
- // Logout from auth store (clears user, isAuthenticated, etc.)
55
- logoutStore();
56
-
57
- // Force KeyManager cache invalidation
58
- KeyManager.invalidateCache();
59
- if (__DEV__ && logger) {
60
- logger('Session state cleared for new identity');
61
- }
62
- }
63
- }, [clearSessionState, logoutStore, logger]);
64
-
65
- /**
66
- * Internal function to perform challenge-response sign in (works offline)
67
- */
68
- const performSignIn = useCallback(async publicKey => {
69
- const deviceFingerprintObj = DeviceManager.getDeviceFingerprint();
70
- const deviceFingerprint = JSON.stringify(deviceFingerprintObj);
71
- const deviceInfo = await DeviceManager.getDeviceInfo();
72
- const deviceName = deviceInfo.deviceName || DeviceManager.getDefaultDeviceName();
73
- let challenge;
74
- let isOffline = false;
75
-
76
- // Try to request challenge from server (online)
77
- try {
78
- const challengeResponse = await oxyServices.requestChallenge(publicKey);
79
- challenge = challengeResponse.challenge;
80
- } catch (error) {
81
- // Network error - generate challenge locally for offline sign-in
82
- const errorMessage = error instanceof Error ? error.message : String(error);
83
- const isNetworkError = errorMessage.includes('Network') || errorMessage.includes('network') || errorMessage.includes('Failed to fetch') || errorMessage.includes('fetch failed') || error?.code === 'NETWORK_ERROR' || error?.status === 0;
84
- if (isNetworkError) {
85
- if (__DEV__ && logger) {
86
- logger('Network unavailable, performing offline sign-in');
87
- }
88
- // Generate challenge locally
89
- challenge = await SignatureService.generateChallenge();
90
- isOffline = true;
91
- } else {
92
- // Re-throw non-network errors
93
- throw error;
94
- }
95
- }
96
-
97
- // Note: Biometric authentication check should be handled by the app layer
98
- // (e.g., accounts app) before calling signIn. The biometric preference is stored
99
- // in local storage as 'oxy_biometric_enabled' and can be checked there.
100
-
101
- // Sign the challenge
102
- const {
103
- challenge: signature,
104
- timestamp
105
- } = await SignatureService.signChallenge(challenge);
106
- let fullUser;
107
- let sessionResponse;
108
- if (isOffline) {
109
- // Offline sign-in: create local session and minimal user object
110
- if (__DEV__ && logger) {
111
- logger('Creating offline session');
112
- }
113
-
114
- // Generate a local session ID
115
- const localSessionId = `offline_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;
116
- const localDeviceId = `device_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;
117
- const expiresAt = new Date(Date.now() + 7 * 24 * 60 * 60 * 1000).toISOString(); // 7 days
118
-
119
- // Create minimal user object with publicKey as id
120
- fullUser = {
121
- id: publicKey,
122
- // Use publicKey as id (per migration document)
123
- publicKey,
124
- username: '',
125
- privacySettings: {}
126
- };
127
- sessionResponse = {
128
- sessionId: localSessionId,
129
- deviceId: localDeviceId,
130
- expiresAt,
131
- user: {
132
- id: publicKey,
133
- username: ''
134
- }
135
- };
136
-
137
- // Store offline session locally
138
- const offlineSession = {
139
- sessionId: localSessionId,
140
- deviceId: localDeviceId,
141
- expiresAt,
142
- lastActive: new Date().toISOString(),
143
- userId: publicKey,
144
- isCurrent: true
145
- };
146
- setActiveSessionId(localSessionId);
147
- await saveActiveSessionId(localSessionId);
148
- updateSessions([offlineSession], {
149
- merge: true
150
- });
151
-
152
- // Mark session as offline for later sync
153
- if (storage) {
154
- await storage.setItem(`oxy_session_${localSessionId}_offline`, 'true');
155
- }
156
- if (__DEV__ && logger) {
157
- logger('Offline sign-in successful');
158
- }
159
- } else {
160
- // Online sign-in: use normal flow
161
- // Verify and create session
162
- sessionResponse = await oxyServices.verifyChallenge(publicKey, challenge, signature, timestamp, deviceName, deviceFingerprint);
163
-
164
- // Get token for the session
165
- await oxyServices.getTokenBySession(sessionResponse.sessionId);
166
-
167
- // Get full user data
168
- fullUser = await oxyServices.getUserBySession(sessionResponse.sessionId);
169
-
170
- // IMPORTANT: user.id should be MongoDB ObjectId, not publicKey
171
- // The API should return the correct id (ObjectId) from the database
172
- // If it doesn't, we need to fix the API, not work around it here
173
- // Validate that id is ObjectId format (24 hex characters)
174
- if (fullUser.id && !/^[0-9a-fA-F]{24}$/.test(fullUser.id)) {
175
- console.warn('[useAuthOperations] User.id is not MongoDB ObjectId format:', {
176
- id: fullUser.id.substring(0, 20),
177
- publicKey: fullUser.publicKey.substring(0, 20),
178
- message: 'API should return MongoDB ObjectId as user.id, not publicKey'
179
- });
180
- // Don't override - let the API fix this issue
181
- }
182
-
183
- // Fetch device sessions
184
- let allDeviceSessions = [];
185
- try {
186
- allDeviceSessions = await fetchSessionsWithFallback(oxyServices, sessionResponse.sessionId, {
187
- fallbackDeviceId: sessionResponse.deviceId,
188
- fallbackUserId: fullUser.id,
189
- logger
190
- });
191
- } catch (error) {
192
- if (__DEV__) {
193
- console.warn('Failed to fetch device sessions after login:', error);
194
- }
195
- }
196
-
197
- // Check for existing session for same user
198
- const existingSession = allDeviceSessions.find(session => session.userId?.toString() === fullUser.id?.toString() && session.sessionId !== sessionResponse.sessionId);
199
- if (existingSession) {
200
- // Logout duplicate session
201
- try {
202
- await oxyServices.logoutSession(sessionResponse.sessionId, sessionResponse.sessionId);
203
- } catch (logoutError) {
204
- if (__DEV__) {
205
- console.warn('Failed to logout duplicate session:', logoutError);
206
- }
207
- }
208
- await switchSession(existingSession.sessionId);
209
- updateSessions(allDeviceSessions.filter(session => session.sessionId !== sessionResponse.sessionId), {
210
- merge: false
211
- });
212
- onAuthStateChange?.(fullUser);
213
- return fullUser;
214
- }
215
- setActiveSessionId(sessionResponse.sessionId);
216
- await saveActiveSessionId(sessionResponse.sessionId);
217
- updateSessions(allDeviceSessions, {
218
- merge: true
219
- });
220
- }
221
- await applyLanguagePreference(fullUser);
222
- loginSuccess(fullUser);
223
- onAuthStateChange?.(fullUser);
224
- return fullUser;
225
- }, [applyLanguagePreference, logger, loginSuccess, onAuthStateChange, oxyServices, saveActiveSessionId, setActiveSessionId, switchSession, updateSessions, storage]);
226
-
227
- /**
228
- * Create a new identity (offline-first)
229
- * Identity is purely cryptographic - no username or email required
230
- *
231
- * This function generates keys locally and does NOT register with the server yet.
232
- * Registration will happen during syncIdentity() or when username is provided.
233
- *
234
- * @param username - Optional username to set during registration (if online)
235
- */
236
- const createIdentity = useCallback(async username => {
237
- if (!storage) throw new Error('Storage not initialized');
238
- setAuthState({
239
- isLoading: true,
240
- error: null
241
- });
242
- try {
243
- // CRITICAL: Get old public key before creating new identity
244
- // If identity changes, we must clear all session data to prevent data leakage
245
- const oldPublicKey = await KeyManager.getPublicKey().catch(() => null);
246
- if (__DEV__ && logger) {
247
- logger('Creating new identity', {
248
- hadPreviousIdentity: !!oldPublicKey
249
- });
250
- }
251
-
252
- // Generate new key pair directly (works offline)
253
- const {
254
- publicKey,
255
- privateKey
256
- } = await KeyManager.generateKeyPair();
257
- await KeyManager.importKeyPair(privateKey);
258
- if (__DEV__ && logger) {
259
- logger('Identity keys generated', {
260
- publicKey: publicKey.substring(0, 16) + '...'
261
- });
262
- }
263
-
264
- // Clear sessions if identity changed (prevents data leakage)
265
- await clearSessionsIfIdentityChanged(oldPublicKey, publicKey);
266
-
267
- // Mark as not synced initially
268
- await storage.setItem('oxy_identity_synced', 'false');
269
- setIdentitySynced(false);
270
-
271
- // If username provided, try to register immediately (online only)
272
- if (username) {
273
- // Validate username format before attempting registration
274
- const trimmedUsername = username.trim();
275
- if (trimmedUsername && /^[a-zA-Z0-9]{3,30}$/.test(trimmedUsername)) {
276
- try {
277
- const {
278
- signature,
279
- timestamp
280
- } = await SignatureService.createRegistrationSignature();
281
- await oxyServices.register(publicKey, signature, timestamp, trimmedUsername);
282
-
283
- // Mark as synced (Zustand store + storage)
284
- await storage.setItem('oxy_identity_synced', 'true');
285
- setIdentitySynced(true);
286
- if (__DEV__ && logger) {
287
- logger('Identity synced with server successfully with username');
288
- }
289
- return {
290
- synced: true
291
- };
292
- } catch (syncError) {
293
- // Offline or server error - identity created locally but not synced
294
- if (__DEV__ && logger) {
295
- logger('Identity created locally with username (offline), will sync when online', syncError);
296
- }
297
- return {
298
- synced: false
299
- };
300
- }
301
- }
302
- }
303
-
304
- // No username provided - defer registration until later
305
- if (__DEV__ && logger) {
306
- logger('Identity created locally without username, will register during sync');
307
- }
308
- return {
309
- synced: false
310
- };
311
- } catch (error) {
312
- // CRITICAL: Never delete identity on error - it may have been successfully created
313
- // Only log the error and let the user recover using their backup file
314
- // Identity deletion should ONLY happen when explicitly requested by the user
315
- if (__DEV__ && logger) {
316
- logger('Error during identity creation (identity may still exist):', error);
317
- }
318
-
319
- // Check if identity was actually created (keys exist)
320
- const hasIdentity = await KeyManager.hasIdentity().catch(() => false);
321
- if (hasIdentity) {
322
- // Identity exists - don't delete it! Just mark as not synced
323
- await storage.setItem('oxy_identity_synced', 'false').catch(() => {});
324
- setIdentitySynced(false);
325
- if (__DEV__ && logger) {
326
- logger('Identity was created but sync failed - user can sync later');
327
- }
328
- } else {
329
- // No identity exists - this was a generation failure, safe to clean up sync flag
330
- await storage.removeItem('oxy_identity_synced').catch(() => {});
331
- setIdentitySynced(false);
332
- }
333
- const message = handleAuthError(error, {
334
- defaultMessage: 'Failed to create identity',
335
- code: REGISTER_ERROR_CODE,
336
- onError,
337
- setAuthError: msg => setAuthState({
338
- error: msg
339
- }),
340
- logger
341
- });
342
- loginFailure(message);
343
- throw error;
344
- } finally {
345
- setAuthState({
346
- isLoading: false
347
- });
348
- }
349
- }, [oxyServices, storage, setAuthState, loginFailure, onError, logger, setIdentitySynced, clearSessionsIfIdentityChanged]);
350
-
351
- /**
352
- * Check if identity is synced with server (reads from storage for persistence)
353
- */
354
- const isIdentitySyncedFn = useCallback(async () => {
355
- if (!storage) return true;
356
- const synced = await storage.getItem('oxy_identity_synced');
357
- const isSynced = synced !== 'false';
358
- setIdentitySynced(isSynced);
359
- return isSynced;
360
- }, [storage, setIdentitySynced]);
361
-
362
- /**
363
- * Sync local identity with server (call when online)
364
- * TanStack Query handles offline mutations automatically
365
- *
366
- * @param username - Optional username to set during sync
367
- */
368
- const syncIdentity = useCallback(async username => {
369
- if (!storage) throw new Error('Storage not initialized');
370
- setAuthState({
371
- isLoading: true,
372
- error: null
373
- });
374
- setSyncing(true);
375
- try {
376
- const publicKey = await KeyManager.getPublicKey();
377
- if (!publicKey) {
378
- throw new Error('No identity found on this device');
379
- }
380
-
381
- // Check if already synced
382
- const alreadySynced = await storage.getItem('oxy_identity_synced');
383
- if (alreadySynced === 'true') {
384
- setIdentitySynced(true);
385
- return await performSignIn(publicKey);
386
- }
387
-
388
- // Check if already registered on server
389
- const {
390
- registered
391
- } = await oxyServices.checkPublicKeyRegistered(publicKey);
392
- if (!registered) {
393
- // Register with server (identity is just the publicKey)
394
- const {
395
- signature,
396
- timestamp
397
- } = await SignatureService.createRegistrationSignature();
398
- await oxyServices.register(publicKey, signature, timestamp, username);
399
- }
400
-
401
- // Mark as synced (Zustand store + storage)
402
- await storage.setItem('oxy_identity_synced', 'true');
403
- setIdentitySynced(true);
404
-
405
- // Sign in
406
- const user = await performSignIn(publicKey);
407
-
408
- // TanStack Query will automatically retry any pending mutations
409
-
410
- return user;
411
- } catch (error) {
412
- const message = handleAuthError(error, {
413
- defaultMessage: 'Failed to sync identity',
414
- code: REGISTER_ERROR_CODE,
415
- onError,
416
- setAuthError: msg => setAuthState({
417
- error: msg
418
- }),
419
- logger
420
- });
421
- loginFailure(message);
422
- throw error;
423
- } finally {
424
- setAuthState({
425
- isLoading: false
426
- });
427
- setSyncing(false);
428
- }
429
- }, [oxyServices, storage, setAuthState, performSignIn, loginFailure, onError, logger, setSyncing, setIdentitySynced]);
430
-
431
- /**
432
- * Import identity from backup file data (offline-first)
433
- *
434
- * @param backupData - The backup data to import
435
- * @param password - Password to decrypt the backup
436
- * @param username - Optional username to set during registration
437
- */
438
- const importIdentity = useCallback(async (backupData, password, username) => {
439
- if (!storage) throw new Error('Storage not initialized');
440
-
441
- // Validate arguments - ensure backupData is an object, not a string (old signature)
442
- if (!backupData || typeof backupData !== 'object' || Array.isArray(backupData)) {
443
- throw new Error('Invalid backup data. Please use the backup file import feature.');
444
- }
445
- if (!backupData.encrypted || !backupData.salt || !backupData.iv || !backupData.publicKey) {
446
- throw new Error('Invalid backup data structure. Missing required fields.');
447
- }
448
- if (!password || typeof password !== 'string') {
449
- throw new Error('Password is required for backup file import.');
450
- }
451
- setAuthState({
452
- isLoading: true,
453
- error: null
454
- });
455
- try {
456
- // CRITICAL: Get old public key before importing new identity
457
- // If identity changes, we must clear all session data to prevent data leakage
458
- const oldPublicKey = await KeyManager.getPublicKey().catch(() => null);
459
- if (__DEV__ && logger) {
460
- logger('Importing identity from backup', {
461
- hadPreviousIdentity: !!oldPublicKey,
462
- backupPublicKey: backupData.publicKey.substring(0, 16) + '...'
463
- });
464
- }
465
-
466
- // Decrypt private key from backup data
467
- const Crypto = await import('expo-crypto');
468
-
469
- // Convert hex strings to Uint8Array
470
- const saltBytes = new Uint8Array(backupData.salt.match(/.{1,2}/g)?.map(byte => parseInt(byte, 16)) || []);
471
- const ivBytes = new Uint8Array(backupData.iv.match(/.{1,2}/g)?.map(byte => parseInt(byte, 16)) || []);
472
-
473
- // Derive key from password (same algorithm as EncryptedBackupGenerator)
474
- const saltHex = Array.from(saltBytes).map(b => b.toString(16).padStart(2, '0')).join('');
475
- let key = password + saltHex;
476
- for (let i = 0; i < 10000; i++) {
477
- key = await Crypto.digestStringAsync(Crypto.CryptoDigestAlgorithm.SHA256, key);
478
- }
479
- const keyBytes = new Uint8Array(32);
480
- for (let i = 0; i < 64 && i < key.length; i += 2) {
481
- keyBytes[i / 2] = parseInt(key.substring(i, i + 2), 16);
482
- }
483
-
484
- // Decrypt private key (XOR decryption - same as encryption)
485
- const encryptedBytes = Buffer.from(backupData.encrypted, 'base64');
486
- const decryptedBytes = new Uint8Array(encryptedBytes.length);
487
- for (let i = 0; i < encryptedBytes.length; i++) {
488
- decryptedBytes[i] = encryptedBytes[i] ^ keyBytes[i % keyBytes.length] ^ ivBytes[i % ivBytes.length];
489
- }
490
- const privateKey = new TextDecoder().decode(decryptedBytes);
491
-
492
- // Import the key pair
493
- const publicKey = await KeyManager.importKeyPair(privateKey);
494
- if (__DEV__ && logger) {
495
- logger('Identity keys imported', {
496
- publicKey: publicKey.substring(0, 16) + '...'
497
- });
498
- }
499
-
500
- // Verify public key matches
501
- if (publicKey !== backupData.publicKey) {
502
- throw new Error('Backup file is corrupted or password is incorrect');
503
- }
504
-
505
- // Clear sessions if identity changed (prevents data leakage)
506
- await clearSessionsIfIdentityChanged(oldPublicKey, publicKey);
507
-
508
- // Mark as not synced
509
- await storage.setItem('oxy_identity_synced', 'false');
510
- setIdentitySynced(false);
511
-
512
- // Try to sync with server
513
- try {
514
- // Check if this identity is already registered
515
- const {
516
- registered
517
- } = await oxyServices.checkPublicKeyRegistered(publicKey);
518
- if (registered) {
519
- // Identity exists, mark as synced
520
- await storage.setItem('oxy_identity_synced', 'true');
521
- setIdentitySynced(true);
522
- return {
523
- synced: true
524
- };
525
- } else {
526
- // Need to register this identity (identity is just the publicKey)
527
- const {
528
- signature,
529
- timestamp
530
- } = await SignatureService.createRegistrationSignature();
531
- await oxyServices.register(publicKey, signature, timestamp, username);
532
- await storage.setItem('oxy_identity_synced', 'true');
533
- setIdentitySynced(true);
534
- return {
535
- synced: true
536
- };
537
- }
538
- } catch (syncError) {
539
- // Offline - identity restored locally but not synced
540
- if (__DEV__) {
541
- console.log('[Auth] Identity imported locally, will sync when online:', syncError);
542
- }
543
- return {
544
- synced: false
545
- };
546
- }
547
- } catch (error) {
548
- const message = handleAuthError(error, {
549
- defaultMessage: 'Failed to import identity. Please check your password and backup file.',
550
- code: REGISTER_ERROR_CODE,
551
- onError,
552
- setAuthError: msg => setAuthState({
553
- error: msg
554
- }),
555
- logger
556
- });
557
- loginFailure(message);
558
- throw error;
559
- } finally {
560
- setAuthState({
561
- isLoading: false
562
- });
563
- }
564
- }, [oxyServices, storage, setAuthState, loginFailure, onError, logger, setIdentitySynced, clearSessionsIfIdentityChanged]);
565
-
566
- /**
567
- * Sign in with existing identity on device
568
- */
569
- const signIn = useCallback(async deviceName => {
570
- if (!storage) throw new Error('Storage not initialized');
571
- setAuthState({
572
- isLoading: true,
573
- error: null
574
- });
575
- try {
576
- // Get stored public key
577
- const publicKey = await KeyManager.getPublicKey();
578
- if (!publicKey) {
579
- throw new Error('No identity found on this device. Please create or import an identity.');
580
- }
581
- return await performSignIn(publicKey);
582
- } catch (error) {
583
- const message = handleAuthError(error, {
584
- defaultMessage: 'Sign in failed',
585
- code: LOGIN_ERROR_CODE,
586
- onError,
587
- setAuthError: msg => setAuthState({
588
- error: msg
589
- }),
590
- logger
591
- });
592
- loginFailure(message);
593
- throw error;
594
- } finally {
595
- setAuthState({
596
- isLoading: false
597
- });
598
- }
599
- }, [storage, setAuthState, performSignIn, loginFailure, onError, logger]);
600
-
601
- /**
602
- * Logout from session
603
- */
604
- const logout = useCallback(async targetSessionId => {
605
- if (!activeSessionId) return;
606
- try {
607
- const sessionToLogout = targetSessionId || activeSessionId;
608
- await oxyServices.logoutSession(activeSessionId, sessionToLogout);
609
- const filteredSessions = sessions.filter(session => session.sessionId !== sessionToLogout);
610
- updateSessions(filteredSessions, {
611
- merge: false
612
- });
613
- if (sessionToLogout === activeSessionId) {
614
- if (filteredSessions.length > 0) {
615
- await switchSession(filteredSessions[0].sessionId);
616
- } else {
617
- await clearSessionState();
618
- return;
619
- }
620
- }
621
- } catch (error) {
622
- const isInvalid = isInvalidSessionError(error);
623
- if (isInvalid && targetSessionId === activeSessionId) {
624
- await clearSessionState();
625
- return;
626
- }
627
- handleAuthError(error, {
628
- defaultMessage: 'Logout failed',
629
- code: LOGOUT_ERROR_CODE,
630
- onError,
631
- setAuthError: msg => setAuthState({
632
- error: msg
633
- }),
634
- logger,
635
- status: isInvalid ? 401 : undefined
636
- });
637
- }
638
- }, [activeSessionId, clearSessionState, logger, onError, oxyServices, sessions, setAuthState, switchSession, updateSessions]);
639
-
640
- /**
641
- * Logout from all sessions
642
- */
643
- const logoutAll = useCallback(async () => {
644
- if (!activeSessionId) {
645
- const error = new Error('No active session found');
646
- setAuthState({
647
- error: error.message
648
- });
649
- onError?.({
650
- message: error.message,
651
- code: LOGOUT_ALL_ERROR_CODE,
652
- status: 404
653
- });
654
- throw error;
655
- }
656
- try {
657
- await oxyServices.logoutAllSessions(activeSessionId);
658
- await clearSessionState();
659
- } catch (error) {
660
- handleAuthError(error, {
661
- defaultMessage: 'Logout all failed',
662
- code: LOGOUT_ALL_ERROR_CODE,
663
- onError,
664
- setAuthError: msg => setAuthState({
665
- error: msg
666
- }),
667
- logger
668
- });
669
- throw error instanceof Error ? error : new Error('Logout all failed');
670
- }
671
- }, [activeSessionId, clearSessionState, logger, onError, oxyServices, setAuthState]);
672
-
673
- /**
674
- * Check if device has an identity stored
675
- */
676
- const hasIdentity = useCallback(async () => {
677
- return KeyManager.hasIdentity();
678
- }, []);
679
-
680
- /**
681
- * Get the public key of the stored identity
682
- */
683
- const getPublicKey = useCallback(async () => {
684
- return KeyManager.getPublicKey();
685
- }, []);
686
- return {
687
- createIdentity,
688
- importIdentity,
689
- signIn,
690
- logout,
691
- logoutAll,
692
- hasIdentity,
693
- getPublicKey,
694
- isIdentitySynced: isIdentitySyncedFn,
695
- syncIdentity
696
- };
697
- };
698
- //# sourceMappingURL=useAuthOperations.js.map