@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.
@@ -0,0 +1,560 @@
1
+ import { K as KernelOptions, A as AuthKeeper, E as EventType, a as EventHandler, U as Unsubscribe, b as AuthEvent, P as Plugin, c as PluginInfo, T as TokenSet, d as TokenPayload, L as LogoutOptions, F as FetchInterceptorOptions, e as AuthFetch, f as TokenHeader } from './index-Dv1VLP97.cjs';
2
+ export { u as AuthError, h as AuthErrorCode, i as AuthErrorOptions, m as ErrorEvent, l as ExpiredEvent, V as FetchInterceptorAPI, y as FetchInterceptorPlugin, j as LoginEvent, r as LoginOptions, k as LogoutEvent, M as MemoryStorageAdapter, Q as MemoryStorageOptions, N as RefreshEngineAPI, O as RefreshEngineOptions, x as RefreshEnginePlugin, R as RefreshEvent, t as RefreshTokenFn, p as StorageAdapter, n as StorageChangeEvent, q as StorageType, S as StoredTokens, o as TabSyncEvent, J as TokenDecoderAPI, w as TokenDecoderPlugin, g as TokenInfo, H as TokenStoreAPI, I as TokenStoreOptions, v as TokenStorePlugin, s as UserInfo, G as createFetchInterceptorPlugin, D as createMemoryStorage, C as createRefreshEnginePlugin, B as createTokenDecoderPlugin, z as createTokenStorePlugin } from './index-Dv1VLP97.cjs';
3
+
4
+ /**
5
+ * Factory Function
6
+ *
7
+ * Creates and initializes an AuthKeeper instance with core plugins.
8
+ */
9
+
10
+ /**
11
+ * Create an AuthKeeper instance
12
+ *
13
+ * Automatically installs core plugins:
14
+ * - token-store: Token state management
15
+ * - token-decoder: JWT decoding
16
+ * - refresh-engine: Auto-refresh with queue
17
+ * - storage-memory: Default secure storage
18
+ * - fetch-interceptor: Auth header injection and 401 retry
19
+ *
20
+ * @param options - Configuration options
21
+ * @returns AuthKeeper instance
22
+ *
23
+ * @example
24
+ * ```typescript
25
+ * const auth = createAuthKeeper({
26
+ * storage: 'memory',
27
+ * refreshToken: async (token) => {
28
+ * const res = await fetch('/api/auth/refresh', {
29
+ * method: 'POST',
30
+ * body: JSON.stringify({ refreshToken: token }),
31
+ * })
32
+ * return res.json()
33
+ * },
34
+ * autoRefresh: true,
35
+ * refreshThreshold: 60,
36
+ * })
37
+ *
38
+ * await auth.init()
39
+ * ```
40
+ */
41
+ declare function createAuthKeeper(options: KernelOptions): Promise<AuthKeeper>;
42
+
43
+ /**
44
+ * Event Bus
45
+ *
46
+ * Pub/sub event system for kernel and plugins.
47
+ * Type-safe event handling with automatic unsubscribe.
48
+ */
49
+
50
+ /**
51
+ * EventBus class for managing event subscriptions and emissions
52
+ */
53
+ declare class EventBus {
54
+ private handlers;
55
+ /**
56
+ * Subscribe to an event
57
+ *
58
+ * @param eventType - Type of event to listen for
59
+ * @param handler - Handler function to call when event is emitted
60
+ * @returns Unsubscribe function
61
+ */
62
+ on<E extends EventType>(eventType: E, handler: EventHandler<E>): Unsubscribe;
63
+ /**
64
+ * Unsubscribe from an event
65
+ *
66
+ * @param eventType - Type of event to stop listening for
67
+ * @param handler - Handler function to remove
68
+ */
69
+ off<E extends EventType>(eventType: E, handler: EventHandler<E>): void;
70
+ /**
71
+ * Emit an event to all subscribers
72
+ *
73
+ * Handlers are executed asynchronously in the next tick to prevent blocking.
74
+ *
75
+ * @param event - Event to emit
76
+ */
77
+ emit(event: AuthEvent): void;
78
+ /**
79
+ * Remove all event handlers
80
+ */
81
+ clear(): void;
82
+ /**
83
+ * Get count of handlers for an event type
84
+ *
85
+ * @param eventType - Event type to count handlers for
86
+ * @returns Number of handlers
87
+ */
88
+ getHandlerCount(eventType: EventType): number;
89
+ /**
90
+ * Get all event types that have handlers
91
+ *
92
+ * @returns Array of event types
93
+ */
94
+ getActiveEventTypes(): EventType[];
95
+ }
96
+
97
+ /**
98
+ * Plugin Registry
99
+ *
100
+ * Manages plugin registration, installation, and lifecycle.
101
+ */
102
+
103
+ /**
104
+ * PluginRegistry class for managing plugins
105
+ */
106
+ declare class PluginRegistry {
107
+ private plugins;
108
+ /**
109
+ * Register a plugin
110
+ *
111
+ * @param plugin - Plugin to register
112
+ * @throws {AuthError} If plugin with same name already registered
113
+ */
114
+ register(plugin: Plugin): void;
115
+ /**
116
+ * Install a plugin
117
+ *
118
+ * Calls the plugin's install method and stores the returned API.
119
+ *
120
+ * @param name - Plugin name
121
+ * @param kernel - Kernel instance to pass to plugin
122
+ * @throws {AuthError} If plugin not found or already installed
123
+ */
124
+ install(name: string, kernel: AuthKeeper): Promise<void>;
125
+ /**
126
+ * Uninstall a plugin
127
+ *
128
+ * Calls the plugin's uninstall method if it exists.
129
+ *
130
+ * @param name - Plugin name
131
+ */
132
+ uninstall(name: string): Promise<void>;
133
+ /**
134
+ * Get a plugin by name
135
+ *
136
+ * @param name - Plugin name
137
+ * @returns Plugin or undefined if not found
138
+ */
139
+ get<P extends Plugin>(name: string): P | undefined;
140
+ /**
141
+ * Get plugin API by name
142
+ *
143
+ * @param name - Plugin name
144
+ * @returns Plugin API or undefined if not found
145
+ */
146
+ getApi<T = any>(name: string): T | undefined;
147
+ /**
148
+ * Check if a plugin is registered
149
+ *
150
+ * @param name - Plugin name
151
+ * @returns true if plugin is registered
152
+ */
153
+ has(name: string): boolean;
154
+ /**
155
+ * Check if a plugin is installed
156
+ *
157
+ * @param name - Plugin name
158
+ * @returns true if plugin is installed
159
+ */
160
+ isInstalled(name: string): boolean;
161
+ /**
162
+ * List all plugins
163
+ *
164
+ * @returns Array of plugin information
165
+ */
166
+ list(): PluginInfo[];
167
+ /**
168
+ * Get all plugin names
169
+ *
170
+ * @returns Array of plugin names
171
+ */
172
+ getNames(): string[];
173
+ /**
174
+ * Clear all plugins
175
+ */
176
+ clear(): void;
177
+ }
178
+
179
+ /**
180
+ * AuthKeeper Kernel
181
+ *
182
+ * The micro-kernel that orchestrates plugins and manages auth state.
183
+ * Most functionality is delegated to core plugins.
184
+ */
185
+
186
+ /**
187
+ * AuthKeeperKernel - Main kernel implementation
188
+ */
189
+ declare class AuthKeeperKernel implements AuthKeeper {
190
+ private pluginRegistry;
191
+ private eventBus;
192
+ private options;
193
+ private initialized;
194
+ constructor(options: KernelOptions);
195
+ /**
196
+ * Initialize the kernel
197
+ *
198
+ * 1. Install core plugins
199
+ * 2. Install user-provided plugins
200
+ * 3. Load tokens from storage
201
+ * 4. Schedule refresh if authenticated
202
+ */
203
+ init(): Promise<void>;
204
+ /**
205
+ * Destroy the kernel and cleanup
206
+ */
207
+ destroy(): void;
208
+ /**
209
+ * Set authentication tokens
210
+ *
211
+ * Delegates to token-store plugin.
212
+ */
213
+ setTokens(tokens: TokenSet): void;
214
+ /**
215
+ * Get access token
216
+ *
217
+ * Delegates to token-store plugin.
218
+ */
219
+ getAccessToken(): string | null;
220
+ /**
221
+ * Get refresh token
222
+ *
223
+ * Delegates to token-store plugin.
224
+ */
225
+ getRefreshToken(): string | null;
226
+ /**
227
+ * Clear all tokens
228
+ */
229
+ clearTokens(): void;
230
+ /**
231
+ * Check if user is authenticated
232
+ */
233
+ isAuthenticated(): boolean;
234
+ /**
235
+ * Check if token is expired
236
+ *
237
+ * Delegates to token-store plugin.
238
+ */
239
+ isExpired(): boolean;
240
+ /**
241
+ * Get token expiration date
242
+ *
243
+ * Delegates to token-store plugin.
244
+ */
245
+ getExpiresAt(): Date | null;
246
+ /**
247
+ * Get time until expiry in milliseconds
248
+ *
249
+ * Delegates to token-store plugin.
250
+ */
251
+ getTimeUntilExpiry(): number | null;
252
+ /**
253
+ * Decode token payload
254
+ *
255
+ * Delegates to token-decoder plugin.
256
+ */
257
+ decode<T = TokenPayload>(): T | null;
258
+ /**
259
+ * Get specific claim from token
260
+ *
261
+ * Delegates to token-decoder plugin.
262
+ */
263
+ getClaim<K extends keyof TokenPayload>(key: K): TokenPayload[K] | undefined;
264
+ /**
265
+ * Get multiple claims from token
266
+ *
267
+ * Delegates to token-decoder plugin.
268
+ */
269
+ getClaims<K extends keyof TokenPayload>(keys: K[]): Pick<TokenPayload, K>;
270
+ /**
271
+ * Manually refresh tokens
272
+ *
273
+ * Delegates to refresh-engine plugin.
274
+ */
275
+ refresh(): Promise<TokenSet>;
276
+ /**
277
+ * Schedule automatic refresh
278
+ *
279
+ * Delegates to refresh-engine plugin.
280
+ */
281
+ scheduleRefresh(): void;
282
+ /**
283
+ * Cancel scheduled refresh
284
+ *
285
+ * Delegates to refresh-engine plugin.
286
+ */
287
+ cancelScheduledRefresh(): void;
288
+ /**
289
+ * Logout user
290
+ *
291
+ * Clears tokens and emits logout event.
292
+ */
293
+ logout(options?: LogoutOptions): void;
294
+ /**
295
+ * Create authenticated fetch function
296
+ *
297
+ * Delegates to fetch-interceptor plugin.
298
+ */
299
+ createFetch(options?: FetchInterceptorOptions): AuthFetch;
300
+ /**
301
+ * Wrap global fetch with auth
302
+ *
303
+ * Delegates to fetch-interceptor plugin.
304
+ */
305
+ wrapFetch(fetch: typeof globalThis.fetch): void;
306
+ /**
307
+ * Register and install a plugin
308
+ */
309
+ register(plugin: Plugin): Promise<void>;
310
+ /**
311
+ * Unregister a plugin
312
+ */
313
+ unregister(pluginName: string): Promise<void>;
314
+ /**
315
+ * Get plugin by name
316
+ */
317
+ getPlugin<P extends Plugin>(name: string): P | undefined;
318
+ /**
319
+ * List all plugins
320
+ */
321
+ listPlugins(): PluginInfo[];
322
+ /**
323
+ * Emit an event
324
+ */
325
+ emit(event: AuthEvent): void;
326
+ /**
327
+ * Subscribe to events
328
+ */
329
+ on<E extends EventType>(eventType: E, handler: EventHandler<E>): Unsubscribe;
330
+ /**
331
+ * Unsubscribe from events
332
+ */
333
+ off<E extends EventType>(eventType: E, handler: EventHandler<E>): void;
334
+ /**
335
+ * Update configuration
336
+ */
337
+ configure(options: Partial<KernelOptions>): void;
338
+ /**
339
+ * Get current configuration
340
+ */
341
+ getOptions(): KernelOptions;
342
+ }
343
+
344
+ /**
345
+ * Base64 and Base64URL encoding/decoding utilities
346
+ *
347
+ * Implements Base64URL encoding/decoding from scratch (zero dependencies).
348
+ * Base64URL is used in JWTs and OAuth2 PKCE.
349
+ */
350
+ /**
351
+ * Encode a Uint8Array to Base64URL string
352
+ *
353
+ * Base64URL is like Base64 but URL-safe:
354
+ * - Uses '-' instead of '+'
355
+ * - Uses '_' instead of '/'
356
+ * - Removes padding '='
357
+ *
358
+ * @param buffer - Data to encode
359
+ * @returns Base64URL encoded string
360
+ */
361
+ declare function base64UrlEncode(buffer: Uint8Array): string;
362
+ /**
363
+ * Decode a Base64URL string to UTF-8 string
364
+ *
365
+ * @param str - Base64URL encoded string
366
+ * @returns Decoded UTF-8 string
367
+ */
368
+ declare function base64UrlDecode(str: string): string;
369
+ /**
370
+ * Encode a string to Base64URL
371
+ *
372
+ * @param str - String to encode
373
+ * @returns Base64URL encoded string
374
+ */
375
+ declare function stringToBase64Url(str: string): string;
376
+ /**
377
+ * Decode a Base64URL string to Uint8Array
378
+ *
379
+ * @param str - Base64URL encoded string
380
+ * @returns Decoded bytes
381
+ */
382
+ declare function base64UrlDecodeToBytes(str: string): Uint8Array;
383
+
384
+ /**
385
+ * JWT (JSON Web Token) utilities
386
+ *
387
+ * Implements JWT decoding without validation.
388
+ * Signature validation is NOT performed (client-side doesn't need it).
389
+ * The server should validate signatures.
390
+ */
391
+
392
+ /**
393
+ * Decode a JWT token into header and payload
394
+ *
395
+ * NOTE: This does NOT validate the signature!
396
+ * Signature validation should be done server-side.
397
+ *
398
+ * @param token - JWT string (header.payload.signature)
399
+ * @returns Decoded header and payload
400
+ * @throws {AuthError} If token format is invalid
401
+ */
402
+ declare function decodeJwt<T = TokenPayload>(token: string): {
403
+ header: TokenHeader;
404
+ payload: T;
405
+ };
406
+ /**
407
+ * Decode only the payload from a JWT token
408
+ *
409
+ * @param token - JWT string
410
+ * @returns Decoded payload
411
+ * @throws {AuthError} If token format is invalid
412
+ */
413
+ declare function decodePayload<T = TokenPayload>(token: string): T;
414
+ /**
415
+ * Decode only the header from a JWT token
416
+ *
417
+ * @param token - JWT string
418
+ * @returns Decoded header
419
+ * @throws {AuthError} If token format is invalid
420
+ */
421
+ declare function decodeHeader(token: string): TokenHeader;
422
+ /**
423
+ * Check if a token is valid JWT format (not expired, not signature)
424
+ *
425
+ * @param token - Token string to validate
426
+ * @returns true if token has valid JWT format
427
+ */
428
+ declare function isValidJwtFormat(token: string): boolean;
429
+ /**
430
+ * Get expiration date from JWT token
431
+ *
432
+ * @param token - JWT string
433
+ * @returns Expiration date or null if no exp claim
434
+ */
435
+ declare function getTokenExpiry(token: string): Date | null;
436
+ /**
437
+ * Check if a JWT token is expired
438
+ *
439
+ * @param token - JWT string
440
+ * @param bufferSeconds - Consider expired if within this many seconds (default: 0)
441
+ * @returns true if token is expired
442
+ */
443
+ declare function isTokenExpired(token: string, bufferSeconds?: number): boolean;
444
+ /**
445
+ * Get time until token expiry in milliseconds
446
+ *
447
+ * @param token - JWT string
448
+ * @returns Milliseconds until expiry, or null if no expiry
449
+ */
450
+ declare function getTimeUntilExpiry(token: string): number | null;
451
+ /**
452
+ * Extract a specific claim from JWT token
453
+ *
454
+ * @param token - JWT string
455
+ * @param claim - Claim name
456
+ * @returns Claim value or undefined
457
+ */
458
+ declare function getClaim<K extends keyof TokenPayload>(token: string, claim: K): TokenPayload[K] | undefined;
459
+ /**
460
+ * Extract multiple claims from JWT token
461
+ *
462
+ * @param token - JWT string
463
+ * @param claims - Array of claim names
464
+ * @returns Object with claim values
465
+ */
466
+ declare function getClaims<K extends keyof TokenPayload>(token: string, claims: K[]): Partial<Pick<TokenPayload, K>>;
467
+
468
+ /**
469
+ * Time and expiry utilities
470
+ *
471
+ * Helper functions for working with token expiration times.
472
+ */
473
+ /**
474
+ * Check if a timestamp is expired
475
+ *
476
+ * @param expiresAt - Expiration timestamp in milliseconds
477
+ * @param bufferMs - Consider expired if within this many milliseconds (default: 0)
478
+ * @returns true if expired
479
+ */
480
+ declare function isExpired(expiresAt: number | null | undefined, bufferMs?: number): boolean;
481
+ /**
482
+ * Get time until expiry in milliseconds
483
+ *
484
+ * @param expiresAt - Expiration timestamp in milliseconds
485
+ * @returns Milliseconds until expiry, or null if no expiry. Returns 0 if already expired.
486
+ */
487
+ declare function getExpiresIn(expiresAt: number | null | undefined): number | null;
488
+ /**
489
+ * Convert seconds to milliseconds
490
+ *
491
+ * @param seconds - Time in seconds
492
+ * @returns Time in milliseconds
493
+ */
494
+ declare function secondsToMs(seconds: number): number;
495
+ /**
496
+ * Convert milliseconds to seconds
497
+ *
498
+ * @param ms - Time in milliseconds
499
+ * @returns Time in seconds
500
+ */
501
+ declare function msToSeconds(ms: number): number;
502
+ /**
503
+ * Calculate expiry timestamp from expiresIn seconds
504
+ *
505
+ * @param expiresIn - Seconds until expiry
506
+ * @returns Expiry timestamp in milliseconds
507
+ */
508
+ declare function calculateExpiresAt(expiresIn: number): number;
509
+ /**
510
+ * Format time remaining as human-readable string
511
+ *
512
+ * @param ms - Milliseconds
513
+ * @returns Formatted string like "5m 30s" or "2h 15m"
514
+ */
515
+ declare function formatTimeRemaining(ms: number): string;
516
+
517
+ /**
518
+ * Cryptographic utilities for PKCE (Proof Key for Code Exchange)
519
+ *
520
+ * Implements OAuth2 PKCE flow requirements:
521
+ * - Code verifier generation (43-128 characters)
522
+ * - Code challenge generation (SHA-256)
523
+ */
524
+ /**
525
+ * Generate a cryptographically secure random code verifier for PKCE
526
+ *
527
+ * The code verifier is a high-entropy cryptographic random string
528
+ * with a minimum length of 43 characters and maximum of 128 characters.
529
+ *
530
+ * @param length - Length of the code verifier (default: 64, min: 43, max: 128)
531
+ * @returns Base64URL-encoded random string
532
+ */
533
+ declare function generateCodeVerifier(length?: number): string;
534
+ /**
535
+ * Generate code challenge from code verifier using SHA-256
536
+ *
537
+ * The code challenge is a Base64URL-encoded SHA-256 hash of the code verifier.
538
+ * This is the recommended method for PKCE (S256).
539
+ *
540
+ * @param codeVerifier - The code verifier to hash
541
+ * @returns Base64URL-encoded SHA-256 hash
542
+ */
543
+ declare function generateCodeChallenge(codeVerifier: string): Promise<string>;
544
+ /**
545
+ * Generate a cryptographically secure random string
546
+ *
547
+ * Useful for generating state, nonce, or other random identifiers.
548
+ *
549
+ * @param length - Desired length of the random string
550
+ * @returns Base64URL-encoded random string
551
+ */
552
+ declare function generateRandomString(length: number): string;
553
+ /**
554
+ * Generate a random UUID v4
555
+ *
556
+ * @returns UUID v4 string
557
+ */
558
+ declare function generateUuid(): string;
559
+
560
+ export { AuthEvent, AuthFetch, AuthKeeper, AuthKeeperKernel, EventBus, EventHandler, EventType, FetchInterceptorOptions, KernelOptions, LogoutOptions, Plugin, PluginInfo, PluginRegistry, TokenHeader, TokenPayload, TokenSet, Unsubscribe, base64UrlDecode, base64UrlDecodeToBytes, base64UrlEncode, calculateExpiresAt, createAuthKeeper, decodeHeader, decodeJwt, decodePayload, formatTimeRemaining, generateCodeChallenge, generateCodeVerifier, generateRandomString, generateUuid, getClaim, getClaims, getExpiresIn, getTimeUntilExpiry, getTokenExpiry, isExpired, isTokenExpired, isValidJwtFormat, msToSeconds, secondsToMs, stringToBase64Url };