@arex95/vue-core 1.1.20 → 1.1.22

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.
@@ -2,7 +2,6 @@ import { AuthParams, AuthResponse } from "@/types";
2
2
  import { SessionPreference } from "@config/global/sessionConfig";
3
3
  /**
4
4
  * @typedef {object} AuthHook
5
- * @property {function(): Promise<string | null>} getJwt - Retrieves the current JWT.
6
5
  * @property {function(): Promise<number | null>} getTokenExpiry - Retrieves the expiration time of the current token in milliseconds.
7
6
  * @property {function(): Promise<void>} cleanCredentials - Clears authentication credentials from storage.
8
7
  * @property {(params?: AuthParams) => Promise<void>} logout - Logs out the user, clears credentials, and reloads the page.
@@ -19,11 +18,7 @@ import { SessionPreference } from "@config/global/sessionConfig";
19
18
  * @returns {AuthHook} An object containing authentication functions.
20
19
  */
21
20
  export declare function useAuth(secretKey?: string): {
22
- getJwt: () => Promise<string | null>;
23
- getTokenExpiry: () => Promise<number | null>;
24
- cleanCredentials: (preference: SessionPreference) => Promise<void>;
25
21
  logout: (params?: AuthParams) => Promise<void>;
26
22
  login: (params: AuthParams, persistence: SessionPreference) => Promise<AuthResponse>;
27
23
  refresh: () => Promise<AuthResponse>;
28
- verifyAuth: () => Promise<boolean>;
29
24
  };
package/dist/index.mjs CHANGED
@@ -2,9 +2,9 @@ import axios from 'axios';
2
2
  import { useRouter } from 'vue-router';
3
3
  import { v4 } from 'uuid';
4
4
  import { useTimeoutFn, useBreakpoints, breakpointsTailwind, useWindowSize } from '@vueuse/core';
5
+ import { jwtDecode } from 'jwt-decode';
5
6
  import { useQuery } from '@tanstack/vue-query';
6
7
  import { ref, watch, onServerPrefetch, onMounted, computed } from 'vue';
7
- import { jwtDecode } from 'jwt-decode';
8
8
 
9
9
  /**
10
10
  * Enum defining available screen sizes.
@@ -2504,6 +2504,213 @@ function isValidHexNumber(hex) {
2504
2504
  // console.log(isValidHexNumber('1A3F')); // true
2505
2505
  // console.log(isValidHexNumber('GHIJ')); // false
2506
2506
 
2507
+ /**
2508
+ * Converts an ArrayBuffer or Uint8Array to a hexadecimal string.
2509
+ * @param buffer The ArrayBuffer or Uint8Array to convert.
2510
+ * @returns The hexadecimal string.
2511
+ */
2512
+ function ab2hex(buffer) {
2513
+ return Array.from(new Uint8Array(buffer))
2514
+ .map((byte) => byte.toString(16).padStart(2, "0"))
2515
+ .join("");
2516
+ }
2517
+ /**
2518
+ * Converts a hexadecimal string to a Uint8Array.
2519
+ * @param hex The hexadecimal string to convert.
2520
+ * @returns The Uint8Array.
2521
+ */
2522
+ function hex2ab(hex) {
2523
+ if (!hex || !/^[0-9a-fA-F]*$/.test(hex)) {
2524
+ return new Uint8Array();
2525
+ }
2526
+ const matches = hex.match(/[0-9a-fA-F]{1,2}/g);
2527
+ return new Uint8Array(matches ? matches.map((byte) => parseInt(byte, 16)) : []);
2528
+ }
2529
+ /**
2530
+ * Derives an encryption key from a secret key.
2531
+ * @param secretKey The secret key in plain text.
2532
+ * @returns A promise that resolves with the derived CryptoKey.
2533
+ */
2534
+ async function importKey(secretKey) {
2535
+ const keyMaterial = new TextEncoder().encode(secretKey);
2536
+ const digest = await crypto.subtle.digest("SHA-256", keyMaterial);
2537
+ return crypto.subtle.importKey("raw", digest, { name: "AES-CBC", length: 256 }, false, ["encrypt", "decrypt"]);
2538
+ }
2539
+ /**
2540
+ * Encrypts a value with the provided secret key.
2541
+ * @param value The value to encrypt.
2542
+ * @param secretKey The secret key for encryption.
2543
+ * @returns A promise that resolves with the IV (hex) + ciphertext (hex) string.
2544
+ */
2545
+ async function encrypt(value, secretKey) {
2546
+ const key = await importKey(secretKey);
2547
+ const iv = crypto.getRandomValues(new Uint8Array(16));
2548
+ const encodedValue = new TextEncoder().encode(value);
2549
+ const ciphertext = await crypto.subtle.encrypt({ name: "AES-CBC", iv: iv }, key, encodedValue);
2550
+ return ab2hex(iv) + ab2hex(new Uint8Array(ciphertext));
2551
+ }
2552
+ /**
2553
+ * Decrypts an encrypted value.
2554
+ * @param encryptedValue The encrypted string (IV_hex + ciphertext_hex).
2555
+ * @param secretKey The secret key for decryption.
2556
+ * @returns A promise that resolves with the decrypted value.
2557
+ */
2558
+ async function decrypt(encryptedValue, secretKey) {
2559
+ const key = await importKey(secretKey);
2560
+ const ivHex = encryptedValue.substring(0, 32);
2561
+ const ciphertextHex = encryptedValue.substring(32);
2562
+ const iv = hex2ab(ivHex);
2563
+ const ciphertext = hex2ab(ciphertextHex);
2564
+ const decryptedBuffer = await crypto.subtle.decrypt({ name: "AES-CBC", iv: iv }, key, ciphertext);
2565
+ return new TextDecoder().decode(decryptedBuffer);
2566
+ }
2567
+
2568
+ /**
2569
+ * Encrypts and stores an item in local or session storage.
2570
+ * Assumes the `window` environment is available.
2571
+ * @param key The key under which to store the value.
2572
+ * @param value The value to encrypt and store.
2573
+ * @param secretKey The secret key for encryption.
2574
+ * @param isRememberMe If true, uses localStorage; otherwise, uses sessionStorage.
2575
+ * @returns A promise that resolves when the item is stored. Throws an error if it fails.
2576
+ */
2577
+ async function storeEncryptedItem(key, value, secretKey, isRememberMe) {
2578
+ if (typeof window === "undefined") {
2579
+ throw new Error("Cannot access storage: window is not defined.");
2580
+ }
2581
+ const storage = isRememberMe ? window.localStorage : window.sessionStorage;
2582
+ const encryptedValue = await encrypt(value, secretKey);
2583
+ storage.setItem(key, encryptedValue);
2584
+ }
2585
+ /**
2586
+ * Retrieves and decrypts a value from local or session storage.
2587
+ * Assumes the `window` environment is available.
2588
+ * @param key The key of the item to retrieve.
2589
+ * @param secretKey The secret key for decryption.
2590
+ * @param isRememberMe If true, searches localStorage; otherwise, sessionStorage.
2591
+ * @returns A promise that resolves with the decrypted value or null if not found or decryption fails.
2592
+ */
2593
+ async function getDecryptedItem(key, secretKey, isRememberMe) {
2594
+ if (typeof window === "undefined") {
2595
+ return null;
2596
+ }
2597
+ const storage = isRememberMe ? window.localStorage : window.sessionStorage;
2598
+ const encryptedData = storage.getItem(key);
2599
+ if (!encryptedData) {
2600
+ return null;
2601
+ }
2602
+ try {
2603
+ return await decrypt(encryptedData, secretKey);
2604
+ }
2605
+ catch (error) {
2606
+ return null;
2607
+ }
2608
+ }
2609
+
2610
+ const tokensConfig = getTokenConfig();
2611
+ /**
2612
+ * Clears all stored authentication data (access and refresh tokens)
2613
+ * from either sessionStorage or localStorage based on the provided preference.
2614
+ *
2615
+ * @param {SessionPreference} preference - The storage preference ('local' for localStorage, 'session' for sessionStorage).
2616
+ * @returns {Promise<void>} A promise that resolves when all relevant storage items are removed.
2617
+ */
2618
+ const cleanCredentials = async (preference) => {
2619
+ Object.keys(tokensConfig).forEach((key) => {
2620
+ const storage = preference === "session" ? sessionStorage : localStorage;
2621
+ storage.removeItem(tokensConfig[key]);
2622
+ });
2623
+ };
2624
+ /**
2625
+ * Retrieves the authentication token (access token) from storage, decrypting it
2626
+ * using the provided secret key and based on the specified session preference.
2627
+ *
2628
+ * @param {string} secretKey - The secret key used for decryption.
2629
+ * @param {SessionPreference} preference - The storage preference ('local' for localStorage, 'session' for sessionStorage).
2630
+ * @returns {Promise<string | null>} A promise that resolves with the decrypted access token, or null if not found.
2631
+ */
2632
+ const getAuthToken = async (secretKey, preference) => {
2633
+ return await getDecryptedItem(tokensConfig.ACCESS_TOKEN, secretKey, preference === "session");
2634
+ };
2635
+ /**
2636
+ * Retrieves the authentication refresh token from storage, decrypting it
2637
+ * using the provided secret key and based on the specified session preference.
2638
+ *
2639
+ * @param {string} secretKey - The secret key used for decryption.
2640
+ * @param {SessionPreference} preference - The storage preference ('local' for localStorage, 'session' for sessionStorage).
2641
+ * @returns {Promise<string | null>} A promise that resolves with the decrypted refresh token, or null if not found.
2642
+ */
2643
+ const getAuthRefreshToken = async (secretKey, preference) => {
2644
+ return await getDecryptedItem(tokensConfig.REFRESH_TOKEN, secretKey, preference === "session");
2645
+ };
2646
+ /**
2647
+ * Stores the authentication token (access token) in storage after encrypting it,
2648
+ * based on the specified session preference.
2649
+ *
2650
+ * @param {string} token - The access token to store.
2651
+ * @param {string} secretKey - The secret key used for encryption.
2652
+ * @param {SessionPreference} preference - The storage preference ('local' for localStorage, 'session' for sessionStorage).
2653
+ * @returns {Promise<void>} A promise that resolves when the token is successfully stored.
2654
+ */
2655
+ const storeAuthToken = async (token, secretKey, preference) => {
2656
+ await storeEncryptedItem(tokensConfig.ACCESS_TOKEN, token, secretKey, preference === "session");
2657
+ };
2658
+ /**
2659
+ * Stores the authentication refresh token in storage after encrypting it,
2660
+ * based on the specified session preference.
2661
+ *
2662
+ * @param {string} token - The refresh token to store.
2663
+ * @param {string} secretKey - The secret key used for encryption.
2664
+ * @param {SessionPreference} preference - The storage preference ('local' for localStorage, 'session' for sessionStorage).
2665
+ * @returns {Promise<void>} A promise that resolves when the token is successfully stored.
2666
+ */
2667
+ const storeAuthRefreshToken = async (token, secretKey, preference) => {
2668
+ await storeEncryptedItem(tokensConfig.REFRESH_TOKEN, token, secretKey, preference === "session");
2669
+ };
2670
+ /**
2671
+ * Verifies the validity and expiration of the current authentication token.
2672
+ * If the token is missing, invalid, or expired, appropriate errors are thrown and credentials are cleaned.
2673
+ *
2674
+ * @param {string} secretKey - The secret key used for token decryption.
2675
+ * @param {SessionPreference} preference - The current session persistence preference.
2676
+ * @returns {Promise<boolean>} True if the token is valid and unexpired.
2677
+ * @throws {Error} "TOKEN_MISSING" if no token is found, "TOKEN_EXPIRED" if the token has expired,
2678
+ * "TOKEN_INVALID" if the token format is invalid.
2679
+ */
2680
+ const verifyAuth = async (secretKey = getSecretKey(), preference = getSessionPersistencePreference()) => {
2681
+ try {
2682
+ const token = await getAuthToken(secretKey, preference);
2683
+ if (!token) {
2684
+ handleError("TOKEN_MISSING: No valid token found", false);
2685
+ await cleanCredentials(preference);
2686
+ return false;
2687
+ }
2688
+ const decoded = jwtDecode(token);
2689
+ const currentTime = Date.now() / 1000;
2690
+ if (typeof decoded.exp !== "number") {
2691
+ handleError("TOKEN_INVALID: Invalid expiration format", false);
2692
+ await cleanCredentials(preference);
2693
+ return false;
2694
+ }
2695
+ if (decoded.exp <= currentTime) {
2696
+ handleError("TOKEN_EXPIRED: Token is expired", false);
2697
+ await cleanCredentials(preference);
2698
+ return false;
2699
+ }
2700
+ return true;
2701
+ }
2702
+ catch (error) {
2703
+ if (error instanceof Error && error.message.includes("Invalid")) {
2704
+ handleError("TOKEN_INVALID: Invalid token format", false);
2705
+ await cleanCredentials(preference);
2706
+ return false;
2707
+ }
2708
+ handleError("AUTH_ERROR: An unexpected error occurred", false);
2709
+ await cleanCredentials(preference);
2710
+ return false;
2711
+ }
2712
+ };
2713
+
2507
2714
  class RestStd {
2508
2715
  static resource;
2509
2716
  static isFormData = false;
@@ -3055,173 +3262,8 @@ function useSorter(items, criteriaList, selectedCriteria) {
3055
3262
  }).value;
3056
3263
  }
3057
3264
 
3058
- /**
3059
- * Converts an ArrayBuffer or Uint8Array to a hexadecimal string.
3060
- * @param buffer The ArrayBuffer or Uint8Array to convert.
3061
- * @returns The hexadecimal string.
3062
- */
3063
- function ab2hex(buffer) {
3064
- return Array.from(new Uint8Array(buffer))
3065
- .map((byte) => byte.toString(16).padStart(2, "0"))
3066
- .join("");
3067
- }
3068
- /**
3069
- * Converts a hexadecimal string to a Uint8Array.
3070
- * @param hex The hexadecimal string to convert.
3071
- * @returns The Uint8Array.
3072
- */
3073
- function hex2ab(hex) {
3074
- if (!hex || !/^[0-9a-fA-F]*$/.test(hex)) {
3075
- return new Uint8Array();
3076
- }
3077
- const matches = hex.match(/[0-9a-fA-F]{1,2}/g);
3078
- return new Uint8Array(matches ? matches.map((byte) => parseInt(byte, 16)) : []);
3079
- }
3080
- /**
3081
- * Derives an encryption key from a secret key.
3082
- * @param secretKey The secret key in plain text.
3083
- * @returns A promise that resolves with the derived CryptoKey.
3084
- */
3085
- async function importKey(secretKey) {
3086
- const keyMaterial = new TextEncoder().encode(secretKey);
3087
- const digest = await crypto.subtle.digest("SHA-256", keyMaterial);
3088
- return crypto.subtle.importKey("raw", digest, { name: "AES-CBC", length: 256 }, false, ["encrypt", "decrypt"]);
3089
- }
3090
- /**
3091
- * Encrypts a value with the provided secret key.
3092
- * @param value The value to encrypt.
3093
- * @param secretKey The secret key for encryption.
3094
- * @returns A promise that resolves with the IV (hex) + ciphertext (hex) string.
3095
- */
3096
- async function encrypt(value, secretKey) {
3097
- const key = await importKey(secretKey);
3098
- const iv = crypto.getRandomValues(new Uint8Array(16));
3099
- const encodedValue = new TextEncoder().encode(value);
3100
- const ciphertext = await crypto.subtle.encrypt({ name: "AES-CBC", iv: iv }, key, encodedValue);
3101
- return ab2hex(iv) + ab2hex(new Uint8Array(ciphertext));
3102
- }
3103
- /**
3104
- * Decrypts an encrypted value.
3105
- * @param encryptedValue The encrypted string (IV_hex + ciphertext_hex).
3106
- * @param secretKey The secret key for decryption.
3107
- * @returns A promise that resolves with the decrypted value.
3108
- */
3109
- async function decrypt(encryptedValue, secretKey) {
3110
- const key = await importKey(secretKey);
3111
- const ivHex = encryptedValue.substring(0, 32);
3112
- const ciphertextHex = encryptedValue.substring(32);
3113
- const iv = hex2ab(ivHex);
3114
- const ciphertext = hex2ab(ciphertextHex);
3115
- const decryptedBuffer = await crypto.subtle.decrypt({ name: "AES-CBC", iv: iv }, key, ciphertext);
3116
- return new TextDecoder().decode(decryptedBuffer);
3117
- }
3118
-
3119
- /**
3120
- * Encrypts and stores an item in local or session storage.
3121
- * Assumes the `window` environment is available.
3122
- * @param key The key under which to store the value.
3123
- * @param value The value to encrypt and store.
3124
- * @param secretKey The secret key for encryption.
3125
- * @param isRememberMe If true, uses localStorage; otherwise, uses sessionStorage.
3126
- * @returns A promise that resolves when the item is stored. Throws an error if it fails.
3127
- */
3128
- async function storeEncryptedItem(key, value, secretKey, isRememberMe) {
3129
- if (typeof window === "undefined") {
3130
- throw new Error("Cannot access storage: window is not defined.");
3131
- }
3132
- const storage = isRememberMe ? window.localStorage : window.sessionStorage;
3133
- const encryptedValue = await encrypt(value, secretKey);
3134
- storage.setItem(key, encryptedValue);
3135
- }
3136
- /**
3137
- * Retrieves and decrypts a value from local or session storage.
3138
- * Assumes the `window` environment is available.
3139
- * @param key The key of the item to retrieve.
3140
- * @param secretKey The secret key for decryption.
3141
- * @param isRememberMe If true, searches localStorage; otherwise, sessionStorage.
3142
- * @returns A promise that resolves with the decrypted value or null if not found or decryption fails.
3143
- */
3144
- async function getDecryptedItem(key, secretKey, isRememberMe) {
3145
- if (typeof window === "undefined") {
3146
- return null;
3147
- }
3148
- const storage = isRememberMe ? window.localStorage : window.sessionStorage;
3149
- const encryptedData = storage.getItem(key);
3150
- if (!encryptedData) {
3151
- return null;
3152
- }
3153
- try {
3154
- return await decrypt(encryptedData, secretKey);
3155
- }
3156
- catch (error) {
3157
- return null;
3158
- }
3159
- }
3160
-
3161
- const tokensConfig = getTokenConfig();
3162
- /**
3163
- * Clears all stored authentication data (access and refresh tokens)
3164
- * from either sessionStorage or localStorage based on the provided preference.
3165
- *
3166
- * @param {SessionPreference} preference - The storage preference ('local' for localStorage, 'session' for sessionStorage).
3167
- * @returns {Promise<void>} A promise that resolves when all relevant storage items are removed.
3168
- */
3169
- const cleanCredentials = async (preference) => {
3170
- Object.keys(tokensConfig).forEach((key) => {
3171
- const storage = preference === "session" ? sessionStorage : localStorage;
3172
- storage.removeItem(tokensConfig[key]);
3173
- });
3174
- };
3175
- /**
3176
- * Retrieves the authentication token (access token) from storage, decrypting it
3177
- * using the provided secret key and based on the specified session preference.
3178
- *
3179
- * @param {string} secretKey - The secret key used for decryption.
3180
- * @param {SessionPreference} preference - The storage preference ('local' for localStorage, 'session' for sessionStorage).
3181
- * @returns {Promise<string | null>} A promise that resolves with the decrypted access token, or null if not found.
3182
- */
3183
- const getAuthToken = async (secretKey, preference) => {
3184
- return await getDecryptedItem(tokensConfig.ACCESS_TOKEN, secretKey, preference === "session");
3185
- };
3186
- /**
3187
- * Retrieves the authentication refresh token from storage, decrypting it
3188
- * using the provided secret key and based on the specified session preference.
3189
- *
3190
- * @param {string} secretKey - The secret key used for decryption.
3191
- * @param {SessionPreference} preference - The storage preference ('local' for localStorage, 'session' for sessionStorage).
3192
- * @returns {Promise<string | null>} A promise that resolves with the decrypted refresh token, or null if not found.
3193
- */
3194
- const getAuthRefreshToken = async (secretKey, preference) => {
3195
- return await getDecryptedItem(tokensConfig.REFRESH_TOKEN, secretKey, preference === "session");
3196
- };
3197
- /**
3198
- * Stores the authentication token (access token) in storage after encrypting it,
3199
- * based on the specified session preference.
3200
- *
3201
- * @param {string} token - The access token to store.
3202
- * @param {string} secretKey - The secret key used for encryption.
3203
- * @param {SessionPreference} preference - The storage preference ('local' for localStorage, 'session' for sessionStorage).
3204
- * @returns {Promise<void>} A promise that resolves when the token is successfully stored.
3205
- */
3206
- const storeAuthToken = async (token, secretKey, preference) => {
3207
- await storeEncryptedItem(tokensConfig.ACCESS_TOKEN, token, secretKey, preference === "session");
3208
- };
3209
- /**
3210
- * Stores the authentication refresh token in storage after encrypting it,
3211
- * based on the specified session preference.
3212
- *
3213
- * @param {string} token - The refresh token to store.
3214
- * @param {string} secretKey - The secret key used for encryption.
3215
- * @param {SessionPreference} preference - The storage preference ('local' for localStorage, 'session' for sessionStorage).
3216
- * @returns {Promise<void>} A promise that resolves when the token is successfully stored.
3217
- */
3218
- const storeAuthRefreshToken = async (token, secretKey, preference) => {
3219
- await storeEncryptedItem(tokensConfig.REFRESH_TOKEN, token, secretKey, preference === "session");
3220
- };
3221
-
3222
3265
  /**
3223
3266
  * @typedef {object} AuthHook
3224
- * @property {function(): Promise<string | null>} getJwt - Retrieves the current JWT.
3225
3267
  * @property {function(): Promise<number | null>} getTokenExpiry - Retrieves the expiration time of the current token in milliseconds.
3226
3268
  * @property {function(): Promise<void>} cleanCredentials - Clears authentication credentials from storage.
3227
3269
  * @property {(params?: AuthParams) => Promise<void>} logout - Logs out the user, clears credentials, and reloads the page.
@@ -3241,38 +3283,6 @@ function useAuth(secretKey = getSecretKey()) {
3241
3283
  const axiosInstance = getAxiosInstance();
3242
3284
  const endpoints = getEndpointsConfig();
3243
3285
  const currentPersistencePreference = getSessionPersistencePreference();
3244
- /**
3245
- * Retrieves the current JSON Web Token (JWT) from storage based on the active session preference.
3246
- *
3247
- * @returns {Promise<string | null>} The JWT string if found, otherwise null.
3248
- */
3249
- const getJwt = async () => {
3250
- try {
3251
- return await getAuthToken(secretKey, currentPersistencePreference);
3252
- }
3253
- catch (error) {
3254
- handleError("Error getting JWT: " + error, false);
3255
- return null;
3256
- }
3257
- };
3258
- /**
3259
- * Retrieves the expiration timestamp of the current authentication token in milliseconds.
3260
- *
3261
- * @returns {Promise<number | null>} The expiration timestamp in milliseconds if the token is valid, otherwise null.
3262
- */
3263
- const getTokenExpiry = async () => {
3264
- const token = await getJwt();
3265
- if (!token)
3266
- return null;
3267
- try {
3268
- const decoded = jwtDecode(token);
3269
- return decoded.exp ? decoded.exp * 1000 : null;
3270
- }
3271
- catch (error) {
3272
- handleError(`TOKEN_INVALID: Token verification failed (malformed or unreadable): ${error.message}`, false);
3273
- return null;
3274
- }
3275
- };
3276
3286
  /**
3277
3287
  * Logs out the user by making a POST request to the logout endpoint,
3278
3288
  * cleaning all stored credentials, and reloading the page.
@@ -3341,51 +3351,10 @@ function useAuth(secretKey = getSecretKey()) {
3341
3351
  throw error;
3342
3352
  }
3343
3353
  };
3344
- /**
3345
- * Verifies the validity and expiration of the current authentication token.
3346
- * If the token is missing, invalid, or expired, appropriate errors are thrown and credentials are cleaned.
3347
- *
3348
- * @returns {Promise<boolean>} True if the token is valid and unexpired.
3349
- * @throws {Error} "TOKEN_MISSING" if no token is found, "TOKEN_EXPIRED" if the token has expired,
3350
- * "TOKEN_INVALID" if the token format is invalid.
3351
- */
3352
- const verifyAuth = async () => {
3353
- const token = await getJwt();
3354
- if (!token) {
3355
- handleError("TOKEN_MISSING: No valid token found", false);
3356
- await cleanCredentials(currentPersistencePreference);
3357
- throw new Error("TOKEN_MISSING: No valid token found");
3358
- }
3359
- try {
3360
- const decoded = jwtDecode(token);
3361
- const currentTime = Date.now() / 1000;
3362
- if (typeof decoded.exp !== "number") {
3363
- throw new Error("Invalid expiration format");
3364
- }
3365
- if (decoded.exp <= currentTime) {
3366
- handleError("TOKEN_EXPIRED: Token is expired", false);
3367
- await cleanCredentials(currentPersistencePreference);
3368
- throw new Error("TOKEN_EXPIRED: Token is expired");
3369
- }
3370
- return true;
3371
- }
3372
- catch (error) {
3373
- if (error instanceof Error && error.message.includes("Invalid")) {
3374
- handleError("TOKEN_INVALID: Invalid token format", false);
3375
- await cleanCredentials(currentPersistencePreference);
3376
- throw new Error("TOKEN_INVALID: Invalid token format");
3377
- }
3378
- throw error;
3379
- }
3380
- };
3381
3354
  return {
3382
- getJwt,
3383
- getTokenExpiry,
3384
- cleanCredentials,
3385
3355
  logout,
3386
3356
  login,
3387
- refresh,
3388
- verifyAuth
3357
+ refresh
3389
3358
  };
3390
3359
  }
3391
3360
 
@@ -3421,4 +3390,4 @@ const ArexVueCore = {
3421
3390
  },
3422
3391
  };
3423
3392
 
3424
- export { AppTypes, ArchiveTypes, ArexVueCore, AudioTypes, AxiosService, ContentTypeEnum, DocumentTypes, ERROR_MESSAGES, ERROR_STYLES, ErrorEnum, ErrorMessages, ErrorStyles, ExceptionEnum, FontTypes, ImageTypes, KeyCodeEnum, OtherTypes, RestStd, ScreenBreakpoint, ScreenSize, StorageKeyEnum, StorageTypeEnum, TextTypes, VideoTypes, addCustomKeyboardShortcut, addDays, addDoubleClickListener, addKeyListener, ageAtDate, axiosFetch, blobToFormData, bufferToBlob, calculateAge, clickOutside, compareObject, configAxios, configEndpoints, configSession, configTokenKeys, copyToClipboard, countWords, createCustomAxiosInstance, createFetch, createKeyMap, customShortcut, daysBetween, daysToNextBirthday, debounce, debounceAsync, debounceAsyncValidator, debounceAsyncWithImmediate, debounceLeading, debounceLeadingTrailing, debounceTrailing, deepClone, deepEqual, deepMerge, detectKeyHold, disableCopy, disableF12Key, disableMouseButtons, disableRightClick, disableSpecificKeys, downloadBlob, enableMouseButtons, enableRightClick, enableSpecificKeys, exportToCSV, exportToExcel, exportToJSON, exportToText, exportToXML, filterObjectByKeys, flattenObject, formDataToObject, formatDate, generateRandomString, getAxiosInstance, getEndOfMonth, getEndpointsConfig, getObjectDifferences, getObjectKeys, getQueryParam, getSecretKey, getSessionConfig, getSessionId, getSessionPersistencePreference, getStartOfMonth, getTokenConfig, hasNestedProperties, isEmptyObject, isLeapYear, isStrongPassword, isValidAge, isValidCreditCard, isValidDate, isValidEmail, isValidExpiryDate, isValidHexColor, isValidHexColorAlpha, isValidHexNumber, isValidIP, isValidPhoneNumber, isValidSSN, isValidTime, isValidURL, isValidUsername, isValidZIP, lowerFirst, objectToFormData, objectToFormDataEnhanced, objectToQueryString, openWindow, parseDate, proxyToPlainObject, readFileAsDataURL, readFileAsText, regenerateSessionId, registerKeyboardShortcuts, removeAccent, removeClickOutside, removeCustomKeyboardShortcut, removeCustomShortcuts, removeDoubleClickListener, removeEmptyProperties, removeKeyListeners, replaceAll, reverseString, safeGet, screenMap, scrollToTop, setSecretKey, simulateKeyPress, stopDetectingKeyHold, stringToBlob, subtractDays, throttle, toCamelCase, toKebabCase, toggleTabNavigation, truncateString, unregisterKeyboardShortcuts, upperFirst, useAuth, useBreakpoint, useFilter, usePagination, useSorter, useVueQuery, validateAlphanumeric, validateLetters, validateNumbers };
3393
+ export { AppTypes, ArchiveTypes, ArexVueCore, AudioTypes, AxiosService, ContentTypeEnum, DocumentTypes, ERROR_MESSAGES, ERROR_STYLES, ErrorEnum, ErrorMessages, ErrorStyles, ExceptionEnum, FontTypes, ImageTypes, KeyCodeEnum, OtherTypes, RestStd, ScreenBreakpoint, ScreenSize, StorageKeyEnum, StorageTypeEnum, TextTypes, VideoTypes, ab2hex, addCustomKeyboardShortcut, addDays, addDoubleClickListener, addKeyListener, ageAtDate, axiosFetch, blobToFormData, bufferToBlob, calculateAge, cleanCredentials, clickOutside, compareObject, configAxios, configEndpoints, configSession, configTokenKeys, copyToClipboard, countWords, createCustomAxiosInstance, createFetch, createKeyMap, customShortcut, daysBetween, daysToNextBirthday, debounce, debounceAsync, debounceAsyncValidator, debounceAsyncWithImmediate, debounceLeading, debounceLeadingTrailing, debounceTrailing, decrypt, deepClone, deepEqual, deepMerge, detectKeyHold, disableCopy, disableF12Key, disableMouseButtons, disableRightClick, disableSpecificKeys, downloadBlob, enableMouseButtons, enableRightClick, enableSpecificKeys, encrypt, exportToCSV, exportToExcel, exportToJSON, exportToText, exportToXML, filterObjectByKeys, flattenObject, formDataToObject, formatDate, generateRandomString, getAuthRefreshToken, getAuthToken, getAxiosInstance, getDecryptedItem, getEndOfMonth, getEndpointsConfig, getObjectDifferences, getObjectKeys, getQueryParam, getSecretKey, getSessionConfig, getSessionId, getSessionPersistencePreference, getStartOfMonth, getTokenConfig, handleError, hasNestedProperties, hex2ab, importKey, isEmptyObject, isLeapYear, isStrongPassword, isValidAge, isValidCreditCard, isValidDate, isValidEmail, isValidExpiryDate, isValidHexColor, isValidHexColorAlpha, isValidHexNumber, isValidIP, isValidPhoneNumber, isValidSSN, isValidTime, isValidURL, isValidUsername, isValidZIP, lowerFirst, objectToFormData, objectToFormDataEnhanced, objectToQueryString, openWindow, parseDate, proxyToPlainObject, readFileAsDataURL, readFileAsText, regenerateSessionId, registerKeyboardShortcuts, removeAccent, removeClickOutside, removeCustomKeyboardShortcut, removeCustomShortcuts, removeDoubleClickListener, removeEmptyProperties, removeKeyListeners, replaceAll, reverseString, safeGet, screenMap, scrollToTop, setSecretKey, simulateKeyPress, stopDetectingKeyHold, storeAuthRefreshToken, storeAuthToken, storeEncryptedItem, stringToBlob, subtractDays, throttle, toCamelCase, toKebabCase, toggleTabNavigation, truncateString, unregisterKeyboardShortcuts, upperFirst, useAuth, useBreakpoint, useFilter, usePagination, useSorter, useVueQuery, validateAlphanumeric, validateLetters, validateNumbers, verifyAuth };
@@ -8,3 +8,4 @@ export * from './SessionConfig';
8
8
  export * from './DecodedJwtPayload';
9
9
  export * from './AuthResponse';
10
10
  export * from './AuthParams';
11
+ export * from './ArexVueCoreOptions';
@@ -45,3 +45,14 @@ export declare const storeAuthToken: (token: string, secretKey: string, preferen
45
45
  * @returns {Promise<void>} A promise that resolves when the token is successfully stored.
46
46
  */
47
47
  export declare const storeAuthRefreshToken: (token: string, secretKey: string, preference: SessionPreference) => Promise<void>;
48
+ /**
49
+ * Verifies the validity and expiration of the current authentication token.
50
+ * If the token is missing, invalid, or expired, appropriate errors are thrown and credentials are cleaned.
51
+ *
52
+ * @param {string} secretKey - The secret key used for token decryption.
53
+ * @param {SessionPreference} preference - The current session persistence preference.
54
+ * @returns {Promise<boolean>} True if the token is valid and unexpired.
55
+ * @throws {Error} "TOKEN_MISSING" if no token is found, "TOKEN_EXPIRED" if the token has expired,
56
+ * "TOKEN_INVALID" if the token format is invalid.
57
+ */
58
+ export declare const verifyAuth: (secretKey?: string, preference?: SessionPreference) => Promise<boolean>;
@@ -7,3 +7,7 @@ export * from './files';
7
7
  export * from './objects';
8
8
  export * from './strings';
9
9
  export * from './validations';
10
+ export * from './credentials';
11
+ export * from './storage';
12
+ export * from './encryption';
13
+ export * from './errors';
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@arex95/vue-core",
3
- "version": "1.1.20",
3
+ "version": "1.1.22",
4
4
  "description": "Opinionated Vue Core",
5
5
  "main": "dist/index.js",
6
6
  "module": "dist/index.mjs",