@nocios/crudify-ui 1.2.28 → 1.2.32

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,3 +1,7 @@
1
+ import {
2
+ tokenManager
3
+ } from "./chunk-M7V4UGCN.mjs";
4
+
1
5
  // src/providers/CrudifyDataProvider.tsx
2
6
  import { createContext, useContext, useEffect, useState, useCallback } from "react";
3
7
 
@@ -52,9 +56,30 @@ var _ConfigurationManager = class _ConfigurationManager {
52
56
  colors: "default"
53
57
  };
54
58
  const env = this.resolveValue("env", propsConfig.env, envConfig.env, cookieConfig.env, "prod", configSource);
55
- const publicApiKey = this.resolveValue("publicApiKey", propsConfig.publicApiKey, envConfig.publicApiKey, cookieConfig.publicApiKey, void 0, configSource);
56
- const loginActions = this.resolveValue("loginActions", propsConfig.loginActions, envConfig.loginActions, cookieConfig.loginActions, [], configSource);
57
- const appName = this.resolveValue("appName", propsConfig.appName, envConfig.appName, cookieConfig.appName, "Crudify App", configSource);
59
+ const publicApiKey = this.resolveValue(
60
+ "publicApiKey",
61
+ propsConfig.publicApiKey,
62
+ envConfig.publicApiKey,
63
+ cookieConfig.publicApiKey,
64
+ void 0,
65
+ configSource
66
+ );
67
+ const loginActions = this.resolveValue(
68
+ "loginActions",
69
+ propsConfig.loginActions,
70
+ envConfig.loginActions,
71
+ cookieConfig.loginActions,
72
+ [],
73
+ configSource
74
+ );
75
+ const appName = this.resolveValue(
76
+ "appName",
77
+ propsConfig.appName,
78
+ envConfig.appName,
79
+ cookieConfig.appName,
80
+ "Crudify App",
81
+ configSource
82
+ );
58
83
  const logo = this.resolveValue("logo", propsConfig.logo, envConfig.logo, cookieConfig.logo, "", configSource);
59
84
  const colors = this.resolveValue("colors", propsConfig.colors, envConfig.colors, cookieConfig.colors, {}, configSource);
60
85
  console.log("\u{1F50D} ConfigurationManager - Resolved values:");
@@ -441,506 +466,6 @@ _CrudifyInitializer.instance = null;
441
466
  var CrudifyInitializer = _CrudifyInitializer;
442
467
  var crudifyInitializer = CrudifyInitializer.getInstance();
443
468
 
444
- // src/core/TokenManager.ts
445
- import crudify2 from "@nocios/crudify-browser";
446
-
447
- // src/components/CrudifyLogin/utils/secureStorage.ts
448
- import CryptoJS from "crypto-js";
449
- var SecureStorage = class {
450
- constructor(storageType = "sessionStorage") {
451
- this.encryptionKey = this.generateEncryptionKey();
452
- this.storage = storageType === "localStorage" ? window.localStorage : window.sessionStorage;
453
- }
454
- generateEncryptionKey() {
455
- const browserFingerprint = [
456
- navigator.userAgent,
457
- navigator.language,
458
- (/* @__PURE__ */ new Date()).getTimezoneOffset(),
459
- screen.colorDepth,
460
- screen.width,
461
- screen.height,
462
- "crudify-login"
463
- ].join("|");
464
- return CryptoJS.SHA256(browserFingerprint).toString();
465
- }
466
- setItem(key, value, expiryMinutes) {
467
- try {
468
- const encrypted = CryptoJS.AES.encrypt(value, this.encryptionKey).toString();
469
- this.storage.setItem(key, encrypted);
470
- if (expiryMinutes) {
471
- const expiryTime = (/* @__PURE__ */ new Date()).getTime() + expiryMinutes * 60 * 1e3;
472
- this.storage.setItem(`${key}_expiry`, expiryTime.toString());
473
- }
474
- } catch (error) {
475
- console.error("Failed to encrypt and store data:", error);
476
- }
477
- }
478
- getItem(key) {
479
- try {
480
- const expiryKey = `${key}_expiry`;
481
- const expiry = this.storage.getItem(expiryKey);
482
- if (expiry) {
483
- const expiryTime = parseInt(expiry, 10);
484
- if ((/* @__PURE__ */ new Date()).getTime() > expiryTime) {
485
- this.removeItem(key);
486
- return null;
487
- }
488
- }
489
- const encrypted = this.storage.getItem(key);
490
- if (!encrypted) return null;
491
- const decrypted = CryptoJS.AES.decrypt(encrypted, this.encryptionKey);
492
- const result = decrypted.toString(CryptoJS.enc.Utf8);
493
- if (!result) {
494
- console.warn("Failed to decrypt stored data - may be corrupted");
495
- this.removeItem(key);
496
- return null;
497
- }
498
- return result;
499
- } catch (error) {
500
- console.error("Failed to decrypt data:", error);
501
- this.removeItem(key);
502
- return null;
503
- }
504
- }
505
- removeItem(key) {
506
- this.storage.removeItem(key);
507
- this.storage.removeItem(`${key}_expiry`);
508
- }
509
- setToken(token) {
510
- try {
511
- const parts = token.split(".");
512
- if (parts.length === 3) {
513
- const payload = JSON.parse(atob(parts[1]));
514
- if (payload.exp) {
515
- const expiryTime = payload.exp * 1e3;
516
- const now = (/* @__PURE__ */ new Date()).getTime();
517
- const minutesUntilExpiry = Math.floor((expiryTime - now) / (60 * 1e3));
518
- if (minutesUntilExpiry > 0) {
519
- this.setItem("authToken", token, minutesUntilExpiry);
520
- return;
521
- }
522
- }
523
- }
524
- } catch (error) {
525
- console.warn("Failed to parse token expiry, using default expiry");
526
- }
527
- this.setItem("authToken", token, 24 * 60);
528
- }
529
- getToken() {
530
- const token = this.getItem("authToken");
531
- if (token) {
532
- try {
533
- const parts = token.split(".");
534
- if (parts.length === 3) {
535
- const payload = JSON.parse(atob(parts[1]));
536
- if (payload.exp) {
537
- const now = Math.floor(Date.now() / 1e3);
538
- if (payload.exp < now) {
539
- this.removeItem("authToken");
540
- return null;
541
- }
542
- }
543
- }
544
- } catch (error) {
545
- console.warn("Failed to validate token expiry");
546
- this.removeItem("authToken");
547
- return null;
548
- }
549
- }
550
- return token;
551
- }
552
- };
553
- var secureSessionStorage = new SecureStorage("sessionStorage");
554
- var secureLocalStorage = new SecureStorage("localStorage");
555
-
556
- // src/utils/jwtUtils.ts
557
- var decodeJwtSafely = (token) => {
558
- try {
559
- const parts = token.split(".");
560
- if (parts.length !== 3) {
561
- console.warn("Invalid JWT format: token must have 3 parts");
562
- return null;
563
- }
564
- const payload = parts[1];
565
- const paddedPayload = payload + "=".repeat((4 - payload.length % 4) % 4);
566
- const decodedPayload = JSON.parse(atob(paddedPayload));
567
- return decodedPayload;
568
- } catch (error) {
569
- console.warn("Failed to decode JWT token:", error);
570
- return null;
571
- }
572
- };
573
- var getCurrentUserEmail = () => {
574
- try {
575
- let token = null;
576
- token = sessionStorage.getItem("authToken");
577
- console.log("\u{1F50D} getCurrentUserEmail - authToken:", token ? `${token.substring(0, 20)}...` : null);
578
- if (!token) {
579
- token = sessionStorage.getItem("token");
580
- console.log("\u{1F50D} getCurrentUserEmail - token:", token ? `${token.substring(0, 20)}...` : null);
581
- }
582
- if (!token) {
583
- token = localStorage.getItem("authToken") || localStorage.getItem("token");
584
- console.log("\u{1F50D} getCurrentUserEmail - localStorage:", token ? `${token.substring(0, 20)}...` : null);
585
- }
586
- if (!token) {
587
- console.warn("\u{1F50D} getCurrentUserEmail - No token found in any storage");
588
- return null;
589
- }
590
- const payload = decodeJwtSafely(token);
591
- if (!payload) {
592
- console.warn("\u{1F50D} getCurrentUserEmail - Failed to decode token");
593
- return null;
594
- }
595
- const email = payload.email || payload["cognito:username"] || null;
596
- console.log("\u{1F50D} getCurrentUserEmail - Extracted email:", email);
597
- return email;
598
- } catch (error) {
599
- console.warn("Failed to get current user email:", error);
600
- return null;
601
- }
602
- };
603
- var isTokenExpired = (token) => {
604
- try {
605
- const payload = decodeJwtSafely(token);
606
- if (!payload || !payload.exp) return true;
607
- const currentTime = Math.floor(Date.now() / 1e3);
608
- return payload.exp < currentTime;
609
- } catch {
610
- return true;
611
- }
612
- };
613
-
614
- // src/core/TokenManager.ts
615
- var _TokenManager = class _TokenManager {
616
- constructor() {
617
- this.TOKEN_KEY = "authToken";
618
- // Compatible with crudia-ui
619
- this.tokenCache = null;
620
- this.parsedTokenCache = null;
621
- this.expirationCheckInterval = null;
622
- this.storageEventListener = null;
623
- this.initializeTokenManager();
624
- }
625
- /**
626
- * Singleton pattern to ensure consistent token management
627
- */
628
- static getInstance() {
629
- if (!_TokenManager.instance) {
630
- _TokenManager.instance = new _TokenManager();
631
- }
632
- return _TokenManager.instance;
633
- }
634
- /**
635
- * Reset the singleton instance (useful for testing)
636
- */
637
- static resetInstance() {
638
- if (_TokenManager.instance) {
639
- _TokenManager.instance.cleanup();
640
- }
641
- _TokenManager.instance = null;
642
- }
643
- /**
644
- * Initialize the token manager with storage synchronization
645
- */
646
- initializeTokenManager() {
647
- console.log("\u{1F510} TokenManager - Initializing token management");
648
- this.migrateFromLocalStorage();
649
- this.loadTokenFromStorage();
650
- this.setupExpirationCheck();
651
- this.setupStorageListener();
652
- console.log("\u{1F510} TokenManager - Initialization complete");
653
- }
654
- /**
655
- * Migrate tokens from localStorage to sessionStorage for better security
656
- * This ensures compatibility with older implementations
657
- */
658
- migrateFromLocalStorage() {
659
- try {
660
- const legacyKeys = ["authToken", "token", "jwt", "jwtToken"];
661
- for (const key of legacyKeys) {
662
- const token = localStorage.getItem(key);
663
- if (token && !secureSessionStorage.getToken()) {
664
- console.log(`\u{1F510} TokenManager - Migrating token from localStorage key: ${key}`);
665
- secureSessionStorage.setToken(token);
666
- localStorage.removeItem(key);
667
- break;
668
- }
669
- }
670
- } catch (error) {
671
- console.warn("\u{1F510} TokenManager - Token migration failed:", error);
672
- }
673
- }
674
- /**
675
- * Load token from storage and synchronize with crudify
676
- */
677
- loadTokenFromStorage() {
678
- console.log("\u{1F510} TokenManager - LOAD_FROM_STORAGE: Entry point - loading token from storage");
679
- try {
680
- console.log("\u{1F510} TokenManager - LOAD_FROM_STORAGE: Getting token from secure session storage");
681
- const storedToken = secureSessionStorage.getToken();
682
- console.log("\u{1F510} TokenManager - LOAD_FROM_STORAGE: Stored token exists:", !!storedToken);
683
- if (storedToken && this.isTokenValid(storedToken)) {
684
- console.log("\u{1F510} TokenManager - LOAD_FROM_STORAGE: Stored token is valid, updating cache");
685
- this.tokenCache = storedToken;
686
- this.parsedTokenCache = this.parseToken(storedToken);
687
- this.syncTokenWithCrudify(storedToken);
688
- console.log("\u{1F510} TokenManager - LOAD_FROM_STORAGE: Token loaded from storage and synchronized");
689
- } else if (storedToken) {
690
- console.log("\u{1F510} TokenManager - LOAD_FROM_STORAGE: Stored token exists but is invalid/expired, clearing");
691
- this.clearToken();
692
- } else {
693
- console.log("\u{1F510} TokenManager - LOAD_FROM_STORAGE: No stored token found");
694
- }
695
- } catch (error) {
696
- console.warn("\u{1F510} TokenManager - LOAD_FROM_STORAGE: Error loading token from storage:", error);
697
- this.clearToken();
698
- }
699
- }
700
- /**
701
- * Set up automatic token expiration checking
702
- */
703
- setupExpirationCheck() {
704
- this.expirationCheckInterval = window.setInterval(() => {
705
- if (this.tokenCache && !this.isTokenValid(this.tokenCache)) {
706
- console.log("\u{1F510} TokenManager - Token expired, clearing automatically");
707
- this.clearToken();
708
- }
709
- }, 3e4);
710
- }
711
- /**
712
- * Set up storage event listener for cross-tab synchronization
713
- */
714
- setupStorageListener() {
715
- this.storageEventListener = (event) => {
716
- if (event.key === this.TOKEN_KEY) {
717
- console.log("\u{1F510} TokenManager - Token change detected from another tab");
718
- this.loadTokenFromStorage();
719
- }
720
- };
721
- window.addEventListener("storage", this.storageEventListener);
722
- }
723
- /**
724
- * Set a new JWT token with automatic synchronization
725
- */
726
- setToken(token) {
727
- console.log("\u{1F510} TokenManager - SET_TOKEN: Entry point - setting token:", token ? "provided" : "null");
728
- try {
729
- if (!token) {
730
- console.log("\u{1F510} TokenManager - SET_TOKEN: No token provided, clearing token");
731
- this.clearToken();
732
- return;
733
- }
734
- console.log("\u{1F510} TokenManager - SET_TOKEN: Validating token before setting");
735
- if (!this.isTokenValid(token)) {
736
- console.warn("\u{1F510} TokenManager - SET_TOKEN: Attempted to set invalid or expired token");
737
- this.clearToken();
738
- return;
739
- }
740
- console.log("\u{1F510} TokenManager - SET_TOKEN: Token is valid, updating cache");
741
- this.tokenCache = token;
742
- this.parsedTokenCache = this.parseToken(token);
743
- console.log("\u{1F510} TokenManager - SET_TOKEN: Storing token in secure storage");
744
- secureSessionStorage.setToken(token);
745
- console.log("\u{1F510} TokenManager - SET_TOKEN: Synchronizing with crudify");
746
- this.syncTokenWithCrudify(token);
747
- console.log("\u{1F510} TokenManager - SET_TOKEN: Token set and synchronized successfully");
748
- } catch (error) {
749
- console.error("\u{1F510} TokenManager - SET_TOKEN: Error setting token:", error);
750
- this.clearToken();
751
- }
752
- }
753
- /**
754
- * Get the current JWT token
755
- */
756
- getToken() {
757
- console.log("\u{1F510} TokenManager - GET_TOKEN: Entry point - checking cache");
758
- if (this.tokenCache) {
759
- console.log("\u{1F510} TokenManager - GET_TOKEN: Cache exists, validating token");
760
- if (this.isTokenValid(this.tokenCache)) {
761
- console.log("\u{1F510} TokenManager - GET_TOKEN: Cache valid, returning cached token");
762
- return this.tokenCache;
763
- } else {
764
- console.log("\u{1F510} TokenManager - GET_TOKEN: Cache invalid, clearing cache");
765
- this.tokenCache = null;
766
- }
767
- } else {
768
- console.log("\u{1F510} TokenManager - GET_TOKEN: No cache, loading from storage");
769
- }
770
- console.log("\u{1F510} TokenManager - GET_TOKEN: Loading from storage");
771
- this.loadTokenFromStorage();
772
- console.log("\u{1F510} TokenManager - GET_TOKEN: Returning final token:", !!this.tokenCache);
773
- return this.tokenCache;
774
- }
775
- /**
776
- * Parse the current JWT token
777
- */
778
- parseToken(token) {
779
- console.log("\u{1F510} TokenManager - PARSE_TOKEN: Entry point - parsing token");
780
- const targetToken = token !== void 0 ? token : this.tokenCache;
781
- console.log("\u{1F510} TokenManager - PARSE_TOKEN: Target token exists:", !!targetToken);
782
- if (!targetToken) {
783
- console.log("\u{1F510} TokenManager - PARSE_TOKEN: No target token, returning null");
784
- return null;
785
- }
786
- if (this.tokenCache === targetToken && this.parsedTokenCache) {
787
- console.log("\u{1F510} TokenManager - PARSE_TOKEN: Returning cached parsed token");
788
- return this.parsedTokenCache;
789
- }
790
- console.log("\u{1F510} TokenManager - PARSE_TOKEN: Cache miss, parsing token with decodeJwtSafely");
791
- const parsed = decodeJwtSafely(targetToken);
792
- console.log("\u{1F510} TokenManager - PARSE_TOKEN: Token parsed successfully:", !!parsed);
793
- if (targetToken === this.tokenCache) {
794
- console.log("\u{1F510} TokenManager - PARSE_TOKEN: Updating parsed token cache");
795
- this.parsedTokenCache = parsed;
796
- }
797
- return parsed;
798
- }
799
- /**
800
- * Check if a token is valid (properly formatted and not expired)
801
- */
802
- isTokenValid(token) {
803
- console.log("\u{1F510} TokenManager - IS_TOKEN_VALID: Entry point - checking token validity");
804
- const targetToken = token !== void 0 ? token : this.tokenCache;
805
- console.log("\u{1F510} TokenManager - IS_TOKEN_VALID: Target token exists:", !!targetToken);
806
- if (!targetToken) {
807
- console.log("\u{1F510} TokenManager - IS_TOKEN_VALID: No token, returning false");
808
- return false;
809
- }
810
- try {
811
- console.log("\u{1F510} TokenManager - IS_TOKEN_VALID: Checking if token is expired");
812
- if (isTokenExpired(targetToken)) {
813
- console.log("\u{1F510} TokenManager - IS_TOKEN_VALID: Token is expired, returning false");
814
- return false;
815
- }
816
- console.log("\u{1F510} TokenManager - IS_TOKEN_VALID: Token not expired, checking if can be parsed");
817
- const parsed = decodeJwtSafely(targetToken);
818
- const isValid = parsed !== null;
819
- console.log("\u{1F510} TokenManager - IS_TOKEN_VALID: Token parsing result:", isValid);
820
- return isValid;
821
- } catch (error) {
822
- console.log("\u{1F510} TokenManager - IS_TOKEN_VALID: Error validating token:", error);
823
- return false;
824
- }
825
- }
826
- /**
827
- * Get token expiration time as Date object
828
- */
829
- getTokenExpiration() {
830
- const token = this.getToken();
831
- if (!token) return null;
832
- const parsed = this.parseToken(token);
833
- if (!parsed?.exp) return null;
834
- return new Date(parsed.exp * 1e3);
835
- }
836
- /**
837
- * Clear the current token from all storages and crudify
838
- */
839
- clearToken() {
840
- console.log("\u{1F510} TokenManager - CLEAR_TOKEN: Entry point - clearing all tokens");
841
- try {
842
- console.log("\u{1F510} TokenManager - CLEAR_TOKEN: Clearing cache");
843
- this.tokenCache = null;
844
- this.parsedTokenCache = null;
845
- console.log("\u{1F510} TokenManager - CLEAR_TOKEN: Clearing from secure storage");
846
- secureSessionStorage.removeItem(this.TOKEN_KEY);
847
- console.log("\u{1F510} TokenManager - CLEAR_TOKEN: Clearing from crudify");
848
- crudify2.setToken("");
849
- console.log("\u{1F510} TokenManager - CLEAR_TOKEN: Token cleared from all storages successfully");
850
- } catch (error) {
851
- console.warn("\u{1F510} TokenManager - CLEAR_TOKEN: Error clearing token:", error);
852
- }
853
- }
854
- /**
855
- * Synchronize token with crudify library
856
- */
857
- syncTokenWithCrudify(token) {
858
- try {
859
- crudify2.setToken(token);
860
- console.log("\u{1F510} TokenManager - Token synchronized with crudify");
861
- } catch (error) {
862
- console.warn("\u{1F510} TokenManager - Failed to sync token with crudify:", error);
863
- }
864
- }
865
- /**
866
- * Refresh token (placeholder for future implementation)
867
- */
868
- async refreshToken() {
869
- throw new Error("Token refresh not yet implemented");
870
- }
871
- /**
872
- * Get user information from the current token
873
- */
874
- getUserInfo() {
875
- const parsed = this.parseToken();
876
- if (!parsed) {
877
- return {
878
- email: null,
879
- userId: null,
880
- userIdentifier: null,
881
- username: null
882
- };
883
- }
884
- return {
885
- email: parsed.email || null,
886
- userId: parsed.sub || null,
887
- userIdentifier: parsed["cognito:username"] || parsed.email || parsed.sub || null,
888
- username: parsed["cognito:username"] || null
889
- };
890
- }
891
- /**
892
- * Check if user is currently authenticated
893
- */
894
- isAuthenticated() {
895
- return this.isTokenValid();
896
- }
897
- /**
898
- * Get time until token expires in minutes
899
- */
900
- getTimeUntilExpiration() {
901
- const expiration = this.getTokenExpiration();
902
- if (!expiration) return null;
903
- const now = /* @__PURE__ */ new Date();
904
- const minutesUntilExpiry = Math.floor((expiration.getTime() - now.getTime()) / (60 * 1e3));
905
- return Math.max(0, minutesUntilExpiry);
906
- }
907
- /**
908
- * Cleanup resources (call when the component unmounts)
909
- */
910
- cleanup() {
911
- if (this.expirationCheckInterval) {
912
- window.clearInterval(this.expirationCheckInterval);
913
- this.expirationCheckInterval = null;
914
- }
915
- if (this.storageEventListener) {
916
- window.removeEventListener("storage", this.storageEventListener);
917
- this.storageEventListener = null;
918
- }
919
- console.log("\u{1F510} TokenManager - Cleanup completed");
920
- }
921
- /**
922
- * Get debug information about the current token state
923
- */
924
- getDebugInfo() {
925
- const token = this.getToken();
926
- const parsed = this.parseToken();
927
- const expiration = this.getTokenExpiration();
928
- return {
929
- hasToken: !!token,
930
- tokenLength: token?.length || 0,
931
- isValid: this.isTokenValid(),
932
- isAuthenticated: this.isAuthenticated(),
933
- expiration: expiration?.toISOString() || null,
934
- minutesUntilExpiry: this.getTimeUntilExpiration(),
935
- userInfo: this.getUserInfo(),
936
- parsedTokenKeys: parsed ? Object.keys(parsed) : []
937
- };
938
- }
939
- };
940
- _TokenManager.instance = null;
941
- var TokenManager = _TokenManager;
942
- var tokenManager = TokenManager.getInstance();
943
-
944
469
  // src/providers/CrudifyDataProvider.tsx
945
470
  import { jsx } from "react/jsx-runtime";
946
471
  var CrudifyDataContext = createContext(null);
@@ -1107,7 +632,18 @@ var CrudifyDataProvider = ({
1107
632
  tokenManager: tokenManager.getDebugInfo(),
1108
633
  crudifyInitializer: crudifyInitializer.getStatus()
1109
634
  };
1110
- }, [isConfigured, configError, isInitialized, isInitializing, initializationError, isAuthenticated, config, token, user, tokenExpiration]);
635
+ }, [
636
+ isConfigured,
637
+ configError,
638
+ isInitialized,
639
+ isInitializing,
640
+ initializationError,
641
+ isAuthenticated,
642
+ config,
643
+ token,
644
+ user,
645
+ tokenExpiration
646
+ ]);
1111
647
  useEffect(() => {
1112
648
  const resolvedConfig = initializeConfiguration();
1113
649
  updateAuthenticationState();
@@ -1158,14 +694,8 @@ var useCrudifyDataContext = () => {
1158
694
 
1159
695
  export {
1160
696
  getCookie,
1161
- secureSessionStorage,
1162
- secureLocalStorage,
1163
697
  configurationManager,
1164
698
  crudifyInitializer,
1165
- decodeJwtSafely,
1166
- getCurrentUserEmail,
1167
- isTokenExpired,
1168
- tokenManager,
1169
699
  CrudifyDataProvider,
1170
700
  useCrudifyDataContext
1171
701
  };