@oxog/authkeeper 1.0.0 → 1.2.0

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