@oxog/authkeeper 1.0.0 → 1.2.1

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.
package/dist/index.js CHANGED
@@ -1,3 +1,6 @@
1
+ import { AuthError, createTokenStorePlugin, resolveStorage, createTokenDecoderPlugin, createRefreshEnginePlugin, createFetchInterceptorPlugin, base64UrlEncode } from './chunk-2IYICQ5C.js';
2
+ export { AuthError, CookieStorageAdapter, FetchInterceptorPlugin, MemoryStorageAdapter, RefreshEnginePlugin, TokenDecoderPlugin, TokenStorePlugin, WebStorageAdapter, base64UrlDecode, base64UrlDecodeToBytes, base64UrlEncode, createFetchInterceptorPlugin, createMemoryStorage, createRefreshEnginePlugin, createTokenDecoderPlugin, createTokenStorePlugin, decodeHeader, decodeJwt, decodePayload, deleteCookie, getClaim, getClaims, getCookie, getTimeUntilExpiry, getTokenExpiry, isStorageAvailable, isTokenExpired, isValidJwtFormat, parseCookies, safeGetItem, safeRemoveItem, safeSetItem, serializeCookie, setCookie, stringToBase64Url } from './chunk-2IYICQ5C.js';
3
+
1
4
  // src/kernel/event-bus.ts
2
5
  var EventBus = class {
3
6
  constructor() {
@@ -11,10 +14,11 @@ var EventBus = class {
11
14
  * @returns Unsubscribe function
12
15
  */
13
16
  on(eventType, handler) {
14
- if (!this.handlers.has(eventType)) {
15
- this.handlers.set(eventType, /* @__PURE__ */ new Set());
17
+ let handlerSet = this.handlers.get(eventType);
18
+ if (!handlerSet) {
19
+ handlerSet = /* @__PURE__ */ new Set();
20
+ this.handlers.set(eventType, handlerSet);
16
21
  }
17
- const handlerSet = this.handlers.get(eventType);
18
22
  handlerSet.add(handler);
19
23
  return () => this.off(eventType, handler);
20
24
  }
@@ -80,20 +84,6 @@ var EventBus = class {
80
84
  }
81
85
  };
82
86
 
83
- // src/types.ts
84
- var AuthError = class _AuthError extends Error {
85
- constructor(code, message, options) {
86
- super(message);
87
- this.name = "AuthError";
88
- this.code = code;
89
- this.context = options?.context;
90
- this.cause = options?.cause;
91
- if (Error.captureStackTrace) {
92
- Error.captureStackTrace(this, _AuthError);
93
- }
94
- }
95
- };
96
-
97
87
  // src/kernel/plugin-registry.ts
98
88
  var PluginRegistry = class {
99
89
  constructor() {
@@ -248,7 +238,6 @@ var AuthKeeperKernel = class {
248
238
  this.options = {
249
239
  autoRefresh: true,
250
240
  refreshThreshold: 60,
251
- syncTabs: true,
252
241
  ...options
253
242
  };
254
243
  this.pluginRegistry = new PluginRegistry();
@@ -303,11 +292,14 @@ var AuthKeeperKernel = class {
303
292
  throw new AuthError("CONFIG_ERROR", "token-store plugin not installed");
304
293
  }
305
294
  tokenStore.set(tokens);
306
- this.emit({
307
- type: "login",
308
- tokens,
309
- timestamp: Date.now()
310
- });
295
+ const refreshEngine = this.pluginRegistry.getApi("refresh-engine");
296
+ if (refreshEngine?.isApplyingRefresh?.() !== true) {
297
+ this.emit({
298
+ type: "login",
299
+ tokens,
300
+ timestamp: Date.now()
301
+ });
302
+ }
311
303
  if (this.options.autoRefresh && !this.isExpired()) {
312
304
  this.scheduleRefresh();
313
305
  }
@@ -340,6 +332,7 @@ var AuthKeeperKernel = class {
340
332
  * Clear all tokens
341
333
  */
342
334
  clearTokens() {
335
+ this.cancelScheduledRefresh();
343
336
  const tokenStore = this.pluginRegistry.getApi("token-store");
344
337
  if (tokenStore) {
345
338
  tokenStore.clear();
@@ -521,10 +514,27 @@ var AuthKeeperKernel = class {
521
514
  // ============================================================================
522
515
  /**
523
516
  * Register and install a plugin
517
+ *
518
+ * The returned promise rejects when the plugin cannot be registered or
519
+ * installed. The failure is also emitted as an 'error' event (context
520
+ * 'plugin') and passed to `onError`, so a caller that does not await the
521
+ * promise does not get an unhandled rejection.
524
522
  */
525
- async register(plugin) {
523
+ register(plugin) {
524
+ const result = this.registerPlugin(plugin);
525
+ result.catch((error) => {
526
+ this.emit({ type: "error", error, context: "plugin", timestamp: Date.now() });
527
+ });
528
+ return result;
529
+ }
530
+ async registerPlugin(plugin) {
526
531
  this.pluginRegistry.register(plugin);
527
- await this.pluginRegistry.install(plugin.name, this);
532
+ try {
533
+ await this.pluginRegistry.install(plugin.name, this);
534
+ } catch (error) {
535
+ await this.pluginRegistry.uninstall(plugin.name);
536
+ throw error;
537
+ }
528
538
  }
529
539
  /**
530
540
  * Unregister a plugin
@@ -590,665 +600,14 @@ var AuthKeeperKernel = class {
590
600
  * Get current configuration
591
601
  */
592
602
  getOptions() {
593
- return { ...this.options };
594
- }
595
- };
596
-
597
- // src/plugins/core/token-store.ts
598
- var TokenStorePlugin = class {
599
- constructor(options = {}) {
600
- this.name = "token-store";
601
- this.version = "1.0.0";
602
- this.type = "core";
603
- this.tokens = null;
604
- this.options = options;
605
- }
606
- install(_kernel) {
607
- return {
608
- set: this.set.bind(this),
609
- get: this.get.bind(this),
610
- clear: this.clear.bind(this),
611
- getAccessToken: () => this.tokens?.accessToken || null,
612
- getRefreshToken: () => this.tokens?.refreshToken || null,
613
- getTokenType: () => this.tokens?.tokenType || "Bearer",
614
- getExpiresAt: () => {
615
- if (!this.tokens?.expiresAt) return null;
616
- return new Date(this.tokens.expiresAt);
617
- },
618
- getExpiresIn: () => {
619
- if (!this.tokens?.expiresAt) return null;
620
- const now = Date.now();
621
- const timeUntil = this.tokens.expiresAt - now;
622
- return Math.max(0, timeUntil);
623
- },
624
- isExpired: () => {
625
- if (!this.tokens?.expiresAt) return false;
626
- return Date.now() >= this.tokens.expiresAt;
627
- },
628
- getSetAt: () => {
629
- if (!this.tokens?.setAt) return null;
630
- return new Date(this.tokens.setAt);
631
- },
632
- getRefreshCount: () => this.tokens?.refreshCount || 0
633
- };
634
- }
635
- /**
636
- * Set tokens
637
- */
638
- set(tokens) {
639
- let expiresAt = null;
640
- if (tokens.expiresAt) {
641
- expiresAt = tokens.expiresAt * 1e3;
642
- } else if (tokens.expiresIn) {
643
- expiresAt = Date.now() + tokens.expiresIn * 1e3;
644
- }
645
- const refreshCount = this.tokens ? this.tokens.refreshCount + 1 : 1;
646
- this.tokens = {
647
- accessToken: tokens.accessToken,
648
- refreshToken: tokens.refreshToken || null,
649
- tokenType: tokens.tokenType || "Bearer",
650
- expiresAt,
651
- setAt: Date.now(),
652
- refreshCount
653
- };
654
- if (this.options.onSet) {
655
- this.options.onSet(this.tokens);
656
- }
657
- }
658
- /**
659
- * Get tokens
660
- */
661
- get() {
662
- return this.tokens;
663
- }
664
- /**
665
- * Clear tokens
666
- */
667
- clear() {
668
- this.tokens = null;
669
- if (this.options.onClear) {
670
- this.options.onClear();
671
- }
672
- }
673
- /**
674
- * Uninstall plugin
675
- */
676
- uninstall() {
677
- this.clear();
603
+ return { ...this.options, syncTabs: false };
678
604
  }
679
605
  };
680
- function createTokenStorePlugin(options) {
681
- return new TokenStorePlugin(options);
682
- }
683
-
684
- // src/utils/base64.ts
685
- function base64UrlEncode(buffer) {
686
- let binary = "";
687
- for (let i = 0; i < buffer.length; i++) {
688
- binary += String.fromCharCode(buffer[i]);
689
- }
690
- const base64 = typeof window !== "undefined" ? btoa(binary) : Buffer.from(binary, "binary").toString("base64");
691
- return base64.replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
692
- }
693
- function base64UrlDecode(str) {
694
- let base64 = str.replace(/-/g, "+").replace(/_/g, "/");
695
- const pad = str.length % 4;
696
- if (pad === 2) {
697
- base64 += "==";
698
- } else if (pad === 3) {
699
- base64 += "=";
700
- }
701
- const binary = typeof window !== "undefined" ? atob(base64) : Buffer.from(base64, "base64").toString("binary");
702
- return decodeURIComponent(
703
- binary.split("").map((c) => {
704
- return "%" + ("00" + c.charCodeAt(0).toString(16)).slice(-2);
705
- }).join("")
706
- );
707
- }
708
- function stringToBase64Url(str) {
709
- const utf8Bytes = new TextEncoder().encode(str);
710
- return base64UrlEncode(utf8Bytes);
711
- }
712
- function base64UrlDecodeToBytes(str) {
713
- let base64 = str.replace(/-/g, "+").replace(/_/g, "/");
714
- const pad = str.length % 4;
715
- if (pad === 2) {
716
- base64 += "==";
717
- } else if (pad === 3) {
718
- base64 += "=";
719
- }
720
- if (typeof window !== "undefined") {
721
- const binary = atob(base64);
722
- const bytes = new Uint8Array(binary.length);
723
- for (let i = 0; i < binary.length; i++) {
724
- bytes[i] = binary.charCodeAt(i);
725
- }
726
- return bytes;
727
- } else {
728
- return new Uint8Array(Buffer.from(base64, "base64"));
729
- }
730
- }
731
-
732
- // src/utils/jwt.ts
733
- function decodeJwt(token) {
734
- const parts = token.split(".");
735
- if (parts.length !== 3) {
736
- throw new AuthError("TOKEN_DECODE_FAILED", "Invalid JWT format: must have 3 parts", {
737
- context: { parts: parts.length }
738
- });
739
- }
740
- try {
741
- const headerJson = base64UrlDecode(parts[0]);
742
- const header = JSON.parse(headerJson);
743
- const payloadJson = base64UrlDecode(parts[1]);
744
- const payload = JSON.parse(payloadJson);
745
- return { header, payload };
746
- } catch (error) {
747
- throw new AuthError("TOKEN_DECODE_FAILED", "Failed to decode JWT", {
748
- cause: error
749
- });
750
- }
751
- }
752
- function decodePayload(token) {
753
- return decodeJwt(token).payload;
754
- }
755
- function decodeHeader(token) {
756
- return decodeJwt(token).header;
757
- }
758
- function isValidJwtFormat(token) {
759
- if (!token || typeof token !== "string") {
760
- return false;
761
- }
762
- const parts = token.split(".");
763
- if (parts.length !== 3) {
764
- return false;
765
- }
766
- try {
767
- base64UrlDecode(parts[0]);
768
- base64UrlDecode(parts[1]);
769
- return true;
770
- } catch {
771
- return false;
772
- }
773
- }
774
- function getTokenExpiry(token) {
775
- try {
776
- const payload = decodePayload(token);
777
- if (payload.exp) {
778
- return new Date(payload.exp * 1e3);
779
- }
780
- return null;
781
- } catch {
782
- return null;
783
- }
784
- }
785
- function isTokenExpired(token, bufferSeconds = 0) {
786
- const expiry = getTokenExpiry(token);
787
- if (!expiry) {
788
- return false;
789
- }
790
- const now = Date.now();
791
- const expiryTime = expiry.getTime() - bufferSeconds * 1e3;
792
- return now >= expiryTime;
793
- }
794
- function getTimeUntilExpiry(token) {
795
- const expiry = getTokenExpiry(token);
796
- if (!expiry) {
797
- return null;
798
- }
799
- const now = Date.now();
800
- const timeUntil = expiry.getTime() - now;
801
- return Math.max(0, timeUntil);
802
- }
803
- function getClaim(token, claim) {
804
- try {
805
- const payload = decodePayload(token);
806
- return payload[claim];
807
- } catch {
808
- return void 0;
809
- }
810
- }
811
- function getClaims(token, claims) {
812
- try {
813
- const payload = decodePayload(token);
814
- const result = {};
815
- for (const claim of claims) {
816
- if (claim in payload) {
817
- result[claim] = payload[claim];
818
- }
819
- }
820
- return result;
821
- } catch {
822
- return {};
823
- }
824
- }
825
-
826
- // src/plugins/core/token-decoder.ts
827
- var TokenDecoderPlugin = class {
828
- constructor() {
829
- this.name = "token-decoder";
830
- this.version = "1.0.0";
831
- this.type = "core";
832
- }
833
- install(kernel) {
834
- this.kernel = kernel;
835
- return {
836
- decode: this.decode.bind(this),
837
- getHeader: this.getHeader.bind(this),
838
- getClaim: this.getClaimFromToken.bind(this),
839
- getClaims: this.getClaimsFromToken.bind(this),
840
- getExpiry: this.getExpiry.bind(this),
841
- isExpired: this.isExpiredToken.bind(this),
842
- getTokenInfo: this.getTokenInfo.bind(this)
843
- };
844
- }
845
- /**
846
- * Decode token payload
847
- */
848
- decode(token) {
849
- const jwt = token || this.kernel.getAccessToken();
850
- if (!jwt) {
851
- return null;
852
- }
853
- try {
854
- return decodePayload(jwt);
855
- } catch {
856
- return null;
857
- }
858
- }
859
- /**
860
- * Decode token header
861
- */
862
- getHeader(token) {
863
- const jwt = token || this.kernel.getAccessToken();
864
- if (!jwt) {
865
- return null;
866
- }
867
- try {
868
- return decodeHeader(jwt);
869
- } catch {
870
- return null;
871
- }
872
- }
873
- /**
874
- * Get specific claim from token
875
- */
876
- getClaimFromToken(key, token) {
877
- const jwt = token || this.kernel.getAccessToken();
878
- if (!jwt) {
879
- return void 0;
880
- }
881
- return getClaim(jwt, key);
882
- }
883
- /**
884
- * Get multiple claims from token
885
- */
886
- getClaimsFromToken(keys, token) {
887
- const jwt = token || this.kernel.getAccessToken();
888
- if (!jwt) {
889
- return {};
890
- }
891
- return getClaims(jwt, keys);
892
- }
893
- /**
894
- * Get token expiry
895
- */
896
- getExpiry(token) {
897
- const jwt = token || this.kernel.getAccessToken();
898
- if (!jwt) {
899
- return null;
900
- }
901
- return getTokenExpiry(jwt);
902
- }
903
- /**
904
- * Check if token is expired
905
- */
906
- isExpiredToken(token) {
907
- const jwt = token || this.kernel.getAccessToken();
908
- if (!jwt) {
909
- return true;
910
- }
911
- return isTokenExpired(jwt);
912
- }
913
- /**
914
- * Get complete token information
915
- */
916
- getTokenInfo(token) {
917
- const jwt = token || this.kernel.getAccessToken();
918
- if (!jwt) {
919
- return null;
920
- }
921
- try {
922
- const { header, payload } = decodeJwt(jwt);
923
- const expiresAt = getTokenExpiry(jwt);
924
- const isExpired2 = isTokenExpired(jwt);
925
- const expiresIn = getTimeUntilExpiry(jwt);
926
- return {
927
- raw: jwt,
928
- header,
929
- payload,
930
- expiresAt,
931
- isExpired: isExpired2,
932
- expiresIn
933
- };
934
- } catch {
935
- return null;
936
- }
937
- }
938
- uninstall() {
939
- }
940
- };
941
- function createTokenDecoderPlugin() {
942
- return new TokenDecoderPlugin();
943
- }
944
-
945
- // src/plugins/core/refresh-engine.ts
946
- var RefreshEnginePlugin = class {
947
- constructor(options) {
948
- this.name = "refresh-engine";
949
- this.version = "1.0.0";
950
- this.type = "core";
951
- this.isRefreshingFlag = false;
952
- this.refreshPromise = null;
953
- this.scheduledRefreshTimeout = null;
954
- this.options = options;
955
- this.refreshFn = options.refreshFn;
956
- this.threshold = options.threshold || 60;
957
- this.maxRetries = options.maxRetries || 3;
958
- this.retryDelay = options.retryDelay || 1e3;
959
- }
960
- install(kernel) {
961
- this.kernel = kernel;
962
- return {
963
- refresh: this.refresh.bind(this),
964
- scheduleRefresh: this.scheduleRefresh.bind(this),
965
- cancelScheduledRefresh: this.cancelScheduledRefresh.bind(this),
966
- isRefreshing: () => this.isRefreshingFlag,
967
- getNextRefreshAt: this.getNextRefreshAt.bind(this),
968
- setRefreshFn: (fn) => {
969
- this.refreshFn = fn;
970
- },
971
- setThreshold: (seconds) => {
972
- this.threshold = seconds;
973
- }
974
- };
975
- }
976
- /**
977
- * Refresh tokens
978
- *
979
- * Queues concurrent requests - only one refresh executes at a time.
980
- */
981
- async refresh() {
982
- if (this.refreshPromise) {
983
- return this.refreshPromise;
984
- }
985
- this.isRefreshingFlag = true;
986
- this.refreshPromise = this.executeRefresh();
987
- try {
988
- const tokens = await this.refreshPromise;
989
- return tokens;
990
- } finally {
991
- this.isRefreshingFlag = false;
992
- this.refreshPromise = null;
993
- }
994
- }
995
- /**
996
- * Execute token refresh with retry logic
997
- */
998
- async executeRefresh(retryCount = 0) {
999
- if (this.options.onRefreshStart) {
1000
- this.options.onRefreshStart();
1001
- }
1002
- const refreshToken = this.kernel.getRefreshToken();
1003
- if (!refreshToken) {
1004
- const error = new Error("No refresh token available");
1005
- error.name = "AuthError";
1006
- error.code = "REFRESH_TOKEN_MISSING";
1007
- this.kernel.emit({
1008
- type: "error",
1009
- error,
1010
- context: "refresh",
1011
- timestamp: Date.now()
1012
- });
1013
- throw error;
1014
- }
1015
- try {
1016
- const previousExpiresAt = this.kernel.getExpiresAt();
1017
- const newTokens = await this.refreshFn(refreshToken);
1018
- this.kernel.setTokens(newTokens);
1019
- const newExpiresAt = this.kernel.getExpiresAt();
1020
- this.kernel.emit({
1021
- type: "refresh",
1022
- tokens: newTokens,
1023
- previousExpiresAt,
1024
- newExpiresAt,
1025
- timestamp: Date.now()
1026
- });
1027
- if (this.options.onRefreshSuccess) {
1028
- this.options.onRefreshSuccess(newTokens);
1029
- }
1030
- this.scheduleRefresh();
1031
- return newTokens;
1032
- } catch (error) {
1033
- if (retryCount < this.maxRetries) {
1034
- const delay = this.retryDelay * Math.pow(2, retryCount);
1035
- await new Promise((resolve) => setTimeout(resolve, delay));
1036
- return this.executeRefresh(retryCount + 1);
1037
- }
1038
- const authError = new Error("Token refresh failed");
1039
- authError.name = "AuthError";
1040
- authError.code = "REFRESH_FAILED";
1041
- authError.cause = error;
1042
- authError.context = { retryCount };
1043
- this.kernel.emit({
1044
- type: "error",
1045
- error: authError,
1046
- context: "refresh",
1047
- timestamp: Date.now()
1048
- });
1049
- if (this.options.onRefreshError) {
1050
- this.options.onRefreshError(authError);
1051
- }
1052
- throw authError;
1053
- }
1054
- }
1055
- /**
1056
- * Schedule automatic refresh
1057
- *
1058
- * Schedules refresh before token expires (threshold seconds before).
1059
- */
1060
- scheduleRefresh() {
1061
- this.cancelScheduledRefresh();
1062
- const expiresIn = this.kernel.getTimeUntilExpiry();
1063
- if (!expiresIn) {
1064
- return;
1065
- }
1066
- const refreshIn = expiresIn - this.threshold * 1e3;
1067
- if (refreshIn > 0) {
1068
- this.scheduledRefreshTimeout = setTimeout(() => {
1069
- this.refresh().catch((error) => {
1070
- console.error("[AuthKeeper] Scheduled refresh failed:", error);
1071
- });
1072
- }, refreshIn);
1073
- } else {
1074
- this.refresh().catch((error) => {
1075
- console.error("[AuthKeeper] Immediate refresh failed:", error);
1076
- });
1077
- }
1078
- }
1079
- /**
1080
- * Cancel scheduled refresh
1081
- */
1082
- cancelScheduledRefresh() {
1083
- if (this.scheduledRefreshTimeout) {
1084
- clearTimeout(this.scheduledRefreshTimeout);
1085
- this.scheduledRefreshTimeout = null;
1086
- }
1087
- }
1088
- /**
1089
- * Get next scheduled refresh time
1090
- */
1091
- getNextRefreshAt() {
1092
- const expiresAt = this.kernel.getExpiresAt();
1093
- if (!expiresAt) {
1094
- return null;
1095
- }
1096
- const refreshAt = new Date(expiresAt.getTime() - this.threshold * 1e3);
1097
- return refreshAt;
1098
- }
1099
- /**
1100
- * Uninstall plugin
1101
- */
1102
- uninstall() {
1103
- this.cancelScheduledRefresh();
1104
- }
1105
- };
1106
- function createRefreshEnginePlugin(options) {
1107
- return new RefreshEnginePlugin(options);
1108
- }
1109
-
1110
- // src/plugins/core/storage-memory.ts
1111
- var MemoryStorageAdapter = class {
1112
- constructor(options = {}) {
1113
- this.store = /* @__PURE__ */ new Map();
1114
- this.prefix = options.prefix || "authkeeper:";
1115
- }
1116
- /**
1117
- * Get value by key
1118
- */
1119
- get(key) {
1120
- return this.store.get(this.prefix + key) || null;
1121
- }
1122
- /**
1123
- * Set value by key
1124
- */
1125
- set(key, value) {
1126
- this.store.set(this.prefix + key, value);
1127
- }
1128
- /**
1129
- * Remove value by key
1130
- */
1131
- remove(key) {
1132
- this.store.delete(this.prefix + key);
1133
- }
1134
- /**
1135
- * Clear all values
1136
- */
1137
- clear() {
1138
- const keysToDelete = [];
1139
- for (const key of this.store.keys()) {
1140
- if (key.startsWith(this.prefix)) {
1141
- keysToDelete.push(key);
1142
- }
1143
- }
1144
- keysToDelete.forEach((key) => this.store.delete(key));
1145
- }
1146
- };
1147
- function createMemoryStorage(options) {
1148
- return new MemoryStorageAdapter(options);
1149
- }
1150
-
1151
- // src/plugins/core/fetch-interceptor.ts
1152
- var FetchInterceptorPlugin = class {
1153
- constructor() {
1154
- this.name = "fetch-interceptor";
1155
- this.version = "1.0.0";
1156
- this.type = "core";
1157
- this.originalFetch = null;
1158
- }
1159
- install(kernel) {
1160
- this.kernel = kernel;
1161
- return {
1162
- createFetch: this.createFetch.bind(this),
1163
- wrapFetch: this.wrapFetch.bind(this),
1164
- unwrapFetch: this.unwrapFetch.bind(this)
1165
- };
1166
- }
1167
- /**
1168
- * Create authenticated fetch function
1169
- */
1170
- createFetch(options = {}) {
1171
- const {
1172
- headerName = "Authorization",
1173
- headerPrefix = "Bearer ",
1174
- includeUrls = [],
1175
- excludeUrls = [],
1176
- retry401 = true,
1177
- maxRetries = 1,
1178
- onUnauthorized
1179
- } = options;
1180
- return async (input, init) => {
1181
- const url = typeof input === "string" ? input : input instanceof URL ? input.href : input.url;
1182
- const shouldInclude = includeUrls.length === 0 || includeUrls.some(
1183
- (pattern) => typeof pattern === "string" ? url.includes(pattern) : pattern.test(url)
1184
- );
1185
- const shouldExclude = excludeUrls.some(
1186
- (pattern) => typeof pattern === "string" ? url.includes(pattern) : pattern.test(url)
1187
- );
1188
- if (!shouldInclude || shouldExclude) {
1189
- return fetch(input, init);
1190
- }
1191
- const accessToken = this.kernel.getAccessToken();
1192
- const headers = new Headers(init?.headers);
1193
- if (accessToken) {
1194
- headers.set(headerName, headerPrefix + accessToken);
1195
- }
1196
- let response = await fetch(input, {
1197
- ...init,
1198
- headers
1199
- });
1200
- if (response.status === 401 && retry401 && maxRetries > 0) {
1201
- if (onUnauthorized) {
1202
- onUnauthorized(response);
1203
- }
1204
- try {
1205
- await this.kernel.refresh();
1206
- const newToken = this.kernel.getAccessToken();
1207
- if (newToken) {
1208
- headers.set(headerName, headerPrefix + newToken);
1209
- response = await fetch(input, {
1210
- ...init,
1211
- headers
1212
- });
1213
- }
1214
- } catch (error) {
1215
- console.error("[AuthKeeper] Token refresh failed during 401 retry:", error);
1216
- }
1217
- }
1218
- return response;
1219
- };
1220
- }
1221
- /**
1222
- * Wrap global fetch with auth
1223
- */
1224
- wrapFetch(fetch2) {
1225
- if (!this.originalFetch) {
1226
- this.originalFetch = fetch2;
1227
- }
1228
- const authFetch = this.createFetch();
1229
- globalThis.fetch = authFetch;
1230
- }
1231
- /**
1232
- * Restore original fetch
1233
- */
1234
- unwrapFetch() {
1235
- if (this.originalFetch) {
1236
- globalThis.fetch = this.originalFetch;
1237
- this.originalFetch = null;
1238
- }
1239
- }
1240
- uninstall() {
1241
- this.unwrapFetch();
1242
- }
1243
- };
1244
- function createFetchInterceptorPlugin() {
1245
- return new FetchInterceptorPlugin();
1246
- }
1247
606
 
1248
607
  // src/factory.ts
1249
608
  async function createAuthKeeper(options) {
1250
609
  const kernel = new AuthKeeperKernel(options);
1251
- await kernel.register(createTokenStorePlugin());
610
+ await kernel.register(createTokenStorePlugin({ storage: resolveStorage(options.storage) }));
1252
611
  await kernel.register(createTokenDecoderPlugin());
1253
612
  await kernel.register(
1254
613
  createRefreshEnginePlugin({
@@ -1258,6 +617,9 @@ async function createAuthKeeper(options) {
1258
617
  );
1259
618
  await kernel.register(createFetchInterceptorPlugin());
1260
619
  await kernel.init();
620
+ if (kernel.getAccessToken() && !kernel.isExpired()) {
621
+ kernel.scheduleRefresh();
622
+ }
1261
623
  return kernel;
1262
624
  }
1263
625
 
@@ -1345,6 +707,6 @@ function generateUuid() {
1345
707
  return `${hex.substring(0, 8)}-${hex.substring(8, 12)}-${hex.substring(12, 16)}-${hex.substring(16, 20)}-${hex.substring(20)}`;
1346
708
  }
1347
709
 
1348
- export { AuthError, AuthKeeperKernel, EventBus, FetchInterceptorPlugin, MemoryStorageAdapter, PluginRegistry, RefreshEnginePlugin, TokenDecoderPlugin, TokenStorePlugin, base64UrlDecode, base64UrlDecodeToBytes, base64UrlEncode, calculateExpiresAt, createAuthKeeper, createFetchInterceptorPlugin, createMemoryStorage, createRefreshEnginePlugin, createTokenDecoderPlugin, createTokenStorePlugin, decodeHeader, decodeJwt, decodePayload, formatTimeRemaining, generateCodeChallenge, generateCodeVerifier, generateRandomString, generateUuid, getClaim, getClaims, getExpiresIn, getTimeUntilExpiry, getTokenExpiry, isExpired, isTokenExpired, isValidJwtFormat, msToSeconds, secondsToMs, stringToBase64Url };
710
+ export { AuthKeeperKernel, EventBus, PluginRegistry, calculateExpiresAt, createAuthKeeper, formatTimeRemaining, generateCodeChallenge, generateCodeVerifier, generateRandomString, generateUuid, getExpiresIn, isExpired, msToSeconds, secondsToMs };
1349
711
  //# sourceMappingURL=index.js.map
1350
712
  //# sourceMappingURL=index.js.map