@strands.gg/accui 1.8.0 → 1.10.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 (49) hide show
  1. package/dist/accui.css +1 -5802
  2. package/dist/nuxt/module.cjs.js +1 -109
  3. package/dist/nuxt/module.cjs.js.map +1 -1
  4. package/dist/nuxt/module.es.js +0 -1
  5. package/dist/nuxt/runtime/composables/useStrandsAuth.cjs.js +1 -57
  6. package/dist/nuxt/runtime/composables/useStrandsAuth.cjs.js.map +1 -1
  7. package/dist/nuxt/runtime/composables/useStrandsAuth.es.js +1 -2
  8. package/dist/nuxt/runtime/middleware/auth.global.cjs.js +1 -42
  9. package/dist/nuxt/runtime/middleware/auth.global.cjs.js.map +1 -1
  10. package/dist/nuxt/runtime/middleware/auth.global.es.js +0 -1
  11. package/dist/nuxt/runtime/plugin.client.cjs.js +1 -26
  12. package/dist/nuxt/runtime/plugin.client.cjs.js.map +1 -1
  13. package/dist/nuxt/runtime/plugin.client.es.js +2 -1
  14. package/dist/nuxt/runtime/plugin.client.es.js.map +1 -1
  15. package/dist/nuxt/runtime/plugin.server.cjs.js +1 -17
  16. package/dist/nuxt/runtime/plugin.server.cjs.js.map +1 -1
  17. package/dist/nuxt/runtime/plugin.server.es.js +0 -1
  18. package/dist/nuxt-v4/module.cjs.js +1 -119
  19. package/dist/nuxt-v4/module.cjs.js.map +1 -1
  20. package/dist/nuxt-v4/module.es.js +0 -1
  21. package/dist/nuxt-v4/runtime/composables/useStrandsAuth.cjs.js +1 -70
  22. package/dist/nuxt-v4/runtime/composables/useStrandsAuth.cjs.js.map +1 -1
  23. package/dist/nuxt-v4/runtime/composables/useStrandsAuth.es.js +1 -2
  24. package/dist/nuxt-v4/runtime/middleware/auth.global.cjs.js +1 -42
  25. package/dist/nuxt-v4/runtime/middleware/auth.global.cjs.js.map +1 -1
  26. package/dist/nuxt-v4/runtime/middleware/auth.global.es.js +0 -1
  27. package/dist/nuxt-v4/runtime/plugin.client.cjs.js +1 -26
  28. package/dist/nuxt-v4/runtime/plugin.client.cjs.js.map +1 -1
  29. package/dist/nuxt-v4/runtime/plugin.client.es.js +2 -1
  30. package/dist/nuxt-v4/runtime/plugin.client.es.js.map +1 -1
  31. package/dist/nuxt-v4/runtime/plugin.server.cjs.js +1 -22
  32. package/dist/nuxt-v4/runtime/plugin.server.cjs.js.map +1 -1
  33. package/dist/nuxt-v4/runtime/plugin.server.es.js +0 -1
  34. package/dist/strands-auth-ui.cjs.js +1 -9840
  35. package/dist/strands-auth-ui.cjs.js.map +1 -1
  36. package/dist/strands-auth-ui.es.js +1398 -808
  37. package/dist/strands-auth-ui.es.js.map +1 -1
  38. package/dist/useStrandsAuth-Co9ekmXB.cjs +1 -0
  39. package/dist/useStrandsAuth-Co9ekmXB.cjs.map +1 -0
  40. package/dist/{useStrandsAuth-Beee__9G.js → useStrandsAuth-kWUOoMm-.js} +314 -172
  41. package/dist/useStrandsAuth-kWUOoMm-.js.map +1 -0
  42. package/dist/useStrandsConfig-Cxb360Os.js +0 -1
  43. package/dist/useStrandsConfig-Z9_36OcV.cjs +1 -0
  44. package/dist/{useStrandsConfig-Dms13Zd0.cjs.map → useStrandsConfig-Z9_36OcV.cjs.map} +1 -1
  45. package/package.json +1 -1
  46. package/dist/useStrandsAuth-Beee__9G.js.map +0 -1
  47. package/dist/useStrandsAuth-JfbGH2c-.cjs +0 -755
  48. package/dist/useStrandsAuth-JfbGH2c-.cjs.map +0 -1
  49. package/dist/useStrandsConfig-Dms13Zd0.cjs +0 -179
@@ -1,755 +0,0 @@
1
- "use strict";
2
- const vue = require("vue");
3
- const useStrandsConfig = require("./useStrandsConfig-Dms13Zd0.cjs");
4
- const { getUrl } = useStrandsConfig.useStrandsConfig();
5
- const currentUser = vue.ref(null);
6
- const currentSession = vue.ref(null);
7
- const isInitializing = vue.ref(true);
8
- const isSigningIn = vue.ref(false);
9
- const isSigningUp = vue.ref(false);
10
- const isSigningOut = vue.ref(false);
11
- const isRefreshingToken = vue.ref(false);
12
- const isSendingMfaEmail = vue.ref(false);
13
- const isVerifyingMfa = vue.ref(false);
14
- const isLoadingProfile = vue.ref(false);
15
- const loading = vue.computed(() => isSigningIn.value || isSigningUp.value || isSigningOut.value || isRefreshingToken.value || isSendingMfaEmail.value || isVerifyingMfa.value || isLoadingProfile.value);
16
- const isLoading = vue.computed(() => isInitializing.value || loading.value);
17
- const loadingMessage = vue.computed(() => {
18
- if (isInitializing.value) return "Checking authentication...";
19
- if (isSigningIn.value) return "Signing you in...";
20
- if (isSigningUp.value) return "Creating your account...";
21
- if (isSigningOut.value) return "Signing you out...";
22
- if (isRefreshingToken.value) return "Refreshing session...";
23
- if (isSendingMfaEmail.value) return "Sending verification code...";
24
- if (isVerifyingMfa.value) return "Verifying code...";
25
- return "Loading...";
26
- });
27
- const isInitialized = vue.ref(false);
28
- const mfaRequired = vue.ref(false);
29
- const mfaSessionId = vue.ref(null);
30
- const availableMfaMethods = vue.ref([]);
31
- let refreshTimer = null;
32
- function useStrandsAuth() {
33
- const getAuthHeaders = () => {
34
- if (!currentSession.value?.accessToken) {
35
- throw new Error("No access token available");
36
- }
37
- const headers = {
38
- "Authorization": `Bearer ${currentSession.value.accessToken}`
39
- };
40
- if (currentSession.value?.refreshToken) {
41
- headers["x-refresh-token"] = currentSession.value.refreshToken;
42
- }
43
- return headers;
44
- };
45
- const completeHardwareKeyRegistration = async (deviceId, credential, accessToken) => {
46
- if (!currentSession.value?.accessToken) {
47
- throw new Error("No access token available");
48
- }
49
- const response = await fetch(getUrl("mfaHardwareCompleteRegistration"), {
50
- method: "POST",
51
- headers: {
52
- "Content-Type": "application/json",
53
- "Authorization": `Bearer ${currentSession.value.accessToken}`
54
- },
55
- body: JSON.stringify({
56
- device_id: deviceId,
57
- credential
58
- })
59
- });
60
- if (!response.ok) {
61
- const errorText = await response.text();
62
- let errorMessage = "Failed to complete hardware key registration";
63
- try {
64
- const errorData = JSON.parse(errorText);
65
- errorMessage = errorData.message || errorData.error || errorText;
66
- } catch {
67
- errorMessage = errorText || "Failed to complete hardware key registration";
68
- }
69
- throw new Error(errorMessage);
70
- }
71
- return response.json();
72
- };
73
- const registerHardwareKey = async (deviceName, accessToken, deviceType = "hardware") => {
74
- if (!currentSession.value?.accessToken) {
75
- throw new Error("No access token available");
76
- }
77
- const response = await fetch(getUrl("mfaHardwareStartRegistration"), {
78
- method: "POST",
79
- headers: {
80
- "Content-Type": "application/json",
81
- "Authorization": `Bearer ${currentSession.value.accessToken}`
82
- },
83
- body: JSON.stringify({
84
- device_name: deviceName,
85
- device_type: deviceType
86
- })
87
- });
88
- if (!response.ok) {
89
- const errorText = await response.text();
90
- let errorMessage = "Failed to start hardware key registration";
91
- try {
92
- const errorData = JSON.parse(errorText);
93
- errorMessage = errorData.message || errorData.error || errorText;
94
- } catch {
95
- errorMessage = errorText || "Failed to start hardware key registration";
96
- }
97
- throw new Error(errorMessage);
98
- }
99
- return response.json();
100
- };
101
- const isAuthenticated = vue.computed(() => currentUser.value !== null);
102
- const signIn = async (credentials) => {
103
- isSigningIn.value = true;
104
- try {
105
- mfaRequired.value = false;
106
- mfaSessionId.value = null;
107
- availableMfaMethods.value = [];
108
- const response = await fetch(getUrl("signIn"), {
109
- method: "POST",
110
- headers: {
111
- "Content-Type": "application/json"
112
- },
113
- body: JSON.stringify(credentials)
114
- });
115
- if (!response.ok) {
116
- if (response.status === 401) {
117
- throw new Error("Invalid email or password");
118
- } else if (response.status === 403) {
119
- throw new Error("Please verify your email address before signing in");
120
- } else {
121
- throw new Error(`Sign in failed: ${response.status} ${response.statusText}`);
122
- }
123
- }
124
- const authData = await response.json();
125
- if (authData.mfa_required) {
126
- mfaRequired.value = true;
127
- mfaSessionId.value = authData.mfa_session_id || null;
128
- const methods = (authData.available_mfa_methods || []).map((method) => {
129
- let fallbackName = `${method.device_type.charAt(0).toUpperCase() + method.device_type.slice(1)} Authentication`;
130
- if (method.device_type === "hardware") {
131
- fallbackName = method.device_name || "Security Key";
132
- } else if (method.device_type === "totp") {
133
- fallbackName = method.device_name || "Authenticator App";
134
- } else if (method.device_type === "email") {
135
- fallbackName = method.device_name || "Email Verification";
136
- }
137
- return {
138
- id: method.device_id,
139
- device_type: method.device_type,
140
- device_name: method.device_name || fallbackName,
141
- is_active: true,
142
- created_at: (/* @__PURE__ */ new Date()).toISOString(),
143
- last_used_at: method.last_used_at,
144
- // Pass through additional metadata if available
145
- credential_id: method.credential_id,
146
- device_info: method.device_info
147
- };
148
- });
149
- availableMfaMethods.value = methods;
150
- isSigningIn.value = false;
151
- return authData;
152
- }
153
- setAuthData(authData);
154
- return authData;
155
- } catch (error) {
156
- throw error;
157
- } finally {
158
- isSigningIn.value = false;
159
- }
160
- };
161
- const signUp = async (userData) => {
162
- isSigningUp.value = true;
163
- try {
164
- throw new Error("Sign up not implemented - please integrate with auth SDK");
165
- } finally {
166
- isSigningUp.value = false;
167
- }
168
- };
169
- const signOut = async () => {
170
- isSigningOut.value = true;
171
- try {
172
- stopTokenRefreshTimer();
173
- currentUser.value = null;
174
- currentSession.value = null;
175
- mfaRequired.value = false;
176
- mfaSessionId.value = null;
177
- availableMfaMethods.value = [];
178
- if (typeof window !== "undefined") {
179
- localStorage.removeItem("strands_auth_session");
180
- localStorage.removeItem("strands_auth_user");
181
- }
182
- } finally {
183
- isSigningOut.value = false;
184
- }
185
- };
186
- const refreshToken = async () => {
187
- if (!currentSession.value?.refreshToken) {
188
- return false;
189
- }
190
- isRefreshingToken.value = true;
191
- try {
192
- const response = await fetch(getUrl("refresh"), {
193
- method: "POST",
194
- headers: {
195
- "Content-Type": "application/json"
196
- },
197
- body: JSON.stringify({
198
- refresh_token: currentSession.value.refreshToken
199
- })
200
- });
201
- if (!response.ok) {
202
- if (response.status === 401) {
203
- await signOut();
204
- return false;
205
- }
206
- throw new Error(`Token refresh failed: ${response.status} ${response.statusText}`);
207
- }
208
- const tokenData = await response.json();
209
- const newSession = {
210
- accessToken: tokenData.access_token,
211
- refreshToken: tokenData.refresh_token,
212
- expiresAt: new Date(Date.now() + 5 * 60 * 1e3),
213
- // 5 minutes from now
214
- userId: currentUser.value?.id
215
- };
216
- currentSession.value = newSession;
217
- if (typeof window !== "undefined") {
218
- localStorage.setItem("strands_auth_session", JSON.stringify(newSession));
219
- }
220
- startTokenRefreshTimer();
221
- return true;
222
- } catch (error) {
223
- await signOut();
224
- return false;
225
- }
226
- };
227
- const fetchProfile = async () => {
228
- if (!currentSession.value?.accessToken) {
229
- throw new Error("No access token available");
230
- }
231
- isLoadingProfile.value = true;
232
- try {
233
- const response = await fetch(getUrl("profile"), {
234
- method: "GET",
235
- headers: {
236
- "Content-Type": "application/json",
237
- "Authorization": `Bearer ${currentSession.value.accessToken}`
238
- }
239
- });
240
- if (!response.ok) {
241
- if (response.status === 401) {
242
- throw new Error("Authentication expired. Please sign in again.");
243
- } else {
244
- throw new Error(`Failed to fetch profile: ${response.status} ${response.statusText}`);
245
- }
246
- }
247
- const userData = await response.json();
248
- currentUser.value = {
249
- id: userData.id,
250
- email: userData.email,
251
- firstName: userData.first_name,
252
- lastName: userData.last_name,
253
- avatar: userData.avatar_url,
254
- mfaEnabled: userData.mfaEnabled || false,
255
- emailVerified: userData.email_verified,
256
- passwordUpdatedAt: userData.password_updated_at,
257
- settings: userData.settings || {},
258
- xp: userData.xp || 0,
259
- level: userData.level || 1,
260
- next_level_xp: userData.next_level_xp || 4,
261
- username: userData.username,
262
- usernameLastChangedAt: userData.username_last_changed_at,
263
- createdAt: userData.created_at,
264
- updatedAt: userData.updated_at || (/* @__PURE__ */ new Date()).toISOString()
265
- };
266
- if (typeof window !== "undefined") {
267
- localStorage.setItem("strands_auth_user", JSON.stringify(currentUser.value));
268
- }
269
- return currentUser.value;
270
- } finally {
271
- isLoadingProfile.value = false;
272
- }
273
- };
274
- const updateProfile = async (profileData) => {
275
- if (!currentSession.value?.accessToken) {
276
- throw new Error("No access token available");
277
- }
278
- isLoadingProfile.value = true;
279
- try {
280
- const response = await fetch(getUrl("profile"), {
281
- method: "POST",
282
- headers: {
283
- "Content-Type": "application/json",
284
- "Authorization": `Bearer ${currentSession.value.accessToken}`
285
- },
286
- body: JSON.stringify({
287
- first_name: profileData.firstName,
288
- last_name: profileData.lastName
289
- })
290
- });
291
- if (!response.ok) {
292
- if (response.status === 401) {
293
- throw new Error("Authentication expired. Please sign in again.");
294
- } else {
295
- throw new Error(`Profile update failed: ${response.status} ${response.statusText}`);
296
- }
297
- }
298
- const updatedUserData = await response.json();
299
- if (currentUser.value) {
300
- currentUser.value = {
301
- ...currentUser.value,
302
- // Update with API response data, preserving the API field names
303
- id: updatedUserData.id,
304
- email: updatedUserData.email,
305
- firstName: updatedUserData.first_name,
306
- lastName: updatedUserData.last_name,
307
- emailVerified: updatedUserData.email_verified,
308
- avatar: updatedUserData.avatar_url,
309
- mfaEnabled: updatedUserData.mfa_enabled,
310
- xp: updatedUserData.xp,
311
- level: updatedUserData.level,
312
- next_level_xp: updatedUserData.next_level_xp,
313
- username: updatedUserData.username,
314
- // This was missing and causing the bug!
315
- usernameLastChangedAt: updatedUserData.username_last_changed_at,
316
- createdAt: updatedUserData.created_at,
317
- updatedAt: updatedUserData.updated_at,
318
- settings: updatedUserData.settings,
319
- passwordUpdatedAt: updatedUserData.password_updated_at
320
- };
321
- if (typeof window !== "undefined") {
322
- localStorage.setItem("strands_auth_user", JSON.stringify(currentUser.value));
323
- }
324
- }
325
- return currentUser.value;
326
- } finally {
327
- isLoadingProfile.value = false;
328
- }
329
- };
330
- const updateUserSettings = async (settings) => {
331
- if (!currentSession.value?.accessToken) {
332
- throw new Error("No access token available");
333
- }
334
- isLoadingProfile.value = true;
335
- try {
336
- const response = await fetch(getUrl("settings"), {
337
- method: "POST",
338
- headers: {
339
- "Content-Type": "application/json",
340
- "Authorization": `Bearer ${currentSession.value.accessToken}`
341
- },
342
- body: JSON.stringify({
343
- settings
344
- })
345
- });
346
- if (!response.ok) {
347
- if (response.status === 401) {
348
- throw new Error("Authentication expired. Please sign in again.");
349
- } else {
350
- throw new Error(`Settings update failed: ${response.status} ${response.statusText}`);
351
- }
352
- }
353
- const updatedUserData = await response.json();
354
- if (currentUser.value) {
355
- currentUser.value = {
356
- ...currentUser.value,
357
- settings: updatedUserData.settings,
358
- updatedAt: updatedUserData.updated_at || (/* @__PURE__ */ new Date()).toISOString()
359
- };
360
- if (typeof window !== "undefined") {
361
- localStorage.setItem("strands_auth_user", JSON.stringify(currentUser.value));
362
- }
363
- }
364
- return currentUser.value;
365
- } finally {
366
- isLoadingProfile.value = false;
367
- }
368
- };
369
- const changeEmail = async (newEmail, password) => {
370
- if (!currentSession.value?.accessToken) {
371
- throw new Error("No access token available");
372
- }
373
- isLoadingProfile.value = true;
374
- try {
375
- const response = await fetch(getUrl("changeEmail"), {
376
- method: "POST",
377
- headers: {
378
- "Content-Type": "application/json",
379
- "Authorization": `Bearer ${currentSession.value.accessToken}`
380
- },
381
- body: JSON.stringify({
382
- new_email: newEmail,
383
- password
384
- })
385
- });
386
- if (!response.ok) {
387
- if (response.status === 401) {
388
- throw new Error("Authentication expired. Please sign in again.");
389
- } else {
390
- const errorData = await response.json().catch(() => ({}));
391
- throw new Error(errorData.message || `Email change failed: ${response.status} ${response.statusText}`);
392
- }
393
- }
394
- const result = await response.json();
395
- if (currentUser.value) {
396
- currentUser.value = {
397
- ...currentUser.value,
398
- email: newEmail,
399
- emailVerified: false,
400
- // Email needs to be verified again
401
- updatedAt: (/* @__PURE__ */ new Date()).toISOString()
402
- };
403
- if (typeof window !== "undefined") {
404
- localStorage.setItem("strands_auth_user", JSON.stringify(currentUser.value));
405
- }
406
- }
407
- return result;
408
- } finally {
409
- isLoadingProfile.value = false;
410
- }
411
- };
412
- const verifyMfa = async (deviceId, code, isBackupCode = false) => {
413
- if (!mfaSessionId.value) {
414
- throw new Error("No MFA session available");
415
- }
416
- isVerifyingMfa.value = true;
417
- try {
418
- const endpoint = isBackupCode ? getUrl("mfaBackupCodeVerify") : getUrl("mfaSigninVerify");
419
- const body = isBackupCode ? { mfa_session_id: mfaSessionId.value, backup_code: code } : { mfa_session_id: mfaSessionId.value, device_id: deviceId, code };
420
- const response = await fetch(endpoint, {
421
- method: "POST",
422
- headers: { "Content-Type": "application/json" },
423
- body: JSON.stringify(body)
424
- });
425
- if (!response.ok) {
426
- const errorText = await response.text();
427
- let errorMessage = "MFA verification failed";
428
- try {
429
- const errorData = JSON.parse(errorText);
430
- errorMessage = errorData.message || errorData.error || errorText;
431
- } catch {
432
- errorMessage = errorText || "MFA verification failed";
433
- }
434
- throw new Error(errorMessage);
435
- }
436
- const authData = await response.json();
437
- mfaRequired.value = false;
438
- mfaSessionId.value = null;
439
- availableMfaMethods.value = [];
440
- setAuthData(authData);
441
- return authData;
442
- } finally {
443
- isVerifyingMfa.value = false;
444
- }
445
- };
446
- const sendMfaEmailCode = async (deviceId) => {
447
- if (!mfaSessionId.value) {
448
- throw new Error("No MFA session available");
449
- }
450
- isSendingMfaEmail.value = true;
451
- try {
452
- const response = await fetch(getUrl("mfaSigninSendEmail"), {
453
- method: "POST",
454
- headers: { "Content-Type": "application/json" },
455
- body: JSON.stringify({
456
- mfa_session_id: mfaSessionId.value,
457
- device_id: deviceId
458
- })
459
- });
460
- if (!response.ok) {
461
- const errorText = await response.text();
462
- let errorMessage = "Failed to send MFA email code";
463
- try {
464
- const errorData = JSON.parse(errorText);
465
- errorMessage = errorData.message || errorData.error || errorText;
466
- } catch {
467
- errorMessage = errorText || "Failed to send MFA email code";
468
- }
469
- throw new Error(errorMessage);
470
- }
471
- const result = await response.json();
472
- return result;
473
- } finally {
474
- isSendingMfaEmail.value = false;
475
- }
476
- };
477
- const getMfaWebAuthnChallenge = async (deviceId) => {
478
- if (!mfaSessionId.value) {
479
- throw new Error("No MFA session available");
480
- }
481
- const response = await fetch(getUrl("mfaWebAuthnChallenge"), {
482
- method: "POST",
483
- headers: { "Content-Type": "application/json" },
484
- body: JSON.stringify({
485
- mfa_session_id: mfaSessionId.value,
486
- device_id: deviceId
487
- })
488
- });
489
- if (!response.ok) {
490
- const errorText = await response.text();
491
- let errorMessage = "Failed to get WebAuthn challenge";
492
- try {
493
- const errorData = JSON.parse(errorText);
494
- errorMessage = errorData.message || errorData.error || errorText;
495
- } catch {
496
- errorMessage = errorText || errorMessage;
497
- }
498
- throw new Error(errorMessage);
499
- }
500
- return response.json();
501
- };
502
- const setAuthData = (authResponse) => {
503
- try {
504
- if (authResponse.user) {
505
- currentUser.value = authResponse.user;
506
- }
507
- const session = {
508
- accessToken: authResponse.access_token,
509
- refreshToken: authResponse.refresh_token,
510
- expiresAt: new Date(Date.now() + 5 * 60 * 1e3),
511
- // 5 minutes from now (matching API token expiry)
512
- userId: currentUser.value?.id || authResponse.user?.id
513
- };
514
- currentSession.value = session;
515
- if (typeof window !== "undefined") {
516
- localStorage.setItem("strands_auth_session", JSON.stringify(session));
517
- if (currentUser.value) {
518
- localStorage.setItem("strands_auth_user", JSON.stringify(currentUser.value));
519
- }
520
- }
521
- startTokenRefreshTimer();
522
- } catch (error) {
523
- console.error("Error setting auth data:", error);
524
- }
525
- };
526
- const startTokenRefreshTimer = () => {
527
- if (refreshTimer) {
528
- clearTimeout(refreshTimer);
529
- }
530
- if (!currentSession.value) return;
531
- const now = /* @__PURE__ */ new Date();
532
- const expiresAt = currentSession.value.expiresAt;
533
- const timeUntilRefresh = expiresAt.getTime() - now.getTime() - 1 * 60 * 1e3;
534
- if (timeUntilRefresh <= 0) {
535
- refreshToken();
536
- return;
537
- }
538
- refreshTimer = setTimeout(async () => {
539
- const success = await refreshToken();
540
- if (success) {
541
- startTokenRefreshTimer();
542
- }
543
- }, timeUntilRefresh);
544
- };
545
- const stopTokenRefreshTimer = () => {
546
- if (refreshTimer) {
547
- clearTimeout(refreshTimer);
548
- refreshTimer = null;
549
- }
550
- };
551
- const initialize = async () => {
552
- if (isInitialized.value) return;
553
- isInitializing.value = true;
554
- try {
555
- if (typeof window !== "undefined") {
556
- const storedSession = localStorage.getItem("strands_auth_session");
557
- const storedUser = localStorage.getItem("strands_auth_user");
558
- if (storedSession && storedUser) {
559
- try {
560
- const session = JSON.parse(storedSession);
561
- const user = JSON.parse(storedUser);
562
- session.expiresAt = new Date(session.expiresAt);
563
- if (session.expiresAt > /* @__PURE__ */ new Date()) {
564
- currentSession.value = session;
565
- currentUser.value = user;
566
- startTokenRefreshTimer();
567
- } else {
568
- localStorage.removeItem("strands_auth_session");
569
- localStorage.removeItem("strands_auth_user");
570
- }
571
- } catch (error) {
572
- localStorage.removeItem("strands_auth_session");
573
- localStorage.removeItem("strands_auth_user");
574
- }
575
- }
576
- }
577
- isInitialized.value = true;
578
- await new Promise((resolve) => setTimeout(resolve, 50));
579
- } catch (error) {
580
- } finally {
581
- isInitializing.value = false;
582
- }
583
- };
584
- const changeUsername = async (newUsername) => {
585
- if (!currentSession.value?.accessToken) {
586
- throw new Error("No access token available");
587
- }
588
- isLoadingProfile.value = true;
589
- try {
590
- const response = await fetch(getUrl("changeUsername"), {
591
- method: "POST",
592
- headers: {
593
- "Content-Type": "application/json",
594
- "Authorization": `Bearer ${currentSession.value.accessToken}`
595
- },
596
- body: JSON.stringify({
597
- username: newUsername
598
- })
599
- });
600
- if (!response.ok) {
601
- const errorData = await response.json().catch(() => ({}));
602
- if (response.status === 409) {
603
- throw new Error("Username is already taken");
604
- } else if (errorData.cooldown_end) {
605
- 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()}`);
606
- }
607
- throw new Error(errorData.message || `Username change failed: ${response.status} ${response.statusText}`);
608
- }
609
- const result = await response.json();
610
- if (currentUser.value) {
611
- currentUser.value = {
612
- ...currentUser.value,
613
- username: newUsername,
614
- usernameLastChangedAt: (/* @__PURE__ */ new Date()).toISOString(),
615
- updatedAt: (/* @__PURE__ */ new Date()).toISOString()
616
- };
617
- if (typeof window !== "undefined") {
618
- localStorage.setItem("strands_auth_user", JSON.stringify(currentUser.value));
619
- }
620
- }
621
- return result;
622
- } finally {
623
- isLoadingProfile.value = false;
624
- }
625
- };
626
- const getUsernameCooldown = async () => {
627
- if (!currentSession.value?.accessToken) {
628
- throw new Error("No access token available");
629
- }
630
- const response = await fetch(getUrl("usernameCooldown"), {
631
- method: "GET",
632
- headers: {
633
- "Authorization": `Bearer ${currentSession.value.accessToken}`
634
- }
635
- });
636
- if (!response.ok) {
637
- throw new Error(`Failed to get username cooldown: ${response.status} ${response.statusText}`);
638
- }
639
- return response.json();
640
- };
641
- const checkUsernameAvailability = async (username) => {
642
- const url = getUrl("checkUsernameAvailability").replace("{username}", encodeURIComponent(username));
643
- const response = await fetch(url, {
644
- method: "GET",
645
- headers: {
646
- "Content-Type": "application/json"
647
- }
648
- });
649
- if (!response.ok) {
650
- throw new Error(`Failed to check username availability: ${response.status} ${response.statusText}`);
651
- }
652
- return response.json();
653
- };
654
- const getUserSessions = async () => {
655
- const response = await fetch(getUrl("sessions"), {
656
- method: "GET",
657
- headers: getAuthHeaders()
658
- });
659
- if (!response.ok) {
660
- throw new Error(`Failed to get user sessions: ${response.status} ${response.statusText}`);
661
- }
662
- return response.json();
663
- };
664
- const getSessionStats = async () => {
665
- const response = await fetch(getUrl("sessionsStats"), {
666
- method: "GET",
667
- headers: getAuthHeaders()
668
- });
669
- if (!response.ok) {
670
- throw new Error(`Failed to get session stats: ${response.status} ${response.statusText}`);
671
- }
672
- return response.json();
673
- };
674
- const revokeSession = async (sessionId) => {
675
- const url = getUrl("sessionRevoke").replace("{session_id}", encodeURIComponent(sessionId));
676
- const response = await fetch(url, {
677
- method: "POST",
678
- headers: getAuthHeaders()
679
- });
680
- if (!response.ok) {
681
- throw new Error(`Failed to revoke session: ${response.status} ${response.statusText}`);
682
- }
683
- return response.status === 200;
684
- };
685
- const revokeAllOtherSessions = async () => {
686
- const response = await fetch(getUrl("sessionsRevokeAll"), {
687
- method: "POST",
688
- headers: getAuthHeaders()
689
- });
690
- if (!response.ok) {
691
- throw new Error(`Failed to revoke all other sessions: ${response.status} ${response.statusText}`);
692
- }
693
- return response.status === 200;
694
- };
695
- if (!isInitialized.value) {
696
- initialize();
697
- }
698
- return {
699
- // State
700
- user: vue.computed(() => currentUser.value),
701
- currentUser: vue.computed(() => currentUser.value),
702
- currentSession: vue.computed(() => currentSession.value),
703
- isAuthenticated,
704
- isLoading: vue.computed(() => isLoading.value || !isInitialized.value),
705
- loading: vue.computed(() => loading.value),
706
- loadingMessage,
707
- // Specific loading states
708
- isInitializing,
709
- isSigningIn,
710
- isSigningUp,
711
- isSigningOut,
712
- isRefreshingToken,
713
- isSendingMfaEmail,
714
- isVerifyingMfa,
715
- // MFA State
716
- mfaRequired: vue.computed(() => mfaRequired.value),
717
- mfaSessionId: vue.computed(() => mfaSessionId.value),
718
- availableMfaMethods: vue.computed(() => availableMfaMethods.value),
719
- // Methods
720
- signIn,
721
- signUp,
722
- signOut,
723
- refreshToken,
724
- fetchProfile,
725
- updateProfile,
726
- updateUserSettings,
727
- changeEmail,
728
- changeUsername,
729
- getUsernameCooldown,
730
- checkUsernameAvailability,
731
- // Session management
732
- getUserSessions,
733
- getSessionStats,
734
- revokeSession,
735
- revokeAllOtherSessions,
736
- initialize,
737
- setAuthData,
738
- verifyMfa,
739
- sendMfaEmailCode,
740
- getMfaWebAuthnChallenge,
741
- registerHardwareKey,
742
- completeHardwareKeyRegistration,
743
- // Token management
744
- startTokenRefreshTimer,
745
- stopTokenRefreshTimer,
746
- // Force re-initialization (useful for testing or navigation)
747
- forceReInit: () => {
748
- isInitialized.value = false;
749
- isInitializing.value = true;
750
- initialize();
751
- }
752
- };
753
- }
754
- exports.useStrandsAuth = useStrandsAuth;
755
- //# sourceMappingURL=useStrandsAuth-JfbGH2c-.cjs.map