@classic-homes/auth 0.1.23 → 0.1.24

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.
@@ -1,4 +1,25 @@
1
+ var __defProp = Object.defineProperty;
2
+ var __getOwnPropNames = Object.getOwnPropertyNames;
3
+ var __esm = (fn, res) => function __init() {
4
+ return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
5
+ };
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+
1
11
  // src/core/config.ts
12
+ function getConfig() {
13
+ if (!config) {
14
+ throw new Error(
15
+ '@classic-homes/auth not initialized. Call initAuth({ baseUrl: "..." }) before using auth services.'
16
+ );
17
+ }
18
+ return config;
19
+ }
20
+ function isInitialized() {
21
+ return config !== null;
22
+ }
2
23
  function getDefaultStorage() {
3
24
  if (typeof window !== "undefined" && window.localStorage) {
4
25
  return {
@@ -15,6 +36,20 @@ function getDefaultStorage() {
15
36
  }
16
37
  };
17
38
  }
39
+ function getStorage() {
40
+ const cfg = getConfig();
41
+ return cfg.storage ?? getDefaultStorage();
42
+ }
43
+ function getFetch() {
44
+ const cfg = getConfig();
45
+ return cfg.fetch ?? fetch;
46
+ }
47
+ var config;
48
+ var init_config = __esm({
49
+ "src/core/config.ts"() {
50
+ config = null;
51
+ }
52
+ });
18
53
 
19
54
  // src/core/jwt.ts
20
55
  function decodeJWT(token) {
@@ -30,13 +65,592 @@ function decodeJWT(token) {
30
65
  return null;
31
66
  }
32
67
  }
68
+ var init_jwt = __esm({
69
+ "src/core/jwt.ts"() {
70
+ }
71
+ });
72
+
73
+ // src/core/client.ts
74
+ function subscribeTokenRefresh(cb) {
75
+ refreshSubscribers.push(cb);
76
+ }
77
+ function onTokenRefreshed(token) {
78
+ refreshSubscribers.forEach((cb) => cb(token));
79
+ refreshSubscribers = [];
80
+ }
81
+ function getAccessToken() {
82
+ const config2 = getConfig();
83
+ const storage = getStorage();
84
+ const authData = storage.getItem(config2.storageKey ?? "classic_auth");
85
+ if (!authData) return null;
86
+ try {
87
+ const parsed = JSON.parse(authData);
88
+ return parsed.accessToken ?? null;
89
+ } catch {
90
+ return null;
91
+ }
92
+ }
93
+ function getRefreshToken() {
94
+ const config2 = getConfig();
95
+ const storage = getStorage();
96
+ const authData = storage.getItem(config2.storageKey ?? "classic_auth");
97
+ if (!authData) return null;
98
+ try {
99
+ const parsed = JSON.parse(authData);
100
+ return parsed.refreshToken ?? null;
101
+ } catch {
102
+ return null;
103
+ }
104
+ }
105
+ function getSessionToken() {
106
+ const storage = getStorage();
107
+ return storage.getItem("sessionToken");
108
+ }
109
+ function updateStoredTokens(accessToken, refreshToken) {
110
+ const config2 = getConfig();
111
+ const storage = getStorage();
112
+ const storageKey = config2.storageKey ?? "classic_auth";
113
+ const authData = storage.getItem(storageKey);
114
+ let parsed = {};
115
+ if (authData) {
116
+ try {
117
+ parsed = JSON.parse(authData);
118
+ } catch {
119
+ }
120
+ }
121
+ parsed.accessToken = accessToken;
122
+ parsed.refreshToken = refreshToken;
123
+ storage.setItem(storageKey, JSON.stringify(parsed));
124
+ Promise.resolve().then(() => (init_auth_svelte(), auth_svelte_exports)).then(({ authStore: authStore2 }) => {
125
+ authStore2.updateTokens(accessToken, refreshToken);
126
+ }).catch(() => {
127
+ });
128
+ config2.onTokenRefresh?.({ accessToken, refreshToken });
129
+ }
130
+ function clearStoredAuth() {
131
+ const config2 = getConfig();
132
+ const storage = getStorage();
133
+ storage.removeItem(config2.storageKey ?? "classic_auth");
134
+ storage.removeItem("sessionToken");
135
+ }
136
+ async function refreshAccessToken() {
137
+ const refreshToken = getRefreshToken();
138
+ const config2 = getConfig();
139
+ const fetchFn = getFetch();
140
+ if (!refreshToken) {
141
+ return false;
142
+ }
143
+ try {
144
+ const response = await fetchFn(`${config2.baseUrl}/auth/refresh`, {
145
+ method: "POST",
146
+ headers: {
147
+ "Content-Type": "application/json"
148
+ },
149
+ body: JSON.stringify({ refreshToken })
150
+ });
151
+ if (response.ok) {
152
+ const apiResponse = await response.json();
153
+ const data = apiResponse.data;
154
+ const tokens = data && typeof data === "object" && "data" in data ? data.data : data;
155
+ if (tokens?.accessToken && tokens?.refreshToken) {
156
+ updateStoredTokens(tokens.accessToken, tokens.refreshToken);
157
+ onTokenRefreshed(tokens.accessToken);
158
+ return true;
159
+ }
160
+ }
161
+ } catch (error) {
162
+ config2.onAuthError?.(error instanceof Error ? error : new Error("Token refresh failed"));
163
+ }
164
+ return false;
165
+ }
166
+ function extractData(response) {
167
+ if (response && typeof response === "object" && "data" in response) {
168
+ const dataField = response.data;
169
+ if (dataField && typeof dataField === "object" && "data" in dataField) {
170
+ return dataField.data;
171
+ }
172
+ if (dataField !== void 0) {
173
+ return dataField;
174
+ }
175
+ }
176
+ return response;
177
+ }
178
+ async function apiRequest(endpoint, options = {}) {
179
+ const { authenticated = false, customFetch, body, ...fetchOptions } = options;
180
+ const config2 = getConfig();
181
+ const fetchFn = customFetch ?? getFetch();
182
+ const url = endpoint.startsWith("http") ? endpoint : `${config2.baseUrl}${endpoint}`;
183
+ const headers = {
184
+ "Content-Type": "application/json",
185
+ ...fetchOptions.headers
186
+ };
187
+ if (authenticated) {
188
+ const accessToken = getAccessToken();
189
+ const sessionToken = getSessionToken();
190
+ if (accessToken) {
191
+ headers["Authorization"] = `Bearer ${accessToken}`;
192
+ }
193
+ if (sessionToken) {
194
+ headers["X-Session-Token"] = sessionToken;
195
+ }
196
+ }
197
+ try {
198
+ const response = await fetchFn(url, {
199
+ ...fetchOptions,
200
+ headers,
201
+ body: body ? JSON.stringify(body) : void 0
202
+ });
203
+ if (response.status === 401 && authenticated && typeof window !== "undefined") {
204
+ if (!isRefreshing) {
205
+ isRefreshing = true;
206
+ const refreshed = await refreshAccessToken();
207
+ isRefreshing = false;
208
+ if (refreshed) {
209
+ return apiRequest(endpoint, options);
210
+ } else {
211
+ clearStoredAuth();
212
+ config2.onLogout?.();
213
+ throw new Error("Authentication failed. Please sign in again.");
214
+ }
215
+ } else {
216
+ return new Promise((resolve, reject) => {
217
+ subscribeTokenRefresh(() => {
218
+ apiRequest(endpoint, options).then(resolve).catch(reject);
219
+ });
220
+ });
221
+ }
222
+ }
223
+ const data = await response.json();
224
+ if (!response.ok) {
225
+ const dataObj = data;
226
+ const errorMessage = data.error?.message || (typeof dataObj.message === "string" ? dataObj.message : void 0) || data.meta?.message || (typeof dataObj.detail === "string" ? dataObj.detail : void 0) || "Request failed";
227
+ const error = new Error(errorMessage);
228
+ config2.onAuthError?.(error);
229
+ throw error;
230
+ }
231
+ return data;
232
+ } catch (error) {
233
+ if (error instanceof Error) {
234
+ throw error;
235
+ }
236
+ throw new Error("API request failed");
237
+ }
238
+ }
239
+ var isRefreshing, refreshSubscribers, api;
240
+ var init_client = __esm({
241
+ "src/core/client.ts"() {
242
+ init_config();
243
+ isRefreshing = false;
244
+ refreshSubscribers = [];
245
+ api = {
246
+ get: (endpoint, authenticated = false, customFetch) => apiRequest(endpoint, { method: "GET", authenticated, customFetch }),
247
+ post: (endpoint, body, authenticated = false, customFetch) => apiRequest(endpoint, {
248
+ method: "POST",
249
+ body,
250
+ authenticated,
251
+ customFetch
252
+ }),
253
+ put: (endpoint, body, authenticated = false, customFetch) => apiRequest(endpoint, {
254
+ method: "PUT",
255
+ body,
256
+ authenticated,
257
+ customFetch
258
+ }),
259
+ patch: (endpoint, body, authenticated = false, customFetch) => apiRequest(endpoint, {
260
+ method: "PATCH",
261
+ body,
262
+ authenticated,
263
+ customFetch
264
+ }),
265
+ delete: (endpoint, authenticated = false, customFetch, body) => apiRequest(endpoint, {
266
+ method: "DELETE",
267
+ body,
268
+ authenticated,
269
+ customFetch
270
+ })
271
+ };
272
+ }
273
+ });
274
+
275
+ // src/core/api.ts
276
+ var authApi;
277
+ var init_api = __esm({
278
+ "src/core/api.ts"() {
279
+ init_client();
280
+ init_config();
281
+ authApi = {
282
+ // ============================================================================
283
+ // Authentication
284
+ // ============================================================================
285
+ /**
286
+ * Login with username and password.
287
+ */
288
+ async login(credentials) {
289
+ const response = await api.post("/auth/login", credentials);
290
+ return extractData(response);
291
+ },
292
+ /**
293
+ * Logout the current user.
294
+ * Returns SSO logout URL if applicable for SSO users.
295
+ */
296
+ async logout() {
297
+ try {
298
+ const response = await api.post("/auth/logout", {}, true);
299
+ return extractData(response);
300
+ } catch {
301
+ return { success: true };
302
+ }
303
+ },
304
+ /**
305
+ * Register a new user.
306
+ */
307
+ async register(data) {
308
+ const response = await api.post("/auth/register", data);
309
+ return extractData(response);
310
+ },
311
+ /**
312
+ * Request a password reset email.
313
+ */
314
+ async forgotPassword(email) {
315
+ await api.post("/auth/forgot-password", { email });
316
+ },
317
+ /**
318
+ * Reset password with a token.
319
+ */
320
+ async resetPassword(token, newPassword) {
321
+ await api.post("/auth/reset-password", { token, newPassword });
322
+ },
323
+ /**
324
+ * Refresh the access token.
325
+ */
326
+ async refreshToken(refreshToken) {
327
+ const response = await api.post("/auth/refresh", { refreshToken });
328
+ return extractData(response);
329
+ },
330
+ /**
331
+ * Initiate SSO login by redirecting to the SSO provider.
332
+ * @param options.callbackUrl - The URL where the SSO provider should redirect after auth
333
+ * @param options.redirectUrl - The final URL to redirect to after processing the callback
334
+ */
335
+ initiateSSOLogin(options) {
336
+ if (typeof window === "undefined") return;
337
+ const config2 = getConfig();
338
+ const authorizeUrl = config2.sso?.authorizeUrl ?? `${config2.baseUrl}/auth/sso/authorize`;
339
+ const params = new URLSearchParams();
340
+ if (options?.callbackUrl) {
341
+ params.set("callback", options.callbackUrl);
342
+ }
343
+ if (options?.redirectUrl) {
344
+ params.set("redirect", options.redirectUrl);
345
+ }
346
+ const url = params.toString() ? `${authorizeUrl}?${params}` : authorizeUrl;
347
+ window.location.href = url;
348
+ },
349
+ // ============================================================================
350
+ // Profile
351
+ // ============================================================================
352
+ /**
353
+ * Get the current user's profile.
354
+ */
355
+ async getProfile(customFetch) {
356
+ const response = await api.get("/auth/profile", true, customFetch);
357
+ return response;
358
+ },
359
+ /**
360
+ * Update the current user's profile.
361
+ */
362
+ async updateProfile(data) {
363
+ const response = await api.put("/auth/profile", data, true);
364
+ return extractData(response);
365
+ },
366
+ /**
367
+ * Change the current user's password.
368
+ */
369
+ async changePassword(data) {
370
+ await api.put("/auth/change-password", data, true);
371
+ },
372
+ // ============================================================================
373
+ // Email Verification
374
+ // ============================================================================
375
+ /**
376
+ * Resend email verification.
377
+ */
378
+ async resendVerification() {
379
+ await api.post("/auth/resend-verification", {}, true);
380
+ },
381
+ /**
382
+ * Verify email with a token.
383
+ */
384
+ async verifyEmail(token) {
385
+ const response = await api.post("/auth/verify-email", {
386
+ token
387
+ });
388
+ return extractData(response);
389
+ },
390
+ // ============================================================================
391
+ // Session Management
392
+ // ============================================================================
393
+ /**
394
+ * Get all active sessions.
395
+ */
396
+ async getSessions(customFetch) {
397
+ const response = await api.get(
398
+ "/auth/sessions",
399
+ true,
400
+ customFetch
401
+ );
402
+ return response;
403
+ },
404
+ /**
405
+ * Revoke a specific session.
406
+ */
407
+ async revokeSession(sessionId) {
408
+ await api.delete(`/auth/sessions/${sessionId}`, true);
409
+ },
410
+ /**
411
+ * Revoke all sessions except the current one.
412
+ */
413
+ async revokeAllSessions() {
414
+ await api.delete("/auth/sessions", true);
415
+ },
416
+ // ============================================================================
417
+ // API Key Management
418
+ // ============================================================================
419
+ /**
420
+ * Get all API keys.
421
+ */
422
+ async getApiKeys(customFetch) {
423
+ const response = await api.get("/auth/api-keys", true, customFetch);
424
+ return response;
425
+ },
426
+ /**
427
+ * Create a new API key.
428
+ */
429
+ async createApiKey(data) {
430
+ const response = await api.post("/auth/api-keys", data, true);
431
+ return extractData(response);
432
+ },
433
+ /**
434
+ * Revoke an API key.
435
+ */
436
+ async revokeApiKey(keyId) {
437
+ await api.delete(`/auth/api-keys/${keyId}`, true);
438
+ },
439
+ /**
440
+ * Update an API key's name.
441
+ */
442
+ async updateApiKey(keyId, data) {
443
+ await api.put(`/auth/api-keys/${keyId}`, data, true);
444
+ },
445
+ // ============================================================================
446
+ // MFA Management
447
+ // ============================================================================
448
+ /**
449
+ * Get MFA status for the current user.
450
+ */
451
+ async getMFAStatus() {
452
+ const response = await api.get("/auth/mfa/status", true);
453
+ return response;
454
+ },
455
+ /**
456
+ * Setup MFA (get QR code and backup codes).
457
+ */
458
+ async setupMFA() {
459
+ const response = await api.post("/auth/mfa-setup", {}, true);
460
+ return extractData(response);
461
+ },
462
+ /**
463
+ * Verify MFA setup with a code.
464
+ */
465
+ async verifyMFASetup(code) {
466
+ await api.post("/auth/mfa/verify", { code }, true);
467
+ },
468
+ /**
469
+ * Disable MFA.
470
+ */
471
+ async disableMFA(password) {
472
+ await api.delete("/auth/mfa", true, void 0, { password });
473
+ },
474
+ /**
475
+ * Regenerate MFA backup codes.
476
+ */
477
+ async regenerateBackupCodes(password) {
478
+ const response = await api.post(
479
+ "/auth/mfa/regenerate-backup-codes",
480
+ { password },
481
+ true
482
+ );
483
+ return extractData(response);
484
+ },
485
+ /**
486
+ * Verify MFA challenge during login.
487
+ */
488
+ async verifyMFAChallenge(data) {
489
+ const config2 = getConfig();
490
+ const fetchFn = config2.fetch ?? fetch;
491
+ const requestBody = {
492
+ code: data.code,
493
+ type: data.method === "backup" ? "backup" : "totp",
494
+ trustDevice: data.trustDevice
495
+ };
496
+ const response = await fetchFn(`${config2.baseUrl}/auth/mfa/challenge`, {
497
+ method: "POST",
498
+ headers: {
499
+ "Content-Type": "application/json",
500
+ Authorization: `Bearer ${data.mfaToken}`
501
+ },
502
+ body: JSON.stringify(requestBody)
503
+ });
504
+ if (!response.ok) {
505
+ const error = await response.json().catch(() => ({ message: "Verification failed" }));
506
+ throw new Error(error.error?.message || error.message || "Invalid verification code");
507
+ }
508
+ const result = await response.json();
509
+ return extractData(result);
510
+ },
511
+ // ============================================================================
512
+ // Device Management
513
+ // ============================================================================
514
+ /**
515
+ * Get all devices.
516
+ */
517
+ async getDevices(customFetch) {
518
+ const response = await api.get(
519
+ "/auth/devices",
520
+ true,
521
+ customFetch
522
+ );
523
+ return response;
524
+ },
525
+ /**
526
+ * Trust a device.
527
+ */
528
+ async trustDevice(deviceId) {
529
+ await api.put(`/auth/devices/${deviceId}/trust`, {}, true);
530
+ },
531
+ /**
532
+ * Revoke device trust.
533
+ */
534
+ async revokeDevice(deviceId) {
535
+ await api.delete(`/auth/devices/${deviceId}/revoke`, true);
536
+ },
537
+ /**
538
+ * Remove a device completely.
539
+ */
540
+ async removeDevice(deviceId) {
541
+ await api.delete(`/auth/devices/${deviceId}`, true);
542
+ },
543
+ /**
544
+ * Approve a device with a token.
545
+ */
546
+ async approveDevice(token) {
547
+ const response = await api.post("/auth/device/approve", {
548
+ token
549
+ });
550
+ return extractData(response);
551
+ },
552
+ /**
553
+ * Block a device with a token.
554
+ */
555
+ async blockDevice(token) {
556
+ const response = await api.post("/auth/device/block", {
557
+ token
558
+ });
559
+ return extractData(response);
560
+ },
561
+ // ============================================================================
562
+ // Preferences
563
+ // ============================================================================
564
+ /**
565
+ * Get user preferences.
566
+ */
567
+ async getPreferences(customFetch) {
568
+ const response = await api.get(
569
+ "/auth/preferences",
570
+ true,
571
+ customFetch
572
+ );
573
+ if (response && typeof response === "object" && "preferences" in response) {
574
+ return response.preferences;
575
+ }
576
+ return response ?? {};
577
+ },
578
+ /**
579
+ * Update user preferences.
580
+ */
581
+ async updatePreferences(data) {
582
+ await api.put("/auth/preferences", data, true);
583
+ },
584
+ // ============================================================================
585
+ // SSO / Linked Accounts
586
+ // ============================================================================
587
+ /**
588
+ * Get SSO linked accounts.
589
+ */
590
+ async getSSOAccounts(customFetch) {
591
+ const response = await api.get(
592
+ "/auth/sso/accounts",
593
+ true,
594
+ customFetch
595
+ );
596
+ if (response && typeof response === "object" && "accounts" in response) {
597
+ return response.accounts;
598
+ }
599
+ return Array.isArray(response) ? response : [];
600
+ },
601
+ /**
602
+ * Unlink an SSO account.
603
+ */
604
+ async unlinkSSOAccount(provider, password) {
605
+ await api.delete("/auth/sso/unlink", true, void 0, { provider, password });
606
+ },
607
+ /**
608
+ * Link an SSO account (redirects to SSO provider).
609
+ */
610
+ async linkSSOAccount(provider = "authentik") {
611
+ if (typeof window === "undefined") return;
612
+ const accessToken = getAccessToken();
613
+ if (!accessToken) {
614
+ throw new Error("Not authenticated");
615
+ }
616
+ const config2 = getConfig();
617
+ const params = new URLSearchParams({
618
+ token: accessToken,
619
+ provider
620
+ });
621
+ window.location.href = `${config2.baseUrl}/auth/sso/link?${params.toString()}`;
622
+ },
623
+ // ============================================================================
624
+ // Security Events
625
+ // ============================================================================
626
+ /**
627
+ * Get security event history.
628
+ */
629
+ async getSecurityEvents(params, customFetch) {
630
+ const queryParams = new URLSearchParams();
631
+ if (params?.page) queryParams.append("page", params.page.toString());
632
+ if (params?.limit) queryParams.append("limit", params.limit.toString());
633
+ if (params?.type) queryParams.append("type", params.type);
634
+ const response = await api.get(`/auth/security/events?${queryParams.toString()}`, true, customFetch);
635
+ return extractData(response);
636
+ }
637
+ };
638
+ }
639
+ });
33
640
 
34
641
  // src/svelte/stores/auth.svelte.ts
642
+ var auth_svelte_exports = {};
643
+ __export(auth_svelte_exports, {
644
+ authActions: () => authActions,
645
+ authStore: () => authStore,
646
+ currentUser: () => currentUser,
647
+ isAuthenticated: () => isAuthenticated
648
+ });
35
649
  function getStorageKey() {
36
- return "classic_auth";
650
+ return isInitialized() ? getConfig().storageKey ?? "classic_auth" : "classic_auth";
37
651
  }
38
652
  function getStorageAdapter() {
39
- return getDefaultStorage();
653
+ return isInitialized() ? getStorage() : getDefaultStorage();
40
654
  }
41
655
  function loadAuthFromStorage() {
42
656
  try {
@@ -78,204 +692,237 @@ function saveAuthToStorage(state) {
78
692
  } catch {
79
693
  }
80
694
  }
81
- var AuthStore = class {
82
- constructor() {
83
- this.subscribers = /* @__PURE__ */ new Set();
84
- this.state = loadAuthFromStorage();
85
- }
86
- /**
87
- * Subscribe to state changes (Svelte store contract).
88
- */
89
- subscribe(subscriber) {
90
- this.subscribers.add(subscriber);
91
- subscriber(this.state);
92
- return () => this.subscribers.delete(subscriber);
93
- }
94
- notify() {
95
- this.subscribers.forEach((sub) => sub(this.state));
96
- }
97
- // Getters for direct access
98
- get accessToken() {
99
- return this.state.accessToken;
100
- }
101
- get refreshToken() {
102
- return this.state.refreshToken;
103
- }
104
- get user() {
105
- return this.state.user;
106
- }
107
- get isAuthenticated() {
108
- return this.state.isAuthenticated;
109
- }
110
- /**
111
- * Get the current auth state snapshot.
112
- */
113
- getState() {
114
- return { ...this.state };
115
- }
116
- /**
117
- * Set auth data after successful login.
118
- */
119
- setAuth(accessToken, refreshToken, user, sessionToken) {
120
- const jwtPayload = decodeJWT(accessToken);
121
- const userWithPermissions = {
122
- ...user,
123
- permissions: user.permissions || jwtPayload?.permissions || [],
124
- roles: user.roles || jwtPayload?.roles || (user.role ? [user.role] : [])
125
- };
126
- this.state = {
127
- accessToken,
128
- refreshToken,
129
- user: userWithPermissions,
130
- isAuthenticated: true
695
+ var AuthStore, authStore, authActions, isAuthenticated, currentUser;
696
+ var init_auth_svelte = __esm({
697
+ "src/svelte/stores/auth.svelte.ts"() {
698
+ init_config();
699
+ init_jwt();
700
+ init_api();
701
+ AuthStore = class {
702
+ constructor() {
703
+ this.subscribers = /* @__PURE__ */ new Set();
704
+ this.state = loadAuthFromStorage();
705
+ }
706
+ /**
707
+ * Subscribe to state changes (Svelte store contract).
708
+ */
709
+ subscribe(subscriber) {
710
+ this.subscribers.add(subscriber);
711
+ subscriber(this.state);
712
+ return () => this.subscribers.delete(subscriber);
713
+ }
714
+ notify() {
715
+ this.subscribers.forEach((sub) => sub(this.state));
716
+ }
717
+ // Getters for direct access
718
+ get accessToken() {
719
+ return this.state.accessToken;
720
+ }
721
+ get refreshToken() {
722
+ return this.state.refreshToken;
723
+ }
724
+ get user() {
725
+ return this.state.user;
726
+ }
727
+ get isAuthenticated() {
728
+ return this.state.isAuthenticated;
729
+ }
730
+ /**
731
+ * Get the current auth state snapshot.
732
+ */
733
+ getState() {
734
+ return { ...this.state };
735
+ }
736
+ /**
737
+ * Set auth data after successful login.
738
+ */
739
+ setAuth(accessToken, refreshToken, user, sessionToken) {
740
+ const jwtPayload = decodeJWT(accessToken);
741
+ const userWithPermissions = {
742
+ ...user,
743
+ permissions: user.permissions || jwtPayload?.permissions || [],
744
+ roles: user.roles || jwtPayload?.roles || (user.role ? [user.role] : [])
745
+ };
746
+ this.state = {
747
+ accessToken,
748
+ refreshToken,
749
+ user: userWithPermissions,
750
+ isAuthenticated: true
751
+ };
752
+ saveAuthToStorage(this.state);
753
+ if (sessionToken && typeof window !== "undefined") {
754
+ getStorageAdapter().setItem("sessionToken", sessionToken);
755
+ }
756
+ if (typeof window !== "undefined") {
757
+ window.dispatchEvent(
758
+ new CustomEvent("auth:login", {
759
+ detail: { user: userWithPermissions }
760
+ })
761
+ );
762
+ }
763
+ this.notify();
764
+ }
765
+ /**
766
+ * Update tokens (e.g., after refresh).
767
+ */
768
+ updateTokens(accessToken, refreshToken) {
769
+ const jwtPayload = decodeJWT(accessToken);
770
+ const updatedUser = this.state.user ? {
771
+ ...this.state.user,
772
+ permissions: jwtPayload?.permissions || this.state.user.permissions || [],
773
+ roles: jwtPayload?.roles || this.state.user.roles || (this.state.user.role ? [this.state.user.role] : [])
774
+ } : null;
775
+ this.state = {
776
+ ...this.state,
777
+ accessToken,
778
+ refreshToken,
779
+ user: updatedUser
780
+ };
781
+ saveAuthToStorage(this.state);
782
+ if (typeof window !== "undefined") {
783
+ window.dispatchEvent(new CustomEvent("auth:token-refresh"));
784
+ }
785
+ this.notify();
786
+ }
787
+ /**
788
+ * Update user data (e.g., after profile update).
789
+ */
790
+ updateUser(user) {
791
+ const jwtPayload = this.state.accessToken ? decodeJWT(this.state.accessToken) : null;
792
+ const updatedUser = {
793
+ ...user,
794
+ permissions: user.permissions || jwtPayload?.permissions || [],
795
+ roles: user.roles || jwtPayload?.roles || (user.role ? [user.role] : [])
796
+ };
797
+ this.state = {
798
+ ...this.state,
799
+ user: updatedUser
800
+ };
801
+ saveAuthToStorage(this.state);
802
+ if (typeof window !== "undefined") {
803
+ window.dispatchEvent(
804
+ new CustomEvent("auth:profile-update", {
805
+ detail: { user: updatedUser }
806
+ })
807
+ );
808
+ }
809
+ this.notify();
810
+ }
811
+ /**
812
+ * Clear auth state (logout).
813
+ */
814
+ logout() {
815
+ this.state = {
816
+ accessToken: null,
817
+ refreshToken: null,
818
+ user: null,
819
+ isAuthenticated: false
820
+ };
821
+ const storage = getStorageAdapter();
822
+ storage.removeItem(getStorageKey());
823
+ storage.removeItem("sessionToken");
824
+ if (typeof window !== "undefined") {
825
+ window.dispatchEvent(new CustomEvent("auth:logout"));
826
+ }
827
+ if (isInitialized()) {
828
+ getConfig().onLogout?.();
829
+ }
830
+ this.notify();
831
+ }
832
+ /**
833
+ * Logout with SSO support.
834
+ * Calls the logout API and returns the SSO logout URL if applicable.
835
+ * Clears local state regardless of API response.
836
+ */
837
+ async logoutWithSSO() {
838
+ try {
839
+ const response = await authApi.logout();
840
+ this.logout();
841
+ if (response?.ssoLogout && response?.logoutUrl) {
842
+ return { ssoLogoutUrl: response.logoutUrl };
843
+ }
844
+ } catch {
845
+ this.logout();
846
+ }
847
+ return {};
848
+ }
849
+ /**
850
+ * Check if user has a specific permission.
851
+ */
852
+ hasPermission(permission) {
853
+ return this.state.user?.permissions?.includes(permission) ?? false;
854
+ }
855
+ /**
856
+ * Check if user has a specific role.
857
+ */
858
+ hasRole(role) {
859
+ return this.state.user?.roles?.includes(role) ?? false;
860
+ }
861
+ /**
862
+ * Check if user has any of the specified roles.
863
+ */
864
+ hasAnyRole(roles) {
865
+ return roles.some((role) => this.state.user?.roles?.includes(role)) ?? false;
866
+ }
867
+ /**
868
+ * Check if user has all of the specified roles.
869
+ */
870
+ hasAllRoles(roles) {
871
+ return roles.every((role) => this.state.user?.roles?.includes(role)) ?? false;
872
+ }
873
+ /**
874
+ * Check if user has any of the specified permissions.
875
+ */
876
+ hasAnyPermission(permissions) {
877
+ return permissions.some((perm) => this.state.user?.permissions?.includes(perm)) ?? false;
878
+ }
879
+ /**
880
+ * Check if user has all of the specified permissions.
881
+ */
882
+ hasAllPermissions(permissions) {
883
+ return permissions.every((perm) => this.state.user?.permissions?.includes(perm)) ?? false;
884
+ }
885
+ /**
886
+ * Re-hydrate state from storage (useful after config changes).
887
+ */
888
+ rehydrate() {
889
+ this.state = loadAuthFromStorage();
890
+ this.notify();
891
+ }
131
892
  };
132
- saveAuthToStorage(this.state);
133
- if (sessionToken && typeof window !== "undefined") {
134
- getStorageAdapter().setItem("sessionToken", sessionToken);
135
- }
136
- if (typeof window !== "undefined") {
137
- window.dispatchEvent(
138
- new CustomEvent("auth:login", {
139
- detail: { user: userWithPermissions }
140
- })
141
- );
142
- }
143
- this.notify();
144
- }
145
- /**
146
- * Update tokens (e.g., after refresh).
147
- */
148
- updateTokens(accessToken, refreshToken) {
149
- const jwtPayload = decodeJWT(accessToken);
150
- const updatedUser = this.state.user ? {
151
- ...this.state.user,
152
- permissions: jwtPayload?.permissions || this.state.user.permissions || [],
153
- roles: jwtPayload?.roles || this.state.user.roles || (this.state.user.role ? [this.state.user.role] : [])
154
- } : null;
155
- this.state = {
156
- ...this.state,
157
- accessToken,
158
- refreshToken,
159
- user: updatedUser
160
- };
161
- saveAuthToStorage(this.state);
162
- if (typeof window !== "undefined") {
163
- window.dispatchEvent(new CustomEvent("auth:token-refresh"));
164
- }
165
- this.notify();
166
- }
167
- /**
168
- * Update user data (e.g., after profile update).
169
- */
170
- updateUser(user) {
171
- const jwtPayload = this.state.accessToken ? decodeJWT(this.state.accessToken) : null;
172
- const updatedUser = {
173
- ...user,
174
- permissions: user.permissions || jwtPayload?.permissions || [],
175
- roles: user.roles || jwtPayload?.roles || (user.role ? [user.role] : [])
893
+ authStore = new AuthStore();
894
+ authActions = {
895
+ setAuth: (accessToken, refreshToken, user, sessionToken) => authStore.setAuth(accessToken, refreshToken, user, sessionToken),
896
+ updateTokens: (accessToken, refreshToken) => authStore.updateTokens(accessToken, refreshToken),
897
+ updateUser: (user) => authStore.updateUser(user),
898
+ logout: () => authStore.logout(),
899
+ logoutWithSSO: () => authStore.logoutWithSSO(),
900
+ hasPermission: (permission) => authStore.hasPermission(permission),
901
+ hasRole: (role) => authStore.hasRole(role),
902
+ hasAnyRole: (roles) => authStore.hasAnyRole(roles),
903
+ hasAllRoles: (roles) => authStore.hasAllRoles(roles),
904
+ hasAnyPermission: (permissions) => authStore.hasAnyPermission(permissions),
905
+ hasAllPermissions: (permissions) => authStore.hasAllPermissions(permissions),
906
+ rehydrate: () => authStore.rehydrate()
176
907
  };
177
- this.state = {
178
- ...this.state,
179
- user: updatedUser
908
+ isAuthenticated = {
909
+ subscribe: (subscriber) => {
910
+ return authStore.subscribe((state) => subscriber(state.isAuthenticated));
911
+ }
180
912
  };
181
- saveAuthToStorage(this.state);
182
- if (typeof window !== "undefined") {
183
- window.dispatchEvent(
184
- new CustomEvent("auth:profile-update", {
185
- detail: { user: updatedUser }
186
- })
187
- );
188
- }
189
- this.notify();
190
- }
191
- /**
192
- * Clear auth state (logout).
193
- */
194
- logout() {
195
- this.state = {
196
- accessToken: null,
197
- refreshToken: null,
198
- user: null,
199
- isAuthenticated: false
913
+ currentUser = {
914
+ subscribe: (subscriber) => {
915
+ return authStore.subscribe((state) => subscriber(state.user));
916
+ }
200
917
  };
201
- const storage = getStorageAdapter();
202
- storage.removeItem(getStorageKey());
203
- storage.removeItem("sessionToken");
204
- if (typeof window !== "undefined") {
205
- window.dispatchEvent(new CustomEvent("auth:logout"));
206
- }
207
- this.notify();
208
- }
209
- /**
210
- * Check if user has a specific permission.
211
- */
212
- hasPermission(permission) {
213
- return this.state.user?.permissions?.includes(permission) ?? false;
214
- }
215
- /**
216
- * Check if user has a specific role.
217
- */
218
- hasRole(role) {
219
- return this.state.user?.roles?.includes(role) ?? false;
220
- }
221
- /**
222
- * Check if user has any of the specified roles.
223
- */
224
- hasAnyRole(roles) {
225
- return roles.some((role) => this.state.user?.roles?.includes(role)) ?? false;
226
918
  }
227
- /**
228
- * Check if user has all of the specified roles.
229
- */
230
- hasAllRoles(roles) {
231
- return roles.every((role) => this.state.user?.roles?.includes(role)) ?? false;
232
- }
233
- /**
234
- * Check if user has any of the specified permissions.
235
- */
236
- hasAnyPermission(permissions) {
237
- return permissions.some((perm) => this.state.user?.permissions?.includes(perm)) ?? false;
238
- }
239
- /**
240
- * Check if user has all of the specified permissions.
241
- */
242
- hasAllPermissions(permissions) {
243
- return permissions.every((perm) => this.state.user?.permissions?.includes(perm)) ?? false;
244
- }
245
- /**
246
- * Re-hydrate state from storage (useful after config changes).
247
- */
248
- rehydrate() {
249
- this.state = loadAuthFromStorage();
250
- this.notify();
251
- }
252
- };
253
- var authStore = new AuthStore();
254
- var authActions = {
255
- setAuth: (accessToken, refreshToken, user, sessionToken) => authStore.setAuth(accessToken, refreshToken, user, sessionToken),
256
- updateTokens: (accessToken, refreshToken) => authStore.updateTokens(accessToken, refreshToken),
257
- updateUser: (user) => authStore.updateUser(user),
258
- logout: () => authStore.logout(),
259
- hasPermission: (permission) => authStore.hasPermission(permission),
260
- hasRole: (role) => authStore.hasRole(role),
261
- hasAnyRole: (roles) => authStore.hasAnyRole(roles),
262
- hasAllRoles: (roles) => authStore.hasAllRoles(roles),
263
- hasAnyPermission: (permissions) => authStore.hasAnyPermission(permissions),
264
- hasAllPermissions: (permissions) => authStore.hasAllPermissions(permissions),
265
- rehydrate: () => authStore.rehydrate()
266
- };
267
- var isAuthenticated = {
268
- subscribe: (subscriber) => {
269
- return authStore.subscribe((state) => subscriber(state.isAuthenticated));
270
- }
271
- };
272
- var currentUser = {
273
- subscribe: (subscriber) => {
274
- return authStore.subscribe((state) => subscriber(state.user));
275
- }
276
- };
919
+ });
920
+
921
+ // src/svelte/index.ts
922
+ init_auth_svelte();
277
923
 
278
924
  // src/svelte/guards/auth-guard.ts
925
+ init_auth_svelte();
279
926
  function checkAuth(options = {}) {
280
927
  const { roles, permissions, requireAllRoles, requireAllPermissions } = options;
281
928
  if (!authStore.isAuthenticated) {