@oxyhq/core 5.5.0 → 6.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 (181) hide show
  1. package/dist/cjs/.tsbuildinfo +1 -1
  2. package/dist/cjs/HttpService.js +6 -3
  3. package/dist/cjs/OxyServices.base.js +7 -102
  4. package/dist/cjs/boot/coldBootV2.js +350 -0
  5. package/dist/cjs/boot/deviceBootReturn.js +152 -0
  6. package/dist/cjs/crypto/keyManager.js +95 -0
  7. package/dist/cjs/i18n/locales/en-US.json +13 -1
  8. package/dist/cjs/i18n/locales/es-ES.json +13 -1
  9. package/dist/cjs/i18n/locales/locales/en-US.json +13 -1
  10. package/dist/cjs/i18n/locales/locales/es-ES.json +13 -1
  11. package/dist/cjs/index.js +47 -44
  12. package/dist/cjs/mixins/OxyServices.accounts.js +6 -13
  13. package/dist/cjs/mixins/OxyServices.auth.js +66 -201
  14. package/dist/cjs/mixins/OxyServices.authorizedApps.js +38 -0
  15. package/dist/cjs/mixins/OxyServices.deviceBoot.js +119 -0
  16. package/dist/cjs/mixins/index.js +13 -17
  17. package/dist/cjs/session/SessionClient.js +40 -1
  18. package/dist/cjs/session/authStateStore.js +284 -0
  19. package/dist/cjs/session/refresh.js +264 -0
  20. package/dist/cjs/utils/accountUtils.js +1 -55
  21. package/dist/cjs/utils/authWebUrl.js +6 -15
  22. package/dist/cjs/utils/fapiAutoDetect.js +16 -64
  23. package/dist/cjs/utils/platform.js +19 -0
  24. package/dist/cjs/utils/ssoBounce.js +15 -362
  25. package/dist/cjs/utils/validationUtils.js +57 -0
  26. package/dist/esm/.tsbuildinfo +1 -1
  27. package/dist/esm/HttpService.js +6 -3
  28. package/dist/esm/OxyServices.base.js +7 -102
  29. package/dist/esm/boot/coldBootV2.js +344 -0
  30. package/dist/esm/boot/deviceBootReturn.js +146 -0
  31. package/dist/esm/crypto/keyManager.js +95 -0
  32. package/dist/esm/i18n/locales/en-US.json +13 -1
  33. package/dist/esm/i18n/locales/es-ES.json +13 -1
  34. package/dist/esm/i18n/locales/locales/en-US.json +13 -1
  35. package/dist/esm/i18n/locales/locales/es-ES.json +13 -1
  36. package/dist/esm/index.js +28 -18
  37. package/dist/esm/mixins/OxyServices.accounts.js +6 -13
  38. package/dist/esm/mixins/OxyServices.auth.js +66 -201
  39. package/dist/esm/mixins/OxyServices.authorizedApps.js +35 -0
  40. package/dist/esm/mixins/OxyServices.deviceBoot.js +116 -0
  41. package/dist/esm/mixins/index.js +13 -17
  42. package/dist/esm/session/SessionClient.js +40 -1
  43. package/dist/esm/session/authStateStore.js +278 -0
  44. package/dist/esm/session/refresh.js +257 -0
  45. package/dist/esm/utils/accountUtils.js +0 -53
  46. package/dist/esm/utils/authWebUrl.js +6 -14
  47. package/dist/esm/utils/fapiAutoDetect.js +16 -63
  48. package/dist/esm/utils/platform.js +18 -0
  49. package/dist/esm/utils/ssoBounce.js +14 -345
  50. package/dist/esm/utils/validationUtils.js +56 -0
  51. package/dist/types/.tsbuildinfo +1 -1
  52. package/dist/types/HttpService.d.ts +13 -0
  53. package/dist/types/OxyServices.base.d.ts +0 -52
  54. package/dist/types/OxyServices.d.ts +0 -25
  55. package/dist/types/boot/coldBootV2.d.ts +76 -0
  56. package/dist/types/boot/deviceBootReturn.d.ts +83 -0
  57. package/dist/types/crypto/keyManager.d.ts +21 -0
  58. package/dist/types/index.d.ts +15 -21
  59. package/dist/types/mixins/OxyServices.accounts.d.ts +0 -2
  60. package/dist/types/mixins/OxyServices.analytics.d.ts +0 -2
  61. package/dist/types/mixins/OxyServices.appData.d.ts +0 -2
  62. package/dist/types/mixins/OxyServices.assets.d.ts +0 -2
  63. package/dist/types/mixins/OxyServices.auth.d.ts +35 -77
  64. package/dist/types/mixins/{OxyServices.redirect.d.ts → OxyServices.authorizedApps.d.ts} +35 -33
  65. package/dist/types/mixins/OxyServices.civic.d.ts +0 -2
  66. package/dist/types/mixins/OxyServices.connectedApps.d.ts +0 -2
  67. package/dist/types/mixins/OxyServices.contacts.d.ts +0 -2
  68. package/dist/types/mixins/OxyServices.deviceBoot.d.ts +110 -0
  69. package/dist/types/mixins/OxyServices.devices.d.ts +0 -2
  70. package/dist/types/mixins/OxyServices.features.d.ts +0 -2
  71. package/dist/types/mixins/OxyServices.identity.d.ts +0 -2
  72. package/dist/types/mixins/OxyServices.language.d.ts +0 -2
  73. package/dist/types/mixins/OxyServices.links.d.ts +0 -2
  74. package/dist/types/mixins/OxyServices.location.d.ts +0 -2
  75. package/dist/types/mixins/OxyServices.nodes.d.ts +0 -2
  76. package/dist/types/mixins/OxyServices.payment.d.ts +0 -2
  77. package/dist/types/mixins/OxyServices.privacy.d.ts +0 -2
  78. package/dist/types/mixins/OxyServices.reputation.d.ts +0 -2
  79. package/dist/types/mixins/OxyServices.security.d.ts +0 -2
  80. package/dist/types/mixins/OxyServices.topics.d.ts +0 -2
  81. package/dist/types/mixins/OxyServices.user.d.ts +0 -2
  82. package/dist/types/mixins/OxyServices.utility.d.ts +0 -2
  83. package/dist/types/mixins/index.d.ts +6 -9
  84. package/dist/types/models/interfaces.d.ts +0 -67
  85. package/dist/types/session/SessionClient.d.ts +25 -0
  86. package/dist/types/session/authStateStore.d.ts +119 -0
  87. package/dist/types/session/refresh.d.ts +93 -0
  88. package/dist/types/utils/accountUtils.d.ts +0 -14
  89. package/dist/types/utils/authWebUrl.d.ts +6 -12
  90. package/dist/types/utils/fapiAutoDetect.d.ts +15 -38
  91. package/dist/types/utils/platform.d.ts +14 -0
  92. package/dist/types/utils/ssoBounce.d.ts +14 -280
  93. package/dist/types/utils/validationUtils.d.ts +15 -0
  94. package/package.json +2 -2
  95. package/src/HttpService.ts +19 -3
  96. package/src/OxyServices.base.ts +7 -112
  97. package/src/OxyServices.ts +0 -38
  98. package/src/boot/__tests__/coldBootV2.test.ts +317 -0
  99. package/src/boot/__tests__/deviceBootReturn.test.ts +158 -0
  100. package/src/boot/coldBootV2.ts +426 -0
  101. package/src/boot/deviceBootReturn.ts +195 -0
  102. package/src/crypto/__tests__/sharedDeviceToken.test.ts +24 -0
  103. package/src/crypto/keyManager.ts +101 -0
  104. package/src/i18n/locales/en-US.json +13 -1
  105. package/src/i18n/locales/es-ES.json +13 -1
  106. package/src/index.ts +74 -65
  107. package/src/mixins/OxyServices.accounts.ts +6 -13
  108. package/src/mixins/OxyServices.auth.ts +78 -253
  109. package/src/mixins/OxyServices.authorizedApps.ts +75 -0
  110. package/src/mixins/OxyServices.deviceBoot.ts +146 -0
  111. package/src/mixins/__tests__/OxyServices.deviceBoot.test.ts +107 -0
  112. package/src/mixins/__tests__/accounts.test.ts +17 -44
  113. package/src/mixins/__tests__/authorizedApps.test.ts +63 -0
  114. package/src/mixins/__tests__/passwordSignIn.test.ts +91 -0
  115. package/src/mixins/index.ts +16 -22
  116. package/src/models/interfaces.ts +0 -79
  117. package/src/session/SessionClient.ts +52 -1
  118. package/src/session/__tests__/SessionClient.additive.test.ts +92 -0
  119. package/src/session/__tests__/SessionClient.rest.test.ts +25 -0
  120. package/src/session/__tests__/SessionClient.state.test.ts +18 -5
  121. package/src/session/__tests__/authStateStore.test.ts +209 -0
  122. package/src/session/__tests__/refresh.test.ts +256 -0
  123. package/src/session/authStateStore.ts +335 -0
  124. package/src/session/refresh.ts +334 -0
  125. package/src/utils/__tests__/authWebUrl.test.ts +5 -29
  126. package/src/utils/__tests__/fapiAutoDetect.test.ts +5 -126
  127. package/src/utils/__tests__/validationUtils.test.ts +30 -0
  128. package/src/utils/accountUtils.ts +0 -62
  129. package/src/utils/authWebUrl.ts +6 -15
  130. package/src/utils/fapiAutoDetect.ts +16 -60
  131. package/src/utils/platform.ts +21 -0
  132. package/src/utils/ssoBounce.ts +14 -393
  133. package/src/utils/validationUtils.ts +62 -0
  134. package/dist/cjs/AuthManager.js +0 -1110
  135. package/dist/cjs/AuthManagerTypes.js +0 -13
  136. package/dist/cjs/CrossDomainAuth.js +0 -206
  137. package/dist/cjs/mixins/OxyServices.fedcm.js +0 -823
  138. package/dist/cjs/mixins/OxyServices.redirect.js +0 -95
  139. package/dist/cjs/mixins/OxyServices.silent.js +0 -204
  140. package/dist/cjs/mixins/OxyServices.sso.js +0 -208
  141. package/dist/cjs/utils/ssoEstablish.js +0 -110
  142. package/dist/cjs/utils/ssoReturn.js +0 -275
  143. package/dist/esm/AuthManager.js +0 -1105
  144. package/dist/esm/AuthManagerTypes.js +0 -12
  145. package/dist/esm/CrossDomainAuth.js +0 -201
  146. package/dist/esm/mixins/OxyServices.fedcm.js +0 -821
  147. package/dist/esm/mixins/OxyServices.redirect.js +0 -92
  148. package/dist/esm/mixins/OxyServices.silent.js +0 -202
  149. package/dist/esm/mixins/OxyServices.sso.js +0 -204
  150. package/dist/esm/utils/ssoEstablish.js +0 -107
  151. package/dist/esm/utils/ssoReturn.js +0 -271
  152. package/dist/types/AuthManager.d.ts +0 -380
  153. package/dist/types/AuthManagerTypes.d.ts +0 -81
  154. package/dist/types/CrossDomainAuth.d.ts +0 -164
  155. package/dist/types/mixins/OxyServices.fedcm.d.ts +0 -331
  156. package/dist/types/mixins/OxyServices.silent.d.ts +0 -132
  157. package/dist/types/mixins/OxyServices.sso.d.ts +0 -138
  158. package/dist/types/utils/ssoEstablish.d.ts +0 -85
  159. package/dist/types/utils/ssoReturn.d.ts +0 -156
  160. package/src/AuthManager.ts +0 -1269
  161. package/src/AuthManagerTypes.ts +0 -86
  162. package/src/CrossDomainAuth.ts +0 -243
  163. package/src/__tests__/authManager.cookiePath.test.ts +0 -390
  164. package/src/__tests__/authManager.security.test.ts +0 -377
  165. package/src/__tests__/crossDomainAuth.test.ts +0 -116
  166. package/src/__tests__/establishDeviceRefreshSlot.test.ts +0 -221
  167. package/src/mixins/OxyServices.fedcm.ts +0 -1026
  168. package/src/mixins/OxyServices.redirect.ts +0 -122
  169. package/src/mixins/OxyServices.silent.ts +0 -272
  170. package/src/mixins/OxyServices.sso.ts +0 -261
  171. package/src/mixins/__tests__/constructorAuthWebUrl.test.ts +0 -85
  172. package/src/mixins/__tests__/fedcm.test.ts +0 -667
  173. package/src/mixins/__tests__/sessionBaseUrl.test.ts +0 -61
  174. package/src/mixins/__tests__/silent.test.ts +0 -102
  175. package/src/mixins/__tests__/sso.test.ts +0 -228
  176. package/src/utils/__tests__/consumeSsoReturn.test.ts +0 -816
  177. package/src/utils/__tests__/ssoBounce.test.ts +0 -219
  178. package/src/utils/__tests__/ssoEstablish.test.ts +0 -204
  179. package/src/utils/__tests__/ssoReturn.test.ts +0 -276
  180. package/src/utils/ssoEstablish.ts +0 -174
  181. package/src/utils/ssoReturn.ts +0 -389
@@ -1,1105 +0,0 @@
1
- /**
2
- * AuthManager - Centralized Authentication Manager
3
- *
4
- * Provides a unified authentication interface for all platforms.
5
- * Handles token storage, session management, and auth state changes.
6
- *
7
- * @module core/AuthManager
8
- */
9
- import { jwtDecode } from 'jwt-decode';
10
- const STORAGE_KEYS = {
11
- /**
12
- * Persisted active `authuser` slot index for the cookie path. Stores ONLY
13
- * the integer slot index (e.g. `"0"`, `"1"`), never a token or session
14
- * id — that lives in the httpOnly `oxy_rt_${n}` cookie. Used so that a
15
- * cold-boot `restoreFromCookies()` lands on the user's last-chosen slot
16
- * instead of always defaulting to the lowest authuser.
17
- */
18
- ACTIVE_AUTHUSER: 'oxy_active_authuser',
19
- };
20
- /**
21
- * Default in-memory storage for non-browser environments.
22
- */
23
- class MemoryStorage {
24
- constructor() {
25
- this.store = new Map();
26
- }
27
- getItem(key) {
28
- return this.store.get(key) ?? null;
29
- }
30
- setItem(key, value) {
31
- this.store.set(key, value);
32
- }
33
- removeItem(key) {
34
- this.store.delete(key);
35
- }
36
- }
37
- /**
38
- * Browser localStorage adapter.
39
- */
40
- class LocalStorageAdapter {
41
- getItem(key) {
42
- if (typeof window === 'undefined')
43
- return null;
44
- try {
45
- return localStorage.getItem(key);
46
- }
47
- catch {
48
- return null;
49
- }
50
- }
51
- setItem(key, value) {
52
- if (typeof window === 'undefined')
53
- return;
54
- try {
55
- localStorage.setItem(key, value);
56
- }
57
- catch {
58
- // Storage full or blocked
59
- }
60
- }
61
- removeItem(key) {
62
- if (typeof window === 'undefined')
63
- return;
64
- try {
65
- localStorage.removeItem(key);
66
- }
67
- catch {
68
- // Ignore errors
69
- }
70
- }
71
- }
72
- /**
73
- * AuthManager - Centralized authentication management.
74
- *
75
- * Provides a single point of control for:
76
- * - Token storage and retrieval
77
- * - Session management
78
- * - Auth state change notifications
79
- * - Multiple auth method support
80
- *
81
- * @example
82
- * ```typescript
83
- * const authManager = new AuthManager(oxyServices);
84
- *
85
- * // Listen for auth changes
86
- * authManager.onAuthStateChange((user) => {
87
- * console.log('Auth state changed:', user);
88
- * });
89
- *
90
- * // Handle successful auth
91
- * await authManager.handleAuthSuccess(session);
92
- *
93
- * // Sign out
94
- * await authManager.signOut();
95
- * ```
96
- */
97
- export class AuthManager {
98
- constructor(oxyServices, config = {}) {
99
- this.listeners = new Set();
100
- this.currentUser = null;
101
- this.currentAuthMethod = null;
102
- this.refreshTimer = null;
103
- this.refreshPromise = null;
104
- /** Tracks the access token this instance last knew about, for cross-tab adoption. */
105
- this._lastKnownAccessToken = null;
106
- /** BroadcastChannel for coordinating token refreshes across browser tabs. */
107
- this._broadcastChannel = null;
108
- /**
109
- * Identifier for this AuthManager instance (≈ "this tab"). Random hex
110
- * generated at construction; advertised in every outgoing broadcast and
111
- * used as the lookup key in `_knownPeerNonces`.
112
- */
113
- this._tabId = AuthManager._randomHex(16);
114
- /**
115
- * Per-tab nonce, advertised in every outgoing broadcast. Receivers record
116
- * the first (tabId, nonce) pair they see from a given peer; subsequent
117
- * messages from the same tabId MUST carry the same nonce or they're
118
- * ignored.
119
- *
120
- * Threat model: a same-origin XSS payload can post to the channel but can
121
- * NOT read this instance's private `_broadcastNonce` field (it lives in
122
- * closure, not on `window`). Forged broadcasts from XSS therefore can't
123
- * impersonate this tab. A new attacker-controlled tabId trips the
124
- * "first message from a new peer" branch, which is by definition trusted
125
- * — so the gate raises the bar but is not a complete defence (a perfect
126
- * mitigation would require message signing with a server-issued key).
127
- */
128
- this._broadcastNonce = AuthManager._randomHex(16);
129
- /**
130
- * Bounded LRU of `(tabId → nonce)` pairs seen on inbound broadcasts. First
131
- * sighting of a new tabId records its nonce; later messages from that
132
- * tabId are rejected if the nonce doesn't match.
133
- */
134
- this._knownPeerNonces = new Map();
135
- /**
136
- * In-flight `switchAuthuser` promise. Deduplicates concurrent calls so two
137
- * near-simultaneous switches don't both fire refresh requests and rotate
138
- * the slot twice. Mirrors the `refreshPromise` pattern used by
139
- * `refreshToken`.
140
- */
141
- this._switchPromise = null;
142
- /**
143
- * Last `restoreFromCookies()` completion timestamp, keyed by the
144
- * AuthManager's active authuser at the time of completion. Used to gate
145
- * cross-tab cascade: a flurry of BroadcastChannel events from sibling
146
- * tabs can otherwise trigger N back-to-back snapshots and rotate every
147
- * slot's access token N times.
148
- */
149
- this._lastRestoreAt = new Map();
150
- /**
151
- * In-memory registry of every device-local account the AuthManager knows
152
- * about, keyed by `authuser` slot index. Populated by:
153
- * - `restoreFromCookies()` (cold boot)
154
- * - `switchAuthuser()` (per-account rotation)
155
- * - `handleAuthSuccess()` (fresh login when the server response carries
156
- * an `authuser` field)
157
- * Access tokens live ONLY here in the cookie path — they are never
158
- * persisted to localStorage.
159
- */
160
- this.accounts = new Map();
161
- /**
162
- * Currently-active `authuser` slot in the cookie path. `null` means either
163
- * the cookie path hasn't been initialised yet, or no slots are signed in.
164
- */
165
- this.activeAuthuser = null;
166
- this.oxyServices = oxyServices;
167
- const crossTabSync = config.crossTabSync ?? (typeof BroadcastChannel !== 'undefined');
168
- this.config = {
169
- storage: config.storage ?? this.getDefaultStorage(),
170
- autoRefresh: config.autoRefresh ?? true,
171
- refreshBuffer: config.refreshBuffer ?? 5 * 60 * 1000, // 5 minutes
172
- crossTabSync,
173
- };
174
- this.storage = this.config.storage;
175
- this.oxyServices.httpService.setAuthRefreshHandler(async () => {
176
- const refreshed = await this.refreshToken();
177
- return refreshed ? this._lastKnownAccessToken : null;
178
- });
179
- // Setup cross-tab coordination in browser environments
180
- if (this.config.crossTabSync) {
181
- this._initBroadcastChannel();
182
- }
183
- }
184
- /**
185
- * Initialize BroadcastChannel for cross-tab token refresh coordination.
186
- * Only called in browser environments where BroadcastChannel is available.
187
- */
188
- _initBroadcastChannel() {
189
- if (typeof BroadcastChannel === 'undefined')
190
- return;
191
- try {
192
- this._broadcastChannel = new BroadcastChannel('oxy_auth_sync');
193
- this._broadcastChannel.onmessage = (event) => {
194
- this._handleCrossTabMessage(event.data);
195
- };
196
- }
197
- catch {
198
- // BroadcastChannel not supported or blocked (e.g., opaque origins)
199
- this._broadcastChannel = null;
200
- }
201
- }
202
- /**
203
- * Handle messages from other tabs about token refresh activity.
204
- */
205
- async _handleCrossTabMessage(message) {
206
- if (!message || !message.type)
207
- return;
208
- if (!this._acceptBroadcast(message))
209
- return;
210
- switch (message.type) {
211
- case 'accounts_restored':
212
- case 'authuser_switched':
213
- case 'authuser_signed_out': {
214
- // Another tab restored/switched/dropped a slot. The authoritative
215
- // state lives in the httpOnly cookies which we can't read from JS,
216
- // so the cleanest reaction is to re-run `restoreFromCookies()` on
217
- // a microtask and re-sync our in-memory registry. We swallow
218
- // failures: a transient network error must not bring down a tab
219
- // that already had a valid session.
220
- //
221
- // The restoreFromCookies() body owns the per-slot debounce so a
222
- // burst of N broadcasts only costs one /auth/refresh-all rotation
223
- // (instead of N back-to-back rotations of every cookie slot).
224
- Promise.resolve().then(() => {
225
- this.restoreFromCookies().catch(() => {
226
- // Best-effort; existing accounts (if any) remain intact.
227
- });
228
- });
229
- break;
230
- }
231
- case 'all_signed_out': {
232
- // Wipe the cookie-path registry after another tab signed every slot out.
233
- if (this.refreshTimer) {
234
- clearTimeout(this.refreshTimer);
235
- this.refreshTimer = null;
236
- }
237
- this.refreshPromise = null;
238
- this.accounts.clear();
239
- this.activeAuthuser = null;
240
- this._lastKnownAccessToken = null;
241
- this.oxyServices.httpService.setTokens('');
242
- this.currentUser = null;
243
- this.currentAuthMethod = null;
244
- this.notifyListeners();
245
- break;
246
- }
247
- }
248
- }
249
- /**
250
- * Broadcast a message to other tabs. Always stamps this tab's `tabId` and
251
- * `nonce` onto the message so receivers can run the cross-tab nonce gate.
252
- */
253
- _broadcast(message) {
254
- const stamped = {
255
- ...message,
256
- tabId: this._tabId,
257
- nonce: this._broadcastNonce,
258
- };
259
- try {
260
- this._broadcastChannel?.postMessage(stamped);
261
- }
262
- catch {
263
- // Channel closed or unavailable
264
- }
265
- }
266
- /**
267
- * Generate `bytes` bytes of cryptographic randomness encoded as lowercase
268
- * hex. Prefers Web Crypto's `getRandomValues` when available (browser /
269
- * modern Node); falls back to `Math.random` ONLY in environments without
270
- * Web Crypto (the resulting nonce is still unguessable to a same-origin
271
- * XSS payload — the goal is unforgeability across tabs, not cryptographic
272
- * secrecy across the network).
273
- */
274
- static _randomHex(bytes) {
275
- const buffer = new Uint8Array(bytes);
276
- const gcrypto = typeof globalThis !== 'undefined'
277
- ? globalThis.crypto
278
- : undefined;
279
- if (gcrypto && typeof gcrypto.getRandomValues === 'function') {
280
- gcrypto.getRandomValues(buffer);
281
- }
282
- else {
283
- for (let i = 0; i < buffer.length; i++) {
284
- buffer[i] = Math.floor(Math.random() * 256);
285
- }
286
- }
287
- let hex = '';
288
- for (const byte of buffer) {
289
- hex += byte.toString(16).padStart(2, '0');
290
- }
291
- return hex;
292
- }
293
- /**
294
- * Validate an inbound broadcast against the cross-tab nonce gate.
295
- *
296
- * Returns `true` when the message should be honoured, `false` when it
297
- * MUST be ignored:
298
- * - Message is missing `tabId` or `nonce` → ignore (forged or
299
- * mismatched-version sibling tab).
300
- * - First sighting of `tabId` → record the nonce and honour the message
301
- * (trust-on-first-use, the best we can do without a shared secret).
302
- * - Subsequent message from the same `tabId` with the SAME nonce →
303
- * honour.
304
- * - Subsequent message from the same `tabId` with a DIFFERENT nonce →
305
- * ignore (the canonical "forged broadcast" case — a same-origin XSS
306
- * payload can't read the real tab's `_broadcastNonce`).
307
- *
308
- * Echoes of this tab's own broadcasts (same `tabId`) are also dropped so
309
- * we don't react to our own messages.
310
- */
311
- _acceptBroadcast(message) {
312
- if (!message || typeof message.tabId !== 'string' || typeof message.nonce !== 'string') {
313
- return false;
314
- }
315
- if (message.tabId === this._tabId) {
316
- // Same-tab echo. Some BroadcastChannel implementations deliver our own
317
- // posts back to us; never act on those.
318
- return false;
319
- }
320
- const seen = this._knownPeerNonces.get(message.tabId);
321
- if (seen === undefined) {
322
- // Trust-on-first-use. Bound the map to avoid unbounded growth from a
323
- // tab-id sprayer.
324
- if (this._knownPeerNonces.size >= AuthManager._MAX_KNOWN_PEERS) {
325
- const oldest = this._knownPeerNonces.keys().next().value;
326
- if (oldest !== undefined) {
327
- this._knownPeerNonces.delete(oldest);
328
- }
329
- }
330
- this._knownPeerNonces.set(message.tabId, message.nonce);
331
- return true;
332
- }
333
- return seen === message.nonce;
334
- }
335
- /**
336
- * Get default storage based on environment.
337
- */
338
- getDefaultStorage() {
339
- try {
340
- if (typeof window !== 'undefined' && window.localStorage) {
341
- return new LocalStorageAdapter();
342
- }
343
- }
344
- catch {
345
- // Accessing window.localStorage can throw in opaque-origin/sandboxed
346
- // browser contexts or when storage is disabled. Fall back to memory so
347
- // AuthManager construction remains safe during provider render.
348
- }
349
- return new MemoryStorage();
350
- }
351
- /**
352
- * Subscribe to auth state changes.
353
- *
354
- * @param callback - Function called when auth state changes
355
- * @returns Unsubscribe function
356
- */
357
- onAuthStateChange(callback) {
358
- this.listeners.add(callback);
359
- // Call immediately with current state
360
- callback(this.currentUser);
361
- return () => {
362
- this.listeners.delete(callback);
363
- };
364
- }
365
- /**
366
- * Notify all listeners of auth state change.
367
- */
368
- notifyListeners() {
369
- for (const listener of this.listeners) {
370
- try {
371
- listener(this.currentUser);
372
- }
373
- catch {
374
- // Ignore listener errors
375
- }
376
- }
377
- }
378
- /**
379
- * Handle successful authentication.
380
- *
381
- * @param session - Session response from auth
382
- * @param method - Auth method used
383
- */
384
- async handleAuthSuccess(session, method = 'credentials') {
385
- // Access tokens are memory-only. Fresh login responses plant the token on
386
- // the HTTP client and the AuthManager registry, but never write it to JS
387
- // storage. Durable web refresh lives in the httpOnly cookie set by the API.
388
- if (session.accessToken) {
389
- this._lastKnownAccessToken = session.accessToken;
390
- this.oxyServices.httpService.setTokens(session.accessToken);
391
- }
392
- if (session.user && typeof session.user.id === 'string' && session.user.id.length > 0) {
393
- this.currentUser = session.user;
394
- }
395
- this.currentAuthMethod = method;
396
- // Register this primary session in the device's first-party multi-account
397
- // refresh-cookie set (web only). Every web primary commit funnels through
398
- // here (FedCM, central `/sso` return, credentials), but only a same-apex
399
- // `/fedcm/exchange` plants an `oxy_rt_<authuser>` slot as a side effect — the
400
- // cross-origin/credential-less restores (`/sso/exchange`, the IdP
401
- // `/auth/silent` postMessage) cannot set an `api.oxy.so` cookie. WITHOUT this
402
- // call those primaries never join the device set, so `refresh-all` returns no
403
- // accounts and account-switch persistence has no foundation. The shared
404
- // `POST /auth/session` primitive plants/reuses this user's slot where the
405
- // cookies ARE visible, re-plants the rotated access token, and returns the
406
- // AUTHORITATIVE `authuser` slot (the one actually written) — preferred over the
407
- // JWT-decoded guess, which may not correspond to a real cookie. No-op on native
408
- // (returns `null`); best-effort on transient failure.
409
- const establishedAuthuser = await this.oxyServices.establishDeviceRefreshSlot();
410
- // The slot mint rotated the access token; pick it up so the registry and the
411
- // refresh authority track the cookie just written. Falls back to the original
412
- // session token when the slot was a no-op (native) or failed.
413
- const rotatedToken = (establishedAuthuser !== null ? this.oxyServices.getAccessToken() : null) ??
414
- session.accessToken;
415
- if (rotatedToken) {
416
- this._lastKnownAccessToken = rotatedToken;
417
- }
418
- const decodedAuthuser = rotatedToken
419
- ? AuthManager.decodeAuthuserFromAccessToken(rotatedToken)
420
- : null;
421
- const authuser = establishedAuthuser ?? decodedAuthuser ?? 0;
422
- if (rotatedToken && session.sessionId) {
423
- this.accounts.set(authuser, {
424
- authuser,
425
- sessionId: session.sessionId,
426
- user: {
427
- id: session.user.id,
428
- username: session.user.username,
429
- name: session.user.name,
430
- avatar: session.user.avatar ?? null,
431
- },
432
- accessToken: rotatedToken,
433
- expiresAt: session.expiresAt,
434
- });
435
- this.activeAuthuser = authuser;
436
- await this.writeActiveAuthuser(authuser);
437
- }
438
- // Setup auto-refresh if enabled
439
- if (this.config.autoRefresh && session.expiresAt) {
440
- this.setupCookieRefresh(session.expiresAt, authuser);
441
- }
442
- // Notify listeners
443
- this.notifyListeners();
444
- }
445
- /**
446
- * Refresh the access token. Deduplicates concurrent calls so only one
447
- * refresh request is in-flight at a time. The only refresh authority is the
448
- * active httpOnly refresh-cookie slot; this method never reads access tokens
449
- * from storage.
450
- */
451
- async refreshToken() {
452
- // If a refresh is already in-flight, return the same promise
453
- if (this.refreshPromise) {
454
- return this.refreshPromise;
455
- }
456
- this.refreshPromise = this._doRefreshToken();
457
- try {
458
- return await this.refreshPromise;
459
- }
460
- finally {
461
- this.refreshPromise = null;
462
- }
463
- }
464
- async _doRefreshToken() {
465
- try {
466
- if (this.activeAuthuser !== null) {
467
- await this.switchAuthuser(this.activeAuthuser);
468
- return true;
469
- }
470
- const restored = await this.restoreFromCookies();
471
- return restored.accounts.length > 0;
472
- }
473
- catch {
474
- await this.clearSession();
475
- this.currentUser = null;
476
- this.accounts.clear();
477
- this.activeAuthuser = null;
478
- this._lastKnownAccessToken = null;
479
- this.oxyServices.httpService.setTokens('');
480
- this.notifyListeners();
481
- return false;
482
- }
483
- }
484
- /**
485
- * Sign out and clear all auth data.
486
- */
487
- async signOut() {
488
- // Clear refresh timer and cancel any in-flight refresh
489
- if (this.refreshTimer) {
490
- clearTimeout(this.refreshTimer);
491
- this.refreshTimer = null;
492
- }
493
- this.refreshPromise = null;
494
- // Invalidate current cookie-backed sessions on the server (best-effort)
495
- try {
496
- await this.signOutAllViaCookies();
497
- }
498
- catch {
499
- // Best-effort: don't block local signout on network failure
500
- }
501
- // Revoke FedCM credential if supported
502
- try {
503
- const services = this.oxyServices;
504
- if (services.revokeFedCMCredential) {
505
- await services.revokeFedCMCredential();
506
- }
507
- }
508
- catch {
509
- // Ignore FedCM errors
510
- }
511
- // Clear HTTP client tokens
512
- this.oxyServices.httpService.setTokens('');
513
- this._lastKnownAccessToken = null;
514
- // Clear storage
515
- await this.clearSession();
516
- // Update state and notify
517
- this.currentUser = null;
518
- this.notifyListeners();
519
- }
520
- /**
521
- * Clear local cookie-path state. The only persisted AuthManager value is the
522
- * active numeric slot; tokens and user objects are intentionally memory-only.
523
- */
524
- async clearSession() {
525
- await this.clearActiveAuthuser();
526
- this.currentAuthMethod = null;
527
- }
528
- /**
529
- * Get current user.
530
- */
531
- getCurrentUser() {
532
- return this.currentUser;
533
- }
534
- /**
535
- * Check if user is authenticated.
536
- */
537
- isAuthenticated() {
538
- return this.currentUser !== null;
539
- }
540
- /**
541
- * Get a valid access token, refreshing automatically if expired or expiring
542
- * soon. The token is read from memory only.
543
- */
544
- async getAccessToken() {
545
- const token = this._lastKnownAccessToken;
546
- if (!token)
547
- return null;
548
- try {
549
- const decoded = jwtDecode(token);
550
- if (decoded.exp) {
551
- const now = Math.floor(Date.now() / 1000);
552
- const buffer = 60; // refresh 60 seconds before expiry
553
- if (decoded.exp - now < buffer) {
554
- const refreshed = await this.refreshToken();
555
- if (refreshed) {
556
- return this._lastKnownAccessToken;
557
- }
558
- }
559
- }
560
- }
561
- catch {
562
- // Decode failed — return token as-is, let the server decide
563
- }
564
- return token;
565
- }
566
- /**
567
- * Get the auth method used for current session.
568
- */
569
- async getAuthMethod() {
570
- return this.currentAuthMethod;
571
- }
572
- /**
573
- * Initialize auth state on app startup.
574
- *
575
- * Only the cookie path is authoritative. `restoreFromCookies()` refreshes
576
- * the httpOnly `oxy_rt_${authuser}` slots through `/auth/refresh-all`,
577
- * plants the active access token in memory, and returns the active user.
578
- * No access token, refresh token, or session JSON is read from localStorage.
579
- *
580
- * Returns the active user on success, or `null` when no cookie-backed
581
- * account was restored.
582
- */
583
- async initialize(options = {}) {
584
- const cookieResult = await this.restoreFromCookies(options);
585
- if (cookieResult.accounts.length > 0) {
586
- return this.currentUser;
587
- }
588
- return null;
589
- }
590
- // -------------------------------------------------------------------------
591
- // Multi-account cookie path (Google-style multi-sign-in).
592
- // -------------------------------------------------------------------------
593
- // The cookie path is web-only. It never touches the retired
594
- // `oxy_access_token` / `oxy_refresh_token` /
595
- // `oxy_session` localStorage keys, because the refresh token lives in the
596
- // httpOnly `oxy_rt_${authuser}` cookies and access tokens live in
597
- // `this.accounts` (in-memory only). The only localStorage key the cookie
598
- // path writes is `STORAGE_KEYS.ACTIVE_AUTHUSER` — a small integer that is
599
- // explicitly NOT a secret.
600
- //
601
- // `initialize()` only uses the cookie path.
602
- // -------------------------------------------------------------------------
603
- /**
604
- * Read the persisted active `authuser` slot index. Returns `null` when
605
- * none is persisted, the value is corrupt, or the storage adapter has no
606
- * record. Storage failures are non-fatal: the cookie path falls back to
607
- * "lowest authuser" deterministic selection.
608
- */
609
- async readActiveAuthuser() {
610
- try {
611
- const raw = await this.storage.getItem(STORAGE_KEYS.ACTIVE_AUTHUSER);
612
- if (raw === null || raw === undefined)
613
- return null;
614
- const parsed = Number.parseInt(raw, 10);
615
- if (!Number.isFinite(parsed) || parsed < 0)
616
- return null;
617
- return parsed;
618
- }
619
- catch {
620
- return null;
621
- }
622
- }
623
- /**
624
- * Persist the active `authuser` slot index. No-ops on storage failure
625
- * (e.g. Safari private mode, native SecureStore unavailable) — this is
626
- * best-effort UX persistence, not authoritative state.
627
- */
628
- async writeActiveAuthuser(authuser) {
629
- if (!Number.isFinite(authuser) || authuser < 0)
630
- return;
631
- try {
632
- await this.storage.setItem(STORAGE_KEYS.ACTIVE_AUTHUSER, String(authuser));
633
- }
634
- catch {
635
- // Best-effort.
636
- }
637
- }
638
- /**
639
- * Clear the persisted active `authuser` so the next cold boot starts from
640
- * a clean slate (used on full sign-out).
641
- */
642
- async clearActiveAuthuser() {
643
- try {
644
- await this.storage.removeItem(STORAGE_KEYS.ACTIVE_AUTHUSER);
645
- }
646
- catch {
647
- // Best-effort.
648
- }
649
- }
650
- /**
651
- * Build a `MinimalUserData` from a `RefreshAllAccount`. Returns `null` when
652
- * the wire entry has no user shape; the AuthManager's caller is expected to
653
- * hydrate via `/users/me` in that case.
654
- */
655
- static toMinimalUser(account) {
656
- if (!account.user)
657
- return null;
658
- return {
659
- id: account.user.id,
660
- username: account.user.username,
661
- name: account.user.name,
662
- avatar: account.user.avatar ?? undefined,
663
- };
664
- }
665
- /**
666
- * Hydrate the user shape for a slot whose AuthManagerAccount currently has
667
- * `user: null` (for example, a switch onto a previously unknown slot). Calls
668
- * `/users/me` with the slot's freshly-planted access
669
- * token already on the HTTP client; merges the result back into the
670
- * registry entry. Network failures are non-fatal — the slot remains with
671
- * `user: null` and the UI is expected to render the public-key fallback
672
- * handle until a later restore picks the real user shape up.
673
- */
674
- async _hydrateUnknownUser(authuser) {
675
- const oxy = this.oxyServices;
676
- if (typeof oxy.getCurrentUser !== 'function')
677
- return;
678
- let me;
679
- try {
680
- me = await oxy.getCurrentUser();
681
- }
682
- catch {
683
- // Best-effort: keep `user: null` and let the UI fall back to the
684
- // public-key handle.
685
- return;
686
- }
687
- const existing = this.accounts.get(authuser);
688
- if (!existing)
689
- return;
690
- const hydrated = {
691
- id: me.id,
692
- username: me.username,
693
- // `User.name` and `RefreshAllAccountUser.name` are the same canonical
694
- // structured `UserNameResponse` shape, so forward it verbatim.
695
- name: me.name,
696
- avatar: me.avatar ?? null,
697
- email: me.email,
698
- color: me.color ?? null,
699
- };
700
- this.accounts.set(authuser, { ...existing, user: hydrated });
701
- // Mirror onto `currentUser` if this is the active slot.
702
- if (this.activeAuthuser === authuser) {
703
- this.currentUser = {
704
- id: hydrated.id,
705
- username: hydrated.username,
706
- name: hydrated.name,
707
- avatar: hydrated.avatar ?? undefined,
708
- };
709
- this.notifyListeners();
710
- }
711
- }
712
- /**
713
- * Snapshot of the registered cookie-path accounts, sorted by `authuser`
714
- * ascending (canonical order). Mutating the returned array does not
715
- * affect AuthManager state.
716
- */
717
- getAccounts() {
718
- return Array.from(this.accounts.values()).sort((a, b) => a.authuser - b.authuser);
719
- }
720
- /**
721
- * The slot index that is currently active in the cookie path, or `null`
722
- * if the cookie path hasn't been initialised or no slots are signed in.
723
- */
724
- getActiveAuthuser() {
725
- return this.activeAuthuser;
726
- }
727
- /**
728
- * Convenience: the AuthManagerAccount currently flagged active.
729
- */
730
- getActiveAccount() {
731
- if (this.activeAuthuser === null)
732
- return null;
733
- return this.accounts.get(this.activeAuthuser) ?? null;
734
- }
735
- /**
736
- * Restore every device-local account from the httpOnly refresh cookies.
737
- *
738
- * Calls `oxyServices.refreshAllSessions()` (`POST /auth/refresh-all` with
739
- * `credentials: 'include'`). The server rotates every presented
740
- * `oxy_rt_${authuser}` cookie in parallel and returns one entry per
741
- * valid slot.
742
- *
743
- * Plants the active account's access token on the shared HTTP client;
744
- * sibling slots' tokens stay in the in-memory registry so a later
745
- * `switchAuthuser()` can hot-swap them without a network round-trip.
746
- *
747
- * The persisted `oxy_active_authuser` slot wins when it matches a
748
- * returned account; otherwise the lowest returned `authuser` is chosen
749
- * deterministically.
750
- *
751
- * Returns `{ accounts: [], activeAuthuser: null }` on any failure or
752
- * empty snapshot — callers treat that as "no signed-in accounts" and
753
- * proceed unauthenticated. State is NOT cleared on failure; existing
754
- * accounts (if any) remain intact.
755
- */
756
- async restoreFromCookies(options = {}) {
757
- // Cross-tab cascade debounce. If we restored within the last
758
- // _RESTORE_DEBOUNCE_MS for the currently-active slot, skip the network
759
- // round-trip and return the cached registry verbatim. A burst of N
760
- // BroadcastChannel events from sibling tabs therefore costs at most one
761
- // /auth/refresh-all rotation. Cold-boot calls (activeAuthuser still
762
- // null) always run because the cache hasn't been seeded yet.
763
- if (this.activeAuthuser !== null) {
764
- const last = this._lastRestoreAt.get(this.activeAuthuser);
765
- if (last !== undefined && Date.now() - last < AuthManager._RESTORE_DEBOUNCE_MS) {
766
- return {
767
- accounts: this.getAccounts(),
768
- activeAuthuser: this.activeAuthuser,
769
- };
770
- }
771
- }
772
- let snapshot;
773
- try {
774
- // Forward the optional cold-boot fail-fast timeout. Undefined (the warm
775
- // cross-tab cascade default) preserves the wait-indefinitely behaviour.
776
- snapshot = await this.oxyServices.refreshAllSessions({ timeout: options.timeout });
777
- }
778
- catch {
779
- return { accounts: [], activeAuthuser: null };
780
- }
781
- if (snapshot.accounts.length === 0) {
782
- return { accounts: [], activeAuthuser: null };
783
- }
784
- // Replace the registry wholesale: the server's snapshot is authoritative.
785
- this.accounts.clear();
786
- for (const account of snapshot.accounts) {
787
- this.accounts.set(account.authuser, {
788
- authuser: account.authuser,
789
- sessionId: account.sessionId,
790
- user: account.user,
791
- accessToken: account.accessToken,
792
- expiresAt: account.expiresAt,
793
- });
794
- }
795
- // Pick the active slot: persisted `oxy_active_authuser` wins if it
796
- // matches a returned account; otherwise the lowest returned authuser
797
- // (the snapshot is already sorted ascending, so accounts[0] is the
798
- // lowest).
799
- const persisted = await this.readActiveAuthuser();
800
- const active = (persisted !== null && this.accounts.has(persisted))
801
- ? persisted
802
- : snapshot.accounts[0].authuser;
803
- this.activeAuthuser = active;
804
- const activeAccount = this.accounts.get(active);
805
- const slotsNeedingHydration = [];
806
- if (activeAccount) {
807
- this._lastKnownAccessToken = activeAccount.accessToken;
808
- this.oxyServices.httpService.setTokens(activeAccount.accessToken);
809
- this.currentUser = AuthManager.toMinimalUser({
810
- authuser: activeAccount.authuser,
811
- accessToken: activeAccount.accessToken,
812
- expiresAt: activeAccount.expiresAt,
813
- sessionId: activeAccount.sessionId,
814
- user: activeAccount.user,
815
- });
816
- await this.writeActiveAuthuser(active);
817
- // Schedule auto-refresh on the active slot so the in-memory access
818
- // token doesn't silently expire under the user.
819
- if (this.config.autoRefresh) {
820
- this.setupCookieRefresh(activeAccount.expiresAt, active);
821
- }
822
- // If the active slot has no user shape, schedule a /users/me hydration so
823
- // the chooser isn't stuck on the public-key handle. Hydration is
824
- // fire-and-forget — the snapshot is already considered "restored" once
825
- // the access token is planted.
826
- if (activeAccount.user === null) {
827
- slotsNeedingHydration.push(activeAccount.authuser);
828
- }
829
- }
830
- this._lastRestoreAt.set(active, Date.now());
831
- this._broadcast({ type: 'accounts_restored', timestamp: Date.now() });
832
- this.notifyListeners();
833
- for (const slot of slotsNeedingHydration) {
834
- void this._hydrateUnknownUser(slot);
835
- }
836
- return {
837
- accounts: this.getAccounts(),
838
- activeAuthuser: this.activeAuthuser,
839
- };
840
- }
841
- /**
842
- * Switch the active account to a different device-local slot.
843
- *
844
- * Calls `oxyServices.refreshTokenViaCookie({ authuser })` to mint a fresh
845
- * access token from the slot's httpOnly cookie, updates the in-memory
846
- * registry entry, plants the token on the HTTP client, persists the new
847
- * active slot, and broadcasts cross-tab.
848
- *
849
- * Throws when the slot's refresh cookie is missing / expired / reused
850
- * (the SDK returns `null` from `refreshTokenViaCookie` in that case, and
851
- * we surface it as an `Error` so callers can clean up the slot from
852
- * their UI).
853
- */
854
- async switchAuthuser(authuser) {
855
- // Concurrency gate. Two near-simultaneous switchAuthuser calls would
856
- // otherwise both POST /auth/refresh?authuser=N, rotating the slot's
857
- // refresh-token family twice and racing on the registry update. The
858
- // gate is keyed only by "any switch in flight" — switching to a
859
- // DIFFERENT slot while a switch is in flight returns the in-flight
860
- // promise (callers can re-issue once it settles if they really meant a
861
- // different slot).
862
- if (this._switchPromise) {
863
- return this._switchPromise;
864
- }
865
- this._switchPromise = this._doSwitchAuthuser(authuser);
866
- try {
867
- return await this._switchPromise;
868
- }
869
- finally {
870
- this._switchPromise = null;
871
- }
872
- }
873
- async _doSwitchAuthuser(authuser) {
874
- const refreshed = await this.oxyServices.refreshTokenViaCookie({ authuser });
875
- if (refreshed === null) {
876
- // Drop the dead slot from our registry so the chooser doesn't keep
877
- // offering it; callers can drive a `restoreFromCookies()` to
878
- // re-sync.
879
- this.accounts.delete(authuser);
880
- if (this.activeAuthuser === authuser) {
881
- this.activeAuthuser = null;
882
- }
883
- throw new Error(`Refresh cookie for authuser=${authuser} is missing or expired`);
884
- }
885
- // Update (or insert) the slot in the registry. We preserve any user
886
- // metadata we already knew from a prior `restoreFromCookies` — the
887
- // single-slot refresh endpoint does NOT re-project the user shape. When
888
- // we have no prior metadata, we leave `user: null` and schedule a
889
- // /users/me hydration below.
890
- const existing = this.accounts.get(authuser);
891
- const decoded = AuthManager.decodeSessionIdFromAccessToken(refreshed.accessToken);
892
- const sessionId = decoded ?? existing?.sessionId ?? '';
893
- const updated = {
894
- authuser,
895
- sessionId,
896
- user: existing?.user ?? null,
897
- accessToken: refreshed.accessToken,
898
- expiresAt: refreshed.expiresAt,
899
- };
900
- this.accounts.set(authuser, updated);
901
- this.activeAuthuser = authuser;
902
- this._lastKnownAccessToken = refreshed.accessToken;
903
- this.oxyServices.httpService.setTokens(refreshed.accessToken);
904
- this.currentUser = updated.user
905
- ? {
906
- id: updated.user.id,
907
- username: updated.user.username,
908
- name: updated.user.name,
909
- avatar: updated.user.avatar ?? undefined,
910
- }
911
- : null;
912
- await this.writeActiveAuthuser(authuser);
913
- if (this.config.autoRefresh) {
914
- this.setupCookieRefresh(refreshed.expiresAt, authuser);
915
- }
916
- this._broadcast({ type: 'authuser_switched', authuser, timestamp: Date.now() });
917
- this.notifyListeners();
918
- if (updated.user === null) {
919
- // Fire-and-forget hydration: the switch is considered complete once
920
- // the token is planted, the UI uses getAccountFallbackHandle (public-
921
- // key fallback) until /users/me resolves.
922
- void this._hydrateUnknownUser(authuser);
923
- }
924
- return {
925
- accessToken: refreshed.accessToken,
926
- expiresAt: refreshed.expiresAt,
927
- authuser,
928
- };
929
- }
930
- /**
931
- * Sign out a single device-local slot.
932
- *
933
- * Calls `oxyServices.logoutSessionByAuthuser(authuser)`: server-side
934
- * revokes the slot's refresh-token family and clears the
935
- * `oxy_rt_${authuser}` cookie via `Set-Cookie`. The slot is removed from
936
- * the in-memory registry. If the slot was active, the next lowest
937
- * remaining authuser becomes active (or `null` when none remain).
938
- */
939
- async signOutAuthuser(authuser) {
940
- try {
941
- await this.oxyServices.logoutSessionByAuthuser(authuser);
942
- }
943
- catch {
944
- // Best-effort: the server-side logout is idempotent on unknown
945
- // tokens, and we'd rather drop the slot locally than leave dead
946
- // state on a network blip.
947
- }
948
- this.accounts.delete(authuser);
949
- if (this.activeAuthuser === authuser) {
950
- const remaining = this.getAccounts();
951
- if (remaining.length > 0) {
952
- // Pick the lowest remaining authuser as the new active. We don't
953
- // proactively refresh its token here — callers can drive
954
- // `switchAuthuser` if they need a fresh bearer. This keeps the
955
- // method's network footprint to exactly one request.
956
- const next = remaining[0];
957
- this.activeAuthuser = next.authuser;
958
- this._lastKnownAccessToken = next.accessToken;
959
- this.oxyServices.httpService.setTokens(next.accessToken);
960
- this.currentUser = next.user
961
- ? {
962
- id: next.user.id,
963
- username: next.user.username,
964
- name: next.user.name,
965
- avatar: next.user.avatar ?? undefined,
966
- }
967
- : null;
968
- await this.writeActiveAuthuser(next.authuser);
969
- if (next.user === null) {
970
- void this._hydrateUnknownUser(next.authuser);
971
- }
972
- }
973
- else {
974
- this.activeAuthuser = null;
975
- this._lastKnownAccessToken = null;
976
- this.oxyServices.httpService.setTokens('');
977
- this.currentUser = null;
978
- this.currentAuthMethod = null;
979
- await this.clearActiveAuthuser();
980
- }
981
- }
982
- this._broadcast({ type: 'authuser_signed_out', authuser, timestamp: Date.now() });
983
- this.notifyListeners();
984
- }
985
- /**
986
- * Sign out EVERY device-local account on this device.
987
- *
988
- * Calls `oxyServices.logoutAllSessionsViaCookie()`: server-side revokes
989
- * every presented family and `Set-Cookie`s an immediate expiry for every
990
- * recognised `oxy_rt_${n}` slot. The in-memory registry is wiped, the active
991
- * slot is cleared, and the persisted `oxy_active_authuser` is removed so the
992
- * next cold boot starts fresh.
993
- */
994
- async signOutAllViaCookies() {
995
- try {
996
- await this.oxyServices.logoutAllSessionsViaCookie();
997
- }
998
- catch {
999
- // Best-effort; server-side endpoint is idempotent.
1000
- }
1001
- this.accounts.clear();
1002
- this.activeAuthuser = null;
1003
- this._lastKnownAccessToken = null;
1004
- this.oxyServices.httpService.setTokens('');
1005
- this.currentUser = null;
1006
- this.currentAuthMethod = null;
1007
- this._lastRestoreAt.clear();
1008
- await this.clearActiveAuthuser();
1009
- // Also clear the refresh timer that the cookie path may have scheduled.
1010
- if (this.refreshTimer) {
1011
- clearTimeout(this.refreshTimer);
1012
- this.refreshTimer = null;
1013
- }
1014
- this._broadcast({ type: 'all_signed_out', timestamp: Date.now() });
1015
- this.notifyListeners();
1016
- }
1017
- /**
1018
- * Schedule an auto-refresh for the cookie path on the active slot. The
1019
- * AuthManager has exactly one active slot at a time, so one timer suffices.
1020
- */
1021
- setupCookieRefresh(expiresAt, authuser) {
1022
- if (this.refreshTimer) {
1023
- clearTimeout(this.refreshTimer);
1024
- }
1025
- const expiresAtMs = new Date(expiresAt).getTime();
1026
- if (!Number.isFinite(expiresAtMs))
1027
- return;
1028
- const refreshAt = expiresAtMs - this.config.refreshBuffer;
1029
- const delay = Math.max(0, refreshAt - Date.now());
1030
- this.refreshTimer = setTimeout(() => {
1031
- // Only refresh if this slot is still the active one when the timer
1032
- // fires (the user might have switched in the meantime).
1033
- if (this.activeAuthuser !== authuser)
1034
- return;
1035
- this.switchAuthuser(authuser).catch(() => {
1036
- // A failed cookie refresh on the active slot means the user must
1037
- // re-auth; surface via `notifyListeners` indirectly when the slot
1038
- // is dropped from the registry by `switchAuthuser`.
1039
- });
1040
- }, delay);
1041
- }
1042
- /**
1043
- * Decode the session id from an unverified JWT access token. Decode-only
1044
- * (no signature verification) — the server already verified the
1045
- * signature when minting the token. Returns `null` on malformed input.
1046
- */
1047
- static decodeSessionIdFromAccessToken(token) {
1048
- try {
1049
- const decoded = jwtDecode(token);
1050
- return typeof decoded.sessionId === 'string' && decoded.sessionId.length > 0
1051
- ? decoded.sessionId
1052
- : null;
1053
- }
1054
- catch {
1055
- return null;
1056
- }
1057
- }
1058
- static decodeAuthuserFromAccessToken(token) {
1059
- try {
1060
- const decoded = jwtDecode(token);
1061
- return typeof decoded.authuser === 'number' && Number.isFinite(decoded.authuser) && decoded.authuser >= 0
1062
- ? decoded.authuser
1063
- : null;
1064
- }
1065
- catch {
1066
- return null;
1067
- }
1068
- }
1069
- /**
1070
- * Destroy the auth manager and clean up resources.
1071
- */
1072
- destroy() {
1073
- if (this.refreshTimer) {
1074
- clearTimeout(this.refreshTimer);
1075
- this.refreshTimer = null;
1076
- }
1077
- this.listeners.clear();
1078
- this._knownPeerNonces.clear();
1079
- this._lastRestoreAt.clear();
1080
- this._switchPromise = null;
1081
- this.refreshPromise = null;
1082
- // Close BroadcastChannel
1083
- if (this._broadcastChannel) {
1084
- try {
1085
- this._broadcastChannel.close();
1086
- }
1087
- catch {
1088
- // Ignore close errors
1089
- }
1090
- this._broadcastChannel = null;
1091
- }
1092
- }
1093
- }
1094
- AuthManager._MAX_KNOWN_PEERS = 32;
1095
- AuthManager._RESTORE_DEBOUNCE_MS = 2000;
1096
- /**
1097
- * Create an AuthManager instance.
1098
- *
1099
- * @param oxyServices - OxyServices instance
1100
- * @param config - Optional configuration
1101
- * @returns AuthManager instance
1102
- */
1103
- export function createAuthManager(oxyServices, config) {
1104
- return new AuthManager(oxyServices, config);
1105
- }