@oxog/authkeeper 1.3.1 → 1.5.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/CHANGELOG.md +24 -0
- package/README.md +152 -2
- package/dist/auth-source-CXqrhLDO.d.ts +37 -0
- package/dist/auth-source-rjMWiP1Q.d.cts +37 -0
- package/dist/{chunk-NZPSW4M7.cjs → chunk-47JWRVTL.cjs} +21 -29
- package/dist/chunk-47JWRVTL.cjs.map +1 -0
- package/dist/{chunk-XUTTHBMF.js → chunk-ANGR5HRJ.js} +12 -19
- package/dist/chunk-ANGR5HRJ.js.map +1 -0
- package/dist/chunk-DLCD3SBV.js +17 -0
- package/dist/chunk-DLCD3SBV.js.map +1 -0
- package/dist/chunk-LGZGECYE.cjs +96 -0
- package/dist/chunk-LGZGECYE.cjs.map +1 -0
- package/dist/chunk-UUQDRHGF.js +90 -0
- package/dist/chunk-UUQDRHGF.js.map +1 -0
- package/dist/chunk-XGKVBZSF.cjs +19 -0
- package/dist/chunk-XGKVBZSF.cjs.map +1 -0
- package/dist/index-C4pGS-TI.d.cts +488 -0
- package/dist/index-CQwGO-Wk.d.ts +488 -0
- package/dist/index.cjs +71 -60
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +9 -3
- package/dist/index.d.ts +9 -3
- package/dist/index.js +24 -12
- package/dist/index.js.map +1 -1
- package/dist/plugins/index.cjs +15 -14
- package/dist/plugins/index.d.cts +2 -1
- package/dist/plugins/index.d.ts +2 -1
- package/dist/plugins/index.js +2 -1
- package/dist/react/index.cjs +124 -3
- package/dist/react/index.cjs.map +1 -1
- package/dist/react/index.d.cts +136 -5
- package/dist/react/index.d.ts +136 -5
- package/dist/react/index.js +118 -3
- package/dist/react/index.js.map +1 -1
- package/dist/svelte/index.cjs +53 -3
- package/dist/svelte/index.cjs.map +1 -1
- package/dist/svelte/index.d.cts +54 -5
- package/dist/svelte/index.d.ts +54 -5
- package/dist/svelte/index.js +51 -3
- package/dist/svelte/index.js.map +1 -1
- package/dist/types-DMPBl-Ym.d.cts +421 -0
- package/dist/types-DMPBl-Ym.d.ts +421 -0
- package/dist/vue/index.cjs +75 -3
- package/dist/vue/index.cjs.map +1 -1
- package/dist/vue/index.d.cts +93 -5
- package/dist/vue/index.d.ts +93 -5
- package/dist/vue/index.js +70 -3
- package/dist/vue/index.js.map +1 -1
- package/package.json +14 -8
- package/dist/chunk-NZPSW4M7.cjs.map +0 -1
- package/dist/chunk-XUTTHBMF.js.map +0 -1
- package/dist/index-BakvZ2rC.d.cts +0 -906
- package/dist/index-BakvZ2rC.d.ts +0 -906
package/dist/index.d.ts
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
|
-
import { K as KernelOptions,
|
|
2
|
-
export {
|
|
1
|
+
import { K as KernelOptions, b as AuthKeeper, E as EventType, d as EventHandler, U as Unsubscribe, e as AuthEvent, P as Plugin, f as PluginInfo, T as TokenSet, a as TokenPayload, L as LogoutOptions, F as FetchInterceptorOptions, A as AuthFetch, g as TokenHeader, S as StorageAdapter } from './types-DMPBl-Ym.js';
|
|
2
|
+
export { c as AuthError, h as AuthErrorCode, i as AuthErrorOptions, j as ErrorEvent, k as ExpiredEvent, l as LoginEvent, m as LoginOptions, n as LogoutEvent, R as RefreshEvent, o as RefreshTokenFn, p as StorageChangeEvent, q as StorageType, r as StoredTokens, s as TabSyncEvent, t as TokenInfo, u as UserInfo } from './types-DMPBl-Ym.js';
|
|
3
|
+
export { C as CookieAttributes, a as CookieStorageAdapter, b as CookieStorageOptions, F as FetchInterceptorAPI, c as FetchInterceptorPlugin, M as MemoryStorageAdapter, d as MemoryStorageOptions, R as RefreshEngineAPI, e as RefreshEngineOptions, f as RefreshEnginePlugin, T as TokenDecoderAPI, g as TokenDecoderPlugin, h as TokenStoreAPI, i as TokenStoreOptions, j as TokenStorePlugin, W as WebStorageAdapter, k as WebStorageOptions, l as createFetchInterceptorPlugin, m as createMemoryStorage, n as createRefreshEnginePlugin, o as createTokenDecoderPlugin, p as createTokenStorePlugin, q as deleteCookie, r as getCookie, s as parseCookies, t as serializeCookie, u as setCookie } from './index-CQwGO-Wk.js';
|
|
3
4
|
|
|
4
5
|
/**
|
|
5
6
|
* Factory Function
|
|
@@ -52,6 +53,8 @@ declare function createAuthKeeper(options: KernelOptions): Promise<AuthKeeper>;
|
|
|
52
53
|
*/
|
|
53
54
|
declare class EventBus {
|
|
54
55
|
private handlers;
|
|
56
|
+
/** Deliveries scheduled by emit() and not run yet (cancelled by clear()) */
|
|
57
|
+
private pending;
|
|
55
58
|
/**
|
|
56
59
|
* Subscribe to an event
|
|
57
60
|
*
|
|
@@ -71,12 +74,15 @@ declare class EventBus {
|
|
|
71
74
|
* Emit an event to all subscribers
|
|
72
75
|
*
|
|
73
76
|
* Handlers are executed asynchronously in the next tick to prevent blocking.
|
|
77
|
+
* The event goes to the handlers subscribed when it is emitted (a handler
|
|
78
|
+
* added later does not receive it) that are still subscribed at delivery.
|
|
74
79
|
*
|
|
75
80
|
* @param event - Event to emit
|
|
76
81
|
*/
|
|
77
82
|
emit(event: AuthEvent): void;
|
|
78
83
|
/**
|
|
79
|
-
* Remove all event handlers
|
|
84
|
+
* Remove all event handlers and cancel deliveries that have not run yet
|
|
85
|
+
* (no handler runs after the kernel is destroyed)
|
|
80
86
|
*/
|
|
81
87
|
clear(): void;
|
|
82
88
|
/**
|
package/dist/index.js
CHANGED
|
@@ -1,10 +1,14 @@
|
|
|
1
|
-
import {
|
|
2
|
-
export {
|
|
1
|
+
import { createTokenStorePlugin, resolveStorage, createTokenDecoderPlugin, createRefreshEnginePlugin, createFetchInterceptorPlugin, base64UrlEncode } from './chunk-ANGR5HRJ.js';
|
|
2
|
+
export { CookieStorageAdapter, FetchInterceptorPlugin, MemoryStorageAdapter, RefreshEnginePlugin, TokenDecoderPlugin, TokenStorePlugin, WebStorageAdapter, base64UrlDecode, base64UrlDecodeToBytes, base64UrlEncode, createFetchInterceptorPlugin, createMemoryStorage, createRefreshEnginePlugin, createTokenDecoderPlugin, createTokenStorePlugin, decodeHeader, decodeJwt, decodePayload, deleteCookie, getClaim, getClaims, getCookie, getTimeUntilExpiry, getTokenExpiry, isStorageAvailable, isTokenExpired, isValidJwtFormat, parseCookies, safeGetItem, safeRemoveItem, safeSetItem, serializeCookie, setCookie, stringToBase64Url } from './chunk-ANGR5HRJ.js';
|
|
3
|
+
import { AuthError } from './chunk-DLCD3SBV.js';
|
|
4
|
+
export { AuthError } from './chunk-DLCD3SBV.js';
|
|
3
5
|
|
|
4
6
|
// src/kernel/event-bus.ts
|
|
5
7
|
var EventBus = class {
|
|
6
8
|
constructor() {
|
|
7
9
|
this.handlers = /* @__PURE__ */ new Map();
|
|
10
|
+
/** Deliveries scheduled by emit() and not run yet (cancelled by clear()) */
|
|
11
|
+
this.pending = /* @__PURE__ */ new Set();
|
|
8
12
|
}
|
|
9
13
|
/**
|
|
10
14
|
* Subscribe to an event
|
|
@@ -41,6 +45,8 @@ var EventBus = class {
|
|
|
41
45
|
* Emit an event to all subscribers
|
|
42
46
|
*
|
|
43
47
|
* Handlers are executed asynchronously in the next tick to prevent blocking.
|
|
48
|
+
* The event goes to the handlers subscribed when it is emitted (a handler
|
|
49
|
+
* added later does not receive it) that are still subscribed at delivery.
|
|
44
50
|
*
|
|
45
51
|
* @param event - Event to emit
|
|
46
52
|
*/
|
|
@@ -49,8 +55,11 @@ var EventBus = class {
|
|
|
49
55
|
if (!handlerSet || handlerSet.size === 0) {
|
|
50
56
|
return;
|
|
51
57
|
}
|
|
52
|
-
|
|
53
|
-
|
|
58
|
+
const recipients = Array.from(handlerSet);
|
|
59
|
+
const timer = setTimeout(() => {
|
|
60
|
+
this.pending.delete(timer);
|
|
61
|
+
recipients.forEach((handler) => {
|
|
62
|
+
if (this.handlers.get(event.type)?.has(handler) !== true) return;
|
|
54
63
|
try {
|
|
55
64
|
handler(event);
|
|
56
65
|
} catch (error) {
|
|
@@ -58,11 +67,15 @@ var EventBus = class {
|
|
|
58
67
|
}
|
|
59
68
|
});
|
|
60
69
|
}, 0);
|
|
70
|
+
this.pending.add(timer);
|
|
61
71
|
}
|
|
62
72
|
/**
|
|
63
|
-
* Remove all event handlers
|
|
73
|
+
* Remove all event handlers and cancel deliveries that have not run yet
|
|
74
|
+
* (no handler runs after the kernel is destroyed)
|
|
64
75
|
*/
|
|
65
76
|
clear() {
|
|
77
|
+
this.pending.forEach((timer) => clearTimeout(timer));
|
|
78
|
+
this.pending.clear();
|
|
66
79
|
this.handlers.clear();
|
|
67
80
|
}
|
|
68
81
|
/**
|
|
@@ -97,13 +110,9 @@ var PluginRegistry = class {
|
|
|
97
110
|
*/
|
|
98
111
|
register(plugin) {
|
|
99
112
|
if (this.plugins.has(plugin.name)) {
|
|
100
|
-
throw new AuthError(
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
{
|
|
104
|
-
context: { pluginName: plugin.name }
|
|
105
|
-
}
|
|
106
|
-
);
|
|
113
|
+
throw new AuthError("CONFIG_ERROR", `Plugin "${plugin.name}" is already registered`, {
|
|
114
|
+
context: { pluginName: plugin.name }
|
|
115
|
+
});
|
|
107
116
|
}
|
|
108
117
|
const instance = {
|
|
109
118
|
plugin,
|
|
@@ -619,6 +628,9 @@ async function createAuthKeeper(options) {
|
|
|
619
628
|
await kernel.init();
|
|
620
629
|
if (kernel.getAccessToken() && !kernel.isExpired()) {
|
|
621
630
|
kernel.scheduleRefresh();
|
|
631
|
+
} else if (kernel.getAccessToken() && kernel.getRefreshToken() && kernel.getOptions().autoRefresh !== false) {
|
|
632
|
+
kernel.refresh().catch(() => {
|
|
633
|
+
});
|
|
622
634
|
}
|
|
623
635
|
return kernel;
|
|
624
636
|
}
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/kernel/event-bus.ts","../src/kernel/plugin-registry.ts","../src/kernel/kernel.ts","../src/factory.ts","../src/utils/time.ts","../src/utils/crypto.ts"],"names":["fetch"],"mappings":";;;;AAeO,IAAM,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AE,QAAA,CAAS,EAAE,EAAE,QAAA,CAAS,CAAA,EAAG,GAAG,CAAC,CAAA,CAC1C,KAAK,EAAE,CAAA;AAEV,EAAA,OAAO,CAAA,EAAG,GAAA,CAAI,SAAA,CAAU,CAAA,EAAG,CAAC,CAAC,CAAA,CAAA,EAAI,GAAA,CAAI,SAAA,CAAU,CAAA,EAAG,EAAE,CAAC,CAAA,CAAA,EAAI,GAAA,CAAI,SAAA,CAAU,EAAA,EAAI,EAAE,CAAC,CAAA,CAAA,EAAI,GAAA,CAAI,SAAA,CAAU,EAAA,EAAI,EAAE,CAAC,CAAA,CAAA,EAAI,GAAA,CAAI,SAAA,CAAU,EAAE,CAAC,CAAA,CAAA;AAC9H","file":"index.js","sourcesContent":["/**\n * Event Bus\n *\n * Pub/sub event system for kernel and plugins.\n * Type-safe event handling with automatic unsubscribe.\n */\n\nimport type { AuthEvent, EventType, EventHandler, Unsubscribe } from '../types'\n\n/** Handler type as stored internally (handlers are keyed by event type) */\ntype AnyEventHandler = (event: AuthEvent) => void\n\n/**\n * EventBus class for managing event subscriptions and emissions\n */\nexport class EventBus {\n private handlers: Map<EventType, Set<AnyEventHandler>> = new Map()\n\n /**\n * Subscribe to an event\n *\n * @param eventType - Type of event to listen for\n * @param handler - Handler function to call when event is emitted\n * @returns Unsubscribe function\n */\n on<E extends EventType>(eventType: E, handler: EventHandler<E>): Unsubscribe {\n // Get or create handler set for this event type\n let handlerSet = this.handlers.get(eventType)\n if (!handlerSet) {\n handlerSet = new Set()\n this.handlers.set(eventType, handlerSet)\n }\n\n handlerSet.add(handler as AnyEventHandler)\n\n // Return unsubscribe function\n return () => this.off(eventType, handler)\n }\n\n /**\n * Unsubscribe from an event\n *\n * @param eventType - Type of event to stop listening for\n * @param handler - Handler function to remove\n */\n off<E extends EventType>(eventType: E, handler: EventHandler<E>): void {\n const handlerSet = this.handlers.get(eventType)\n if (handlerSet) {\n handlerSet.delete(handler as AnyEventHandler)\n\n // Clean up empty sets\n if (handlerSet.size === 0) {\n this.handlers.delete(eventType)\n }\n }\n }\n\n /**\n * Emit an event to all subscribers\n *\n * Handlers are executed asynchronously in the next tick to prevent blocking.\n *\n * @param event - Event to emit\n */\n emit(event: AuthEvent): void {\n const handlerSet = this.handlers.get(event.type)\n if (!handlerSet || handlerSet.size === 0) {\n return\n }\n\n // Execute handlers in next tick to prevent blocking\n setTimeout(() => {\n handlerSet.forEach((handler) => {\n try {\n handler(event)\n } catch (error) {\n // Log error but don't throw to prevent one handler from breaking others\n console.error(`[AuthKeeper] Error in event handler for ${event.type}:`, error)\n }\n })\n }, 0)\n }\n\n /**\n * Remove all event handlers\n */\n clear(): void {\n this.handlers.clear()\n }\n\n /**\n * Get count of handlers for an event type\n *\n * @param eventType - Event type to count handlers for\n * @returns Number of handlers\n */\n getHandlerCount(eventType: EventType): number {\n return this.handlers.get(eventType)?.size || 0\n }\n\n /**\n * Get all event types that have handlers\n *\n * @returns Array of event types\n */\n getActiveEventTypes(): EventType[] {\n return Array.from(this.handlers.keys())\n }\n}\n","/**\n * Plugin Registry\n *\n * Manages plugin registration, installation, and lifecycle.\n */\n\nimport { AuthError, type Plugin, type PluginInfo, type AuthKeeper } from '../types'\n\n/**\n * Plugin instance with metadata\n */\ninterface PluginInstance {\n plugin: Plugin\n installed: boolean\n api: unknown\n}\n\n/**\n * PluginRegistry class for managing plugins\n */\nexport class PluginRegistry {\n private plugins: Map<string, PluginInstance> = new Map()\n\n /**\n * Register a plugin\n *\n * @param plugin - Plugin to register\n * @throws {AuthError} If plugin with same name already registered\n */\n register(plugin: Plugin): void {\n if (this.plugins.has(plugin.name)) {\n throw new AuthError(\n 'CONFIG_ERROR',\n `Plugin \"${plugin.name}\" is already registered`,\n {\n context: { pluginName: plugin.name },\n }\n )\n }\n\n const instance: PluginInstance = {\n plugin,\n installed: false,\n api: null,\n }\n\n this.plugins.set(plugin.name, instance)\n }\n\n /**\n * Install a plugin\n *\n * Calls the plugin's install method and stores the returned API.\n *\n * @param name - Plugin name\n * @param kernel - Kernel instance to pass to plugin\n * @throws {AuthError} If plugin not found or already installed\n */\n async install(name: string, kernel: AuthKeeper): Promise<void> {\n const instance = this.plugins.get(name)\n\n if (!instance) {\n throw new AuthError('CONFIG_ERROR', `Plugin \"${name}\" not found`, {\n context: { pluginName: name },\n })\n }\n\n if (instance.installed) {\n // Already installed, skip\n return\n }\n\n try {\n // Call plugin's install method\n const api: unknown = await instance.plugin.install(kernel)\n instance.api = api || null\n instance.installed = true\n } catch (error) {\n throw new AuthError('CONFIG_ERROR', `Failed to install plugin \"${name}\"`, {\n cause: error as Error,\n context: { pluginName: name },\n })\n }\n }\n\n /**\n * Uninstall a plugin\n *\n * Calls the plugin's uninstall method if it exists.\n *\n * @param name - Plugin name\n */\n async uninstall(name: string): Promise<void> {\n const instance = this.plugins.get(name)\n\n if (!instance) {\n // Plugin not found, nothing to uninstall\n return\n }\n\n if (instance.installed && instance.plugin.uninstall) {\n try {\n await instance.plugin.uninstall()\n } catch (error) {\n console.error(`[AuthKeeper] Error uninstalling plugin \"${name}\":`, error)\n }\n }\n\n this.plugins.delete(name)\n }\n\n /**\n * Get a plugin by name\n *\n * @param name - Plugin name\n * @returns Plugin or undefined if not found\n */\n get<P extends Plugin>(name: string): P | undefined {\n const instance = this.plugins.get(name)\n return instance?.plugin as P | undefined\n }\n\n /**\n * Get plugin API by name\n *\n * @param name - Plugin name\n * @returns Plugin API or undefined if not found\n */\n getApi<T = unknown>(name: string): T | undefined {\n const instance = this.plugins.get(name)\n return instance?.api as T | undefined\n }\n\n /**\n * Check if a plugin is registered\n *\n * @param name - Plugin name\n * @returns true if plugin is registered\n */\n has(name: string): boolean {\n return this.plugins.has(name)\n }\n\n /**\n * Check if a plugin is installed\n *\n * @param name - Plugin name\n * @returns true if plugin is installed\n */\n isInstalled(name: string): boolean {\n const instance = this.plugins.get(name)\n return instance?.installed || false\n }\n\n /**\n * List all plugins\n *\n * @returns Array of plugin information\n */\n list(): PluginInfo[] {\n return Array.from(this.plugins.entries()).map(([name, instance]) => ({\n name,\n version: instance.plugin.version,\n type: instance.plugin.type,\n enabled: instance.installed,\n }))\n }\n\n /**\n * Get all plugin names\n *\n * @returns Array of plugin names\n */\n getNames(): string[] {\n return Array.from(this.plugins.keys())\n }\n\n /**\n * Clear all plugins\n */\n clear(): void {\n this.plugins.clear()\n }\n}\n","/**\n * AuthKeeper Kernel\n *\n * The micro-kernel that orchestrates plugins and manages auth state.\n * Most functionality is delegated to core plugins.\n */\n\nimport { EventBus } from './event-bus'\nimport { PluginRegistry } from './plugin-registry'\nimport {\n AuthError,\n type AuthKeeper,\n type KernelOptions,\n type Plugin,\n type PluginInfo,\n type TokenSet,\n type TokenPayload,\n type LogoutOptions,\n type AuthFetch,\n type FetchInterceptorOptions,\n type EventType,\n type EventHandler,\n type Unsubscribe,\n type AuthEvent,\n} from '../types'\nimport type {\n TokenStoreAPI,\n TokenDecoderAPI,\n RefreshEngineAPI,\n FetchInterceptorAPI,\n} from '../plugins/core'\n\n/**\n * AuthKeeperKernel - Main kernel implementation\n */\nexport class AuthKeeperKernel implements AuthKeeper {\n private pluginRegistry: PluginRegistry\n private eventBus: EventBus\n private options: KernelOptions\n private initialized: boolean = false\n\n constructor(options: KernelOptions) {\n this.options = {\n autoRefresh: true,\n refreshThreshold: 60,\n ...options,\n }\n\n this.pluginRegistry = new PluginRegistry()\n this.eventBus = new EventBus()\n }\n\n // ============================================================================\n // Lifecycle\n // ============================================================================\n\n /**\n * Initialize the kernel\n *\n * 1. Install core plugins\n * 2. Install user-provided plugins\n * 3. Load tokens from storage\n * 4. Schedule refresh if authenticated\n */\n async init(): Promise<void> {\n if (this.initialized) {\n return\n }\n\n // Core plugins will be installed in Phase 4\n // For now, we just mark as initialized\n\n // Install user-provided plugins\n if (this.options.plugins) {\n for (const plugin of this.options.plugins) {\n await this.register(plugin)\n }\n }\n\n this.initialized = true\n }\n\n /**\n * Destroy the kernel and cleanup\n */\n destroy(): void {\n // Cancel any scheduled refreshes\n this.cancelScheduledRefresh()\n\n // Clear event handlers\n this.eventBus.clear()\n\n // Uninstall all plugins\n const pluginNames = this.pluginRegistry.getNames()\n for (const name of pluginNames) {\n // Not awaited: uninstall() catches plugin errors and destroy() stays synchronous\n void this.pluginRegistry.uninstall(name)\n }\n\n this.pluginRegistry.clear()\n this.initialized = false\n }\n\n // ============================================================================\n // Token Management\n // ============================================================================\n\n /**\n * Set authentication tokens\n *\n * Delegates to token-store plugin.\n */\n setTokens(tokens: TokenSet): void {\n const tokenStore = this.pluginRegistry.getApi<TokenStoreAPI>('token-store')\n if (!tokenStore) {\n throw new AuthError('CONFIG_ERROR', 'token-store plugin not installed')\n }\n\n tokenStore.set(tokens)\n\n // Emit login event - but not when the refresh engine is storing the\n // result of a token refresh (that is reported as a 'refresh' event)\n const refreshEngine = this.pluginRegistry.getApi<RefreshEngineAPI>('refresh-engine')\n if (refreshEngine?.isApplyingRefresh?.() !== true) {\n this.emit({\n type: 'login',\n tokens,\n timestamp: Date.now(),\n })\n }\n\n // Schedule auto-refresh if enabled\n if (this.options.autoRefresh && !this.isExpired()) {\n this.scheduleRefresh()\n }\n }\n\n /**\n * Get access token\n *\n * Delegates to token-store plugin.\n */\n getAccessToken(): string | null {\n const tokenStore = this.pluginRegistry.getApi<TokenStoreAPI>('token-store')\n if (!tokenStore) {\n return null\n }\n\n return tokenStore.getAccessToken()\n }\n\n /**\n * Get refresh token\n *\n * Delegates to token-store plugin.\n */\n getRefreshToken(): string | null {\n const tokenStore = this.pluginRegistry.getApi<TokenStoreAPI>('token-store')\n if (!tokenStore) {\n return null\n }\n\n return tokenStore.getRefreshToken()\n }\n\n /**\n * Clear all tokens\n */\n clearTokens(): void {\n // Nothing left to refresh: a pending scheduled refresh would only fail\n // with REFRESH_TOKEN_MISSING\n this.cancelScheduledRefresh()\n\n const tokenStore = this.pluginRegistry.getApi<TokenStoreAPI>('token-store')\n if (tokenStore) {\n tokenStore.clear()\n }\n }\n\n // ============================================================================\n // Auth State\n // ============================================================================\n\n /**\n * Check if user is authenticated\n */\n isAuthenticated(): boolean {\n const accessToken = this.getAccessToken()\n return accessToken !== null && !this.isExpired()\n }\n\n /**\n * Check if token is expired\n *\n * Delegates to token-store plugin.\n */\n isExpired(): boolean {\n const tokenStore = this.pluginRegistry.getApi<TokenStoreAPI>('token-store')\n if (!tokenStore) {\n return true\n }\n\n return tokenStore.isExpired()\n }\n\n /**\n * Get token expiration date\n *\n * Delegates to token-store plugin.\n */\n getExpiresAt(): Date | null {\n const tokenStore = this.pluginRegistry.getApi<TokenStoreAPI>('token-store')\n if (!tokenStore) {\n return null\n }\n\n return tokenStore.getExpiresAt()\n }\n\n /**\n * Get time until expiry in milliseconds\n *\n * Delegates to token-store plugin.\n */\n getTimeUntilExpiry(): number | null {\n const tokenStore = this.pluginRegistry.getApi<TokenStoreAPI>('token-store')\n if (!tokenStore) {\n return null\n }\n\n return tokenStore.getExpiresIn()\n }\n\n // ============================================================================\n // Token Decoding\n // ============================================================================\n\n /**\n * Decode token payload\n *\n * Delegates to token-decoder plugin.\n */\n decode<T = TokenPayload>(): T | null {\n const tokenDecoder = this.pluginRegistry.getApi<TokenDecoderAPI>('token-decoder')\n if (!tokenDecoder) {\n return null\n }\n\n return tokenDecoder.decode<T>()\n }\n\n /**\n * Get specific claim from token\n *\n * Delegates to token-decoder plugin.\n */\n getClaim<K extends keyof TokenPayload>(key: K): TokenPayload[K] | undefined {\n const tokenDecoder = this.pluginRegistry.getApi<TokenDecoderAPI>('token-decoder')\n if (!tokenDecoder) {\n return undefined\n }\n\n return tokenDecoder.getClaim(key)\n }\n\n /**\n * Get multiple claims from token\n *\n * Delegates to token-decoder plugin.\n */\n getClaims<K extends keyof TokenPayload>(keys: K[]): Pick<TokenPayload, K> {\n const tokenDecoder = this.pluginRegistry.getApi<TokenDecoderAPI>('token-decoder')\n if (!tokenDecoder) {\n return {} as Pick<TokenPayload, K>\n }\n\n return tokenDecoder.getClaims(keys)\n }\n\n // ============================================================================\n // Refresh\n // ============================================================================\n\n /**\n * Manually refresh tokens\n *\n * Delegates to refresh-engine plugin.\n */\n async refresh(): Promise<TokenSet> {\n const refreshEngine = this.pluginRegistry.getApi<RefreshEngineAPI>('refresh-engine')\n if (!refreshEngine) {\n throw new AuthError('CONFIG_ERROR', 'refresh-engine plugin not installed')\n }\n\n return refreshEngine.refresh()\n }\n\n /**\n * Schedule automatic refresh\n *\n * Delegates to refresh-engine plugin.\n */\n scheduleRefresh(): void {\n if (!this.options.autoRefresh) {\n return\n }\n\n const refreshEngine = this.pluginRegistry.getApi<RefreshEngineAPI>('refresh-engine')\n if (refreshEngine) {\n refreshEngine.scheduleRefresh()\n }\n }\n\n /**\n * Cancel scheduled refresh\n *\n * Delegates to refresh-engine plugin.\n */\n cancelScheduledRefresh(): void {\n const refreshEngine = this.pluginRegistry.getApi<RefreshEngineAPI>('refresh-engine')\n if (refreshEngine) {\n refreshEngine.cancelScheduledRefresh()\n }\n }\n\n // ============================================================================\n // Logout\n // ============================================================================\n\n /**\n * Logout user\n *\n * Clears tokens and emits logout event.\n */\n logout(options: LogoutOptions = {}): void {\n // Cancel scheduled refresh\n this.cancelScheduledRefresh()\n\n // Clear tokens\n this.clearTokens()\n\n // Emit logout event\n this.emit({\n type: 'logout',\n reason: 'manual',\n timestamp: Date.now(),\n })\n\n // Handle redirect if specified\n if (options.redirect && typeof window !== 'undefined') {\n window.location.href = options.redirect\n }\n }\n\n // ============================================================================\n // Interceptors\n // ============================================================================\n\n /**\n * Create authenticated fetch function\n *\n * Delegates to fetch-interceptor plugin.\n */\n createFetch(options?: FetchInterceptorOptions): AuthFetch {\n const fetchInterceptor = this.pluginRegistry.getApi<FetchInterceptorAPI>('fetch-interceptor')\n if (!fetchInterceptor) {\n // Return regular fetch if plugin not installed\n return fetch.bind(globalThis)\n }\n\n return fetchInterceptor.createFetch(options)\n }\n\n /**\n * Wrap global fetch with auth\n *\n * Delegates to fetch-interceptor plugin.\n */\n wrapFetch(fetch: typeof globalThis.fetch): void {\n const fetchInterceptor = this.pluginRegistry.getApi<FetchInterceptorAPI>('fetch-interceptor')\n if (fetchInterceptor) {\n fetchInterceptor.wrapFetch(fetch)\n }\n }\n\n // ============================================================================\n // Plugin Management\n // ============================================================================\n\n /**\n * Register and install a plugin\n *\n * The returned promise rejects when the plugin cannot be registered or\n * installed. The failure is also emitted as an 'error' event (context\n * 'plugin') and passed to `onError`, so a caller that does not await the\n * promise does not get an unhandled rejection.\n */\n register(plugin: Plugin): Promise<void> {\n const result = this.registerPlugin(plugin)\n result.catch((error: AuthError) => {\n // PluginRegistry only throws AuthError (CONFIG_ERROR)\n this.emit({ type: 'error', error, context: 'plugin', timestamp: Date.now() })\n })\n return result\n }\n\n private async registerPlugin(plugin: Plugin): Promise<void> {\n this.pluginRegistry.register(plugin)\n try {\n await this.pluginRegistry.install(plugin.name, this)\n } catch (error) {\n // Drop the half-registered plugin so it can be registered again\n await this.pluginRegistry.uninstall(plugin.name)\n throw error\n }\n }\n\n /**\n * Unregister a plugin\n */\n async unregister(pluginName: string): Promise<void> {\n await this.pluginRegistry.uninstall(pluginName)\n }\n\n /**\n * Get plugin by name\n */\n getPlugin<P extends Plugin>(name: string): P | undefined {\n return this.pluginRegistry.get<P>(name)\n }\n\n /**\n * List all plugins\n */\n listPlugins(): PluginInfo[] {\n return this.pluginRegistry.list()\n }\n\n // ============================================================================\n // Event System\n // ============================================================================\n\n /**\n * Emit an event\n */\n emit(event: AuthEvent): void {\n this.eventBus.emit(event)\n\n // Call global error handler if it's an error event\n if (event.type === 'error' && this.options.onError) {\n this.options.onError(event.error)\n }\n }\n\n /**\n * Subscribe to events\n */\n on<E extends EventType>(eventType: E, handler: EventHandler<E>): Unsubscribe {\n return this.eventBus.on(eventType, handler)\n }\n\n /**\n * Unsubscribe from events\n */\n off<E extends EventType>(eventType: E, handler: EventHandler<E>): void {\n this.eventBus.off(eventType, handler)\n }\n\n // ============================================================================\n // Configuration\n // ============================================================================\n\n /**\n * Update configuration\n */\n configure(options: Partial<KernelOptions>): void {\n this.options = {\n ...this.options,\n ...options,\n }\n\n // Update refresh engine threshold if changed\n if (options.refreshThreshold !== undefined) {\n const refreshEngine = this.pluginRegistry.getApi<RefreshEngineAPI>('refresh-engine')\n if (refreshEngine && refreshEngine.setThreshold) {\n refreshEngine.setThreshold(options.refreshThreshold)\n }\n }\n }\n\n /**\n * Get current configuration\n */\n getOptions(): KernelOptions {\n // Multi-tab sync is not implemented: report the effective value\n return { ...this.options, syncTabs: false }\n }\n}\n","/**\n * Factory Function\n *\n * Creates and initializes an AuthKeeper instance with core plugins.\n */\n\nimport { AuthKeeperKernel } from './kernel'\nimport {\n resolveStorage,\n createTokenStorePlugin,\n createTokenDecoderPlugin,\n createRefreshEnginePlugin,\n createFetchInterceptorPlugin,\n} from './plugins/core'\nimport type { AuthKeeper, KernelOptions } from './types'\n\n/**\n * Create an AuthKeeper instance\n *\n * Automatically installs core plugins:\n * - token-store: Token state management\n * - token-decoder: JWT decoding\n * - refresh-engine: Auto-refresh with queue\n * - storage-memory: Default secure storage\n * - fetch-interceptor: Auth header injection and 401 retry\n *\n * @param options - Configuration options\n * @returns AuthKeeper instance\n *\n * @example\n * ```typescript\n * const auth = createAuthKeeper({\n * storage: 'memory',\n * refreshToken: async (token) => {\n * const res = await fetch('/api/auth/refresh', {\n * method: 'POST',\n * body: JSON.stringify({ refreshToken: token }),\n * })\n * return res.json()\n * },\n * autoRefresh: true,\n * refreshThreshold: 60,\n * })\n *\n * await auth.init()\n * ```\n */\nexport async function createAuthKeeper(options: KernelOptions): Promise<AuthKeeper> {\n // Create kernel\n const kernel = new AuthKeeperKernel(options)\n\n // Register and install core plugins\n // 1. token-store (restores persisted tokens from the configured storage)\n await kernel.register(createTokenStorePlugin({ storage: resolveStorage(options.storage) }))\n\n // 2. token-decoder\n await kernel.register(createTokenDecoderPlugin())\n\n // 3. refresh-engine\n await kernel.register(\n createRefreshEnginePlugin({\n refreshFn: options.refreshToken,\n threshold: options.refreshThreshold,\n })\n )\n\n // 5. fetch-interceptor\n await kernel.register(createFetchInterceptorPlugin())\n\n // Initialize kernel\n await kernel.init()\n\n // Resume auto-refresh for tokens restored from storage\n if (kernel.getAccessToken() && !kernel.isExpired()) {\n kernel.scheduleRefresh()\n }\n\n return kernel\n}\n","/**\n * Time and expiry utilities\n *\n * Helper functions for working with token expiration times.\n */\n\n/**\n * Check if a timestamp is expired\n *\n * @param expiresAt - Expiration timestamp in milliseconds\n * @param bufferMs - Consider expired if within this many milliseconds (default: 0)\n * @returns true if expired\n */\nexport function isExpired(expiresAt: number | null | undefined, bufferMs: number = 0): boolean {\n if (!expiresAt) {\n return false\n }\n\n const now = Date.now()\n return now >= expiresAt - bufferMs\n}\n\n/**\n * Get time until expiry in milliseconds\n *\n * @param expiresAt - Expiration timestamp in milliseconds\n * @returns Milliseconds until expiry, or null if no expiry. Returns 0 if already expired.\n */\nexport function getExpiresIn(expiresAt: number | null | undefined): number | null {\n if (!expiresAt) {\n return null\n }\n\n const now = Date.now()\n const timeUntil = expiresAt - now\n return Math.max(0, timeUntil)\n}\n\n/**\n * Convert seconds to milliseconds\n *\n * @param seconds - Time in seconds\n * @returns Time in milliseconds\n */\nexport function secondsToMs(seconds: number): number {\n return seconds * 1000\n}\n\n/**\n * Convert milliseconds to seconds\n *\n * @param ms - Time in milliseconds\n * @returns Time in seconds\n */\nexport function msToSeconds(ms: number): number {\n return Math.floor(ms / 1000)\n}\n\n/**\n * Calculate expiry timestamp from expiresIn seconds\n *\n * @param expiresIn - Seconds until expiry\n * @returns Expiry timestamp in milliseconds\n */\nexport function calculateExpiresAt(expiresIn: number): number {\n return Date.now() + secondsToMs(expiresIn)\n}\n\n/**\n * Format time remaining as human-readable string\n *\n * @param ms - Milliseconds\n * @returns Formatted string like \"5m 30s\" or \"2h 15m\"\n */\nexport function formatTimeRemaining(ms: number): string {\n if (ms <= 0) {\n return 'expired'\n }\n\n const seconds = Math.floor(ms / 1000)\n const minutes = Math.floor(seconds / 60)\n const hours = Math.floor(minutes / 60)\n const days = Math.floor(hours / 24)\n\n if (days > 0) {\n const remainingHours = hours % 24\n return remainingHours > 0 ? `${days}d ${remainingHours}h` : `${days}d`\n }\n\n if (hours > 0) {\n const remainingMinutes = minutes % 60\n return remainingMinutes > 0 ? `${hours}h ${remainingMinutes}m` : `${hours}h`\n }\n\n if (minutes > 0) {\n const remainingSeconds = seconds % 60\n return remainingSeconds > 0 ? `${minutes}m ${remainingSeconds}s` : `${minutes}m`\n }\n\n return `${seconds}s`\n}\n","/**\n * Cryptographic utilities for PKCE (Proof Key for Code Exchange)\n *\n * Implements OAuth2 PKCE flow requirements:\n * - Code verifier generation (43-128 characters)\n * - Code challenge generation (SHA-256)\n */\n\nimport { base64UrlEncode } from './base64'\n\n/**\n * Generate a cryptographically secure random code verifier for PKCE\n *\n * The code verifier is a high-entropy cryptographic random string\n * with a minimum length of 43 characters and maximum of 128 characters.\n *\n * @param length - Length of the code verifier (default: 64, min: 43, max: 128)\n * @returns Base64URL-encoded random string\n */\nexport function generateCodeVerifier(length: number = 64): string {\n // Validate length\n if (length < 43 || length > 128) {\n throw new Error('Code verifier length must be between 43 and 128 characters')\n }\n\n // Generate random bytes\n // We need enough bytes to produce the desired length after base64url encoding\n // Base64 encoding increases size by ~33%, so we generate 3/4 of desired length\n const byteLength = Math.ceil((length * 3) / 4)\n const randomBytes = new Uint8Array(byteLength)\n crypto.getRandomValues(randomBytes)\n\n // Encode and trim to exact length\n const verifier = base64UrlEncode(randomBytes).substring(0, length)\n return verifier\n}\n\n/**\n * Generate code challenge from code verifier using SHA-256\n *\n * The code challenge is a Base64URL-encoded SHA-256 hash of the code verifier.\n * This is the recommended method for PKCE (S256).\n *\n * @param codeVerifier - The code verifier to hash\n * @returns Base64URL-encoded SHA-256 hash\n */\nexport async function generateCodeChallenge(codeVerifier: string): Promise<string> {\n // Convert verifier string to bytes\n const encoder = new TextEncoder()\n const data = encoder.encode(codeVerifier)\n\n // Hash with SHA-256\n const hashBuffer = await crypto.subtle.digest('SHA-256', data)\n\n // Convert to Base64URL\n const hashArray = new Uint8Array(hashBuffer)\n return base64UrlEncode(hashArray)\n}\n\n/**\n * Generate a cryptographically secure random string\n *\n * Useful for generating state, nonce, or other random identifiers.\n *\n * @param length - Desired length of the random string\n * @returns Base64URL-encoded random string\n */\nexport function generateRandomString(length: number): string {\n const byteLength = Math.ceil((length * 3) / 4)\n const randomBytes = new Uint8Array(byteLength)\n crypto.getRandomValues(randomBytes)\n return base64UrlEncode(randomBytes).substring(0, length)\n}\n\n/**\n * Generate a random UUID v4\n *\n * @returns UUID v4 string\n */\nexport function generateUuid(): string {\n // Use crypto.randomUUID if available\n if (typeof crypto.randomUUID === 'function') {\n return crypto.randomUUID()\n }\n\n // Fallback: generate UUID v4 manually\n const bytes = new Uint8Array(16)\n crypto.getRandomValues(bytes)\n\n // Set version (4) and variant bits\n bytes[6] = ((bytes[6] as number) & 0x0f) | 0x40 // Version 4\n bytes[8] = ((bytes[8] as number) & 0x3f) | 0x80 // Variant 10\n\n // Convert to hex string with dashes\n const hex = Array.from(bytes)\n .map((b) => b.toString(16).padStart(2, '0'))\n .join('')\n\n return `${hex.substring(0, 8)}-${hex.substring(8, 12)}-${hex.substring(12, 16)}-${hex.substring(16, 20)}-${hex.substring(20)}`\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["../src/kernel/event-bus.ts","../src/kernel/plugin-registry.ts","../src/kernel/kernel.ts","../src/factory.ts","../src/utils/time.ts","../src/utils/crypto.ts"],"names":["fetch"],"mappings":";;;;;;AAeO,IAAM,WAAN,MAAe;AAAA,EAAf,WAAA,GAAA;AACL,IAAA,IAAA,CAAQ,QAAA,uBAAqD,GAAA,EAAI;AAEjE;AAAA,IAAA,IAAA,CAAQ,OAAA,uBAAkD,GAAA,EAAI;AAAA,EAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAS9D,EAAA,CAAwB,WAAc,OAAA,EAAuC;AAE3E,IAAA,IAAI,UAAA,GAAa,IAAA,CAA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A,CAAO,UAAA,KAAe,UAAA,EAAY;AAC3C,IAAA,OAAO,OAAO,UAAA,EAAW;AAAA,EAC3B;AAGA,EAAA,MAAM,KAAA,GAAQ,IAAI,UAAA,CAAW,EAAE,CAAA;AAC/B,EAAA,MAAA,CAAO,gBAAgB,KAAK,CAAA;AAG5B,EAAA,KAAA,CAAM,CAAC,CAAA,GAAM,KAAA,CAAM,CAAC,IAAe,EAAA,GAAQ,EAAA;AAC3C,EAAA,KAAA,CAAM,CAAC,CAAA,GAAM,KAAA,CAAM,CAAC,IAAe,EAAA,GAAQ,GAAA;AAG3C,EAAA,MAAM,MAAM,KAAA,CAAM,IAAA,CAAK,KAAK,CAAA,CACzB,GAAA,CAAI,CAAC,CAAA,KAAM,CAAA,CAAE,QAAA,CAAS,EAAE,EAAE,QAAA,CAAS,CAAA,EAAG,GAAG,CAAC,CAAA,CAC1C,KAAK,EAAE,CAAA;AAEV,EAAA,OAAO,CAAA,EAAG,GAAA,CAAI,SAAA,CAAU,CAAA,EAAG,CAAC,CAAC,CAAA,CAAA,EAAI,GAAA,CAAI,SAAA,CAAU,CAAA,EAAG,EAAE,CAAC,CAAA,CAAA,EAAI,GAAA,CAAI,SAAA,CAAU,EAAA,EAAI,EAAE,CAAC,CAAA,CAAA,EAAI,GAAA,CAAI,SAAA,CAAU,EAAA,EAAI,EAAE,CAAC,CAAA,CAAA,EAAI,GAAA,CAAI,SAAA,CAAU,EAAE,CAAC,CAAA,CAAA;AAC9H","file":"index.js","sourcesContent":["/**\n * Event Bus\n *\n * Pub/sub event system for kernel and plugins.\n * Type-safe event handling with automatic unsubscribe.\n */\n\nimport type { AuthEvent, EventType, EventHandler, Unsubscribe } from '../types'\n\n/** Handler type as stored internally (handlers are keyed by event type) */\ntype AnyEventHandler = (event: AuthEvent) => void\n\n/**\n * EventBus class for managing event subscriptions and emissions\n */\nexport class EventBus {\n private handlers: Map<EventType, Set<AnyEventHandler>> = new Map()\n /** Deliveries scheduled by emit() and not run yet (cancelled by clear()) */\n private pending: Set<ReturnType<typeof setTimeout>> = new Set()\n\n /**\n * Subscribe to an event\n *\n * @param eventType - Type of event to listen for\n * @param handler - Handler function to call when event is emitted\n * @returns Unsubscribe function\n */\n on<E extends EventType>(eventType: E, handler: EventHandler<E>): Unsubscribe {\n // Get or create handler set for this event type\n let handlerSet = this.handlers.get(eventType)\n if (!handlerSet) {\n handlerSet = new Set()\n this.handlers.set(eventType, handlerSet)\n }\n\n handlerSet.add(handler as AnyEventHandler)\n\n // Return unsubscribe function\n return () => this.off(eventType, handler)\n }\n\n /**\n * Unsubscribe from an event\n *\n * @param eventType - Type of event to stop listening for\n * @param handler - Handler function to remove\n */\n off<E extends EventType>(eventType: E, handler: EventHandler<E>): void {\n const handlerSet = this.handlers.get(eventType)\n if (handlerSet) {\n handlerSet.delete(handler as AnyEventHandler)\n\n // Clean up empty sets\n if (handlerSet.size === 0) {\n this.handlers.delete(eventType)\n }\n }\n }\n\n /**\n * Emit an event to all subscribers\n *\n * Handlers are executed asynchronously in the next tick to prevent blocking.\n * The event goes to the handlers subscribed when it is emitted (a handler\n * added later does not receive it) that are still subscribed at delivery.\n *\n * @param event - Event to emit\n */\n emit(event: AuthEvent): void {\n const handlerSet = this.handlers.get(event.type)\n if (!handlerSet || handlerSet.size === 0) {\n return\n }\n const recipients = Array.from(handlerSet)\n\n // Execute handlers in next tick to prevent blocking\n const timer = setTimeout(() => {\n this.pending.delete(timer)\n recipients.forEach((handler) => {\n // Unsubscribed meanwhile (also by an earlier handler of this event)\n if (this.handlers.get(event.type)?.has(handler) !== true) return\n try {\n handler(event)\n } catch (error) {\n // Log error but don't throw to prevent one handler from breaking others\n console.error(`[AuthKeeper] Error in event handler for ${event.type}:`, error)\n }\n })\n }, 0)\n this.pending.add(timer)\n }\n\n /**\n * Remove all event handlers and cancel deliveries that have not run yet\n * (no handler runs after the kernel is destroyed)\n */\n clear(): void {\n this.pending.forEach((timer) => clearTimeout(timer))\n this.pending.clear()\n this.handlers.clear()\n }\n\n /**\n * Get count of handlers for an event type\n *\n * @param eventType - Event type to count handlers for\n * @returns Number of handlers\n */\n getHandlerCount(eventType: EventType): number {\n return this.handlers.get(eventType)?.size || 0\n }\n\n /**\n * Get all event types that have handlers\n *\n * @returns Array of event types\n */\n getActiveEventTypes(): EventType[] {\n return Array.from(this.handlers.keys())\n }\n}\n","/**\n * Plugin Registry\n *\n * Manages plugin registration, installation, and lifecycle.\n */\n\nimport { AuthError, type Plugin, type PluginInfo, type AuthKeeper } from '../types'\n\n/**\n * Plugin instance with metadata\n */\ninterface PluginInstance {\n plugin: Plugin\n installed: boolean\n api: unknown\n}\n\n/**\n * PluginRegistry class for managing plugins\n */\nexport class PluginRegistry {\n private plugins: Map<string, PluginInstance> = new Map()\n\n /**\n * Register a plugin\n *\n * @param plugin - Plugin to register\n * @throws {AuthError} If plugin with same name already registered\n */\n register(plugin: Plugin): void {\n if (this.plugins.has(plugin.name)) {\n throw new AuthError('CONFIG_ERROR', `Plugin \"${plugin.name}\" is already registered`, {\n context: { pluginName: plugin.name },\n })\n }\n\n const instance: PluginInstance = {\n plugin,\n installed: false,\n api: null,\n }\n\n this.plugins.set(plugin.name, instance)\n }\n\n /**\n * Install a plugin\n *\n * Calls the plugin's install method and stores the returned API.\n *\n * @param name - Plugin name\n * @param kernel - Kernel instance to pass to plugin\n * @throws {AuthError} If plugin not found or already installed\n */\n async install(name: string, kernel: AuthKeeper): Promise<void> {\n const instance = this.plugins.get(name)\n\n if (!instance) {\n throw new AuthError('CONFIG_ERROR', `Plugin \"${name}\" not found`, {\n context: { pluginName: name },\n })\n }\n\n if (instance.installed) {\n // Already installed, skip\n return\n }\n\n try {\n // Call plugin's install method\n const api: unknown = await instance.plugin.install(kernel)\n instance.api = api || null\n instance.installed = true\n } catch (error) {\n throw new AuthError('CONFIG_ERROR', `Failed to install plugin \"${name}\"`, {\n cause: error as Error,\n context: { pluginName: name },\n })\n }\n }\n\n /**\n * Uninstall a plugin\n *\n * Calls the plugin's uninstall method if it exists.\n *\n * @param name - Plugin name\n */\n async uninstall(name: string): Promise<void> {\n const instance = this.plugins.get(name)\n\n if (!instance) {\n // Plugin not found, nothing to uninstall\n return\n }\n\n if (instance.installed && instance.plugin.uninstall) {\n try {\n await instance.plugin.uninstall()\n } catch (error) {\n console.error(`[AuthKeeper] Error uninstalling plugin \"${name}\":`, error)\n }\n }\n\n this.plugins.delete(name)\n }\n\n /**\n * Get a plugin by name\n *\n * @param name - Plugin name\n * @returns Plugin or undefined if not found\n */\n get<P extends Plugin>(name: string): P | undefined {\n const instance = this.plugins.get(name)\n return instance?.plugin as P | undefined\n }\n\n /**\n * Get plugin API by name\n *\n * @param name - Plugin name\n * @returns Plugin API or undefined if not found\n */\n getApi<T = unknown>(name: string): T | undefined {\n const instance = this.plugins.get(name)\n return instance?.api as T | undefined\n }\n\n /**\n * Check if a plugin is registered\n *\n * @param name - Plugin name\n * @returns true if plugin is registered\n */\n has(name: string): boolean {\n return this.plugins.has(name)\n }\n\n /**\n * Check if a plugin is installed\n *\n * @param name - Plugin name\n * @returns true if plugin is installed\n */\n isInstalled(name: string): boolean {\n const instance = this.plugins.get(name)\n return instance?.installed || false\n }\n\n /**\n * List all plugins\n *\n * @returns Array of plugin information\n */\n list(): PluginInfo[] {\n return Array.from(this.plugins.entries()).map(([name, instance]) => ({\n name,\n version: instance.plugin.version,\n type: instance.plugin.type,\n enabled: instance.installed,\n }))\n }\n\n /**\n * Get all plugin names\n *\n * @returns Array of plugin names\n */\n getNames(): string[] {\n return Array.from(this.plugins.keys())\n }\n\n /**\n * Clear all plugins\n */\n clear(): void {\n this.plugins.clear()\n }\n}\n","/**\n * AuthKeeper Kernel\n *\n * The micro-kernel that orchestrates plugins and manages auth state.\n * Most functionality is delegated to core plugins.\n */\n\nimport { EventBus } from './event-bus'\nimport { PluginRegistry } from './plugin-registry'\nimport {\n AuthError,\n type AuthKeeper,\n type KernelOptions,\n type Plugin,\n type PluginInfo,\n type TokenSet,\n type TokenPayload,\n type LogoutOptions,\n type AuthFetch,\n type FetchInterceptorOptions,\n type EventType,\n type EventHandler,\n type Unsubscribe,\n type AuthEvent,\n} from '../types'\nimport type {\n TokenStoreAPI,\n TokenDecoderAPI,\n RefreshEngineAPI,\n FetchInterceptorAPI,\n} from '../plugins/core'\n\n/**\n * AuthKeeperKernel - Main kernel implementation\n */\nexport class AuthKeeperKernel implements AuthKeeper {\n private pluginRegistry: PluginRegistry\n private eventBus: EventBus\n private options: KernelOptions\n private initialized: boolean = false\n\n constructor(options: KernelOptions) {\n this.options = {\n autoRefresh: true,\n refreshThreshold: 60,\n ...options,\n }\n\n this.pluginRegistry = new PluginRegistry()\n this.eventBus = new EventBus()\n }\n\n // ============================================================================\n // Lifecycle\n // ============================================================================\n\n /**\n * Initialize the kernel\n *\n * 1. Install core plugins\n * 2. Install user-provided plugins\n * 3. Load tokens from storage\n * 4. Schedule refresh if authenticated\n */\n async init(): Promise<void> {\n if (this.initialized) {\n return\n }\n\n // Core plugins will be installed in Phase 4\n // For now, we just mark as initialized\n\n // Install user-provided plugins\n if (this.options.plugins) {\n for (const plugin of this.options.plugins) {\n await this.register(plugin)\n }\n }\n\n this.initialized = true\n }\n\n /**\n * Destroy the kernel and cleanup\n */\n destroy(): void {\n // Cancel any scheduled refreshes\n this.cancelScheduledRefresh()\n\n // Clear event handlers\n this.eventBus.clear()\n\n // Uninstall all plugins\n const pluginNames = this.pluginRegistry.getNames()\n for (const name of pluginNames) {\n // Not awaited: uninstall() catches plugin errors and destroy() stays synchronous\n void this.pluginRegistry.uninstall(name)\n }\n\n this.pluginRegistry.clear()\n this.initialized = false\n }\n\n // ============================================================================\n // Token Management\n // ============================================================================\n\n /**\n * Set authentication tokens\n *\n * Delegates to token-store plugin.\n */\n setTokens(tokens: TokenSet): void {\n const tokenStore = this.pluginRegistry.getApi<TokenStoreAPI>('token-store')\n if (!tokenStore) {\n throw new AuthError('CONFIG_ERROR', 'token-store plugin not installed')\n }\n\n tokenStore.set(tokens)\n\n // Emit login event - but not when the refresh engine is storing the\n // result of a token refresh (that is reported as a 'refresh' event)\n const refreshEngine = this.pluginRegistry.getApi<RefreshEngineAPI>('refresh-engine')\n if (refreshEngine?.isApplyingRefresh?.() !== true) {\n this.emit({\n type: 'login',\n tokens,\n timestamp: Date.now(),\n })\n }\n\n // Schedule auto-refresh if enabled\n if (this.options.autoRefresh && !this.isExpired()) {\n this.scheduleRefresh()\n }\n }\n\n /**\n * Get access token\n *\n * Delegates to token-store plugin.\n */\n getAccessToken(): string | null {\n const tokenStore = this.pluginRegistry.getApi<TokenStoreAPI>('token-store')\n if (!tokenStore) {\n return null\n }\n\n return tokenStore.getAccessToken()\n }\n\n /**\n * Get refresh token\n *\n * Delegates to token-store plugin.\n */\n getRefreshToken(): string | null {\n const tokenStore = this.pluginRegistry.getApi<TokenStoreAPI>('token-store')\n if (!tokenStore) {\n return null\n }\n\n return tokenStore.getRefreshToken()\n }\n\n /**\n * Clear all tokens\n */\n clearTokens(): void {\n // Nothing left to refresh: a pending scheduled refresh would only fail\n // with REFRESH_TOKEN_MISSING\n this.cancelScheduledRefresh()\n\n const tokenStore = this.pluginRegistry.getApi<TokenStoreAPI>('token-store')\n if (tokenStore) {\n tokenStore.clear()\n }\n }\n\n // ============================================================================\n // Auth State\n // ============================================================================\n\n /**\n * Check if user is authenticated\n */\n isAuthenticated(): boolean {\n const accessToken = this.getAccessToken()\n return accessToken !== null && !this.isExpired()\n }\n\n /**\n * Check if token is expired\n *\n * Delegates to token-store plugin.\n */\n isExpired(): boolean {\n const tokenStore = this.pluginRegistry.getApi<TokenStoreAPI>('token-store')\n if (!tokenStore) {\n return true\n }\n\n return tokenStore.isExpired()\n }\n\n /**\n * Get token expiration date\n *\n * Delegates to token-store plugin.\n */\n getExpiresAt(): Date | null {\n const tokenStore = this.pluginRegistry.getApi<TokenStoreAPI>('token-store')\n if (!tokenStore) {\n return null\n }\n\n return tokenStore.getExpiresAt()\n }\n\n /**\n * Get time until expiry in milliseconds\n *\n * Delegates to token-store plugin.\n */\n getTimeUntilExpiry(): number | null {\n const tokenStore = this.pluginRegistry.getApi<TokenStoreAPI>('token-store')\n if (!tokenStore) {\n return null\n }\n\n return tokenStore.getExpiresIn()\n }\n\n // ============================================================================\n // Token Decoding\n // ============================================================================\n\n /**\n * Decode token payload\n *\n * Delegates to token-decoder plugin.\n */\n decode<T = TokenPayload>(): T | null {\n const tokenDecoder = this.pluginRegistry.getApi<TokenDecoderAPI>('token-decoder')\n if (!tokenDecoder) {\n return null\n }\n\n return tokenDecoder.decode<T>()\n }\n\n /**\n * Get specific claim from token\n *\n * Delegates to token-decoder plugin.\n */\n getClaim<K extends keyof TokenPayload>(key: K): TokenPayload[K] | undefined {\n const tokenDecoder = this.pluginRegistry.getApi<TokenDecoderAPI>('token-decoder')\n if (!tokenDecoder) {\n return undefined\n }\n\n return tokenDecoder.getClaim(key)\n }\n\n /**\n * Get multiple claims from token\n *\n * Delegates to token-decoder plugin.\n */\n getClaims<K extends keyof TokenPayload>(keys: K[]): Pick<TokenPayload, K> {\n const tokenDecoder = this.pluginRegistry.getApi<TokenDecoderAPI>('token-decoder')\n if (!tokenDecoder) {\n return {} as Pick<TokenPayload, K>\n }\n\n return tokenDecoder.getClaims(keys)\n }\n\n // ============================================================================\n // Refresh\n // ============================================================================\n\n /**\n * Manually refresh tokens\n *\n * Delegates to refresh-engine plugin.\n */\n async refresh(): Promise<TokenSet> {\n const refreshEngine = this.pluginRegistry.getApi<RefreshEngineAPI>('refresh-engine')\n if (!refreshEngine) {\n throw new AuthError('CONFIG_ERROR', 'refresh-engine plugin not installed')\n }\n\n return refreshEngine.refresh()\n }\n\n /**\n * Schedule automatic refresh\n *\n * Delegates to refresh-engine plugin.\n */\n scheduleRefresh(): void {\n if (!this.options.autoRefresh) {\n return\n }\n\n const refreshEngine = this.pluginRegistry.getApi<RefreshEngineAPI>('refresh-engine')\n if (refreshEngine) {\n refreshEngine.scheduleRefresh()\n }\n }\n\n /**\n * Cancel scheduled refresh\n *\n * Delegates to refresh-engine plugin.\n */\n cancelScheduledRefresh(): void {\n const refreshEngine = this.pluginRegistry.getApi<RefreshEngineAPI>('refresh-engine')\n if (refreshEngine) {\n refreshEngine.cancelScheduledRefresh()\n }\n }\n\n // ============================================================================\n // Logout\n // ============================================================================\n\n /**\n * Logout user\n *\n * Clears tokens and emits logout event.\n */\n logout(options: LogoutOptions = {}): void {\n // Cancel scheduled refresh\n this.cancelScheduledRefresh()\n\n // Clear tokens\n this.clearTokens()\n\n // Emit logout event\n this.emit({\n type: 'logout',\n reason: 'manual',\n timestamp: Date.now(),\n })\n\n // Handle redirect if specified\n if (options.redirect && typeof window !== 'undefined') {\n window.location.href = options.redirect\n }\n }\n\n // ============================================================================\n // Interceptors\n // ============================================================================\n\n /**\n * Create authenticated fetch function\n *\n * Delegates to fetch-interceptor plugin.\n */\n createFetch(options?: FetchInterceptorOptions): AuthFetch {\n const fetchInterceptor = this.pluginRegistry.getApi<FetchInterceptorAPI>('fetch-interceptor')\n if (!fetchInterceptor) {\n // Return regular fetch if plugin not installed\n return fetch.bind(globalThis)\n }\n\n return fetchInterceptor.createFetch(options)\n }\n\n /**\n * Wrap global fetch with auth\n *\n * Delegates to fetch-interceptor plugin.\n */\n wrapFetch(fetch: typeof globalThis.fetch): void {\n const fetchInterceptor = this.pluginRegistry.getApi<FetchInterceptorAPI>('fetch-interceptor')\n if (fetchInterceptor) {\n fetchInterceptor.wrapFetch(fetch)\n }\n }\n\n // ============================================================================\n // Plugin Management\n // ============================================================================\n\n /**\n * Register and install a plugin\n *\n * The returned promise rejects when the plugin cannot be registered or\n * installed. The failure is also emitted as an 'error' event (context\n * 'plugin') and passed to `onError`, so a caller that does not await the\n * promise does not get an unhandled rejection.\n */\n register(plugin: Plugin): Promise<void> {\n const result = this.registerPlugin(plugin)\n result.catch((error: AuthError) => {\n // PluginRegistry only throws AuthError (CONFIG_ERROR)\n this.emit({ type: 'error', error, context: 'plugin', timestamp: Date.now() })\n })\n return result\n }\n\n private async registerPlugin(plugin: Plugin): Promise<void> {\n this.pluginRegistry.register(plugin)\n try {\n await this.pluginRegistry.install(plugin.name, this)\n } catch (error) {\n // Drop the half-registered plugin so it can be registered again\n await this.pluginRegistry.uninstall(plugin.name)\n throw error\n }\n }\n\n /**\n * Unregister a plugin\n */\n async unregister(pluginName: string): Promise<void> {\n await this.pluginRegistry.uninstall(pluginName)\n }\n\n /**\n * Get plugin by name\n */\n getPlugin<P extends Plugin>(name: string): P | undefined {\n return this.pluginRegistry.get<P>(name)\n }\n\n /**\n * List all plugins\n */\n listPlugins(): PluginInfo[] {\n return this.pluginRegistry.list()\n }\n\n // ============================================================================\n // Event System\n // ============================================================================\n\n /**\n * Emit an event\n */\n emit(event: AuthEvent): void {\n this.eventBus.emit(event)\n\n // Call global error handler if it's an error event\n if (event.type === 'error' && this.options.onError) {\n this.options.onError(event.error)\n }\n }\n\n /**\n * Subscribe to events\n */\n on<E extends EventType>(eventType: E, handler: EventHandler<E>): Unsubscribe {\n return this.eventBus.on(eventType, handler)\n }\n\n /**\n * Unsubscribe from events\n */\n off<E extends EventType>(eventType: E, handler: EventHandler<E>): void {\n this.eventBus.off(eventType, handler)\n }\n\n // ============================================================================\n // Configuration\n // ============================================================================\n\n /**\n * Update configuration\n */\n configure(options: Partial<KernelOptions>): void {\n this.options = {\n ...this.options,\n ...options,\n }\n\n // Update refresh engine threshold if changed\n if (options.refreshThreshold !== undefined) {\n const refreshEngine = this.pluginRegistry.getApi<RefreshEngineAPI>('refresh-engine')\n if (refreshEngine && refreshEngine.setThreshold) {\n refreshEngine.setThreshold(options.refreshThreshold)\n }\n }\n }\n\n /**\n * Get current configuration\n */\n getOptions(): KernelOptions {\n // Multi-tab sync is not implemented: report the effective value\n return { ...this.options, syncTabs: false }\n }\n}\n","/**\n * Factory Function\n *\n * Creates and initializes an AuthKeeper instance with core plugins.\n */\n\nimport { AuthKeeperKernel } from './kernel'\nimport {\n resolveStorage,\n createTokenStorePlugin,\n createTokenDecoderPlugin,\n createRefreshEnginePlugin,\n createFetchInterceptorPlugin,\n} from './plugins/core'\nimport type { AuthKeeper, KernelOptions } from './types'\n\n/**\n * Create an AuthKeeper instance\n *\n * Automatically installs core plugins:\n * - token-store: Token state management\n * - token-decoder: JWT decoding\n * - refresh-engine: Auto-refresh with queue\n * - storage-memory: Default secure storage\n * - fetch-interceptor: Auth header injection and 401 retry\n *\n * @param options - Configuration options\n * @returns AuthKeeper instance\n *\n * @example\n * ```typescript\n * const auth = createAuthKeeper({\n * storage: 'memory',\n * refreshToken: async (token) => {\n * const res = await fetch('/api/auth/refresh', {\n * method: 'POST',\n * body: JSON.stringify({ refreshToken: token }),\n * })\n * return res.json()\n * },\n * autoRefresh: true,\n * refreshThreshold: 60,\n * })\n *\n * await auth.init()\n * ```\n */\nexport async function createAuthKeeper(options: KernelOptions): Promise<AuthKeeper> {\n // Create kernel\n const kernel = new AuthKeeperKernel(options)\n\n // Register and install core plugins\n // 1. token-store (restores persisted tokens from the configured storage)\n await kernel.register(createTokenStorePlugin({ storage: resolveStorage(options.storage) }))\n\n // 2. token-decoder\n await kernel.register(createTokenDecoderPlugin())\n\n // 3. refresh-engine\n await kernel.register(\n createRefreshEnginePlugin({\n refreshFn: options.refreshToken,\n threshold: options.refreshThreshold,\n }),\n )\n\n // 5. fetch-interceptor\n await kernel.register(createFetchInterceptorPlugin())\n\n // Initialize kernel\n await kernel.init()\n\n // Resume auto-refresh for tokens restored from storage\n if (kernel.getAccessToken() && !kernel.isExpired()) {\n kernel.scheduleRefresh()\n } else if (\n kernel.getAccessToken() &&\n kernel.getRefreshToken() &&\n kernel.getOptions().autoRefresh !== false\n ) {\n // Restored tokens already expired: refresh them in the background\n // (`await auth.refresh()` joins this refresh). A failure is reported as\n // an 'error' event / onError, like any refresh failure.\n kernel.refresh().catch(() => {})\n }\n\n return kernel\n}\n","/**\n * Time and expiry utilities\n *\n * Helper functions for working with token expiration times.\n */\n\n/**\n * Check if a timestamp is expired\n *\n * @param expiresAt - Expiration timestamp in milliseconds\n * @param bufferMs - Consider expired if within this many milliseconds (default: 0)\n * @returns true if expired\n */\nexport function isExpired(expiresAt: number | null | undefined, bufferMs: number = 0): boolean {\n if (!expiresAt) {\n return false\n }\n\n const now = Date.now()\n return now >= expiresAt - bufferMs\n}\n\n/**\n * Get time until expiry in milliseconds\n *\n * @param expiresAt - Expiration timestamp in milliseconds\n * @returns Milliseconds until expiry, or null if no expiry. Returns 0 if already expired.\n */\nexport function getExpiresIn(expiresAt: number | null | undefined): number | null {\n if (!expiresAt) {\n return null\n }\n\n const now = Date.now()\n const timeUntil = expiresAt - now\n return Math.max(0, timeUntil)\n}\n\n/**\n * Convert seconds to milliseconds\n *\n * @param seconds - Time in seconds\n * @returns Time in milliseconds\n */\nexport function secondsToMs(seconds: number): number {\n return seconds * 1000\n}\n\n/**\n * Convert milliseconds to seconds\n *\n * @param ms - Time in milliseconds\n * @returns Time in seconds\n */\nexport function msToSeconds(ms: number): number {\n return Math.floor(ms / 1000)\n}\n\n/**\n * Calculate expiry timestamp from expiresIn seconds\n *\n * @param expiresIn - Seconds until expiry\n * @returns Expiry timestamp in milliseconds\n */\nexport function calculateExpiresAt(expiresIn: number): number {\n return Date.now() + secondsToMs(expiresIn)\n}\n\n/**\n * Format time remaining as human-readable string\n *\n * @param ms - Milliseconds\n * @returns Formatted string like \"5m 30s\" or \"2h 15m\"\n */\nexport function formatTimeRemaining(ms: number): string {\n if (ms <= 0) {\n return 'expired'\n }\n\n const seconds = Math.floor(ms / 1000)\n const minutes = Math.floor(seconds / 60)\n const hours = Math.floor(minutes / 60)\n const days = Math.floor(hours / 24)\n\n if (days > 0) {\n const remainingHours = hours % 24\n return remainingHours > 0 ? `${days}d ${remainingHours}h` : `${days}d`\n }\n\n if (hours > 0) {\n const remainingMinutes = minutes % 60\n return remainingMinutes > 0 ? `${hours}h ${remainingMinutes}m` : `${hours}h`\n }\n\n if (minutes > 0) {\n const remainingSeconds = seconds % 60\n return remainingSeconds > 0 ? `${minutes}m ${remainingSeconds}s` : `${minutes}m`\n }\n\n return `${seconds}s`\n}\n","/**\n * Cryptographic utilities for PKCE (Proof Key for Code Exchange)\n *\n * Implements OAuth2 PKCE flow requirements:\n * - Code verifier generation (43-128 characters)\n * - Code challenge generation (SHA-256)\n */\n\nimport { base64UrlEncode } from './base64'\n\n/**\n * Generate a cryptographically secure random code verifier for PKCE\n *\n * The code verifier is a high-entropy cryptographic random string\n * with a minimum length of 43 characters and maximum of 128 characters.\n *\n * @param length - Length of the code verifier (default: 64, min: 43, max: 128)\n * @returns Base64URL-encoded random string\n */\nexport function generateCodeVerifier(length: number = 64): string {\n // Validate length\n if (length < 43 || length > 128) {\n throw new Error('Code verifier length must be between 43 and 128 characters')\n }\n\n // Generate random bytes\n // We need enough bytes to produce the desired length after base64url encoding\n // Base64 encoding increases size by ~33%, so we generate 3/4 of desired length\n const byteLength = Math.ceil((length * 3) / 4)\n const randomBytes = new Uint8Array(byteLength)\n crypto.getRandomValues(randomBytes)\n\n // Encode and trim to exact length\n const verifier = base64UrlEncode(randomBytes).substring(0, length)\n return verifier\n}\n\n/**\n * Generate code challenge from code verifier using SHA-256\n *\n * The code challenge is a Base64URL-encoded SHA-256 hash of the code verifier.\n * This is the recommended method for PKCE (S256).\n *\n * @param codeVerifier - The code verifier to hash\n * @returns Base64URL-encoded SHA-256 hash\n */\nexport async function generateCodeChallenge(codeVerifier: string): Promise<string> {\n // Convert verifier string to bytes\n const encoder = new TextEncoder()\n const data = encoder.encode(codeVerifier)\n\n // Hash with SHA-256\n const hashBuffer = await crypto.subtle.digest('SHA-256', data)\n\n // Convert to Base64URL\n const hashArray = new Uint8Array(hashBuffer)\n return base64UrlEncode(hashArray)\n}\n\n/**\n * Generate a cryptographically secure random string\n *\n * Useful for generating state, nonce, or other random identifiers.\n *\n * @param length - Desired length of the random string\n * @returns Base64URL-encoded random string\n */\nexport function generateRandomString(length: number): string {\n const byteLength = Math.ceil((length * 3) / 4)\n const randomBytes = new Uint8Array(byteLength)\n crypto.getRandomValues(randomBytes)\n return base64UrlEncode(randomBytes).substring(0, length)\n}\n\n/**\n * Generate a random UUID v4\n *\n * @returns UUID v4 string\n */\nexport function generateUuid(): string {\n // Use crypto.randomUUID if available\n if (typeof crypto.randomUUID === 'function') {\n return crypto.randomUUID()\n }\n\n // Fallback: generate UUID v4 manually\n const bytes = new Uint8Array(16)\n crypto.getRandomValues(bytes)\n\n // Set version (4) and variant bits\n bytes[6] = ((bytes[6] as number) & 0x0f) | 0x40 // Version 4\n bytes[8] = ((bytes[8] as number) & 0x3f) | 0x80 // Variant 10\n\n // Convert to hex string with dashes\n const hex = Array.from(bytes)\n .map((b) => b.toString(16).padStart(2, '0'))\n .join('')\n\n return `${hex.substring(0, 8)}-${hex.substring(8, 12)}-${hex.substring(12, 16)}-${hex.substring(16, 20)}-${hex.substring(20)}`\n}\n"]}
|
package/dist/plugins/index.cjs
CHANGED
|
@@ -1,60 +1,61 @@
|
|
|
1
1
|
'use strict';
|
|
2
2
|
|
|
3
|
-
var
|
|
3
|
+
var chunk47JWRVTL_cjs = require('../chunk-47JWRVTL.cjs');
|
|
4
|
+
require('../chunk-XGKVBZSF.cjs');
|
|
4
5
|
|
|
5
6
|
|
|
6
7
|
|
|
7
8
|
Object.defineProperty(exports, "CookieStorageAdapter", {
|
|
8
9
|
enumerable: true,
|
|
9
|
-
get: function () { return
|
|
10
|
+
get: function () { return chunk47JWRVTL_cjs.CookieStorageAdapter; }
|
|
10
11
|
});
|
|
11
12
|
Object.defineProperty(exports, "FetchInterceptorPlugin", {
|
|
12
13
|
enumerable: true,
|
|
13
|
-
get: function () { return
|
|
14
|
+
get: function () { return chunk47JWRVTL_cjs.FetchInterceptorPlugin; }
|
|
14
15
|
});
|
|
15
16
|
Object.defineProperty(exports, "MemoryStorageAdapter", {
|
|
16
17
|
enumerable: true,
|
|
17
|
-
get: function () { return
|
|
18
|
+
get: function () { return chunk47JWRVTL_cjs.MemoryStorageAdapter; }
|
|
18
19
|
});
|
|
19
20
|
Object.defineProperty(exports, "RefreshEnginePlugin", {
|
|
20
21
|
enumerable: true,
|
|
21
|
-
get: function () { return
|
|
22
|
+
get: function () { return chunk47JWRVTL_cjs.RefreshEnginePlugin; }
|
|
22
23
|
});
|
|
23
24
|
Object.defineProperty(exports, "TokenDecoderPlugin", {
|
|
24
25
|
enumerable: true,
|
|
25
|
-
get: function () { return
|
|
26
|
+
get: function () { return chunk47JWRVTL_cjs.TokenDecoderPlugin; }
|
|
26
27
|
});
|
|
27
28
|
Object.defineProperty(exports, "TokenStorePlugin", {
|
|
28
29
|
enumerable: true,
|
|
29
|
-
get: function () { return
|
|
30
|
+
get: function () { return chunk47JWRVTL_cjs.TokenStorePlugin; }
|
|
30
31
|
});
|
|
31
32
|
Object.defineProperty(exports, "WebStorageAdapter", {
|
|
32
33
|
enumerable: true,
|
|
33
|
-
get: function () { return
|
|
34
|
+
get: function () { return chunk47JWRVTL_cjs.WebStorageAdapter; }
|
|
34
35
|
});
|
|
35
36
|
Object.defineProperty(exports, "createFetchInterceptorPlugin", {
|
|
36
37
|
enumerable: true,
|
|
37
|
-
get: function () { return
|
|
38
|
+
get: function () { return chunk47JWRVTL_cjs.createFetchInterceptorPlugin; }
|
|
38
39
|
});
|
|
39
40
|
Object.defineProperty(exports, "createMemoryStorage", {
|
|
40
41
|
enumerable: true,
|
|
41
|
-
get: function () { return
|
|
42
|
+
get: function () { return chunk47JWRVTL_cjs.createMemoryStorage; }
|
|
42
43
|
});
|
|
43
44
|
Object.defineProperty(exports, "createRefreshEnginePlugin", {
|
|
44
45
|
enumerable: true,
|
|
45
|
-
get: function () { return
|
|
46
|
+
get: function () { return chunk47JWRVTL_cjs.createRefreshEnginePlugin; }
|
|
46
47
|
});
|
|
47
48
|
Object.defineProperty(exports, "createTokenDecoderPlugin", {
|
|
48
49
|
enumerable: true,
|
|
49
|
-
get: function () { return
|
|
50
|
+
get: function () { return chunk47JWRVTL_cjs.createTokenDecoderPlugin; }
|
|
50
51
|
});
|
|
51
52
|
Object.defineProperty(exports, "createTokenStorePlugin", {
|
|
52
53
|
enumerable: true,
|
|
53
|
-
get: function () { return
|
|
54
|
+
get: function () { return chunk47JWRVTL_cjs.createTokenStorePlugin; }
|
|
54
55
|
});
|
|
55
56
|
Object.defineProperty(exports, "resolveStorage", {
|
|
56
57
|
enumerable: true,
|
|
57
|
-
get: function () { return
|
|
58
|
+
get: function () { return chunk47JWRVTL_cjs.resolveStorage; }
|
|
58
59
|
});
|
|
59
60
|
//# sourceMappingURL=index.cjs.map
|
|
60
61
|
//# sourceMappingURL=index.cjs.map
|
package/dist/plugins/index.d.cts
CHANGED
|
@@ -1 +1,2 @@
|
|
|
1
|
-
export {
|
|
1
|
+
export { a as CookieStorageAdapter, b as CookieStorageOptions, F as FetchInterceptorAPI, c as FetchInterceptorPlugin, M as MemoryStorageAdapter, d as MemoryStorageOptions, R as RefreshEngineAPI, e as RefreshEngineOptions, f as RefreshEnginePlugin, T as TokenDecoderAPI, g as TokenDecoderPlugin, h as TokenStoreAPI, i as TokenStoreOptions, j as TokenStorePlugin, W as WebStorageAdapter, k as WebStorageOptions, l as createFetchInterceptorPlugin, m as createMemoryStorage, n as createRefreshEnginePlugin, o as createTokenDecoderPlugin, p as createTokenStorePlugin, v as resolveStorage } from '../index-C4pGS-TI.cjs';
|
|
2
|
+
import '../types-DMPBl-Ym.cjs';
|
package/dist/plugins/index.d.ts
CHANGED
|
@@ -1 +1,2 @@
|
|
|
1
|
-
export {
|
|
1
|
+
export { a as CookieStorageAdapter, b as CookieStorageOptions, F as FetchInterceptorAPI, c as FetchInterceptorPlugin, M as MemoryStorageAdapter, d as MemoryStorageOptions, R as RefreshEngineAPI, e as RefreshEngineOptions, f as RefreshEnginePlugin, T as TokenDecoderAPI, g as TokenDecoderPlugin, h as TokenStoreAPI, i as TokenStoreOptions, j as TokenStorePlugin, W as WebStorageAdapter, k as WebStorageOptions, l as createFetchInterceptorPlugin, m as createMemoryStorage, n as createRefreshEnginePlugin, o as createTokenDecoderPlugin, p as createTokenStorePlugin, v as resolveStorage } from '../index-CQwGO-Wk.js';
|
|
2
|
+
import '../types-DMPBl-Ym.js';
|
package/dist/plugins/index.js
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
-
export { CookieStorageAdapter, FetchInterceptorPlugin, MemoryStorageAdapter, RefreshEnginePlugin, TokenDecoderPlugin, TokenStorePlugin, WebStorageAdapter, createFetchInterceptorPlugin, createMemoryStorage, createRefreshEnginePlugin, createTokenDecoderPlugin, createTokenStorePlugin, resolveStorage } from '../chunk-
|
|
1
|
+
export { CookieStorageAdapter, FetchInterceptorPlugin, MemoryStorageAdapter, RefreshEnginePlugin, TokenDecoderPlugin, TokenStorePlugin, WebStorageAdapter, createFetchInterceptorPlugin, createMemoryStorage, createRefreshEnginePlugin, createTokenDecoderPlugin, createTokenStorePlugin, resolveStorage } from '../chunk-ANGR5HRJ.js';
|
|
2
|
+
import '../chunk-DLCD3SBV.js';
|
|
2
3
|
//# sourceMappingURL=index.js.map
|
|
3
4
|
//# sourceMappingURL=index.js.map
|
package/dist/react/index.cjs
CHANGED
|
@@ -1,8 +1,129 @@
|
|
|
1
1
|
'use strict';
|
|
2
2
|
|
|
3
|
-
|
|
4
|
-
var
|
|
3
|
+
var chunkXGKVBZSF_cjs = require('../chunk-XGKVBZSF.cjs');
|
|
4
|
+
var chunkLGZGECYE_cjs = require('../chunk-LGZGECYE.cjs');
|
|
5
|
+
var react = require('react');
|
|
5
6
|
|
|
6
|
-
|
|
7
|
+
var AuthContext = react.createContext(null);
|
|
8
|
+
function AuthProvider({ auth, children }) {
|
|
9
|
+
return react.createElement(AuthContext.Provider, { value: auth }, children);
|
|
10
|
+
}
|
|
11
|
+
function useAuthKeeper() {
|
|
12
|
+
const auth = react.useContext(AuthContext);
|
|
13
|
+
if (!auth) {
|
|
14
|
+
throw new chunkXGKVBZSF_cjs.AuthError("CONFIG_ERROR", "useAuthKeeper() must be used inside <AuthProvider>");
|
|
15
|
+
}
|
|
16
|
+
return auth;
|
|
17
|
+
}
|
|
18
|
+
var getServerState = () => chunkLGZGECYE_cjs.SIGNED_OUT_STATE;
|
|
19
|
+
function useAuthInstance(auth, caller) {
|
|
20
|
+
const fromContext = react.useContext(AuthContext);
|
|
21
|
+
const instance = auth ?? fromContext;
|
|
22
|
+
if (!instance) {
|
|
23
|
+
throw new chunkXGKVBZSF_cjs.AuthError(
|
|
24
|
+
"CONFIG_ERROR",
|
|
25
|
+
`${caller} needs an AuthKeeper instance: pass it or render inside <AuthProvider auth={...}>`
|
|
26
|
+
);
|
|
27
|
+
}
|
|
28
|
+
return instance;
|
|
29
|
+
}
|
|
30
|
+
function useAuthSource(instance) {
|
|
31
|
+
return react.useMemo(() => chunkLGZGECYE_cjs.createAuthSource(instance), [instance]);
|
|
32
|
+
}
|
|
33
|
+
function useAuth(auth) {
|
|
34
|
+
const instance = useAuthInstance(auth, "useAuth()");
|
|
35
|
+
const source = useAuthSource(instance);
|
|
36
|
+
const state = react.useSyncExternalStore(source.subscribe, source.getState, getServerState);
|
|
37
|
+
const actions = react.useMemo(
|
|
38
|
+
() => ({
|
|
39
|
+
setTokens: (tokens) => instance.setTokens(tokens),
|
|
40
|
+
logout: (options) => instance.logout(options),
|
|
41
|
+
refresh: () => instance.refresh()
|
|
42
|
+
}),
|
|
43
|
+
[instance]
|
|
44
|
+
);
|
|
45
|
+
return react.useMemo(() => ({ ...state, ...actions }), [state, actions]);
|
|
46
|
+
}
|
|
47
|
+
var getServerTokenState = () => chunkLGZGECYE_cjs.NO_TOKEN_STATE;
|
|
48
|
+
var getServerUser = () => null;
|
|
49
|
+
function useToken(auth) {
|
|
50
|
+
const instance = useAuthInstance(auth, "useToken()");
|
|
51
|
+
const source = useAuthSource(instance);
|
|
52
|
+
const state = react.useSyncExternalStore(source.subscribe, source.getTokenState, getServerTokenState);
|
|
53
|
+
const authFetch = react.useMemo(() => instance.createFetch(), [instance]);
|
|
54
|
+
return react.useMemo(() => ({ ...state, authFetch }), [state, authFetch]);
|
|
55
|
+
}
|
|
56
|
+
function useUser(auth) {
|
|
57
|
+
const instance = useAuthInstance(auth, "useUser()");
|
|
58
|
+
const source = useAuthSource(instance);
|
|
59
|
+
const user = react.useSyncExternalStore(source.subscribe, () => source.getState().user, getServerUser);
|
|
60
|
+
const getClaim = react.useCallback(
|
|
61
|
+
(key) => chunkLGZGECYE_cjs.readClaim(user, key),
|
|
62
|
+
[user]
|
|
63
|
+
);
|
|
64
|
+
return react.useMemo(() => ({ user, claims: user ?? chunkLGZGECYE_cjs.NO_CLAIMS, getClaim }), [user, getClaim]);
|
|
65
|
+
}
|
|
66
|
+
function claimList(user, key) {
|
|
67
|
+
const value = user?.[key];
|
|
68
|
+
return Array.isArray(value) ? value : [];
|
|
69
|
+
}
|
|
70
|
+
function checkAccess(state, roles, permissions) {
|
|
71
|
+
if (!state.isAuthenticated) return "unauthenticated";
|
|
72
|
+
const userRoles = claimList(state.user, "roles");
|
|
73
|
+
const userPermissions = claimList(state.user, "permissions");
|
|
74
|
+
if (roles?.length && !roles.some((role) => userRoles.includes(role))) return "forbidden";
|
|
75
|
+
if (permissions && !permissions.every((p) => userPermissions.includes(p))) return "forbidden";
|
|
76
|
+
return "authorized";
|
|
77
|
+
}
|
|
78
|
+
var getServerAccess = () => "pending";
|
|
79
|
+
function RequireAuth({
|
|
80
|
+
children,
|
|
81
|
+
fallback = null,
|
|
82
|
+
loadingFallback = null,
|
|
83
|
+
roles,
|
|
84
|
+
permissions,
|
|
85
|
+
onUnauthorized,
|
|
86
|
+
auth
|
|
87
|
+
}) {
|
|
88
|
+
const instance = useAuthInstance(auth, "<RequireAuth>");
|
|
89
|
+
const source = useAuthSource(instance);
|
|
90
|
+
const access = react.useSyncExternalStore(
|
|
91
|
+
source.subscribe,
|
|
92
|
+
() => checkAccess(source.getState(), roles, permissions),
|
|
93
|
+
getServerAccess
|
|
94
|
+
);
|
|
95
|
+
const reported = react.useRef(null);
|
|
96
|
+
react.useEffect(() => {
|
|
97
|
+
if (access === "authorized" || access === "pending") {
|
|
98
|
+
reported.current = null;
|
|
99
|
+
} else if (reported.current !== access) {
|
|
100
|
+
reported.current = access;
|
|
101
|
+
onUnauthorized?.(access);
|
|
102
|
+
}
|
|
103
|
+
}, [access]);
|
|
104
|
+
const content = access === "authorized" ? children : access === "pending" ? loadingFallback : fallback;
|
|
105
|
+
return react.createElement(react.Fragment, null, content);
|
|
106
|
+
}
|
|
107
|
+
function nameOf(component) {
|
|
108
|
+
const { displayName, name, render, type } = component;
|
|
109
|
+
const inner = render ?? type;
|
|
110
|
+
return displayName || name || inner && nameOf(inner);
|
|
111
|
+
}
|
|
112
|
+
function withAuth(Component, options = {}) {
|
|
113
|
+
const Inner = Component;
|
|
114
|
+
const Wrapped = react.forwardRef(
|
|
115
|
+
(props, ref) => react.createElement(RequireAuth, options, react.createElement(Inner, { ...props, ref }))
|
|
116
|
+
);
|
|
117
|
+
Wrapped.displayName = `withAuth(${nameOf(Component) || "Component"})`;
|
|
118
|
+
return Wrapped;
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
exports.AuthProvider = AuthProvider;
|
|
122
|
+
exports.RequireAuth = RequireAuth;
|
|
123
|
+
exports.useAuth = useAuth;
|
|
124
|
+
exports.useAuthKeeper = useAuthKeeper;
|
|
125
|
+
exports.useToken = useToken;
|
|
126
|
+
exports.useUser = useUser;
|
|
127
|
+
exports.withAuth = withAuth;
|
|
7
128
|
//# sourceMappingURL=index.cjs.map
|
|
8
129
|
//# sourceMappingURL=index.cjs.map
|
package/dist/react/index.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/adapters/react/index.ts"],"names":[],"mappings":";;;AAQO,IAAM,6BAAA,GAAgC","file":"index.cjs","sourcesContent":["/**\n * React Adapter\n *\n * React hooks and components for AuthKeeper.\n * Will be implemented in Phase 7.\n */\n\n// Placeholder export to prevent build errors\nexport const __REACT_ADAPTER_PLACEHOLDER__ = true\n"]}
|
|
1
|
+
{"version":3,"sources":["../../src/adapters/react/use-auth.ts","../../src/adapters/react/use-token.ts","../../src/adapters/react/require-auth.ts"],"names":["createContext","createElement","useContext","AuthError","SIGNED_OUT_STATE","useMemo","createAuthSource","useSyncExternalStore","NO_TOKEN_STATE","useCallback","readClaim","NO_CLAIMS","useRef","useEffect","Fragment","forwardRef"],"mappings":";;;;;;AAgBA,IAAM,WAAA,GAAcA,oBAAiC,IAAI,CAAA;AAclD,SAAS,YAAA,CAAa,EAAE,IAAA,EAAM,QAAA,EAAS,EAAoC;AAChF,EAAA,OAAOC,oBAAc,WAAA,CAAY,QAAA,EAAU,EAAE,KAAA,EAAO,IAAA,IAAQ,QAAQ,CAAA;AACtE;AAMO,SAAS,aAAA,GAA4B;AAC1C,EAAA,MAAM,IAAA,GAAOC,iBAAW,WAAW,CAAA;AACnC,EAAA,IAAI,CAAC,IAAA,EAAM;AACT,IAAA,MAAM,IAAIC,2BAAA,CAAU,cAAA,EAAgB,oDAAoD,CAAA;AAAA,EAC1F;AACA,EAAA,OAAO,IAAA;AACT;AAYA,IAAM,iBAAiB,MAAiBC,kCAAA;AAMjC,SAAS,eAAA,CAAgB,MAA8B,MAAA,EAA4B;AACxF,EAAA,MAAM,WAAA,GAAcF,iBAAW,WAAW,CAAA;AAC1C,EAAA,MAAM,WAAW,IAAA,IAAQ,WAAA;AACzB,EAAA,IAAI,CAAC,QAAA,EAAU;AACb,IAAA,MAAM,IAAIC,2BAAA;AAAA,MACR,cAAA;AAAA,MACA,GAAG,MAAM,CAAA,iFAAA;AAAA,KACX;AAAA,EACF;AACA,EAAA,OAAO,QAAA;AACT;AAMO,SAAS,cAAc,QAAA,EAAkC;AAC9D,EAAA,OAAOE,cAAQ,MAAMC,kCAAA,CAAiB,QAAQ,CAAA,EAAG,CAAC,QAAQ,CAAC,CAAA;AAC7D;AAWO,SAAS,QAAQ,IAAA,EAAkC;AACxD,EAAA,MAAM,QAAA,GAAW,eAAA,CAAgB,IAAA,EAAM,WAAW,CAAA;AA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IAAU,IAAA;AACxB,EAAA,OAAO,WAAA,IAAe,IAAA,IAAS,KAAA,IAAS,MAAA,CAAO,KAAK,CAAA;AACtD;AAMO,SAAS,QAAA,CAId,SAAA,EACA,OAAA,GAA2B,EAAC,EACyB;AACrD,EAAA,MAAM,KAAA,GAAqB,SAAA;AAC3B,EAAA,MAAM,OAAA,GAAUC,gBAAA;AAAA,IAA4B,CAAC,KAAA,EAAO,GAAA,KAClDd,mBAAAA,CAAc,WAAA,EAAa,OAAA,EAASA,mBAAAA,CAAc,KAAA,EAAO,EAAE,GAAG,KAAA,EAAO,GAAA,EAAK,CAAC;AAAA,GAC7E;AACA,EAAA,OAAA,CAAQ,WAAA,GAAc,CAAA,SAAA,EAAY,MAAA,CAAO,SAAS,KAAK,WAAW,CAAA,CAAA,CAAA;AAClE,EAAA,OAAO,OAAA;AACT","file":"index.cjs","sourcesContent":["/**\n * React bindings: <AuthProvider> and useAuth()\n */\n\nimport {\n createContext,\n createElement,\n useContext,\n useMemo,\n useSyncExternalStore,\n type ReactElement,\n type ReactNode,\n} from 'react'\nimport { AuthError, type AuthKeeper, type LogoutOptions, type TokenSet } from '../../types'\nimport { createAuthSource, SIGNED_OUT_STATE, type AuthSource, type AuthState } from '../auth-source'\n\nconst AuthContext = createContext<AuthKeeper | null>(null)\n\n/**\n * <AuthProvider> props\n */\nexport interface AuthProviderProps {\n /** Instance returned by `createAuthKeeper()` */\n auth: AuthKeeper\n children?: ReactNode\n}\n\n/**\n * Make an AuthKeeper instance available to `useAuth()` / `useAuthKeeper()`\n */\nexport function AuthProvider({ auth, children }: AuthProviderProps): ReactElement {\n return createElement(AuthContext.Provider, { value: auth }, children)\n}\n\n/**\n * The AuthKeeper instance from the nearest <AuthProvider>\n * @throws {AuthError} CONFIG_ERROR outside an <AuthProvider>\n */\nexport function useAuthKeeper(): AuthKeeper {\n const auth = useContext(AuthContext)\n if (!auth) {\n throw new AuthError('CONFIG_ERROR', 'useAuthKeeper() must be used inside <AuthProvider>')\n }\n return auth\n}\n\n/**\n * useAuth() return value: the auth state plus actions\n */\nexport interface UseAuthReturn extends AuthState {\n /** Store tokens (e.g. after your login request) */\n setTokens: (tokens: TokenSet) => void\n logout: (options?: LogoutOptions) => void\n refresh: () => Promise<TokenSet>\n}\n\nconst getServerState = (): AuthState => SIGNED_OUT_STATE\n\n/**\n * The given instance, else the one from <AuthProvider>\n * @internal\n */\nexport function useAuthInstance(auth: AuthKeeper | undefined, caller: string): AuthKeeper {\n const fromContext = useContext(AuthContext)\n const instance = auth ?? fromContext\n if (!instance) {\n throw new AuthError(\n 'CONFIG_ERROR',\n `${caller} needs an AuthKeeper instance: pass it or render inside <AuthProvider auth={...}>`,\n )\n }\n return instance\n}\n\n/**\n * The snapshot source of an instance, kept for the component's lifetime\n * @internal\n */\nexport function useAuthSource(instance: AuthKeeper): AuthSource {\n return useMemo(() => createAuthSource(instance), [instance])\n}\n\n/**\n * Subscribe a component to the auth state.\n *\n * Re-renders after login, logout, refresh and error events and when the\n * access token expires. On the server and during hydration the state is\n * signed out; the client state follows right after hydration.\n *\n * @param auth - Instance to use (default: the one from <AuthProvider>)\n */\nexport function useAuth(auth?: AuthKeeper): UseAuthReturn {\n const instance = useAuthInstance(auth, 'useAuth()')\n const source = useAuthSource(instance)\n const state = useSyncExternalStore(source.subscribe, source.getState, getServerState)\n\n const actions = useMemo(\n () => ({\n setTokens: (tokens: TokenSet) => instance.setTokens(tokens),\n logout: (options?: LogoutOptions) => instance.logout(options),\n refresh: () => instance.refresh(),\n }),\n [instance],\n )\n\n return useMemo(() => ({ ...state, ...actions }), [state, actions])\n}\n","/**\n * React bindings: useToken() and useUser()\n */\n\nimport { useCallback, useMemo, useSyncExternalStore } from 'react'\nimport type { AuthFetch, AuthKeeper, TokenPayload } from '../../types'\nimport { NO_CLAIMS, NO_TOKEN_STATE, readClaim, type TokenState } from '../auth-source'\nimport { useAuthInstance, useAuthSource } from './use-auth'\n\n/**\n * useToken() return value: the token state plus an authenticated fetch\n */\nexport interface UseTokenReturn extends TokenState {\n /** `fetch` that adds the access token (and refreshes on 401): `auth.createFetch()` */\n authFetch: AuthFetch\n}\n\nconst getServerTokenState = (): TokenState => NO_TOKEN_STATE\nconst getServerUser = (): TokenPayload | null => null\n\n/**\n * Subscribe a component to the tokens.\n *\n * Re-renders only when a token or the expiry changes (login, refresh, logout,\n * expiry). On the server and during hydration there are no tokens.\n *\n * @param auth - Instance to use (default: the one from <AuthProvider>)\n */\nexport function useToken(auth?: AuthKeeper): UseTokenReturn {\n const instance = useAuthInstance(auth, 'useToken()')\n const source = useAuthSource(instance)\n const state = useSyncExternalStore(source.subscribe, source.getTokenState, getServerTokenState)\n const authFetch = useMemo(() => instance.createFetch(), [instance])\n return useMemo(() => ({ ...state, authFetch }), [state, authFetch])\n}\n\n/**\n * useUser() return value\n */\nexport interface UseUserReturn {\n /** Decoded access token payload (null when signed out or for opaque tokens) */\n user: TokenPayload | null\n /** The payload's claims (empty when there is no user) */\n claims: TokenPayload\n /** One claim of the payload */\n getClaim: <K extends keyof TokenPayload>(key: K) => TokenPayload[K] | undefined\n}\n\n/**\n * Subscribe a component to the decoded access token payload.\n *\n * Re-renders only when the access token changes. On the server and during\n * hydration there is no user.\n *\n * @param auth - Instance to use (default: the one from <AuthProvider>)\n */\nexport function useUser(auth?: AuthKeeper): UseUserReturn {\n const instance = useAuthInstance(auth, 'useUser()')\n const source = useAuthSource(instance)\n const user = useSyncExternalStore(source.subscribe, () => source.getState().user, getServerUser)\n const getClaim = useCallback(\n <K extends keyof TokenPayload>(key: K) => readClaim(user, key),\n [user],\n )\n return useMemo(() => ({ user, claims: user ?? NO_CLAIMS, getClaim }), [user, getClaim])\n}\n","/**\n * React bindings: <RequireAuth> and withAuth()\n */\n\nimport {\n createElement,\n forwardRef,\n Fragment,\n useEffect,\n useRef,\n useSyncExternalStore,\n type ComponentPropsWithRef,\n type ComponentType,\n type ElementType,\n type ForwardRefExoticComponent,\n type ReactElement,\n type ReactNode,\n} from 'react'\nimport type { AuthKeeper, TokenPayload } from '../../types'\nimport type { AuthState } from '../auth-source'\nimport { useAuthInstance, useAuthSource } from './use-auth'\n\n/**\n * Why <RequireAuth> did not render its children: signed out, or signed in\n * without the required roles / permissions\n */\nexport type UnauthorizedReason = 'unauthenticated' | 'forbidden'\n\n/** 'pending' on the server and during hydration, before the client state is known */\ntype Access = 'pending' | 'authorized' | UnauthorizedReason\n\n/**\n * <RequireAuth> props\n */\nexport interface RequireAuthProps {\n /** Rendered only while authorized */\n children?: ReactNode\n /** Rendered while signed out or not allowed (default: nothing) */\n fallback?: ReactNode\n /**\n * Rendered on the server and during hydration, before the client auth state\n * is known (default: nothing)\n */\n loadingFallback?: ReactNode\n /** The user needs at least one of these roles (`roles` claim) */\n roles?: readonly string[]\n /** The user needs every one of these permissions (`permissions` claim) */\n permissions?: readonly string[]\n /**\n * Called after rendering the fallback, once each time access is lost (e.g.\n * to redirect to a login page)\n */\n onUnauthorized?: (reason: UnauthorizedReason) => void\n /** Instance to use (default: the one from <AuthProvider>) */\n auth?: AuthKeeper\n}\n\nfunction claimList(user: TokenPayload | null, key: 'roles' | 'permissions'): readonly unknown[] {\n const value = user?.[key]\n return Array.isArray(value) ? value : []\n}\n\nfunction checkAccess(\n state: AuthState,\n roles: readonly string[] | undefined,\n permissions: readonly string[] | undefined,\n): Access {\n if (!state.isAuthenticated) return 'unauthenticated'\n const userRoles = claimList(state.user, 'roles')\n const userPermissions = claimList(state.user, 'permissions')\n if (roles?.length && !roles.some((role) => userRoles.includes(role))) return 'forbidden'\n if (permissions && !permissions.every((p) => userPermissions.includes(p))) return 'forbidden'\n return 'authorized'\n}\n\nconst getServerAccess = (): Access => 'pending'\n\n/**\n * Render `children` only while the user is signed in (and has the required\n * roles / permissions), else `fallback`.\n *\n * Re-renders only when access changes. On the server and during hydration it\n * renders `loadingFallback`, so protected content never appears before the\n * client state is known and the server markup matches the hydration render.\n */\nexport function RequireAuth({\n children,\n fallback = null,\n loadingFallback = null,\n roles,\n permissions,\n onUnauthorized,\n auth,\n}: RequireAuthProps): ReactElement {\n const instance = useAuthInstance(auth, '<RequireAuth>')\n const source = useAuthSource(instance)\n const access = useSyncExternalStore(\n source.subscribe,\n () => checkAccess(source.getState(), roles, permissions),\n getServerAccess,\n )\n\n // The reason last reported, so StrictMode's repeated effects report it once\n const reported = useRef<UnauthorizedReason | null>(null)\n useEffect(() => {\n if (access === 'authorized' || access === 'pending') {\n reported.current = null\n } else if (reported.current !== access) {\n reported.current = access\n onUnauthorized?.(access)\n }\n // A new onUnauthorized (e.g. an inline arrow) is no reason to report again\n }, [access])\n\n const content =\n access === 'authorized' ? children : access === 'pending' ? loadingFallback : fallback\n return createElement(Fragment, null, content)\n}\n\n/**\n * withAuth() options: <RequireAuth> props\n */\nexport type WithAuthOptions = Omit<RequireAuthProps, 'children'>\n\n/** A component's name; forwardRef() / memo() components are named after the inner one */\nfunction nameOf(component: object): string | undefined {\n const { displayName, name, render, type } = component as {\n displayName?: string\n name?: string\n render?: object\n type?: object\n }\n const inner = render ?? type\n return displayName || name || (inner && nameOf(inner))\n}\n\n/**\n * Wrap a component in <RequireAuth>. The wrapper forwards its ref to the\n * component and is named `withAuth(Name)`.\n */\nexport function withAuth<\n // eslint-disable-next-line @typescript-eslint/no-explicit-any -- accepts any component's props\n C extends ComponentType<any>,\n>(\n Component: C,\n options: WithAuthOptions = {},\n): ForwardRefExoticComponent<ComponentPropsWithRef<C>> {\n const Inner: ElementType = Component\n const Wrapped = forwardRef<unknown, object>((props, ref) =>\n createElement(RequireAuth, options, createElement(Inner, { ...props, ref })),\n )\n Wrapped.displayName = `withAuth(${nameOf(Component) || 'Component'})`\n return Wrapped as unknown as ForwardRefExoticComponent<ComponentPropsWithRef<C>>\n}\n"]}
|