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