@oxog/authkeeper 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs ADDED
@@ -0,0 +1,1389 @@
1
+ 'use strict';
2
+
3
+ // src/kernel/event-bus.ts
4
+ var EventBus = class {
5
+ constructor() {
6
+ this.handlers = /* @__PURE__ */ new Map();
7
+ }
8
+ /**
9
+ * Subscribe to an event
10
+ *
11
+ * @param eventType - Type of event to listen for
12
+ * @param handler - Handler function to call when event is emitted
13
+ * @returns Unsubscribe function
14
+ */
15
+ on(eventType, handler) {
16
+ if (!this.handlers.has(eventType)) {
17
+ this.handlers.set(eventType, /* @__PURE__ */ new Set());
18
+ }
19
+ const handlerSet = this.handlers.get(eventType);
20
+ handlerSet.add(handler);
21
+ return () => this.off(eventType, handler);
22
+ }
23
+ /**
24
+ * Unsubscribe from an event
25
+ *
26
+ * @param eventType - Type of event to stop listening for
27
+ * @param handler - Handler function to remove
28
+ */
29
+ off(eventType, handler) {
30
+ const handlerSet = this.handlers.get(eventType);
31
+ if (handlerSet) {
32
+ handlerSet.delete(handler);
33
+ if (handlerSet.size === 0) {
34
+ this.handlers.delete(eventType);
35
+ }
36
+ }
37
+ }
38
+ /**
39
+ * Emit an event to all subscribers
40
+ *
41
+ * Handlers are executed asynchronously in the next tick to prevent blocking.
42
+ *
43
+ * @param event - Event to emit
44
+ */
45
+ emit(event) {
46
+ const handlerSet = this.handlers.get(event.type);
47
+ if (!handlerSet || handlerSet.size === 0) {
48
+ return;
49
+ }
50
+ setTimeout(() => {
51
+ handlerSet.forEach((handler) => {
52
+ try {
53
+ handler(event);
54
+ } catch (error) {
55
+ console.error(`[AuthKeeper] Error in event handler for ${event.type}:`, error);
56
+ }
57
+ });
58
+ }, 0);
59
+ }
60
+ /**
61
+ * Remove all event handlers
62
+ */
63
+ clear() {
64
+ this.handlers.clear();
65
+ }
66
+ /**
67
+ * Get count of handlers for an event type
68
+ *
69
+ * @param eventType - Event type to count handlers for
70
+ * @returns Number of handlers
71
+ */
72
+ getHandlerCount(eventType) {
73
+ return this.handlers.get(eventType)?.size || 0;
74
+ }
75
+ /**
76
+ * Get all event types that have handlers
77
+ *
78
+ * @returns Array of event types
79
+ */
80
+ getActiveEventTypes() {
81
+ return Array.from(this.handlers.keys());
82
+ }
83
+ };
84
+
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
+ // src/kernel/plugin-registry.ts
100
+ var PluginRegistry = class {
101
+ constructor() {
102
+ this.plugins = /* @__PURE__ */ new Map();
103
+ }
104
+ /**
105
+ * Register a plugin
106
+ *
107
+ * @param plugin - Plugin to register
108
+ * @throws {AuthError} If plugin with same name already registered
109
+ */
110
+ register(plugin) {
111
+ if (this.plugins.has(plugin.name)) {
112
+ throw new AuthError(
113
+ "CONFIG_ERROR",
114
+ `Plugin "${plugin.name}" is already registered`,
115
+ {
116
+ context: { pluginName: plugin.name }
117
+ }
118
+ );
119
+ }
120
+ const instance = {
121
+ plugin,
122
+ installed: false,
123
+ api: null
124
+ };
125
+ this.plugins.set(plugin.name, instance);
126
+ }
127
+ /**
128
+ * Install a plugin
129
+ *
130
+ * Calls the plugin's install method and stores the returned API.
131
+ *
132
+ * @param name - Plugin name
133
+ * @param kernel - Kernel instance to pass to plugin
134
+ * @throws {AuthError} If plugin not found or already installed
135
+ */
136
+ async install(name, kernel) {
137
+ const instance = this.plugins.get(name);
138
+ if (!instance) {
139
+ throw new AuthError("CONFIG_ERROR", `Plugin "${name}" not found`, {
140
+ context: { pluginName: name }
141
+ });
142
+ }
143
+ if (instance.installed) {
144
+ return;
145
+ }
146
+ try {
147
+ const api = await instance.plugin.install(kernel);
148
+ instance.api = api || null;
149
+ instance.installed = true;
150
+ } catch (error) {
151
+ throw new AuthError("CONFIG_ERROR", `Failed to install plugin "${name}"`, {
152
+ cause: error,
153
+ context: { pluginName: name }
154
+ });
155
+ }
156
+ }
157
+ /**
158
+ * Uninstall a plugin
159
+ *
160
+ * Calls the plugin's uninstall method if it exists.
161
+ *
162
+ * @param name - Plugin name
163
+ */
164
+ async uninstall(name) {
165
+ const instance = this.plugins.get(name);
166
+ if (!instance) {
167
+ return;
168
+ }
169
+ if (instance.installed && instance.plugin.uninstall) {
170
+ try {
171
+ await instance.plugin.uninstall();
172
+ } catch (error) {
173
+ console.error(`[AuthKeeper] Error uninstalling plugin "${name}":`, error);
174
+ }
175
+ }
176
+ this.plugins.delete(name);
177
+ }
178
+ /**
179
+ * Get a plugin by name
180
+ *
181
+ * @param name - Plugin name
182
+ * @returns Plugin or undefined if not found
183
+ */
184
+ get(name) {
185
+ const instance = this.plugins.get(name);
186
+ return instance?.plugin;
187
+ }
188
+ /**
189
+ * Get plugin API by name
190
+ *
191
+ * @param name - Plugin name
192
+ * @returns Plugin API or undefined if not found
193
+ */
194
+ getApi(name) {
195
+ const instance = this.plugins.get(name);
196
+ return instance?.api;
197
+ }
198
+ /**
199
+ * Check if a plugin is registered
200
+ *
201
+ * @param name - Plugin name
202
+ * @returns true if plugin is registered
203
+ */
204
+ has(name) {
205
+ return this.plugins.has(name);
206
+ }
207
+ /**
208
+ * Check if a plugin is installed
209
+ *
210
+ * @param name - Plugin name
211
+ * @returns true if plugin is installed
212
+ */
213
+ isInstalled(name) {
214
+ const instance = this.plugins.get(name);
215
+ return instance?.installed || false;
216
+ }
217
+ /**
218
+ * List all plugins
219
+ *
220
+ * @returns Array of plugin information
221
+ */
222
+ list() {
223
+ return Array.from(this.plugins.entries()).map(([name, instance]) => ({
224
+ name,
225
+ version: instance.plugin.version,
226
+ type: instance.plugin.type,
227
+ enabled: instance.installed
228
+ }));
229
+ }
230
+ /**
231
+ * Get all plugin names
232
+ *
233
+ * @returns Array of plugin names
234
+ */
235
+ getNames() {
236
+ return Array.from(this.plugins.keys());
237
+ }
238
+ /**
239
+ * Clear all plugins
240
+ */
241
+ clear() {
242
+ this.plugins.clear();
243
+ }
244
+ };
245
+
246
+ // src/kernel/kernel.ts
247
+ var AuthKeeperKernel = class {
248
+ constructor(options) {
249
+ this.initialized = false;
250
+ this.options = {
251
+ autoRefresh: true,
252
+ refreshThreshold: 60,
253
+ syncTabs: true,
254
+ ...options
255
+ };
256
+ this.pluginRegistry = new PluginRegistry();
257
+ this.eventBus = new EventBus();
258
+ }
259
+ // ============================================================================
260
+ // Lifecycle
261
+ // ============================================================================
262
+ /**
263
+ * Initialize the kernel
264
+ *
265
+ * 1. Install core plugins
266
+ * 2. Install user-provided plugins
267
+ * 3. Load tokens from storage
268
+ * 4. Schedule refresh if authenticated
269
+ */
270
+ async init() {
271
+ if (this.initialized) {
272
+ return;
273
+ }
274
+ if (this.options.plugins) {
275
+ for (const plugin of this.options.plugins) {
276
+ await this.register(plugin);
277
+ }
278
+ }
279
+ this.initialized = true;
280
+ }
281
+ /**
282
+ * Destroy the kernel and cleanup
283
+ */
284
+ destroy() {
285
+ this.cancelScheduledRefresh();
286
+ this.eventBus.clear();
287
+ const pluginNames = this.pluginRegistry.getNames();
288
+ for (const name of pluginNames) {
289
+ this.pluginRegistry.uninstall(name);
290
+ }
291
+ this.pluginRegistry.clear();
292
+ this.initialized = false;
293
+ }
294
+ // ============================================================================
295
+ // Token Management
296
+ // ============================================================================
297
+ /**
298
+ * Set authentication tokens
299
+ *
300
+ * Delegates to token-store plugin.
301
+ */
302
+ setTokens(tokens) {
303
+ const tokenStore = this.pluginRegistry.getApi("token-store");
304
+ if (!tokenStore) {
305
+ throw new AuthError("CONFIG_ERROR", "token-store plugin not installed");
306
+ }
307
+ tokenStore.set(tokens);
308
+ this.emit({
309
+ type: "login",
310
+ tokens,
311
+ timestamp: Date.now()
312
+ });
313
+ if (this.options.autoRefresh && !this.isExpired()) {
314
+ this.scheduleRefresh();
315
+ }
316
+ }
317
+ /**
318
+ * Get access token
319
+ *
320
+ * Delegates to token-store plugin.
321
+ */
322
+ getAccessToken() {
323
+ const tokenStore = this.pluginRegistry.getApi("token-store");
324
+ if (!tokenStore) {
325
+ return null;
326
+ }
327
+ return tokenStore.getAccessToken();
328
+ }
329
+ /**
330
+ * Get refresh token
331
+ *
332
+ * Delegates to token-store plugin.
333
+ */
334
+ getRefreshToken() {
335
+ const tokenStore = this.pluginRegistry.getApi("token-store");
336
+ if (!tokenStore) {
337
+ return null;
338
+ }
339
+ return tokenStore.getRefreshToken();
340
+ }
341
+ /**
342
+ * Clear all tokens
343
+ */
344
+ clearTokens() {
345
+ const tokenStore = this.pluginRegistry.getApi("token-store");
346
+ if (tokenStore) {
347
+ tokenStore.clear();
348
+ }
349
+ }
350
+ // ============================================================================
351
+ // Auth State
352
+ // ============================================================================
353
+ /**
354
+ * Check if user is authenticated
355
+ */
356
+ isAuthenticated() {
357
+ const accessToken = this.getAccessToken();
358
+ return accessToken !== null && !this.isExpired();
359
+ }
360
+ /**
361
+ * Check if token is expired
362
+ *
363
+ * Delegates to token-store plugin.
364
+ */
365
+ isExpired() {
366
+ const tokenStore = this.pluginRegistry.getApi("token-store");
367
+ if (!tokenStore) {
368
+ return true;
369
+ }
370
+ return tokenStore.isExpired();
371
+ }
372
+ /**
373
+ * Get token expiration date
374
+ *
375
+ * Delegates to token-store plugin.
376
+ */
377
+ getExpiresAt() {
378
+ const tokenStore = this.pluginRegistry.getApi("token-store");
379
+ if (!tokenStore) {
380
+ return null;
381
+ }
382
+ return tokenStore.getExpiresAt();
383
+ }
384
+ /**
385
+ * Get time until expiry in milliseconds
386
+ *
387
+ * Delegates to token-store plugin.
388
+ */
389
+ getTimeUntilExpiry() {
390
+ const tokenStore = this.pluginRegistry.getApi("token-store");
391
+ if (!tokenStore) {
392
+ return null;
393
+ }
394
+ return tokenStore.getExpiresIn();
395
+ }
396
+ // ============================================================================
397
+ // Token Decoding
398
+ // ============================================================================
399
+ /**
400
+ * Decode token payload
401
+ *
402
+ * Delegates to token-decoder plugin.
403
+ */
404
+ decode() {
405
+ const tokenDecoder = this.pluginRegistry.getApi("token-decoder");
406
+ if (!tokenDecoder) {
407
+ return null;
408
+ }
409
+ return tokenDecoder.decode();
410
+ }
411
+ /**
412
+ * Get specific claim from token
413
+ *
414
+ * Delegates to token-decoder plugin.
415
+ */
416
+ getClaim(key) {
417
+ const tokenDecoder = this.pluginRegistry.getApi("token-decoder");
418
+ if (!tokenDecoder) {
419
+ return void 0;
420
+ }
421
+ return tokenDecoder.getClaim(key);
422
+ }
423
+ /**
424
+ * Get multiple claims from token
425
+ *
426
+ * Delegates to token-decoder plugin.
427
+ */
428
+ getClaims(keys) {
429
+ const tokenDecoder = this.pluginRegistry.getApi("token-decoder");
430
+ if (!tokenDecoder) {
431
+ return {};
432
+ }
433
+ return tokenDecoder.getClaims(keys);
434
+ }
435
+ // ============================================================================
436
+ // Refresh
437
+ // ============================================================================
438
+ /**
439
+ * Manually refresh tokens
440
+ *
441
+ * Delegates to refresh-engine plugin.
442
+ */
443
+ async refresh() {
444
+ const refreshEngine = this.pluginRegistry.getApi("refresh-engine");
445
+ if (!refreshEngine) {
446
+ throw new AuthError("CONFIG_ERROR", "refresh-engine plugin not installed");
447
+ }
448
+ return refreshEngine.refresh();
449
+ }
450
+ /**
451
+ * Schedule automatic refresh
452
+ *
453
+ * Delegates to refresh-engine plugin.
454
+ */
455
+ scheduleRefresh() {
456
+ if (!this.options.autoRefresh) {
457
+ return;
458
+ }
459
+ const refreshEngine = this.pluginRegistry.getApi("refresh-engine");
460
+ if (refreshEngine) {
461
+ refreshEngine.scheduleRefresh();
462
+ }
463
+ }
464
+ /**
465
+ * Cancel scheduled refresh
466
+ *
467
+ * Delegates to refresh-engine plugin.
468
+ */
469
+ cancelScheduledRefresh() {
470
+ const refreshEngine = this.pluginRegistry.getApi("refresh-engine");
471
+ if (refreshEngine) {
472
+ refreshEngine.cancelScheduledRefresh();
473
+ }
474
+ }
475
+ // ============================================================================
476
+ // Logout
477
+ // ============================================================================
478
+ /**
479
+ * Logout user
480
+ *
481
+ * Clears tokens and emits logout event.
482
+ */
483
+ logout(options = {}) {
484
+ this.cancelScheduledRefresh();
485
+ this.clearTokens();
486
+ this.emit({
487
+ type: "logout",
488
+ reason: "manual",
489
+ timestamp: Date.now()
490
+ });
491
+ if (options.redirect && typeof window !== "undefined") {
492
+ window.location.href = options.redirect;
493
+ }
494
+ }
495
+ // ============================================================================
496
+ // Interceptors
497
+ // ============================================================================
498
+ /**
499
+ * Create authenticated fetch function
500
+ *
501
+ * Delegates to fetch-interceptor plugin.
502
+ */
503
+ createFetch(options) {
504
+ const fetchInterceptor = this.pluginRegistry.getApi("fetch-interceptor");
505
+ if (!fetchInterceptor) {
506
+ return fetch.bind(globalThis);
507
+ }
508
+ return fetchInterceptor.createFetch(options);
509
+ }
510
+ /**
511
+ * Wrap global fetch with auth
512
+ *
513
+ * Delegates to fetch-interceptor plugin.
514
+ */
515
+ wrapFetch(fetch2) {
516
+ const fetchInterceptor = this.pluginRegistry.getApi("fetch-interceptor");
517
+ if (fetchInterceptor) {
518
+ fetchInterceptor.wrapFetch(fetch2);
519
+ }
520
+ }
521
+ // ============================================================================
522
+ // Plugin Management
523
+ // ============================================================================
524
+ /**
525
+ * Register and install a plugin
526
+ */
527
+ async register(plugin) {
528
+ this.pluginRegistry.register(plugin);
529
+ await this.pluginRegistry.install(plugin.name, this);
530
+ }
531
+ /**
532
+ * Unregister a plugin
533
+ */
534
+ async unregister(pluginName) {
535
+ await this.pluginRegistry.uninstall(pluginName);
536
+ }
537
+ /**
538
+ * Get plugin by name
539
+ */
540
+ getPlugin(name) {
541
+ return this.pluginRegistry.get(name);
542
+ }
543
+ /**
544
+ * List all plugins
545
+ */
546
+ listPlugins() {
547
+ return this.pluginRegistry.list();
548
+ }
549
+ // ============================================================================
550
+ // Event System
551
+ // ============================================================================
552
+ /**
553
+ * Emit an event
554
+ */
555
+ emit(event) {
556
+ this.eventBus.emit(event);
557
+ if (event.type === "error" && this.options.onError) {
558
+ this.options.onError(event.error);
559
+ }
560
+ }
561
+ /**
562
+ * Subscribe to events
563
+ */
564
+ on(eventType, handler) {
565
+ return this.eventBus.on(eventType, handler);
566
+ }
567
+ /**
568
+ * Unsubscribe from events
569
+ */
570
+ off(eventType, handler) {
571
+ this.eventBus.off(eventType, handler);
572
+ }
573
+ // ============================================================================
574
+ // Configuration
575
+ // ============================================================================
576
+ /**
577
+ * Update configuration
578
+ */
579
+ configure(options) {
580
+ this.options = {
581
+ ...this.options,
582
+ ...options
583
+ };
584
+ if (options.refreshThreshold !== void 0) {
585
+ const refreshEngine = this.pluginRegistry.getApi("refresh-engine");
586
+ if (refreshEngine && refreshEngine.setThreshold) {
587
+ refreshEngine.setThreshold(options.refreshThreshold);
588
+ }
589
+ }
590
+ }
591
+ /**
592
+ * Get current configuration
593
+ */
594
+ 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();
680
+ }
681
+ };
682
+ function createTokenStorePlugin(options) {
683
+ return new TokenStorePlugin(options);
684
+ }
685
+
686
+ // src/utils/base64.ts
687
+ function base64UrlEncode(buffer) {
688
+ let binary = "";
689
+ for (let i = 0; i < buffer.length; i++) {
690
+ binary += String.fromCharCode(buffer[i]);
691
+ }
692
+ const base64 = typeof window !== "undefined" ? btoa(binary) : Buffer.from(binary, "binary").toString("base64");
693
+ return base64.replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
694
+ }
695
+ function base64UrlDecode(str) {
696
+ let base64 = str.replace(/-/g, "+").replace(/_/g, "/");
697
+ const pad = str.length % 4;
698
+ if (pad === 2) {
699
+ base64 += "==";
700
+ } else if (pad === 3) {
701
+ base64 += "=";
702
+ }
703
+ const binary = typeof window !== "undefined" ? atob(base64) : Buffer.from(base64, "base64").toString("binary");
704
+ return decodeURIComponent(
705
+ binary.split("").map((c) => {
706
+ return "%" + ("00" + c.charCodeAt(0).toString(16)).slice(-2);
707
+ }).join("")
708
+ );
709
+ }
710
+ function stringToBase64Url(str) {
711
+ const utf8Bytes = new TextEncoder().encode(str);
712
+ return base64UrlEncode(utf8Bytes);
713
+ }
714
+ function base64UrlDecodeToBytes(str) {
715
+ let base64 = str.replace(/-/g, "+").replace(/_/g, "/");
716
+ const pad = str.length % 4;
717
+ if (pad === 2) {
718
+ base64 += "==";
719
+ } else if (pad === 3) {
720
+ base64 += "=";
721
+ }
722
+ if (typeof window !== "undefined") {
723
+ const binary = atob(base64);
724
+ const bytes = new Uint8Array(binary.length);
725
+ for (let i = 0; i < binary.length; i++) {
726
+ bytes[i] = binary.charCodeAt(i);
727
+ }
728
+ return bytes;
729
+ } else {
730
+ return new Uint8Array(Buffer.from(base64, "base64"));
731
+ }
732
+ }
733
+
734
+ // src/utils/jwt.ts
735
+ function decodeJwt(token) {
736
+ const parts = token.split(".");
737
+ if (parts.length !== 3) {
738
+ throw new AuthError("TOKEN_DECODE_FAILED", "Invalid JWT format: must have 3 parts", {
739
+ context: { parts: parts.length }
740
+ });
741
+ }
742
+ try {
743
+ const headerJson = base64UrlDecode(parts[0]);
744
+ const header = JSON.parse(headerJson);
745
+ const payloadJson = base64UrlDecode(parts[1]);
746
+ const payload = JSON.parse(payloadJson);
747
+ return { header, payload };
748
+ } catch (error) {
749
+ throw new AuthError("TOKEN_DECODE_FAILED", "Failed to decode JWT", {
750
+ cause: error
751
+ });
752
+ }
753
+ }
754
+ function decodePayload(token) {
755
+ return decodeJwt(token).payload;
756
+ }
757
+ function decodeHeader(token) {
758
+ return decodeJwt(token).header;
759
+ }
760
+ function isValidJwtFormat(token) {
761
+ if (!token || typeof token !== "string") {
762
+ return false;
763
+ }
764
+ const parts = token.split(".");
765
+ if (parts.length !== 3) {
766
+ return false;
767
+ }
768
+ try {
769
+ base64UrlDecode(parts[0]);
770
+ base64UrlDecode(parts[1]);
771
+ return true;
772
+ } catch {
773
+ return false;
774
+ }
775
+ }
776
+ function getTokenExpiry(token) {
777
+ try {
778
+ const payload = decodePayload(token);
779
+ if (payload.exp) {
780
+ return new Date(payload.exp * 1e3);
781
+ }
782
+ return null;
783
+ } catch {
784
+ return null;
785
+ }
786
+ }
787
+ function isTokenExpired(token, bufferSeconds = 0) {
788
+ const expiry = getTokenExpiry(token);
789
+ if (!expiry) {
790
+ return false;
791
+ }
792
+ const now = Date.now();
793
+ const expiryTime = expiry.getTime() - bufferSeconds * 1e3;
794
+ return now >= expiryTime;
795
+ }
796
+ function getTimeUntilExpiry(token) {
797
+ const expiry = getTokenExpiry(token);
798
+ if (!expiry) {
799
+ return null;
800
+ }
801
+ const now = Date.now();
802
+ const timeUntil = expiry.getTime() - now;
803
+ return Math.max(0, timeUntil);
804
+ }
805
+ function getClaim(token, claim) {
806
+ try {
807
+ const payload = decodePayload(token);
808
+ return payload[claim];
809
+ } catch {
810
+ return void 0;
811
+ }
812
+ }
813
+ function getClaims(token, claims) {
814
+ try {
815
+ const payload = decodePayload(token);
816
+ const result = {};
817
+ for (const claim of claims) {
818
+ if (claim in payload) {
819
+ result[claim] = payload[claim];
820
+ }
821
+ }
822
+ return result;
823
+ } catch {
824
+ return {};
825
+ }
826
+ }
827
+
828
+ // src/plugins/core/token-decoder.ts
829
+ var TokenDecoderPlugin = class {
830
+ constructor() {
831
+ this.name = "token-decoder";
832
+ this.version = "1.0.0";
833
+ this.type = "core";
834
+ }
835
+ install(kernel) {
836
+ this.kernel = kernel;
837
+ return {
838
+ decode: this.decode.bind(this),
839
+ getHeader: this.getHeader.bind(this),
840
+ getClaim: this.getClaimFromToken.bind(this),
841
+ getClaims: this.getClaimsFromToken.bind(this),
842
+ getExpiry: this.getExpiry.bind(this),
843
+ isExpired: this.isExpiredToken.bind(this),
844
+ getTokenInfo: this.getTokenInfo.bind(this)
845
+ };
846
+ }
847
+ /**
848
+ * Decode token payload
849
+ */
850
+ decode(token) {
851
+ const jwt = token || this.kernel.getAccessToken();
852
+ if (!jwt) {
853
+ return null;
854
+ }
855
+ try {
856
+ return decodePayload(jwt);
857
+ } catch {
858
+ return null;
859
+ }
860
+ }
861
+ /**
862
+ * Decode token header
863
+ */
864
+ getHeader(token) {
865
+ const jwt = token || this.kernel.getAccessToken();
866
+ if (!jwt) {
867
+ return null;
868
+ }
869
+ try {
870
+ return decodeHeader(jwt);
871
+ } catch {
872
+ return null;
873
+ }
874
+ }
875
+ /**
876
+ * Get specific claim from token
877
+ */
878
+ getClaimFromToken(key, token) {
879
+ const jwt = token || this.kernel.getAccessToken();
880
+ if (!jwt) {
881
+ return void 0;
882
+ }
883
+ return getClaim(jwt, key);
884
+ }
885
+ /**
886
+ * Get multiple claims from token
887
+ */
888
+ getClaimsFromToken(keys, token) {
889
+ const jwt = token || this.kernel.getAccessToken();
890
+ if (!jwt) {
891
+ return {};
892
+ }
893
+ return getClaims(jwt, keys);
894
+ }
895
+ /**
896
+ * Get token expiry
897
+ */
898
+ getExpiry(token) {
899
+ const jwt = token || this.kernel.getAccessToken();
900
+ if (!jwt) {
901
+ return null;
902
+ }
903
+ return getTokenExpiry(jwt);
904
+ }
905
+ /**
906
+ * Check if token is expired
907
+ */
908
+ isExpiredToken(token) {
909
+ const jwt = token || this.kernel.getAccessToken();
910
+ if (!jwt) {
911
+ return true;
912
+ }
913
+ return isTokenExpired(jwt);
914
+ }
915
+ /**
916
+ * Get complete token information
917
+ */
918
+ getTokenInfo(token) {
919
+ const jwt = token || this.kernel.getAccessToken();
920
+ if (!jwt) {
921
+ return null;
922
+ }
923
+ try {
924
+ const { header, payload } = decodeJwt(jwt);
925
+ const expiresAt = getTokenExpiry(jwt);
926
+ const isExpired2 = isTokenExpired(jwt);
927
+ const expiresIn = getTimeUntilExpiry(jwt);
928
+ return {
929
+ raw: jwt,
930
+ header,
931
+ payload,
932
+ expiresAt,
933
+ isExpired: isExpired2,
934
+ expiresIn
935
+ };
936
+ } catch {
937
+ return null;
938
+ }
939
+ }
940
+ uninstall() {
941
+ }
942
+ };
943
+ function createTokenDecoderPlugin() {
944
+ return new TokenDecoderPlugin();
945
+ }
946
+
947
+ // src/plugins/core/refresh-engine.ts
948
+ var RefreshEnginePlugin = class {
949
+ constructor(options) {
950
+ this.name = "refresh-engine";
951
+ this.version = "1.0.0";
952
+ this.type = "core";
953
+ this.isRefreshingFlag = false;
954
+ this.refreshPromise = null;
955
+ this.scheduledRefreshTimeout = null;
956
+ this.options = options;
957
+ this.refreshFn = options.refreshFn;
958
+ this.threshold = options.threshold || 60;
959
+ this.maxRetries = options.maxRetries || 3;
960
+ this.retryDelay = options.retryDelay || 1e3;
961
+ }
962
+ install(kernel) {
963
+ this.kernel = kernel;
964
+ return {
965
+ refresh: this.refresh.bind(this),
966
+ scheduleRefresh: this.scheduleRefresh.bind(this),
967
+ cancelScheduledRefresh: this.cancelScheduledRefresh.bind(this),
968
+ isRefreshing: () => this.isRefreshingFlag,
969
+ getNextRefreshAt: this.getNextRefreshAt.bind(this),
970
+ setRefreshFn: (fn) => {
971
+ this.refreshFn = fn;
972
+ },
973
+ setThreshold: (seconds) => {
974
+ this.threshold = seconds;
975
+ }
976
+ };
977
+ }
978
+ /**
979
+ * Refresh tokens
980
+ *
981
+ * Queues concurrent requests - only one refresh executes at a time.
982
+ */
983
+ async refresh() {
984
+ if (this.refreshPromise) {
985
+ return this.refreshPromise;
986
+ }
987
+ this.isRefreshingFlag = true;
988
+ this.refreshPromise = this.executeRefresh();
989
+ try {
990
+ const tokens = await this.refreshPromise;
991
+ return tokens;
992
+ } finally {
993
+ this.isRefreshingFlag = false;
994
+ this.refreshPromise = null;
995
+ }
996
+ }
997
+ /**
998
+ * Execute token refresh with retry logic
999
+ */
1000
+ async executeRefresh(retryCount = 0) {
1001
+ if (this.options.onRefreshStart) {
1002
+ this.options.onRefreshStart();
1003
+ }
1004
+ const refreshToken = this.kernel.getRefreshToken();
1005
+ if (!refreshToken) {
1006
+ const error = new Error("No refresh token available");
1007
+ error.name = "AuthError";
1008
+ error.code = "REFRESH_TOKEN_MISSING";
1009
+ this.kernel.emit({
1010
+ type: "error",
1011
+ error,
1012
+ context: "refresh",
1013
+ timestamp: Date.now()
1014
+ });
1015
+ throw error;
1016
+ }
1017
+ try {
1018
+ const previousExpiresAt = this.kernel.getExpiresAt();
1019
+ const newTokens = await this.refreshFn(refreshToken);
1020
+ this.kernel.setTokens(newTokens);
1021
+ const newExpiresAt = this.kernel.getExpiresAt();
1022
+ this.kernel.emit({
1023
+ type: "refresh",
1024
+ tokens: newTokens,
1025
+ previousExpiresAt,
1026
+ newExpiresAt,
1027
+ timestamp: Date.now()
1028
+ });
1029
+ if (this.options.onRefreshSuccess) {
1030
+ this.options.onRefreshSuccess(newTokens);
1031
+ }
1032
+ this.scheduleRefresh();
1033
+ return newTokens;
1034
+ } catch (error) {
1035
+ if (retryCount < this.maxRetries) {
1036
+ const delay = this.retryDelay * Math.pow(2, retryCount);
1037
+ await new Promise((resolve) => setTimeout(resolve, delay));
1038
+ return this.executeRefresh(retryCount + 1);
1039
+ }
1040
+ const authError = new Error("Token refresh failed");
1041
+ authError.name = "AuthError";
1042
+ authError.code = "REFRESH_FAILED";
1043
+ authError.cause = error;
1044
+ authError.context = { retryCount };
1045
+ this.kernel.emit({
1046
+ type: "error",
1047
+ error: authError,
1048
+ context: "refresh",
1049
+ timestamp: Date.now()
1050
+ });
1051
+ if (this.options.onRefreshError) {
1052
+ this.options.onRefreshError(authError);
1053
+ }
1054
+ throw authError;
1055
+ }
1056
+ }
1057
+ /**
1058
+ * Schedule automatic refresh
1059
+ *
1060
+ * Schedules refresh before token expires (threshold seconds before).
1061
+ */
1062
+ scheduleRefresh() {
1063
+ this.cancelScheduledRefresh();
1064
+ const expiresIn = this.kernel.getTimeUntilExpiry();
1065
+ if (!expiresIn) {
1066
+ return;
1067
+ }
1068
+ const refreshIn = expiresIn - this.threshold * 1e3;
1069
+ if (refreshIn > 0) {
1070
+ this.scheduledRefreshTimeout = setTimeout(() => {
1071
+ this.refresh().catch((error) => {
1072
+ console.error("[AuthKeeper] Scheduled refresh failed:", error);
1073
+ });
1074
+ }, refreshIn);
1075
+ } else {
1076
+ this.refresh().catch((error) => {
1077
+ console.error("[AuthKeeper] Immediate refresh failed:", error);
1078
+ });
1079
+ }
1080
+ }
1081
+ /**
1082
+ * Cancel scheduled refresh
1083
+ */
1084
+ cancelScheduledRefresh() {
1085
+ if (this.scheduledRefreshTimeout) {
1086
+ clearTimeout(this.scheduledRefreshTimeout);
1087
+ this.scheduledRefreshTimeout = null;
1088
+ }
1089
+ }
1090
+ /**
1091
+ * Get next scheduled refresh time
1092
+ */
1093
+ getNextRefreshAt() {
1094
+ const expiresAt = this.kernel.getExpiresAt();
1095
+ if (!expiresAt) {
1096
+ return null;
1097
+ }
1098
+ const refreshAt = new Date(expiresAt.getTime() - this.threshold * 1e3);
1099
+ return refreshAt;
1100
+ }
1101
+ /**
1102
+ * Uninstall plugin
1103
+ */
1104
+ uninstall() {
1105
+ this.cancelScheduledRefresh();
1106
+ }
1107
+ };
1108
+ function createRefreshEnginePlugin(options) {
1109
+ return new RefreshEnginePlugin(options);
1110
+ }
1111
+
1112
+ // src/plugins/core/storage-memory.ts
1113
+ var MemoryStorageAdapter = class {
1114
+ constructor(options = {}) {
1115
+ this.store = /* @__PURE__ */ new Map();
1116
+ this.prefix = options.prefix || "authkeeper:";
1117
+ }
1118
+ /**
1119
+ * Get value by key
1120
+ */
1121
+ get(key) {
1122
+ return this.store.get(this.prefix + key) || null;
1123
+ }
1124
+ /**
1125
+ * Set value by key
1126
+ */
1127
+ set(key, value) {
1128
+ this.store.set(this.prefix + key, value);
1129
+ }
1130
+ /**
1131
+ * Remove value by key
1132
+ */
1133
+ remove(key) {
1134
+ this.store.delete(this.prefix + key);
1135
+ }
1136
+ /**
1137
+ * Clear all values
1138
+ */
1139
+ clear() {
1140
+ const keysToDelete = [];
1141
+ for (const key of this.store.keys()) {
1142
+ if (key.startsWith(this.prefix)) {
1143
+ keysToDelete.push(key);
1144
+ }
1145
+ }
1146
+ keysToDelete.forEach((key) => this.store.delete(key));
1147
+ }
1148
+ };
1149
+ function createMemoryStorage(options) {
1150
+ return new MemoryStorageAdapter(options);
1151
+ }
1152
+
1153
+ // src/plugins/core/fetch-interceptor.ts
1154
+ var FetchInterceptorPlugin = class {
1155
+ constructor() {
1156
+ this.name = "fetch-interceptor";
1157
+ this.version = "1.0.0";
1158
+ this.type = "core";
1159
+ this.originalFetch = null;
1160
+ }
1161
+ install(kernel) {
1162
+ this.kernel = kernel;
1163
+ return {
1164
+ createFetch: this.createFetch.bind(this),
1165
+ wrapFetch: this.wrapFetch.bind(this),
1166
+ unwrapFetch: this.unwrapFetch.bind(this)
1167
+ };
1168
+ }
1169
+ /**
1170
+ * Create authenticated fetch function
1171
+ */
1172
+ createFetch(options = {}) {
1173
+ const {
1174
+ headerName = "Authorization",
1175
+ headerPrefix = "Bearer ",
1176
+ includeUrls = [],
1177
+ excludeUrls = [],
1178
+ retry401 = true,
1179
+ maxRetries = 1,
1180
+ onUnauthorized
1181
+ } = options;
1182
+ return async (input, init) => {
1183
+ const url = typeof input === "string" ? input : input instanceof URL ? input.href : input.url;
1184
+ const shouldInclude = includeUrls.length === 0 || includeUrls.some(
1185
+ (pattern) => typeof pattern === "string" ? url.includes(pattern) : pattern.test(url)
1186
+ );
1187
+ const shouldExclude = excludeUrls.some(
1188
+ (pattern) => typeof pattern === "string" ? url.includes(pattern) : pattern.test(url)
1189
+ );
1190
+ if (!shouldInclude || shouldExclude) {
1191
+ return fetch(input, init);
1192
+ }
1193
+ const accessToken = this.kernel.getAccessToken();
1194
+ const headers = new Headers(init?.headers);
1195
+ if (accessToken) {
1196
+ headers.set(headerName, headerPrefix + accessToken);
1197
+ }
1198
+ let response = await fetch(input, {
1199
+ ...init,
1200
+ headers
1201
+ });
1202
+ if (response.status === 401 && retry401 && maxRetries > 0) {
1203
+ if (onUnauthorized) {
1204
+ onUnauthorized(response);
1205
+ }
1206
+ try {
1207
+ await this.kernel.refresh();
1208
+ const newToken = this.kernel.getAccessToken();
1209
+ if (newToken) {
1210
+ headers.set(headerName, headerPrefix + newToken);
1211
+ response = await fetch(input, {
1212
+ ...init,
1213
+ headers
1214
+ });
1215
+ }
1216
+ } catch (error) {
1217
+ console.error("[AuthKeeper] Token refresh failed during 401 retry:", error);
1218
+ }
1219
+ }
1220
+ return response;
1221
+ };
1222
+ }
1223
+ /**
1224
+ * Wrap global fetch with auth
1225
+ */
1226
+ wrapFetch(fetch2) {
1227
+ if (!this.originalFetch) {
1228
+ this.originalFetch = fetch2;
1229
+ }
1230
+ const authFetch = this.createFetch();
1231
+ globalThis.fetch = authFetch;
1232
+ }
1233
+ /**
1234
+ * Restore original fetch
1235
+ */
1236
+ unwrapFetch() {
1237
+ if (this.originalFetch) {
1238
+ globalThis.fetch = this.originalFetch;
1239
+ this.originalFetch = null;
1240
+ }
1241
+ }
1242
+ uninstall() {
1243
+ this.unwrapFetch();
1244
+ }
1245
+ };
1246
+ function createFetchInterceptorPlugin() {
1247
+ return new FetchInterceptorPlugin();
1248
+ }
1249
+
1250
+ // src/factory.ts
1251
+ async function createAuthKeeper(options) {
1252
+ const kernel = new AuthKeeperKernel(options);
1253
+ await kernel.register(createTokenStorePlugin());
1254
+ await kernel.register(createTokenDecoderPlugin());
1255
+ await kernel.register(
1256
+ createRefreshEnginePlugin({
1257
+ refreshFn: options.refreshToken,
1258
+ threshold: options.refreshThreshold
1259
+ })
1260
+ );
1261
+ await kernel.register(createFetchInterceptorPlugin());
1262
+ await kernel.init();
1263
+ return kernel;
1264
+ }
1265
+
1266
+ // src/utils/time.ts
1267
+ function isExpired(expiresAt, bufferMs = 0) {
1268
+ if (!expiresAt) {
1269
+ return false;
1270
+ }
1271
+ const now = Date.now();
1272
+ return now >= expiresAt - bufferMs;
1273
+ }
1274
+ function getExpiresIn(expiresAt) {
1275
+ if (!expiresAt) {
1276
+ return null;
1277
+ }
1278
+ const now = Date.now();
1279
+ const timeUntil = expiresAt - now;
1280
+ return Math.max(0, timeUntil);
1281
+ }
1282
+ function secondsToMs(seconds) {
1283
+ return seconds * 1e3;
1284
+ }
1285
+ function msToSeconds(ms) {
1286
+ return Math.floor(ms / 1e3);
1287
+ }
1288
+ function calculateExpiresAt(expiresIn) {
1289
+ return Date.now() + secondsToMs(expiresIn);
1290
+ }
1291
+ function formatTimeRemaining(ms) {
1292
+ if (ms <= 0) {
1293
+ return "expired";
1294
+ }
1295
+ const seconds = Math.floor(ms / 1e3);
1296
+ const minutes = Math.floor(seconds / 60);
1297
+ const hours = Math.floor(minutes / 60);
1298
+ const days = Math.floor(hours / 24);
1299
+ if (days > 0) {
1300
+ const remainingHours = hours % 24;
1301
+ return remainingHours > 0 ? `${days}d ${remainingHours}h` : `${days}d`;
1302
+ }
1303
+ if (hours > 0) {
1304
+ const remainingMinutes = minutes % 60;
1305
+ return remainingMinutes > 0 ? `${hours}h ${remainingMinutes}m` : `${hours}h`;
1306
+ }
1307
+ if (minutes > 0) {
1308
+ const remainingSeconds = seconds % 60;
1309
+ return remainingSeconds > 0 ? `${minutes}m ${remainingSeconds}s` : `${minutes}m`;
1310
+ }
1311
+ return `${seconds}s`;
1312
+ }
1313
+
1314
+ // src/utils/crypto.ts
1315
+ function generateCodeVerifier(length = 64) {
1316
+ if (length < 43 || length > 128) {
1317
+ throw new Error("Code verifier length must be between 43 and 128 characters");
1318
+ }
1319
+ const byteLength = Math.ceil(length * 3 / 4);
1320
+ const randomBytes = new Uint8Array(byteLength);
1321
+ crypto.getRandomValues(randomBytes);
1322
+ const verifier = base64UrlEncode(randomBytes).substring(0, length);
1323
+ return verifier;
1324
+ }
1325
+ async function generateCodeChallenge(codeVerifier) {
1326
+ const encoder = new TextEncoder();
1327
+ const data = encoder.encode(codeVerifier);
1328
+ const hashBuffer = await crypto.subtle.digest("SHA-256", data);
1329
+ const hashArray = new Uint8Array(hashBuffer);
1330
+ return base64UrlEncode(hashArray);
1331
+ }
1332
+ function generateRandomString(length) {
1333
+ const byteLength = Math.ceil(length * 3 / 4);
1334
+ const randomBytes = new Uint8Array(byteLength);
1335
+ crypto.getRandomValues(randomBytes);
1336
+ return base64UrlEncode(randomBytes).substring(0, length);
1337
+ }
1338
+ function generateUuid() {
1339
+ if (typeof crypto.randomUUID === "function") {
1340
+ return crypto.randomUUID();
1341
+ }
1342
+ const bytes = new Uint8Array(16);
1343
+ crypto.getRandomValues(bytes);
1344
+ bytes[6] = bytes[6] & 15 | 64;
1345
+ bytes[8] = bytes[8] & 63 | 128;
1346
+ const hex = Array.from(bytes).map((b) => b.toString(16).padStart(2, "0")).join("");
1347
+ return `${hex.substring(0, 8)}-${hex.substring(8, 12)}-${hex.substring(12, 16)}-${hex.substring(16, 20)}-${hex.substring(20)}`;
1348
+ }
1349
+
1350
+ exports.AuthError = AuthError;
1351
+ exports.AuthKeeperKernel = AuthKeeperKernel;
1352
+ exports.EventBus = EventBus;
1353
+ exports.FetchInterceptorPlugin = FetchInterceptorPlugin;
1354
+ exports.MemoryStorageAdapter = MemoryStorageAdapter;
1355
+ 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
+ exports.calculateExpiresAt = calculateExpiresAt;
1363
+ 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
+ exports.formatTimeRemaining = formatTimeRemaining;
1373
+ exports.generateCodeChallenge = generateCodeChallenge;
1374
+ exports.generateCodeVerifier = generateCodeVerifier;
1375
+ exports.generateRandomString = generateRandomString;
1376
+ exports.generateUuid = generateUuid;
1377
+ exports.getClaim = getClaim;
1378
+ exports.getClaims = getClaims;
1379
+ exports.getExpiresIn = getExpiresIn;
1380
+ exports.getTimeUntilExpiry = getTimeUntilExpiry;
1381
+ exports.getTokenExpiry = getTokenExpiry;
1382
+ exports.isExpired = isExpired;
1383
+ exports.isTokenExpired = isTokenExpired;
1384
+ exports.isValidJwtFormat = isValidJwtFormat;
1385
+ exports.msToSeconds = msToSeconds;
1386
+ exports.secondsToMs = secondsToMs;
1387
+ exports.stringToBase64Url = stringToBase64Url;
1388
+ //# sourceMappingURL=index.cjs.map
1389
+ //# sourceMappingURL=index.cjs.map