@oxyhq/services 23.2.0 → 24.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 (172) hide show
  1. package/android/src/main/java/so/oxy/identity/OxyIdentityStore.kt +21 -127
  2. package/android/src/main/java/so/oxy/session/OxyBackgroundSession.kt +184 -0
  3. package/android/src/main/java/so/oxy/session/OxyBackgroundSessionApi.kt +162 -0
  4. package/android/src/main/java/so/oxy/session/OxyBackgroundSessionModule.kt +101 -0
  5. package/android/src/main/java/so/oxy/session/OxyBackgroundSessionStore.kt +170 -0
  6. package/android/src/main/java/so/oxy/session/OxyBackgroundToken.kt +61 -0
  7. package/android/src/main/java/so/oxy/storage/OxyEncryptedPrefs.kt +241 -0
  8. package/expo-module.config.json +4 -1
  9. package/lib/commonjs/ui/components/OxyProvider.js +3 -1
  10. package/lib/commonjs/ui/components/OxyProvider.js.map +1 -1
  11. package/lib/commonjs/ui/components/ProfileButton.js +1 -1
  12. package/lib/commonjs/ui/components/ProfileButton.js.map +1 -1
  13. package/lib/commonjs/ui/components/internal/PinInput.js +3 -1
  14. package/lib/commonjs/ui/components/internal/PinInput.js.map +1 -1
  15. package/lib/commonjs/ui/components/logo/LogoText.js +4 -4
  16. package/lib/commonjs/ui/components/logo/LogoText.js.map +1 -1
  17. package/lib/commonjs/ui/components/payment/PaymentSummaryStep.js +2 -2
  18. package/lib/commonjs/ui/components/payment/PaymentSummaryStep.js.map +1 -1
  19. package/lib/commonjs/ui/context/OxyContext.js +13 -0
  20. package/lib/commonjs/ui/context/OxyContext.js.map +1 -1
  21. package/lib/commonjs/ui/screens/AccountSettingsScreen.js +2 -3
  22. package/lib/commonjs/ui/screens/AccountSettingsScreen.js.map +1 -1
  23. package/lib/commonjs/ui/screens/ChangeAvatarScreen.js +2 -3
  24. package/lib/commonjs/ui/screens/ChangeAvatarScreen.js.map +1 -1
  25. package/lib/commonjs/ui/screens/EditProfileScreen.js +2 -3
  26. package/lib/commonjs/ui/screens/EditProfileScreen.js.map +1 -1
  27. package/lib/commonjs/ui/screens/FeedbackScreen.js +3 -1
  28. package/lib/commonjs/ui/screens/FeedbackScreen.js.map +1 -1
  29. package/lib/commonjs/ui/screens/ManageAccountScreen.js +1 -1
  30. package/lib/commonjs/ui/screens/ManageAccountScreen.js.map +1 -1
  31. package/lib/commonjs/ui/screens/PremiumSubscriptionScreen.js +2 -2
  32. package/lib/commonjs/ui/screens/PremiumSubscriptionScreen.js.map +1 -1
  33. package/lib/commonjs/ui/screens/PrivacySettingsScreen.js +8 -9
  34. package/lib/commonjs/ui/screens/PrivacySettingsScreen.js.map +1 -1
  35. package/lib/commonjs/ui/screens/ProfileScreen.js +1 -1
  36. package/lib/commonjs/ui/screens/ProfileScreen.js.map +1 -1
  37. package/lib/commonjs/ui/screens/UserListScreen.js +2 -3
  38. package/lib/commonjs/ui/screens/UserListScreen.js.map +1 -1
  39. package/lib/commonjs/ui/screens/trust/TrustCenterScreen.js +1 -1
  40. package/lib/commonjs/ui/screens/trust/TrustCenterScreen.js.map +1 -1
  41. package/lib/commonjs/ui/screens/trust/TrustLeaderboardScreen.js +2 -3
  42. package/lib/commonjs/ui/screens/trust/TrustLeaderboardScreen.js.map +1 -1
  43. package/lib/commonjs/ui/screens/trust/TrustRewardsScreen.js +1 -1
  44. package/lib/commonjs/ui/screens/trust/TrustRewardsScreen.js.map +1 -1
  45. package/lib/commonjs/ui/session/backgroundSession.js +233 -0
  46. package/lib/commonjs/ui/session/backgroundSession.js.map +1 -0
  47. package/lib/commonjs/ui/session/index.js +7 -0
  48. package/lib/commonjs/ui/session/index.js.map +1 -1
  49. package/lib/commonjs/ui/session/useBackgroundSessionSync.js +82 -0
  50. package/lib/commonjs/ui/session/useBackgroundSessionSync.js.map +1 -0
  51. package/lib/commonjs/ui/utils/userUtils.js +31 -22
  52. package/lib/commonjs/ui/utils/userUtils.js.map +1 -1
  53. package/lib/module/ui/components/OxyProvider.js +3 -1
  54. package/lib/module/ui/components/OxyProvider.js.map +1 -1
  55. package/lib/module/ui/components/ProfileButton.js +2 -2
  56. package/lib/module/ui/components/ProfileButton.js.map +1 -1
  57. package/lib/module/ui/components/internal/PinInput.js +3 -1
  58. package/lib/module/ui/components/internal/PinInput.js.map +1 -1
  59. package/lib/module/ui/components/logo/LogoText.js +4 -4
  60. package/lib/module/ui/components/logo/LogoText.js.map +1 -1
  61. package/lib/module/ui/components/payment/PaymentSummaryStep.js +2 -2
  62. package/lib/module/ui/components/payment/PaymentSummaryStep.js.map +1 -1
  63. package/lib/module/ui/context/OxyContext.js +14 -1
  64. package/lib/module/ui/context/OxyContext.js.map +1 -1
  65. package/lib/module/ui/screens/AccountSettingsScreen.js +2 -3
  66. package/lib/module/ui/screens/AccountSettingsScreen.js.map +1 -1
  67. package/lib/module/ui/screens/ChangeAvatarScreen.js +3 -4
  68. package/lib/module/ui/screens/ChangeAvatarScreen.js.map +1 -1
  69. package/lib/module/ui/screens/EditProfileScreen.js +3 -4
  70. package/lib/module/ui/screens/EditProfileScreen.js.map +1 -1
  71. package/lib/module/ui/screens/FeedbackScreen.js +3 -1
  72. package/lib/module/ui/screens/FeedbackScreen.js.map +1 -1
  73. package/lib/module/ui/screens/ManageAccountScreen.js +2 -2
  74. package/lib/module/ui/screens/ManageAccountScreen.js.map +1 -1
  75. package/lib/module/ui/screens/PremiumSubscriptionScreen.js +2 -2
  76. package/lib/module/ui/screens/PremiumSubscriptionScreen.js.map +1 -1
  77. package/lib/module/ui/screens/PrivacySettingsScreen.js +9 -10
  78. package/lib/module/ui/screens/PrivacySettingsScreen.js.map +1 -1
  79. package/lib/module/ui/screens/ProfileScreen.js +1 -1
  80. package/lib/module/ui/screens/ProfileScreen.js.map +1 -1
  81. package/lib/module/ui/screens/UserListScreen.js +2 -3
  82. package/lib/module/ui/screens/UserListScreen.js.map +1 -1
  83. package/lib/module/ui/screens/trust/TrustCenterScreen.js +1 -1
  84. package/lib/module/ui/screens/trust/TrustCenterScreen.js.map +1 -1
  85. package/lib/module/ui/screens/trust/TrustLeaderboardScreen.js +2 -3
  86. package/lib/module/ui/screens/trust/TrustLeaderboardScreen.js.map +1 -1
  87. package/lib/module/ui/screens/trust/TrustRewardsScreen.js +1 -1
  88. package/lib/module/ui/screens/trust/TrustRewardsScreen.js.map +1 -1
  89. package/lib/module/ui/session/backgroundSession.js +227 -0
  90. package/lib/module/ui/session/backgroundSession.js.map +1 -0
  91. package/lib/module/ui/session/index.js +1 -0
  92. package/lib/module/ui/session/index.js.map +1 -1
  93. package/lib/module/ui/session/useBackgroundSessionSync.js +77 -0
  94. package/lib/module/ui/session/useBackgroundSessionSync.js.map +1 -0
  95. package/lib/module/ui/utils/userUtils.js +31 -22
  96. package/lib/module/ui/utils/userUtils.js.map +1 -1
  97. package/lib/typescript/commonjs/ui/components/OxyProvider.d.ts.map +1 -1
  98. package/lib/typescript/commonjs/ui/components/ProfileButton.d.ts.map +1 -1
  99. package/lib/typescript/commonjs/ui/components/internal/PinInput.d.ts.map +1 -1
  100. package/lib/typescript/commonjs/ui/context/OxyContext.d.ts.map +1 -1
  101. package/lib/typescript/commonjs/ui/context/oxyContextTypes.d.ts +22 -0
  102. package/lib/typescript/commonjs/ui/context/oxyContextTypes.d.ts.map +1 -1
  103. package/lib/typescript/commonjs/ui/screens/ChangeAvatarScreen.d.ts.map +1 -1
  104. package/lib/typescript/commonjs/ui/screens/EditProfileScreen.d.ts.map +1 -1
  105. package/lib/typescript/commonjs/ui/screens/FeedbackScreen.d.ts.map +1 -1
  106. package/lib/typescript/commonjs/ui/screens/ManageAccountScreen.d.ts.map +1 -1
  107. package/lib/typescript/commonjs/ui/screens/PrivacySettingsScreen.d.ts.map +1 -1
  108. package/lib/typescript/commonjs/ui/screens/ProfileScreen.d.ts.map +1 -1
  109. package/lib/typescript/commonjs/ui/screens/trust/trustTier.d.ts +1 -1
  110. package/lib/typescript/commonjs/ui/screens/trust/trustTier.d.ts.map +1 -1
  111. package/lib/typescript/commonjs/ui/session/backgroundSession.d.ts +42 -0
  112. package/lib/typescript/commonjs/ui/session/backgroundSession.d.ts.map +1 -0
  113. package/lib/typescript/commonjs/ui/session/index.d.ts +1 -0
  114. package/lib/typescript/commonjs/ui/session/index.d.ts.map +1 -1
  115. package/lib/typescript/commonjs/ui/session/useBackgroundSessionSync.d.ts +23 -0
  116. package/lib/typescript/commonjs/ui/session/useBackgroundSessionSync.d.ts.map +1 -0
  117. package/lib/typescript/commonjs/ui/types/navigation.d.ts +7 -0
  118. package/lib/typescript/commonjs/ui/types/navigation.d.ts.map +1 -1
  119. package/lib/typescript/commonjs/ui/utils/userUtils.d.ts +7 -12
  120. package/lib/typescript/commonjs/ui/utils/userUtils.d.ts.map +1 -1
  121. package/lib/typescript/module/ui/components/OxyProvider.d.ts.map +1 -1
  122. package/lib/typescript/module/ui/components/ProfileButton.d.ts.map +1 -1
  123. package/lib/typescript/module/ui/components/internal/PinInput.d.ts.map +1 -1
  124. package/lib/typescript/module/ui/context/OxyContext.d.ts.map +1 -1
  125. package/lib/typescript/module/ui/context/oxyContextTypes.d.ts +22 -0
  126. package/lib/typescript/module/ui/context/oxyContextTypes.d.ts.map +1 -1
  127. package/lib/typescript/module/ui/screens/ChangeAvatarScreen.d.ts.map +1 -1
  128. package/lib/typescript/module/ui/screens/EditProfileScreen.d.ts.map +1 -1
  129. package/lib/typescript/module/ui/screens/FeedbackScreen.d.ts.map +1 -1
  130. package/lib/typescript/module/ui/screens/ManageAccountScreen.d.ts.map +1 -1
  131. package/lib/typescript/module/ui/screens/PrivacySettingsScreen.d.ts.map +1 -1
  132. package/lib/typescript/module/ui/screens/ProfileScreen.d.ts.map +1 -1
  133. package/lib/typescript/module/ui/screens/trust/trustTier.d.ts +1 -1
  134. package/lib/typescript/module/ui/screens/trust/trustTier.d.ts.map +1 -1
  135. package/lib/typescript/module/ui/session/backgroundSession.d.ts +42 -0
  136. package/lib/typescript/module/ui/session/backgroundSession.d.ts.map +1 -0
  137. package/lib/typescript/module/ui/session/index.d.ts +1 -0
  138. package/lib/typescript/module/ui/session/index.d.ts.map +1 -1
  139. package/lib/typescript/module/ui/session/useBackgroundSessionSync.d.ts +23 -0
  140. package/lib/typescript/module/ui/session/useBackgroundSessionSync.d.ts.map +1 -0
  141. package/lib/typescript/module/ui/types/navigation.d.ts +7 -0
  142. package/lib/typescript/module/ui/types/navigation.d.ts.map +1 -1
  143. package/lib/typescript/module/ui/utils/userUtils.d.ts +7 -12
  144. package/lib/typescript/module/ui/utils/userUtils.d.ts.map +1 -1
  145. package/package.json +5 -5
  146. package/src/ui/components/OxyProvider.tsx +2 -0
  147. package/src/ui/components/ProfileButton.tsx +5 -2
  148. package/src/ui/components/internal/PinInput.tsx +1 -0
  149. package/src/ui/components/logo/LogoText.tsx +4 -4
  150. package/src/ui/components/payment/PaymentSummaryStep.tsx +2 -2
  151. package/src/ui/context/OxyContext.tsx +14 -0
  152. package/src/ui/context/oxyContextTypes.ts +22 -0
  153. package/src/ui/screens/AccountSettingsScreen.tsx +4 -4
  154. package/src/ui/screens/ChangeAvatarScreen.tsx +6 -3
  155. package/src/ui/screens/EditProfileScreen.tsx +6 -3
  156. package/src/ui/screens/FeedbackScreen.tsx +1 -0
  157. package/src/ui/screens/ManageAccountScreen.tsx +8 -1
  158. package/src/ui/screens/PremiumSubscriptionScreen.tsx +2 -2
  159. package/src/ui/screens/PrivacySettingsScreen.tsx +13 -11
  160. package/src/ui/screens/ProfileScreen.tsx +3 -1
  161. package/src/ui/screens/UserListScreen.tsx +2 -2
  162. package/src/ui/screens/trust/TrustCenterScreen.tsx +2 -2
  163. package/src/ui/screens/trust/TrustLeaderboardScreen.tsx +3 -3
  164. package/src/ui/screens/trust/TrustRewardsScreen.tsx +1 -1
  165. package/src/ui/screens/trust/TrustRulesScreen.tsx +1 -1
  166. package/src/ui/screens/trust/trustTier.ts +1 -1
  167. package/src/ui/session/__tests__/backgroundSession.test.ts +337 -0
  168. package/src/ui/session/backgroundSession.ts +268 -0
  169. package/src/ui/session/index.ts +1 -0
  170. package/src/ui/session/useBackgroundSessionSync.ts +93 -0
  171. package/src/ui/types/navigation.ts +7 -0
  172. package/src/ui/utils/userUtils.ts +34 -20
@@ -7,7 +7,7 @@ import {
7
7
  FlatList,
8
8
  TouchableOpacity,
9
9
  } from 'react-native';
10
- import type { ReputationLeaderboardEntry } from '@oxyhq/core';
10
+ import type { ReputationLeaderboardEntry } from '@oxyhq/contracts';
11
11
  import { getNormalizedUserHandle, logger } from '@oxyhq/core';
12
12
  import { useTheme } from '@oxyhq/bloom/theme';
13
13
  import { H6, Text } from '@oxyhq/bloom/typography';
@@ -29,7 +29,7 @@ const PODIUM_RANK = 3;
29
29
 
30
30
  const TrustLeaderboardScreen: React.FC<BaseScreenProps> = ({ navigate }) => {
31
31
  const { oxyServices, user: currentUser } = useOxy();
32
- const { t, locale } = useI18n();
32
+ const { t } = useI18n();
33
33
  const bloomTheme = useTheme();
34
34
 
35
35
  const [leaderboard, setLeaderboard] = useState<ReputationLeaderboardEntry[]>([]);
@@ -116,7 +116,7 @@ const TrustLeaderboardScreen: React.FC<BaseScreenProps> = ({ navigate }) => {
116
116
  </TouchableOpacity>
117
117
  );
118
118
  },
119
- [oxyServices, locale, currentUserId, handleEntryPress, t],
119
+ [oxyServices, currentUserId, handleEntryPress, t],
120
120
  );
121
121
 
122
122
  const keyExtractor = useCallback(
@@ -97,7 +97,7 @@ const TrustRewardsScreen: React.FC<BaseScreenProps> = () => {
97
97
  return;
98
98
  }
99
99
  setIsLoading(true);
100
- oxyServices.getReputationBalance(user.id)
100
+ oxyServices.getMyReputationBalance()
101
101
  .then((balance) => {
102
102
  setReputationTotal(balance.total || 0);
103
103
  })
@@ -4,7 +4,7 @@ import { View, Text } from 'react-native';
4
4
  import { SettingsListGroup, SettingsListItem } from '@oxyhq/bloom/settings-list';
5
5
  import { Chip } from '@oxyhq/bloom/chip';
6
6
  import { useTheme } from '@oxyhq/bloom/theme';
7
- import type { ReputationRule, ReputationCategory } from '@oxyhq/core';
7
+ import type { ReputationRule, ReputationCategory } from '@oxyhq/contracts';
8
8
  import type { BaseScreenProps } from '../../types/navigation';
9
9
  import { useSurfaceHeader } from '../../hooks/useSurfaceHeader';
10
10
  import { Loading } from '@oxyhq/bloom/loading';
@@ -1,4 +1,4 @@
1
- import type { TrustTier } from '@oxyhq/core';
1
+ import type { TrustTier } from '@oxyhq/contracts';
2
2
 
3
3
  type Translate = (key: string, vars?: Record<string, string | number>) => string;
4
4
 
@@ -0,0 +1,337 @@
1
+ /**
2
+ * The background credential's ORDERING and REVOCATION rules, which are the parts
3
+ * that can leak one account's data to another or leave a live credential behind.
4
+ *
5
+ * The native store and the mint are exercised on a device (see the design note);
6
+ * what is tested here is every decision JS makes about when to clear, when to
7
+ * provision, and — most importantly — when NOT to write.
8
+ */
9
+ const requireOptionalNativeModule = jest.fn();
10
+
11
+ jest.mock('expo-modules-core', () => ({
12
+ requireOptionalNativeModule: (...args: unknown[]) => requireOptionalNativeModule(...args),
13
+ }));
14
+
15
+ interface NativeCalls {
16
+ order: string[];
17
+ put: jest.Mock;
18
+ clear: jest.Mock;
19
+ peek: jest.Mock;
20
+ }
21
+
22
+ const DAY_MS = 24 * 60 * 60 * 1000;
23
+
24
+ function fakeNative(peekValue: { accountId: string; expiresAt: number } | null): NativeCalls {
25
+ const order: string[] = [];
26
+ return {
27
+ order,
28
+ put: jest.fn(async () => {
29
+ order.push('put');
30
+ return true;
31
+ }),
32
+ clear: jest.fn(async () => {
33
+ order.push('clear');
34
+ return true;
35
+ }),
36
+ peek: jest.fn(async () => {
37
+ order.push('peek');
38
+ return peekValue;
39
+ }),
40
+ };
41
+ }
42
+
43
+ function fakeOxy(
44
+ provision: jest.Mock,
45
+ baseURL = 'https://api.oxy.so',
46
+ ): Parameters<typeof import('../backgroundSession').syncBackgroundSession>[0]['oxyServices'] {
47
+ return {
48
+ provisionBackgroundCredential: provision,
49
+ getBaseURL: () => baseURL,
50
+ } as unknown as Parameters<
51
+ typeof import('../backgroundSession').syncBackgroundSession
52
+ >[0]['oxyServices'];
53
+ }
54
+
55
+ /**
56
+ * Re-import the module per test: it memoises the resolved native module, which is
57
+ * correct in production (one resolution per process) and must not leak between
58
+ * cases here.
59
+ */
60
+ async function loadModule(native: NativeCalls | null) {
61
+ jest.resetModules();
62
+ requireOptionalNativeModule.mockReturnValue(
63
+ native ? { put: native.put, clear: native.clear, peek: native.peek } : null,
64
+ );
65
+ return import('../backgroundSession');
66
+ }
67
+
68
+ function provisioned(overrides: Partial<Record<string, unknown>> = {}) {
69
+ return {
70
+ deviceId: 'device-1',
71
+ secret: 'bg-secret',
72
+ accountId: 'user-1',
73
+ expiresAt: new Date(Date.now() + 30 * DAY_MS).toISOString(),
74
+ ...overrides,
75
+ };
76
+ }
77
+
78
+ describe('syncBackgroundSession', () => {
79
+ test('signed out clears the credential and never calls the network', async () => {
80
+ const native = fakeNative({ accountId: 'user-1', expiresAt: Date.now() + 30 * DAY_MS });
81
+ const { syncBackgroundSession } = await loadModule(native);
82
+ const provision = jest.fn();
83
+
84
+ await syncBackgroundSession({
85
+ oxyServices: fakeOxy(provision),
86
+ userId: null,
87
+ canUsePrivateApi: true,
88
+ isCurrent: () => true,
89
+ });
90
+
91
+ expect(native.clear).toHaveBeenCalledTimes(1);
92
+ expect(provision).not.toHaveBeenCalled();
93
+ // Not even a read: signing out must not depend on anything succeeding first.
94
+ expect(native.peek).not.toHaveBeenCalled();
95
+ });
96
+
97
+ test('a credential for a DIFFERENT account is cleared BEFORE any network call', async () => {
98
+ const native = fakeNative({ accountId: 'previous-user', expiresAt: Date.now() + 30 * DAY_MS });
99
+ const { syncBackgroundSession } = await loadModule(native);
100
+ const provision = jest.fn(async () => {
101
+ native.order.push('provision');
102
+ return provisioned();
103
+ });
104
+
105
+ await syncBackgroundSession({
106
+ oxyServices: fakeOxy(provision),
107
+ userId: 'user-1',
108
+ canUsePrivateApi: true,
109
+ isCurrent: () => true,
110
+ });
111
+
112
+ // The ordering IS the guarantee: a crash after the clear leaves background
113
+ // code signed out, never serving the previous account's data.
114
+ expect(native.order).toEqual(['peek', 'clear', 'provision', 'put']);
115
+ });
116
+
117
+ test('a healthy credential for the signed-in account makes no network call', async () => {
118
+ const native = fakeNative({ accountId: 'user-1', expiresAt: Date.now() + 30 * DAY_MS });
119
+ const { syncBackgroundSession } = await loadModule(native);
120
+ const provision = jest.fn();
121
+
122
+ await syncBackgroundSession({
123
+ oxyServices: fakeOxy(provision),
124
+ userId: 'user-1',
125
+ canUsePrivateApi: true,
126
+ isCurrent: () => true,
127
+ });
128
+
129
+ expect(provision).not.toHaveBeenCalled();
130
+ expect(native.clear).not.toHaveBeenCalled();
131
+ expect(native.put).not.toHaveBeenCalled();
132
+ });
133
+
134
+ test('renews a credential inside the renewal window', async () => {
135
+ const native = fakeNative({ accountId: 'user-1', expiresAt: Date.now() + 2 * DAY_MS });
136
+ const { syncBackgroundSession } = await loadModule(native);
137
+ const expiresAt = new Date(Date.now() + 30 * DAY_MS).toISOString();
138
+ const provision = jest.fn(async () => provisioned({ expiresAt }));
139
+
140
+ await syncBackgroundSession({
141
+ oxyServices: fakeOxy(provision),
142
+ userId: 'user-1',
143
+ canUsePrivateApi: true,
144
+ isCurrent: () => true,
145
+ });
146
+
147
+ expect(provision).toHaveBeenCalledTimes(1);
148
+ expect(native.put).toHaveBeenCalledWith({
149
+ baseUrl: 'https://api.oxy.so',
150
+ deviceId: 'device-1',
151
+ secret: 'bg-secret',
152
+ accountId: 'user-1',
153
+ expiresAt: Date.parse(expiresAt),
154
+ });
155
+ // Same account, so nothing was revoked on the way.
156
+ expect(native.clear).not.toHaveBeenCalled();
157
+ });
158
+
159
+ test('waits for a bearer instead of provisioning without one', async () => {
160
+ const native = fakeNative(null);
161
+ const { syncBackgroundSession } = await loadModule(native);
162
+ const provision = jest.fn();
163
+
164
+ await syncBackgroundSession({
165
+ oxyServices: fakeOxy(provision),
166
+ userId: 'user-1',
167
+ canUsePrivateApi: false,
168
+ isCurrent: () => true,
169
+ });
170
+
171
+ expect(provision).not.toHaveBeenCalled();
172
+ expect(native.put).not.toHaveBeenCalled();
173
+ });
174
+
175
+ test('a not-yet-deployed endpoint (null) is quiet and writes nothing', async () => {
176
+ const native = fakeNative(null);
177
+ const { syncBackgroundSession } = await loadModule(native);
178
+ const provision = jest.fn(async () => null);
179
+
180
+ await syncBackgroundSession({
181
+ oxyServices: fakeOxy(provision),
182
+ userId: 'user-1',
183
+ canUsePrivateApi: true,
184
+ isCurrent: () => true,
185
+ });
186
+
187
+ expect(provision).toHaveBeenCalledTimes(1);
188
+ expect(native.put).not.toHaveBeenCalled();
189
+ expect(native.clear).not.toHaveBeenCalled();
190
+ });
191
+
192
+ test('a credential minted for another account mid-flight is dropped, not stored', async () => {
193
+ const native = fakeNative(null);
194
+ const { syncBackgroundSession } = await loadModule(native);
195
+ // The active account moved while the request was in flight, so the server
196
+ // answered for someone other than the account this run is syncing.
197
+ const provision = jest.fn(async () => provisioned({ accountId: 'other-user' }));
198
+
199
+ await syncBackgroundSession({
200
+ oxyServices: fakeOxy(provision),
201
+ userId: 'user-1',
202
+ canUsePrivateApi: true,
203
+ isCurrent: () => true,
204
+ });
205
+
206
+ expect(native.put).not.toHaveBeenCalled();
207
+ expect(native.clear).toHaveBeenCalledTimes(1);
208
+ });
209
+
210
+ test('a superseded run does not write the credential it fetched', async () => {
211
+ const native = fakeNative(null);
212
+ const { syncBackgroundSession } = await loadModule(native);
213
+ const provision = jest.fn(async () => provisioned());
214
+
215
+ await syncBackgroundSession({
216
+ oxyServices: fakeOxy(provision),
217
+ userId: 'user-1',
218
+ canUsePrivateApi: true,
219
+ // Superseded while the request was in flight (unmount, or a newer run).
220
+ isCurrent: () => false,
221
+ });
222
+
223
+ expect(native.put).not.toHaveBeenCalled();
224
+ });
225
+
226
+ test('an unparseable expiry is rejected rather than stored as garbage', async () => {
227
+ const native = fakeNative(null);
228
+ const { syncBackgroundSession } = await loadModule(native);
229
+ const provision = jest.fn(async () => provisioned({ expiresAt: 'not-a-date' }));
230
+
231
+ await syncBackgroundSession({
232
+ oxyServices: fakeOxy(provision),
233
+ userId: 'user-1',
234
+ canUsePrivateApi: true,
235
+ isCurrent: () => true,
236
+ });
237
+
238
+ expect(native.put).not.toHaveBeenCalled();
239
+ });
240
+
241
+ test('a provisioning failure never escapes to the caller', async () => {
242
+ const native = fakeNative(null);
243
+ const { syncBackgroundSession } = await loadModule(native);
244
+ const provision = jest.fn(async () => {
245
+ throw new Error('network down');
246
+ });
247
+
248
+ await expect(
249
+ syncBackgroundSession({
250
+ oxyServices: fakeOxy(provision),
251
+ userId: 'user-1',
252
+ canUsePrivateApi: true,
253
+ isCurrent: () => true,
254
+ }),
255
+ ).resolves.toBeUndefined();
256
+ expect(native.put).not.toHaveBeenCalled();
257
+ });
258
+ });
259
+
260
+ describe('a @oxyhq/core too old to provision', () => {
261
+ /**
262
+ * The ONE failure that must not be quiet. Every other failure here is caught and
263
+ * logged at warn, which is right for a flaky network — but a version skew means
264
+ * background refreshes never work at all, and hiding that behind a warning is how
265
+ * it would go unnoticed indefinitely.
266
+ */
267
+ function oxyWithoutProvisioning(): Parameters<
268
+ typeof import('../backgroundSession').syncBackgroundSession
269
+ >[0]['oxyServices'] {
270
+ return { getBaseURL: () => 'https://api.oxy.so' } as unknown as Parameters<
271
+ typeof import('../backgroundSession').syncBackgroundSession
272
+ >[0]['oxyServices'];
273
+ }
274
+
275
+ test('rejects loudly and logs at error rather than warning quietly', async () => {
276
+ const native = fakeNative(null);
277
+ const { syncBackgroundSession } = await loadModule(native);
278
+ const { logger } = await import('@oxyhq/core');
279
+ const errorSpy = jest.spyOn(logger, 'error').mockImplementation(() => undefined);
280
+ const warnSpy = jest.spyOn(logger, 'warn').mockImplementation(() => undefined);
281
+
282
+ try {
283
+ await expect(
284
+ syncBackgroundSession({
285
+ oxyServices: oxyWithoutProvisioning(),
286
+ userId: 'user-1',
287
+ canUsePrivateApi: true,
288
+ isCurrent: () => true,
289
+ }),
290
+ ).rejects.toThrow(/provisionBackgroundCredential/);
291
+
292
+ expect(errorSpy).toHaveBeenCalledTimes(1);
293
+ // If this ever becomes a warn, the skew is silent again.
294
+ expect(warnSpy).not.toHaveBeenCalled();
295
+ expect(native.put).not.toHaveBeenCalled();
296
+ } finally {
297
+ errorSpy.mockRestore();
298
+ warnSpy.mockRestore();
299
+ }
300
+ });
301
+
302
+ test('still lets a signed-out user clear, since that needs no core method', async () => {
303
+ const native = fakeNative({ accountId: 'user-1', expiresAt: Date.now() + 30 * DAY_MS });
304
+ const { syncBackgroundSession } = await loadModule(native);
305
+
306
+ // A sign-out must never be blocked by a dependency problem.
307
+ await expect(
308
+ syncBackgroundSession({
309
+ oxyServices: oxyWithoutProvisioning(),
310
+ userId: null,
311
+ canUsePrivateApi: false,
312
+ isCurrent: () => true,
313
+ }),
314
+ ).resolves.toBeUndefined();
315
+ expect(native.clear).toHaveBeenCalledTimes(1);
316
+ });
317
+ });
318
+
319
+ describe('without the native module', () => {
320
+ test('every entry point is an inert no-op', async () => {
321
+ const { syncBackgroundSession, clearBackgroundSession, isBackgroundSessionSupported } =
322
+ await loadModule(null);
323
+ const provision = jest.fn();
324
+
325
+ expect(isBackgroundSessionSupported()).toBe(false);
326
+ await expect(clearBackgroundSession()).resolves.toBeUndefined();
327
+ await expect(
328
+ syncBackgroundSession({
329
+ oxyServices: fakeOxy(provision),
330
+ userId: 'user-1',
331
+ canUsePrivateApi: true,
332
+ isCurrent: () => true,
333
+ }),
334
+ ).resolves.toBeUndefined();
335
+ expect(provision).not.toHaveBeenCalled();
336
+ });
337
+ });
@@ -0,0 +1,268 @@
1
+ /**
2
+ * The JS half of the native background session credential.
3
+ *
4
+ * A home-screen widget or a sync job refreshes while the app process is dead:
5
+ * there is no JS runtime, so it cannot go through this SDK's normal session lane
6
+ * at all. Native code needs its own way to obtain a bearer, and this module is
7
+ * what gives it one — while the app runs, it provisions a purpose-built
8
+ * credential and hands it to the native store that `so.oxy.session.OxyBackgroundSession`
9
+ * reads.
10
+ *
11
+ * ## Why a separate credential rather than the device secret
12
+ *
13
+ * `POST /session/device/token` ROTATES the device secret on every mint, and the
14
+ * presented secret dies 60 seconds later. Native code minting with it would be a
15
+ * second writer to the value this SDK's whole session depends on — and since
16
+ * `createNativeAuthStateStore` serves JS from an in-process mirror that never
17
+ * re-reads storage, JS would be blind to that rotation. A worker killed between
18
+ * the server's rotation and its local write would sign the user out of the app.
19
+ * A credential that nobody rotates removes that failure mode instead of managing
20
+ * it.
21
+ *
22
+ * ## What this does NOT do
23
+ *
24
+ * It never reads or writes `oxy.auth.v1` / expo-secure-store. The two credentials
25
+ * live in different stores with one writer each, so there is nothing to keep in
26
+ * lockstep and no state that can disagree.
27
+ *
28
+ * Android only. `requireOptionalNativeModule` resolves `null` on web and on any
29
+ * app that does not ship the native module, and every function here degrades to a
30
+ * no-op in that case — so an app can enable this and lose nothing on other
31
+ * platforms.
32
+ */
33
+ import { requireOptionalNativeModule } from 'expo-modules-core';
34
+ import type { OxyServices } from '@oxyhq/core';
35
+ import { logger } from '@oxyhq/core';
36
+
37
+ /**
38
+ * The native module's surface. Deliberately write-mostly: there is no `get`,
39
+ * because JS has no use for the secret it just wrote and keeping native as the
40
+ * secret's only reader is one less place it can leak from.
41
+ */
42
+ interface OxyBackgroundSessionNativeModule {
43
+ /** Store (replacing) the credential. Resolves `false` when it was rejected or storage failed. */
44
+ put(credential: {
45
+ baseUrl: string;
46
+ deviceId: string;
47
+ secret: string;
48
+ accountId: string;
49
+ /** Epoch millis — parsed from the server's ISO-8601 string here, not natively. */
50
+ expiresAt: number;
51
+ }): Promise<boolean>;
52
+ /** Drop the credential and any cached access token. */
53
+ clear(): Promise<boolean>;
54
+ /** What is stored: the owning account and its expiry (epoch millis), or `null`. */
55
+ peek(): Promise<{ accountId: string; expiresAt: number } | null>;
56
+ }
57
+
58
+ /**
59
+ * Re-provision once the remaining lifetime drops below this.
60
+ *
61
+ * The server issues a 30-day credential; renewing with a week to spare means an
62
+ * app opened even occasionally always holds a live one, while an app left unopened
63
+ * for a month lets it lapse — which is the intended outcome, not a failure.
64
+ */
65
+ const RENEW_WHEN_REMAINING_MS = 7 * 24 * 60 * 60 * 1000;
66
+
67
+ let nativeModule: OxyBackgroundSessionNativeModule | null | undefined;
68
+
69
+ /**
70
+ * Resolve the native module once.
71
+ *
72
+ * `requireOptionalNativeModule` (a static import Metro always resolves) rather
73
+ * than a dynamic `import(moduleName)`: the latter compiles to `require(variable)`
74
+ * in the CJS build, which Metro cannot resolve inside a consuming app — it
75
+ * silently returned `null` there, which is exactly how the cross-app SSO bridge
76
+ * broke once. Same reasoning as `loadSharedIdentityBridge` in `@oxyhq/protocol`.
77
+ */
78
+ function loadNativeModule(): OxyBackgroundSessionNativeModule | null {
79
+ if (nativeModule === undefined) {
80
+ const native = requireOptionalNativeModule<Partial<OxyBackgroundSessionNativeModule>>(
81
+ 'OxyBackgroundSession',
82
+ );
83
+ nativeModule =
84
+ native &&
85
+ typeof native.put === 'function' &&
86
+ typeof native.clear === 'function' &&
87
+ typeof native.peek === 'function'
88
+ ? {
89
+ put: native.put.bind(native),
90
+ clear: native.clear.bind(native),
91
+ peek: native.peek.bind(native),
92
+ }
93
+ : null;
94
+ }
95
+ return nativeModule;
96
+ }
97
+
98
+ /** Whether this platform/app can hold a background credential at all. */
99
+ export function isBackgroundSessionSupported(): boolean {
100
+ return loadNativeModule() !== null;
101
+ }
102
+
103
+ /**
104
+ * Drop the stored credential. No-op where unsupported, and never throws.
105
+ *
106
+ * Called on sign-out and BEFORE an account switch's network work, so the window
107
+ * in which background code could still serve the previous account is as short as
108
+ * one local write.
109
+ */
110
+ export async function clearBackgroundSession(): Promise<void> {
111
+ const native = loadNativeModule();
112
+ if (!native) {
113
+ return;
114
+ }
115
+ try {
116
+ await native.clear();
117
+ } catch (error) {
118
+ logger.warn('[backgroundSession] could not clear the native background credential', {
119
+ component: 'backgroundSession',
120
+ error,
121
+ });
122
+ }
123
+ }
124
+
125
+ export interface BackgroundSessionSyncInput {
126
+ oxyServices: OxyServices;
127
+ /** The signed-in account, or `null` when signed out. */
128
+ userId: string | null;
129
+ /** Whether a bearer is available yet — provisioning requires one. */
130
+ canUsePrivateApi: boolean;
131
+ /**
132
+ * Whether this run is still the current one. A run that loses its relevance
133
+ * mid-flight (unmount, or another identity change) must not write the
134
+ * credential it was about to write.
135
+ */
136
+ isCurrent: () => boolean;
137
+ }
138
+
139
+ /**
140
+ * Fail LOUDLY when the installed `@oxyhq/core` predates
141
+ * `provisionBackgroundCredential`.
142
+ *
143
+ * This is the one failure here that is a build/dependency mistake rather than a
144
+ * runtime condition, and it is the one that must never be quiet. Everything else
145
+ * in `syncBackgroundSession` is caught and logged at warn, which is right for a
146
+ * flaky network — but applying that to a version skew would leave background
147
+ * refreshes permanently non-functional behind a warning nobody reads. So this
148
+ * throws, and logs at ERROR first so it is still visible in a release build whose
149
+ * rejection handler is silent.
150
+ *
151
+ * Reachable only through a runtime skew: the declared `@oxyhq/core` range covers
152
+ * the method, so a correctly-resolved install cannot get here, and TypeScript
153
+ * rules it out at compile time.
154
+ */
155
+ function assertProvisioningAvailable(oxyServices: OxyServices): void {
156
+ if (typeof oxyServices.provisionBackgroundCredential === 'function') {
157
+ return;
158
+ }
159
+ const message =
160
+ '[backgroundSession] the installed @oxyhq/core has no provisionBackgroundCredential, ' +
161
+ 'so no background credential can be provisioned and native background refreshes will ' +
162
+ 'never authenticate. Install a @oxyhq/core that satisfies this package\'s declared range.';
163
+ logger.error(message, undefined, { component: 'backgroundSession' });
164
+ throw new Error(message);
165
+ }
166
+
167
+ /**
168
+ * Bring the native credential in line with the session JS currently holds.
169
+ *
170
+ * Ordering is the load-bearing part: a credential belonging to a DIFFERENT
171
+ * account is cleared before any network call, so a crash mid-provision leaves
172
+ * background code signed out rather than serving the previous account's data
173
+ * under the new account's name. The server enforces the same rule independently
174
+ * (a mint is re-authorized against the live device session, and against its ACTIVE
175
+ * account), so this is the fast local half of a belt-and-braces pair, not the only
176
+ * guard.
177
+ *
178
+ * Throws for exactly one thing — a `@oxyhq/core` too old to provision (see
179
+ * {@link assertProvisioningAvailable}). Every other failure is caught and logged:
180
+ * a background credential is an enhancement, and failing to provision one must
181
+ * not disturb the session that is working.
182
+ */
183
+ export async function syncBackgroundSession(input: BackgroundSessionSyncInput): Promise<void> {
184
+ const native = loadNativeModule();
185
+ if (!native) {
186
+ return;
187
+ }
188
+ const { oxyServices, userId, canUsePrivateApi, isCurrent } = input;
189
+
190
+ // Before the try, so the catch below cannot turn a dependency skew into a
191
+ // warning. Signed-out is exempt: clearing needs no core method, and a sign-out
192
+ // must never be blocked by one.
193
+ if (userId) {
194
+ assertProvisioningAvailable(oxyServices);
195
+ }
196
+
197
+ try {
198
+ if (!userId) {
199
+ // Signed out. Local-only, so it works with no bearer and no network.
200
+ await native.clear();
201
+ return;
202
+ }
203
+
204
+ const stored = await native.peek();
205
+ if (stored && stored.accountId !== userId) {
206
+ // Identity changed under a live credential — clear FIRST, provision after.
207
+ await native.clear();
208
+ }
209
+
210
+ const isForCurrentAccount = stored?.accountId === userId;
211
+ const hasLifeLeft =
212
+ isForCurrentAccount && stored.expiresAt - Date.now() > RENEW_WHEN_REMAINING_MS;
213
+ if (hasLifeLeft) {
214
+ return;
215
+ }
216
+
217
+ // Everything below needs a bearer. Without one yet (cold boot still
218
+ // resolving) there is nothing to do but wait for the next run — the token
219
+ // landing re-triggers this.
220
+ if (!canUsePrivateApi || !isCurrent()) {
221
+ return;
222
+ }
223
+
224
+ const provisioned = await oxyServices.provisionBackgroundCredential();
225
+ if (!provisioned) {
226
+ // `null` means the endpoint is not deployed yet. Expected during the
227
+ // rollout window (api leads the SDK) and deliberately quiet.
228
+ return;
229
+ }
230
+ if (!isCurrent()) {
231
+ return;
232
+ }
233
+ if (provisioned.accountId !== userId) {
234
+ // The active account moved while the request was in flight, so this
235
+ // credential is already for the wrong account. Drop it; the next run
236
+ // provisions for the account that is actually signed in.
237
+ await native.clear();
238
+ return;
239
+ }
240
+
241
+ const expiresAt = Date.parse(provisioned.expiresAt);
242
+ if (!Number.isFinite(expiresAt)) {
243
+ logger.warn('[backgroundSession] server returned an unparseable credential expiry', {
244
+ component: 'backgroundSession',
245
+ });
246
+ return;
247
+ }
248
+
249
+ const persisted = await native.put({
250
+ baseUrl: oxyServices.getBaseURL(),
251
+ deviceId: provisioned.deviceId,
252
+ secret: provisioned.secret,
253
+ accountId: provisioned.accountId,
254
+ expiresAt,
255
+ });
256
+ if (!persisted) {
257
+ logger.warn(
258
+ '[backgroundSession] the native store did not retain the background credential; background refreshes stay signed out until the next attempt',
259
+ { component: 'backgroundSession' },
260
+ );
261
+ }
262
+ } catch (error) {
263
+ logger.warn('[backgroundSession] could not sync the native background credential', {
264
+ component: 'backgroundSession',
265
+ error,
266
+ });
267
+ }
268
+ }
@@ -13,6 +13,7 @@
13
13
  export { createSessionClient } from './createSessionClient';
14
14
  export { createTokenTransport } from './tokenTransport';
15
15
  export { createPlatformAuthStateStore } from './authStore';
16
+ export { useBackgroundSessionSync } from './useBackgroundSessionSync';
16
17
  export { createIdentitySessionBinding, IdentityBoundSessionError } from './identityBinding';
17
18
  export type { IdentitySessionBinding } from './identityBinding';
18
19
  export {