@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.cjs CHANGED
@@ -1,5 +1,7 @@
1
1
  'use strict';
2
2
 
3
+ var chunkLIPOAFHP_cjs = require('./chunk-LIPOAFHP.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 chunkLIPOAFHP_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 chunkLIPOAFHP_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 chunkLIPOAFHP_cjs.AuthError("CONFIG_ERROR", `Failed to install plugin "${name}"`, {
152
141
  cause: error,
153
142
  context: { pluginName: name }
154
143
  });
@@ -250,7 +239,6 @@ var AuthKeeperKernel = class {
250
239
  this.options = {
251
240
  autoRefresh: true,
252
241
  refreshThreshold: 60,
253
- syncTabs: true,
254
242
  ...options
255
243
  };
256
244
  this.pluginRegistry = new PluginRegistry();
@@ -302,14 +290,17 @@ var AuthKeeperKernel = class {
302
290
  setTokens(tokens) {
303
291
  const tokenStore = this.pluginRegistry.getApi("token-store");
304
292
  if (!tokenStore) {
305
- throw new AuthError("CONFIG_ERROR", "token-store plugin not installed");
293
+ throw new chunkLIPOAFHP_cjs.AuthError("CONFIG_ERROR", "token-store plugin not installed");
306
294
  }
307
295
  tokenStore.set(tokens);
308
- this.emit({
309
- type: "login",
310
- tokens,
311
- timestamp: Date.now()
312
- });
296
+ const refreshEngine = this.pluginRegistry.getApi("refresh-engine");
297
+ if (refreshEngine?.isApplyingRefresh?.() !== true) {
298
+ this.emit({
299
+ type: "login",
300
+ tokens,
301
+ timestamp: Date.now()
302
+ });
303
+ }
313
304
  if (this.options.autoRefresh && !this.isExpired()) {
314
305
  this.scheduleRefresh();
315
306
  }
@@ -342,6 +333,7 @@ var AuthKeeperKernel = class {
342
333
  * Clear all tokens
343
334
  */
344
335
  clearTokens() {
336
+ this.cancelScheduledRefresh();
345
337
  const tokenStore = this.pluginRegistry.getApi("token-store");
346
338
  if (tokenStore) {
347
339
  tokenStore.clear();
@@ -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 chunkLIPOAFHP_cjs.AuthError("CONFIG_ERROR", "refresh-engine plugin not installed");
447
439
  }
448
440
  return refreshEngine.refresh();
449
441
  }
@@ -523,10 +515,27 @@ var AuthKeeperKernel = class {
523
515
  // ============================================================================
524
516
  /**
525
517
  * Register and install a plugin
518
+ *
519
+ * The returned promise rejects when the plugin cannot be registered or
520
+ * installed. The failure is also emitted as an 'error' event (context
521
+ * 'plugin') and passed to `onError`, so a caller that does not await the
522
+ * promise does not get an unhandled rejection.
526
523
  */
527
- async register(plugin) {
524
+ register(plugin) {
525
+ const result = this.registerPlugin(plugin);
526
+ result.catch((error) => {
527
+ this.emit({ type: "error", error, context: "plugin", timestamp: Date.now() });
528
+ });
529
+ return result;
530
+ }
531
+ async registerPlugin(plugin) {
528
532
  this.pluginRegistry.register(plugin);
529
- await this.pluginRegistry.install(plugin.name, this);
533
+ try {
534
+ await this.pluginRegistry.install(plugin.name, this);
535
+ } catch (error) {
536
+ await this.pluginRegistry.uninstall(plugin.name);
537
+ throw error;
538
+ }
530
539
  }
531
540
  /**
532
541
  * Unregister a plugin
@@ -592,674 +601,26 @@ var AuthKeeperKernel = class {
592
601
  * Get current configuration
593
602
  */
594
603
  getOptions() {
595
- return { ...this.options };
596
- }
597
- };
598
-
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();
604
+ return { ...this.options, syncTabs: false };
680
605
  }
681
606
  };
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
607
 
1250
608
  // src/factory.ts
1251
609
  async function createAuthKeeper(options) {
1252
610
  const kernel = new AuthKeeperKernel(options);
1253
- await kernel.register(createTokenStorePlugin());
1254
- await kernel.register(createTokenDecoderPlugin());
611
+ await kernel.register(chunkLIPOAFHP_cjs.createTokenStorePlugin({ storage: chunkLIPOAFHP_cjs.resolveStorage(options.storage) }));
612
+ await kernel.register(chunkLIPOAFHP_cjs.createTokenDecoderPlugin());
1255
613
  await kernel.register(
1256
- createRefreshEnginePlugin({
614
+ chunkLIPOAFHP_cjs.createRefreshEnginePlugin({
1257
615
  refreshFn: options.refreshToken,
1258
616
  threshold: options.refreshThreshold
1259
617
  })
1260
618
  );
1261
- await kernel.register(createFetchInterceptorPlugin());
619
+ await kernel.register(chunkLIPOAFHP_cjs.createFetchInterceptorPlugin());
1262
620
  await kernel.init();
621
+ if (kernel.getAccessToken() && !kernel.isExpired()) {
622
+ kernel.scheduleRefresh();
623
+ }
1263
624
  return kernel;
1264
625
  }
1265
626
 
@@ -1319,7 +680,7 @@ function generateCodeVerifier(length = 64) {
1319
680
  const byteLength = Math.ceil(length * 3 / 4);
1320
681
  const randomBytes = new Uint8Array(byteLength);
1321
682
  crypto.getRandomValues(randomBytes);
1322
- const verifier = base64UrlEncode(randomBytes).substring(0, length);
683
+ const verifier = chunkLIPOAFHP_cjs.base64UrlEncode(randomBytes).substring(0, length);
1323
684
  return verifier;
1324
685
  }
1325
686
  async function generateCodeChallenge(codeVerifier) {
@@ -1327,13 +688,13 @@ async function generateCodeChallenge(codeVerifier) {
1327
688
  const data = encoder.encode(codeVerifier);
1328
689
  const hashBuffer = await crypto.subtle.digest("SHA-256", data);
1329
690
  const hashArray = new Uint8Array(hashBuffer);
1330
- return base64UrlEncode(hashArray);
691
+ return chunkLIPOAFHP_cjs.base64UrlEncode(hashArray);
1331
692
  }
1332
693
  function generateRandomString(length) {
1333
694
  const byteLength = Math.ceil(length * 3 / 4);
1334
695
  const randomBytes = new Uint8Array(byteLength);
1335
696
  crypto.getRandomValues(randomBytes);
1336
- return base64UrlEncode(randomBytes).substring(0, length);
697
+ return chunkLIPOAFHP_cjs.base64UrlEncode(randomBytes).substring(0, length);
1337
698
  }
1338
699
  function generateUuid() {
1339
700
  if (typeof crypto.randomUUID === "function") {
@@ -1347,43 +708,159 @@ function generateUuid() {
1347
708
  return `${hex.substring(0, 8)}-${hex.substring(8, 12)}-${hex.substring(12, 16)}-${hex.substring(16, 20)}-${hex.substring(20)}`;
1348
709
  }
1349
710
 
1350
- exports.AuthError = AuthError;
711
+ Object.defineProperty(exports, "AuthError", {
712
+ enumerable: true,
713
+ get: function () { return chunkLIPOAFHP_cjs.AuthError; }
714
+ });
715
+ Object.defineProperty(exports, "CookieStorageAdapter", {
716
+ enumerable: true,
717
+ get: function () { return chunkLIPOAFHP_cjs.CookieStorageAdapter; }
718
+ });
719
+ Object.defineProperty(exports, "FetchInterceptorPlugin", {
720
+ enumerable: true,
721
+ get: function () { return chunkLIPOAFHP_cjs.FetchInterceptorPlugin; }
722
+ });
723
+ Object.defineProperty(exports, "MemoryStorageAdapter", {
724
+ enumerable: true,
725
+ get: function () { return chunkLIPOAFHP_cjs.MemoryStorageAdapter; }
726
+ });
727
+ Object.defineProperty(exports, "RefreshEnginePlugin", {
728
+ enumerable: true,
729
+ get: function () { return chunkLIPOAFHP_cjs.RefreshEnginePlugin; }
730
+ });
731
+ Object.defineProperty(exports, "TokenDecoderPlugin", {
732
+ enumerable: true,
733
+ get: function () { return chunkLIPOAFHP_cjs.TokenDecoderPlugin; }
734
+ });
735
+ Object.defineProperty(exports, "TokenStorePlugin", {
736
+ enumerable: true,
737
+ get: function () { return chunkLIPOAFHP_cjs.TokenStorePlugin; }
738
+ });
739
+ Object.defineProperty(exports, "WebStorageAdapter", {
740
+ enumerable: true,
741
+ get: function () { return chunkLIPOAFHP_cjs.WebStorageAdapter; }
742
+ });
743
+ Object.defineProperty(exports, "base64UrlDecode", {
744
+ enumerable: true,
745
+ get: function () { return chunkLIPOAFHP_cjs.base64UrlDecode; }
746
+ });
747
+ Object.defineProperty(exports, "base64UrlDecodeToBytes", {
748
+ enumerable: true,
749
+ get: function () { return chunkLIPOAFHP_cjs.base64UrlDecodeToBytes; }
750
+ });
751
+ Object.defineProperty(exports, "base64UrlEncode", {
752
+ enumerable: true,
753
+ get: function () { return chunkLIPOAFHP_cjs.base64UrlEncode; }
754
+ });
755
+ Object.defineProperty(exports, "createFetchInterceptorPlugin", {
756
+ enumerable: true,
757
+ get: function () { return chunkLIPOAFHP_cjs.createFetchInterceptorPlugin; }
758
+ });
759
+ Object.defineProperty(exports, "createMemoryStorage", {
760
+ enumerable: true,
761
+ get: function () { return chunkLIPOAFHP_cjs.createMemoryStorage; }
762
+ });
763
+ Object.defineProperty(exports, "createRefreshEnginePlugin", {
764
+ enumerable: true,
765
+ get: function () { return chunkLIPOAFHP_cjs.createRefreshEnginePlugin; }
766
+ });
767
+ Object.defineProperty(exports, "createTokenDecoderPlugin", {
768
+ enumerable: true,
769
+ get: function () { return chunkLIPOAFHP_cjs.createTokenDecoderPlugin; }
770
+ });
771
+ Object.defineProperty(exports, "createTokenStorePlugin", {
772
+ enumerable: true,
773
+ get: function () { return chunkLIPOAFHP_cjs.createTokenStorePlugin; }
774
+ });
775
+ Object.defineProperty(exports, "decodeHeader", {
776
+ enumerable: true,
777
+ get: function () { return chunkLIPOAFHP_cjs.decodeHeader; }
778
+ });
779
+ Object.defineProperty(exports, "decodeJwt", {
780
+ enumerable: true,
781
+ get: function () { return chunkLIPOAFHP_cjs.decodeJwt; }
782
+ });
783
+ Object.defineProperty(exports, "decodePayload", {
784
+ enumerable: true,
785
+ get: function () { return chunkLIPOAFHP_cjs.decodePayload; }
786
+ });
787
+ Object.defineProperty(exports, "deleteCookie", {
788
+ enumerable: true,
789
+ get: function () { return chunkLIPOAFHP_cjs.deleteCookie; }
790
+ });
791
+ Object.defineProperty(exports, "getClaim", {
792
+ enumerable: true,
793
+ get: function () { return chunkLIPOAFHP_cjs.getClaim; }
794
+ });
795
+ Object.defineProperty(exports, "getClaims", {
796
+ enumerable: true,
797
+ get: function () { return chunkLIPOAFHP_cjs.getClaims; }
798
+ });
799
+ Object.defineProperty(exports, "getCookie", {
800
+ enumerable: true,
801
+ get: function () { return chunkLIPOAFHP_cjs.getCookie; }
802
+ });
803
+ Object.defineProperty(exports, "getTimeUntilExpiry", {
804
+ enumerable: true,
805
+ get: function () { return chunkLIPOAFHP_cjs.getTimeUntilExpiry; }
806
+ });
807
+ Object.defineProperty(exports, "getTokenExpiry", {
808
+ enumerable: true,
809
+ get: function () { return chunkLIPOAFHP_cjs.getTokenExpiry; }
810
+ });
811
+ Object.defineProperty(exports, "isStorageAvailable", {
812
+ enumerable: true,
813
+ get: function () { return chunkLIPOAFHP_cjs.isStorageAvailable; }
814
+ });
815
+ Object.defineProperty(exports, "isTokenExpired", {
816
+ enumerable: true,
817
+ get: function () { return chunkLIPOAFHP_cjs.isTokenExpired; }
818
+ });
819
+ Object.defineProperty(exports, "isValidJwtFormat", {
820
+ enumerable: true,
821
+ get: function () { return chunkLIPOAFHP_cjs.isValidJwtFormat; }
822
+ });
823
+ Object.defineProperty(exports, "parseCookies", {
824
+ enumerable: true,
825
+ get: function () { return chunkLIPOAFHP_cjs.parseCookies; }
826
+ });
827
+ Object.defineProperty(exports, "safeGetItem", {
828
+ enumerable: true,
829
+ get: function () { return chunkLIPOAFHP_cjs.safeGetItem; }
830
+ });
831
+ Object.defineProperty(exports, "safeRemoveItem", {
832
+ enumerable: true,
833
+ get: function () { return chunkLIPOAFHP_cjs.safeRemoveItem; }
834
+ });
835
+ Object.defineProperty(exports, "safeSetItem", {
836
+ enumerable: true,
837
+ get: function () { return chunkLIPOAFHP_cjs.safeSetItem; }
838
+ });
839
+ Object.defineProperty(exports, "serializeCookie", {
840
+ enumerable: true,
841
+ get: function () { return chunkLIPOAFHP_cjs.serializeCookie; }
842
+ });
843
+ Object.defineProperty(exports, "setCookie", {
844
+ enumerable: true,
845
+ get: function () { return chunkLIPOAFHP_cjs.setCookie; }
846
+ });
847
+ Object.defineProperty(exports, "stringToBase64Url", {
848
+ enumerable: true,
849
+ get: function () { return chunkLIPOAFHP_cjs.stringToBase64Url; }
850
+ });
1351
851
  exports.AuthKeeperKernel = AuthKeeperKernel;
1352
852
  exports.EventBus = EventBus;
1353
- exports.FetchInterceptorPlugin = FetchInterceptorPlugin;
1354
- exports.MemoryStorageAdapter = MemoryStorageAdapter;
1355
853
  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
854
  exports.calculateExpiresAt = calculateExpiresAt;
1363
855
  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
856
  exports.formatTimeRemaining = formatTimeRemaining;
1373
857
  exports.generateCodeChallenge = generateCodeChallenge;
1374
858
  exports.generateCodeVerifier = generateCodeVerifier;
1375
859
  exports.generateRandomString = generateRandomString;
1376
860
  exports.generateUuid = generateUuid;
1377
- exports.getClaim = getClaim;
1378
- exports.getClaims = getClaims;
1379
861
  exports.getExpiresIn = getExpiresIn;
1380
- exports.getTimeUntilExpiry = getTimeUntilExpiry;
1381
- exports.getTokenExpiry = getTokenExpiry;
1382
862
  exports.isExpired = isExpired;
1383
- exports.isTokenExpired = isTokenExpired;
1384
- exports.isValidJwtFormat = isValidJwtFormat;
1385
863
  exports.msToSeconds = msToSeconds;
1386
864
  exports.secondsToMs = secondsToMs;
1387
- exports.stringToBase64Url = stringToBase64Url;
1388
865
  //# sourceMappingURL=index.cjs.map
1389
866
  //# sourceMappingURL=index.cjs.map