@oxog/authkeeper 1.4.0 → 1.5.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/CHANGELOG.md +18 -0
- package/README.md +72 -0
- package/dist/{auth-source-BaZ_-Fu7.d.cts → auth-source-CXqrhLDO.d.ts} +15 -2
- package/dist/{auth-source-Cm0R6C6I.d.ts → auth-source-rjMWiP1Q.d.cts} +15 -2
- package/dist/{chunk-KE7V52DI.js → chunk-7B77NZGY.js} +18 -8
- package/dist/chunk-7B77NZGY.js.map +1 -0
- package/dist/{chunk-CYCWWUCJ.js → chunk-DLCD3SBV.js} +2 -2
- package/dist/chunk-DLCD3SBV.js.map +1 -0
- package/dist/{chunk-KLT44YR2.cjs → chunk-LGZGECYE.cjs} +35 -8
- package/dist/chunk-LGZGECYE.cjs.map +1 -0
- package/dist/{chunk-SUGFPZ6O.js → chunk-UUQDRHGF.js} +33 -9
- package/dist/chunk-UUQDRHGF.js.map +1 -0
- package/dist/{chunk-EXV2RG6T.cjs → chunk-VVSZPARR.cjs} +28 -18
- package/dist/chunk-VVSZPARR.cjs.map +1 -0
- package/dist/{chunk-62XK5QLP.cjs → chunk-XGKVBZSF.cjs} +2 -2
- package/dist/chunk-XGKVBZSF.cjs.map +1 -0
- package/dist/{index-CuvfPscu.d.cts → index-C4pGS-TI.d.cts} +1 -1
- package/dist/{index-BF4j_buH.d.ts → index-CQwGO-Wk.d.ts} +1 -1
- package/dist/index.cjs +51 -55
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +7 -3
- package/dist/index.d.ts +7 -3
- package/dist/index.js +7 -11
- package/dist/index.js.map +1 -1
- package/dist/plugins/index.cjs +15 -15
- package/dist/plugins/index.d.cts +2 -2
- package/dist/plugins/index.d.ts +2 -2
- package/dist/plugins/index.js +2 -2
- package/dist/react/index.cjs +92 -8
- package/dist/react/index.cjs.map +1 -1
- package/dist/react/index.d.cts +98 -4
- package/dist/react/index.d.ts +98 -4
- package/dist/react/index.js +87 -7
- package/dist/react/index.js.map +1 -1
- package/dist/svelte/index.cjs +25 -9
- package/dist/svelte/index.cjs.map +1 -1
- package/dist/svelte/index.d.cts +40 -9
- package/dist/svelte/index.d.ts +40 -9
- package/dist/svelte/index.js +24 -10
- package/dist/svelte/index.js.map +1 -1
- package/dist/{types-Bmo8S8O4.d.cts → types-DMPBl-Ym.d.cts} +1 -1
- package/dist/{types-Bmo8S8O4.d.ts → types-DMPBl-Ym.d.ts} +1 -1
- package/dist/vue/index.cjs +36 -7
- package/dist/vue/index.cjs.map +1 -1
- package/dist/vue/index.d.cts +51 -3
- package/dist/vue/index.d.ts +51 -3
- package/dist/vue/index.js +35 -8
- package/dist/vue/index.js.map +1 -1
- package/package.json +8 -4
- package/dist/chunk-62XK5QLP.cjs.map +0 -1
- package/dist/chunk-CYCWWUCJ.js.map +0 -1
- package/dist/chunk-EXV2RG6T.cjs.map +0 -1
- package/dist/chunk-KE7V52DI.js.map +0 -1
- package/dist/chunk-KLT44YR2.cjs.map +0 -1
- package/dist/chunk-SUGFPZ6O.js.map +0 -1
package/dist/index.cjs
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
'use strict';
|
|
2
2
|
|
|
3
|
-
var
|
|
4
|
-
var
|
|
3
|
+
var chunkVVSZPARR_cjs = require('./chunk-VVSZPARR.cjs');
|
|
4
|
+
var chunkXGKVBZSF_cjs = require('./chunk-XGKVBZSF.cjs');
|
|
5
5
|
|
|
6
6
|
// src/kernel/event-bus.ts
|
|
7
7
|
var EventBus = class {
|
|
@@ -110,13 +110,9 @@ var PluginRegistry = class {
|
|
|
110
110
|
*/
|
|
111
111
|
register(plugin) {
|
|
112
112
|
if (this.plugins.has(plugin.name)) {
|
|
113
|
-
throw new
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
{
|
|
117
|
-
context: { pluginName: plugin.name }
|
|
118
|
-
}
|
|
119
|
-
);
|
|
113
|
+
throw new chunkXGKVBZSF_cjs.AuthError("CONFIG_ERROR", `Plugin "${plugin.name}" is already registered`, {
|
|
114
|
+
context: { pluginName: plugin.name }
|
|
115
|
+
});
|
|
120
116
|
}
|
|
121
117
|
const instance = {
|
|
122
118
|
plugin,
|
|
@@ -137,7 +133,7 @@ var PluginRegistry = class {
|
|
|
137
133
|
async install(name, kernel) {
|
|
138
134
|
const instance = this.plugins.get(name);
|
|
139
135
|
if (!instance) {
|
|
140
|
-
throw new
|
|
136
|
+
throw new chunkXGKVBZSF_cjs.AuthError("CONFIG_ERROR", `Plugin "${name}" not found`, {
|
|
141
137
|
context: { pluginName: name }
|
|
142
138
|
});
|
|
143
139
|
}
|
|
@@ -149,7 +145,7 @@ var PluginRegistry = class {
|
|
|
149
145
|
instance.api = api || null;
|
|
150
146
|
instance.installed = true;
|
|
151
147
|
} catch (error) {
|
|
152
|
-
throw new
|
|
148
|
+
throw new chunkXGKVBZSF_cjs.AuthError("CONFIG_ERROR", `Failed to install plugin "${name}"`, {
|
|
153
149
|
cause: error,
|
|
154
150
|
context: { pluginName: name }
|
|
155
151
|
});
|
|
@@ -302,7 +298,7 @@ var AuthKeeperKernel = class {
|
|
|
302
298
|
setTokens(tokens) {
|
|
303
299
|
const tokenStore = this.pluginRegistry.getApi("token-store");
|
|
304
300
|
if (!tokenStore) {
|
|
305
|
-
throw new
|
|
301
|
+
throw new chunkXGKVBZSF_cjs.AuthError("CONFIG_ERROR", "token-store plugin not installed");
|
|
306
302
|
}
|
|
307
303
|
tokenStore.set(tokens);
|
|
308
304
|
const refreshEngine = this.pluginRegistry.getApi("refresh-engine");
|
|
@@ -447,7 +443,7 @@ var AuthKeeperKernel = class {
|
|
|
447
443
|
async refresh() {
|
|
448
444
|
const refreshEngine = this.pluginRegistry.getApi("refresh-engine");
|
|
449
445
|
if (!refreshEngine) {
|
|
450
|
-
throw new
|
|
446
|
+
throw new chunkXGKVBZSF_cjs.AuthError("CONFIG_ERROR", "refresh-engine plugin not installed");
|
|
451
447
|
}
|
|
452
448
|
return refreshEngine.refresh();
|
|
453
449
|
}
|
|
@@ -620,15 +616,15 @@ var AuthKeeperKernel = class {
|
|
|
620
616
|
// src/factory.ts
|
|
621
617
|
async function createAuthKeeper(options) {
|
|
622
618
|
const kernel = new AuthKeeperKernel(options);
|
|
623
|
-
await kernel.register(
|
|
624
|
-
await kernel.register(
|
|
619
|
+
await kernel.register(chunkVVSZPARR_cjs.createTokenStorePlugin({ storage: chunkVVSZPARR_cjs.resolveStorage(options.storage) }));
|
|
620
|
+
await kernel.register(chunkVVSZPARR_cjs.createTokenDecoderPlugin());
|
|
625
621
|
await kernel.register(
|
|
626
|
-
|
|
622
|
+
chunkVVSZPARR_cjs.createRefreshEnginePlugin({
|
|
627
623
|
refreshFn: options.refreshToken,
|
|
628
624
|
threshold: options.refreshThreshold
|
|
629
625
|
})
|
|
630
626
|
);
|
|
631
|
-
await kernel.register(
|
|
627
|
+
await kernel.register(chunkVVSZPARR_cjs.createFetchInterceptorPlugin());
|
|
632
628
|
await kernel.init();
|
|
633
629
|
if (kernel.getAccessToken() && !kernel.isExpired()) {
|
|
634
630
|
kernel.scheduleRefresh();
|
|
@@ -695,7 +691,7 @@ function generateCodeVerifier(length = 64) {
|
|
|
695
691
|
const byteLength = Math.ceil(length * 3 / 4);
|
|
696
692
|
const randomBytes = new Uint8Array(byteLength);
|
|
697
693
|
crypto.getRandomValues(randomBytes);
|
|
698
|
-
const verifier =
|
|
694
|
+
const verifier = chunkVVSZPARR_cjs.base64UrlEncode(randomBytes).substring(0, length);
|
|
699
695
|
return verifier;
|
|
700
696
|
}
|
|
701
697
|
async function generateCodeChallenge(codeVerifier) {
|
|
@@ -703,13 +699,13 @@ async function generateCodeChallenge(codeVerifier) {
|
|
|
703
699
|
const data = encoder.encode(codeVerifier);
|
|
704
700
|
const hashBuffer = await crypto.subtle.digest("SHA-256", data);
|
|
705
701
|
const hashArray = new Uint8Array(hashBuffer);
|
|
706
|
-
return
|
|
702
|
+
return chunkVVSZPARR_cjs.base64UrlEncode(hashArray);
|
|
707
703
|
}
|
|
708
704
|
function generateRandomString(length) {
|
|
709
705
|
const byteLength = Math.ceil(length * 3 / 4);
|
|
710
706
|
const randomBytes = new Uint8Array(byteLength);
|
|
711
707
|
crypto.getRandomValues(randomBytes);
|
|
712
|
-
return
|
|
708
|
+
return chunkVVSZPARR_cjs.base64UrlEncode(randomBytes).substring(0, length);
|
|
713
709
|
}
|
|
714
710
|
function generateUuid() {
|
|
715
711
|
if (typeof crypto.randomUUID === "function") {
|
|
@@ -725,143 +721,143 @@ function generateUuid() {
|
|
|
725
721
|
|
|
726
722
|
Object.defineProperty(exports, "CookieStorageAdapter", {
|
|
727
723
|
enumerable: true,
|
|
728
|
-
get: function () { return
|
|
724
|
+
get: function () { return chunkVVSZPARR_cjs.CookieStorageAdapter; }
|
|
729
725
|
});
|
|
730
726
|
Object.defineProperty(exports, "FetchInterceptorPlugin", {
|
|
731
727
|
enumerable: true,
|
|
732
|
-
get: function () { return
|
|
728
|
+
get: function () { return chunkVVSZPARR_cjs.FetchInterceptorPlugin; }
|
|
733
729
|
});
|
|
734
730
|
Object.defineProperty(exports, "MemoryStorageAdapter", {
|
|
735
731
|
enumerable: true,
|
|
736
|
-
get: function () { return
|
|
732
|
+
get: function () { return chunkVVSZPARR_cjs.MemoryStorageAdapter; }
|
|
737
733
|
});
|
|
738
734
|
Object.defineProperty(exports, "RefreshEnginePlugin", {
|
|
739
735
|
enumerable: true,
|
|
740
|
-
get: function () { return
|
|
736
|
+
get: function () { return chunkVVSZPARR_cjs.RefreshEnginePlugin; }
|
|
741
737
|
});
|
|
742
738
|
Object.defineProperty(exports, "TokenDecoderPlugin", {
|
|
743
739
|
enumerable: true,
|
|
744
|
-
get: function () { return
|
|
740
|
+
get: function () { return chunkVVSZPARR_cjs.TokenDecoderPlugin; }
|
|
745
741
|
});
|
|
746
742
|
Object.defineProperty(exports, "TokenStorePlugin", {
|
|
747
743
|
enumerable: true,
|
|
748
|
-
get: function () { return
|
|
744
|
+
get: function () { return chunkVVSZPARR_cjs.TokenStorePlugin; }
|
|
749
745
|
});
|
|
750
746
|
Object.defineProperty(exports, "WebStorageAdapter", {
|
|
751
747
|
enumerable: true,
|
|
752
|
-
get: function () { return
|
|
748
|
+
get: function () { return chunkVVSZPARR_cjs.WebStorageAdapter; }
|
|
753
749
|
});
|
|
754
750
|
Object.defineProperty(exports, "base64UrlDecode", {
|
|
755
751
|
enumerable: true,
|
|
756
|
-
get: function () { return
|
|
752
|
+
get: function () { return chunkVVSZPARR_cjs.base64UrlDecode; }
|
|
757
753
|
});
|
|
758
754
|
Object.defineProperty(exports, "base64UrlDecodeToBytes", {
|
|
759
755
|
enumerable: true,
|
|
760
|
-
get: function () { return
|
|
756
|
+
get: function () { return chunkVVSZPARR_cjs.base64UrlDecodeToBytes; }
|
|
761
757
|
});
|
|
762
758
|
Object.defineProperty(exports, "base64UrlEncode", {
|
|
763
759
|
enumerable: true,
|
|
764
|
-
get: function () { return
|
|
760
|
+
get: function () { return chunkVVSZPARR_cjs.base64UrlEncode; }
|
|
765
761
|
});
|
|
766
762
|
Object.defineProperty(exports, "createFetchInterceptorPlugin", {
|
|
767
763
|
enumerable: true,
|
|
768
|
-
get: function () { return
|
|
764
|
+
get: function () { return chunkVVSZPARR_cjs.createFetchInterceptorPlugin; }
|
|
769
765
|
});
|
|
770
766
|
Object.defineProperty(exports, "createMemoryStorage", {
|
|
771
767
|
enumerable: true,
|
|
772
|
-
get: function () { return
|
|
768
|
+
get: function () { return chunkVVSZPARR_cjs.createMemoryStorage; }
|
|
773
769
|
});
|
|
774
770
|
Object.defineProperty(exports, "createRefreshEnginePlugin", {
|
|
775
771
|
enumerable: true,
|
|
776
|
-
get: function () { return
|
|
772
|
+
get: function () { return chunkVVSZPARR_cjs.createRefreshEnginePlugin; }
|
|
777
773
|
});
|
|
778
774
|
Object.defineProperty(exports, "createTokenDecoderPlugin", {
|
|
779
775
|
enumerable: true,
|
|
780
|
-
get: function () { return
|
|
776
|
+
get: function () { return chunkVVSZPARR_cjs.createTokenDecoderPlugin; }
|
|
781
777
|
});
|
|
782
778
|
Object.defineProperty(exports, "createTokenStorePlugin", {
|
|
783
779
|
enumerable: true,
|
|
784
|
-
get: function () { return
|
|
780
|
+
get: function () { return chunkVVSZPARR_cjs.createTokenStorePlugin; }
|
|
785
781
|
});
|
|
786
782
|
Object.defineProperty(exports, "decodeHeader", {
|
|
787
783
|
enumerable: true,
|
|
788
|
-
get: function () { return
|
|
784
|
+
get: function () { return chunkVVSZPARR_cjs.decodeHeader; }
|
|
789
785
|
});
|
|
790
786
|
Object.defineProperty(exports, "decodeJwt", {
|
|
791
787
|
enumerable: true,
|
|
792
|
-
get: function () { return
|
|
788
|
+
get: function () { return chunkVVSZPARR_cjs.decodeJwt; }
|
|
793
789
|
});
|
|
794
790
|
Object.defineProperty(exports, "decodePayload", {
|
|
795
791
|
enumerable: true,
|
|
796
|
-
get: function () { return
|
|
792
|
+
get: function () { return chunkVVSZPARR_cjs.decodePayload; }
|
|
797
793
|
});
|
|
798
794
|
Object.defineProperty(exports, "deleteCookie", {
|
|
799
795
|
enumerable: true,
|
|
800
|
-
get: function () { return
|
|
796
|
+
get: function () { return chunkVVSZPARR_cjs.deleteCookie; }
|
|
801
797
|
});
|
|
802
798
|
Object.defineProperty(exports, "getClaim", {
|
|
803
799
|
enumerable: true,
|
|
804
|
-
get: function () { return
|
|
800
|
+
get: function () { return chunkVVSZPARR_cjs.getClaim; }
|
|
805
801
|
});
|
|
806
802
|
Object.defineProperty(exports, "getClaims", {
|
|
807
803
|
enumerable: true,
|
|
808
|
-
get: function () { return
|
|
804
|
+
get: function () { return chunkVVSZPARR_cjs.getClaims; }
|
|
809
805
|
});
|
|
810
806
|
Object.defineProperty(exports, "getCookie", {
|
|
811
807
|
enumerable: true,
|
|
812
|
-
get: function () { return
|
|
808
|
+
get: function () { return chunkVVSZPARR_cjs.getCookie; }
|
|
813
809
|
});
|
|
814
810
|
Object.defineProperty(exports, "getTimeUntilExpiry", {
|
|
815
811
|
enumerable: true,
|
|
816
|
-
get: function () { return
|
|
812
|
+
get: function () { return chunkVVSZPARR_cjs.getTimeUntilExpiry; }
|
|
817
813
|
});
|
|
818
814
|
Object.defineProperty(exports, "getTokenExpiry", {
|
|
819
815
|
enumerable: true,
|
|
820
|
-
get: function () { return
|
|
816
|
+
get: function () { return chunkVVSZPARR_cjs.getTokenExpiry; }
|
|
821
817
|
});
|
|
822
818
|
Object.defineProperty(exports, "isStorageAvailable", {
|
|
823
819
|
enumerable: true,
|
|
824
|
-
get: function () { return
|
|
820
|
+
get: function () { return chunkVVSZPARR_cjs.isStorageAvailable; }
|
|
825
821
|
});
|
|
826
822
|
Object.defineProperty(exports, "isTokenExpired", {
|
|
827
823
|
enumerable: true,
|
|
828
|
-
get: function () { return
|
|
824
|
+
get: function () { return chunkVVSZPARR_cjs.isTokenExpired; }
|
|
829
825
|
});
|
|
830
826
|
Object.defineProperty(exports, "isValidJwtFormat", {
|
|
831
827
|
enumerable: true,
|
|
832
|
-
get: function () { return
|
|
828
|
+
get: function () { return chunkVVSZPARR_cjs.isValidJwtFormat; }
|
|
833
829
|
});
|
|
834
830
|
Object.defineProperty(exports, "parseCookies", {
|
|
835
831
|
enumerable: true,
|
|
836
|
-
get: function () { return
|
|
832
|
+
get: function () { return chunkVVSZPARR_cjs.parseCookies; }
|
|
837
833
|
});
|
|
838
834
|
Object.defineProperty(exports, "safeGetItem", {
|
|
839
835
|
enumerable: true,
|
|
840
|
-
get: function () { return
|
|
836
|
+
get: function () { return chunkVVSZPARR_cjs.safeGetItem; }
|
|
841
837
|
});
|
|
842
838
|
Object.defineProperty(exports, "safeRemoveItem", {
|
|
843
839
|
enumerable: true,
|
|
844
|
-
get: function () { return
|
|
840
|
+
get: function () { return chunkVVSZPARR_cjs.safeRemoveItem; }
|
|
845
841
|
});
|
|
846
842
|
Object.defineProperty(exports, "safeSetItem", {
|
|
847
843
|
enumerable: true,
|
|
848
|
-
get: function () { return
|
|
844
|
+
get: function () { return chunkVVSZPARR_cjs.safeSetItem; }
|
|
849
845
|
});
|
|
850
846
|
Object.defineProperty(exports, "serializeCookie", {
|
|
851
847
|
enumerable: true,
|
|
852
|
-
get: function () { return
|
|
848
|
+
get: function () { return chunkVVSZPARR_cjs.serializeCookie; }
|
|
853
849
|
});
|
|
854
850
|
Object.defineProperty(exports, "setCookie", {
|
|
855
851
|
enumerable: true,
|
|
856
|
-
get: function () { return
|
|
852
|
+
get: function () { return chunkVVSZPARR_cjs.setCookie; }
|
|
857
853
|
});
|
|
858
854
|
Object.defineProperty(exports, "stringToBase64Url", {
|
|
859
855
|
enumerable: true,
|
|
860
|
-
get: function () { return
|
|
856
|
+
get: function () { return chunkVVSZPARR_cjs.stringToBase64Url; }
|
|
861
857
|
});
|
|
862
858
|
Object.defineProperty(exports, "AuthError", {
|
|
863
859
|
enumerable: true,
|
|
864
|
-
get: function () { return
|
|
860
|
+
get: function () { return chunkXGKVBZSF_cjs.AuthError; }
|
|
865
861
|
});
|
|
866
862
|
exports.AuthKeeperKernel = AuthKeeperKernel;
|
|
867
863
|
exports.EventBus = EventBus;
|
package/dist/index.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/kernel/event-bus.ts","../src/kernel/plugin-registry.ts","../src/kernel/kernel.ts","../src/factory.ts","../src/utils/time.ts","../src/utils/crypto.ts"],"names":["AuthError","fetch","createTokenStorePlugin","resolveStorage","createTokenDecoderPlugin","createRefreshEnginePlugin","createFetchInterceptorPlugin","base64UrlEncode"],"mappings":";;;;;;AAeO,IAAM,WAAN,MAAe;AAAA,EAAf,WAAA,GAAA;AACL,IAAA,IAAA,CAAQ,QAAA,uBAAqD,GAAA,EAAI;AAEjE;AAAA,IAAA,IAAA,CAAQ,OAAA,uBAAkD,GAAA,EAAI;AAAA,EAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAS9D,EAAA,CAAwB,WAAc,OAAA,EAAuC;AAE3E,IAAA,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;AAOO,SAAS,YAAA,GAAuB;AAErC,EAAA,IAAI,OAAO,MAAA,CAAO,UAAA,KAAe,UAAA,EAAY;AAC3C,IAAA,OAAO,OAAO,UAAA,EAAW;AAAA,EAC3B;AAGA,EAAA,MAAM,KAAA,GAAQ,IAAI,UAAA,CAAW,EAAE,CAAA;AAC/B,EAAA,MAAA,CAAO,gBAAgB,KAAK,CAAA;AAG5B,EAAA,KAAA,CAAM,CAAC,CAAA,GAAM,KAAA,CAAM,CAAC,IAAe,EAAA,GAAQ,EAAA;AAC3C,EAAA,KAAA,CAAM,CAAC,CAAA,GAAM,KAAA,CAAM,CAAC,IAAe,EAAA,GAAQ,GAAA;AAG3C,EAAA,MAAM,MAAM,KAAA,CAAM,IAAA,CAAK,KAAK,CAAA,CACzB,GAAA,CAAI,CAAC,CAAA,KAAM,CAAA,CAAE,QAAA,CAAS,EAAE,EAAE,QAAA,CAAS,CAAA,EAAG,GAAG,CAAC,CAAA,CAC1C,KAAK,EAAE,CAAA;AAEV,EAAA,OAAO,CAAA,EAAG,GAAA,CAAI,SAAA,CAAU,CAAA,EAAG,CAAC,CAAC,CAAA,CAAA,EAAI,GAAA,CAAI,SAAA,CAAU,CAAA,EAAG,EAAE,CAAC,CAAA,CAAA,EAAI,GAAA,CAAI,SAAA,CAAU,EAAA,EAAI,EAAE,CAAC,CAAA,CAAA,EAAI,GAAA,CAAI,SAAA,CAAU,EAAA,EAAI,EAAE,CAAC,CAAA,CAAA,EAAI,GAAA,CAAI,SAAA,CAAU,EAAE,CAAC,CAAA,CAAA;AAC9H","file":"index.cjs","sourcesContent":["/**\n * Event Bus\n *\n * Pub/sub event system for kernel and plugins.\n * Type-safe event handling with automatic unsubscribe.\n */\n\nimport type { AuthEvent, EventType, EventHandler, Unsubscribe } from '../types'\n\n/** Handler type as stored internally (handlers are keyed by event type) */\ntype AnyEventHandler = (event: AuthEvent) => void\n\n/**\n * EventBus class for managing event subscriptions and emissions\n */\nexport class EventBus {\n private handlers: Map<EventType, Set<AnyEventHandler>> = new Map()\n /** Deliveries scheduled by emit() and not run yet (cancelled by clear()) */\n private pending: Set<ReturnType<typeof setTimeout>> = new Set()\n\n /**\n * Subscribe to an event\n *\n * @param eventType - Type of event to listen for\n * @param handler - Handler function to call when event is emitted\n * @returns Unsubscribe function\n */\n on<E extends EventType>(eventType: E, handler: EventHandler<E>): Unsubscribe {\n // Get or create handler set for this event type\n let handlerSet = this.handlers.get(eventType)\n if (!handlerSet) {\n handlerSet = new Set()\n this.handlers.set(eventType, handlerSet)\n }\n\n handlerSet.add(handler as AnyEventHandler)\n\n // Return unsubscribe function\n return () => this.off(eventType, handler)\n }\n\n /**\n * Unsubscribe from an event\n *\n * @param eventType - Type of event to stop listening for\n * @param handler - Handler function to remove\n */\n off<E extends EventType>(eventType: E, handler: EventHandler<E>): void {\n const handlerSet = this.handlers.get(eventType)\n if (handlerSet) {\n handlerSet.delete(handler as AnyEventHandler)\n\n // Clean up empty sets\n if (handlerSet.size === 0) {\n this.handlers.delete(eventType)\n }\n }\n }\n\n /**\n * Emit an event to all subscribers\n *\n * Handlers are executed asynchronously in the next tick to prevent blocking.\n * The event goes to the handlers subscribed when it is emitted (a handler\n * added later does not receive it) that are still subscribed at delivery.\n *\n * @param event - Event to emit\n */\n emit(event: AuthEvent): void {\n const handlerSet = this.handlers.get(event.type)\n if (!handlerSet || handlerSet.size === 0) {\n return\n }\n const recipients = Array.from(handlerSet)\n\n // Execute handlers in next tick to prevent blocking\n const timer = setTimeout(() => {\n this.pending.delete(timer)\n recipients.forEach((handler) => {\n // Unsubscribed meanwhile (also by an earlier handler of this event)\n if (this.handlers.get(event.type)?.has(handler) !== true) return\n try {\n handler(event)\n } catch (error) {\n // Log error but don't throw to prevent one handler from breaking others\n console.error(`[AuthKeeper] Error in event handler for ${event.type}:`, error)\n }\n })\n }, 0)\n this.pending.add(timer)\n }\n\n /**\n * Remove all event handlers and cancel deliveries that have not run yet\n * (no handler runs after the kernel is destroyed)\n */\n clear(): void {\n this.pending.forEach((timer) => clearTimeout(timer))\n this.pending.clear()\n this.handlers.clear()\n }\n\n /**\n * Get count of handlers for an event type\n *\n * @param eventType - Event type to count handlers for\n * @returns Number of handlers\n */\n getHandlerCount(eventType: EventType): number {\n return this.handlers.get(eventType)?.size || 0\n }\n\n /**\n * Get all event types that have handlers\n *\n * @returns Array of event types\n */\n getActiveEventTypes(): EventType[] {\n return Array.from(this.handlers.keys())\n }\n}\n","/**\n * Plugin Registry\n *\n * Manages plugin registration, installation, and lifecycle.\n */\n\nimport { AuthError, type Plugin, type PluginInfo, type AuthKeeper } from '../types'\n\n/**\n * Plugin instance with metadata\n */\ninterface PluginInstance {\n plugin: Plugin\n installed: boolean\n api: unknown\n}\n\n/**\n * PluginRegistry class for managing plugins\n */\nexport class PluginRegistry {\n private plugins: Map<string, PluginInstance> = new Map()\n\n /**\n * Register a plugin\n *\n * @param plugin - Plugin to register\n * @throws {AuthError} If plugin with same name already registered\n */\n register(plugin: Plugin): void {\n if (this.plugins.has(plugin.name)) {\n throw new AuthError(\n 'CONFIG_ERROR',\n `Plugin \"${plugin.name}\" is already registered`,\n {\n context: { pluginName: plugin.name },\n }\n )\n }\n\n const instance: PluginInstance = {\n plugin,\n installed: false,\n api: null,\n }\n\n this.plugins.set(plugin.name, instance)\n }\n\n /**\n * Install a plugin\n *\n * Calls the plugin's install method and stores the returned API.\n *\n * @param name - Plugin name\n * @param kernel - Kernel instance to pass to plugin\n * @throws {AuthError} If plugin not found or already installed\n */\n async install(name: string, kernel: AuthKeeper): Promise<void> {\n const instance = this.plugins.get(name)\n\n if (!instance) {\n throw new AuthError('CONFIG_ERROR', `Plugin \"${name}\" not found`, {\n context: { pluginName: name },\n })\n }\n\n if (instance.installed) {\n // Already installed, skip\n return\n }\n\n try {\n // Call plugin's install method\n const api: unknown = await instance.plugin.install(kernel)\n instance.api = api || null\n instance.installed = true\n } catch (error) {\n throw new AuthError('CONFIG_ERROR', `Failed to install plugin \"${name}\"`, {\n cause: error as Error,\n context: { pluginName: name },\n })\n }\n }\n\n /**\n * Uninstall a plugin\n *\n * Calls the plugin's uninstall method if it exists.\n *\n * @param name - Plugin name\n */\n async uninstall(name: string): Promise<void> {\n const instance = this.plugins.get(name)\n\n if (!instance) {\n // Plugin not found, nothing to uninstall\n return\n }\n\n if (instance.installed && instance.plugin.uninstall) {\n try {\n await instance.plugin.uninstall()\n } catch (error) {\n console.error(`[AuthKeeper] Error uninstalling plugin \"${name}\":`, error)\n }\n }\n\n this.plugins.delete(name)\n }\n\n /**\n * Get a plugin by name\n *\n * @param name - Plugin name\n * @returns Plugin or undefined if not found\n */\n get<P extends Plugin>(name: string): P | undefined {\n const instance = this.plugins.get(name)\n return instance?.plugin as P | undefined\n }\n\n /**\n * Get plugin API by name\n *\n * @param name - Plugin name\n * @returns Plugin API or undefined if not found\n */\n getApi<T = unknown>(name: string): T | undefined {\n const instance = this.plugins.get(name)\n return instance?.api as T | undefined\n }\n\n /**\n * Check if a plugin is registered\n *\n * @param name - Plugin name\n * @returns true if plugin is registered\n */\n has(name: string): boolean {\n return this.plugins.has(name)\n }\n\n /**\n * Check if a plugin is installed\n *\n * @param name - Plugin name\n * @returns true if plugin is installed\n */\n isInstalled(name: string): boolean {\n const instance = this.plugins.get(name)\n return instance?.installed || false\n }\n\n /**\n * List all plugins\n *\n * @returns Array of plugin information\n */\n list(): PluginInfo[] {\n return Array.from(this.plugins.entries()).map(([name, instance]) => ({\n name,\n version: instance.plugin.version,\n type: instance.plugin.type,\n enabled: instance.installed,\n }))\n }\n\n /**\n * Get all plugin names\n *\n * @returns Array of plugin names\n */\n getNames(): string[] {\n return Array.from(this.plugins.keys())\n }\n\n /**\n * Clear all plugins\n */\n clear(): void {\n this.plugins.clear()\n }\n}\n","/**\n * AuthKeeper Kernel\n *\n * The micro-kernel that orchestrates plugins and manages auth state.\n * Most functionality is delegated to core plugins.\n */\n\nimport { EventBus } from './event-bus'\nimport { PluginRegistry } from './plugin-registry'\nimport {\n AuthError,\n type AuthKeeper,\n type KernelOptions,\n type Plugin,\n type PluginInfo,\n type TokenSet,\n type TokenPayload,\n type LogoutOptions,\n type AuthFetch,\n type FetchInterceptorOptions,\n type EventType,\n type EventHandler,\n type Unsubscribe,\n type AuthEvent,\n} from '../types'\nimport type {\n TokenStoreAPI,\n TokenDecoderAPI,\n RefreshEngineAPI,\n FetchInterceptorAPI,\n} from '../plugins/core'\n\n/**\n * AuthKeeperKernel - Main kernel implementation\n */\nexport class AuthKeeperKernel implements AuthKeeper {\n private pluginRegistry: PluginRegistry\n private eventBus: EventBus\n private options: KernelOptions\n private initialized: boolean = false\n\n constructor(options: KernelOptions) {\n this.options = {\n autoRefresh: true,\n refreshThreshold: 60,\n ...options,\n }\n\n this.pluginRegistry = new PluginRegistry()\n this.eventBus = new EventBus()\n }\n\n // ============================================================================\n // Lifecycle\n // ============================================================================\n\n /**\n * Initialize the kernel\n *\n * 1. Install core plugins\n * 2. Install user-provided plugins\n * 3. Load tokens from storage\n * 4. Schedule refresh if authenticated\n */\n async init(): Promise<void> {\n if (this.initialized) {\n return\n }\n\n // Core plugins will be installed in Phase 4\n // For now, we just mark as initialized\n\n // Install user-provided plugins\n if (this.options.plugins) {\n for (const plugin of this.options.plugins) {\n await this.register(plugin)\n }\n }\n\n this.initialized = true\n }\n\n /**\n * Destroy the kernel and cleanup\n */\n destroy(): void {\n // Cancel any scheduled refreshes\n this.cancelScheduledRefresh()\n\n // Clear event handlers\n this.eventBus.clear()\n\n // Uninstall all plugins\n const pluginNames = this.pluginRegistry.getNames()\n for (const name of pluginNames) {\n // Not awaited: uninstall() catches plugin errors and destroy() stays synchronous\n void this.pluginRegistry.uninstall(name)\n }\n\n this.pluginRegistry.clear()\n this.initialized = false\n }\n\n // ============================================================================\n // Token Management\n // ============================================================================\n\n /**\n * Set authentication tokens\n *\n * Delegates to token-store plugin.\n */\n setTokens(tokens: TokenSet): void {\n const tokenStore = this.pluginRegistry.getApi<TokenStoreAPI>('token-store')\n if (!tokenStore) {\n throw new AuthError('CONFIG_ERROR', 'token-store plugin not installed')\n }\n\n tokenStore.set(tokens)\n\n // Emit login event - but not when the refresh engine is storing the\n // result of a token refresh (that is reported as a 'refresh' event)\n const refreshEngine = this.pluginRegistry.getApi<RefreshEngineAPI>('refresh-engine')\n if (refreshEngine?.isApplyingRefresh?.() !== true) {\n this.emit({\n type: 'login',\n tokens,\n timestamp: Date.now(),\n })\n }\n\n // Schedule auto-refresh if enabled\n if (this.options.autoRefresh && !this.isExpired()) {\n this.scheduleRefresh()\n }\n }\n\n /**\n * Get access token\n *\n * Delegates to token-store plugin.\n */\n getAccessToken(): string | null {\n const tokenStore = this.pluginRegistry.getApi<TokenStoreAPI>('token-store')\n if (!tokenStore) {\n return null\n }\n\n return tokenStore.getAccessToken()\n }\n\n /**\n * Get refresh token\n *\n * Delegates to token-store plugin.\n */\n getRefreshToken(): string | null {\n const tokenStore = this.pluginRegistry.getApi<TokenStoreAPI>('token-store')\n if (!tokenStore) {\n return null\n }\n\n return tokenStore.getRefreshToken()\n }\n\n /**\n * Clear all tokens\n */\n clearTokens(): void {\n // Nothing left to refresh: a pending scheduled refresh would only fail\n // with REFRESH_TOKEN_MISSING\n this.cancelScheduledRefresh()\n\n const tokenStore = this.pluginRegistry.getApi<TokenStoreAPI>('token-store')\n if (tokenStore) {\n tokenStore.clear()\n }\n }\n\n // ============================================================================\n // Auth State\n // ============================================================================\n\n /**\n * Check if user is authenticated\n */\n isAuthenticated(): boolean {\n const accessToken = this.getAccessToken()\n return accessToken !== null && !this.isExpired()\n }\n\n /**\n * Check if token is expired\n *\n * Delegates to token-store plugin.\n */\n isExpired(): boolean {\n const tokenStore = this.pluginRegistry.getApi<TokenStoreAPI>('token-store')\n if (!tokenStore) {\n return true\n }\n\n return tokenStore.isExpired()\n }\n\n /**\n * Get token expiration date\n *\n * Delegates to token-store plugin.\n */\n getExpiresAt(): Date | null {\n const tokenStore = this.pluginRegistry.getApi<TokenStoreAPI>('token-store')\n if (!tokenStore) {\n return null\n }\n\n return tokenStore.getExpiresAt()\n }\n\n /**\n * Get time until expiry in milliseconds\n *\n * Delegates to token-store plugin.\n */\n getTimeUntilExpiry(): number | null {\n const tokenStore = this.pluginRegistry.getApi<TokenStoreAPI>('token-store')\n if (!tokenStore) {\n return null\n }\n\n return tokenStore.getExpiresIn()\n }\n\n // ============================================================================\n // Token Decoding\n // ============================================================================\n\n /**\n * Decode token payload\n *\n * Delegates to token-decoder plugin.\n */\n decode<T = TokenPayload>(): T | null {\n const tokenDecoder = this.pluginRegistry.getApi<TokenDecoderAPI>('token-decoder')\n if (!tokenDecoder) {\n return null\n }\n\n return tokenDecoder.decode<T>()\n }\n\n /**\n * Get specific claim from token\n *\n * Delegates to token-decoder plugin.\n */\n getClaim<K extends keyof TokenPayload>(key: K): TokenPayload[K] | undefined {\n const tokenDecoder = this.pluginRegistry.getApi<TokenDecoderAPI>('token-decoder')\n if (!tokenDecoder) {\n return undefined\n }\n\n return tokenDecoder.getClaim(key)\n }\n\n /**\n * Get multiple claims from token\n *\n * Delegates to token-decoder plugin.\n */\n getClaims<K extends keyof TokenPayload>(keys: K[]): Pick<TokenPayload, K> {\n const tokenDecoder = this.pluginRegistry.getApi<TokenDecoderAPI>('token-decoder')\n if (!tokenDecoder) {\n return {} as Pick<TokenPayload, K>\n }\n\n return tokenDecoder.getClaims(keys)\n }\n\n // ============================================================================\n // Refresh\n // ============================================================================\n\n /**\n * Manually refresh tokens\n *\n * Delegates to refresh-engine plugin.\n */\n async refresh(): Promise<TokenSet> {\n const refreshEngine = this.pluginRegistry.getApi<RefreshEngineAPI>('refresh-engine')\n if (!refreshEngine) {\n throw new AuthError('CONFIG_ERROR', 'refresh-engine plugin not installed')\n }\n\n return refreshEngine.refresh()\n }\n\n /**\n * Schedule automatic refresh\n *\n * Delegates to refresh-engine plugin.\n */\n scheduleRefresh(): void {\n if (!this.options.autoRefresh) {\n return\n }\n\n const refreshEngine = this.pluginRegistry.getApi<RefreshEngineAPI>('refresh-engine')\n if (refreshEngine) {\n refreshEngine.scheduleRefresh()\n }\n }\n\n /**\n * Cancel scheduled refresh\n *\n * Delegates to refresh-engine plugin.\n */\n cancelScheduledRefresh(): void {\n const refreshEngine = this.pluginRegistry.getApi<RefreshEngineAPI>('refresh-engine')\n if (refreshEngine) {\n refreshEngine.cancelScheduledRefresh()\n }\n }\n\n // ============================================================================\n // Logout\n // ============================================================================\n\n /**\n * Logout user\n *\n * Clears tokens and emits logout event.\n */\n logout(options: LogoutOptions = {}): void {\n // Cancel scheduled refresh\n this.cancelScheduledRefresh()\n\n // Clear tokens\n this.clearTokens()\n\n // Emit logout event\n this.emit({\n type: 'logout',\n reason: 'manual',\n timestamp: Date.now(),\n })\n\n // Handle redirect if specified\n if (options.redirect && typeof window !== 'undefined') {\n window.location.href = options.redirect\n }\n }\n\n // ============================================================================\n // Interceptors\n // ============================================================================\n\n /**\n * Create authenticated fetch function\n *\n * Delegates to fetch-interceptor plugin.\n */\n createFetch(options?: FetchInterceptorOptions): AuthFetch {\n const fetchInterceptor = this.pluginRegistry.getApi<FetchInterceptorAPI>('fetch-interceptor')\n if (!fetchInterceptor) {\n // Return regular fetch if plugin not installed\n return fetch.bind(globalThis)\n }\n\n return fetchInterceptor.createFetch(options)\n }\n\n /**\n * Wrap global fetch with auth\n *\n * Delegates to fetch-interceptor plugin.\n */\n wrapFetch(fetch: typeof globalThis.fetch): void {\n const fetchInterceptor = this.pluginRegistry.getApi<FetchInterceptorAPI>('fetch-interceptor')\n if (fetchInterceptor) {\n fetchInterceptor.wrapFetch(fetch)\n }\n }\n\n // ============================================================================\n // Plugin Management\n // ============================================================================\n\n /**\n * Register and install a plugin\n *\n * The returned promise rejects when the plugin cannot be registered or\n * installed. The failure is also emitted as an 'error' event (context\n * 'plugin') and passed to `onError`, so a caller that does not await the\n * promise does not get an unhandled rejection.\n */\n register(plugin: Plugin): Promise<void> {\n const result = this.registerPlugin(plugin)\n result.catch((error: AuthError) => {\n // PluginRegistry only throws AuthError (CONFIG_ERROR)\n this.emit({ type: 'error', error, context: 'plugin', timestamp: Date.now() })\n })\n return result\n }\n\n private async registerPlugin(plugin: Plugin): Promise<void> {\n this.pluginRegistry.register(plugin)\n try {\n await this.pluginRegistry.install(plugin.name, this)\n } catch (error) {\n // Drop the half-registered plugin so it can be registered again\n await this.pluginRegistry.uninstall(plugin.name)\n throw error\n }\n }\n\n /**\n * Unregister a plugin\n */\n async unregister(pluginName: string): Promise<void> {\n await this.pluginRegistry.uninstall(pluginName)\n }\n\n /**\n * Get plugin by name\n */\n getPlugin<P extends Plugin>(name: string): P | undefined {\n return this.pluginRegistry.get<P>(name)\n }\n\n /**\n * List all plugins\n */\n listPlugins(): PluginInfo[] {\n return this.pluginRegistry.list()\n }\n\n // ============================================================================\n // Event System\n // ============================================================================\n\n /**\n * Emit an event\n */\n emit(event: AuthEvent): void {\n this.eventBus.emit(event)\n\n // Call global error handler if it's an error event\n if (event.type === 'error' && this.options.onError) {\n this.options.onError(event.error)\n }\n }\n\n /**\n * Subscribe to events\n */\n on<E extends EventType>(eventType: E, handler: EventHandler<E>): Unsubscribe {\n return this.eventBus.on(eventType, handler)\n }\n\n /**\n * Unsubscribe from events\n */\n off<E extends EventType>(eventType: E, handler: EventHandler<E>): void {\n this.eventBus.off(eventType, handler)\n }\n\n // ============================================================================\n // Configuration\n // ============================================================================\n\n /**\n * Update configuration\n */\n configure(options: Partial<KernelOptions>): void {\n this.options = {\n ...this.options,\n ...options,\n }\n\n // Update refresh engine threshold if changed\n if (options.refreshThreshold !== undefined) {\n const refreshEngine = this.pluginRegistry.getApi<RefreshEngineAPI>('refresh-engine')\n if (refreshEngine && refreshEngine.setThreshold) {\n refreshEngine.setThreshold(options.refreshThreshold)\n }\n }\n }\n\n /**\n * Get current configuration\n */\n getOptions(): KernelOptions {\n // Multi-tab sync is not implemented: report the effective value\n return { ...this.options, syncTabs: false }\n }\n}\n","/**\n * Factory Function\n *\n * Creates and initializes an AuthKeeper instance with core plugins.\n */\n\nimport { AuthKeeperKernel } from './kernel'\nimport {\n resolveStorage,\n createTokenStorePlugin,\n createTokenDecoderPlugin,\n createRefreshEnginePlugin,\n createFetchInterceptorPlugin,\n} from './plugins/core'\nimport type { AuthKeeper, KernelOptions } from './types'\n\n/**\n * Create an AuthKeeper instance\n *\n * Automatically installs core plugins:\n * - token-store: Token state management\n * - token-decoder: JWT decoding\n * - refresh-engine: Auto-refresh with queue\n * - storage-memory: Default secure storage\n * - fetch-interceptor: Auth header injection and 401 retry\n *\n * @param options - Configuration options\n * @returns AuthKeeper instance\n *\n * @example\n * ```typescript\n * const auth = createAuthKeeper({\n * storage: 'memory',\n * refreshToken: async (token) => {\n * const res = await fetch('/api/auth/refresh', {\n * method: 'POST',\n * body: JSON.stringify({ refreshToken: token }),\n * })\n * return res.json()\n * },\n * autoRefresh: true,\n * refreshThreshold: 60,\n * })\n *\n * await auth.init()\n * ```\n */\nexport async function createAuthKeeper(options: KernelOptions): Promise<AuthKeeper> {\n // Create kernel\n const kernel = new AuthKeeperKernel(options)\n\n // Register and install core plugins\n // 1. token-store (restores persisted tokens from the configured storage)\n await kernel.register(createTokenStorePlugin({ storage: resolveStorage(options.storage) }))\n\n // 2. token-decoder\n await kernel.register(createTokenDecoderPlugin())\n\n // 3. refresh-engine\n await kernel.register(\n createRefreshEnginePlugin({\n refreshFn: options.refreshToken,\n threshold: options.refreshThreshold,\n })\n )\n\n // 5. fetch-interceptor\n await kernel.register(createFetchInterceptorPlugin())\n\n // Initialize kernel\n await kernel.init()\n\n // Resume auto-refresh for tokens restored from storage\n if (kernel.getAccessToken() && !kernel.isExpired()) {\n kernel.scheduleRefresh()\n } else if (\n kernel.getAccessToken() &&\n kernel.getRefreshToken() &&\n kernel.getOptions().autoRefresh !== false\n ) {\n // Restored tokens already expired: refresh them in the background\n // (`await auth.refresh()` joins this refresh). A failure is reported as\n // an 'error' event / onError, like any refresh failure.\n kernel.refresh().catch(() => {})\n }\n\n return kernel\n}\n","/**\n * Time and expiry utilities\n *\n * Helper functions for working with token expiration times.\n */\n\n/**\n * Check if a timestamp is expired\n *\n * @param expiresAt - Expiration timestamp in milliseconds\n * @param bufferMs - Consider expired if within this many milliseconds (default: 0)\n * @returns true if expired\n */\nexport function isExpired(expiresAt: number | null | undefined, bufferMs: number = 0): boolean {\n if (!expiresAt) {\n return false\n }\n\n const now = Date.now()\n return now >= expiresAt - bufferMs\n}\n\n/**\n * Get time until expiry in milliseconds\n *\n * @param expiresAt - Expiration timestamp in milliseconds\n * @returns Milliseconds until expiry, or null if no expiry. Returns 0 if already expired.\n */\nexport function getExpiresIn(expiresAt: number | null | undefined): number | null {\n if (!expiresAt) {\n return null\n }\n\n const now = Date.now()\n const timeUntil = expiresAt - now\n return Math.max(0, timeUntil)\n}\n\n/**\n * Convert seconds to milliseconds\n *\n * @param seconds - Time in seconds\n * @returns Time in milliseconds\n */\nexport function secondsToMs(seconds: number): number {\n return seconds * 1000\n}\n\n/**\n * Convert milliseconds to seconds\n *\n * @param ms - Time in milliseconds\n * @returns Time in seconds\n */\nexport function msToSeconds(ms: number): number {\n return Math.floor(ms / 1000)\n}\n\n/**\n * Calculate expiry timestamp from expiresIn seconds\n *\n * @param expiresIn - Seconds until expiry\n * @returns Expiry timestamp in milliseconds\n */\nexport function calculateExpiresAt(expiresIn: number): number {\n return Date.now() + secondsToMs(expiresIn)\n}\n\n/**\n * Format time remaining as human-readable string\n *\n * @param ms - Milliseconds\n * @returns Formatted string like \"5m 30s\" or \"2h 15m\"\n */\nexport function formatTimeRemaining(ms: number): string {\n if (ms <= 0) {\n return 'expired'\n }\n\n const seconds = Math.floor(ms / 1000)\n const minutes = Math.floor(seconds / 60)\n const hours = Math.floor(minutes / 60)\n const days = Math.floor(hours / 24)\n\n if (days > 0) {\n const remainingHours = hours % 24\n return remainingHours > 0 ? `${days}d ${remainingHours}h` : `${days}d`\n }\n\n if (hours > 0) {\n const remainingMinutes = minutes % 60\n return remainingMinutes > 0 ? `${hours}h ${remainingMinutes}m` : `${hours}h`\n }\n\n if (minutes > 0) {\n const remainingSeconds = seconds % 60\n return remainingSeconds > 0 ? `${minutes}m ${remainingSeconds}s` : `${minutes}m`\n }\n\n return `${seconds}s`\n}\n","/**\n * Cryptographic utilities for PKCE (Proof Key for Code Exchange)\n *\n * Implements OAuth2 PKCE flow requirements:\n * - Code verifier generation (43-128 characters)\n * - Code challenge generation (SHA-256)\n */\n\nimport { base64UrlEncode } from './base64'\n\n/**\n * Generate a cryptographically secure random code verifier for PKCE\n *\n * The code verifier is a high-entropy cryptographic random string\n * with a minimum length of 43 characters and maximum of 128 characters.\n *\n * @param length - Length of the code verifier (default: 64, min: 43, max: 128)\n * @returns Base64URL-encoded random string\n */\nexport function generateCodeVerifier(length: number = 64): string {\n // Validate length\n if (length < 43 || length > 128) {\n throw new Error('Code verifier length must be between 43 and 128 characters')\n }\n\n // Generate random bytes\n // We need enough bytes to produce the desired length after base64url encoding\n // Base64 encoding increases size by ~33%, so we generate 3/4 of desired length\n const byteLength = Math.ceil((length * 3) / 4)\n const randomBytes = new Uint8Array(byteLength)\n crypto.getRandomValues(randomBytes)\n\n // Encode and trim to exact length\n const verifier = base64UrlEncode(randomBytes).substring(0, length)\n return verifier\n}\n\n/**\n * Generate code challenge from code verifier using SHA-256\n *\n * The code challenge is a Base64URL-encoded SHA-256 hash of the code verifier.\n * This is the recommended method for PKCE (S256).\n *\n * @param codeVerifier - The code verifier to hash\n * @returns Base64URL-encoded SHA-256 hash\n */\nexport async function generateCodeChallenge(codeVerifier: string): Promise<string> {\n // Convert verifier string to bytes\n const encoder = new TextEncoder()\n const data = encoder.encode(codeVerifier)\n\n // Hash with SHA-256\n const hashBuffer = await crypto.subtle.digest('SHA-256', data)\n\n // Convert to Base64URL\n const hashArray = new Uint8Array(hashBuffer)\n return base64UrlEncode(hashArray)\n}\n\n/**\n * Generate a cryptographically secure random string\n *\n * Useful for generating state, nonce, or other random identifiers.\n *\n * @param length - Desired length of the random string\n * @returns Base64URL-encoded random string\n */\nexport function generateRandomString(length: number): string {\n const byteLength = Math.ceil((length * 3) / 4)\n const randomBytes = new Uint8Array(byteLength)\n crypto.getRandomValues(randomBytes)\n return base64UrlEncode(randomBytes).substring(0, length)\n}\n\n/**\n * Generate a random UUID v4\n *\n * @returns UUID v4 string\n */\nexport function generateUuid(): string {\n // Use crypto.randomUUID if available\n if (typeof crypto.randomUUID === 'function') {\n return crypto.randomUUID()\n }\n\n // Fallback: generate UUID v4 manually\n const bytes = new Uint8Array(16)\n crypto.getRandomValues(bytes)\n\n // Set version (4) and variant bits\n bytes[6] = ((bytes[6] as number) & 0x0f) | 0x40 // Version 4\n bytes[8] = ((bytes[8] as number) & 0x3f) | 0x80 // Variant 10\n\n // Convert to hex string with dashes\n const hex = Array.from(bytes)\n .map((b) => b.toString(16).padStart(2, '0'))\n .join('')\n\n return `${hex.substring(0, 8)}-${hex.substring(8, 12)}-${hex.substring(12, 16)}-${hex.substring(16, 20)}-${hex.substring(20)}`\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["../src/kernel/event-bus.ts","../src/kernel/plugin-registry.ts","../src/kernel/kernel.ts","../src/factory.ts","../src/utils/time.ts","../src/utils/crypto.ts"],"names":["AuthError","fetch","createTokenStorePlugin","resolveStorage","createTokenDecoderPlugin","createRefreshEnginePlugin","createFetchInterceptorPlugin","base64UrlEncode"],"mappings":";;;;;;AAeO,IAAM,WAAN,MAAe;AAAA,EAAf,WAAA,GAAA;AACL,IAAA,IAAA,CAAQ,QAAA,uBAAqD,GAAA,EAAI;AAEjE;AAAA,IAAA,IAAA,CAAQ,OAAA,uBAAkD,GAAA,EAAI;AAAA,EAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAS9D,EAAA,CAAwB,WAAc,OAAA,EAAuC;AAE3E,IAAA,IAAI,UAAA,GAAa,IAAA,CAAK,QAAA,CAAS,GAAA,CAAI,SAAS,CAAA;AAC5C,IAAA,IAAI,CAAC,UAAA,EAAY;AACf,MAAA,UAAA,uBAAiB,G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;AAGA,EAAA,MAAM,KAAA,GAAQ,IAAI,UAAA,CAAW,EAAE,CAAA;AAC/B,EAAA,MAAA,CAAO,gBAAgB,KAAK,CAAA;AAG5B,EAAA,KAAA,CAAM,CAAC,CAAA,GAAM,KAAA,CAAM,CAAC,IAAe,EAAA,GAAQ,EAAA;AAC3C,EAAA,KAAA,CAAM,CAAC,CAAA,GAAM,KAAA,CAAM,CAAC,IAAe,EAAA,GAAQ,GAAA;AAG3C,EAAA,MAAM,MAAM,KAAA,CAAM,IAAA,CAAK,KAAK,CAAA,CACzB,GAAA,CAAI,CAAC,CAAA,KAAM,CAAA,CAAE,QAAA,CAAS,EAAE,EAAE,QAAA,CAAS,CAAA,EAAG,GAAG,CAAC,CAAA,CAC1C,KAAK,EAAE,CAAA;AAEV,EAAA,OAAO,CAAA,EAAG,GAAA,CAAI,SAAA,CAAU,CAAA,EAAG,CAAC,CAAC,CAAA,CAAA,EAAI,GAAA,CAAI,SAAA,CAAU,CAAA,EAAG,EAAE,CAAC,CAAA,CAAA,EAAI,GAAA,CAAI,SAAA,CAAU,EAAA,EAAI,EAAE,CAAC,CAAA,CAAA,EAAI,GAAA,CAAI,SAAA,CAAU,EAAA,EAAI,EAAE,CAAC,CAAA,CAAA,EAAI,GAAA,CAAI,SAAA,CAAU,EAAE,CAAC,CAAA,CAAA;AAC9H","file":"index.cjs","sourcesContent":["/**\n * Event Bus\n *\n * Pub/sub event system for kernel and plugins.\n * Type-safe event handling with automatic unsubscribe.\n */\n\nimport type { AuthEvent, EventType, EventHandler, Unsubscribe } from '../types'\n\n/** Handler type as stored internally (handlers are keyed by event type) */\ntype AnyEventHandler = (event: AuthEvent) => void\n\n/**\n * EventBus class for managing event subscriptions and emissions\n */\nexport class EventBus {\n private handlers: Map<EventType, Set<AnyEventHandler>> = new Map()\n /** Deliveries scheduled by emit() and not run yet (cancelled by clear()) */\n private pending: Set<ReturnType<typeof setTimeout>> = new Set()\n\n /**\n * Subscribe to an event\n *\n * @param eventType - Type of event to listen for\n * @param handler - Handler function to call when event is emitted\n * @returns Unsubscribe function\n */\n on<E extends EventType>(eventType: E, handler: EventHandler<E>): Unsubscribe {\n // Get or create handler set for this event type\n let handlerSet = this.handlers.get(eventType)\n if (!handlerSet) {\n handlerSet = new Set()\n this.handlers.set(eventType, handlerSet)\n }\n\n handlerSet.add(handler as AnyEventHandler)\n\n // Return unsubscribe function\n return () => this.off(eventType, handler)\n }\n\n /**\n * Unsubscribe from an event\n *\n * @param eventType - Type of event to stop listening for\n * @param handler - Handler function to remove\n */\n off<E extends EventType>(eventType: E, handler: EventHandler<E>): void {\n const handlerSet = this.handlers.get(eventType)\n if (handlerSet) {\n handlerSet.delete(handler as AnyEventHandler)\n\n // Clean up empty sets\n if (handlerSet.size === 0) {\n this.handlers.delete(eventType)\n }\n }\n }\n\n /**\n * Emit an event to all subscribers\n *\n * Handlers are executed asynchronously in the next tick to prevent blocking.\n * The event goes to the handlers subscribed when it is emitted (a handler\n * added later does not receive it) that are still subscribed at delivery.\n *\n * @param event - Event to emit\n */\n emit(event: AuthEvent): void {\n const handlerSet = this.handlers.get(event.type)\n if (!handlerSet || handlerSet.size === 0) {\n return\n }\n const recipients = Array.from(handlerSet)\n\n // Execute handlers in next tick to prevent blocking\n const timer = setTimeout(() => {\n this.pending.delete(timer)\n recipients.forEach((handler) => {\n // Unsubscribed meanwhile (also by an earlier handler of this event)\n if (this.handlers.get(event.type)?.has(handler) !== true) return\n try {\n handler(event)\n } catch (error) {\n // Log error but don't throw to prevent one handler from breaking others\n console.error(`[AuthKeeper] Error in event handler for ${event.type}:`, error)\n }\n })\n }, 0)\n this.pending.add(timer)\n }\n\n /**\n * Remove all event handlers and cancel deliveries that have not run yet\n * (no handler runs after the kernel is destroyed)\n */\n clear(): void {\n this.pending.forEach((timer) => clearTimeout(timer))\n this.pending.clear()\n this.handlers.clear()\n }\n\n /**\n * Get count of handlers for an event type\n *\n * @param eventType - Event type to count handlers for\n * @returns Number of handlers\n */\n getHandlerCount(eventType: EventType): number {\n return this.handlers.get(eventType)?.size || 0\n }\n\n /**\n * Get all event types that have handlers\n *\n * @returns Array of event types\n */\n getActiveEventTypes(): EventType[] {\n return Array.from(this.handlers.keys())\n }\n}\n","/**\n * Plugin Registry\n *\n * Manages plugin registration, installation, and lifecycle.\n */\n\nimport { AuthError, type Plugin, type PluginInfo, type AuthKeeper } from '../types'\n\n/**\n * Plugin instance with metadata\n */\ninterface PluginInstance {\n plugin: Plugin\n installed: boolean\n api: unknown\n}\n\n/**\n * PluginRegistry class for managing plugins\n */\nexport class PluginRegistry {\n private plugins: Map<string, PluginInstance> = new Map()\n\n /**\n * Register a plugin\n *\n * @param plugin - Plugin to register\n * @throws {AuthError} If plugin with same name already registered\n */\n register(plugin: Plugin): void {\n if (this.plugins.has(plugin.name)) {\n throw new AuthError('CONFIG_ERROR', `Plugin \"${plugin.name}\" is already registered`, {\n context: { pluginName: plugin.name },\n })\n }\n\n const instance: PluginInstance = {\n plugin,\n installed: false,\n api: null,\n }\n\n this.plugins.set(plugin.name, instance)\n }\n\n /**\n * Install a plugin\n *\n * Calls the plugin's install method and stores the returned API.\n *\n * @param name - Plugin name\n * @param kernel - Kernel instance to pass to plugin\n * @throws {AuthError} If plugin not found or already installed\n */\n async install(name: string, kernel: AuthKeeper): Promise<void> {\n const instance = this.plugins.get(name)\n\n if (!instance) {\n throw new AuthError('CONFIG_ERROR', `Plugin \"${name}\" not found`, {\n context: { pluginName: name },\n })\n }\n\n if (instance.installed) {\n // Already installed, skip\n return\n }\n\n try {\n // Call plugin's install method\n const api: unknown = await instance.plugin.install(kernel)\n instance.api = api || null\n instance.installed = true\n } catch (error) {\n throw new AuthError('CONFIG_ERROR', `Failed to install plugin \"${name}\"`, {\n cause: error as Error,\n context: { pluginName: name },\n })\n }\n }\n\n /**\n * Uninstall a plugin\n *\n * Calls the plugin's uninstall method if it exists.\n *\n * @param name - Plugin name\n */\n async uninstall(name: string): Promise<void> {\n const instance = this.plugins.get(name)\n\n if (!instance) {\n // Plugin not found, nothing to uninstall\n return\n }\n\n if (instance.installed && instance.plugin.uninstall) {\n try {\n await instance.plugin.uninstall()\n } catch (error) {\n console.error(`[AuthKeeper] Error uninstalling plugin \"${name}\":`, error)\n }\n }\n\n this.plugins.delete(name)\n }\n\n /**\n * Get a plugin by name\n *\n * @param name - Plugin name\n * @returns Plugin or undefined if not found\n */\n get<P extends Plugin>(name: string): P | undefined {\n const instance = this.plugins.get(name)\n return instance?.plugin as P | undefined\n }\n\n /**\n * Get plugin API by name\n *\n * @param name - Plugin name\n * @returns Plugin API or undefined if not found\n */\n getApi<T = unknown>(name: string): T | undefined {\n const instance = this.plugins.get(name)\n return instance?.api as T | undefined\n }\n\n /**\n * Check if a plugin is registered\n *\n * @param name - Plugin name\n * @returns true if plugin is registered\n */\n has(name: string): boolean {\n return this.plugins.has(name)\n }\n\n /**\n * Check if a plugin is installed\n *\n * @param name - Plugin name\n * @returns true if plugin is installed\n */\n isInstalled(name: string): boolean {\n const instance = this.plugins.get(name)\n return instance?.installed || false\n }\n\n /**\n * List all plugins\n *\n * @returns Array of plugin information\n */\n list(): PluginInfo[] {\n return Array.from(this.plugins.entries()).map(([name, instance]) => ({\n name,\n version: instance.plugin.version,\n type: instance.plugin.type,\n enabled: instance.installed,\n }))\n }\n\n /**\n * Get all plugin names\n *\n * @returns Array of plugin names\n */\n getNames(): string[] {\n return Array.from(this.plugins.keys())\n }\n\n /**\n * Clear all plugins\n */\n clear(): void {\n this.plugins.clear()\n }\n}\n","/**\n * AuthKeeper Kernel\n *\n * The micro-kernel that orchestrates plugins and manages auth state.\n * Most functionality is delegated to core plugins.\n */\n\nimport { EventBus } from './event-bus'\nimport { PluginRegistry } from './plugin-registry'\nimport {\n AuthError,\n type AuthKeeper,\n type KernelOptions,\n type Plugin,\n type PluginInfo,\n type TokenSet,\n type TokenPayload,\n type LogoutOptions,\n type AuthFetch,\n type FetchInterceptorOptions,\n type EventType,\n type EventHandler,\n type Unsubscribe,\n type AuthEvent,\n} from '../types'\nimport type {\n TokenStoreAPI,\n TokenDecoderAPI,\n RefreshEngineAPI,\n FetchInterceptorAPI,\n} from '../plugins/core'\n\n/**\n * AuthKeeperKernel - Main kernel implementation\n */\nexport class AuthKeeperKernel implements AuthKeeper {\n private pluginRegistry: PluginRegistry\n private eventBus: EventBus\n private options: KernelOptions\n private initialized: boolean = false\n\n constructor(options: KernelOptions) {\n this.options = {\n autoRefresh: true,\n refreshThreshold: 60,\n ...options,\n }\n\n this.pluginRegistry = new PluginRegistry()\n this.eventBus = new EventBus()\n }\n\n // ============================================================================\n // Lifecycle\n // ============================================================================\n\n /**\n * Initialize the kernel\n *\n * 1. Install core plugins\n * 2. Install user-provided plugins\n * 3. Load tokens from storage\n * 4. Schedule refresh if authenticated\n */\n async init(): Promise<void> {\n if (this.initialized) {\n return\n }\n\n // Core plugins will be installed in Phase 4\n // For now, we just mark as initialized\n\n // Install user-provided plugins\n if (this.options.plugins) {\n for (const plugin of this.options.plugins) {\n await this.register(plugin)\n }\n }\n\n this.initialized = true\n }\n\n /**\n * Destroy the kernel and cleanup\n */\n destroy(): void {\n // Cancel any scheduled refreshes\n this.cancelScheduledRefresh()\n\n // Clear event handlers\n this.eventBus.clear()\n\n // Uninstall all plugins\n const pluginNames = this.pluginRegistry.getNames()\n for (const name of pluginNames) {\n // Not awaited: uninstall() catches plugin errors and destroy() stays synchronous\n void this.pluginRegistry.uninstall(name)\n }\n\n this.pluginRegistry.clear()\n this.initialized = false\n }\n\n // ============================================================================\n // Token Management\n // ============================================================================\n\n /**\n * Set authentication tokens\n *\n * Delegates to token-store plugin.\n */\n setTokens(tokens: TokenSet): void {\n const tokenStore = this.pluginRegistry.getApi<TokenStoreAPI>('token-store')\n if (!tokenStore) {\n throw new AuthError('CONFIG_ERROR', 'token-store plugin not installed')\n }\n\n tokenStore.set(tokens)\n\n // Emit login event - but not when the refresh engine is storing the\n // result of a token refresh (that is reported as a 'refresh' event)\n const refreshEngine = this.pluginRegistry.getApi<RefreshEngineAPI>('refresh-engine')\n if (refreshEngine?.isApplyingRefresh?.() !== true) {\n this.emit({\n type: 'login',\n tokens,\n timestamp: Date.now(),\n })\n }\n\n // Schedule auto-refresh if enabled\n if (this.options.autoRefresh && !this.isExpired()) {\n this.scheduleRefresh()\n }\n }\n\n /**\n * Get access token\n *\n * Delegates to token-store plugin.\n */\n getAccessToken(): string | null {\n const tokenStore = this.pluginRegistry.getApi<TokenStoreAPI>('token-store')\n if (!tokenStore) {\n return null\n }\n\n return tokenStore.getAccessToken()\n }\n\n /**\n * Get refresh token\n *\n * Delegates to token-store plugin.\n */\n getRefreshToken(): string | null {\n const tokenStore = this.pluginRegistry.getApi<TokenStoreAPI>('token-store')\n if (!tokenStore) {\n return null\n }\n\n return tokenStore.getRefreshToken()\n }\n\n /**\n * Clear all tokens\n */\n clearTokens(): void {\n // Nothing left to refresh: a pending scheduled refresh would only fail\n // with REFRESH_TOKEN_MISSING\n this.cancelScheduledRefresh()\n\n const tokenStore = this.pluginRegistry.getApi<TokenStoreAPI>('token-store')\n if (tokenStore) {\n tokenStore.clear()\n }\n }\n\n // ============================================================================\n // Auth State\n // ============================================================================\n\n /**\n * Check if user is authenticated\n */\n isAuthenticated(): boolean {\n const accessToken = this.getAccessToken()\n return accessToken !== null && !this.isExpired()\n }\n\n /**\n * Check if token is expired\n *\n * Delegates to token-store plugin.\n */\n isExpired(): boolean {\n const tokenStore = this.pluginRegistry.getApi<TokenStoreAPI>('token-store')\n if (!tokenStore) {\n return true\n }\n\n return tokenStore.isExpired()\n }\n\n /**\n * Get token expiration date\n *\n * Delegates to token-store plugin.\n */\n getExpiresAt(): Date | null {\n const tokenStore = this.pluginRegistry.getApi<TokenStoreAPI>('token-store')\n if (!tokenStore) {\n return null\n }\n\n return tokenStore.getExpiresAt()\n }\n\n /**\n * Get time until expiry in milliseconds\n *\n * Delegates to token-store plugin.\n */\n getTimeUntilExpiry(): number | null {\n const tokenStore = this.pluginRegistry.getApi<TokenStoreAPI>('token-store')\n if (!tokenStore) {\n return null\n }\n\n return tokenStore.getExpiresIn()\n }\n\n // ============================================================================\n // Token Decoding\n // ============================================================================\n\n /**\n * Decode token payload\n *\n * Delegates to token-decoder plugin.\n */\n decode<T = TokenPayload>(): T | null {\n const tokenDecoder = this.pluginRegistry.getApi<TokenDecoderAPI>('token-decoder')\n if (!tokenDecoder) {\n return null\n }\n\n return tokenDecoder.decode<T>()\n }\n\n /**\n * Get specific claim from token\n *\n * Delegates to token-decoder plugin.\n */\n getClaim<K extends keyof TokenPayload>(key: K): TokenPayload[K] | undefined {\n const tokenDecoder = this.pluginRegistry.getApi<TokenDecoderAPI>('token-decoder')\n if (!tokenDecoder) {\n return undefined\n }\n\n return tokenDecoder.getClaim(key)\n }\n\n /**\n * Get multiple claims from token\n *\n * Delegates to token-decoder plugin.\n */\n getClaims<K extends keyof TokenPayload>(keys: K[]): Pick<TokenPayload, K> {\n const tokenDecoder = this.pluginRegistry.getApi<TokenDecoderAPI>('token-decoder')\n if (!tokenDecoder) {\n return {} as Pick<TokenPayload, K>\n }\n\n return tokenDecoder.getClaims(keys)\n }\n\n // ============================================================================\n // Refresh\n // ============================================================================\n\n /**\n * Manually refresh tokens\n *\n * Delegates to refresh-engine plugin.\n */\n async refresh(): Promise<TokenSet> {\n const refreshEngine = this.pluginRegistry.getApi<RefreshEngineAPI>('refresh-engine')\n if (!refreshEngine) {\n throw new AuthError('CONFIG_ERROR', 'refresh-engine plugin not installed')\n }\n\n return refreshEngine.refresh()\n }\n\n /**\n * Schedule automatic refresh\n *\n * Delegates to refresh-engine plugin.\n */\n scheduleRefresh(): void {\n if (!this.options.autoRefresh) {\n return\n }\n\n const refreshEngine = this.pluginRegistry.getApi<RefreshEngineAPI>('refresh-engine')\n if (refreshEngine) {\n refreshEngine.scheduleRefresh()\n }\n }\n\n /**\n * Cancel scheduled refresh\n *\n * Delegates to refresh-engine plugin.\n */\n cancelScheduledRefresh(): void {\n const refreshEngine = this.pluginRegistry.getApi<RefreshEngineAPI>('refresh-engine')\n if (refreshEngine) {\n refreshEngine.cancelScheduledRefresh()\n }\n }\n\n // ============================================================================\n // Logout\n // ============================================================================\n\n /**\n * Logout user\n *\n * Clears tokens and emits logout event.\n */\n logout(options: LogoutOptions = {}): void {\n // Cancel scheduled refresh\n this.cancelScheduledRefresh()\n\n // Clear tokens\n this.clearTokens()\n\n // Emit logout event\n this.emit({\n type: 'logout',\n reason: 'manual',\n timestamp: Date.now(),\n })\n\n // Handle redirect if specified\n if (options.redirect && typeof window !== 'undefined') {\n window.location.href = options.redirect\n }\n }\n\n // ============================================================================\n // Interceptors\n // ============================================================================\n\n /**\n * Create authenticated fetch function\n *\n * Delegates to fetch-interceptor plugin.\n */\n createFetch(options?: FetchInterceptorOptions): AuthFetch {\n const fetchInterceptor = this.pluginRegistry.getApi<FetchInterceptorAPI>('fetch-interceptor')\n if (!fetchInterceptor) {\n // Return regular fetch if plugin not installed\n return fetch.bind(globalThis)\n }\n\n return fetchInterceptor.createFetch(options)\n }\n\n /**\n * Wrap global fetch with auth\n *\n * Delegates to fetch-interceptor plugin.\n */\n wrapFetch(fetch: typeof globalThis.fetch): void {\n const fetchInterceptor = this.pluginRegistry.getApi<FetchInterceptorAPI>('fetch-interceptor')\n if (fetchInterceptor) {\n fetchInterceptor.wrapFetch(fetch)\n }\n }\n\n // ============================================================================\n // Plugin Management\n // ============================================================================\n\n /**\n * Register and install a plugin\n *\n * The returned promise rejects when the plugin cannot be registered or\n * installed. The failure is also emitted as an 'error' event (context\n * 'plugin') and passed to `onError`, so a caller that does not await the\n * promise does not get an unhandled rejection.\n */\n register(plugin: Plugin): Promise<void> {\n const result = this.registerPlugin(plugin)\n result.catch((error: AuthError) => {\n // PluginRegistry only throws AuthError (CONFIG_ERROR)\n this.emit({ type: 'error', error, context: 'plugin', timestamp: Date.now() })\n })\n return result\n }\n\n private async registerPlugin(plugin: Plugin): Promise<void> {\n this.pluginRegistry.register(plugin)\n try {\n await this.pluginRegistry.install(plugin.name, this)\n } catch (error) {\n // Drop the half-registered plugin so it can be registered again\n await this.pluginRegistry.uninstall(plugin.name)\n throw error\n }\n }\n\n /**\n * Unregister a plugin\n */\n async unregister(pluginName: string): Promise<void> {\n await this.pluginRegistry.uninstall(pluginName)\n }\n\n /**\n * Get plugin by name\n */\n getPlugin<P extends Plugin>(name: string): P | undefined {\n return this.pluginRegistry.get<P>(name)\n }\n\n /**\n * List all plugins\n */\n listPlugins(): PluginInfo[] {\n return this.pluginRegistry.list()\n }\n\n // ============================================================================\n // Event System\n // ============================================================================\n\n /**\n * Emit an event\n */\n emit(event: AuthEvent): void {\n this.eventBus.emit(event)\n\n // Call global error handler if it's an error event\n if (event.type === 'error' && this.options.onError) {\n this.options.onError(event.error)\n }\n }\n\n /**\n * Subscribe to events\n */\n on<E extends EventType>(eventType: E, handler: EventHandler<E>): Unsubscribe {\n return this.eventBus.on(eventType, handler)\n }\n\n /**\n * Unsubscribe from events\n */\n off<E extends EventType>(eventType: E, handler: EventHandler<E>): void {\n this.eventBus.off(eventType, handler)\n }\n\n // ============================================================================\n // Configuration\n // ============================================================================\n\n /**\n * Update configuration\n */\n configure(options: Partial<KernelOptions>): void {\n this.options = {\n ...this.options,\n ...options,\n }\n\n // Update refresh engine threshold if changed\n if (options.refreshThreshold !== undefined) {\n const refreshEngine = this.pluginRegistry.getApi<RefreshEngineAPI>('refresh-engine')\n if (refreshEngine && refreshEngine.setThreshold) {\n refreshEngine.setThreshold(options.refreshThreshold)\n }\n }\n }\n\n /**\n * Get current configuration\n */\n getOptions(): KernelOptions {\n // Multi-tab sync is not implemented: report the effective value\n return { ...this.options, syncTabs: false }\n }\n}\n","/**\n * Factory Function\n *\n * Creates and initializes an AuthKeeper instance with core plugins.\n */\n\nimport { AuthKeeperKernel } from './kernel'\nimport {\n resolveStorage,\n createTokenStorePlugin,\n createTokenDecoderPlugin,\n createRefreshEnginePlugin,\n createFetchInterceptorPlugin,\n} from './plugins/core'\nimport type { AuthKeeper, KernelOptions } from './types'\n\n/**\n * Create an AuthKeeper instance\n *\n * Automatically installs core plugins:\n * - token-store: Token state management\n * - token-decoder: JWT decoding\n * - refresh-engine: Auto-refresh with queue\n * - storage-memory: Default secure storage\n * - fetch-interceptor: Auth header injection and 401 retry\n *\n * @param options - Configuration options\n * @returns AuthKeeper instance\n *\n * @example\n * ```typescript\n * const auth = createAuthKeeper({\n * storage: 'memory',\n * refreshToken: async (token) => {\n * const res = await fetch('/api/auth/refresh', {\n * method: 'POST',\n * body: JSON.stringify({ refreshToken: token }),\n * })\n * return res.json()\n * },\n * autoRefresh: true,\n * refreshThreshold: 60,\n * })\n *\n * await auth.init()\n * ```\n */\nexport async function createAuthKeeper(options: KernelOptions): Promise<AuthKeeper> {\n // Create kernel\n const kernel = new AuthKeeperKernel(options)\n\n // Register and install core plugins\n // 1. token-store (restores persisted tokens from the configured storage)\n await kernel.register(createTokenStorePlugin({ storage: resolveStorage(options.storage) }))\n\n // 2. token-decoder\n await kernel.register(createTokenDecoderPlugin())\n\n // 3. refresh-engine\n await kernel.register(\n createRefreshEnginePlugin({\n refreshFn: options.refreshToken,\n threshold: options.refreshThreshold,\n }),\n )\n\n // 5. fetch-interceptor\n await kernel.register(createFetchInterceptorPlugin())\n\n // Initialize kernel\n await kernel.init()\n\n // Resume auto-refresh for tokens restored from storage\n if (kernel.getAccessToken() && !kernel.isExpired()) {\n kernel.scheduleRefresh()\n } else if (\n kernel.getAccessToken() &&\n kernel.getRefreshToken() &&\n kernel.getOptions().autoRefresh !== false\n ) {\n // Restored tokens already expired: refresh them in the background\n // (`await auth.refresh()` joins this refresh). A failure is reported as\n // an 'error' event / onError, like any refresh failure.\n kernel.refresh().catch(() => {})\n }\n\n return kernel\n}\n","/**\n * Time and expiry utilities\n *\n * Helper functions for working with token expiration times.\n */\n\n/**\n * Check if a timestamp is expired\n *\n * @param expiresAt - Expiration timestamp in milliseconds\n * @param bufferMs - Consider expired if within this many milliseconds (default: 0)\n * @returns true if expired\n */\nexport function isExpired(expiresAt: number | null | undefined, bufferMs: number = 0): boolean {\n if (!expiresAt) {\n return false\n }\n\n const now = Date.now()\n return now >= expiresAt - bufferMs\n}\n\n/**\n * Get time until expiry in milliseconds\n *\n * @param expiresAt - Expiration timestamp in milliseconds\n * @returns Milliseconds until expiry, or null if no expiry. Returns 0 if already expired.\n */\nexport function getExpiresIn(expiresAt: number | null | undefined): number | null {\n if (!expiresAt) {\n return null\n }\n\n const now = Date.now()\n const timeUntil = expiresAt - now\n return Math.max(0, timeUntil)\n}\n\n/**\n * Convert seconds to milliseconds\n *\n * @param seconds - Time in seconds\n * @returns Time in milliseconds\n */\nexport function secondsToMs(seconds: number): number {\n return seconds * 1000\n}\n\n/**\n * Convert milliseconds to seconds\n *\n * @param ms - Time in milliseconds\n * @returns Time in seconds\n */\nexport function msToSeconds(ms: number): number {\n return Math.floor(ms / 1000)\n}\n\n/**\n * Calculate expiry timestamp from expiresIn seconds\n *\n * @param expiresIn - Seconds until expiry\n * @returns Expiry timestamp in milliseconds\n */\nexport function calculateExpiresAt(expiresIn: number): number {\n return Date.now() + secondsToMs(expiresIn)\n}\n\n/**\n * Format time remaining as human-readable string\n *\n * @param ms - Milliseconds\n * @returns Formatted string like \"5m 30s\" or \"2h 15m\"\n */\nexport function formatTimeRemaining(ms: number): string {\n if (ms <= 0) {\n return 'expired'\n }\n\n const seconds = Math.floor(ms / 1000)\n const minutes = Math.floor(seconds / 60)\n const hours = Math.floor(minutes / 60)\n const days = Math.floor(hours / 24)\n\n if (days > 0) {\n const remainingHours = hours % 24\n return remainingHours > 0 ? `${days}d ${remainingHours}h` : `${days}d`\n }\n\n if (hours > 0) {\n const remainingMinutes = minutes % 60\n return remainingMinutes > 0 ? `${hours}h ${remainingMinutes}m` : `${hours}h`\n }\n\n if (minutes > 0) {\n const remainingSeconds = seconds % 60\n return remainingSeconds > 0 ? `${minutes}m ${remainingSeconds}s` : `${minutes}m`\n }\n\n return `${seconds}s`\n}\n","/**\n * Cryptographic utilities for PKCE (Proof Key for Code Exchange)\n *\n * Implements OAuth2 PKCE flow requirements:\n * - Code verifier generation (43-128 characters)\n * - Code challenge generation (SHA-256)\n */\n\nimport { base64UrlEncode } from './base64'\n\n/**\n * Generate a cryptographically secure random code verifier for PKCE\n *\n * The code verifier is a high-entropy cryptographic random string\n * with a minimum length of 43 characters and maximum of 128 characters.\n *\n * @param length - Length of the code verifier (default: 64, min: 43, max: 128)\n * @returns Base64URL-encoded random string\n */\nexport function generateCodeVerifier(length: number = 64): string {\n // Validate length\n if (length < 43 || length > 128) {\n throw new Error('Code verifier length must be between 43 and 128 characters')\n }\n\n // Generate random bytes\n // We need enough bytes to produce the desired length after base64url encoding\n // Base64 encoding increases size by ~33%, so we generate 3/4 of desired length\n const byteLength = Math.ceil((length * 3) / 4)\n const randomBytes = new Uint8Array(byteLength)\n crypto.getRandomValues(randomBytes)\n\n // Encode and trim to exact length\n const verifier = base64UrlEncode(randomBytes).substring(0, length)\n return verifier\n}\n\n/**\n * Generate code challenge from code verifier using SHA-256\n *\n * The code challenge is a Base64URL-encoded SHA-256 hash of the code verifier.\n * This is the recommended method for PKCE (S256).\n *\n * @param codeVerifier - The code verifier to hash\n * @returns Base64URL-encoded SHA-256 hash\n */\nexport async function generateCodeChallenge(codeVerifier: string): Promise<string> {\n // Convert verifier string to bytes\n const encoder = new TextEncoder()\n const data = encoder.encode(codeVerifier)\n\n // Hash with SHA-256\n const hashBuffer = await crypto.subtle.digest('SHA-256', data)\n\n // Convert to Base64URL\n const hashArray = new Uint8Array(hashBuffer)\n return base64UrlEncode(hashArray)\n}\n\n/**\n * Generate a cryptographically secure random string\n *\n * Useful for generating state, nonce, or other random identifiers.\n *\n * @param length - Desired length of the random string\n * @returns Base64URL-encoded random string\n */\nexport function generateRandomString(length: number): string {\n const byteLength = Math.ceil((length * 3) / 4)\n const randomBytes = new Uint8Array(byteLength)\n crypto.getRandomValues(randomBytes)\n return base64UrlEncode(randomBytes).substring(0, length)\n}\n\n/**\n * Generate a random UUID v4\n *\n * @returns UUID v4 string\n */\nexport function generateUuid(): string {\n // Use crypto.randomUUID if available\n if (typeof crypto.randomUUID === 'function') {\n return crypto.randomUUID()\n }\n\n // Fallback: generate UUID v4 manually\n const bytes = new Uint8Array(16)\n crypto.getRandomValues(bytes)\n\n // Set version (4) and variant bits\n bytes[6] = ((bytes[6] as number) & 0x0f) | 0x40 // Version 4\n bytes[8] = ((bytes[8] as number) & 0x3f) | 0x80 // Variant 10\n\n // Convert to hex string with dashes\n const hex = Array.from(bytes)\n .map((b) => b.toString(16).padStart(2, '0'))\n .join('')\n\n return `${hex.substring(0, 8)}-${hex.substring(8, 12)}-${hex.substring(12, 16)}-${hex.substring(16, 20)}-${hex.substring(20)}`\n}\n"]}
|
package/dist/index.d.cts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import { K as KernelOptions,
|
|
2
|
-
export {
|
|
3
|
-
export { C as CookieAttributes, a as CookieStorageAdapter, b as CookieStorageOptions, F as FetchInterceptorAPI, c as FetchInterceptorPlugin, M as MemoryStorageAdapter, d as MemoryStorageOptions, R as RefreshEngineAPI, e as RefreshEngineOptions, f as RefreshEnginePlugin, T as TokenDecoderAPI, g as TokenDecoderPlugin, h as TokenStoreAPI, i as TokenStoreOptions, j as TokenStorePlugin, W as WebStorageAdapter, k as WebStorageOptions, l as createFetchInterceptorPlugin, m as createMemoryStorage, n as createRefreshEnginePlugin, o as createTokenDecoderPlugin, p as createTokenStorePlugin, q as deleteCookie, r as getCookie, s as parseCookies, t as serializeCookie, u as setCookie } from './index-
|
|
1
|
+
import { K as KernelOptions, b as AuthKeeper, E as EventType, d as EventHandler, U as Unsubscribe, e as AuthEvent, P as Plugin, f as PluginInfo, T as TokenSet, a as TokenPayload, L as LogoutOptions, F as FetchInterceptorOptions, A as AuthFetch, g as TokenHeader, S as StorageAdapter } from './types-DMPBl-Ym.cjs';
|
|
2
|
+
export { c as AuthError, h as AuthErrorCode, i as AuthErrorOptions, j as ErrorEvent, k as ExpiredEvent, l as LoginEvent, m as LoginOptions, n as LogoutEvent, R as RefreshEvent, o as RefreshTokenFn, p as StorageChangeEvent, q as StorageType, r as StoredTokens, s as TabSyncEvent, t as TokenInfo, u as UserInfo } from './types-DMPBl-Ym.cjs';
|
|
3
|
+
export { C as CookieAttributes, a as CookieStorageAdapter, b as CookieStorageOptions, F as FetchInterceptorAPI, c as FetchInterceptorPlugin, M as MemoryStorageAdapter, d as MemoryStorageOptions, R as RefreshEngineAPI, e as RefreshEngineOptions, f as RefreshEnginePlugin, T as TokenDecoderAPI, g as TokenDecoderPlugin, h as TokenStoreAPI, i as TokenStoreOptions, j as TokenStorePlugin, W as WebStorageAdapter, k as WebStorageOptions, l as createFetchInterceptorPlugin, m as createMemoryStorage, n as createRefreshEnginePlugin, o as createTokenDecoderPlugin, p as createTokenStorePlugin, q as deleteCookie, r as getCookie, s as parseCookies, t as serializeCookie, u as setCookie } from './index-C4pGS-TI.cjs';
|
|
4
4
|
|
|
5
5
|
/**
|
|
6
6
|
* Factory Function
|
|
@@ -578,6 +578,10 @@ declare function generateUuid(): string;
|
|
|
578
578
|
/**
|
|
579
579
|
* Check if a storage API is available
|
|
580
580
|
*
|
|
581
|
+
* A storage that is full but holds data counts as available: reading and
|
|
582
|
+
* removing still work (a persisted session must be restored, and a logout
|
|
583
|
+
* must remove it). A storage that refuses even the first write is not.
|
|
584
|
+
*
|
|
581
585
|
* @param storage - Storage object to check (localStorage, sessionStorage, etc.)
|
|
582
586
|
* @returns true if storage is available and working
|
|
583
587
|
*/
|
package/dist/index.d.ts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import { K as KernelOptions,
|
|
2
|
-
export {
|
|
3
|
-
export { C as CookieAttributes, a as CookieStorageAdapter, b as CookieStorageOptions, F as FetchInterceptorAPI, c as FetchInterceptorPlugin, M as MemoryStorageAdapter, d as MemoryStorageOptions, R as RefreshEngineAPI, e as RefreshEngineOptions, f as RefreshEnginePlugin, T as TokenDecoderAPI, g as TokenDecoderPlugin, h as TokenStoreAPI, i as TokenStoreOptions, j as TokenStorePlugin, W as WebStorageAdapter, k as WebStorageOptions, l as createFetchInterceptorPlugin, m as createMemoryStorage, n as createRefreshEnginePlugin, o as createTokenDecoderPlugin, p as createTokenStorePlugin, q as deleteCookie, r as getCookie, s as parseCookies, t as serializeCookie, u as setCookie } from './index-
|
|
1
|
+
import { K as KernelOptions, b as AuthKeeper, E as EventType, d as EventHandler, U as Unsubscribe, e as AuthEvent, P as Plugin, f as PluginInfo, T as TokenSet, a as TokenPayload, L as LogoutOptions, F as FetchInterceptorOptions, A as AuthFetch, g as TokenHeader, S as StorageAdapter } from './types-DMPBl-Ym.js';
|
|
2
|
+
export { c as AuthError, h as AuthErrorCode, i as AuthErrorOptions, j as ErrorEvent, k as ExpiredEvent, l as LoginEvent, m as LoginOptions, n as LogoutEvent, R as RefreshEvent, o as RefreshTokenFn, p as StorageChangeEvent, q as StorageType, r as StoredTokens, s as TabSyncEvent, t as TokenInfo, u as UserInfo } from './types-DMPBl-Ym.js';
|
|
3
|
+
export { C as CookieAttributes, a as CookieStorageAdapter, b as CookieStorageOptions, F as FetchInterceptorAPI, c as FetchInterceptorPlugin, M as MemoryStorageAdapter, d as MemoryStorageOptions, R as RefreshEngineAPI, e as RefreshEngineOptions, f as RefreshEnginePlugin, T as TokenDecoderAPI, g as TokenDecoderPlugin, h as TokenStoreAPI, i as TokenStoreOptions, j as TokenStorePlugin, W as WebStorageAdapter, k as WebStorageOptions, l as createFetchInterceptorPlugin, m as createMemoryStorage, n as createRefreshEnginePlugin, o as createTokenDecoderPlugin, p as createTokenStorePlugin, q as deleteCookie, r as getCookie, s as parseCookies, t as serializeCookie, u as setCookie } from './index-CQwGO-Wk.js';
|
|
4
4
|
|
|
5
5
|
/**
|
|
6
6
|
* Factory Function
|
|
@@ -578,6 +578,10 @@ declare function generateUuid(): string;
|
|
|
578
578
|
/**
|
|
579
579
|
* Check if a storage API is available
|
|
580
580
|
*
|
|
581
|
+
* A storage that is full but holds data counts as available: reading and
|
|
582
|
+
* removing still work (a persisted session must be restored, and a logout
|
|
583
|
+
* must remove it). A storage that refuses even the first write is not.
|
|
584
|
+
*
|
|
581
585
|
* @param storage - Storage object to check (localStorage, sessionStorage, etc.)
|
|
582
586
|
* @returns true if storage is available and working
|
|
583
587
|
*/
|
package/dist/index.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
import { createTokenStorePlugin, resolveStorage, createTokenDecoderPlugin, createRefreshEnginePlugin, createFetchInterceptorPlugin, base64UrlEncode } from './chunk-
|
|
2
|
-
export { 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-
|
|
3
|
-
import { AuthError } from './chunk-
|
|
4
|
-
export { AuthError } from './chunk-
|
|
1
|
+
import { createTokenStorePlugin, resolveStorage, createTokenDecoderPlugin, createRefreshEnginePlugin, createFetchInterceptorPlugin, base64UrlEncode } from './chunk-7B77NZGY.js';
|
|
2
|
+
export { 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-7B77NZGY.js';
|
|
3
|
+
import { AuthError } from './chunk-DLCD3SBV.js';
|
|
4
|
+
export { AuthError } from './chunk-DLCD3SBV.js';
|
|
5
5
|
|
|
6
6
|
// src/kernel/event-bus.ts
|
|
7
7
|
var EventBus = class {
|
|
@@ -110,13 +110,9 @@ var PluginRegistry = class {
|
|
|
110
110
|
*/
|
|
111
111
|
register(plugin) {
|
|
112
112
|
if (this.plugins.has(plugin.name)) {
|
|
113
|
-
throw new AuthError(
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
{
|
|
117
|
-
context: { pluginName: plugin.name }
|
|
118
|
-
}
|
|
119
|
-
);
|
|
113
|
+
throw new AuthError("CONFIG_ERROR", `Plugin "${plugin.name}" is already registered`, {
|
|
114
|
+
context: { pluginName: plugin.name }
|
|
115
|
+
});
|
|
120
116
|
}
|
|
121
117
|
const instance = {
|
|
122
118
|
plugin,
|