@strands.gg/accui 2.1.5 → 2.1.7

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 (173) hide show
  1. package/dist/index.d.ts +1 -6
  2. package/dist/js/auth-components-BJhPF4dS.js +8195 -0
  3. package/dist/js/auth-components-BJhPF4dS.js.br +0 -0
  4. package/dist/js/auth-components-BJhPF4dS.js.gz +0 -0
  5. package/dist/js/auth-components-CXT-W3fG.js +1 -0
  6. package/dist/js/auth-components-CXT-W3fG.js.br +0 -0
  7. package/dist/js/auth-components-CXT-W3fG.js.gz +0 -0
  8. package/dist/js/composables-BqIRpDGP.js +1609 -0
  9. package/dist/js/composables-BqIRpDGP.js.br +0 -0
  10. package/dist/js/composables-BqIRpDGP.js.gz +0 -0
  11. package/dist/js/composables-BqLSXNon.js +1 -0
  12. package/dist/js/composables-BqLSXNon.js.br +0 -0
  13. package/dist/js/composables-BqLSXNon.js.gz +0 -0
  14. package/dist/js/icons-CQ3z-CUv.js +398 -0
  15. package/dist/js/icons-CQ3z-CUv.js.br +0 -0
  16. package/dist/js/icons-CQ3z-CUv.js.gz +0 -0
  17. package/dist/js/icons-MGGFfB13.js +1 -0
  18. package/dist/js/index-87OecKtg.js +1 -0
  19. package/dist/js/index-B113vWue.js +106 -0
  20. package/dist/js/nuxt/module-BA8ZjBpp.js +1 -0
  21. package/dist/{nuxt/module.es.js → js/nuxt/module-YfdoaPCb.js} +2 -0
  22. package/dist/{nuxt/runtime/composables/useAuthenticatedFetch.es.js → js/nuxt/runtime/composables/useAuthenticatedFetch-DToDCO6a.js} +1 -1
  23. package/dist/js/nuxt/runtime/composables/useAuthenticatedFetch-qYkd06Dm.js +1 -0
  24. package/dist/{nuxt/runtime/composables/useStrandsAuth.es.js → js/nuxt/runtime/composables/useStrandsAuth-8b_bomlH.js} +1 -1
  25. package/dist/js/nuxt/runtime/composables/useStrandsAuth-Dn15YEQw.js +1 -0
  26. package/dist/{nuxt/runtime/middleware/auth.global.es.js → js/nuxt/runtime/middleware/auth.global-_2xq-SvK.js} +1 -1
  27. package/dist/js/nuxt/runtime/middleware/auth.global-dZpk-3-I.js +1 -0
  28. package/dist/js/nuxt/runtime/plugin.client-D7S6ulTg.js +1 -0
  29. package/dist/{nuxt/runtime/plugin.client.es.js → js/nuxt/runtime/plugin.client-KK_pCEfA.js} +2 -4
  30. package/dist/js/nuxt/runtime/plugin.server-BpSAN5Gh.js +1 -0
  31. package/dist/{nuxt/runtime/plugin.server.es.js → js/nuxt/runtime/plugin.server-CGdeJOoz.js} +1 -1
  32. package/dist/js/nuxt/runtime/plugins/auth-interceptor.client-BQu0eR16.js +1 -0
  33. package/dist/{nuxt/runtime/plugins/auth-interceptor.client.es.js → js/nuxt/runtime/plugins/auth-interceptor.client-DIa4pC59.js} +1 -1
  34. package/dist/js/nuxt-DqhAWeo-.js +1 -0
  35. package/dist/{nuxt.es.js → js/nuxt-MUpTW0D9.js} +3 -3
  36. package/dist/{nuxt-v4/module.es.js → js/nuxt-v4/module-CCvkwSrU.js} +2 -0
  37. package/dist/js/nuxt-v4/module-CDtxGAn8.js +1 -0
  38. package/dist/{nuxt-v4/runtime/composables/useAuthenticatedFetch.es.js → js/nuxt-v4/runtime/composables/useAuthenticatedFetch-I0BKB43E.js} +1 -1
  39. package/dist/js/nuxt-v4/runtime/composables/useAuthenticatedFetch-fAO6ieYd.js +1 -0
  40. package/dist/{nuxt-v4/runtime/composables/useStrandsAuth.es.js → js/nuxt-v4/runtime/composables/useStrandsAuth-BZe8CTx0.js} +1 -1
  41. package/dist/js/nuxt-v4/runtime/composables/useStrandsAuth-DPGVMZ-e.js +1 -0
  42. package/dist/js/nuxt-v4/runtime/middleware/auth.global-B0pyByUu.js +1 -0
  43. package/dist/{nuxt-v4/runtime/middleware/auth.global.es.js → js/nuxt-v4/runtime/middleware/auth.global-C_saJaMU.js} +1 -1
  44. package/dist/{nuxt-v4/runtime/plugin.client.es.js → js/nuxt-v4/runtime/plugin.client-CxLmYQfu.js} +2 -4
  45. package/dist/js/nuxt-v4/runtime/plugin.client-DGO53i-e.js +1 -0
  46. package/dist/{nuxt-v4/runtime/plugin.server.es.js → js/nuxt-v4/runtime/plugin.server-BM6HYyiZ.js} +1 -1
  47. package/dist/js/nuxt-v4/runtime/plugin.server-D_dUMHYo.js +1 -0
  48. package/dist/js/nuxt-v4/runtime/plugins/auth-interceptor.client-CUNOTFBp.js +1 -0
  49. package/dist/{nuxt-v4/runtime/plugins/auth-interceptor.client.es.js → js/nuxt-v4/runtime/plugins/auth-interceptor.client-Qht8QSLW.js} +1 -1
  50. package/dist/{nuxt-v4.es.js → js/nuxt-v4-C5JN4uyM.js} +3 -3
  51. package/dist/js/nuxt-v4-DuwGUuhX.js +1 -0
  52. package/dist/js/ui-components-BC1UK39i.js +5204 -0
  53. package/dist/js/ui-components-BC1UK39i.js.br +0 -0
  54. package/dist/js/ui-components-BC1UK39i.js.gz +0 -0
  55. package/dist/js/ui-components-CocLXkUI.js +1 -0
  56. package/dist/js/ui-components-CocLXkUI.js.br +0 -0
  57. package/dist/js/ui-components-CocLXkUI.js.gz +0 -0
  58. package/dist/js/utils-B9zcSW52.js +1 -0
  59. package/dist/js/utils-B9zcSW52.js.br +0 -0
  60. package/dist/js/utils-B9zcSW52.js.gz +0 -0
  61. package/dist/js/utils-BZHeJkZf.js +1080 -0
  62. package/dist/js/utils-BZHeJkZf.js.br +0 -0
  63. package/dist/js/utils-BZHeJkZf.js.gz +0 -0
  64. package/dist/nuxt/module.d.ts +1 -5
  65. package/dist/nuxt/runtime/composables/useAuthenticatedFetch.d.ts +1 -20
  66. package/dist/nuxt/runtime/composables/useStrandsAuth.d.ts +1 -142
  67. package/dist/nuxt/runtime/middleware/auth.global.d.ts +1 -3
  68. package/dist/nuxt/runtime/plugin.client.d.ts +1 -3
  69. package/dist/nuxt/runtime/plugin.server.d.ts +1 -3
  70. package/dist/nuxt/runtime/plugins/auth-interceptor.client.d.ts +1 -3
  71. package/dist/nuxt-v4/module.d.ts +1 -5
  72. package/dist/nuxt-v4/runtime/composables/useAuthenticatedFetch.d.ts +1 -20
  73. package/dist/nuxt-v4/runtime/composables/useStrandsAuth.d.ts +1 -27
  74. package/dist/nuxt-v4/runtime/middleware/auth.global.d.ts +1 -3
  75. package/dist/nuxt-v4/runtime/plugin.client.d.ts +1 -3
  76. package/dist/nuxt-v4/runtime/plugin.server.d.ts +1 -3
  77. package/dist/nuxt-v4/runtime/plugins/auth-interceptor.client.d.ts +1 -3
  78. package/dist/nuxt-v4.d.ts +1 -4
  79. package/dist/nuxt.d.ts +1 -4
  80. package/dist/robots.txt +4 -0
  81. package/dist/sitemap.xml +9 -0
  82. package/dist/styles/accui-DF7zRGFD.css +1 -0
  83. package/dist/styles/accui-DF7zRGFD.css.br +0 -0
  84. package/dist/styles/accui-DF7zRGFD.css.gz +0 -0
  85. package/package.json +5 -1
  86. package/dist/accui.css +0 -1
  87. package/dist/nuxt/module.cjs.js +0 -1
  88. package/dist/nuxt/runtime/composables/useAuthenticatedFetch.cjs.js +0 -1
  89. package/dist/nuxt/runtime/composables/useStrandsAuth.cjs.js +0 -1
  90. package/dist/nuxt/runtime/middleware/auth.d.ts +0 -7
  91. package/dist/nuxt/runtime/middleware/auth.global.cjs.js +0 -1
  92. package/dist/nuxt/runtime/middleware/guest.d.ts +0 -7
  93. package/dist/nuxt/runtime/plugin.client.cjs.js +0 -1
  94. package/dist/nuxt/runtime/plugin.server.cjs.js +0 -1
  95. package/dist/nuxt/runtime/plugins/auth-interceptor.client.cjs.js +0 -1
  96. package/dist/nuxt/types.d.ts +0 -45
  97. package/dist/nuxt-v4/module.cjs.js +0 -1
  98. package/dist/nuxt-v4/runtime/composables/useAuthenticatedFetch.cjs.js +0 -1
  99. package/dist/nuxt-v4/runtime/composables/useStrandsAuth.cjs.js +0 -1
  100. package/dist/nuxt-v4/runtime/middleware/auth.global.cjs.js +0 -1
  101. package/dist/nuxt-v4/runtime/plugin.client.cjs.js +0 -1
  102. package/dist/nuxt-v4/runtime/plugin.server.cjs.js +0 -1
  103. package/dist/nuxt-v4/runtime/plugins/auth-interceptor.client.cjs.js +0 -1
  104. package/dist/nuxt-v4/types.d.ts +0 -63
  105. package/dist/nuxt-v4.cjs.js +0 -1
  106. package/dist/nuxt.cjs.js +0 -1
  107. package/dist/shared/defaults.d.ts +0 -2
  108. package/dist/strands-auth-ui.cjs.js +0 -1
  109. package/dist/strands-auth-ui.es.js +0 -10561
  110. package/dist/types/index.d.ts +0 -236
  111. package/dist/useStrandsAuth-CTlaiFqK.cjs +0 -1
  112. package/dist/useStrandsAuth-Cev-PTun.js +0 -899
  113. package/dist/useStrandsConfig-Cxb360Os.js +0 -179
  114. package/dist/useStrandsConfig-Z9_36OcV.cjs +0 -1
  115. package/dist/utils/index.d.ts +0 -1
  116. package/dist/utils/slots.d.ts +0 -1
  117. package/dist/utils/validation.d.ts +0 -12
  118. package/dist/vue/components/SignedIn.vue.d.ts +0 -54
  119. package/dist/vue/components/SignedOut.vue.d.ts +0 -54
  120. package/dist/vue/components/StrandsAuth.vue.d.ts +0 -25
  121. package/dist/vue/components/StrandsBackupCodesModal.vue.d.ts +0 -12
  122. package/dist/vue/components/StrandsCompleteSignUp.vue.d.ts +0 -21
  123. package/dist/vue/components/StrandsConfigProvider.vue.d.ts +0 -22
  124. package/dist/vue/components/StrandsConfirmModal.vue.d.ts +0 -22
  125. package/dist/vue/components/StrandsEmailMfaSetupModal.vue.d.ts +0 -12
  126. package/dist/vue/components/StrandsHardwareKeySetupModal.vue.d.ts +0 -15
  127. package/dist/vue/components/StrandsLogo.vue.d.ts +0 -8
  128. package/dist/vue/components/StrandsMFASetup.vue.d.ts +0 -16
  129. package/dist/vue/components/StrandsMfaModal.vue.d.ts +0 -12
  130. package/dist/vue/components/StrandsMfaVerification.vue.d.ts +0 -17
  131. package/dist/vue/components/StrandsPasswordReset.vue.d.ts +0 -15
  132. package/dist/vue/components/StrandsSecuredFooter.vue.d.ts +0 -22
  133. package/dist/vue/components/StrandsSessionsModal.vue.d.ts +0 -14
  134. package/dist/vue/components/StrandsSettingsModal.vue.d.ts +0 -18
  135. package/dist/vue/components/StrandsSignIn.vue.d.ts +0 -21
  136. package/dist/vue/components/StrandsSignUp.vue.d.ts +0 -19
  137. package/dist/vue/components/StrandsTotpSetupModal.vue.d.ts +0 -12
  138. package/dist/vue/components/StrandsUserButton.vue.d.ts +0 -30
  139. package/dist/vue/components/StrandsUserProfile.vue.d.ts +0 -26
  140. package/dist/vue/components/SvgIcon.vue.d.ts +0 -17
  141. package/dist/vue/components/VirtualList.vue.d.ts +0 -37
  142. package/dist/vue/components/icons/IconGithub.vue.d.ts +0 -3
  143. package/dist/vue/components/icons/IconGoogle.vue.d.ts +0 -3
  144. package/dist/vue/components/icons/index.d.ts +0 -2
  145. package/dist/vue/components/index.d.ts +0 -26
  146. package/dist/vue/composables/useAuthenticatedFetch.d.ts +0 -20
  147. package/dist/vue/composables/useOAuthProviders.d.ts +0 -74
  148. package/dist/vue/composables/useStrandsAuth.d.ts +0 -130
  149. package/dist/vue/composables/useStrandsConfig.d.ts +0 -11
  150. package/dist/vue/composables/useStrandsMfa.d.ts +0 -38
  151. package/dist/vue/index.d.ts +0 -12
  152. package/dist/vue/plugins/StrandsUIPlugin.d.ts +0 -19
  153. package/dist/vue/ui/UiAlert.vue.d.ts +0 -31
  154. package/dist/vue/ui/UiAvatarEditor.vue.d.ts +0 -25
  155. package/dist/vue/ui/UiButton.vue.d.ts +0 -54
  156. package/dist/vue/ui/UiCard.vue.d.ts +0 -29
  157. package/dist/vue/ui/UiInput.vue.d.ts +0 -48
  158. package/dist/vue/ui/UiLevelProgress.vue.d.ts +0 -19
  159. package/dist/vue/ui/UiLink.vue.d.ts +0 -42
  160. package/dist/vue/ui/UiLoader.vue.d.ts +0 -15
  161. package/dist/vue/ui/UiModal.vue.d.ts +0 -33
  162. package/dist/vue/ui/UiTabs.vue.d.ts +0 -17
  163. package/dist/vue/ui/UiToggle.vue.d.ts +0 -15
  164. package/dist/vue/ui/index.d.ts +0 -29
  165. package/dist/vue/utils/contrast.d.ts +0 -79
  166. package/dist/vue/utils/debounce.d.ts +0 -12
  167. package/dist/vue/utils/fontPreloader.d.ts +0 -19
  168. package/dist/vue/utils/iconProps.d.ts +0 -9
  169. package/dist/vue/utils/lazyComponents.d.ts +0 -2
  170. package/dist/vue/utils/levels.d.ts +0 -27
  171. package/dist/vue/utils/performanceInit.d.ts +0 -40
  172. package/dist/vue/utils/requestCache.d.ts +0 -49
  173. package/dist/vue/utils/sounds.d.ts +0 -56
@@ -1,899 +0,0 @@
1
- import { ref, computed, onUnmounted } from "vue";
2
- import { u as useStrandsConfig } from "./useStrandsConfig-Cxb360Os.js";
3
- class RequestCache {
4
- cache = /* @__PURE__ */ new Map();
5
- DEFAULT_TTL = 5 * 60 * 1e3;
6
- // 5 minutes
7
- /**
8
- * Memoized fetch - prevents duplicate requests and caches results
9
- */
10
- async fetch(key, fetcher, ttl = this.DEFAULT_TTL) {
11
- const now = Date.now();
12
- const entry = this.cache.get(key);
13
- if (entry && now - entry.timestamp < entry.ttl) {
14
- return entry.promise;
15
- }
16
- this.cleanExpired();
17
- const promise = fetcher().finally(() => {
18
- setTimeout(() => {
19
- this.cache.delete(key);
20
- }, ttl);
21
- });
22
- this.cache.set(key, {
23
- promise,
24
- timestamp: now,
25
- ttl
26
- });
27
- return promise;
28
- }
29
- /**
30
- * Clear all cached entries
31
- */
32
- clear() {
33
- this.cache.clear();
34
- }
35
- /**
36
- * Remove a specific cache entry
37
- */
38
- invalidate(key) {
39
- this.cache.delete(key);
40
- }
41
- /**
42
- * Clean expired cache entries
43
- */
44
- cleanExpired() {
45
- const now = Date.now();
46
- for (const [key, entry] of this.cache.entries()) {
47
- if (now - entry.timestamp > entry.ttl) {
48
- this.cache.delete(key);
49
- }
50
- }
51
- }
52
- /**
53
- * Get cache statistics (for debugging)
54
- */
55
- getStats() {
56
- return {
57
- size: this.cache.size,
58
- entries: Array.from(this.cache.keys())
59
- };
60
- }
61
- }
62
- const requestCache = new RequestCache();
63
- function useRequestCache() {
64
- return {
65
- fetch: requestCache.fetch.bind(requestCache),
66
- clear: requestCache.clear.bind(requestCache),
67
- invalidate: requestCache.invalidate.bind(requestCache),
68
- getStats: requestCache.getStats.bind(requestCache)
69
- };
70
- }
71
- function debounce(func, wait) {
72
- let timeout = null;
73
- return (...args) => {
74
- if (timeout) {
75
- clearTimeout(timeout);
76
- }
77
- timeout = setTimeout(() => {
78
- func(...args);
79
- }, wait);
80
- };
81
- }
82
- const debouncedSetItem = debounce((key, value) => {
83
- if (typeof window !== "undefined") {
84
- localStorage.setItem(key, value);
85
- }
86
- }, 300);
87
- const mapApiUserToFrontend = (apiUser) => {
88
- return {
89
- id: apiUser.id,
90
- email: apiUser.email,
91
- firstName: apiUser.first_name || apiUser.firstName || "",
92
- lastName: apiUser.last_name || apiUser.lastName || "",
93
- avatar: apiUser.avatar_url || apiUser.avatar,
94
- mfaEnabled: apiUser.mfa_enabled ?? apiUser.mfaEnabled ?? false,
95
- emailVerified: apiUser.email_verified ?? apiUser.emailVerified ?? false,
96
- passwordUpdatedAt: apiUser.password_updated_at || apiUser.passwordUpdatedAt,
97
- settings: apiUser.settings || {},
98
- xp: apiUser.xp || 0,
99
- level: apiUser.level || 1,
100
- next_level_xp: apiUser.next_level_xp || apiUser.next_level_xp || 4,
101
- username: apiUser.username,
102
- usernameLastChangedAt: apiUser.username_last_changed_at || apiUser.usernameLastChangedAt,
103
- createdAt: apiUser.created_at || apiUser.createdAt,
104
- updatedAt: apiUser.updated_at || apiUser.updatedAt || (/* @__PURE__ */ new Date()).toISOString()
105
- };
106
- };
107
- const globalState = {
108
- currentUser: ref(null),
109
- currentSession: ref(null),
110
- loadingStates: ref({
111
- initializing: true,
112
- signingIn: false,
113
- signingUp: false,
114
- signingOut: false,
115
- refreshingToken: false,
116
- sendingMfaEmail: false,
117
- verifyingMfa: false,
118
- loadingProfile: false
119
- }),
120
- isInitialized: ref(false),
121
- mfaRequired: ref(false),
122
- mfaSessionId: ref(null),
123
- availableMfaMethods: ref([])
124
- };
125
- let refreshTimer = null;
126
- let refreshPromise = null;
127
- function useStrandsAuth() {
128
- const { getUrl } = useStrandsConfig();
129
- const { fetch: cachedFetch, clear: clearCache, invalidate } = useRequestCache();
130
- const { currentUser, currentSession, loadingStates, isInitialized, mfaRequired, mfaSessionId, availableMfaMethods } = globalState;
131
- const isInitializing = computed(() => loadingStates.value.initializing);
132
- const isSigningIn = computed(() => loadingStates.value.signingIn);
133
- const isSigningUp = computed(() => loadingStates.value.signingUp);
134
- const isSigningOut = computed(() => loadingStates.value.signingOut);
135
- const isRefreshingToken = computed(() => loadingStates.value.refreshingToken);
136
- const isSendingMfaEmail = computed(() => loadingStates.value.sendingMfaEmail);
137
- const isVerifyingMfa = computed(() => loadingStates.value.verifyingMfa);
138
- computed(() => loadingStates.value.loadingProfile);
139
- const loading = computed(
140
- () => loadingStates.value.signingIn || loadingStates.value.signingUp || loadingStates.value.signingOut || loadingStates.value.refreshingToken || loadingStates.value.sendingMfaEmail || loadingStates.value.verifyingMfa || loadingStates.value.loadingProfile
141
- );
142
- const isLoading = computed(() => loadingStates.value.initializing || loading.value);
143
- const loadingMessage = computed(() => {
144
- const states = loadingStates.value;
145
- if (states.initializing) return "Checking authentication...";
146
- if (states.signingIn) return "Signing you in...";
147
- if (states.signingUp) return "Creating your account...";
148
- if (states.signingOut) return "Signing you out...";
149
- if (states.refreshingToken) return "Refreshing session...";
150
- if (states.sendingMfaEmail) return "Sending verification code...";
151
- if (states.verifyingMfa) return "Verifying code...";
152
- if (states.loadingProfile) return "Loading profile...";
153
- return "Loading...";
154
- });
155
- const getAuthHeaders = () => {
156
- if (!currentSession.value?.accessToken) {
157
- throw new Error("No access token available");
158
- }
159
- currentSession.value.expiresAt;
160
- const headers = {
161
- "Authorization": `Bearer ${currentSession.value.accessToken}`
162
- };
163
- if (currentSession.value?.refreshToken) {
164
- headers["x-refresh-token"] = currentSession.value.refreshToken;
165
- }
166
- return headers;
167
- };
168
- const completeHardwareKeyRegistration = async (deviceId, credential, accessToken) => {
169
- if (!currentSession.value?.accessToken) {
170
- throw new Error("No access token available");
171
- }
172
- const response = await fetch(getUrl("mfaHardwareCompleteRegistration"), {
173
- method: "POST",
174
- headers: {
175
- "Content-Type": "application/json",
176
- "Authorization": `Bearer ${currentSession.value.accessToken}`
177
- },
178
- body: JSON.stringify({
179
- device_id: deviceId,
180
- credential
181
- })
182
- });
183
- if (!response.ok) {
184
- const errorText = await response.text();
185
- let errorMessage = "Failed to complete hardware key registration";
186
- try {
187
- const errorData = JSON.parse(errorText);
188
- errorMessage = errorData.message || errorData.error || errorText;
189
- } catch {
190
- errorMessage = errorText || "Failed to complete hardware key registration";
191
- }
192
- throw new Error(errorMessage);
193
- }
194
- return response.json();
195
- };
196
- const registerHardwareKey = async (deviceName, accessToken, deviceType = "hardware") => {
197
- if (!currentSession.value?.accessToken) {
198
- throw new Error("No access token available");
199
- }
200
- const response = await fetch(getUrl("mfaHardwareStartRegistration"), {
201
- method: "POST",
202
- headers: {
203
- "Content-Type": "application/json",
204
- "Authorization": `Bearer ${currentSession.value.accessToken}`
205
- },
206
- body: JSON.stringify({
207
- device_name: deviceName,
208
- device_type: deviceType
209
- })
210
- });
211
- if (!response.ok) {
212
- const errorText = await response.text();
213
- let errorMessage = "Failed to start hardware key registration";
214
- try {
215
- const errorData = JSON.parse(errorText);
216
- errorMessage = errorData.message || errorData.error || errorText;
217
- } catch {
218
- errorMessage = errorText || "Failed to start hardware key registration";
219
- }
220
- throw new Error(errorMessage);
221
- }
222
- return response.json();
223
- };
224
- const isAuthenticated = computed(() => currentUser.value !== null);
225
- const signIn = async (credentials) => {
226
- loadingStates.value.signingIn = true;
227
- try {
228
- mfaRequired.value = false;
229
- mfaSessionId.value = null;
230
- availableMfaMethods.value = [];
231
- const headers = {
232
- "Content-Type": "application/json"
233
- };
234
- if (typeof window !== "undefined" && window.location) {
235
- headers["Origin"] = window.location.origin;
236
- }
237
- const response = await fetch(getUrl("signIn"), {
238
- method: "POST",
239
- headers,
240
- body: JSON.stringify(credentials)
241
- });
242
- if (!response.ok) {
243
- if (response.status === 401) {
244
- throw new Error("Invalid email or password");
245
- } else if (response.status === 403) {
246
- throw new Error("Please verify your email address before signing in");
247
- } else {
248
- throw new Error(`Sign in failed: ${response.status} ${response.statusText}`);
249
- }
250
- }
251
- const authData = await response.json();
252
- if (authData.mfa_required) {
253
- mfaRequired.value = true;
254
- mfaSessionId.value = authData.mfa_session_id || null;
255
- const methods = (authData.available_mfa_methods || []).map((method) => {
256
- let fallbackName = `${method.device_type.charAt(0).toUpperCase() + method.device_type.slice(1)} Authentication`;
257
- if (method.device_type === "hardware") {
258
- fallbackName = method.device_name || "Security Key";
259
- } else if (method.device_type === "totp") {
260
- fallbackName = method.device_name || "Authenticator App";
261
- } else if (method.device_type === "email") {
262
- fallbackName = method.device_name || "Email Verification";
263
- }
264
- return {
265
- id: method.device_id,
266
- device_type: method.device_type,
267
- device_name: method.device_name || fallbackName,
268
- is_active: true,
269
- created_at: (/* @__PURE__ */ new Date()).toISOString(),
270
- last_used_at: method.last_used_at,
271
- // Pass through additional metadata if available
272
- credential_id: method.credential_id,
273
- device_info: method.device_info
274
- };
275
- });
276
- availableMfaMethods.value = methods;
277
- loadingStates.value.signingIn = false;
278
- return authData;
279
- }
280
- await setAuthData(authData);
281
- return authData;
282
- } catch (error) {
283
- throw error;
284
- } finally {
285
- loadingStates.value.signingIn = false;
286
- }
287
- };
288
- const signUp = async (userData) => {
289
- loadingStates.value.signingUp = true;
290
- try {
291
- throw new Error("Sign up not implemented - please integrate with auth SDK");
292
- } finally {
293
- loadingStates.value.signingUp = false;
294
- }
295
- };
296
- const signOut = async () => {
297
- loadingStates.value.signingOut = true;
298
- try {
299
- stopTokenRefreshTimer();
300
- refreshPromise = null;
301
- clearCache();
302
- currentUser.value = null;
303
- currentSession.value = null;
304
- mfaRequired.value = false;
305
- mfaSessionId.value = null;
306
- availableMfaMethods.value = [];
307
- if (typeof window !== "undefined") {
308
- localStorage.removeItem("strands_auth_session");
309
- localStorage.removeItem("strands_auth_user");
310
- }
311
- } finally {
312
- loadingStates.value.signingOut = false;
313
- }
314
- };
315
- const refreshToken = async () => {
316
- if (!currentSession.value?.refreshToken) {
317
- return false;
318
- }
319
- if (refreshPromise) {
320
- console.log("Token refresh already in progress, waiting for completion...");
321
- return await refreshPromise;
322
- }
323
- refreshPromise = (async () => {
324
- loadingStates.value.refreshingToken = true;
325
- try {
326
- const response = await fetch(getUrl("refresh"), {
327
- method: "POST",
328
- headers: {
329
- "Content-Type": "application/json"
330
- },
331
- body: JSON.stringify({
332
- refresh_token: currentSession.value.refreshToken
333
- })
334
- });
335
- if (!response.ok) {
336
- if (response.status === 401) {
337
- await signOut();
338
- return false;
339
- }
340
- throw new Error(`Token refresh failed: ${response.status} ${response.statusText}`);
341
- }
342
- const tokenData = await response.json();
343
- if (tokenData.user) {
344
- currentUser.value = mapApiUserToFrontend(tokenData.user);
345
- if (currentUser.value && typeof window !== "undefined") {
346
- localStorage.setItem("strands_auth_user", JSON.stringify(currentUser.value));
347
- }
348
- }
349
- const newSession = {
350
- accessToken: tokenData.access_token,
351
- refreshToken: tokenData.refresh_token,
352
- expiresAt: new Date(Date.now() + 5 * 60 * 1e3),
353
- // 5 minutes from now
354
- userId: tokenData.user?.id || currentUser.value?.id
355
- };
356
- currentSession.value = newSession;
357
- if (typeof window !== "undefined") {
358
- localStorage.setItem("strands_auth_session", JSON.stringify(newSession));
359
- }
360
- startTokenRefreshTimer();
361
- invalidate(`sessions:${currentSession.value.accessToken.slice(0, 20)}`);
362
- return true;
363
- } catch (error) {
364
- await signOut();
365
- return false;
366
- } finally {
367
- loadingStates.value.refreshingToken = false;
368
- }
369
- })();
370
- const result = await refreshPromise;
371
- refreshPromise = null;
372
- return result;
373
- };
374
- const fetchProfile = async () => {
375
- if (!currentSession.value?.accessToken) {
376
- throw new Error("No access token available");
377
- }
378
- const cacheKey = `profile:${currentSession.value.accessToken.slice(0, 20)}`;
379
- loadingStates.value.loadingProfile = true;
380
- try {
381
- return await cachedFetch(cacheKey, async () => {
382
- const response = await fetch(getUrl("profile"), {
383
- method: "GET",
384
- headers: {
385
- "Content-Type": "application/json",
386
- "Authorization": `Bearer ${currentSession.value?.accessToken}`
387
- }
388
- });
389
- if (!response.ok) {
390
- if (response.status === 401) {
391
- throw new Error("Authentication expired. Please sign in again.");
392
- } else {
393
- throw new Error(`Failed to fetch profile: ${response.status} ${response.statusText}`);
394
- }
395
- }
396
- const userData = await response.json();
397
- currentUser.value = mapApiUserToFrontend(userData);
398
- if (currentUser.value && typeof window !== "undefined") {
399
- localStorage.setItem("strands_auth_user", JSON.stringify(currentUser.value));
400
- }
401
- return currentUser.value;
402
- });
403
- } finally {
404
- loadingStates.value.loadingProfile = false;
405
- }
406
- };
407
- const updateProfile = async (profileData) => {
408
- if (!currentSession.value?.accessToken) {
409
- throw new Error("No access token available");
410
- }
411
- loadingStates.value.loadingProfile = true;
412
- try {
413
- const response = await fetch(getUrl("profile"), {
414
- method: "POST",
415
- headers: {
416
- "Content-Type": "application/json",
417
- "Authorization": `Bearer ${currentSession.value.accessToken}`
418
- },
419
- body: JSON.stringify({
420
- first_name: profileData.firstName,
421
- last_name: profileData.lastName
422
- })
423
- });
424
- if (!response.ok) {
425
- if (response.status === 401) {
426
- throw new Error("Authentication expired. Please sign in again.");
427
- } else {
428
- throw new Error(`Profile update failed: ${response.status} ${response.statusText}`);
429
- }
430
- }
431
- const updatedUserData = await response.json();
432
- currentUser.value = mapApiUserToFrontend(updatedUserData);
433
- if (currentUser.value) {
434
- debouncedSetItem("strands_auth_user", JSON.stringify(currentUser.value));
435
- }
436
- return currentUser.value;
437
- } finally {
438
- loadingStates.value.loadingProfile = false;
439
- }
440
- };
441
- const updateUserSettings = async (settings) => {
442
- if (!currentSession.value?.accessToken) {
443
- throw new Error("No access token available");
444
- }
445
- loadingStates.value.loadingProfile = true;
446
- try {
447
- const response = await fetch(getUrl("settings"), {
448
- method: "POST",
449
- headers: {
450
- "Content-Type": "application/json",
451
- "Authorization": `Bearer ${currentSession.value.accessToken}`
452
- },
453
- body: JSON.stringify({
454
- settings
455
- })
456
- });
457
- if (!response.ok) {
458
- if (response.status === 401) {
459
- throw new Error("Authentication expired. Please sign in again.");
460
- } else {
461
- throw new Error(`Settings update failed: ${response.status} ${response.statusText}`);
462
- }
463
- }
464
- const updatedUserData = await response.json();
465
- currentUser.value = mapApiUserToFrontend(updatedUserData);
466
- if (currentUser.value) {
467
- debouncedSetItem("strands_auth_user", JSON.stringify(currentUser.value));
468
- }
469
- return currentUser.value;
470
- } finally {
471
- loadingStates.value.loadingProfile = false;
472
- }
473
- };
474
- const changeEmail = async (newEmail, password) => {
475
- if (!currentSession.value?.accessToken) {
476
- throw new Error("No access token available");
477
- }
478
- loadingStates.value.loadingProfile = true;
479
- try {
480
- const response = await fetch(getUrl("changeEmail"), {
481
- method: "POST",
482
- headers: {
483
- "Content-Type": "application/json",
484
- "Authorization": `Bearer ${currentSession.value.accessToken}`
485
- },
486
- body: JSON.stringify({
487
- new_email: newEmail,
488
- password
489
- })
490
- });
491
- if (!response.ok) {
492
- if (response.status === 401) {
493
- throw new Error("Authentication expired. Please sign in again.");
494
- } else {
495
- const errorData = await response.json().catch(() => ({}));
496
- throw new Error(errorData.message || `Email change failed: ${response.status} ${response.statusText}`);
497
- }
498
- }
499
- const result = await response.json();
500
- if (currentUser.value) {
501
- currentUser.value = {
502
- ...currentUser.value,
503
- email: newEmail,
504
- emailVerified: false,
505
- // Email needs to be verified again
506
- updatedAt: (/* @__PURE__ */ new Date()).toISOString()
507
- };
508
- if (typeof window !== "undefined") {
509
- localStorage.setItem("strands_auth_user", JSON.stringify(currentUser.value));
510
- }
511
- }
512
- return result;
513
- } finally {
514
- loadingStates.value.loadingProfile = false;
515
- }
516
- };
517
- const verifyMfa = async (deviceId, code, isBackupCode = false) => {
518
- if (!mfaSessionId.value) {
519
- throw new Error("No MFA session available");
520
- }
521
- loadingStates.value.verifyingMfa = true;
522
- try {
523
- const endpoint = isBackupCode ? getUrl("mfaBackupCodeVerify") : getUrl("mfaSigninVerify");
524
- const body = isBackupCode ? { mfa_session_id: mfaSessionId.value, backup_code: code } : { mfa_session_id: mfaSessionId.value, device_id: deviceId, code };
525
- const response = await fetch(endpoint, {
526
- method: "POST",
527
- headers: { "Content-Type": "application/json" },
528
- body: JSON.stringify(body)
529
- });
530
- if (!response.ok) {
531
- const errorText = await response.text();
532
- let errorMessage = "MFA verification failed";
533
- try {
534
- const errorData = JSON.parse(errorText);
535
- errorMessage = errorData.message || errorData.error || errorText;
536
- } catch {
537
- errorMessage = errorText || "MFA verification failed";
538
- }
539
- throw new Error(errorMessage);
540
- }
541
- const authData = await response.json();
542
- mfaRequired.value = false;
543
- mfaSessionId.value = null;
544
- availableMfaMethods.value = [];
545
- await setAuthData(authData);
546
- return authData;
547
- } finally {
548
- loadingStates.value.verifyingMfa = false;
549
- }
550
- };
551
- const sendMfaEmailCode = async (deviceId) => {
552
- if (!mfaSessionId.value) {
553
- throw new Error("No MFA session available");
554
- }
555
- loadingStates.value.sendingMfaEmail = true;
556
- try {
557
- const response = await fetch(getUrl("mfaSigninSendEmail"), {
558
- method: "POST",
559
- headers: { "Content-Type": "application/json" },
560
- body: JSON.stringify({
561
- mfa_session_id: mfaSessionId.value,
562
- device_id: deviceId
563
- })
564
- });
565
- if (!response.ok) {
566
- const errorText = await response.text();
567
- let errorMessage = "Failed to send MFA email code";
568
- try {
569
- const errorData = JSON.parse(errorText);
570
- errorMessage = errorData.message || errorData.error || errorText;
571
- } catch {
572
- errorMessage = errorText || "Failed to send MFA email code";
573
- }
574
- throw new Error(errorMessage);
575
- }
576
- const result = await response.json();
577
- return result;
578
- } finally {
579
- loadingStates.value.sendingMfaEmail = false;
580
- }
581
- };
582
- const getMfaWebAuthnChallenge = async (deviceId) => {
583
- if (!mfaSessionId.value) {
584
- throw new Error("No MFA session available");
585
- }
586
- const response = await fetch(getUrl("mfaWebAuthnChallenge"), {
587
- method: "POST",
588
- headers: { "Content-Type": "application/json" },
589
- body: JSON.stringify({
590
- mfa_session_id: mfaSessionId.value,
591
- device_id: deviceId
592
- })
593
- });
594
- if (!response.ok) {
595
- const errorText = await response.text();
596
- let errorMessage = "Failed to get WebAuthn challenge";
597
- try {
598
- const errorData = JSON.parse(errorText);
599
- errorMessage = errorData.message || errorData.error || errorText;
600
- } catch {
601
- errorMessage = errorText || errorMessage;
602
- }
603
- throw new Error(errorMessage);
604
- }
605
- return response.json();
606
- };
607
- const setAuthData = async (authResponse) => {
608
- try {
609
- if (authResponse.user) {
610
- currentUser.value = mapApiUserToFrontend(authResponse.user);
611
- }
612
- const session = {
613
- accessToken: authResponse.access_token,
614
- refreshToken: authResponse.refresh_token,
615
- expiresAt: new Date(Date.now() + 5 * 60 * 1e3),
616
- // 5 minutes from now (matching API token expiry)
617
- userId: currentUser.value?.id || authResponse.user?.id
618
- };
619
- currentSession.value = session;
620
- if (typeof window !== "undefined") {
621
- localStorage.setItem("strands_auth_session", JSON.stringify(session));
622
- if (currentUser.value) {
623
- localStorage.setItem("strands_auth_user", JSON.stringify(currentUser.value));
624
- }
625
- }
626
- startTokenRefreshTimer();
627
- } catch (error) {
628
- }
629
- };
630
- const startTokenRefreshTimer = () => {
631
- if (refreshTimer) {
632
- clearTimeout(refreshTimer);
633
- }
634
- if (!currentSession.value) return;
635
- if (typeof document !== "undefined" && document.visibilityState === "hidden") {
636
- return;
637
- }
638
- const now = /* @__PURE__ */ new Date();
639
- const expiresAt = currentSession.value.expiresAt;
640
- const timeUntilRefresh = expiresAt.getTime() - now.getTime() - 1 * 60 * 1e3;
641
- if (timeUntilRefresh <= 0) {
642
- refreshToken();
643
- return;
644
- }
645
- refreshTimer = setTimeout(async () => {
646
- if (typeof document === "undefined" || document.visibilityState === "visible") {
647
- const success = await refreshToken();
648
- if (success) {
649
- startTokenRefreshTimer();
650
- }
651
- }
652
- }, timeUntilRefresh);
653
- };
654
- const stopTokenRefreshTimer = () => {
655
- if (refreshTimer) {
656
- clearTimeout(refreshTimer);
657
- refreshTimer = null;
658
- }
659
- };
660
- const initialize = async () => {
661
- if (isInitialized.value) return;
662
- loadingStates.value.initializing = true;
663
- try {
664
- if (typeof window !== "undefined") {
665
- const storedSession = localStorage.getItem("strands_auth_session");
666
- const storedUser = localStorage.getItem("strands_auth_user");
667
- if (storedSession && storedUser) {
668
- try {
669
- const session = JSON.parse(storedSession);
670
- const user = JSON.parse(storedUser);
671
- session.expiresAt = new Date(session.expiresAt);
672
- if (session.expiresAt > /* @__PURE__ */ new Date()) {
673
- currentSession.value = session;
674
- currentUser.value = user;
675
- startTokenRefreshTimer();
676
- } else {
677
- localStorage.removeItem("strands_auth_session");
678
- localStorage.removeItem("strands_auth_user");
679
- }
680
- } catch (error) {
681
- localStorage.removeItem("strands_auth_session");
682
- localStorage.removeItem("strands_auth_user");
683
- }
684
- }
685
- }
686
- isInitialized.value = true;
687
- await new Promise((resolve) => setTimeout(resolve, 50));
688
- } catch (error) {
689
- } finally {
690
- loadingStates.value.initializing = false;
691
- }
692
- };
693
- const changeUsername = async (newUsername) => {
694
- if (!currentSession.value?.accessToken) {
695
- throw new Error("No access token available");
696
- }
697
- loadingStates.value.loadingProfile = true;
698
- try {
699
- const response = await fetch(getUrl("changeUsername"), {
700
- method: "POST",
701
- headers: {
702
- "Content-Type": "application/json",
703
- "Authorization": `Bearer ${currentSession.value.accessToken}`
704
- },
705
- body: JSON.stringify({
706
- username: newUsername
707
- })
708
- });
709
- if (!response.ok) {
710
- const errorData = await response.json().catch(() => ({}));
711
- if (response.status === 409) {
712
- throw new Error("Username is already taken");
713
- } else if (errorData.cooldown_end) {
714
- throw new Error(`You can only change your username once every 30 days. You can change it again on ${new Date(errorData.cooldown_end).toLocaleDateString()}`);
715
- }
716
- throw new Error(errorData.message || `Username change failed: ${response.status} ${response.statusText}`);
717
- }
718
- const result = await response.json();
719
- if (currentUser.value) {
720
- currentUser.value = {
721
- ...currentUser.value,
722
- username: newUsername,
723
- usernameLastChangedAt: (/* @__PURE__ */ new Date()).toISOString(),
724
- updatedAt: (/* @__PURE__ */ new Date()).toISOString()
725
- };
726
- if (typeof window !== "undefined") {
727
- localStorage.setItem("strands_auth_user", JSON.stringify(currentUser.value));
728
- }
729
- }
730
- return result;
731
- } finally {
732
- loadingStates.value.loadingProfile = false;
733
- }
734
- };
735
- const getUsernameCooldown = async () => {
736
- if (!currentSession.value?.accessToken) {
737
- throw new Error("No access token available");
738
- }
739
- const response = await fetch(getUrl("usernameCooldown"), {
740
- method: "GET",
741
- headers: {
742
- "Authorization": `Bearer ${currentSession.value.accessToken}`
743
- }
744
- });
745
- if (!response.ok) {
746
- throw new Error(`Failed to get username cooldown: ${response.status} ${response.statusText}`);
747
- }
748
- return response.json();
749
- };
750
- const checkUsernameAvailability = async (username) => {
751
- const url = getUrl("checkUsernameAvailability").replace("{username}", encodeURIComponent(username));
752
- const response = await fetch(url, {
753
- method: "GET",
754
- headers: {
755
- "Content-Type": "application/json"
756
- }
757
- });
758
- if (!response.ok) {
759
- throw new Error(`Failed to check username availability: ${response.status} ${response.statusText}`);
760
- }
761
- return response.json();
762
- };
763
- const getUserSessions = async () => {
764
- if (!currentSession.value?.accessToken) {
765
- throw new Error("No access token available");
766
- }
767
- const cacheKey = `sessions:${currentSession.value.accessToken.slice(0, 20)}`;
768
- try {
769
- return await cachedFetch(cacheKey, async () => {
770
- const headers = getAuthHeaders();
771
- const response = await fetch(getUrl("sessions"), {
772
- method: "GET",
773
- headers
774
- });
775
- if (!response.ok) {
776
- const errorText = await response.text();
777
- throw new Error(`Failed to get user sessions: ${response.status} ${response.statusText}`);
778
- }
779
- return response.json();
780
- }, 2 * 60 * 1e3);
781
- } catch (error) {
782
- throw error;
783
- }
784
- };
785
- const getSessionStats = async () => {
786
- const response = await fetch(getUrl("sessionsStats"), {
787
- method: "GET",
788
- headers: getAuthHeaders()
789
- });
790
- if (!response.ok) {
791
- throw new Error(`Failed to get session stats: ${response.status} ${response.statusText}`);
792
- }
793
- return response.json();
794
- };
795
- const revokeSession = async (sessionId) => {
796
- const url = getUrl("sessionRevoke").replace("{session_id}", encodeURIComponent(sessionId));
797
- const response = await fetch(url, {
798
- method: "POST",
799
- headers: getAuthHeaders()
800
- });
801
- if (!response.ok) {
802
- throw new Error(`Failed to revoke session: ${response.status} ${response.statusText}`);
803
- }
804
- return response.status === 200;
805
- };
806
- const revokeAllOtherSessions = async () => {
807
- const response = await fetch(getUrl("sessionsRevokeAll"), {
808
- method: "POST",
809
- headers: getAuthHeaders()
810
- });
811
- if (!response.ok) {
812
- throw new Error(`Failed to revoke all other sessions: ${response.status} ${response.statusText}`);
813
- }
814
- return response.status === 200;
815
- };
816
- if (typeof document !== "undefined") {
817
- document.addEventListener("visibilitychange", () => {
818
- if (document.visibilityState === "visible" && currentSession.value) {
819
- startTokenRefreshTimer();
820
- } else if (document.visibilityState === "hidden") {
821
- stopTokenRefreshTimer();
822
- }
823
- });
824
- }
825
- const cleanup = () => {
826
- stopTokenRefreshTimer();
827
- clearCache();
828
- if (typeof document !== "undefined") {
829
- document.removeEventListener("visibilitychange", () => {
830
- });
831
- }
832
- };
833
- try {
834
- onUnmounted(cleanup);
835
- } catch (e) {
836
- }
837
- if (!isInitialized.value) {
838
- initialize();
839
- }
840
- return {
841
- // State
842
- user: computed(() => currentUser.value),
843
- currentUser: computed(() => currentUser.value),
844
- currentSession: computed(() => currentSession.value),
845
- isAuthenticated,
846
- isLoading: computed(() => isLoading.value || !isInitialized.value),
847
- loading: computed(() => loading.value),
848
- loadingMessage,
849
- // Specific loading states
850
- isInitializing,
851
- isSigningIn,
852
- isSigningUp,
853
- isSigningOut,
854
- isRefreshingToken,
855
- isSendingMfaEmail,
856
- isVerifyingMfa,
857
- // MFA State
858
- mfaRequired: computed(() => mfaRequired.value),
859
- mfaSessionId: computed(() => mfaSessionId.value),
860
- availableMfaMethods: computed(() => availableMfaMethods.value),
861
- // Methods
862
- signIn,
863
- signUp,
864
- signOut,
865
- refreshToken,
866
- fetchProfile,
867
- updateProfile,
868
- updateUserSettings,
869
- changeEmail,
870
- changeUsername,
871
- getUsernameCooldown,
872
- checkUsernameAvailability,
873
- // Session management
874
- getUserSessions,
875
- getSessionStats,
876
- revokeSession,
877
- revokeAllOtherSessions,
878
- initialize,
879
- setAuthData,
880
- verifyMfa,
881
- sendMfaEmailCode,
882
- getMfaWebAuthnChallenge,
883
- registerHardwareKey,
884
- completeHardwareKeyRegistration,
885
- // Token management
886
- startTokenRefreshTimer,
887
- stopTokenRefreshTimer,
888
- getAuthHeaders,
889
- // Force re-initialization (useful for testing or navigation)
890
- forceReInit: () => {
891
- isInitialized.value = false;
892
- loadingStates.value.initializing = true;
893
- initialize();
894
- }
895
- };
896
- }
897
- export {
898
- useStrandsAuth as u
899
- };